oa/ml/nn/
layer_norm.gen.rs1use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix};
8
9pub 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 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 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 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 pub fn forward_channel(&self, input: &Matrix) -> Result<Matrix> {
141 self.forward_channel_impl(input, false)
142 }
143
144 pub fn forward_channel_relu(&self, input: &Matrix) -> Result<Matrix> {
151 self.forward_channel_impl(input, true)
152 }
153
154 pub const fn normalized_shape(&self) -> usize {
156 self.normalized_shape
157 }
158
159 pub const fn epsilon(&self) -> f32 {
161 self.epsilon
162 }
163
164 pub fn weight(&self) -> Parameter {
166 self.weight.clone()
167 }
168
169 pub fn bias(&self) -> Parameter {
171 self.bias.clone()
172 }
173
174 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}