Skip to main content

oa/ml/nn/
glu.rs

1//! Gated linear unit (`nn.GLU`): split the last configured axis in half and
2//! emit `a * sigmoid(b)`.
3
4use crate::{Error, Matrix, Result, matrix};
5
6use super::super::{Module, ModuleRegistry, matrix as ml_matrix};
7
8/// Gated linear unit over one axis (donor default `dim = -1`).
9pub struct Glu {
10	dim: i32,
11	registry: ModuleRegistry,
12}
13
14impl Glu {
15	/// Construct a GLU over the last axis.
16	pub const fn new() -> Self {
17		Self::new_with_dim(-1)
18	}
19
20	/// Construct a GLU over `dim` (negative values index from the end).
21	pub const fn new_with_dim(dim: i32) -> Self {
22		Self {
23			dim,
24			registry: ModuleRegistry::new(),
25		}
26	}
27
28	/// Return the configured split axis.
29	pub const fn dim(&self) -> i32 {
30		self.dim
31	}
32
33	/// Emit `a * sigmoid(b)` for the two halves of `dim`.
34	///
35	/// # Errors
36	///
37	/// Returns an error when the axis is out of range, its extent is odd, or
38	/// the composed dispatch fails.
39	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
40		let rank = input.shape().len();
41		let dim = if self.dim < 0 {
42			self.dim + rank as i32
43		} else {
44			self.dim
45		};
46		if dim < 0 || dim as usize >= rank {
47			return Err(Error::invalid_argument(format!(
48				"Glu dim {} is outside rank {rank}",
49				self.dim
50			)));
51		}
52		let extent = input.shape()[dim as usize];
53		if !extent.is_multiple_of(2) {
54			return Err(Error::invalid_argument(format!(
55				"Glu requires an even extent on the split axis; found {extent}"
56			)));
57		}
58		let half = extent as i64 / 2;
59		let gate = matrix::slice(input, dim, 0, half)?;
60		let value = matrix::slice(input, dim, half, extent as i64)?;
61		matrix::mul(&gate, &ml_matrix::sigmoid(&value)?)
62	}
63}
64
65impl Default for Glu {
66	fn default() -> Self {
67		Self::new()
68	}
69}
70
71impl Module for Glu {
72	fn forward(&self, input: &Matrix) -> Result<Matrix> {
73		Glu::forward(self, input)
74	}
75
76	fn registry(&self) -> &ModuleRegistry {
77		&self.registry
78	}
79}