Skip to main content

oa/ml/nn/
rms_norm.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_rms_norm.json
3// generator_version=8; schema_sha256=8861e2801d4c9ad7411def70c9c5e243059c5e9b60217edb2287fb84ff5c604c
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/rmsnorm/rmsNorm.cpp
10// Adaptation: Preserve existing Rust initialization, parameter versions and autograd; adapt donor structure to ModuleRegistry ownership
11/// Trainable FP32 RMSNorm over the final input dimension.
12pub struct RmsNorm {
13	dimension: usize,
14	epsilon: f32,
15	weight: Parameter,
16	registry: ModuleRegistry,
17}
18
19impl RmsNorm {
20	pub fn new(dimension: usize, epsilon: f32) -> Result<Self> {
21		Self::new_on(&Runtime::current()?, dimension, epsilon)
22	}
23
24	/// Construct RMSNorm with unit weight.
25	///
26	/// # Errors
27	///
28	/// Returns an error when `dimension` is zero, `epsilon` is not finite and
29	/// positive, or parameter allocation/upload fails.
30	pub fn new_on(runtime: &Runtime, dimension: usize, epsilon: f32) -> Result<Self> {
31		if dimension == 0 {
32			return Err(Error::invalid_argument("RMSNorm dimension must be nonzero"));
33		}
34		let weight = Matrix::new_from_f32_on(runtime, [dimension], &vec![1.0; dimension])?;
35		Self::new_from_matrix(weight, epsilon)
36	}
37
38	/// Construct RMSNorm from an exact weight Matrix.
39	///
40	/// # Errors
41	///
42	/// Returns an error unless weight is a nonempty F32 vector and `epsilon` is
43	/// finite and positive.
44	pub fn new_from_matrix(weight: Matrix, epsilon: f32) -> Result<Self> {
45		let [dimension] = weight.shape() else {
46			return Err(Error::invalid_argument("RMSNorm weight must be rank one"));
47		};
48		if *dimension == 0 || weight.dtype() != DType::F32 || !epsilon.is_finite() || epsilon <= 0.0 {
49			return Err(Error::invalid_argument(
50				"RMSNorm requires a nonempty F32 weight vector and finite positive epsilon",
51			));
52		}
53		let dimension = *dimension;
54		let weight = Parameter::new("weight", weight)?;
55		let mut registry = ModuleRegistry::new();
56		registry.register_parameter("weight", weight.clone())?;
57		Ok(Self {
58			dimension,
59			epsilon,
60			weight,
61			registry,
62		})
63	}
64
65	/// Normalize each row by its root mean square and apply weight.
66	///
67	/// # Errors
68	///
69	/// Returns an error for an incompatible input or runtime recording failure.
70	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
71		let (weight, version, requires_grad) = self.weight.snapshot();
72		let output = matrix::rms_norm_forward(input, &weight, self.epsilon)?;
73		let parameter = requires_grad.then(|| (self.weight.clone(), version));
74		autograd::record_rms_norm(input, &output, parameter, weight, self.epsilon)?;
75		Ok(output)
76	}
77
78	/// Return the normalized final-dimension width.
79	pub const fn dimension(&self) -> usize {
80		self.dimension
81	}
82
83	/// Return the numerical-stability epsilon.
84	pub const fn epsilon(&self) -> f32 {
85		self.epsilon
86	}
87
88	/// Return the stable trainable weight handle.
89	pub fn weight(&self) -> Parameter {
90		self.weight.clone()
91	}
92
93	/// Return the one registered parameter.
94	pub fn parameters(&self) -> [Parameter; 1] {
95		[self.weight.clone()]
96	}
97}
98
99impl Module for RmsNorm {
100	fn forward(&self, input: &Matrix) -> Result<Matrix> {
101		RmsNorm::forward(self, input)
102	}
103
104	fn registry(&self) -> &ModuleRegistry {
105		&self.registry
106	}
107}