ruvector-attention 2.1.0

Attention mechanisms for ruvector - geometric, graph, and sparse attention
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Topology Gated Attention
//!
//! Main attention mechanism that uses topological coherence as a permission signal.

use super::coherence::{CoherenceMetric, WindowCoherence};
use super::policy::{AttentionMode, AttentionPolicy, PolicyConfig};
use crate::error::{AttentionError, AttentionResult};
use crate::traits::Attention;
use serde::{Deserialize, Serialize};

/// Configuration for topology-gated attention
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopologyGatedConfig {
    /// Model dimension
    pub dim: usize,
    /// Number of neighbors for coherence graph
    pub k_neighbors: usize,
    /// Coherence metrics to use
    pub metrics: Vec<CoherenceMetric>,
    /// Policy configuration
    pub policy: PolicyConfig,
    /// Temperature for softmax
    pub temperature: f32,
    /// Base attention width
    pub base_width: usize,
}

impl Default for TopologyGatedConfig {
    fn default() -> Self {
        Self {
            dim: 512,
            k_neighbors: 8,
            metrics: vec![
                CoherenceMetric::BoundaryMass,
                CoherenceMetric::SimilarityVariance,
            ],
            policy: PolicyConfig::default(),
            temperature: 1.0,
            base_width: 64,
        }
    }
}

/// Topology Gated Attention
///
/// Uses structural coherence to control attention behavior:
/// - Stable mode: full attention, normal updates
/// - Cautious mode: reduced width, increased sparsity
/// - Freeze mode: retrieval only, no updates
#[derive(Debug, Clone)]
pub struct TopologyGatedAttention {
    config: TopologyGatedConfig,
    policy: AttentionPolicy,
    cached_coherence: Option<WindowCoherence>,
}

impl TopologyGatedAttention {
    /// Create new topology-gated attention
    pub fn new(config: TopologyGatedConfig) -> Self {
        let policy = AttentionPolicy::new(config.policy.clone());

        Self {
            config,
            policy,
            cached_coherence: None,
        }
    }

    /// Create with dimension
    pub fn with_dim(dim: usize) -> Self {
        Self::new(TopologyGatedConfig {
            dim,
            ..Default::default()
        })
    }

    /// Update coherence from keys (call periodically, not every token)
    pub fn update_coherence(&mut self, keys: &[&[f32]]) {
        let coherence =
            WindowCoherence::compute(keys, self.config.k_neighbors, &self.config.metrics);
        self.policy.determine_mode(coherence.score);
        self.cached_coherence = Some(coherence);
    }

    /// Get current mode
    pub fn current_mode(&self) -> AttentionMode {
        self.policy.current_mode()
    }

    /// Check if coherence update is needed
    pub fn needs_coherence_update(&self) -> bool {
        match &self.cached_coherence {
            Some(c) => c.needs_update(self.config.policy.update_period),
            None => true,
        }
    }

    /// Tick coherence counter
    pub fn tick_coherence(&mut self) {
        if let Some(ref mut c) = self.cached_coherence {
            c.tick();
        }
    }

    /// Get effective attention width
    pub fn get_attention_width(&self) -> usize {
        self.policy.get_attention_width(self.config.base_width)
    }

    /// Check if updates are allowed
    pub fn allows_updates(&self) -> bool {
        self.policy.allows_updates()
    }

    /// Compute gated attention
    pub fn compute_gated(
        &mut self,
        query: &[f32],
        keys: &[&[f32]],
        values: &[&[f32]],
    ) -> AttentionResult<Vec<f32>> {
        // Update coherence if needed
        if self.needs_coherence_update() {
            self.update_coherence(keys);
        } else {
            self.tick_coherence();
        }

        match self.current_mode() {
            AttentionMode::Stable => {
                // Full attention
                self.full_attention(query, keys, values)
            }
            AttentionMode::Cautious => {
                // Sparse attention with reduced width
                let width = self.get_attention_width();
                self.sparse_attention(query, keys, values, width)
            }
            AttentionMode::Freeze => {
                // Retrieval only: just return query projection
                // (no attention, just pass-through with light weighting)
                self.retrieval_only(query, keys, values)
            }
        }
    }

    /// Full attention (stable mode)
    fn full_attention(
        &self,
        query: &[f32],
        keys: &[&[f32]],
        values: &[&[f32]],
    ) -> AttentionResult<Vec<f32>> {
        if keys.is_empty() {
            return Err(AttentionError::InvalidConfig("No keys".into()));
        }

        // Standard scaled dot-product attention
        let scale = 1.0 / (self.config.dim as f32).sqrt();

        let logits: Vec<f32> = keys
            .iter()
            .map(|k| Self::dot_product_simd(query, k) * scale / self.config.temperature)
            .collect();

        let weights = Self::stable_softmax(&logits);

        self.weighted_sum(&weights, values)
    }

    /// Sparse attention with limited width (cautious mode)
    fn sparse_attention(
        &self,
        query: &[f32],
        keys: &[&[f32]],
        values: &[&[f32]],
        width: usize,
    ) -> AttentionResult<Vec<f32>> {
        if keys.is_empty() {
            return Err(AttentionError::InvalidConfig("No keys".into()));
        }

        let width = width.min(keys.len());

        // Get top-k keys by dot product
        let scale = 1.0 / (self.config.dim as f32).sqrt();
        let mut scores: Vec<(usize, f32)> = keys
            .iter()
            .enumerate()
            .map(|(i, k)| (i, Self::dot_product_simd(query, k) * scale))
            .collect();

        scores.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        // Take top-k
        let top_k: Vec<(usize, f32)> = scores.into_iter().take(width).collect();

        // Compute attention over selected keys
        let logits: Vec<f32> = top_k
            .iter()
            .map(|(_, s)| s / self.config.temperature)
            .collect();

        let weights = Self::stable_softmax(&logits);

        // Weighted sum of selected values
        let selected_values: Vec<&[f32]> = top_k.iter().map(|(i, _)| values[*i]).collect();

        self.weighted_sum(&weights, &selected_values)
    }

    /// Retrieval-only mode (freeze mode)
    fn retrieval_only(
        &self,
        query: &[f32],
        keys: &[&[f32]],
        values: &[&[f32]],
    ) -> AttentionResult<Vec<f32>> {
        if keys.is_empty() {
            return Err(AttentionError::InvalidConfig("No keys".into()));
        }

        // Find single best match and return its value
        // This is ultra-sparse: only 1 key contributes
        let scale = 1.0 / (self.config.dim as f32).sqrt();

        let best_idx = keys
            .iter()
            .enumerate()
            .map(|(i, k)| (i, Self::dot_product_simd(query, k) * scale))
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(i, _)| i)
            .unwrap_or(0);

        Ok(values[best_idx].to_vec())
    }

    /// SIMD-friendly dot product
    #[inline(always)]
    fn dot_product_simd(a: &[f32], b: &[f32]) -> f32 {
        let len = a.len().min(b.len());
        let chunks = len / 4;
        let remainder = len % 4;

        let mut sum0 = 0.0f32;
        let mut sum1 = 0.0f32;
        let mut sum2 = 0.0f32;
        let mut sum3 = 0.0f32;

        for i in 0..chunks {
            let base = i * 4;
            sum0 += a[base] * b[base];
            sum1 += a[base + 1] * b[base + 1];
            sum2 += a[base + 2] * b[base + 2];
            sum3 += a[base + 3] * b[base + 3];
        }

        let base = chunks * 4;
        for i in 0..remainder {
            sum0 += a[base + i] * b[base + i];
        }

        sum0 + sum1 + sum2 + sum3
    }

    /// Stable softmax
    fn stable_softmax(logits: &[f32]) -> Vec<f32> {
        if logits.is_empty() {
            return vec![];
        }

        let max_logit = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
        let exp_logits: Vec<f32> = logits.iter().map(|&l| (l - max_logit).exp()).collect();
        let sum: f32 = exp_logits.iter().sum();

        exp_logits.iter().map(|&e| e / sum).collect()
    }

    /// Weighted sum
    fn weighted_sum(&self, weights: &[f32], values: &[&[f32]]) -> AttentionResult<Vec<f32>> {
        if weights.is_empty() || values.is_empty() {
            return Err(AttentionError::InvalidConfig("Empty inputs".into()));
        }

        let dim = values[0].len();
        let mut output = vec![0.0f32; dim];

        for (weight, value) in weights.iter().zip(values.iter()) {
            for (o, &v) in output.iter_mut().zip(value.iter()) {
                *o += weight * v;
            }
        }

        Ok(output)
    }
}

impl Attention for TopologyGatedAttention {
    fn compute(
        &self,
        query: &[f32],
        keys: &[&[f32]],
        values: &[&[f32]],
    ) -> AttentionResult<Vec<f32>> {
        // For trait, use clone to allow mutation
        let mut att = self.clone();
        att.compute_gated(query, keys, values)
    }

    fn compute_with_mask(
        &self,
        query: &[f32],
        keys: &[&[f32]],
        values: &[&[f32]],
        mask: Option<&[bool]>,
    ) -> AttentionResult<Vec<f32>> {
        if let Some(m) = mask {
            let filtered: Vec<(&[f32], &[f32])> = keys
                .iter()
                .zip(values.iter())
                .enumerate()
                .filter(|(i, _)| m.get(*i).copied().unwrap_or(true))
                .map(|(_, (k, v))| (*k, *v))
                .collect();

            let filtered_keys: Vec<&[f32]> = filtered.iter().map(|(k, _)| *k).collect();
            let filtered_values: Vec<&[f32]> = filtered.iter().map(|(_, v)| *v).collect();

            self.compute(query, &filtered_keys, &filtered_values)
        } else {
            self.compute(query, keys, values)
        }
    }

    fn dim(&self) -> usize {
        self.config.dim
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_topology_gated_attention() {
        let mut attention = TopologyGatedAttention::with_dim(32);

        let query = vec![0.5f32; 32];
        let keys: Vec<Vec<f32>> = (0..20).map(|i| vec![0.1 + i as f32 * 0.02; 32]).collect();
        let values: Vec<Vec<f32>> = (0..20).map(|i| vec![i as f32; 32]).collect();

        let keys_refs: Vec<&[f32]> = keys.iter().map(|k| k.as_slice()).collect();
        let values_refs: Vec<&[f32]> = values.iter().map(|v| v.as_slice()).collect();

        let output = attention
            .compute_gated(&query, &keys_refs, &values_refs)
            .unwrap();
        assert_eq!(output.len(), 32);
    }

    #[test]
    fn test_mode_affects_output() {
        let config = TopologyGatedConfig {
            dim: 16,
            base_width: 32,
            policy: PolicyConfig {
                stable_threshold: 0.9, // Very high threshold
                freeze_threshold: 0.8,
                ..Default::default()
            },
            ..Default::default()
        };
        let mut attention = TopologyGatedAttention::new(config);

        // Create diverse keys (low coherence)
        let keys: Vec<Vec<f32>> = (0..10)
            .map(|i| {
                let mut v = vec![0.0f32; 16];
                v[i % 16] = 1.0;
                v
            })
            .collect();
        let values: Vec<Vec<f32>> = (0..10).map(|i| vec![i as f32; 16]).collect();

        let keys_refs: Vec<&[f32]> = keys.iter().map(|k| k.as_slice()).collect();
        let values_refs: Vec<&[f32]> = values.iter().map(|v| v.as_slice()).collect();

        attention.update_coherence(&keys_refs);

        // With diverse keys, should trigger freeze mode
        let query = vec![0.5f32; 16];
        let _output = attention
            .compute_gated(&query, &keys_refs, &values_refs)
            .unwrap();

        // Mode should be freeze or cautious due to low coherence
        let mode = attention.current_mode();
        assert!(mode == AttentionMode::Freeze || mode == AttentionMode::Cautious);
    }

    #[test]
    fn test_coherence_update_period() {
        let config = TopologyGatedConfig {
            dim: 16,
            policy: PolicyConfig {
                update_period: 4,
                ..Default::default()
            },
            ..Default::default()
        };
        let mut attention = TopologyGatedAttention::new(config);

        // No coherence yet
        assert!(attention.needs_coherence_update());

        let keys: Vec<Vec<f32>> = vec![vec![1.0; 16]; 5];
        let keys_refs: Vec<&[f32]> = keys.iter().map(|k| k.as_slice()).collect();

        attention.update_coherence(&keys_refs);
        assert!(!attention.needs_coherence_update());

        // Tick 4 times
        for _ in 0..4 {
            attention.tick_coherence();
        }

        assert!(attention.needs_coherence_update());
    }
}