1use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix};
8
9pub 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 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 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 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 pub const fn dimension(&self) -> usize {
80 self.dimension
81 }
82
83 pub const fn epsilon(&self) -> f32 {
85 self.epsilon
86 }
87
88 pub fn weight(&self) -> Parameter {
90 self.weight.clone()
91 }
92
93 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}