Skip to main content

oa/ml/nn/
batch_norm_ext.rs

1//! Rank-adapted batch normalization over the shared 2d kernel family.
2
3use std::rc::Rc;
4
5use crate::{Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry};
8use super::BatchNorm2d;
9
10/// `nn.BatchNorm1d`: `[N, C, L]` batch normalization.
11///
12/// The composed contract reshapes to `[N, C, 1, L]` and delegates to the
13/// shared `BatchNorm2d` kernel family — batch statistics, running
14/// buffers, and adjoints are identical because normalization is
15/// per-`(N, C)` over flattened spatial extents.
16pub struct BatchNorm1d {
17	inner: Rc<BatchNorm2d>,
18	registry: ModuleRegistry,
19}
20
21impl BatchNorm1d {
22	/// Construct over `num_features` channels on the current runtime.
23	///
24	/// # Errors
25	///
26	/// Returns an error under the same contract as [`BatchNorm2d::new_on`].
27	pub fn new(num_features: usize) -> Result<Self> {
28		Self::new_on(&Runtime::current()?, num_features)
29	}
30
31	/// Construct on `runtime`.
32	///
33	/// # Errors
34	///
35	/// Returns an error under the same contract as [`BatchNorm2d::new_on`].
36	pub fn new_on(runtime: &Runtime, num_features: usize) -> Result<Self> {
37		let inner = Rc::new(BatchNorm2d::new_on(runtime, num_features)?);
38		let mut registry = ModuleRegistry::new();
39		registry.register_module("inner", Rc::clone(&inner) as Rc<dyn Module>)?;
40		Ok(Self { inner, registry })
41	}
42
43	/// Normalize `[N, C, L]` through the shared kernel.
44	///
45	/// # Errors
46	///
47	/// Returns an error unless `input` is rank three, or the delegated
48	/// forward fails.
49	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
50		let &[batch, channels, length] = input.shape() else {
51			return Err(Error::invalid_argument(format!(
52				"batch_norm1d requires [N, C, L]; found {:?}",
53				input.shape(),
54			)));
55		};
56		self
57			.inner
58			.forward(&input.reshape([batch, channels, 1, length])?)?
59			.reshape([batch, channels, length])
60	}
61}
62
63impl Module for BatchNorm1d {
64	fn forward(&self, input: &Matrix) -> Result<Matrix> {
65		BatchNorm1d::forward(self, input)
66	}
67
68	fn registry(&self) -> &ModuleRegistry {
69		&self.registry
70	}
71}
72
73/// `nn.BatchNorm3d`: `[N, C, D, H, W]` batch normalization.
74///
75/// Shares the `BatchNorm2d` kernel family by flattening `[D, H, W]` to
76/// `[D, H*W]` — normalization is per-`(N, C)` over spatial extents, so the
77/// flat layout is equivalent.
78pub struct BatchNorm3d {
79	inner: Rc<BatchNorm2d>,
80	registry: ModuleRegistry,
81}
82
83impl BatchNorm3d {
84	/// Construct over `num_features` channels on the current runtime.
85	///
86	/// # Errors
87	///
88	/// Returns an error under the same contract as [`BatchNorm2d::new_on`].
89	pub fn new(num_features: usize) -> Result<Self> {
90		Self::new_on(&Runtime::current()?, num_features)
91	}
92
93	/// Construct on `runtime`.
94	///
95	/// # Errors
96	///
97	/// Returns an error under the same contract as [`BatchNorm2d::new_on`].
98	pub fn new_on(runtime: &Runtime, num_features: usize) -> Result<Self> {
99		let inner = Rc::new(BatchNorm2d::new_on(runtime, num_features)?);
100		let mut registry = ModuleRegistry::new();
101		registry.register_module("inner", Rc::clone(&inner) as Rc<dyn Module>)?;
102		Ok(Self { inner, registry })
103	}
104
105	/// Normalize `[N, C, D, H, W]` through the shared kernel.
106	///
107	/// # Errors
108	///
109	/// Returns an error unless `input` is rank five, or the delegated
110	/// forward fails.
111	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
112		let &[batch, channels, depth, height, width] = input.shape() else {
113			return Err(Error::invalid_argument(format!(
114				"batch_norm3d requires [N, C, D, H, W]; found {:?}",
115				input.shape(),
116			)));
117		};
118		let flat = height
119			.checked_mul(width)
120			.ok_or_else(|| Error::invalid_argument("batch_norm3d spatial size overflows usize"))?;
121		self
122			.inner
123			.forward(&input.reshape([batch, channels, depth, flat])?)?
124			.reshape([batch, channels, depth, height, width])
125	}
126}
127
128impl Module for BatchNorm3d {
129	fn forward(&self, input: &Matrix) -> Result<Matrix> {
130		BatchNorm3d::forward(self, input)
131	}
132
133	fn registry(&self) -> &ModuleRegistry {
134		&self.registry
135	}
136}