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
use burn_tensor::activation::hard_sigmoid;

use crate as burn;
use crate::config::Config;
use crate::module::Module;
use crate::module::{Content, DisplaySettings, ModuleDisplay};
use crate::tensor::backend::Backend;
use crate::tensor::Tensor;

/// Hard Sigmoid layer.
///
/// Should be created with [HardSigmoidConfig](HardSigmoidConfig).
#[derive(Module, Clone, Debug)]
#[module(custom_display)]
pub struct HardSigmoid {
    /// The alpha value.
    pub alpha: f64,
    /// The beta value.
    pub beta: f64,
}
/// Configuration to create a [Hard Sigmoid](HardSigmoid) layer using the [init function](HardSigmoidConfig::init).
#[derive(Config, Debug)]
pub struct HardSigmoidConfig {
    /// The alpha value. Default is 0.2
    #[config(default = "0.2")]
    pub alpha: f64,
    /// The beta value. Default is 0.5
    #[config(default = "0.5")]
    pub beta: f64,
}
impl HardSigmoidConfig {
    /// Initialize a new [Hard Sigmoid](HardSigmoid) Layer
    pub fn init(&self) -> HardSigmoid {
        HardSigmoid {
            alpha: self.alpha,
            beta: self.beta,
        }
    }
}

impl ModuleDisplay for HardSigmoid {
    fn custom_settings(&self) -> Option<DisplaySettings> {
        DisplaySettings::new()
            .with_new_line_after_attribute(false)
            .optional()
    }

    fn custom_content(&self, content: Content) -> Option<Content> {
        content
            .add("alpha", &self.alpha)
            .add("beta", &self.beta)
            .optional()
    }
}

impl HardSigmoid {
    /// Forward pass for the Hard Sigmoid layer.
    ///
    /// See [hard_sigmoid](crate::tensor::activation::hard_sigmoid) for more information.
    ///
    /// # Shapes
    /// - input: `[..., any]`
    /// - output: `[..., any]`
    pub fn forward<B: Backend, const D: usize>(&self, input: Tensor<B, D>) -> Tensor<B, D> {
        hard_sigmoid(input, self.alpha, self.beta)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tensor::TensorData;
    use crate::TestBackend;

    #[test]
    fn test_hard_sigmoid_forward() {
        let device = <TestBackend as Backend>::Device::default();
        let model: HardSigmoid = HardSigmoidConfig::new().init();
        let input =
            Tensor::<TestBackend, 2>::from_data(TensorData::from([[0.4410, -0.2507]]), &device);
        let out = model.forward(input);
        let expected = TensorData::from([[0.5882, 0.44986]]);
        out.to_data().assert_approx_eq(&expected, 4);
    }

    #[test]
    fn display() {
        let config = HardSigmoidConfig::new().init();
        assert_eq!(
            alloc::format!("{}", config),
            "HardSigmoid {alpha: 0.2, beta: 0.5}"
        );
    }
}