use std::rc::Rc;
use crate::{Error, Matrix, Result, Runtime};
use super::super::{Module, ModuleRegistry};
use super::BatchNorm2d;
pub struct BatchNorm1d {
inner: Rc<BatchNorm2d>,
registry: ModuleRegistry,
}
impl BatchNorm1d {
pub fn new(num_features: usize) -> Result<Self> {
Self::new_on(&Runtime::current()?, num_features)
}
pub fn new_on(runtime: &Runtime, num_features: usize) -> Result<Self> {
let inner = Rc::new(BatchNorm2d::new_on(runtime, num_features)?);
let mut registry = ModuleRegistry::new();
registry.register_module("inner", Rc::clone(&inner) as Rc<dyn Module>)?;
Ok(Self { inner, registry })
}
pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
let &[batch, channels, length] = input.shape() else {
return Err(Error::invalid_argument(format!(
"batch_norm1d requires [N, C, L]; found {:?}",
input.shape(),
)));
};
self
.inner
.forward(&input.reshape([batch, channels, 1, length])?)?
.reshape([batch, channels, length])
}
}
impl Module for BatchNorm1d {
fn forward(&self, input: &Matrix) -> Result<Matrix> {
BatchNorm1d::forward(self, input)
}
fn registry(&self) -> &ModuleRegistry {
&self.registry
}
}
pub struct BatchNorm3d {
inner: Rc<BatchNorm2d>,
registry: ModuleRegistry,
}
impl BatchNorm3d {
pub fn new(num_features: usize) -> Result<Self> {
Self::new_on(&Runtime::current()?, num_features)
}
pub fn new_on(runtime: &Runtime, num_features: usize) -> Result<Self> {
let inner = Rc::new(BatchNorm2d::new_on(runtime, num_features)?);
let mut registry = ModuleRegistry::new();
registry.register_module("inner", Rc::clone(&inner) as Rc<dyn Module>)?;
Ok(Self { inner, registry })
}
pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
let &[batch, channels, depth, height, width] = input.shape() else {
return Err(Error::invalid_argument(format!(
"batch_norm3d requires [N, C, D, H, W]; found {:?}",
input.shape(),
)));
};
let flat = height
.checked_mul(width)
.ok_or_else(|| Error::invalid_argument("batch_norm3d spatial size overflows usize"))?;
self
.inner
.forward(&input.reshape([batch, channels, depth, flat])?)?
.reshape([batch, channels, depth, height, width])
}
}
impl Module for BatchNorm3d {
fn forward(&self, input: &Matrix) -> Result<Matrix> {
BatchNorm3d::forward(self, input)
}
fn registry(&self) -> &ModuleRegistry {
&self.registry
}
}