Skip to main content

oa/ml/nn/
prelu.rs

1//! Parametric activation modules: learned-slope PReLU and alpha-scaled ELU.
2
3use crate::ml::matrix::relu;
4use crate::{Error, Matrix, Result, Runtime, matrix};
5
6use super::super::{Module, ModuleRegistry, Parameter, autograd};
7
8/// Parametric ReLU: `max(0, x) - slope * relu(-x)` elementwise.
9///
10/// `num_slope_parameters` is `1` for a shared slope or `channels` for the
11/// per-channel `nn.PReLU` form; channelwise slopes broadcast over the channel
12/// (second) axis of rank >= 2 inputs. The slope is a trainable `Parameter`
13/// registered as `slope`, initialized to `0.25` matching the PyTorch default.
14pub struct Prelu {
15	num_slope_parameters: usize,
16	slope: Parameter,
17	registry: ModuleRegistry,
18}
19
20impl Prelu {
21	/// Construct with `num_slope_parameters` slopes initialized to `0.25`.
22	///
23	/// # Errors
24	///
25	/// Returns an error when `num_slope_parameters` is zero or allocation fails.
26	pub fn new_on(runtime: &Runtime, num_slope_parameters: usize) -> Result<Self> {
27		if num_slope_parameters == 0 {
28			return Err(Error::invalid_argument(
29				"prelu requires at least one slope parameter",
30			));
31		}
32		let data = Matrix::new_from_f32_on(
33			runtime,
34			[num_slope_parameters],
35			&vec![0.25_f32; num_slope_parameters],
36		)?;
37		let slope = Parameter::new("slope", data)?;
38		let mut registry = ModuleRegistry::new();
39		registry.register_parameter("slope", slope.clone())?;
40		Ok(Self {
41			num_slope_parameters,
42			slope,
43			registry,
44		})
45	}
46
47	/// Construct on the current runtime.
48	///
49	/// # Errors
50	///
51	/// Returns an error under the same contract as [`Self::new_on`].
52	pub fn new(num_slope_parameters: usize) -> Result<Self> {
53		Self::new_on(&Runtime::current()?, num_slope_parameters)
54	}
55
56	/// Return the learned slope parameter.
57	pub fn slope(&self) -> Parameter {
58		self.slope.clone()
59	}
60
61	/// Apply `max(0, x) - slope * relu(-x)`.
62	///
63	/// # Errors
64	///
65	/// Returns an error when a channelwise slope count does not match the
66	/// channel axis, or the composed elementwise ops fail.
67	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
68		if self.num_slope_parameters > 1 {
69			let channels = input.shape().get(1).copied().unwrap_or(0);
70			if channels != self.num_slope_parameters {
71				return Err(Error::invalid_argument(format!(
72					"prelu has {} slopes for channel axis {}; found {:?}",
73					self.num_slope_parameters,
74					channels,
75					input.shape(),
76				)));
77			}
78		}
79		let slope_shape = if self.num_slope_parameters == 1 {
80			vec![1_usize]
81		} else {
82			let mut shape = vec![1_usize; input.shape().len()];
83			shape[1] = self.num_slope_parameters;
84			shape
85		};
86		autograd::record_parameter_leaf(&self.slope)?;
87		let slope = self.slope.data().reshape(slope_shape)?;
88		let negative = relu(&matrix::neg(input)?)?;
89		matrix::sub(&relu(input)?, &matrix::mul(&slope, &negative)?)
90	}
91}
92
93impl Module for Prelu {
94	fn forward(&self, input: &Matrix) -> Result<Matrix> {
95		Prelu::forward(self, input)
96	}
97
98	fn registry(&self) -> &ModuleRegistry {
99		&self.registry
100	}
101}
102
103/// Exponential linear unit: `x` for `x > 0`, `alpha * (e^x - 1)` otherwise.
104///
105/// Stateless composed contract: `relu(x) + alpha * (exp(-relu(-x)) - 1)`,
106/// so autograd flows through the elementwise adjoints.
107pub struct Elu {
108	alpha: f32,
109	registry: ModuleRegistry,
110}
111
112impl Elu {
113	/// Construct with the `alpha` negative-range scale (torch default `1.0`).
114	///
115	/// # Errors
116	///
117	/// Returns an error when `alpha` is not finite.
118	pub fn new(alpha: f32) -> Result<Self> {
119		if !alpha.is_finite() {
120			return Err(Error::invalid_argument("elu alpha must be finite"));
121		}
122		Ok(Self {
123			alpha,
124			registry: ModuleRegistry::new(),
125		})
126	}
127
128	/// Return the configured `alpha`.
129	pub const fn alpha(&self) -> f32 {
130		self.alpha
131	}
132
133	/// Apply the composed ELU formula.
134	///
135	/// # Errors
136	///
137	/// Returns an error when the composed elementwise ops fail.
138	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
139		let negative = relu(&matrix::neg(input)?)?;
140		let branch = matrix::scale(
141			&matrix::sub_scalar(&matrix::exp(&matrix::neg(&negative)?)?, 1.0)?,
142			self.alpha,
143		)?;
144		matrix::add(&relu(input)?, &branch)
145	}
146}
147
148impl Module for Elu {
149	fn forward(&self, input: &Matrix) -> Result<Matrix> {
150		Elu::forward(self, input)
151	}
152
153	fn registry(&self) -> &ModuleRegistry {
154		&self.registry
155	}
156}