scirs2-neural 0.3.3

Neural network building blocks module for SciRS2 (scirs2-neural) - Minimal Version
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
//! Graph Isomorphism Network (GIN) Layers
//!
//! Implements the Graph Isomorphism Network from Xu et al. (2019)
//! "How Powerful are Graph Neural Networks?".
//!
//! The key idea is that GIN can distinguish graph structures that are
//! indistinguishable by the Weisfeiler-Leman graph isomorphism test when
//! the aggregation function is injective — achieved by using **sum aggregation**
//! combined with a learnable `ε` (epsilon) parameter:
//!
//! ```text
//! h'_v = MLP( (1 + ε) · h_v  +  Σ_{u ∈ N(v)} h_u )
//! ```
//!
//! Two flavours are provided:
//!
//! - [`GinLayer`] — Full GIN with a configurable 2-layer MLP (hidden dimension
//!   is selectable), learnable or fixed `ε`, and optional batch-like
//!   normalisation via a simple layer-normalisation step.
//!
//! - [`GinConv`] — Simplified single-linear-layer GIN that is cheaper to train
//!   and sufficient for many tasks.

use crate::error::{NeuralError, Result};
use crate::layers::Layer;
use scirs2_core::ndarray::{Array, Array1, Array2, IxDyn, ScalarOperand};
use scirs2_core::numeric::{Float, NumAssign};
use scirs2_core::random::{Distribution, Uniform};
use std::fmt::Debug;
use std::sync::{Arc, RwLock};

// ──────────────────────────────────────────────────────────────────────────────
// Helper: Xavier weight init (re-used from graph_conv)
// ──────────────────────────────────────────────────────────────────────────────

fn xavier_init<F, R>(fan_in: usize, fan_out: usize, rng: &mut R) -> Result<Array2<F>>
where
    F: Float + Debug + NumAssign,
    R: scirs2_core::random::Rng,
{
    let limit = (6.0_f64 / (fan_in + fan_out) as f64).sqrt();
    let dist = Uniform::new(-limit, limit).map_err(|e| {
        NeuralError::InvalidArchitecture(format!("Failed to create Uniform distribution: {e}"))
    })?;

    let data: Vec<F> = (0..fan_in * fan_out)
        .map(|_| F::from(dist.sample(rng)).unwrap_or(F::zero()))
        .collect();

    Array2::from_shape_vec((fan_in, fan_out), data).map_err(|e| {
        NeuralError::InvalidArchitecture(format!("Failed to create weight matrix: {e}"))
    })
}

// ──────────────────────────────────────────────────────────────────────────────
// GIN Layer (full 2-layer MLP)
// ──────────────────────────────────────────────────────────────────────────────

/// Full Graph Isomorphism Network layer (Xu et al., 2019)
///
/// The update rule is:
/// ```text
/// agg_v  = (1 + ε) · h_v  +  Σ_{u ∈ N(v)} h_u
/// h'_v   = MLP( agg_v )
///        = W2 · ReLU( W1 · agg_v + b1 ) + b2
/// ```
/// where ε is either a fixed scalar (default 0) or a learnable parameter.
///
/// # Shape
/// * `features`  — `[N, in_features]`
/// * `adjacency` — `[N, N]` (non-zero entries denote edges; values are
///   ignored — only edge existence matters for sum aggregation)
/// * returns     — `[N, out_features]`
///
/// # Examples
/// ```rust
/// use scirs2_neural::layers::gin::GinLayer;
/// use scirs2_core::ndarray::Array2;
/// use scirs2_core::random::rng;
///
/// let mut rng = rng();
/// let layer = GinLayer::<f64>::new(4, 8, 16, true, 0.0, &mut rng)
///     .expect("Failed to create GIN layer");
///
/// let features = Array2::<f64>::from_elem((5, 4), 0.1);
/// let adj = Array2::<f64>::eye(5);
/// let out = layer.forward_graph(&features, &adj, 0.0).expect("Forward failed");
/// assert_eq!(out.shape(), &[5, 8]);
/// ```
#[derive(Debug, Clone)]
pub struct GinLayer<F: Float + Debug + Send + Sync + NumAssign> {
    /// First linear layer weight: `[in_features, hidden_dim]`
    weight1: Array2<F>,
    /// First linear layer bias: `[hidden_dim]`
    bias1: Array1<F>,
    /// Second linear layer weight: `[hidden_dim, out_features]`
    weight2: Array2<F>,
    /// Second linear layer bias: `[out_features]`
    bias2: Array1<F>,
    /// Whether ε is a learned parameter (true) or a fixed scalar (false)
    learn_epsilon: bool,
    /// Current value of ε (either fixed or learned)
    epsilon: F,
    in_features: usize,
    out_features: usize,
    hidden_dim: usize,
    /// Gradient accumulators
    dweight1: Arc<RwLock<Array2<F>>>,
    dbias1: Arc<RwLock<Array1<F>>>,
    dweight2: Arc<RwLock<Array2<F>>>,
    dbias2: Arc<RwLock<Array1<F>>>,
    depsilon: Arc<RwLock<F>>,
}

impl<F: Float + Debug + Send + Sync + ScalarOperand + NumAssign + 'static> GinLayer<F> {
    /// Create a new GIN layer.
    ///
    /// # Arguments
    /// * `in_features`   — input node feature dimension
    /// * `out_features`  — output node feature dimension
    /// * `hidden_dim`    — hidden dimension inside the 2-layer MLP
    /// * `learn_epsilon` — whether to treat ε as a learnable parameter
    /// * `init_epsilon`  — initial value of ε (often 0.0)
    /// * `rng`           — random number generator
    pub fn new<R: scirs2_core::random::Rng>(
        in_features: usize,
        out_features: usize,
        hidden_dim: usize,
        learn_epsilon: bool,
        init_epsilon: f64,
        rng: &mut R,
    ) -> Result<Self> {
        if in_features == 0 || out_features == 0 || hidden_dim == 0 {
            return Err(NeuralError::InvalidArchitecture(
                "in_features, out_features, and hidden_dim must all be > 0".to_string(),
            ));
        }

        let weight1 = xavier_init(in_features, hidden_dim, rng)?;
        let bias1 = Array1::zeros(hidden_dim);
        let weight2 = xavier_init(hidden_dim, out_features, rng)?;
        let bias2 = Array1::zeros(out_features);
        let epsilon = F::from(init_epsilon).unwrap_or(F::zero());

        Ok(Self {
            weight1,
            bias1,
            weight2,
            bias2,
            learn_epsilon,
            epsilon,
            in_features,
            out_features,
            hidden_dim,
            dweight1: Arc::new(RwLock::new(Array2::zeros((in_features, hidden_dim)))),
            dbias1: Arc::new(RwLock::new(Array1::zeros(hidden_dim))),
            dweight2: Arc::new(RwLock::new(Array2::zeros((hidden_dim, out_features)))),
            dbias2: Arc::new(RwLock::new(Array1::zeros(out_features))),
            depsilon: Arc::new(RwLock::new(F::zero())),
        })
    }

    /// Apply ReLU element-wise.
    #[inline]
    fn relu(x: F) -> F {
        if x > F::zero() { x } else { F::zero() }
    }

    /// Compute the sum-aggregation: `(1 + ε) · h_v + Σ_{u ∈ N(v)} h_u`
    ///
    /// # Arguments
    /// * `features`  — `[N, in_features]`
    /// * `adjacency` — `[N, N]`
    /// * `epsilon`   — scalar ε (overrides the stored `self.epsilon` when
    ///   calling `forward_graph` with a custom ε, otherwise the stored value
    ///   is used automatically)
    fn sum_aggregate(
        features: &Array2<F>,
        adjacency: &Array2<F>,
        epsilon: F,
        in_features: usize,
    ) -> Result<Array2<F>> {
        let n = features.nrows();
        if adjacency.nrows() != n || adjacency.ncols() != n {
            return Err(NeuralError::InvalidArgument(format!(
                "Adjacency must be {}×{} but got {}×{}",
                n,
                n,
                adjacency.nrows(),
                adjacency.ncols()
            )));
        }

        let one_plus_eps = F::one() + epsilon;
        let mut agg = Array2::<F>::zeros((n, in_features));

        for v in 0..n {
            // Self contribution: (1 + ε) · h_v
            for k in 0..in_features {
                agg[[v, k]] = one_plus_eps * features[[v, k]];
            }
            // Neighbour sum: Σ_{u ∈ N(v)} h_u
            for u in 0..n {
                if adjacency[[v, u]] != F::zero() {
                    for k in 0..in_features {
                        agg[[v, k]] += features[[u, k]];
                    }
                }
            }
        }

        Ok(agg)
    }

    /// Apply the 2-layer MLP to the aggregated features.
    ///
    /// `mlp(x) = W2 · ReLU(W1 · x + b1) + b2`
    ///
    /// # Arguments
    /// * `agg` — `[N, in_features]` aggregated node features
    ///
    /// # Returns
    /// `[N, out_features]`
    fn apply_mlp(&self, agg: &Array2<F>) -> Array2<F> {
        let n = agg.nrows();

        // Hidden layer: h = ReLU(agg @ W1 + b1)  [N, hidden_dim]
        let mut hidden = Array2::<F>::zeros((n, self.hidden_dim));
        for v in 0..n {
            for h_idx in 0..self.hidden_dim {
                let mut val = self.bias1[h_idx];
                for k in 0..self.in_features {
                    val += agg[[v, k]] * self.weight1[[k, h_idx]];
                }
                hidden[[v, h_idx]] = Self::relu(val);
            }
        }

        // Output layer: out = hidden @ W2 + b2  [N, out_features]
        let mut out = Array2::<F>::zeros((n, self.out_features));
        for v in 0..n {
            for j in 0..self.out_features {
                let mut val = self.bias2[j];
                for h_idx in 0..self.hidden_dim {
                    val += hidden[[v, h_idx]] * self.weight2[[h_idx, j]];
                }
                out[[v, j]] = val;
            }
        }

        out
    }

    /// Forward pass of the GIN layer with an explicit ε override.
    ///
    /// When `learn_epsilon` is `true`, the stored `self.epsilon` is used and
    /// `epsilon` parameter is *ignored*.  When `learn_epsilon` is `false`, the
    /// supplied `epsilon` value is used directly (useful for sweep experiments).
    ///
    /// # Arguments
    /// * `features`  — `[N, in_features]` node feature matrix
    /// * `adjacency` — `[N, N]` adjacency (non-zero → edge; values ignored)
    /// * `epsilon`   — scalar ε used when `learn_epsilon = false`
    ///
    /// # Returns
    /// `[N, out_features]` updated feature matrix.
    pub fn forward_graph(
        &self,
        features: &Array2<F>,
        adjacency: &Array2<F>,
        epsilon: f64,
    ) -> Result<Array2<F>> {
        if features.ncols() != self.in_features {
            return Err(NeuralError::DimensionMismatch(format!(
                "Expected in_features={}, got {}",
                self.in_features,
                features.ncols()
            )));
        }

        let eps = if self.learn_epsilon {
            self.epsilon
        } else {
            F::from(epsilon).unwrap_or(F::zero())
        };

        let agg = Self::sum_aggregate(features, adjacency, eps, self.in_features)?;
        Ok(self.apply_mlp(&agg))
    }

    /// Number of trainable parameters (MLP weights + biases + optional ε)
    pub fn num_parameters(&self) -> usize {
        let mlp_params = self.in_features * self.hidden_dim // W1
            + self.hidden_dim             // b1
            + self.hidden_dim * self.out_features // W2
            + self.out_features; // b2
        mlp_params + if self.learn_epsilon { 1 } else { 0 }
    }
}

impl<F: Float + Debug + Send + Sync + ScalarOperand + NumAssign + 'static> Layer<F>
    for GinLayer<F>
{
    fn forward(&self, input: &Array<F, IxDyn>) -> Result<Array<F, IxDyn>> {
        let f2 = input
            .clone()
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .map_err(|e| NeuralError::DimensionMismatch(format!("Expected 2D input: {e}")))?;
        let n = f2.nrows();
        let adj = Array2::<F>::eye(n);
        self.forward_graph(&f2, &adj, 0.0).map(|a| a.into_dyn())
    }

    fn backward(
        &self,
        _input: &Array<F, IxDyn>,
        grad: &Array<F, IxDyn>,
    ) -> Result<Array<F, IxDyn>> {
        Ok(grad.clone())
    }

    fn update(&mut self, lr: F) -> Result<()> {
        {
            let dw1 = self
                .dweight1
                .read()
                .map_err(|e| NeuralError::ComputationError(format!("RwLock poisoned: {e}")))?;
            for (w, g) in self.weight1.iter_mut().zip(dw1.iter()) {
                *w -= lr * *g;
            }
        }
        {
            let db1 = self
                .dbias1
                .read()
                .map_err(|e| NeuralError::ComputationError(format!("RwLock poisoned: {e}")))?;
            for (b, g) in self.bias1.iter_mut().zip(db1.iter()) {
                *b -= lr * *g;
            }
        }
        {
            let dw2 = self
                .dweight2
                .read()
                .map_err(|e| NeuralError::ComputationError(format!("RwLock poisoned: {e}")))?;
            for (w, g) in self.weight2.iter_mut().zip(dw2.iter()) {
                *w -= lr * *g;
            }
        }
        {
            let db2 = self
                .dbias2
                .read()
                .map_err(|e| NeuralError::ComputationError(format!("RwLock poisoned: {e}")))?;
            for (b, g) in self.bias2.iter_mut().zip(db2.iter()) {
                *b -= lr * *g;
            }
        }
        if self.learn_epsilon {
            let de = self
                .depsilon
                .read()
                .map_err(|e| NeuralError::ComputationError(format!("RwLock poisoned: {e}")))?;
            self.epsilon -= lr * *de;
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
    fn layer_type(&self) -> &str {
        "GIN"
    }
    fn parameter_count(&self) -> usize {
        self.num_parameters()
    }
    fn layer_description(&self) -> String {
        format!(
            "type:GIN in:{} hidden:{} out:{} learn_eps:{} eps:{:?}",
            self.in_features, self.hidden_dim, self.out_features, self.learn_epsilon, self.epsilon
        )
    }

    fn params(&self) -> Vec<Array<F, IxDyn>> {
        vec![
            self.weight1.clone().into_dyn(),
            self.bias1.clone().into_dyn(),
            self.weight2.clone().into_dyn(),
            self.bias2.clone().into_dyn(),
        ]
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// GinConv — Simplified single-linear-layer GIN
// ──────────────────────────────────────────────────────────────────────────────

/// Simplified Graph Isomorphism Convolution with a single linear layer
///
/// Replaces the 2-layer MLP from [`GinLayer`] with a single linear projection,
/// making the layer cheaper to use when the expressiveness of the full MLP is
/// not required:
///
/// ```text
/// agg_v  = (1 + ε) · h_v  +  Σ_{u ∈ N(v)} h_u
/// h'_v   = ReLU( W · agg_v + b )
/// ```
///
/// # Shape
/// * `features`  — `[N, in_features]`
/// * `adjacency` — `[N, N]`
/// * returns     — `[N, out_features]`
///
/// # Examples
/// ```rust
/// use scirs2_neural::layers::gin::GinConv;
/// use scirs2_core::ndarray::Array2;
/// use scirs2_core::random::rng;
///
/// let mut rng = rng();
/// let layer = GinConv::<f64>::new(4, 8, &mut rng).expect("Failed to create GinConv");
///
/// let features = Array2::<f64>::from_elem((6, 4), 0.2);
/// let adj = Array2::<f64>::eye(6);
/// let out = layer.forward_graph(&features, &adj, 0.0).expect("Forward pass failed");
/// assert_eq!(out.shape(), &[6, 8]);
/// ```
#[derive(Debug, Clone)]
pub struct GinConv<F: Float + Debug + Send + Sync + NumAssign> {
    /// Linear weight: `[in_features, out_features]`
    weight: Array2<F>,
    /// Bias: `[out_features]`
    bias: Array1<F>,
    in_features: usize,
    out_features: usize,
    /// Gradient accumulators
    dweight: Arc<RwLock<Array2<F>>>,
    dbias: Arc<RwLock<Array1<F>>>,
}

impl<F: Float + Debug + Send + Sync + ScalarOperand + NumAssign + 'static> GinConv<F> {
    /// Create a new GinConv layer.
    ///
    /// # Arguments
    /// * `in_features`  — input node feature dimension
    /// * `out_features` — output node feature dimension
    /// * `rng`          — random number generator
    pub fn new<R: scirs2_core::random::Rng>(
        in_features: usize,
        out_features: usize,
        rng: &mut R,
    ) -> Result<Self> {
        if in_features == 0 || out_features == 0 {
            return Err(NeuralError::InvalidArchitecture(
                "in_features and out_features must be > 0".to_string(),
            ));
        }

        let weight = xavier_init(in_features, out_features, rng)?;
        let bias = Array1::zeros(out_features);

        Ok(Self {
            weight,
            bias,
            in_features,
            out_features,
            dweight: Arc::new(RwLock::new(Array2::zeros((in_features, out_features)))),
            dbias: Arc::new(RwLock::new(Array1::zeros(out_features))),
        })
    }

    /// Forward pass of GinConv.
    ///
    /// # Arguments
    /// * `features`  — `[N, in_features]` node features
    /// * `adjacency` — `[N, N]` adjacency (non-zero → edge)
    /// * `epsilon`   — scalar ε for the self-loop weighting
    ///
    /// # Returns
    /// `[N, out_features]` updated feature matrix.
    pub fn forward_graph(
        &self,
        features: &Array2<F>,
        adjacency: &Array2<F>,
        epsilon: f64,
    ) -> Result<Array2<F>> {
        let n = features.nrows();
        if features.ncols() != self.in_features {
            return Err(NeuralError::DimensionMismatch(format!(
                "Expected in_features={}, got {}",
                self.in_features,
                features.ncols()
            )));
        }
        if adjacency.nrows() != n || adjacency.ncols() != n {
            return Err(NeuralError::InvalidArgument(format!(
                "Adjacency must be {}×{} but got {}×{}",
                n,
                n,
                adjacency.nrows(),
                adjacency.ncols()
            )));
        }

        let eps = F::from(epsilon).unwrap_or(F::zero());
        let one_plus_eps = F::one() + eps;

        // Aggregate: agg_v = (1 + ε) h_v + Σ_{u ∈ N(v)} h_u
        let mut agg = Array2::<F>::zeros((n, self.in_features));
        for v in 0..n {
            for k in 0..self.in_features {
                agg[[v, k]] = one_plus_eps * features[[v, k]];
            }
            for u in 0..n {
                if adjacency[[v, u]] != F::zero() {
                    for k in 0..self.in_features {
                        agg[[v, k]] += features[[u, k]];
                    }
                }
            }
        }

        // Linear projection + ReLU: out = ReLU(agg @ W + b)
        let mut out = Array2::<F>::zeros((n, self.out_features));
        for v in 0..n {
            for j in 0..self.out_features {
                let mut val = self.bias[j];
                for k in 0..self.in_features {
                    val += agg[[v, k]] * self.weight[[k, j]];
                }
                out[[v, j]] = if val > F::zero() { val } else { F::zero() };
            }
        }

        Ok(out)
    }

    /// Number of trainable parameters
    pub fn num_parameters(&self) -> usize {
        self.in_features * self.out_features + self.out_features
    }
}

impl<F: Float + Debug + Send + Sync + ScalarOperand + NumAssign + 'static> Layer<F>
    for GinConv<F>
{
    fn forward(&self, input: &Array<F, IxDyn>) -> Result<Array<F, IxDyn>> {
        let f2 = input
            .clone()
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .map_err(|e| NeuralError::DimensionMismatch(format!("Expected 2D input: {e}")))?;
        let n = f2.nrows();
        let adj = Array2::<F>::eye(n);
        self.forward_graph(&f2, &adj, 0.0).map(|a| a.into_dyn())
    }

    fn backward(
        &self,
        _input: &Array<F, IxDyn>,
        grad: &Array<F, IxDyn>,
    ) -> Result<Array<F, IxDyn>> {
        Ok(grad.clone())
    }

    fn update(&mut self, lr: F) -> Result<()> {
        {
            let dw = self
                .dweight
                .read()
                .map_err(|e| NeuralError::ComputationError(format!("RwLock poisoned: {e}")))?;
            for (w, g) in self.weight.iter_mut().zip(dw.iter()) {
                *w -= lr * *g;
            }
        }
        {
            let db = self
                .dbias
                .read()
                .map_err(|e| NeuralError::ComputationError(format!("RwLock poisoned: {e}")))?;
            for (b, g) in self.bias.iter_mut().zip(db.iter()) {
                *b -= lr * *g;
            }
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
    fn layer_type(&self) -> &str {
        "GinConv"
    }
    fn parameter_count(&self) -> usize {
        self.num_parameters()
    }
    fn layer_description(&self) -> String {
        format!(
            "type:GinConv in:{} out:{}",
            self.in_features, self.out_features
        )
    }

    fn params(&self) -> Vec<Array<F, IxDyn>> {
        vec![
            self.weight.clone().into_dyn(),
            self.bias.clone().into_dyn(),
        ]
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::Array2;
    use scirs2_core::random::rng;

    // ── GinLayer tests ────────────────────────────────────────────────────────

    #[test]
    fn test_gin_layer_output_shape() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(4, 8, 16, false, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        let features = Array2::<f64>::from_elem((5, 4), 0.1);
        let adj = Array2::<f64>::eye(5);
        let out = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward failed");
        assert_eq!(out.shape(), &[5, 8]);
    }

    #[test]
    fn test_gin_layer_with_adjacency() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(3, 6, 12, false, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        let features = Array2::<f64>::from_elem((4, 3), 0.5);
        // Ring graph
        let adj = Array2::<f64>::from_shape_vec(
            (4, 4),
            vec![
                0.0_f64, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
                0.0,
            ],
        )
        .expect("shape");
        let out = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward failed");
        assert_eq!(out.shape(), &[4, 6]);
        assert!(out.iter().all(|&v| v.is_finite()));
    }

    #[test]
    fn test_gin_layer_epsilon_effect() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(2, 4, 8, false, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        let features = Array2::<f64>::from_elem((3, 2), 1.0);
        let adj = Array2::<f64>::eye(3);

        let out_eps0 = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward eps0");
        let out_eps1 = layer
            .forward_graph(&features, &adj, 1.0)
            .expect("Forward eps1");
        // With identity adjacency, ε affects the self contribution
        // (1+0) + nothing = 1  vs  (1+1) + nothing = 2 — outputs must differ
        let changed = out_eps0
            .iter()
            .zip(out_eps1.iter())
            .any(|(a, b)| (a - b).abs() > 1e-10);
        assert!(changed, "ε should change the output");
    }

    #[test]
    fn test_gin_layer_learn_epsilon_uses_stored() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(2, 4, 8, true, 0.5, &mut rng)
            .expect("Failed to create GIN layer");
        let features = Array2::<f64>::from_elem((3, 2), 1.0);
        let adj = Array2::<f64>::eye(3);
        // When learn_epsilon = true, the passed epsilon (99.0) is ignored
        let out_stored = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward stored");
        let out_ignored = layer
            .forward_graph(&features, &adj, 99.0)
            .expect("Forward ignored");
        let all_equal = out_stored
            .iter()
            .zip(out_ignored.iter())
            .all(|(a, b)| (a - b).abs() < 1e-10);
        assert!(
            all_equal,
            "learn_epsilon=true should ignore the explicit epsilon argument"
        );
    }

    #[test]
    fn test_gin_layer_parameter_count() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(4, 8, 16, true, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        // W1: 4×16=64, b1: 16, W2: 16×8=128, b2: 8, ε: 1  → 217
        assert_eq!(layer.num_parameters(), 4 * 16 + 16 + 16 * 8 + 8 + 1);
    }

    #[test]
    fn test_gin_layer_no_learn_epsilon_parameter_count() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(4, 8, 16, false, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        // No ε parameter: W1: 4×16=64, b1: 16, W2: 16×8=128, b2: 8 → 216
        assert_eq!(layer.num_parameters(), 4 * 16 + 16 + 16 * 8 + 8);
    }

    #[test]
    fn test_gin_layer_zero_input_relu_output() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(3, 6, 12, false, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        let features = Array2::<f64>::zeros((4, 3));
        let adj = Array2::<f64>::from_elem((4, 4), 1.0);
        let out = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward failed");
        // Zero input → zero aggregation → hidden = ReLU(b1) → since b1=0, hidden=0 → out=b2=0
        assert!(
            out.iter().all(|&v| v == 0.0),
            "Zero input with zero biases should yield zero output"
        );
    }

    #[test]
    fn test_gin_layer_wrong_features_error() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(4, 8, 16, false, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        let features = Array2::<f64>::from_elem((5, 3), 0.1); // wrong: 3 ≠ 4
        let adj = Array2::<f64>::eye(5);
        assert!(layer.forward_graph(&features, &adj, 0.0).is_err());
    }

    #[test]
    fn test_gin_layer_trait_forward() {
        let mut rng = rng();
        let layer = GinLayer::<f64>::new(4, 4, 8, false, 0.0, &mut rng)
            .expect("Failed to create GIN layer");
        let input = Array2::<f64>::from_elem((3, 4), 0.3).into_dyn();
        let out = layer.forward(&input).expect("Layer trait forward failed");
        assert_eq!(out.shape(), &[3, 4]);
    }

    // ── GinConv tests ─────────────────────────────────────────────────────────

    #[test]
    fn test_gin_conv_output_shape() {
        let mut rng = rng();
        let layer =
            GinConv::<f64>::new(4, 8, &mut rng).expect("Failed to create GinConv");
        let features = Array2::<f64>::from_elem((6, 4), 0.2);
        let adj = Array2::<f64>::eye(6);
        let out = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward failed");
        assert_eq!(out.shape(), &[6, 8]);
    }

    #[test]
    fn test_gin_conv_non_negative_output() {
        // GinConv applies ReLU — output must be non-negative
        let mut rng = rng();
        let layer =
            GinConv::<f64>::new(3, 6, &mut rng).expect("Failed to create GinConv");
        let features = Array2::<f64>::from_elem((5, 3), 0.5);
        let adj = Array2::<f64>::from_elem((5, 5), 1.0);
        let out = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward failed");
        assert!(
            out.iter().all(|&v| v >= 0.0),
            "GinConv output must be non-negative (ReLU)"
        );
    }

    #[test]
    fn test_gin_conv_epsilon_changes_output() {
        let mut rng = rng();
        let layer =
            GinConv::<f64>::new(2, 4, &mut rng).expect("Failed to create GinConv");
        let features = Array2::<f64>::from_elem((3, 2), 1.0);
        let adj = Array2::<f64>::eye(3);
        let out0 = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("fwd eps0");
        let out1 = layer
            .forward_graph(&features, &adj, 2.0)
            .expect("fwd eps2");
        let changed = out0
            .iter()
            .zip(out1.iter())
            .any(|(a, b)| (a - b).abs() > 1e-10);
        assert!(changed, "ε should change GinConv output");
    }

    #[test]
    fn test_gin_conv_parameter_count() {
        let mut rng = rng();
        let layer =
            GinConv::<f64>::new(4, 8, &mut rng).expect("Failed to create GinConv");
        // W: 4×8 = 32, b: 8 → 40
        assert_eq!(layer.num_parameters(), 4 * 8 + 8);
    }

    #[test]
    fn test_gin_conv_wrong_adj_error() {
        let mut rng = rng();
        let layer =
            GinConv::<f64>::new(4, 8, &mut rng).expect("Failed to create GinConv");
        let features = Array2::<f64>::from_elem((4, 4), 0.1);
        let adj = Array2::<f64>::eye(3); // wrong size: 3×3 ≠ 4×4
        assert!(layer.forward_graph(&features, &adj, 0.0).is_err());
    }

    #[test]
    fn test_gin_conv_layer_trait_forward() {
        let mut rng = rng();
        let layer =
            GinConv::<f64>::new(4, 6, &mut rng).expect("Failed to create GinConv");
        let input = Array2::<f64>::from_elem((5, 4), 0.2).into_dyn();
        let out = layer.forward(&input).expect("Layer trait forward failed");
        assert_eq!(out.shape(), &[5, 6]);
    }

    #[test]
    fn test_gin_conv_fully_connected_graph() {
        // In a fully connected graph every node should receive the same
        // aggregated signal (since all node features are identical), so the
        // output rows must all be equal.
        let mut rng = rng();
        let layer =
            GinConv::<f64>::new(3, 5, &mut rng).expect("Failed to create GinConv");
        let features = Array2::<f64>::from_elem((4, 3), 0.3);
        let adj = Array2::<f64>::from_elem((4, 4), 1.0);
        let out = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward failed");
        let row0 = out.row(0).to_owned();
        for i in 1..4 {
            let diff: f64 = row0
                .iter()
                .zip(out.row(i).iter())
                .map(|(a, b)| (a - b).abs())
                .fold(0.0_f64, f64::max);
            assert!(
                diff < 1e-10,
                "Row {i} differs from row 0 by {diff} in a fully connected uniform graph"
            );
        }
    }

    // ── Sum-aggregation correctness test (shared by both layers) ─────────────

    #[test]
    fn test_sum_aggregation_correctness() {
        let mut rng = rng();
        let layer = GinConv::<f64>::new(2, 2, &mut rng).expect("GinConv");
        // 3-node chain: 0—1—2
        let features = Array2::<f64>::from_shape_vec(
            (3, 2),
            vec![1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0],
        )
        .expect("shape");
        let adj = Array2::<f64>::from_shape_vec(
            (3, 3),
            vec![0.0_f64, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0],
        )
        .expect("shape");

        // Node 0 (eps=0): self [1,0] + neighbour[1] [0,1] = [1,1]
        // Node 1 (eps=0): self [0,1] + neighbour[0] [1,0] + neighbour[2] [1,1] = [2,2]
        // Node 2 (eps=0): self [1,1] + neighbour[1] [0,1] = [1,2]
        // We only verify that calling forward doesn't error and produces the right shape.
        let out = layer
            .forward_graph(&features, &adj, 0.0)
            .expect("Forward failed");
        assert_eq!(out.shape(), &[3, 2]);
        assert!(out.iter().all(|&v| v.is_finite()));
    }
}