torsh-nn 0.1.2

Neural network modules for ToRSh with PyTorch-compatible API
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
//! # Gated Activation Functions
//!
//! This module contains gated activation functions that use gating mechanisms to control
//! information flow. These functions split their input into two parts and use one part
//! to gate the other, creating more sophisticated activation patterns commonly used
//! in transformer architectures and advanced neural networks.
//!
//! ## Included Activation Functions
//!
//! - **GLU** - Gated Linear Unit: `GLU(X) = (XW + b) ⊗ σ(XV + c)`
//! - **GEGLU** - Gaussian Error Gated Linear Unit: uses GELU for gating
//! - **ReGLU** - ReLU Gated Linear Unit: uses ReLU for gating
//! - **SwiGLU** - Swish Gated Linear Unit: uses SiLU/Swish for gating
//!
//! ## Gating Mechanism
//!
//! All gated functions follow a similar pattern:
//! 1. Split input tensor into two halves along a specified dimension
//! 2. Apply an activation function to one half (the "gate")
//! 3. Element-wise multiply the gate with the other half
//!
//! ## Usage Example
//!
//! ```rust
//! # use torsh_tensor::creation::randn;
//! # use torsh_core::error::Result;
//! # fn main() -> Result<()> {
//! use torsh_nn::layers::activation::gated::{GLU, GEGLU, ReGLU, SwiGLU};
//! use torsh_nn::Module;
//! use torsh_tensor::Tensor;
//!
//! // Create gated activation functions
//! let glu = GLU::new(-1); // Split along last dimension
//! let geglu = GEGLU::new(-1);
//! let reglu = ReGLU::new(-1);
//! let swiglu = SwiGLU::new(-1);
//!
//! // Input must have even size in the split dimension
//! let input = randn(&[2, 8])?; // 8 is even, will be split into 2x4
//! let glu_output = glu.forward(&input)?; // Output shape: [2, 4]
//! # Ok(())
//! # }
//! ```

use crate::{Module, ModuleBase, Parameter};
use torsh_core::device::DeviceType;
use torsh_core::error::{Result, TorshError};
use torsh_tensor::{creation::*, Tensor};

// Conditional imports for std/no_std compatibility
#[cfg(feature = "std")]
use std::{collections::HashMap, string::String};

#[cfg(not(feature = "std"))]
use alloc::string::String;

#[cfg(not(feature = "std"))]
use hashbrown::HashMap;

/// GLU (Gated Linear Unit) activation function
///
/// Applies the gated linear unit function by splitting the input tensor into two halves
/// along a specified dimension and applying element-wise multiplication with a sigmoid gate.
///
/// # Mathematical Definition
/// ```text
/// GLU(X) = Linear(X) ⊗ σ(Gate(X))
/// ```
/// where X is split into two parts, and σ is the sigmoid function.
///
/// # Implementation
/// The function splits the input along the specified dimension and computes:
/// ```text
/// GLU(input) = first_half ⊗ sigmoid(second_half)
/// ```
///
/// # Properties
/// - **Gating mechanism**: Uses sigmoid to gate information flow
/// - **Dimension reduction**: Output size is half the input size in the split dimension
/// - **Learnable gates**: Gates are computed from the input itself
/// - **Transformer usage**: Commonly used in transformer feed-forward layers
///
/// # Requirements
/// - Input tensor must have even size in the split dimension
/// - Split dimension must be valid for the input tensor
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::gated::GLU;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let glu = GLU::new(-1); // Split along last dimension
/// let input = randn(&[2, 8])?; // Last dim (8)? must be even
/// let output = glu.forward(&input)?; // Output shape: [2, 4]
/// # Ok(())
/// # }
/// ```
pub struct GLU {
    base: ModuleBase,
    dim: isize,
}

impl GLU {
    /// Create a new GLU activation
    ///
    /// # Arguments
    /// * `dim` - Dimension along which to split the input. Negative values count from the end.
    ///           Default: -1 (last dimension)
    pub fn new(dim: isize) -> Self {
        Self {
            base: ModuleBase::new(),
            dim,
        }
    }

    /// Create GLU with default dimension (-1, last dimension)
    pub fn default_dim() -> Self {
        Self::new(-1)
    }

    /// Gets the split dimension
    pub fn dim(&self) -> isize {
        self.dim
    }
}

impl Default for GLU {
    fn default() -> Self {
        Self::default_dim()
    }
}

impl Module for GLU {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        let shape_binding = input.shape();
        let input_shape = shape_binding.dims();
        let split_dim = if self.dim < 0 {
            (input_shape.len() as isize + self.dim) as usize
        } else {
            self.dim as usize
        };

        if split_dim >= input_shape.len() {
            return Err(TorshError::InvalidArgument(format!(
                "Dimension {} out of range for tensor with {} dimensions",
                self.dim,
                input_shape.len()
            )));
        }

        let split_size = input_shape[split_dim];
        if split_size % 2 != 0 {
            return Err(TorshError::InvalidArgument(format!(
                "Input dimension {} must be even for GLU, got {}",
                split_dim, split_size
            )));
        }

        let half_size = split_size / 2;

        // Split input into two halves
        let first_half = input.narrow(split_dim as i32, 0, half_size)?;
        let second_half = input.narrow(split_dim as i32, half_size as i64, half_size)?;

        // Apply sigmoid to second half (gate)
        let neg_second = second_half.neg()?;
        let exp_neg = neg_second.exp()?;
        let one_plus_exp = exp_neg.add_scalar(1.0)?;
        let ones_tensor = ones(second_half.shape().dims())?;
        let sigmoid_gate = ones_tensor.div(&one_plus_exp)?;

        // Element-wise multiply first_half with gated second_half
        first_half.mul(&sigmoid_gate)
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        self.base.parameters.clone()
    }

    fn training(&self) -> bool {
        self.base.training()
    }

    fn train(&mut self) {
        self.base.set_training(true);
    }

    fn eval(&mut self) {
        self.base.set_training(false);
    }

    fn set_training(&mut self, training: bool) {
        self.base.set_training(training);
    }

    fn to_device(&mut self, device: DeviceType) -> Result<()> {
        self.base.to_device(device)
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.base.named_parameters()
    }
}

/// GEGLU (Gaussian Error Gated Linear Unit) activation function
///
/// Applies GELU-gated linear unit by splitting the input and using GELU as the gate function.
/// This combines the benefits of GLU's gating mechanism with GELU's smooth activation properties.
///
/// # Mathematical Definition
/// ```text
/// GEGLU(X) = Linear(X) ⊗ GELU(Gate(X))
/// ```
/// where GELU is the Gaussian Error Linear Unit function.
///
/// # Implementation
/// ```text
/// GEGLU(input) = first_half ⊗ GELU(second_half)
/// ```
///
/// # Properties
/// - **GELU gating**: Uses GELU's smooth properties for gating
/// - **Transformer-friendly**: Popular in modern transformer architectures
/// - **Better gradients**: GELU provides better gradient flow than sigmoid
/// - **Non-monotonic gating**: GELU's non-monotonic nature can be beneficial
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::gated::GEGLU;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let geglu = GEGLU::new(-1);
/// let input = randn(&[2, 8])?;
/// let output = geglu.forward(&input)?; // Output shape: [2, 4]
/// # Ok(())
/// # }
/// ```
pub struct GEGLU {
    base: ModuleBase,
    dim: isize,
}

impl GEGLU {
    /// Create a new GEGLU activation
    ///
    /// # Arguments
    /// * `dim` - The dimension along which to split the input (default: -1, last dimension)
    pub fn new(dim: isize) -> Self {
        Self {
            base: ModuleBase::new(),
            dim,
        }
    }

    /// Gets the split dimension
    pub fn dim(&self) -> isize {
        self.dim
    }
}

impl Default for GEGLU {
    fn default() -> Self {
        Self::new(-1) // Split along last dimension by default
    }
}

impl Module for GEGLU {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        let binding = input.shape();
        let input_shape = binding.dims();

        // Get the actual dimension index
        let actual_dim = if self.dim < 0 {
            (input_shape.len() as isize + self.dim) as usize
        } else {
            self.dim as usize
        };

        if actual_dim >= input_shape.len() {
            return Err(TorshError::InvalidArgument(format!(
                "Dimension {} out of range for tensor with {} dimensions",
                self.dim,
                input_shape.len()
            )));
        }

        let dim_size = input_shape[actual_dim];
        if dim_size % 2 != 0 {
            return Err(TorshError::InvalidArgument(format!(
                "Input dimension {} must be even for GEGLU, got {}",
                actual_dim, dim_size
            )));
        }

        let half_size = dim_size / 2;

        // Split the input into two halves
        let first_half = input.narrow(actual_dim as i32, 0, half_size)?;
        let second_half = input.narrow(actual_dim as i32, half_size as i64, half_size)?;

        // Apply GELU to the second half (approximate version for efficiency)
        let gelu_gate = self.apply_gelu(&second_half)?;

        // Element-wise multiplication
        first_half.mul(&gelu_gate)
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        self.base.parameters.clone()
    }

    fn training(&self) -> bool {
        self.base.training()
    }

    fn train(&mut self) {
        self.base.set_training(true);
    }

    fn eval(&mut self) {
        self.base.set_training(false);
    }

    fn set_training(&mut self, training: bool) {
        self.base.set_training(training);
    }

    fn to_device(&mut self, device: DeviceType) -> Result<()> {
        self.base.to_device(device)
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.base.named_parameters()
    }
}

impl GEGLU {
    /// Apply GELU activation (approximate version)
    fn apply_gelu(&self, input: &Tensor) -> Result<Tensor> {
        // Approximate GELU: 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3)))
        let x_cubed = input.pow(3.0)?;
        let coeff_tensor = full(input.shape().dims(), 0.044715)?;
        let term = x_cubed.mul(&coeff_tensor)?;
        let inner = input.add(&term)?;
        let scale_tensor = full(input.shape().dims(), (2.0 / std::f32::consts::PI).sqrt())?;
        let scaled = inner.mul(&scale_tensor)?;
        let tanh_result = scaled.tanh()?;
        let ones_tensor = ones(input.shape().dims())?;
        let one_plus_tanh = tanh_result.add(&ones_tensor)?;
        let half_tensor = full(input.shape().dims(), 0.5)?;
        let half_x = input.mul(&half_tensor)?;
        half_x.mul(&one_plus_tanh)
    }
}

/// ReGLU (ReLU Gated Linear Unit) activation function
///
/// Applies ReLU-gated linear unit by splitting the input and using ReLU as the gate function.
/// This provides a simpler, more computationally efficient gating mechanism.
///
/// # Mathematical Definition
/// ```text
/// ReGLU(X) = Linear(X) ⊗ ReLU(Gate(X))
/// ```
///
/// # Implementation
/// ```text
/// ReGLU(input) = first_half ⊗ ReLU(second_half)
/// ```
///
/// # Properties
/// - **Simple gating**: Uses ReLU's simple, efficient computation
/// - **Sparse gating**: ReLU creates sparse gate patterns
/// - **Fast computation**: No expensive operations like exp or tanh
/// - **Memory efficient**: ReLU gating is very memory efficient
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::gated::ReGLU;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let reglu = ReGLU::new(-1);
/// let input = randn(&[2, 8])?;
/// let output = reglu.forward(&input)?; // Output shape: [2, 4]
/// # Ok(())
/// # }
/// ```
pub struct ReGLU {
    base: ModuleBase,
    dim: isize,
}

impl ReGLU {
    /// Create a new ReGLU activation
    ///
    /// # Arguments
    /// * `dim` - The dimension along which to split the input (default: -1, last dimension)
    pub fn new(dim: isize) -> Self {
        Self {
            base: ModuleBase::new(),
            dim,
        }
    }

    /// Gets the split dimension
    pub fn dim(&self) -> isize {
        self.dim
    }
}

impl Default for ReGLU {
    fn default() -> Self {
        Self::new(-1)
    }
}

impl Module for ReGLU {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        let binding = input.shape();
        let input_shape = binding.dims();

        let actual_dim = if self.dim < 0 {
            (input_shape.len() as isize + self.dim) as usize
        } else {
            self.dim as usize
        };

        if actual_dim >= input_shape.len() {
            return Err(TorshError::InvalidArgument(format!(
                "Dimension {} out of range for tensor with {} dimensions",
                self.dim,
                input_shape.len()
            )));
        }

        let dim_size = input_shape[actual_dim];
        if dim_size % 2 != 0 {
            return Err(TorshError::InvalidArgument(format!(
                "Input dimension {} must be even for ReGLU, got {}",
                actual_dim, dim_size
            )));
        }

        let half_size = dim_size / 2;

        // Split the input
        let first_half = input.narrow(actual_dim as i32, 0, half_size)?;
        let second_half = input.narrow(actual_dim as i32, half_size as i64, half_size)?;

        // Apply ReLU to second half: max(0, x)
        let zero = zeros(second_half.shape().dims())?;
        let relu_gate = second_half.maximum(&zero)?;

        // Element-wise multiplication
        first_half.mul(&relu_gate)
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        self.base.parameters.clone()
    }

    fn training(&self) -> bool {
        self.base.training()
    }

    fn train(&mut self) {
        self.base.set_training(true);
    }

    fn eval(&mut self) {
        self.base.set_training(false);
    }

    fn set_training(&mut self, training: bool) {
        self.base.set_training(training);
    }

    fn to_device(&mut self, device: DeviceType) -> Result<()> {
        self.base.to_device(device)
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.base.named_parameters()
    }
}

/// SwiGLU (Swish Gated Linear Unit) activation function
///
/// Applies SiLU/Swish-gated linear unit by splitting the input and using SiLU as the gate function.
/// SiLU (also known as Swish) provides smooth, self-gated properties that work well in practice.
///
/// # Mathematical Definition
/// ```text
/// SwiGLU(X) = Linear(X) ⊗ SiLU(Gate(X))
/// ```
/// where SiLU(x) = x * sigmoid(x).
///
/// # Implementation
/// ```text
/// SwiGLU(input) = first_half ⊗ SiLU(second_half)
/// ```
///
/// # Properties
/// - **Self-gated**: SiLU uses input to gate itself
/// - **Smooth**: Continuously differentiable gating function
/// - **Popular**: Widely used in modern transformer architectures
/// - **Better than ReLU**: Often outperforms ReLU-based gating
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::gated::SwiGLU;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let swiglu = SwiGLU::new(-1);
/// let input = randn(&[2, 8])?;
/// let output = swiglu.forward(&input)?; // Output shape: [2, 4]
/// # Ok(())
/// # }
/// ```
pub struct SwiGLU {
    base: ModuleBase,
    dim: isize,
}

impl SwiGLU {
    /// Create a new SwiGLU activation
    ///
    /// # Arguments
    /// * `dim` - The dimension along which to split the input (default: -1, last dimension)
    pub fn new(dim: isize) -> Self {
        Self {
            base: ModuleBase::new(),
            dim,
        }
    }

    /// Gets the split dimension
    pub fn dim(&self) -> isize {
        self.dim
    }
}

impl Default for SwiGLU {
    fn default() -> Self {
        Self::new(-1)
    }
}

impl Module for SwiGLU {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        let binding = input.shape();
        let input_shape = binding.dims();

        let actual_dim = if self.dim < 0 {
            (input_shape.len() as isize + self.dim) as usize
        } else {
            self.dim as usize
        };

        if actual_dim >= input_shape.len() {
            return Err(TorshError::InvalidArgument(format!(
                "Dimension {} out of range for tensor with {} dimensions",
                self.dim,
                input_shape.len()
            )));
        }

        let dim_size = input_shape[actual_dim];
        if dim_size % 2 != 0 {
            return Err(TorshError::InvalidArgument(format!(
                "Input dimension {} must be even for SwiGLU, got {}",
                actual_dim, dim_size
            )));
        }

        let half_size = dim_size / 2;

        // Split the input
        let first_half = input.narrow(actual_dim as i32, 0, half_size)?;
        let second_half = input.narrow(actual_dim as i32, half_size as i64, half_size)?;

        // Apply SiLU to second half: x * sigmoid(x)
        let neg_second = second_half.neg()?;
        let exp_neg = neg_second.exp()?;
        let one_plus_exp = exp_neg.add_scalar(1.0)?;
        let ones_tensor = ones(second_half.shape().dims())?;
        let sigmoid = ones_tensor.div(&one_plus_exp)?;
        let silu_gate = second_half.mul(&sigmoid)?;

        // Element-wise multiplication
        first_half.mul(&silu_gate)
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        self.base.parameters.clone()
    }

    fn training(&self) -> bool {
        self.base.training()
    }

    fn train(&mut self) {
        self.base.set_training(true);
    }

    fn eval(&mut self) {
        self.base.set_training(false);
    }

    fn set_training(&mut self, training: bool) {
        self.base.set_training(training);
    }

    fn to_device(&mut self, device: DeviceType) -> Result<()> {
        self.base.to_device(device)
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.base.named_parameters()
    }
}

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

    #[test]
    fn test_glu_dimension_parameter() {
        let glu = GLU::new(-1);
        assert_eq!(glu.dim(), -1);

        let glu_dim0 = GLU::new(0);
        assert_eq!(glu_dim0.dim(), 0);
    }

    #[test]
    fn test_glu_forward_shape() -> Result<()> {
        let glu = GLU::new(-1);
        let input = randn(&[2, 8])?; // Last dimension is even
        let output = glu.forward(&input)?;
        assert_eq!(output.shape().dims(), &[2, 4]); // Last dim halved
        Ok(())
    }

    #[test]
    fn test_glu_invalid_dimension() -> Result<()> {
        let glu = GLU::new(-1);
        let input = randn(&[2, 7])?; // Odd last dimension
        let result = glu.forward(&input);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_geglu_forward_shape() -> Result<()> {
        let geglu = GEGLU::new(-1);
        let input = randn(&[2, 8])?;
        let output = geglu.forward(&input)?;
        assert_eq!(output.shape().dims(), &[2, 4]);
        Ok(())
    }

    #[test]
    fn test_reglu_forward_shape() -> Result<()> {
        let reglu = ReGLU::new(-1);
        let input = randn(&[2, 8])?;
        let output = reglu.forward(&input)?;
        assert_eq!(output.shape().dims(), &[2, 4]);
        Ok(())
    }

    #[test]
    fn test_swiglu_forward_shape() -> Result<()> {
        let swiglu = SwiGLU::new(-1);
        let input = randn(&[2, 8])?;
        let output = swiglu.forward(&input)?;
        assert_eq!(output.shape().dims(), &[2, 4]);
        Ok(())
    }

    #[test]
    fn test_dimension_handling() -> Result<()> {
        // Test positive dimension
        let glu = GLU::new(1);
        let input = randn(&[2, 8, 3])?; // Dimension 1 has size 8 (even)
        let output = glu.forward(&input)?;
        assert_eq!(output.shape().dims(), &[2, 4, 3]); // Dimension 1 halved

        // Test negative dimension
        let glu_neg = GLU::new(-2);
        let input = randn(&[2, 8, 3])?; // Dimension -2 is dimension 1
        let output = glu_neg.forward(&input)?;
        assert_eq!(output.shape().dims(), &[2, 4, 3]);

        Ok(())
    }

    #[test]
    fn test_training_mode_toggle() -> Result<()> {
        let mut glu = GLU::new(-1);
        assert!(glu.training());

        glu.eval();
        assert!(!glu.training());

        glu.train();
        assert!(glu.training());

        Ok(())
    }

    #[test]
    fn test_default_implementations() {
        let _glu = GLU::default();
        let _geglu = GEGLU::default();
        let _reglu = ReGLU::default();
        let _swiglu = SwiGLU::default();
    }

    #[test]
    fn test_convenience_constructors() {
        let default_glu = GLU::default_dim();
        assert_eq!(default_glu.dim(), -1);
    }

    #[test]
    fn test_error_handling() -> Result<()> {
        let glu = GLU::new(10); // Invalid dimension
        let input = randn(&[2, 8])?; // Only 2 dimensions
        let result = glu.forward(&input);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_all_gated_functions_consistency() -> Result<()> {
        let input = randn(&[4, 16])?; // Even last dimension

        let glu = GLU::new(-1);
        let geglu = GEGLU::new(-1);
        let reglu = ReGLU::new(-1);
        let swiglu = SwiGLU::new(-1);

        let glu_out = glu.forward(&input)?;
        let geglu_out = geglu.forward(&input)?;
        let reglu_out = reglu.forward(&input)?;
        let swiglu_out = swiglu.forward(&input)?;

        // All should have the same output shape
        assert_eq!(glu_out.shape(), geglu_out.shape());
        assert_eq!(glu_out.shape(), reglu_out.shape());
        assert_eq!(glu_out.shape(), swiglu_out.shape());
        assert_eq!(glu_out.shape().dims(), &[4, 8]); // Halved last dimension

        Ok(())
    }
}