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
//! # Threshold and Shrinking Activation Functions
//!
//! This module contains activation functions that perform thresholding and shrinking operations.
//! These functions are useful for creating sparse representations and implementing various
//! non-linear transformations with specific threshold behaviors.
//!
//! ## Included Activation Functions
//!
//! - **Hardshrink** - Hard shrinkage function: zeros out values within a threshold range
//! - **Softshrink** - Soft shrinkage function: soft thresholding with linear shrinkage
//! - **Hardtanh** - Hard hyperbolic tangent: clamped linear function
//! - **Threshold** - Basic threshold function: replaces values below threshold with a constant
//! - **Tanhshrink** - Tanh shrinkage function: `x - tanh(x)`
//!
//! ## Usage Example
//!
//! ```rust
//! # use torsh_tensor::creation::{randn, tensor_1d};
//! # use torsh_core::error::Result;
//! # fn main() -> Result<()> {
//! # use torsh_tensor::creation::randn;
//! # use torsh_core::error::Result;
//! # fn main() -> Result<()> {
//! use torsh_nn::layers::activation::threshold::{Hardshrink, Softshrink, Hardtanh, Threshold};
//! use torsh_nn::Module;
//! use torsh_tensor::Tensor;
//!
//! // Create threshold and shrinking functions
//! let hardshrink = Hardshrink::new(0.5);
//! let softshrink = Softshrink::new(0.5);
//! let hardtanh = Hardtanh::new(-1.0, 1.0);
//! let threshold = Threshold::new(0.1, 0.0);
//!
//! // Apply to tensors
//! let input = randn(&[2, 3])?;
//! let hardshrink_output = hardshrink.forward(&input)?;
//! let softshrink_output = softshrink.forward(&input)?;
//! # Ok(())
//! # }
//! # Ok(())
//! # }
//! ```

use crate::{Module, ModuleBase, Parameter};
use torsh_core::device::DeviceType;
use torsh_core::error::Result;
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;

/// Hardshrink activation function
///
/// Applies the hard shrinkage function element-wise. This function zeros out values
/// whose absolute value is less than or equal to a threshold λ (lambda), and keeps
/// other values unchanged. It creates sparse representations by eliminating small values.
///
/// # Mathematical Definition
/// ```text
/// Hardshrink(x) = {
///     x    if |x| > λ
///     0    if |x| ≤ λ
/// }
/// ```
///
/// # Properties
/// - **Sparsity-inducing**: Creates sparse representations by zeroing small values
/// - **Piecewise**: Discontinuous function with sharp transitions
/// - **Configurable**: Threshold λ can be adjusted based on requirements
/// - **Symmetric**: Treats positive and negative values symmetrically
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::{randn, tensor_1d};
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::threshold::Hardshrink;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let hardshrink = Hardshrink::new(0.5); // λ = 0.5
/// let input = tensor_1d(&[-1.0, -0.3, 0.0, 0.3, 1.0])?;
/// let output = hardshrink.forward(&input)?; // [-1.0, 0.0, 0.0, 0.0, 1.0]
/// # Ok(())
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Hardshrink {
    base: ModuleBase,
    lambd: f32,
}

impl Hardshrink {
    /// Creates a new Hardshrink activation function
    ///
    /// # Arguments
    /// * `lambd` - The threshold parameter λ. Values with |x| ≤ λ are set to zero.
    pub fn new(lambd: f32) -> Self {
        Self {
            base: ModuleBase::new(),
            lambd,
        }
    }

    /// Gets the current lambda (threshold) value
    pub fn lambda(&self) -> f32 {
        self.lambd
    }
}

impl Default for Hardshrink {
    fn default() -> Self {
        Self::new(0.5)
    }
}

impl Module for Hardshrink {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // Apply hardshrink: x if |x| > λ, else 0
        let abs_input = input.abs()?;
        let lambda_tensor = full(input.shape().dims(), self.lambd)?;
        let zeros_tensor = zeros(input.shape().dims())?;

        // Use where to create the mask directly
        let condition = abs_input.gt(&lambda_tensor)?;
        input.where_tensor(&condition, &zeros_tensor)
    }

    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()
    }
}

/// Softshrink activation function
///
/// Applies the soft shrinkage function element-wise. This function performs soft thresholding,
/// which shrinks values towards zero by a constant amount λ (lambda) when their absolute
/// value exceeds the threshold, and sets them to zero otherwise.
///
/// # Mathematical Definition
/// ```text
/// Softshrink(x) = {
///     x - λ    if x > λ
///     x + λ    if x < -λ
///     0        if |x| ≤ λ
/// }
/// ```
///
/// # Properties
/// - **Soft thresholding**: Smoothly shrinks values rather than hard cutoff
/// - **Sparsity-inducing**: Creates sparse representations by zeroing small values
/// - **Continuous**: Piecewise linear but continuous function
/// - **Symmetric**: Treats positive and negative values symmetrically
/// - **Regularization**: Often used for L1-like regularization effects
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::{randn, tensor_1d};
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::threshold::Softshrink;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let softshrink = Softshrink::new(0.5); // λ = 0.5
/// let input = tensor_1d(&[-2.0, -0.3, 0.0, 0.3, 2.0])?;
/// let output = softshrink.forward(&input)?; // [-1.5, 0.0, 0.0, 0.0, 1.5]
/// # Ok(())
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Softshrink {
    base: ModuleBase,
    lambd: f32,
}

impl Softshrink {
    /// Creates a new Softshrink activation function
    ///
    /// # Arguments
    /// * `lambd` - The shrinkage parameter λ. Values with |x| ≤ λ are set to zero,
    ///             others are shrunk by λ towards zero.
    pub fn new(lambd: f32) -> Self {
        Self {
            base: ModuleBase::new(),
            lambd,
        }
    }

    /// Gets the current lambda (shrinkage) value
    pub fn lambda(&self) -> f32 {
        self.lambd
    }
}

impl Default for Softshrink {
    fn default() -> Self {
        Self::new(0.5)
    }
}

impl Module for Softshrink {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // Apply softshrink: sign(x) * max(|x| - λ, 0)
        let abs_input = input.abs()?;
        let lambda_tensor = full(input.shape().dims(), self.lambd)?;
        let zero_tensor = zeros(input.shape().dims())?;

        // Calculate |x| - λ
        let abs_minus_lambda = abs_input.sub(&lambda_tensor)?;

        // Apply max(|x| - λ, 0)
        let thresholded = abs_minus_lambda.maximum(&zero_tensor)?;

        // Apply sign(x) by using input.sign() or manual computation
        let sign_input = input.sign()?;
        thresholded.mul(&sign_input)
    }

    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()
    }
}

/// Hardtanh activation function
///
/// Applies the hard hyperbolic tangent function element-wise. This function clamps
/// input values to a specified range [min_val, max_val], creating a piecewise linear
/// function that is computationally efficient compared to the standard tanh function.
///
/// # Mathematical Definition
/// ```text
/// Hardtanh(x) = {
///     max_val    if x > max_val
///     x          if min_val ≤ x ≤ max_val
///     min_val    if x < min_val
/// }
/// ```
///
/// # Properties
/// - **Bounded**: Output is always within [min_val, max_val]
/// - **Piecewise linear**: Computationally efficient approximation to tanh
/// - **Configurable range**: Min and max values can be customized
/// - **Gradient preservation**: Has gradient 1 in the linear region
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::{randn, tensor_1d};
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::threshold::Hardtanh;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let hardtanh = Hardtanh::new(-1.0, 1.0); // Clamp to [-1, 1]
/// let input = tensor_1d(&[-2.0, -0.5, 0.0, 0.5, 2.0])?;
/// let output = hardtanh.forward(&input)?; // [-1.0, -0.5, 0.0, 0.5, 1.0]
/// # Ok(())
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Hardtanh {
    base: ModuleBase,
    min_val: f32,
    max_val: f32,
}

impl Hardtanh {
    /// Creates a new Hardtanh activation function
    ///
    /// # Arguments
    /// * `min_val` - The minimum value for clamping
    /// * `max_val` - The maximum value for clamping
    ///
    /// # Panics
    /// Panics if min_val >= max_val
    pub fn new(min_val: f32, max_val: f32) -> Self {
        assert!(min_val < max_val, "min_val must be less than max_val");
        Self {
            base: ModuleBase::new(),
            min_val,
            max_val,
        }
    }

    /// Creates a standard Hardtanh with range [-1, 1]
    pub fn standard() -> Self {
        Self::new(-1.0, 1.0)
    }

    /// Gets the minimum value
    pub fn min_val(&self) -> f32 {
        self.min_val
    }

    /// Gets the maximum value
    pub fn max_val(&self) -> f32 {
        self.max_val
    }
}

impl Default for Hardtanh {
    fn default() -> Self {
        Self::new(-1.0, 1.0)
    }
}

impl Module for Hardtanh {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // Apply hardtanh: clamp(x, min_val, max_val)
        let min_tensor = full(input.shape().dims(), self.min_val)?;
        let max_tensor = full(input.shape().dims(), self.max_val)?;

        // Clamp to [min_val, max_val]
        let clamped_high = input.minimum(&max_tensor)?;
        clamped_high.maximum(&min_tensor)
    }

    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()
    }
}

/// Threshold activation function
///
/// Applies a basic threshold function element-wise. Values above the threshold
/// are kept unchanged, while values at or below the threshold are replaced
/// with a specified value (typically 0).
///
/// # Mathematical Definition
/// ```text
/// Threshold(x) = {
///     x        if x > threshold
///     value    if x ≤ threshold
/// }
/// ```
///
/// # Properties
/// - **Binary decision**: Simple threshold-based activation
/// - **Configurable**: Both threshold and replacement value can be set
/// - **Discontinuous**: Sharp transition at the threshold
/// - **Asymmetric**: Different behavior above and below threshold
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::{randn, tensor_1d};
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::threshold::Threshold;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let threshold = Threshold::new(0.1, 0.0); // Threshold=0.1, replace with 0.0
/// let input = tensor_1d(&[-0.5, 0.05, 0.1, 0.2, 0.5])?;
/// let output = threshold.forward(&input)?; // [0.0, 0.0, 0.0, 0.2, 0.5]
/// # Ok(())
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Threshold {
    base: ModuleBase,
    threshold: f32,
    value: f32,
}

impl Threshold {
    /// Creates a new Threshold activation function
    ///
    /// # Arguments
    /// * `threshold` - The threshold value for comparison
    /// * `value` - The value to replace inputs that are ≤ threshold
    pub fn new(threshold: f32, value: f32) -> Self {
        Self {
            base: ModuleBase::new(),
            threshold,
            value,
        }
    }

    /// Creates a Threshold that zeros out values ≤ threshold
    pub fn zeroing(threshold: f32) -> Self {
        Self::new(threshold, 0.0)
    }

    /// Gets the threshold value
    pub fn threshold(&self) -> f32 {
        self.threshold
    }

    /// Gets the replacement value
    pub fn value(&self) -> f32 {
        self.value
    }
}

impl Default for Threshold {
    fn default() -> Self {
        Self::new(0.0, 0.0)
    }
}

impl Module for Threshold {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // Apply threshold: x if x > threshold, else value
        let threshold_tensor = full(input.shape().dims(), self.threshold)?;
        let value_tensor = full(input.shape().dims(), self.value)?;

        // Apply: input if input > threshold, else value
        let condition = input.gt(&threshold_tensor)?;
        input.where_tensor(&condition, &value_tensor)
    }

    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()
    }
}

/// Tanhshrink activation function
///
/// Applies the tanh shrinkage function element-wise: `x - tanh(x)`.
/// This function shrinks the input by subtracting its hyperbolic tangent,
/// creating an activation that has interesting properties for certain applications.
///
/// # Mathematical Definition
/// ```text
/// Tanhshrink(x) = x - tanh(x)
/// ```
///
/// # Properties
/// - **Shrinkage**: Always reduces the magnitude of the input
/// - **Bounded shrinkage**: The shrinkage amount is bounded by tanh(x)
/// - **Zero-preserving**: f(0) = 0
/// - **Odd function**: f(-x) = -f(x)
/// - **Smooth**: Continuously differentiable everywhere
///
/// # Example
/// ```rust
/// # use torsh_tensor::creation::{randn, tensor_1d};
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// # use torsh_tensor::creation::randn;
/// # use torsh_core::error::Result;
/// # fn main() -> Result<()> {
/// use torsh_nn::layers::activation::threshold::Tanhshrink;
/// use torsh_nn::Module;
/// use torsh_tensor::Tensor;
///
/// let tanhshrink = Tanhshrink::new();
/// let input = tensor_1d(&[-2.0, -1.0, 0.0, 1.0, 2.0])?;
/// let output = tanhshrink.forward(&input)?;
/// // Output will be x - tanh(x) for each element
/// # Ok(())
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Tanhshrink {
    base: ModuleBase,
}

impl Tanhshrink {
    /// Creates a new Tanhshrink activation function
    pub fn new() -> Self {
        Self {
            base: ModuleBase::new(),
        }
    }
}

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

impl Module for Tanhshrink {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // Apply tanhshrink: x - tanh(x)
        let tanh_result = input.tanh()?;
        input.sub(&tanh_result)
    }

    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_hardshrink_parameters() {
        let hardshrink = Hardshrink::new(0.3);
        assert_eq!(hardshrink.lambda(), 0.3);

        let default_hardshrink = Hardshrink::default();
        assert_eq!(default_hardshrink.lambda(), 0.5);
    }

    #[test]
    fn test_hardshrink_forward() -> Result<()> {
        let hardshrink = Hardshrink::new(0.5);
        let input = randn(&[2, 3])?;
        let output = hardshrink.forward(&input)?;
        assert_eq!(output.shape(), input.shape());
        Ok(())
    }

    #[test]
    fn test_softshrink_parameters() {
        let softshrink = Softshrink::new(0.3);
        assert_eq!(softshrink.lambda(), 0.3);

        let default_softshrink = Softshrink::default();
        assert_eq!(default_softshrink.lambda(), 0.5);
    }

    #[test]
    fn test_softshrink_forward() -> Result<()> {
        let softshrink = Softshrink::new(0.5);
        let input = randn(&[2, 3])?;
        let output = softshrink.forward(&input)?;
        assert_eq!(output.shape(), input.shape());
        Ok(())
    }

    #[test]
    fn test_hardtanh_parameters() {
        let hardtanh = Hardtanh::new(-2.0, 3.0);
        assert_eq!(hardtanh.min_val(), -2.0);
        assert_eq!(hardtanh.max_val(), 3.0);

        let standard_hardtanh = Hardtanh::standard();
        assert_eq!(standard_hardtanh.min_val(), -1.0);
        assert_eq!(standard_hardtanh.max_val(), 1.0);
    }

    #[test]
    #[should_panic(expected = "min_val must be less than max_val")]
    fn test_hardtanh_invalid_range() {
        let _hardtanh = Hardtanh::new(1.0, -1.0); // Should panic
    }

    #[test]
    fn test_hardtanh_forward() -> Result<()> {
        let hardtanh = Hardtanh::new(-1.0, 1.0);
        let input = randn(&[2, 3])?;
        let output = hardtanh.forward(&input)?;
        assert_eq!(output.shape(), input.shape());
        Ok(())
    }

    #[test]
    fn test_threshold_parameters() {
        let threshold = Threshold::new(0.1, -1.0);
        assert_eq!(threshold.threshold(), 0.1);
        assert_eq!(threshold.value(), -1.0);

        let zeroing_threshold = Threshold::zeroing(0.5);
        assert_eq!(zeroing_threshold.threshold(), 0.5);
        assert_eq!(zeroing_threshold.value(), 0.0);
    }

    #[test]
    fn test_threshold_forward() -> Result<()> {
        let threshold = Threshold::new(0.0, -1.0);
        let input = randn(&[2, 3])?;
        let output = threshold.forward(&input)?;
        assert_eq!(output.shape(), input.shape());
        Ok(())
    }

    #[test]
    fn test_tanhshrink_forward() -> Result<()> {
        let tanhshrink = Tanhshrink::new();
        let input = randn(&[2, 3])?;
        let output = tanhshrink.forward(&input)?;
        assert_eq!(output.shape(), input.shape());
        Ok(())
    }

    #[test]
    fn test_training_mode_toggle() -> Result<()> {
        let mut hardshrink = Hardshrink::new(0.5);
        assert!(hardshrink.training());

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

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

        Ok(())
    }

    #[test]
    fn test_default_implementations() {
        let _hardshrink = Hardshrink::default();
        let _softshrink = Softshrink::default();
        let _hardtanh = Hardtanh::default();
        let _threshold = Threshold::default();
        let _tanhshrink = Tanhshrink::default();
    }

    #[test]
    fn test_convenience_constructors() {
        let standard_hardtanh = Hardtanh::standard();
        assert_eq!(standard_hardtanh.min_val(), -1.0);
        assert_eq!(standard_hardtanh.max_val(), 1.0);

        let zeroing_threshold = Threshold::zeroing(0.1);
        assert_eq!(zeroing_threshold.threshold(), 0.1);
        assert_eq!(zeroing_threshold.value(), 0.0);
    }
}