coeus-nn 0.14.0

Neural-network layers and operators for Coeus.
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
use crate::module::{Module, ModuleError};
use coeus_autograd::Var;
use coeus_core::Float;

mod prelu;

pub use prelu::{prelu, PReLU};

/// Functional ELU activation.
#[inline]
pub fn elu<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::elu(input)
}

/// ELU activation module (alpha = 1.0).
#[derive(Clone, Debug, Default)]
pub struct ELU;

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for ELU {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(elu(input)?)
    }
}

/// Functional GELU tanh approximation.
#[inline]
pub fn gelu_tanh<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::gelu_tanh(input)
}

/// GELU tanh approximation module.
#[derive(Clone, Debug, Default)]
pub struct GeLUTanh;

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for GeLUTanh {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(gelu_tanh(input)?)
    }
}

/// Functional Gated Linear Unit along `dim` (`torch.nn.functional.glu`).
///
/// Splits `input` into two equal halves `[a, b]` along `dim` and gates the first
/// by the sigmoid of the second: `a * sigmoid(b)`. Differentiable — composed from
/// tracked `slice`, `sigmoid`, and `mul`, so gradients flow to `input`.
///
/// # Panics
/// If `dim` is out of range or the extent along `dim` is odd.
pub fn glu<T: Float + coeus_cpu::RealScalar, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
    dim: usize,
) -> Result<Var<T, B>, B::Error> {
    let shape = input.tensor.shape();
    let ndim = shape.len();
    assert!(dim < ndim, "glu: dim {dim} out of range for rank {ndim}");
    let axis = shape[dim];
    assert!(
        axis.is_multiple_of(2),
        "glu: dim {dim} must have even extent, got {axis}"
    );
    let half = axis / 2;
    let mut first: Vec<(usize, usize)> = shape.iter().map(|&extent| (0, extent)).collect();
    let mut second = first.clone();
    first[dim] = (0, half);
    second[dim] = (half, axis);
    let a = coeus_autograd::slice(input, &first)?;
    let b = coeus_autograd::slice(input, &second)?;
    coeus_autograd::mul(&a, &coeus_autograd::sigmoid(&b)?)
}

/// Gated Linear Unit module gating along a fixed `dim` (see [`glu`]).
///
/// Parameter-free; the split dimension is captured at construction so `GLU` can
/// participate in a [`Sequential`](crate::Sequential) stack like other activations.
#[derive(Clone, Copy, Debug)]
pub struct GLU {
    dim: usize,
}

impl GLU {
    /// Create a GLU module that gates along `dim`.
    #[inline]
    #[must_use]
    pub fn new(dim: usize) -> Self {
        Self { dim }
    }
}

impl<T: Float + coeus_cpu::RealScalar, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for GLU {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        let shape = input.tensor.shape();
        let Some(&extent) = shape.get(self.dim) else {
            return Err(ModuleError::InvalidAxis {
                module: "GLU",
                axis: self.dim,
                rank: shape.len(),
            });
        };
        if !extent.is_multiple_of(2) {
            return Err(ModuleError::UnevenSplit {
                module: "GLU",
                axis: self.dim,
                extent,
            });
        }
        Ok(glu(input, self.dim)?)
    }
}

/// Functional LeakyReLU activation.
#[inline]
pub fn leaky_relu<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
    negative_slope: f64,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::leaky_relu(input, negative_slope)
}

/// LeakyReLU activation module.
#[derive(Clone, Debug)]
pub struct LeakyReLU {
    /// Slope for negative inputs.
    pub negative_slope: f64,
}

impl LeakyReLU {
    /// Create a LeakyReLU module.
    pub fn new(negative_slope: f64) -> Self {
        Self { negative_slope }
    }
}

impl Default for LeakyReLU {
    fn default() -> Self {
        Self {
            negative_slope: 0.01,
        }
    }
}

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for LeakyReLU {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(leaky_relu(input, self.negative_slope)?)
    }
}

/// Public descriptor for the functional Hardtanh parameter set.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HardtanhOp {
    /// Lower clamp bound.
    pub min_val: f64,
    /// Upper clamp bound.
    pub max_val: f64,
}

impl HardtanhOp {
    /// Construct a Hardtanh descriptor from explicit bounds.
    #[must_use]
    pub const fn from_bounds(min_val: f64, max_val: f64) -> Self {
        Self { min_val, max_val }
    }
}

/// Functional Hardtanh activation.
#[inline]
pub fn hardtanh<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
    min_val: f64,
    max_val: f64,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::hardtanh(input, min_val, max_val)
}

/// Hardtanh activation module (default range [-1, 1], matching PyTorch's
/// `torch.nn.Hardtanh`).
#[derive(Clone, Debug)]
pub struct Hardtanh {
    /// Lower clamp bound.
    pub min_val: f64,
    /// Upper clamp bound.
    pub max_val: f64,
}

impl Hardtanh {
    /// Create a Hardtanh module with custom bounds.
    pub fn new(min_val: f64, max_val: f64) -> Self {
        Self { min_val, max_val }
    }
}

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

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Hardtanh {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(hardtanh(input, self.min_val, self.max_val)?)
    }
}

/// Public descriptor for the functional Hardshrink parameter set.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HardshrinkOp(pub f64);

impl HardshrinkOp {
    /// Construct a Hardshrink descriptor from lambda.
    #[must_use]
    pub const fn from_lambda(lambda: f64) -> Self {
        Self(lambda)
    }
}

/// Functional Hardshrink activation.
#[inline]
pub fn hardshrink<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
    lambda: f64,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::hardshrink(input, lambda)
}

/// Hardshrink activation module (default λ = 0.5, matching PyTorch's
/// `torch.nn.Hardshrink`).
#[derive(Clone, Debug)]
pub struct Hardshrink {
    /// Threshold λ below which the activation is replaced with 0.
    pub lambda: f64,
}

impl Hardshrink {
    /// Create a Hardshrink module with custom λ.
    pub fn new(lambda: f64) -> Self {
        Self { lambda }
    }
}

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

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Hardshrink {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(hardshrink(input, self.lambda)?)
    }
}

/// Public descriptor for the functional Softshrink parameter set.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SoftshrinkOp(pub f64);

impl SoftshrinkOp {
    /// Construct a Softshrink descriptor from lambda.
    #[must_use]
    pub const fn from_lambda(lambda: f64) -> Self {
        Self(lambda)
    }
}

/// Functional Softshrink activation.
#[inline]
pub fn softshrink<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
    lambda: f64,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::softshrink(input, lambda)
}

/// Softshrink activation module (default λ = 0.5).
#[derive(Clone, Debug)]
pub struct Softshrink {
    /// Threshold λ below which the activation maps to 0.
    pub lambda: f64,
}

impl Softshrink {
    /// Create a Softshrink module with custom λ.
    pub fn new(lambda: f64) -> Self {
        Self { lambda }
    }
}

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

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Softshrink {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(softshrink(input, self.lambda)?)
    }
}

/// Public descriptor for the functional Threshold operation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ThresholdNode;

impl ThresholdNode {
    /// Operation name used by the autograd node.
    #[must_use]
    pub const fn op_name() -> &'static str {
        "threshold"
    }
}

/// Functional Threshold activation.
#[inline]
pub fn threshold<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
    thresh: f64,
    value: f64,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::threshold(input, thresh, value)
}

/// Threshold activation module (default threshold=0, value=0).
#[derive(Clone, Debug)]
pub struct Threshold {
    /// Lower-bound threshold.
    pub threshold: f64,
    /// Replacement value below threshold.
    pub value: f64,
}

impl Threshold {
    /// Create a Threshold module with custom `threshold` and `value`.
    pub fn new(threshold: f64, value: f64) -> Self {
        Self { threshold, value }
    }
}

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

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Threshold {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(threshold(input, self.threshold, self.value)?)
    }
}

/// Public descriptor for the functional Celu parameter set.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CeluOp(pub f64);

impl CeluOp {
    /// Construct a Celu descriptor from alpha.
    #[must_use]
    pub const fn from_alpha(alpha: f64) -> Self {
        Self(alpha)
    }
}

/// Functional Celu activation.
#[inline]
pub fn celu<T: Float, B: coeus_ops::BackendOps<T> + Default>(
    input: &Var<T, B>,
    alpha: f64,
) -> Result<Var<T, B>, B::Error> {
    coeus_autograd::celu(input, alpha)
}

/// Celu activation module (default α = 1.0, matching PyTorch).
#[derive(Clone, Debug)]
pub struct Celu {
    /// Continuity-preserving α constant.
    pub alpha: f64,
}

impl Celu {
    /// Create a Celu module with custom α.
    pub fn new(alpha: f64) -> Self {
        Self { alpha }
    }
}

impl Default for Celu {
    fn default() -> Self {
        Self { alpha: 1.0 }
    }
}

impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Celu {
    #[inline]
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    #[inline]
    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        Ok(celu(input, self.alpha)?)
    }
}