1use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, NamedBuffer, Parameter, autograd, matrix};
8
9pub struct BatchNorm2d {
13 num_features: usize,
14 epsilon: f32,
15 momentum: f32,
16 weight: Parameter,
17 bias: Parameter,
18 running_mean: NamedBuffer,
19 running_variance: NamedBuffer,
20 registry: ModuleRegistry,
21}
22
23impl BatchNorm2d {
24 pub fn new(num_features: usize) -> Result<Self> {
25 Self::new_on(&Runtime::current()?, num_features)
26 }
27
28 pub fn new_on(runtime: &Runtime, num_features: usize) -> Result<Self> {
34 Self::new_with_options_on(runtime, num_features, 1e-5, 0.1)
35 }
36
37 #[allow(clippy::too_many_arguments)]
38 pub fn new_with_options(num_features: usize, epsilon: f32, momentum: f32) -> Result<Self> {
39 Self::new_with_options_on(&Runtime::current()?, num_features, epsilon, momentum)
40 }
41
42 pub fn new_with_options_on(
50 runtime: &Runtime,
51 num_features: usize,
52 epsilon: f32,
53 momentum: f32,
54 ) -> Result<Self> {
55 if num_features == 0 {
56 return Err(Error::invalid_argument(
57 "BatchNorm2d feature count must be nonzero",
58 ));
59 }
60 let weight = Matrix::new_from_f32_on(runtime, [num_features], &vec![1.0; num_features])?;
61 let bias = Matrix::new_from_f32_on(runtime, [num_features], &vec![0.0; num_features])?;
62 let running_mean = Matrix::new_from_f32_on(runtime, [num_features], &vec![0.0; num_features])?;
63 let running_variance =
64 Matrix::new_from_f32_on(runtime, [num_features], &vec![1.0; num_features])?;
65 Self::new_from_state(
66 weight,
67 bias,
68 running_mean,
69 running_variance,
70 epsilon,
71 momentum,
72 false,
73 )
74 }
75
76 pub fn new_from_matrices(
84 weight: Matrix,
85 bias: Matrix,
86 running_mean: Matrix,
87 running_variance: Matrix,
88 epsilon: f32,
89 momentum: f32,
90 ) -> Result<Self> {
91 Self::new_from_state(
92 weight,
93 bias,
94 running_mean,
95 running_variance,
96 epsilon,
97 momentum,
98 true,
99 )
100 }
101
102 fn new_from_state(
103 weight: Matrix,
104 bias: Matrix,
105 running_mean: Matrix,
106 running_variance: Matrix,
107 epsilon: f32,
108 momentum: f32,
109 copy_running_state: bool,
110 ) -> Result<Self> {
111 let [num_features] = weight.shape() else {
112 return Err(Error::invalid_argument(
113 "BatchNorm2d weight must have rank one",
114 ));
115 };
116 if *num_features == 0
117 || bias.shape() != [*num_features]
118 || running_mean.shape() != [*num_features]
119 || running_variance.shape() != [*num_features]
120 || [
121 weight.dtype(),
122 bias.dtype(),
123 running_mean.dtype(),
124 running_variance.dtype(),
125 ]
126 .into_iter()
127 .any(|dtype| dtype != DType::F32)
128 || !weight.runtime().same_as(bias.runtime())
129 || !weight.runtime().same_as(running_mean.runtime())
130 || !weight.runtime().same_as(running_variance.runtime())
131 || !epsilon.is_finite()
132 || epsilon <= 0.0
133 || !momentum.is_finite()
134 || !(0.0..=1.0).contains(&momentum)
135 {
136 return Err(Error::invalid_argument(
137 "BatchNorm2d requires equal nonempty same-runtime F32 state vectors, finite positive epsilon, and momentum in [0, 1]",
138 ));
139 }
140 let num_features = *num_features;
141 let weight = Parameter::new("weight", weight)?;
142 let bias = Parameter::new("bias", bias)?;
143 let (running_mean, running_variance) = if copy_running_state {
144 (running_mean.copy()?, running_variance.copy()?)
145 } else {
146 (running_mean, running_variance)
147 };
148 let mut registry = ModuleRegistry::new();
149 registry.register_parameter("weight", weight.clone())?;
150 registry.register_parameter("bias", bias.clone())?;
151 registry.register_buffer("running_mean", running_mean, true)?;
152 registry.register_buffer("running_variance", running_variance, true)?;
153 let running_mean = registry
154 .buffer_handle("running_mean")
155 .ok_or_else(|| Error::internal("BatchNorm2d running mean registration was lost"))?;
156 let running_variance = registry
157 .buffer_handle("running_variance")
158 .ok_or_else(|| Error::internal("BatchNorm2d running variance registration was lost"))?;
159 Ok(Self {
160 num_features,
161 epsilon,
162 momentum,
163 weight,
164 bias,
165 running_mean,
166 running_variance,
167 registry,
168 })
169 }
170
171 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
181 let (weight_value, weight_version, weight_requires_grad) = self.weight.snapshot();
182 let (bias_value, bias_version, bias_requires_grad) = self.bias.snapshot();
183 let training = self.is_training();
184 let (output, mean, variance) = if training {
185 let result = matrix::batch_norm_2d_forward(input, &weight_value, &bias_value, self.epsilon)?;
186 let running_mean = self.running_mean.data();
187 let running_variance = self.running_variance.data();
188 matrix::batch_norm_2d_running_update(
189 &running_mean,
190 &running_variance,
191 &result.mean,
192 &result.variance,
193 self.momentum,
194 )?;
195 (result.output, result.mean, result.variance)
196 } else {
197 let mean = self.running_mean.data();
198 let variance = self.running_variance.data();
199 let (mean, variance) = if autograd::recording_active() {
201 (mean.copy()?, variance.copy()?)
202 } else {
203 (mean, variance)
204 };
205 let output = matrix::batch_norm_2d_with_stats_forward(
206 input,
207 &mean,
208 &variance,
209 &weight_value,
210 &bias_value,
211 self.epsilon,
212 )?;
213 (output, mean, variance)
214 };
215 autograd::record_batch_norm_2d(
216 input,
217 &output,
218 mean,
219 variance,
220 weight_requires_grad.then(|| (self.weight.clone(), weight_version)),
221 weight_value,
222 bias_requires_grad.then(|| (self.bias.clone(), bias_version)),
223 bias_value,
224 self.epsilon,
225 training,
226 )?;
227 Ok(output)
228 }
229
230 pub const fn num_features(&self) -> usize {
232 self.num_features
233 }
234
235 pub const fn epsilon(&self) -> f32 {
237 self.epsilon
238 }
239
240 pub const fn momentum(&self) -> f32 {
242 self.momentum
243 }
244
245 pub fn weight(&self) -> Parameter {
247 self.weight.clone()
248 }
249
250 pub fn bias(&self) -> Parameter {
252 self.bias.clone()
253 }
254
255 pub fn running_mean(&self) -> Matrix {
257 self.running_mean.data()
258 }
259
260 pub fn running_variance(&self) -> Matrix {
262 self.running_variance.data()
263 }
264
265 pub fn parameters(&self) -> [Parameter; 2] {
267 [self.weight.clone(), self.bias.clone()]
268 }
269}
270
271impl Module for BatchNorm2d {
272 fn forward(&self, input: &Matrix) -> Result<Matrix> {
273 BatchNorm2d::forward(self, input)
274 }
275
276 fn registry(&self) -> &ModuleRegistry {
277 &self.registry
278 }
279}