Skip to main content

oa/ml/nn/
layer_norm.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_layer_norm.json
3// generator_version=8; schema_sha256=41b906970f56e4adfa6da53610867cc492eb94755106603f4a57fe689f883b8d
4
5use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/layernorm/layerNorm.cpp
10// Adaptation: Preserve existing Rust initialization, parameter versions and autograd; adapt donor structure to ModuleRegistry ownership
11/// Trainable FP32 LayerNorm over the final input dimension.
12pub struct LayerNorm {
13	normalized_shape: usize,
14	epsilon: f32,
15	weight: Parameter,
16	bias: Parameter,
17	registry: ModuleRegistry,
18}
19
20impl LayerNorm {
21	pub fn new(normalized_shape: usize, epsilon: f32) -> Result<Self> {
22		Self::new_on(&Runtime::current()?, normalized_shape, epsilon)
23	}
24
25	/// Construct a LayerNorm with unit weight and zero bias.
26	///
27	/// # Errors
28	///
29	/// Returns an error when `normalized_shape` is zero, `epsilon` is not finite
30	/// and positive, or parameter allocation/upload fails.
31	pub fn new_on(runtime: &Runtime, normalized_shape: usize, epsilon: f32) -> Result<Self> {
32		if normalized_shape == 0 {
33			return Err(Error::invalid_argument(
34				"layer norm normalized shape must be nonzero",
35			));
36		}
37		if !epsilon.is_finite() || epsilon <= 0.0 {
38			return Err(Error::invalid_argument(
39				"layer norm epsilon must be finite and positive",
40			));
41		}
42		let weight =
43			Matrix::new_from_f32_on(runtime, [normalized_shape], &vec![1.0; normalized_shape])?;
44		let bias = Matrix::new_from_f32_on(runtime, [normalized_shape], &vec![0.0; normalized_shape])?;
45		Self::new_from_matrices(weight, bias, epsilon)
46	}
47
48	/// Construct a LayerNorm from exact weight and bias matrices.
49	///
50	/// # Errors
51	///
52	/// Returns an error unless weight and bias are equal, nonempty, same-runtime
53	/// FP32 vectors and `epsilon` is finite and positive.
54	pub fn new_from_matrices(weight: Matrix, bias: Matrix, epsilon: f32) -> Result<Self> {
55		let [normalized_shape] = weight.shape() else {
56			return Err(Error::invalid_argument(
57				"layer norm weight must be rank one",
58			));
59		};
60		if *normalized_shape == 0
61			|| bias.shape() != [*normalized_shape]
62			|| weight.dtype() != DType::F32
63			|| bias.dtype() != DType::F32
64			|| !weight.runtime().same_as(bias.runtime())
65			|| !epsilon.is_finite()
66			|| epsilon <= 0.0
67		{
68			return Err(Error::invalid_argument(
69				"layer norm requires nonempty same-runtime FP32 weight/bias vectors and finite positive epsilon",
70			));
71		}
72		let normalized_shape = *normalized_shape;
73		let weight = Parameter::new("weight", weight)?;
74		let bias = Parameter::new("bias", bias)?;
75		let mut registry = ModuleRegistry::new();
76		registry.register_parameter("weight", weight.clone())?;
77		registry.register_parameter("bias", bias.clone())?;
78		Ok(Self {
79			normalized_shape,
80			epsilon,
81			weight,
82			bias,
83			registry,
84		})
85	}
86
87	/// Normalize each row over the final dimension and apply affine parameters.
88	///
89	/// # Errors
90	///
91	/// Returns an error when the input is empty, is not FP32, its final dimension
92	/// differs from the normalized shape, it belongs to another runtime, or runtime
93	/// recording fails.
94	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
95		let (weight, weight_version, weight_requires_grad) = self.weight.snapshot();
96		let (bias, bias_version, bias_requires_grad) = self.bias.snapshot();
97		let result = matrix::layer_norm(input, &weight, &bias, self.epsilon)?;
98		if weight_requires_grad || bias_requires_grad {
99			autograd::record_layer_norm(
100				input,
101				&result.output,
102				result.normalized,
103				result.inverse_stddev,
104				self.weight.clone(),
105				weight,
106				weight_version,
107				self.bias.clone(),
108				bias_version,
109			)?;
110		}
111		Ok(result.output)
112	}
113
114	fn forward_channel_impl(&self, input: &Matrix, relu: bool) -> Result<Matrix> {
115		let (weight, weight_version, weight_requires_grad) = self.weight.snapshot();
116		let (bias, bias_version, bias_requires_grad) = self.bias.snapshot();
117		let output = matrix::channel_norm_forward(input, &weight, &bias, self.epsilon, relu)?;
118		autograd::record_channel_norm(
119			input,
120			&output,
121			weight_requires_grad.then(|| (self.weight.clone(), weight_version)),
122			weight,
123			bias_requires_grad.then(|| (self.bias.clone(), bias_version)),
124			bias,
125			self.epsilon,
126			relu,
127		)?;
128		Ok(output)
129	}
130
131	/// Normalize channels directly in `[B, C, T]` storage.
132	///
133	/// This uses the same affine parameters as ordinary LayerNorm without the
134	/// transpose pair otherwise needed to place `C` last.
135	///
136	/// # Errors
137	///
138	/// Returns an error unless the input satisfies the channel-normalization
139	/// contract or runtime recording fails.
140	pub fn forward_channel(&self, input: &Matrix) -> Result<Matrix> {
141		self.forward_channel_impl(input, false)
142	}
143
144	/// Normalize channels in `[B, C, T]` storage and fuse ReLU.
145	///
146	/// # Errors
147	///
148	/// Returns an error unless the input satisfies the channel-normalization
149	/// contract or runtime recording fails.
150	pub fn forward_channel_relu(&self, input: &Matrix) -> Result<Matrix> {
151		self.forward_channel_impl(input, true)
152	}
153
154	/// Return the normalized final-dimension width.
155	pub const fn normalized_shape(&self) -> usize {
156		self.normalized_shape
157	}
158
159	/// Return the numerical-stability epsilon.
160	pub const fn epsilon(&self) -> f32 {
161		self.epsilon
162	}
163
164	/// Return the stable trainable weight handle.
165	pub fn weight(&self) -> Parameter {
166		self.weight.clone()
167	}
168
169	/// Return the stable trainable bias handle.
170	pub fn bias(&self) -> Parameter {
171		self.bias.clone()
172	}
173
174	/// Return the parameters in deterministic weight, bias order.
175	pub fn parameters(&self) -> [Parameter; 2] {
176		[self.weight.clone(), self.bias.clone()]
177	}
178}
179
180impl Module for LayerNorm {
181	fn forward(&self, input: &Matrix) -> Result<Matrix> {
182		LayerNorm::forward(self, input)
183	}
184
185	fn registry(&self) -> &ModuleRegistry {
186		&self.registry
187	}
188}