scirs2-neural 0.4.2

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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! GAN (Generative Adversarial Network) framework
//!
//! Provides a modular GAN framework with:
//! - Configurable Generator and Discriminator networks
//! - Standard GAN training loop (alternating optimization)
//! - WGAN-GP (Wasserstein GAN with Gradient Penalty) variant
//! - Generation from noise
//!
//! References:
//! - "Generative Adversarial Nets", Goodfellow et al. (2014) <https://arxiv.org/abs/1406.2661>
//! - "Improved Training of Wasserstein GANs", Gulrajani et al. (2017) <https://arxiv.org/abs/1704.00028>

use crate::error::{NeuralError, Result};
use crate::layers::{Dense, Dropout, Layer};
use scirs2_core::ndarray::{Array, IxDyn, ScalarOperand};
use scirs2_core::numeric::{Float, NumAssign};
use scirs2_core::random::SeedableRng;
use std::fmt::Debug;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// GAN training mode
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GANMode {
    /// Standard GAN with binary cross-entropy loss
    Standard,
    /// Wasserstein GAN with gradient penalty (WGAN-GP)
    WGANGP,
}

/// Configuration for the Generator network
#[derive(Debug, Clone)]
pub struct GeneratorConfig {
    /// Noise (latent) input dimension
    pub noise_dim: usize,
    /// Hidden layer dimensions
    pub hidden_dims: Vec<usize>,
    /// Output dimension (e.g., flattened image size)
    pub output_dim: usize,
    /// Dropout rate
    pub dropout_rate: f64,
    /// Whether to use batch normalization
    pub use_batch_norm: bool,
}

impl GeneratorConfig {
    /// Standard generator config
    pub fn standard(noise_dim: usize, output_dim: usize) -> Self {
        Self {
            noise_dim,
            hidden_dims: vec![256, 512, 1024],
            output_dim,
            dropout_rate: 0.0,
            use_batch_norm: true,
        }
    }

    /// Tiny generator for testing
    pub fn tiny(noise_dim: usize, output_dim: usize) -> Self {
        Self {
            noise_dim,
            hidden_dims: vec![32, 64],
            output_dim,
            dropout_rate: 0.0,
            use_batch_norm: false,
        }
    }
}

/// Configuration for the Discriminator network
#[derive(Debug, Clone)]
pub struct DiscriminatorConfig {
    /// Input dimension (same as generator output)
    pub input_dim: usize,
    /// Hidden layer dimensions
    pub hidden_dims: Vec<usize>,
    /// Dropout rate (commonly used in discriminators)
    pub dropout_rate: f64,
}

impl DiscriminatorConfig {
    /// Standard discriminator config
    pub fn standard(input_dim: usize) -> Self {
        Self {
            input_dim,
            hidden_dims: vec![1024, 512, 256],
            dropout_rate: 0.2,
        }
    }

    /// Tiny discriminator for testing
    pub fn tiny(input_dim: usize) -> Self {
        Self {
            input_dim,
            hidden_dims: vec![64, 32],
            dropout_rate: 0.0,
        }
    }
}

/// Configuration for the full GAN system
#[derive(Debug, Clone)]
pub struct GANConfig {
    /// Generator configuration
    pub generator: GeneratorConfig,
    /// Discriminator configuration
    pub discriminator: DiscriminatorConfig,
    /// Training mode
    pub mode: GANMode,
    /// Gradient penalty coefficient for WGAN-GP (lambda)
    pub gradient_penalty_weight: f64,
    /// Number of discriminator steps per generator step
    pub n_critic: usize,
}

impl GANConfig {
    /// Standard GAN configuration
    pub fn standard(noise_dim: usize, data_dim: usize) -> Self {
        Self {
            generator: GeneratorConfig::standard(noise_dim, data_dim),
            discriminator: DiscriminatorConfig::standard(data_dim),
            mode: GANMode::Standard,
            gradient_penalty_weight: 10.0,
            n_critic: 1,
        }
    }

    /// WGAN-GP configuration (recommended)
    pub fn wgan_gp(noise_dim: usize, data_dim: usize) -> Self {
        Self {
            generator: GeneratorConfig::standard(noise_dim, data_dim),
            discriminator: DiscriminatorConfig::standard(data_dim),
            mode: GANMode::WGANGP,
            gradient_penalty_weight: 10.0,
            n_critic: 5,
        }
    }

    /// Tiny configuration for testing
    pub fn tiny(noise_dim: usize, data_dim: usize) -> Self {
        Self {
            generator: GeneratorConfig::tiny(noise_dim, data_dim),
            discriminator: DiscriminatorConfig::tiny(data_dim),
            mode: GANMode::Standard,
            gradient_penalty_weight: 10.0,
            n_critic: 1,
        }
    }

    /// Set GAN mode
    pub fn with_mode(mut self, mode: GANMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set gradient penalty weight (WGAN-GP)
    pub fn with_gradient_penalty(mut self, weight: f64) -> Self {
        self.gradient_penalty_weight = weight;
        self
    }

    /// Set number of critic steps per generator step
    pub fn with_n_critic(mut self, n: usize) -> Self {
        self.n_critic = n.max(1);
        self
    }
}

// ---------------------------------------------------------------------------
// Generator
// ---------------------------------------------------------------------------

/// Generator network: maps noise z to data space
///
/// Architecture: noise_dim -> hidden[0] -> ... -> hidden[n-1] -> output_dim
/// Uses ReLU activations in hidden layers and tanh in the output layer.
pub struct Generator<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> {
    config: GeneratorConfig,
    layers: Vec<Dense<F>>,
    dropout: Option<Dropout<F>>,
}

impl<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> Generator<F> {
    /// Create a new Generator
    pub fn new(config: GeneratorConfig) -> Result<Self> {
        if config.noise_dim == 0 || config.output_dim == 0 {
            return Err(NeuralError::InvalidArchitecture(
                "noise_dim and output_dim must be > 0".to_string(),
            ));
        }

        let mut layers = Vec::new();
        let mut in_dim = config.noise_dim;
        let mut seed: u8 = 110;

        for &hdim in &config.hidden_dims {
            let mut rng = scirs2_core::random::rngs::SmallRng::from_seed([seed; 32]);
            seed = seed.wrapping_add(1);
            layers.push(Dense::new(in_dim, hdim, None, &mut rng)?);
            in_dim = hdim;
        }

        // Output layer
        {
            let mut rng = scirs2_core::random::rngs::SmallRng::from_seed([seed; 32]);
            layers.push(Dense::new(in_dim, config.output_dim, None, &mut rng)?);
        }

        let dropout = if config.dropout_rate > 0.0 {
            let mut rng = scirs2_core::random::rngs::SmallRng::from_seed([120; 32]);
            Some(Dropout::new(config.dropout_rate, &mut rng)?)
        } else {
            None
        };

        Ok(Self {
            config,
            layers,
            dropout,
        })
    }

    /// Get config
    pub fn config(&self) -> &GeneratorConfig {
        &self.config
    }

    /// Total parameter count
    pub fn total_parameter_count(&self) -> usize {
        self.layers.iter().map(|l| l.parameter_count()).sum()
    }
}

impl<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> Layer<F>
    for Generator<F>
{
    fn forward(&self, input: &Array<F, IxDyn>) -> Result<Array<F, IxDyn>> {
        let mut x = input.clone();
        for (i, layer) in self.layers.iter().enumerate() {
            x = layer.forward(&x)?;
            if i < self.layers.len() - 1 {
                // Hidden layers: ReLU + optional dropout
                x = x.mapv(|v| v.max(F::zero()));
                if let Some(ref drop) = self.dropout {
                    x = drop.forward(&x)?;
                }
            } else {
                // Output layer: tanh to bound output to [-1, 1]
                x = x.mapv(|v| v.tanh());
            }
        }
        Ok(x)
    }

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

    fn update(&mut self, learning_rate: F) -> Result<()> {
        for layer in &mut self.layers {
            layer.update(learning_rate)?;
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn params(&self) -> Vec<Array<F, IxDyn>> {
        self.layers.iter().flat_map(|l| l.params()).collect()
    }

    fn parameter_count(&self) -> usize {
        self.total_parameter_count()
    }

    fn layer_type(&self) -> &str {
        "Generator"
    }

    fn layer_description(&self) -> String {
        format!(
            "Generator(noise={}, hidden={:?}, output={}, params={})",
            self.config.noise_dim,
            self.config.hidden_dims,
            self.config.output_dim,
            self.total_parameter_count()
        )
    }
}

// ---------------------------------------------------------------------------
// Discriminator
// ---------------------------------------------------------------------------

/// Discriminator network: maps data to a scalar (real/fake score)
///
/// Architecture: input_dim -> hidden[0] -> ... -> hidden[n-1] -> 1
/// Uses LeakyReLU activations in hidden layers.
/// Output is raw logit (no sigmoid) for numerical stability.
pub struct Discriminator<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> {
    config: DiscriminatorConfig,
    layers: Vec<Dense<F>>,
    dropout: Option<Dropout<F>>,
}

impl<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> Discriminator<F> {
    /// Create a new Discriminator
    pub fn new(config: DiscriminatorConfig) -> Result<Self> {
        if config.input_dim == 0 {
            return Err(NeuralError::InvalidArchitecture(
                "input_dim must be > 0".to_string(),
            ));
        }

        let mut layers = Vec::new();
        let mut in_dim = config.input_dim;
        let mut seed: u8 = 130;

        for &hdim in &config.hidden_dims {
            let mut rng = scirs2_core::random::rngs::SmallRng::from_seed([seed; 32]);
            seed = seed.wrapping_add(1);
            layers.push(Dense::new(in_dim, hdim, None, &mut rng)?);
            in_dim = hdim;
        }

        // Output layer: single logit
        {
            let mut rng = scirs2_core::random::rngs::SmallRng::from_seed([seed; 32]);
            layers.push(Dense::new(in_dim, 1, None, &mut rng)?);
        }

        let dropout = if config.dropout_rate > 0.0 {
            let mut rng = scirs2_core::random::rngs::SmallRng::from_seed([140; 32]);
            Some(Dropout::new(config.dropout_rate, &mut rng)?)
        } else {
            None
        };

        Ok(Self {
            config,
            layers,
            dropout,
        })
    }

    /// Get config
    pub fn config(&self) -> &DiscriminatorConfig {
        &self.config
    }

    /// Total parameter count
    pub fn total_parameter_count(&self) -> usize {
        self.layers.iter().map(|l| l.parameter_count()).sum()
    }
}

/// LeakyReLU with negative slope 0.2
fn leaky_relu<F: Float>(x: F) -> F {
    let slope = F::from(0.2).expect("leaky relu slope");
    if x > F::zero() {
        x
    } else {
        slope * x
    }
}

impl<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> Layer<F>
    for Discriminator<F>
{
    fn forward(&self, input: &Array<F, IxDyn>) -> Result<Array<F, IxDyn>> {
        let mut x = input.clone();
        for (i, layer) in self.layers.iter().enumerate() {
            x = layer.forward(&x)?;
            if i < self.layers.len() - 1 {
                // Hidden: LeakyReLU + optional dropout
                x = x.mapv(leaky_relu);
                if let Some(ref drop) = self.dropout {
                    x = drop.forward(&x)?;
                }
            }
            // Output: raw logit (no activation)
        }
        Ok(x)
    }

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

    fn update(&mut self, learning_rate: F) -> Result<()> {
        for layer in &mut self.layers {
            layer.update(learning_rate)?;
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn params(&self) -> Vec<Array<F, IxDyn>> {
        self.layers.iter().flat_map(|l| l.params()).collect()
    }

    fn parameter_count(&self) -> usize {
        self.total_parameter_count()
    }

    fn layer_type(&self) -> &str {
        "Discriminator"
    }

    fn layer_description(&self) -> String {
        format!(
            "Discriminator(input={}, hidden={:?}, params={})",
            self.config.input_dim,
            self.config.hidden_dims,
            self.total_parameter_count()
        )
    }
}

// ---------------------------------------------------------------------------
// GAN training step result
// ---------------------------------------------------------------------------

/// Result of a single GAN training step
#[derive(Debug, Clone)]
pub struct GANStepResult<F: Float> {
    /// Discriminator loss
    pub d_loss: F,
    /// Generator loss
    pub g_loss: F,
    /// Gradient penalty (WGAN-GP only, zero otherwise)
    pub gradient_penalty: F,
    /// Mean discriminator output on real data
    pub d_real_mean: F,
    /// Mean discriminator output on fake data
    pub d_fake_mean: F,
}

// ---------------------------------------------------------------------------
// GAN system
// ---------------------------------------------------------------------------

/// Complete GAN system combining Generator and Discriminator
///
/// Supports standard GAN training and WGAN-GP variant.
///
/// # Examples
///
/// ```no_run
/// use scirs2_neural::models::architectures::gan::{GAN, GANConfig};
///
/// let config = GANConfig::tiny(10, 20);
/// let mut gan: GAN<f64> = GAN::new(config).expect("Failed to create GAN");
/// ```
pub struct GAN<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> {
    config: GANConfig,
    /// Generator network
    pub generator: Generator<F>,
    /// Discriminator (critic) network
    pub discriminator: Discriminator<F>,
    /// PRNG state for noise generation
    rng_state: std::cell::Cell<u64>,
    /// Training step counter
    step_count: usize,
}

// SAFETY: rng_state is only mutated during single-threaded forward/train calls
unsafe impl<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> Sync for GAN<F> {}

impl<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> GAN<F> {
    /// Create a new GAN
    pub fn new(config: GANConfig) -> Result<Self> {
        let generator = Generator::new(config.generator.clone())?;
        let discriminator = Discriminator::new(config.discriminator.clone())?;

        Ok(Self {
            config,
            generator,
            discriminator,
            rng_state: std::cell::Cell::new(0xBEEF_CAFE_DEAD_BABEu64),
            step_count: 0,
        })
    }

    /// Get configuration
    pub fn config(&self) -> &GANConfig {
        &self.config
    }

    /// Generate random noise for the generator
    pub fn sample_noise(&self, batch_size: usize) -> Array<F, IxDyn> {
        let noise_dim = self.config.generator.noise_dim;
        let mut state = self.rng_state.get();
        let mut noise = Array::zeros(IxDyn(&[batch_size, noise_dim]));

        for b in 0..batch_size {
            for d in 0..noise_dim {
                // Box-Muller for standard normal
                let u1 = xorshift_f64(&mut state).max(1e-10);
                let u2 = xorshift_f64(&mut state);
                let normal = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos();
                noise[[b, d]] = F::from(normal).expect("noise conversion");
            }
        }

        self.rng_state.set(state);
        noise
    }

    /// Generate fake samples
    pub fn generate(&self, batch_size: usize) -> Result<Array<F, IxDyn>> {
        let noise = self.sample_noise(batch_size);
        self.generator.forward(&noise)
    }

    /// Compute binary cross-entropy loss (standard GAN)
    ///
    /// loss = -mean(target * log(sigmoid(logit)) + (1-target) * log(1-sigmoid(logit)))
    fn bce_loss(logits: &Array<F, IxDyn>, target: F) -> F {
        let eps = F::from(1e-7).expect("eps");
        let one = F::one();
        let n = F::from(logits.len()).expect("n");

        let mut loss = F::zero();
        for &logit in logits.iter() {
            let sigmoid = one / (one + (-logit).exp());
            let sig_clamped = sigmoid.max(eps).min(one - eps);
            loss += target * sig_clamped.ln() + (one - target) * (one - sig_clamped).ln();
        }

        -loss / n
    }

    /// Compute Wasserstein loss
    ///
    /// D wants to maximize E[D(real)] - E[D(fake)]
    /// G wants to maximize E[D(fake)]
    fn wasserstein_d_loss(d_real: &Array<F, IxDyn>, d_fake: &Array<F, IxDyn>) -> F {
        let n_real = F::from(d_real.len()).expect("n");
        let n_fake = F::from(d_fake.len()).expect("n");
        let real_mean: F = d_real.iter().copied().fold(F::zero(), |a, b| a + b) / n_real;
        let fake_mean: F = d_fake.iter().copied().fold(F::zero(), |a, b| a + b) / n_fake;
        // Minimize negative Wasserstein distance
        fake_mean - real_mean
    }

    fn wasserstein_g_loss(d_fake: &Array<F, IxDyn>) -> F {
        let n = F::from(d_fake.len()).expect("n");
        let fake_mean: F = d_fake.iter().copied().fold(F::zero(), |a, b| a + b) / n;
        -fake_mean
    }

    /// Compute gradient penalty for WGAN-GP
    ///
    /// Approximation: we compute the finite-difference gradient of D
    /// along the interpolation between real and fake samples, and penalize
    /// deviations from unit norm.
    fn gradient_penalty(&self, real: &Array<F, IxDyn>, fake: &Array<F, IxDyn>) -> Result<F> {
        let shape = real.shape();
        let batch_size = shape[0];
        let data_dim = shape[1];

        // Random interpolation coefficient per sample
        let mut state = self.rng_state.get();
        let mut penalty = F::zero();
        let epsilon_fd = F::from(1e-4).expect("fd epsilon");

        for b in 0..batch_size {
            let alpha = F::from(xorshift_f64(&mut state)).expect("alpha");

            // Interpolated point
            let mut interp = Array::zeros(IxDyn(&[1, data_dim]));
            for d in 0..data_dim {
                interp[[0, d]] = alpha * real[[b, d]] + (F::one() - alpha) * fake[[b, d]];
            }

            // Approximate gradient norm via finite differences
            let d_interp = self.discriminator.forward(&interp)?;
            let base_val = d_interp[[0, 0]];

            let mut grad_norm_sq = F::zero();
            for d in 0..data_dim {
                let mut perturbed = interp.clone();
                perturbed[[0, d]] += epsilon_fd;
                let d_perturbed = self.discriminator.forward(&perturbed)?;
                let grad_d = (d_perturbed[[0, 0]] - base_val) / epsilon_fd;
                grad_norm_sq += grad_d * grad_d;
            }

            let grad_norm = grad_norm_sq.sqrt();
            let diff = grad_norm - F::one();
            penalty += diff * diff;
        }

        self.rng_state.set(state);

        Ok(penalty / F::from(batch_size).expect("batch"))
    }

    /// Execute one training step
    ///
    /// Performs alternating discriminator and generator updates.
    /// Returns loss statistics.
    pub fn train_step(
        &mut self,
        real_data: &Array<F, IxDyn>,
        learning_rate: F,
    ) -> Result<GANStepResult<F>> {
        let batch_size = real_data.shape()[0];

        // ----- Discriminator step -----
        let fake_data = self.generate(batch_size)?;

        let d_real = self.discriminator.forward(real_data)?;
        let d_fake = self.discriminator.forward(&fake_data)?;

        let (d_loss, gp) = match self.config.mode {
            GANMode::Standard => {
                let loss_real = Self::bce_loss(&d_real, F::one());
                let loss_fake = Self::bce_loss(&d_fake, F::zero());
                (loss_real + loss_fake, F::zero())
            }
            GANMode::WGANGP => {
                let w_loss = Self::wasserstein_d_loss(&d_real, &d_fake);
                let gp = self.gradient_penalty(real_data, &fake_data)?;
                let lambda = F::from(self.config.gradient_penalty_weight).expect("lambda");
                (w_loss + lambda * gp, gp)
            }
        };

        // Update discriminator
        self.discriminator.update(learning_rate)?;

        // ----- Generator step (every n_critic steps) -----
        self.step_count += 1;
        let g_loss = if self.step_count % self.config.n_critic == 0 {
            let fake_data = self.generate(batch_size)?;
            let d_fake_for_g = self.discriminator.forward(&fake_data)?;

            let g_loss = match self.config.mode {
                GANMode::Standard => Self::bce_loss(&d_fake_for_g, F::one()),
                GANMode::WGANGP => Self::wasserstein_g_loss(&d_fake_for_g),
            };

            self.generator.update(learning_rate)?;
            g_loss
        } else {
            F::zero()
        };

        // Compute means for monitoring
        let n_real = F::from(d_real.len()).expect("n");
        let n_fake = F::from(d_fake.len()).expect("n");
        let d_real_mean: F = d_real.iter().copied().fold(F::zero(), |a, b| a + b) / n_real;
        let d_fake_mean: F = d_fake.iter().copied().fold(F::zero(), |a, b| a + b) / n_fake;

        Ok(GANStepResult {
            d_loss,
            g_loss,
            gradient_penalty: gp,
            d_real_mean,
            d_fake_mean,
        })
    }

    /// Total parameter count for both networks
    pub fn total_parameter_count(&self) -> usize {
        self.generator.total_parameter_count() + self.discriminator.total_parameter_count()
    }
}

/// Simple xorshift64 returning f64 in [0, 1)
fn xorshift_f64(state: &mut u64) -> f64 {
    let mut s = *state;
    s ^= s << 13;
    s ^= s >> 7;
    s ^= s << 17;
    *state = s;
    (s >> 11) as f64 / ((1u64 << 53) as f64)
}

impl<F: Float + Debug + ScalarOperand + Send + Sync + NumAssign + 'static> Layer<F> for GAN<F> {
    /// Forward pass runs the generator (maps noise to data)
    fn forward(&self, input: &Array<F, IxDyn>) -> Result<Array<F, IxDyn>> {
        self.generator.forward(input)
    }

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

    fn update(&mut self, learning_rate: F) -> Result<()> {
        self.generator.update(learning_rate)?;
        self.discriminator.update(learning_rate)?;
        Ok(())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn params(&self) -> Vec<Array<F, IxDyn>> {
        let mut p = self.generator.params();
        p.extend(self.discriminator.params());
        p
    }

    fn parameter_count(&self) -> usize {
        self.total_parameter_count()
    }

    fn layer_type(&self) -> &str {
        "GAN"
    }

    fn layer_description(&self) -> String {
        format!(
            "GAN(mode={:?}, noise={}, data={}, g_params={}, d_params={})",
            self.config.mode,
            self.config.generator.noise_dim,
            self.config.generator.output_dim,
            self.generator.total_parameter_count(),
            self.discriminator.total_parameter_count()
        )
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // ---- Config Tests ----

    #[test]
    fn test_generator_config_standard() {
        let cfg = GeneratorConfig::standard(100, 784);
        assert_eq!(cfg.noise_dim, 100);
        assert_eq!(cfg.output_dim, 784);
        assert_eq!(cfg.hidden_dims, vec![256, 512, 1024]);
    }

    #[test]
    fn test_generator_config_tiny() {
        let cfg = GeneratorConfig::tiny(10, 20);
        assert_eq!(cfg.hidden_dims, vec![32, 64]);
    }

    #[test]
    fn test_discriminator_config_standard() {
        let cfg = DiscriminatorConfig::standard(784);
        assert_eq!(cfg.input_dim, 784);
        assert_eq!(cfg.hidden_dims, vec![1024, 512, 256]);
        assert!((cfg.dropout_rate - 0.2).abs() < 1e-10);
    }

    #[test]
    fn test_gan_config_standard() {
        let cfg = GANConfig::standard(100, 784);
        assert_eq!(cfg.mode, GANMode::Standard);
        assert_eq!(cfg.n_critic, 1);
    }

    #[test]
    fn test_gan_config_wgan_gp() {
        let cfg = GANConfig::wgan_gp(100, 784);
        assert_eq!(cfg.mode, GANMode::WGANGP);
        assert_eq!(cfg.n_critic, 5);
        assert!((cfg.gradient_penalty_weight - 10.0).abs() < 1e-10);
    }

    #[test]
    fn test_gan_config_builder() {
        let cfg = GANConfig::standard(10, 20)
            .with_mode(GANMode::WGANGP)
            .with_gradient_penalty(5.0)
            .with_n_critic(3);
        assert_eq!(cfg.mode, GANMode::WGANGP);
        assert!((cfg.gradient_penalty_weight - 5.0).abs() < 1e-10);
        assert_eq!(cfg.n_critic, 3);
    }

    // ---- Generator Tests ----

    #[test]
    fn test_generator_creation() {
        let cfg = GeneratorConfig::tiny(10, 20);
        let gen: Generator<f64> = Generator::new(cfg).expect("Failed to create generator");
        assert!(gen.total_parameter_count() > 0);
    }

    #[test]
    fn test_generator_forward() {
        let cfg = GeneratorConfig::tiny(10, 20);
        let gen: Generator<f64> = Generator::new(cfg).expect("Failed to create generator");

        let noise = Array::zeros(IxDyn(&[2, 10]));
        let output = gen.forward(&noise).expect("Generator forward failed");
        assert_eq!(output.shape(), &[2, 20]);

        // Output should be bounded by tanh: [-1, 1]
        for &v in output.iter() {
            assert!(v >= -1.0 && v <= 1.0, "tanh should bound output, got {}", v);
        }
    }

    #[test]
    fn test_generator_layer_trait() {
        let cfg = GeneratorConfig::tiny(10, 20);
        let gen: Generator<f64> = Generator::new(cfg).expect("Failed to create generator");
        assert_eq!(gen.layer_type(), "Generator");
        assert!(gen.parameter_count() > 0);
    }

    #[test]
    fn test_generator_invalid() {
        let cfg = GeneratorConfig {
            noise_dim: 0,
            hidden_dims: vec![],
            output_dim: 10,
            dropout_rate: 0.0,
            use_batch_norm: false,
        };
        assert!(Generator::<f64>::new(cfg).is_err());
    }

    // ---- Discriminator Tests ----

    #[test]
    fn test_discriminator_creation() {
        let cfg = DiscriminatorConfig::tiny(20);
        let disc: Discriminator<f64> =
            Discriminator::new(cfg).expect("Failed to create discriminator");
        assert!(disc.total_parameter_count() > 0);
    }

    #[test]
    fn test_discriminator_forward() {
        let cfg = DiscriminatorConfig::tiny(20);
        let disc: Discriminator<f64> =
            Discriminator::new(cfg).expect("Failed to create discriminator");

        let input = Array::zeros(IxDyn(&[3, 20]));
        let output = disc.forward(&input).expect("Discriminator forward failed");
        assert_eq!(output.shape(), &[3, 1]);
    }

    #[test]
    fn test_discriminator_layer_trait() {
        let cfg = DiscriminatorConfig::tiny(20);
        let disc: Discriminator<f64> =
            Discriminator::new(cfg).expect("Failed to create discriminator");
        assert_eq!(disc.layer_type(), "Discriminator");
    }

    #[test]
    fn test_discriminator_invalid() {
        let cfg = DiscriminatorConfig {
            input_dim: 0,
            hidden_dims: vec![],
            dropout_rate: 0.0,
        };
        assert!(Discriminator::<f64>::new(cfg).is_err());
    }

    // ---- GAN System Tests ----

    #[test]
    fn test_gan_creation() {
        let cfg = GANConfig::tiny(10, 20);
        let gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");
        assert!(gan.total_parameter_count() > 0);
    }

    #[test]
    fn test_gan_generate() {
        let cfg = GANConfig::tiny(10, 20);
        let gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");

        let samples = gan.generate(5).expect("Generation failed");
        assert_eq!(samples.shape(), &[5, 20]);
    }

    #[test]
    fn test_gan_sample_noise() {
        let cfg = GANConfig::tiny(10, 20);
        let gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");

        let noise = gan.sample_noise(3);
        assert_eq!(noise.shape(), &[3, 10]);
    }

    #[test]
    fn test_gan_forward() {
        let cfg = GANConfig::tiny(10, 20);
        let gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");

        let noise = Array::zeros(IxDyn(&[2, 10]));
        let output = gan.forward(&noise).expect("GAN forward failed");
        assert_eq!(output.shape(), &[2, 20]);
    }

    #[test]
    fn test_gan_train_step_standard() {
        let cfg = GANConfig::tiny(10, 20);
        let mut gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");

        let real_data = Array::zeros(IxDyn(&[4, 20]));
        let result = gan
            .train_step(&real_data, 0.001)
            .expect("Train step failed");

        assert!(result.d_loss.is_finite(), "d_loss should be finite");
        assert!(result.g_loss.is_finite(), "g_loss should be finite");
    }

    #[test]
    fn test_gan_train_step_wgan() {
        let cfg = GANConfig::tiny(10, 20)
            .with_mode(GANMode::WGANGP)
            .with_n_critic(1);
        let mut gan: GAN<f64> = GAN::new(cfg).expect("Failed to create WGAN");

        let real_data = Array::zeros(IxDyn(&[4, 20]));
        let result = gan
            .train_step(&real_data, 0.001)
            .expect("WGAN train step failed");

        assert!(result.d_loss.is_finite(), "d_loss should be finite");
        assert!(result.gradient_penalty.is_finite(), "GP should be finite");
    }

    #[test]
    fn test_gan_multiple_train_steps() {
        let cfg = GANConfig::tiny(10, 20);
        let mut gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");

        let real_data = Array::zeros(IxDyn(&[4, 20]));
        for _ in 0..5 {
            let result = gan
                .train_step(&real_data, 0.001)
                .expect("Train step failed");
            assert!(result.d_loss.is_finite());
        }
    }

    #[test]
    fn test_gan_layer_trait() {
        let cfg = GANConfig::tiny(10, 20);
        let gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");
        assert_eq!(gan.layer_type(), "GAN");
        let desc = gan.layer_description();
        assert!(desc.contains("GAN"));
        assert!(desc.contains("Standard"));
    }

    #[test]
    fn test_gan_update() {
        let cfg = GANConfig::tiny(10, 20);
        let mut gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");
        gan.update(0.001).expect("Update failed");
    }

    #[test]
    fn test_gan_params() {
        let cfg = GANConfig::tiny(10, 20);
        let gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");
        let p = gan.params();
        assert!(!p.is_empty());
    }

    #[test]
    fn test_gan_f32() {
        let cfg = GANConfig::tiny(10, 20);
        let gan: GAN<f32> = GAN::new(cfg).expect("Failed to create f32 GAN");
        let noise = Array::zeros(IxDyn(&[1, 10]));
        let output = gan.forward(&noise).expect("f32 forward failed");
        assert_eq!(output.shape(), &[1, 20]);
    }

    #[test]
    fn test_bce_loss() {
        // When logits are large positive and target=1, loss should be small
        let logits = Array::from_elem(IxDyn(&[4, 1]), 10.0_f64);
        let loss = GAN::<f64>::bce_loss(&logits, 1.0);
        assert!(
            loss < 0.01,
            "BCE loss should be small for correct prediction"
        );

        // When logits are large positive and target=0, loss should be large
        let loss_wrong = GAN::<f64>::bce_loss(&logits, 0.0);
        assert!(loss_wrong > loss, "Wrong target should give higher loss");
    }

    #[test]
    fn test_leaky_relu() {
        assert!((leaky_relu(1.0_f64) - 1.0).abs() < 1e-10);
        assert!((leaky_relu(0.0_f64) - 0.0).abs() < 1e-10);
        assert!((leaky_relu(-1.0_f64) - (-0.2)).abs() < 1e-10);
        assert!((leaky_relu(-5.0_f64) - (-1.0)).abs() < 1e-10);
    }

    #[test]
    fn test_xorshift_f64_range() {
        let mut state = 42u64;
        for _ in 0..100 {
            let v = xorshift_f64(&mut state);
            assert!(v >= 0.0 && v < 1.0);
        }
    }

    #[test]
    fn test_n_critic_skips_generator() {
        let cfg = GANConfig::tiny(10, 20).with_n_critic(3);
        let mut gan: GAN<f64> = GAN::new(cfg).expect("Failed to create GAN");

        let real_data = Array::zeros(IxDyn(&[2, 20]));

        // Steps 1 and 2: generator loss should be 0 (not updated)
        let r1 = gan.train_step(&real_data, 0.001).expect("Step 1");
        assert!(
            (r1.g_loss - 0.0).abs() < 1e-10,
            "G should not train on step 1"
        );

        let r2 = gan.train_step(&real_data, 0.001).expect("Step 2");
        assert!(
            (r2.g_loss - 0.0).abs() < 1e-10,
            "G should not train on step 2"
        );

        // Step 3: generator should train
        let r3 = gan.train_step(&real_data, 0.001).expect("Step 3");
        // g_loss will be non-zero (it was computed)
        assert!(r3.g_loss.is_finite(), "G should train on step 3");
    }
}