oa/ml/nn/
batch_norm_ext.rs1use std::rc::Rc;
4
5use crate::{Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry};
8use super::BatchNorm2d;
9
10pub struct BatchNorm1d {
17 inner: Rc<BatchNorm2d>,
18 registry: ModuleRegistry,
19}
20
21impl BatchNorm1d {
22 pub fn new(num_features: usize) -> Result<Self> {
28 Self::new_on(&Runtime::current()?, num_features)
29 }
30
31 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 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
73pub struct BatchNorm3d {
79 inner: Rc<BatchNorm2d>,
80 registry: ModuleRegistry,
81}
82
83impl BatchNorm3d {
84 pub fn new(num_features: usize) -> Result<Self> {
90 Self::new_on(&Runtime::current()?, num_features)
91 }
92
93 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 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}