burn-tensor 0.22.0-pre.1

Tensor library with user-friendly APIs and automatic differentiation support
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
use burn_backend::ops::ActivationOps;
use burn_dispatch::Dispatch;

use crate::check::TensorCheck;
use crate::check::unwrap_dim_index;
use crate::ops::BridgeTensor;
use crate::{AsIndex, Tensor, check, s};

/// Applies the rectified linear unit function element-wise
/// as described in the paper [Deep Learning using Rectified Linear Units (ReLU)](https://arxiv.org/pdf/1803.08375).
///
#[cfg_attr(doc, doc = "$$\\text{ReLU}\\(x\\) = \\(x\\)^+ = \\max\\(0, x\\)$$")]
#[cfg_attr(not(doc), doc = "`ReLU(x) = max(0, x)`")]
pub fn relu<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.relu()
}

/// Applies the HardTanh function element-wise, clamping each element to the
/// range `[min_val, max_val]` (a cheap, piecewise-linear approximation of tanh).
///
#[cfg_attr(not(doc), doc = "`HardTanh(x) = max(min_val, min(max_val, x))`")]
pub fn hardtanh<const D: usize>(tensor: Tensor<D>, min_val: f64, max_val: f64) -> Tensor<D> {
    tensor.clamp(min_val, max_val)
}

/// Applies the Tanhshrink function element-wise, `x - tanh(x)`.
///
#[cfg_attr(not(doc), doc = "`Tanhshrink(x) = x - tanh(x)`")]
pub fn tanhshrink<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.clone().sub(tensor.tanh())
}

/// Applies the ReLU6 function element-wise, the rectified linear unit clamped to
/// the range `[0, 6]` (as used in [MobileNetV2](https://arxiv.org/abs/1801.04381)).
///
#[cfg_attr(doc, doc = "$$\\text{ReLU6}\\(x\\) = \\min\\(\\max\\(0, x\\), 6\\)$$")]
#[cfg_attr(not(doc), doc = "`ReLU6(x) = min(max(0, x), 6)`")]
pub fn relu6<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.clamp(0.0, 6.0)
}

/// Applies the leaky rectified linear unit function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{LeakyReLU}\(x\) = \max\(0,x\) + \text{negative\\_slope} \cdot \min\(0, x\)
$$

or

$$
\text{LeakyReLU}(x) =
 \begin{cases}
     x & \text{if } x \geq 0 \newline
     \text{negative\\_slope} \cdot x & \text{otherwise}
 \end{cases}
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`f(x) =`\n- `x for x >= 0`\n- `negative_slope * x if x < 0`"
)]
pub fn leaky_relu<const D: usize>(tensor: Tensor<D>, negative_slope: f64) -> Tensor<D> {
    Tensor::new(leaky_relu_impl(tensor.primitive, negative_slope))
}

/// Applies the Gaussian Error Linear Units function as described in the paper
/// [Gaussian Error Linear Units (GELUs)](https://arxiv.org/pdf/1606.08415v3.pdf).
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{GELU}(x)
= x \cdot \Phi(x)
= x \cdot \frac{1}{2}\left(1 + \text{erf}\left(\frac{x}{\sqrt{2}}\right)\right)
$$

where $\Phi(x)$ is the cumulative distribution function for the Gaussian distribution.
"#
)]
#[cfg_attr(
    not(doc),
    doc = r#"
`GELU(x) = x * Φ(x) = x * 1/2 * (1 + erf(x / sqrt(2)))`

where `Φ(x)` is the cumulative distribution function for the Gaussian distribution.
"#
)]
pub fn gelu<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    Tensor::new(gelu_impl(tensor.primitive))
}

/// Applies the tanh-based approximate GELU function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{GELU\_approx}(x)
= \frac{x}{2}\left(1 + \tanh\left(\sqrt{\frac{2}{\pi}}\left(x + 0.044715\,x^3\right)\right)\right)
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`GELU_approx(x) = 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))`"
)]
pub fn gelu_approximate<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    /// sqrt(2/Ï€) precomputed as FRAC_2_SQRT_PI * FRAC_1_SQRT_2
    const SQRT_2_OVER_PI: f64 =
        core::f64::consts::FRAC_2_SQRT_PI * core::f64::consts::FRAC_1_SQRT_2;

    let x = tensor;
    let inner = x.clone() + x.clone().powf_scalar(3.0) * 0.044715;
    let inner = inner * SQRT_2_OVER_PI;
    (x.clone() * (inner.tanh() + 1)) * 0.5
}

/// Applies Parametric ReLu activation function as described in the paper
/// [Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](https://arxiv.org/pdf/1502.01852).
///
/// - The tensor is assumed to be of shape `[batch_size, channels, ...]`.
/// - `alpha` is assumed to be of shape `[channels]` or `[1]`.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{PReLU}\(x\) = \max\(0,x\) + \alpha \cdot \min\(0, x\)
$$

or

$$
\text{PReLU}(x) =
 \begin{cases}
     x & \text{if } x \geq 0 \newline
     \alpha x & \text{otherwise}
 \end{cases}
$$
"#
)]
#[cfg_attr(not(doc), doc = "`PReLu(x) = max(0,x) + alpha * min(0,x)`")]
pub fn prelu<const D: usize>(tensor: Tensor<D>, alpha: Tensor<1>) -> Tensor<D> {
    check!(TensorCheck::check_prelu_shape::<D>(
        &tensor.shape(),
        &alpha.shape()
    ));

    let weight = if alpha.dims()[0] == 1 {
        // if there is only 1 weight, then reshape it to (1,1,1... D times) so that the rank is D
        alpha.reshape([1; D])
    } else {
        // D>=2 because the case where D==1 and num_weights >1 is handled by check function
        // there is more than 1 weight and rank is more than 2
        let num_weights = alpha.dims()[0];
        let mut s = [1; D];
        s[1] = num_weights;
        // reshape the weights to (1, channels,1 ...)
        alpha.reshape(s)
    };

    Tensor::new(prelu_impl(tensor.primitive, weight.primitive))
}

/// Applies the softmax function on the input tensor along the given dimension.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{softmax}\(x_i\) = \frac{\exp\(x_i\)}{\sum_j \exp\(x_j\)}
$$
"#
)]
#[cfg_attr(not(doc), doc = "`softmax(x_i) = exp(x_i) / sum_j(exp(x_j))`")]
///
/// # Arguments
/// - `dim`: the dimension along which Softmax will be computed.
///   Negative dimensions are supported and count from the end.
///
/// # Panics
/// - If `dim` is outside [-D, D)
pub fn softmax<const D: usize>(tensor: Tensor<D>, dim: impl AsIndex) -> Tensor<D> {
    let dim = unwrap_dim_index(dim.try_dim_index(D), "Softmax");
    Tensor::new(softmax_impl(tensor.primitive, dim))
}

/// Applies the softmin function on the input tensor along the given dimension.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{softmin}\(x_i\) = \frac{\exp\(-x_i\)}{\sum_j \exp\(-x_j\)}
$$
"#
)]
#[cfg_attr(not(doc), doc = "`softmin(x_i) = exp(-x_i) / sum_j(exp(-x_j)`")]
///
/// # Arguments
/// - `dim`: the dimension along which Softmin will be computed.
///   Negative dimensions are supported and count from the end.
///
/// # Panics
/// - If `dim` is outside [-D, D)
pub fn softmin<const D: usize>(tensor: Tensor<D>, dim: impl AsIndex) -> Tensor<D> {
    let dim = unwrap_dim_index(dim.try_dim_index(D), "Softmin");
    Tensor::new(softmin_impl(tensor.primitive, dim))
}

/// Applies the SoftPlus function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{softplus}\(x\) = \frac{1}{\beta}\log\(1 + \exp\(\beta x\)\)
$$
"#
)]
#[cfg_attr(not(doc), doc = "`softplus(x_i) = log(1 + exp(beta * x_i)) / beta`")]
///
/// The SoftPlus function is a smooth approximation of the ReLU function.
pub fn softplus<const D: usize>(tensor: Tensor<D>, beta: f64) -> Tensor<D> {
    let tensor = (tensor.mul_scalar(beta).exp() + 1).log();
    tensor.div_scalar(beta)
}

/// Applies the "quiet softmax" function on the input tensor along the given dimension.
///
/// Also referred to as [`softmax1`](https://www.evanmiller.org/attention-is-off-by-one.html).
///
/// This function is similar to the softmax function, but it allows for "no selection" when
/// all the outputs are close to zero.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{quiet\\_softmax}\(x_i\) = \frac{\exp\(x_i\)}{1 + \sum_j \exp\(x_j\)}
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`quiet_softmax(x_i) = exp(x_i) / [ 1 + sum_j(exp(x_j)) ]`"
)]
///
/// # Arguments
/// - `dim`: the dimension along which Quiet Softmax will be computed.
///   Negative dimensions are supported and count from the end.
///
/// # Panics
/// - If `dim` is outside [-D, D)
pub fn quiet_softmax<const D: usize>(tensor: Tensor<D>, dim: impl AsIndex) -> Tensor<D> {
    let dim = unwrap_dim_index(dim.try_dim_index(D), "Quiet Softmax");
    let max_vals = tensor.clone().detach().max_dim(dim);
    let exp_x = (tensor - max_vals.clone()).exp();
    let sum_exp = exp_x.clone().sum_dim(dim);

    exp_x.div(sum_exp + max_vals.neg().exp())
}

/// Applies the log softmax function on the input tensor along the given dimension.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{log\\_softmax}\(x_i\)
= \log\left(\text{softmax}\(x_i\)\right)
= \log\left(\frac{\exp\(x_i\)}{\sum_j \exp\(x_j\)}\right)
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`log_softmax(x_i) = log(softmax(x_i)) = log(exp(x_i) / sum_j(exp(x_j)))`"
)]
///
/// # Arguments
/// - `dim`: the dimension along which Log Softmax will be computed.
///   Negative dimensions are supported and count from the end.
///
/// # Panics
/// - If `dim` is outside [-D, D)
pub fn log_softmax<const D: usize>(tensor: Tensor<D>, dim: impl AsIndex) -> Tensor<D> {
    let dim = unwrap_dim_index(dim.try_dim_index(D), "Log Softmax");
    Tensor::new(log_softmax_impl(tensor.primitive, dim))
}

/// Applies the sigmoid function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{sigmoid}\(x\)
= \sigma(x)
= \frac{1}{1 + \exp(-x)}
$$
"#
)]
#[cfg_attr(not(doc), doc = "`sigmoid(x) = 1 / (1 + exp(-x))`")]
pub fn sigmoid<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    Tensor::new(sigmoid_impl(tensor.primitive))
}

/// Applies the hard sigmoid function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{hard\\_sigmoid}\(x\) = \max(0, \min(1, \alpha \cdot x + \beta))
$$
"#
)]
#[cfg_attr(not(doc), doc = "`hard_sigmoid(x) = max(0, min(1, alpha * x + beta))`")]
pub fn hard_sigmoid<const D: usize>(tensor: Tensor<D>, alpha: f64, beta: f64) -> Tensor<D> {
    Tensor::new(hard_sigmoid_impl(tensor.primitive, alpha, beta))
}

/// Applies the log sigmoid function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{log\\_sigmoid}\(x\) = \log\left(\frac{1}{1 + \exp(-x)}\right)
$$
"#
)]
#[cfg_attr(not(doc), doc = "`log_sigmoid(x) = log(1 / (1 + exp(-x)))`")]
pub fn log_sigmoid<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    Tensor::new(log_sigmoid_impl(tensor.primitive))
}

/// Applies the SiLU function (also known as the swish function) element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{SiLU}\(x\) = x \cdot \sigma(x) = \frac{x}{1 + \exp(-x)}
$$
"#
)]
#[cfg_attr(not(doc), doc = "`SiLU(x) = x * sigmoid(x) = x / (1 + exp(-x))`")]
pub fn silu<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.clone().mul(sigmoid(tensor))
}

/// Applies the hard swish function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{hard\_swish}\(x\) = x \cdot \text{hard\_sigmoid}(x) = x \cdot \max(0, \min(1, \frac{x}{6} + 0.5))
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`hard_swish(x) = x * hard_sigmoid(x) = x * max(0, min(1, x/6 + 0.5))`"
)]
pub fn hard_swish<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.clone().mul(hard_sigmoid(tensor, 1.0 / 6.0, 0.5))
}

/// Applies the Mish function as described in the paper in
/// [Mish: A Self Regularized Non-Monotonic Neural Activation Function](https://arxiv.org/abs/1908.08681).
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{Mish}\(x\)
= x \cdot \tanh(\text{Softplus}(x))
= \tanh\left(\log\(1 + \exp\(x\)\)\right)
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`mish(x) = x * tanh(softplus(x)) = tanh(log(1 + exp(x)))`"
)]
pub fn mish<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.clone().mul(softplus(tensor, 1.0).tanh())
}

/// Applies the tanh function element-wise.
pub fn tanh<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.tanh()
}

/// Applies the Exponential Linear Unit function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{ELU}\(x\) =
 \begin{cases}
     x & \text{if } x > 0 \newline
     \alpha \cdot (\exp(x) - 1) & \text{if } x \leq 0
 \end{cases}
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`f(x) =`\n- `x for x > 0`\n- `alpha * (exp(x) - 1) for x <= 0`"
)]
pub fn elu<const D: usize>(tensor: Tensor<D>, alpha: f64) -> Tensor<D> {
    let mask = tensor.clone().lower_equal_scalar(0);
    let scaled = tensor.clone().exp().sub_scalar(1).mul_scalar(alpha);
    tensor.mask_where(mask, scaled)
}

/// Applies the Continuously Differentiable Exponential Linear Unit function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{CELU}(x) =
 \begin{cases}
     x & \text{if } x \geq 0 \newline
     \alpha \cdot \left(\exp\left(\frac{x}{\alpha}\right) - 1\right) & \text{otherwise}
 \end{cases}
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`celu(x) = max(0, x) + min(0, alpha * (exp(x / alpha) - 1))`"
)]
///
/// See also [CELU](https://pytorch.org/docs/stable/generated/torch.nn.CELU.html)
///
/// # Arguments
/// - `alpha`: scaling parameter for the negative part.
pub fn celu<const D: usize>(tensor: Tensor<D>, alpha: f64) -> Tensor<D> {
    let mask = tensor.clone().lower_equal_scalar(0);
    let scaled = tensor
        .clone()
        .div_scalar(alpha)
        .exp()
        .sub_scalar(1)
        .mul_scalar(alpha);
    tensor.mask_where(mask, scaled)
}

/// Applies the Scaled Exponential Linear Unit function element-wise
/// as described in the paper [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515).
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{SELU}\(x\) = \gamma \cdot
 \begin{cases}
     x & \text{if } x > 0 \newline
     \alpha \cdot (\exp(x) - 1) & \text{if } x \leq 0
 \end{cases}
$$

where $\alpha \approx 1.6733$ and $\gamma \approx 1.0507$.
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`selu(x) = gamma * x if x > 0, gamma * alpha * (exp(x) - 1) if x <= 0`"
)]
pub fn selu<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    // Constants from the SELU paper / ONNX spec
    const ALPHA: f64 = 1.6732632423543772848170429916717_f64;
    const GAMMA: f64 = 1.0507009873554804934193349852946_f64;

    let mask = tensor.clone().greater_equal_scalar(0.0);
    let positive = tensor.clone().mul_scalar(GAMMA);
    let negative = tensor.exp().sub_scalar(1.0).mul_scalar(ALPHA * GAMMA);

    negative.mask_where(mask, positive)
}

/// Applies the thresholded rectified linear unit function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{ThresholdedReLU}(x) =
 \begin{cases}
     x & \text{if } x > \alpha \newline
     0 & \text{otherwise}
 \end{cases}
$$
"#
)]
#[cfg_attr(not(doc), doc = "`f(x) =`\n- `x if x > alpha`\n- `0 otherwise`")]
///
/// # Arguments
/// - `alpha`: threshold value (default in ONNX is 1.0).
pub fn thresholded_relu<const D: usize>(tensor: Tensor<D>, alpha: f64) -> Tensor<D> {
    let mask = tensor.clone().lower_equal_scalar(alpha);
    tensor.mask_fill(mask, 0)
}

/// Applies the Threshold function element-wise, generalising `thresholded_relu`
/// (which fixes `value = 0`): returns `x` where `x > threshold`, and `value`
/// otherwise.
///
#[cfg_attr(
    not(doc),
    doc = "`f(x) =`\n- `x if x > threshold`\n- `value otherwise`"
)]
///
/// # Arguments
/// - `threshold`: the value to threshold at.
/// - `value`: the value to replace with where `x <= threshold`.
pub fn threshold<const D: usize>(tensor: Tensor<D>, threshold: f64, value: f64) -> Tensor<D> {
    let mask = tensor.clone().lower_equal_scalar(threshold);
    tensor.mask_fill(mask, value)
}

/// Applies the gated linear unit function.
///
/// GLU(a,b)=a⊗σ(b) where `a` is the first half of the input matrices and `b` is the second half.
///
/// **Note**:
/// * The size of the input tensor along `dim` must be divisible by 2.
/// * Negative dimensions are supported and count from the end.
///
/// ### Arguments
/// * `tensor` - The input tensor.
/// * `dim` - The dimension on which to split the input.
///
/// ### Returns
/// * A tensor with the same shape as the input, except the size along `dim` is halved.
pub fn glu<const D: usize>(tensor: Tensor<D>, dim: impl AsIndex) -> Tensor<D> {
    let dim = unwrap_dim_index(dim.try_dim_index(D), "GLU");
    assert!(
        tensor.dims()[dim].is_multiple_of(2),
        "Input tensor along dimension {dim} must have an even size. N is divisible by 2."
    );
    let new_len = tensor.dims()[dim] / 2;

    let a = tensor.clone().slice_dim(dim, s![0..new_len]);
    let b = tensor.slice_dim(dim, s![new_len..new_len * 2]);

    a.mul(sigmoid(b))
}

/// Applies the Softsign function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{softsign}(x) = \frac{x}{1 + |x|}
$$
"#
)]
#[cfg_attr(not(doc), doc = "`softsign(x_i) = x_i / (1 + |x_i|)`")]
pub fn softsign<const D: usize>(tensor: Tensor<D>) -> Tensor<D> {
    tensor.clone().div(tensor.abs() + 1)
}

/// Applies the HardShrink function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{hard\_shrink}(x) =
 \begin{cases}
     x & \text{if } x > \lambda \newline
     x & \text{if } x < -\lambda \newline
     0 & \text{otherwise}
 \end{cases}
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`hard_shrink(x) = x if x > lambda, x if x < -lambda, 0 otherwise`"
)]
/// # Arguments
/// - `lambda`: the lambda value for the Hard Shrink formulation. Default is 0.5.
pub fn hard_shrink<const D: usize>(tensor: Tensor<D>, lambda: f64) -> Tensor<D> {
    let mask = tensor.clone().abs().lower_equal_scalar(lambda);
    tensor.mask_fill(mask, 0)
}

/// Applies the SoftShrink function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{soft\_shrink}(x) =
 \begin{cases}
     x - \lambda & \text{if } x > \lambda \newline
     x + \lambda & \text{if } x < -\lambda \newline
     0 & \text{otherwise}
 \end{cases}
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`soft_shrink(x) = x - lambda if x > lambda, x + lambda if x < -lambda, 0 otherwise`"
)]
/// # Arguments
/// - `lambda`: the lambda value for the Soft Shrink formulation. Default is 0.5.
pub fn soft_shrink<const D: usize>(tensor: Tensor<D>, lambda: f64) -> Tensor<D> {
    shrink(tensor, lambda, lambda)
}

/// Applies the Shrink function element-wise.
///
#[cfg_attr(
    doc,
    doc = r#"
$$
\text{shrink}(x) =
 \begin{cases}
     x - \text{bias} & \text{if } x > \lambda \newline
     x + \text{bias} & \text{if } x < -\lambda \newline
     0 & \text{otherwise}
 \end{cases}
$$
"#
)]
#[cfg_attr(
    not(doc),
    doc = "`shrink(x) = x - bias if x > lambda, x + bias if x < -lambda, 0 otherwise`"
)]
/// # Arguments
/// - `lambda`: the lambda value for the Shrink formulation.
/// - `bias`: the bias value for the Shrink formulation.
pub fn shrink<const D: usize>(tensor: Tensor<D>, lambda: f64, bias: f64) -> Tensor<D> {
    let abs_tensor = tensor.clone().abs();
    let sign = tensor.clone().sign();
    let shrunk = tensor.sub(sign.mul_scalar(bias));
    let mask = abs_tensor.lower_equal_scalar(lambda);
    shrunk.mask_fill(mask, 0)
}

// =========================================================================
// Non-generic implementation helpers (outlined from the generic API).
// See the crate-level docs for the rationale behind this pattern.
// =========================================================================

fn leaky_relu_impl(p: BridgeTensor, negative_slope: f64) -> BridgeTensor {
    BridgeTensor::float(Dispatch::leaky_relu(p.into_float(), negative_slope.into()))
}

fn gelu_impl(p: BridgeTensor) -> BridgeTensor {
    BridgeTensor::float(Dispatch::gelu(p.into_float()))
}

fn prelu_impl(p: BridgeTensor, weight: BridgeTensor) -> BridgeTensor {
    BridgeTensor::float(Dispatch::prelu(p.into_float(), weight.into_float()))
}

fn softmax_impl(p: BridgeTensor, dim: usize) -> BridgeTensor {
    BridgeTensor::float(Dispatch::softmax(p.into_float(), dim))
}

fn softmin_impl(p: BridgeTensor, dim: usize) -> BridgeTensor {
    BridgeTensor::float(Dispatch::softmin(p.into_float(), dim))
}

fn log_softmax_impl(p: BridgeTensor, dim: usize) -> BridgeTensor {
    BridgeTensor::float(Dispatch::log_softmax(p.into_float(), dim))
}

fn sigmoid_impl(p: BridgeTensor) -> BridgeTensor {
    BridgeTensor::float(Dispatch::sigmoid(p.into_float()))
}

fn hard_sigmoid_impl(p: BridgeTensor, alpha: f64, beta: f64) -> BridgeTensor {
    BridgeTensor::float(Dispatch::hard_sigmoid(
        p.into_float(),
        alpha.into(),
        beta.into(),
    ))
}

fn log_sigmoid_impl(p: BridgeTensor) -> BridgeTensor {
    BridgeTensor::float(Dispatch::log_sigmoid(p.into_float()))
}