aprender-core 0.31.2

Next-generation machine learning library in pure Rust
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
//! Activation function modules.
//!
//! These modules wrap activation functions for use in Sequential containers.
//! For functional versions, see `nn::functional`.
//!
//! # References
//!
//! - Nair, V., & Hinton, G. E. (2010). Rectified linear units improve restricted
//!   Boltzmann machines. ICML.
//! - He, K., et al. (2015). Delving deep into rectifiers. ICCV.

use super::module::Module;
use crate::autograd::Tensor;

/// Rectified Linear Unit activation: ReLU(x) = max(0, x)
///
/// # Shape
///
/// - Input: `(*)` any shape
/// - Output: `(*)` same shape as input
///
/// # Example
///
/// ```ignore
/// use aprender::nn::{Module, ReLU};
/// use aprender::autograd::Tensor;
///
/// let relu = ReLU::new();
/// let x = Tensor::from_slice(&[-1.0, 0.0, 1.0, 2.0]);
/// let y = relu.forward(&x);  // [0.0, 0.0, 1.0, 2.0]
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct ReLU;

impl ReLU {
    /// Create a new `ReLU` activation.
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl Module for ReLU {
    fn forward(&self, input: &Tensor) -> Tensor {
        input.relu()
    }
}

/// Leaky `ReLU` activation: LeakyReLU(x) = `max(negative_slope` * x, x)
///
/// # Arguments
///
/// * `negative_slope` - Controls angle of negative slope (default: 0.01)
#[derive(Debug, Clone, Copy)]
pub struct LeakyReLU {
    negative_slope: f32,
}

impl LeakyReLU {
    /// Create a new `LeakyReLU` with default negative slope (0.01).
    #[must_use]
    pub fn new() -> Self {
        Self {
            negative_slope: 0.01,
        }
    }

    /// Create a new `LeakyReLU` with specified negative slope.
    #[must_use]
    pub fn with_slope(negative_slope: f32) -> Self {
        Self { negative_slope }
    }
}

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

impl Module for LeakyReLU {
    fn forward(&self, input: &Tensor) -> Tensor {
        input.leaky_relu(self.negative_slope)
    }
}

/// Sigmoid activation: σ(x) = 1 / (1 + exp(-x))
///
/// Maps inputs to (0, 1) range.
#[derive(Debug, Clone, Copy, Default)]
pub struct Sigmoid;

impl Sigmoid {
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl Module for Sigmoid {
    fn forward(&self, input: &Tensor) -> Tensor {
        input.sigmoid()
    }
}

/// Tanh activation: tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))
///
/// Maps inputs to (-1, 1) range.
#[derive(Debug, Clone, Copy, Default)]
pub struct Tanh;

impl Tanh {
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl Module for Tanh {
    fn forward(&self, input: &Tensor) -> Tensor {
        input.tanh_()
    }
}

/// Gaussian Error Linear Unit (GELU) activation.
///
/// GELU(x) = x * Φ(x) where Φ is the CDF of standard normal.
/// Approximation: 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x³)))
///
/// # Reference
///
/// - Hendrycks, D., & Gimpel, K. (2016). Gaussian Error Linear Units (GELUs).
#[derive(Debug, Clone, Copy, Default)]
pub struct GELU;

impl GELU {
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl Module for GELU {
    fn forward(&self, input: &Tensor) -> Tensor {
        input.gelu()
    }
}

/// Softmax activation: softmax(x)_i = `exp(x_i)` / `Σ_j` `exp(x_j)`
///
/// Converts logits to probabilities that sum to 1.
///
/// # Arguments
///
/// * `dim` - Dimension along which to compute softmax
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub struct Softmax {
    dim: i32,
}

impl Softmax {
    /// Create a new Softmax along the specified dimension.
    #[must_use]
    pub fn new(dim: i32) -> Self {
        Self { dim }
    }
}

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

impl Module for Softmax {
    fn forward(&self, input: &Tensor) -> Tensor {
        input.softmax()
    }
}

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

    #[test]
    fn test_relu() {
        let relu = ReLU::new();
        let x = Tensor::from_slice(&[-2.0, -1.0, 0.0, 1.0, 2.0]);
        let y = relu.forward(&x);

        assert_eq!(y.data(), &[0.0, 0.0, 0.0, 1.0, 2.0]);
    }

    #[test]
    fn test_leaky_relu() {
        let lrelu = LeakyReLU::with_slope(0.1);
        let x = Tensor::from_slice(&[-2.0, -1.0, 0.0, 1.0, 2.0]);
        let y = lrelu.forward(&x);

        assert_eq!(y.data(), &[-0.2, -0.1, 0.0, 1.0, 2.0]);
    }

    #[test]
    fn test_sigmoid() {
        let sigmoid = Sigmoid::new();
        let x = Tensor::from_slice(&[0.0]);
        let y = sigmoid.forward(&x);

        assert!((y.data()[0] - 0.5).abs() < 1e-5);
    }

    #[test]
    fn test_sigmoid_bounds() {
        let sigmoid = Sigmoid::new();
        let x = Tensor::from_slice(&[-10.0, 0.0, 10.0]);
        let y = sigmoid.forward(&x);

        // Should be in (0, 1)
        for &val in y.data() {
            assert!(val > 0.0 && val < 1.0);
        }
    }

    #[test]
    fn test_tanh() {
        let tanh = Tanh::new();
        let x = Tensor::from_slice(&[0.0]);
        let y = tanh.forward(&x);

        assert!((y.data()[0]).abs() < 1e-5);
    }

    #[test]
    fn test_tanh_bounds() {
        let tanh = Tanh::new();
        let x = Tensor::from_slice(&[-2.0, 0.0, 2.0]);
        let y = tanh.forward(&x);

        // Should be in (-1, 1)
        for &val in y.data() {
            assert!((-1.0..=1.0).contains(&val));
        }

        // More specific bounds for non-extreme values
        assert!(y.data()[0] > -1.0 && y.data()[0] < -0.9); // tanh(-2) ≈ -0.964
        assert!(y.data()[2] > 0.9 && y.data()[2] < 1.0); // tanh(2) ≈ 0.964
    }

    #[test]
    fn test_gelu() {
        let gelu = GELU::new();
        let x = Tensor::from_slice(&[0.0]);
        let y = gelu.forward(&x);

        // GELU(0) = 0
        assert!((y.data()[0]).abs() < 1e-5);
    }

    #[test]
    fn test_gelu_positive() {
        let gelu = GELU::new();
        let x = Tensor::from_slice(&[1.0]);
        let y = gelu.forward(&x);

        // GELU(1) ≈ 0.841
        assert!((y.data()[0] - 0.841).abs() < 0.01);
    }

    #[test]
    fn test_softmax_sums_to_one() {
        let softmax = Softmax::new(-1);
        let x = Tensor::new(&[1.0, 2.0, 3.0, 1.0, 2.0, 3.0], &[2, 3]);
        let y = softmax.forward(&x);

        // Each row should sum to 1
        let (batch, features) = (2, 3);
        for b in 0..batch {
            let sum: f32 = (0..features).map(|j| y.data()[b * features + j]).sum();
            assert!((sum - 1.0).abs() < 1e-5, "Row {b} sums to {sum}");
        }
    }

    #[test]
    fn test_softmax_numerical_stability() {
        let softmax = Softmax::new(-1);
        // Large values that could cause overflow without proper handling
        let x = Tensor::new(&[1000.0, 1001.0, 1002.0], &[1, 3]);
        let y = softmax.forward(&x);

        // Should not have NaN or Inf
        for &val in y.data() {
            assert!(val.is_finite());
            assert!((0.0..=1.0).contains(&val));
        }

        // Should still sum to 1
        let sum: f32 = y.data().iter().sum();
        assert!((sum - 1.0).abs() < 1e-5);
    }

    // =========================================================================
    // Additional coverage tests for Default impls and Debug
    // =========================================================================

    #[test]
    fn test_relu_default() {
        let relu = ReLU::default();
        let x = Tensor::from_slice(&[-1.0, 1.0]);
        let y = relu.forward(&x);
        assert_eq!(y.data(), &[0.0, 1.0]);
    }

    #[test]
    fn test_relu_debug_clone_copy() {
        let relu = ReLU::new();
        let debug_str = format!("{:?}", relu);
        assert!(debug_str.contains("ReLU"));

        let cloned = relu.clone();
        let copied = relu;
        let _ = cloned.forward(&Tensor::from_slice(&[1.0]));
        let _ = copied.forward(&Tensor::from_slice(&[1.0]));
    }

    #[test]
    fn test_leaky_relu_default() {
        let lrelu = LeakyReLU::default();
        let x = Tensor::from_slice(&[-100.0]);
        let y = lrelu.forward(&x);
        // Default slope is 0.01
        assert!((y.data()[0] - (-1.0)).abs() < 0.001);
    }

    #[test]
    fn test_leaky_relu_debug_clone_copy() {
        let lrelu = LeakyReLU::new();
        let debug_str = format!("{:?}", lrelu);
        assert!(debug_str.contains("LeakyReLU"));

        let cloned = lrelu.clone();
        let copied = lrelu;
        let _ = cloned.forward(&Tensor::from_slice(&[1.0]));
        let _ = copied.forward(&Tensor::from_slice(&[1.0]));
    }

    #[test]
    fn test_sigmoid_default() {
        let sigmoid = Sigmoid::default();
        let x = Tensor::from_slice(&[0.0]);
        let y = sigmoid.forward(&x);
        assert!((y.data()[0] - 0.5).abs() < 1e-5);
    }

    #[test]
    fn test_sigmoid_debug_clone_copy() {
        let sigmoid = Sigmoid::new();
        let debug_str = format!("{:?}", sigmoid);
        assert!(debug_str.contains("Sigmoid"));

        let cloned = sigmoid.clone();
        let copied = sigmoid;
        let _ = cloned.forward(&Tensor::from_slice(&[0.0]));
        let _ = copied.forward(&Tensor::from_slice(&[0.0]));
    }

    #[test]
    fn test_tanh_default() {
        let tanh = Tanh::default();
        let x = Tensor::from_slice(&[0.0]);
        let y = tanh.forward(&x);
        assert!((y.data()[0]).abs() < 1e-5);
    }

    #[test]
    fn test_tanh_debug_clone_copy() {
        let tanh = Tanh::new();
        let debug_str = format!("{:?}", tanh);
        assert!(debug_str.contains("Tanh"));

        let cloned = tanh.clone();
        let copied = tanh;
        let _ = cloned.forward(&Tensor::from_slice(&[0.0]));
        let _ = copied.forward(&Tensor::from_slice(&[0.0]));
    }

    #[test]
    fn test_gelu_default() {
        let gelu = GELU::default();
        let x = Tensor::from_slice(&[0.0]);
        let y = gelu.forward(&x);
        assert!((y.data()[0]).abs() < 1e-5);
    }

    #[test]
    fn test_gelu_debug_clone_copy() {
        let gelu = GELU::new();
        let debug_str = format!("{:?}", gelu);
        assert!(debug_str.contains("GELU"));

        let cloned = gelu.clone();
        let copied = gelu;
        let _ = cloned.forward(&Tensor::from_slice(&[1.0]));
        let _ = copied.forward(&Tensor::from_slice(&[1.0]));
    }

    #[test]
    fn test_softmax_default() {
        let softmax = Softmax::default(); // dim = -1
        let x = Tensor::new(&[1.0, 2.0, 3.0], &[1, 3]);
        let y = softmax.forward(&x);
        let sum: f32 = y.data().iter().sum();
        assert!((sum - 1.0).abs() < 1e-5);
    }

    #[test]
    fn test_softmax_debug_clone_copy() {
        let softmax = Softmax::new(-1);
        let debug_str = format!("{:?}", softmax);
        assert!(debug_str.contains("Softmax"));

        let cloned = softmax.clone();
        let copied = softmax;
        let _ = cloned.forward(&Tensor::new(&[1.0, 2.0], &[1, 2]));
        let _ = copied.forward(&Tensor::new(&[1.0, 2.0], &[1, 2]));
    }
}