scirs2-graph 0.4.2

Graph processing module for SciRS2 (scirs2-graph)
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Graph Attention Network (GAT) layers
//!
//! Implements the multi-head graph attention operator from Veličković et al.
//! (2018), "Graph Attention Networks".
//!
//! Each attention head computes:
//! ```text
//!   α_{ij}^k = softmax_j( LeakyReLU( a_k^T [ W_k h_i ‖ W_k h_j ] ) )
//!   h_i'^k   = σ( Σ_j α_{ij}^k  W_k h_j )
//! ```
//! Multiple heads are concatenated (hidden layers) or averaged (final layer):
//! ```text
//!   h_i' = ‖_{k=1}^{K}  σ( Σ_j α_{ij}^k W_k h_j )
//! ```

use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::random::{Rng, RngExt};

use crate::error::{GraphError, Result};
use crate::gnn::gcn::CsrMatrix;

// ============================================================================
// Helpers
// ============================================================================

/// Numerically-stable softmax over a slice.
fn softmax(xs: &[f64]) -> Vec<f64> {
    if xs.is_empty() {
        return Vec::new();
    }
    let max_val = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
    let exps: Vec<f64> = xs.iter().map(|x| (x - max_val).exp()).collect();
    let sum: f64 = exps.iter().sum::<f64>().max(1e-12);
    exps.iter().map(|e| e / sum).collect()
}

/// LeakyReLU with configurable negative slope.
#[inline]
fn leaky_relu(x: f64, neg_slope: f64) -> f64 {
    if x >= 0.0 {
        x
    } else {
        neg_slope * x
    }
}

// ============================================================================
// Functional API: gat_forward
// ============================================================================

/// Single-head GAT forward pass (functional API).
///
/// Computes attention-weighted node embeddings:
/// ```text
///   α_{ij} = softmax_j( LeakyReLU( a^T [W h_i ‖ W h_j] ) )
///   h_i'   = σ( Σ_j α_{ij} W h_j )
/// ```
///
/// # Arguments
/// * `adj` – Sparse adjacency (row i → neighbors of i; self-loops are added
///   automatically so every node attends to itself).
/// * `features` – Node feature matrix `[n_nodes, in_dim]`.
/// * `w` – Linear weight matrix `[in_dim, out_dim]`.
/// * `a` – Attention parameter vector `[2 * out_dim]`.
/// * `neg_slope` – LeakyReLU negative slope (typically 0.2).
///
/// # Returns
/// Updated node embeddings `[n_nodes, out_dim]` (raw, before global activation).
pub fn gat_forward(
    adj: &CsrMatrix,
    features: &Array2<f64>,
    w: &Array2<f64>,
    a: &Array1<f64>,
    neg_slope: f64,
) -> Result<Array2<f64>> {
    let n = adj.n_rows;
    let (feat_n, in_dim) = features.dim();
    let (w_in, out_dim) = w.dim();

    if feat_n != n {
        return Err(GraphError::InvalidParameter {
            param: "features".to_string(),
            value: format!("{feat_n} rows"),
            expected: format!("{n} rows"),
            context: "gat_forward".to_string(),
        });
    }
    if w_in != in_dim {
        return Err(GraphError::InvalidParameter {
            param: "w".to_string(),
            value: format!("{w_in} rows"),
            expected: format!("{in_dim}"),
            context: "gat_forward".to_string(),
        });
    }
    if a.len() != 2 * out_dim {
        return Err(GraphError::InvalidParameter {
            param: "a".to_string(),
            value: format!("len={}", a.len()),
            expected: format!("2 * out_dim = {}", 2 * out_dim),
            context: "gat_forward".to_string(),
        });
    }

    // Step 1: W h_i for each node  →  wh: [n, out_dim]
    let mut wh = Array2::<f64>::zeros((n, out_dim));
    for i in 0..n {
        for j in 0..out_dim {
            let mut s = 0.0;
            for k in 0..in_dim {
                s += features[[i, k]] * w[[k, j]];
            }
            wh[[i, j]] = s;
        }
    }

    // Step 2: Build neighbor lists including self
    let mut neighbors: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (row, col, _) in adj.iter() {
        neighbors[row].push(col);
    }
    for i in 0..n {
        if !neighbors[i].contains(&i) {
            neighbors[i].push(i);
        }
    }

    // Step 3: Attention-weighted aggregation
    let mut output = Array2::<f64>::zeros((n, out_dim));

    for i in 0..n {
        let nbrs = &neighbors[i];
        if nbrs.is_empty() {
            continue;
        }

        // Compute raw scores  e_{ij} = a^T [Wh_i || Wh_j]
        let scores: Vec<f64> = nbrs
            .iter()
            .map(|&j| {
                let mut dot = 0.0;
                for k in 0..out_dim {
                    dot += a[k] * wh[[i, k]];
                    dot += a[out_dim + k] * wh[[j, k]];
                }
                leaky_relu(dot, neg_slope)
            })
            .collect();

        let alphas = softmax(&scores);

        for (idx, &j) in nbrs.iter().enumerate() {
            let alpha = alphas[idx];
            for k in 0..out_dim {
                output[[i, k]] += alpha * wh[[j, k]];
            }
        }
    }

    Ok(output)
}

// ============================================================================
// GraphAttentionLayer struct (multi-head)
// ============================================================================

/// A single multi-head Graph Attention layer.
///
/// Maintains `n_heads` independent weight matrices and attention vectors.
/// Hidden layers concatenate head outputs; the final layer can average them.
#[derive(Debug, Clone)]
pub struct GraphAttentionLayer {
    /// Per-head weight matrices, each `[in_dim, head_out_dim]`
    pub head_weights: Vec<Array2<f64>>,
    /// Per-head attention vectors, each `[2 * head_out_dim]`
    pub head_attention: Vec<Array1<f64>>,
    /// Optional output bias `[out_dim]` (applied after concat/average)
    pub bias: Option<Array1<f64>>,
    /// Number of attention heads
    pub n_heads: usize,
    /// Output dimension per head
    pub head_out_dim: usize,
    /// Input dimension
    pub in_dim: usize,
    /// LeakyReLU negative slope
    pub neg_slope: f64,
    /// If true, concatenate head outputs; otherwise average them
    pub concat_heads: bool,
    /// Apply ELU activation on the output
    pub use_activation: bool,
}

impl GraphAttentionLayer {
    /// Create a multi-head GAT layer.
    ///
    /// # Arguments
    /// * `in_dim` – Input feature dimension per node.
    /// * `head_out_dim` – Output dimension per attention head.
    /// * `n_heads` – Number of attention heads.
    /// * `concat` – If `true`, concatenate head outputs (total out = n_heads *
    ///   head_out_dim); if `false`, average them (total out = head_out_dim).
    pub fn new(in_dim: usize, head_out_dim: usize, n_heads: usize, concat: bool) -> Self {
        let mut rng = scirs2_core::random::rng();
        let w_scale = (6.0_f64 / (in_dim + head_out_dim) as f64).sqrt();
        let a_scale = (6.0_f64 / (2 * head_out_dim) as f64).sqrt();

        let head_weights: Vec<Array2<f64>> = (0..n_heads)
            .map(|_| {
                Array2::from_shape_fn((in_dim, head_out_dim), |_| {
                    rng.random::<f64>() * 2.0 * w_scale - w_scale
                })
            })
            .collect();

        let head_attention: Vec<Array1<f64>> = (0..n_heads)
            .map(|_| {
                Array1::from_iter(
                    (0..2 * head_out_dim).map(|_| rng.random::<f64>() * 2.0 * a_scale - a_scale),
                )
            })
            .collect();

        GraphAttentionLayer {
            head_weights,
            head_attention,
            bias: None,
            n_heads,
            head_out_dim,
            in_dim,
            neg_slope: 0.2,
            concat_heads: concat,
            use_activation: true,
        }
    }

    /// The effective output dimension: `n_heads * head_out_dim` when
    /// concatenating, or `head_out_dim` when averaging.
    pub fn out_dim(&self) -> usize {
        if self.concat_heads {
            self.n_heads * self.head_out_dim
        } else {
            self.head_out_dim
        }
    }

    /// Set the LeakyReLU negative slope (default 0.2).
    pub fn with_neg_slope(mut self, slope: f64) -> Self {
        self.neg_slope = slope;
        self
    }

    /// Disable ELU activation on the output.
    pub fn without_activation(mut self) -> Self {
        self.use_activation = false;
        self
    }

    /// Forward pass of the multi-head GAT layer.
    ///
    /// # Arguments
    /// * `adj` – Sparse adjacency matrix.
    /// * `features` – Node features `[n_nodes, in_dim]`.
    ///
    /// # Returns
    /// * Concatenated or averaged embeddings `[n_nodes, out_dim]`.
    pub fn forward(&self, adj: &CsrMatrix, features: &Array2<f64>) -> Result<Array2<f64>> {
        let n = adj.n_rows;
        let (feat_n, feat_dim) = features.dim();

        if feat_n != n {
            return Err(GraphError::InvalidParameter {
                param: "features".to_string(),
                value: format!("{feat_n}"),
                expected: format!("{n}"),
                context: "GraphAttentionLayer::forward".to_string(),
            });
        }
        if feat_dim != self.in_dim {
            return Err(GraphError::InvalidParameter {
                param: "features in_dim".to_string(),
                value: format!("{feat_dim}"),
                expected: format!("{}", self.in_dim),
                context: "GraphAttentionLayer::forward".to_string(),
            });
        }

        // Run each head
        let head_outputs: Vec<Array2<f64>> = (0..self.n_heads)
            .map(|h| {
                gat_forward(
                    adj,
                    features,
                    &self.head_weights[h],
                    &self.head_attention[h],
                    self.neg_slope,
                )
            })
            .collect::<Result<Vec<_>>>()?;

        // Combine heads
        let out_dim = self.out_dim();
        let mut output = Array2::<f64>::zeros((n, out_dim));

        if self.concat_heads {
            for (h, head_out) in head_outputs.iter().enumerate() {
                let offset = h * self.head_out_dim;
                for i in 0..n {
                    for k in 0..self.head_out_dim {
                        output[[i, offset + k]] = head_out[[i, k]];
                    }
                }
            }
        } else {
            // Average
            let inv = 1.0 / self.n_heads as f64;
            for head_out in &head_outputs {
                for i in 0..n {
                    for k in 0..self.head_out_dim {
                        output[[i, k]] += inv * head_out[[i, k]];
                    }
                }
            }
        }

        // Optional bias
        if let Some(ref b) = self.bias {
            for i in 0..n {
                for j in 0..out_dim {
                    output[[i, j]] += b[j];
                }
            }
        }

        // ELU activation
        if self.use_activation {
            output.mapv_inplace(|x| if x >= 0.0 { x } else { x.exp() - 1.0 });
        }

        Ok(output)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    fn triangle_csr() -> CsrMatrix {
        let coo = vec![
            (0, 1, 1.0),
            (1, 0, 1.0),
            (1, 2, 1.0),
            (2, 1, 1.0),
            (0, 2, 1.0),
            (2, 0, 1.0),
        ];
        CsrMatrix::from_coo(3, 3, &coo).expect("triangle CSR")
    }

    fn feats(n: usize, d: usize) -> Array2<f64> {
        Array2::from_shape_fn((n, d), |(i, j)| (i * d + j) as f64 * 0.1)
    }

    #[test]
    fn test_softmax_sums_to_one() {
        let xs = vec![1.0, 2.0, 3.0, 4.0];
        let probs = softmax(&xs);
        let s: f64 = probs.iter().sum();
        assert!((s - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_gat_forward_shape() {
        let adj = triangle_csr();
        let f = feats(3, 4);
        let w = Array2::from_shape_fn((4, 8), |(i, j)| (i + j) as f64 * 0.01);
        let a = Array1::from_vec(vec![0.1; 16]);
        let out = gat_forward(&adj, &f, &w, &a, 0.2).expect("gat_forward");
        assert_eq!(out.dim(), (3, 8));
    }

    #[test]
    fn test_gat_forward_finite_values() {
        let adj = triangle_csr();
        let f = feats(3, 4);
        let w = Array2::from_shape_fn((4, 6), |(i, j)| (i as f64 - j as f64) * 0.05);
        let a = Array1::from_vec(
            (0..12)
                .map(|i| if i % 2 == 0 { 0.3 } else { -0.3 })
                .collect(),
        );
        let out = gat_forward(&adj, &f, &w, &a, 0.2).expect("gat_forward");
        for &v in out.iter() {
            assert!(v.is_finite(), "non-finite: {v}");
        }
    }

    #[test]
    fn test_gat_layer_concat_output_dim() {
        let adj = triangle_csr();
        let f = feats(3, 4);
        // 3 heads × 6 out_dim_per_head = 18 total
        let layer = GraphAttentionLayer::new(4, 6, 3, true);
        assert_eq!(layer.out_dim(), 18);
        let out = layer.forward(&adj, &f).expect("layer forward");
        assert_eq!(out.dim(), (3, 18));
    }

    #[test]
    fn test_gat_layer_mean_output_dim() {
        let adj = triangle_csr();
        let f = feats(3, 4);
        // Average across 4 heads → out_dim = head_out_dim = 8
        let layer = GraphAttentionLayer::new(4, 8, 4, false);
        assert_eq!(layer.out_dim(), 8);
        let out = layer.forward(&adj, &f).expect("layer forward");
        assert_eq!(out.dim(), (3, 8));
    }

    #[test]
    fn test_gat_layer_single_head() {
        let adj = triangle_csr();
        let f = feats(3, 4);
        let layer = GraphAttentionLayer::new(4, 8, 1, true);
        let out = layer.forward(&adj, &f).expect("single head");
        assert_eq!(out.dim(), (3, 8));
    }

    #[test]
    fn test_gat_layer_no_activation() {
        let adj = triangle_csr();
        let f = feats(3, 4);
        let layer = GraphAttentionLayer::new(4, 6, 2, false).without_activation();
        let out = layer.forward(&adj, &f).expect("no act");
        assert_eq!(out.dim(), (3, 6));
    }

    #[test]
    fn test_gat_forward_dimension_mismatch() {
        let adj = triangle_csr();
        let f = feats(3, 4);
        let w = Array2::from_shape_fn((5, 8), |(i, j)| (i + j) as f64 * 0.01); // wrong in_dim
        let a = Array1::from_vec(vec![0.1; 16]);
        let result = gat_forward(&adj, &f, &w, &a, 0.2);
        assert!(result.is_err());
    }

    #[test]
    fn test_attention_coefficients_sum_to_one() {
        // Build a star graph: node 0 connected to 1, 2, 3
        let coo = vec![
            (0, 1, 1.0),
            (1, 0, 1.0),
            (0, 2, 1.0),
            (2, 0, 1.0),
            (0, 3, 1.0),
            (3, 0, 1.0),
        ];
        let adj = CsrMatrix::from_coo(4, 4, &coo).expect("star CSR");
        let f = feats(4, 3);
        let w = Array2::eye(3);
        let a = Array1::from_vec(vec![1.0; 6]);
        // Just verify output is finite and shaped correctly
        let out = gat_forward(&adj, &f, &w, &a, 0.2).expect("star gat");
        assert_eq!(out.dim(), (4, 3));
        for &v in out.iter() {
            assert!(v.is_finite());
        }
    }
}