Skip to main content

oa/ml/nn/
group_norm.rs

1//! Group- and instance-normalization modules composed over reduce ops.
2
3use crate::{DType, Error, Matrix, Result, Runtime, matrix};
4
5use super::super::{Module, ModuleRegistry, Parameter, autograd};
6
7/// Group normalization: normalize each `channels / num_groups` channel group
8/// per sample, then apply a learned per-channel affine.
9///
10/// Composed contract over `reshape` + `mean` + `mul`/`sub`/`div`/`sqrt`, so
11/// gradients flow through the elementwise and reduce adjoints into `weight`
12/// and `bias` parameters without a fused kernel. The variance uses the
13/// biased `mean((x - mu)^2)` form matching `nn.GroupNorm`.
14pub struct GroupNorm {
15	num_groups: usize,
16	num_channels: usize,
17	epsilon: f32,
18	weight: Parameter,
19	bias: Parameter,
20	registry: ModuleRegistry,
21}
22
23impl GroupNorm {
24	/// Construct with unit weight and zero bias.
25	///
26	/// # Errors
27	///
28	/// Returns an error when `num_channels` is zero, `num_groups` does not
29	/// divide it, `epsilon` is not finite and positive, or allocation fails.
30	pub fn new_on(
31		runtime: &Runtime,
32		num_groups: usize,
33		num_channels: usize,
34		epsilon: f32,
35	) -> Result<Self> {
36		if num_channels == 0 || num_groups == 0 || !num_channels.is_multiple_of(num_groups) {
37			return Err(Error::invalid_argument(format!(
38				"group norm requires 0 < num_groups | num_channels; found {num_groups}/{num_channels}"
39			)));
40		}
41		if !epsilon.is_finite() || epsilon <= 0.0 {
42			return Err(Error::invalid_argument(
43				"group norm epsilon must be finite and positive",
44			));
45		}
46		let weight = Parameter::new(
47			"weight",
48			Matrix::new_from_f32_on(runtime, [num_channels], &vec![1.0_f32; num_channels])?,
49		)?;
50		let bias = Parameter::new(
51			"bias",
52			Matrix::new_from_f32_on(runtime, [num_channels], &vec![0.0_f32; num_channels])?,
53		)?;
54		let mut registry = ModuleRegistry::new();
55		registry.register_parameter("weight", weight.clone())?;
56		registry.register_parameter("bias", bias.clone())?;
57		Ok(Self {
58			num_groups,
59			num_channels,
60			epsilon,
61			weight,
62			bias,
63			registry,
64		})
65	}
66
67	/// Construct on the current runtime with `epsilon = 1e-5`.
68	///
69	/// # Errors
70	///
71	/// Returns an error under the same contract as [`Self::new_on`].
72	pub fn new(num_groups: usize, num_channels: usize) -> Result<Self> {
73		Self::new_on(&Runtime::current()?, num_groups, num_channels, 1e-5)
74	}
75
76	/// Normalize `input` shaped `[N, C, *spatial]` and apply the affine.
77	///
78	/// # Errors
79	///
80	/// Returns an error when the input is not F32 rank >= 2 with
81	/// `num_channels` channels, or the composed ops fail.
82	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
83		if input.dtype() != DType::F32
84			|| input.shape().len() < 2
85			|| input.shape()[1] != self.num_channels
86		{
87			return Err(Error::invalid_argument(format!(
88				"group norm requires F32 [N, {}, *]; found {:?} {}",
89				self.num_channels,
90				input.shape(),
91				input.dtype().token(),
92			)));
93		}
94		let batch = input.shape()[0];
95		let spatial: usize = input.shape()[2..].iter().product();
96		let inner = (self.num_channels / self.num_groups)
97			.checked_mul(spatial)
98			.ok_or_else(|| Error::invalid_argument("group norm inner size overflows usize"))?;
99		let rows = input.reshape([batch * self.num_groups, inner])?;
100		let mean = matrix::mean(&rows, 1)?;
101		let centered = matrix::sub(&rows, &mean)?;
102		let variance = matrix::mean(&matrix::mul(&centered, &centered)?, 1)?;
103		let inv_std = matrix::sqrt(&matrix::add_scalar(&variance, self.epsilon)?)?;
104		let normalized = matrix::div(&centered, &inv_std)?;
105		autograd::record_parameter_leaf(&self.weight)?;
106		autograd::record_parameter_leaf(&self.bias)?;
107		let mut channel_shape = vec![1_usize; input.shape().len()];
108		channel_shape[1] = self.num_channels;
109		let restored = normalized.reshape(input.shape().to_vec())?;
110		let scaled = matrix::mul(
111			&restored,
112			&self.weight.data().reshape(channel_shape.clone())?,
113		)?;
114		matrix::add(&scaled, &self.bias.data().reshape(channel_shape)?)
115	}
116}
117
118impl Module for GroupNorm {
119	fn forward(&self, input: &Matrix) -> Result<Matrix> {
120		GroupNorm::forward(self, input)
121	}
122
123	fn registry(&self) -> &ModuleRegistry {
124		&self.registry
125	}
126}
127
128/// Instance normalization: [`GroupNorm`] with `num_groups == num_channels`.
129///
130/// Each channel normalizes per sample over its own spatial extent, matching
131/// `nn.InstanceNormNd` semantics without running statistics.
132pub struct InstanceNorm {
133	inner: GroupNorm,
134}
135
136impl InstanceNorm {
137	/// Construct per-channel normalization with `epsilon = 1e-5`.
138	///
139	/// # Errors
140	///
141	/// Returns an error under the same contract as [`GroupNorm::new_on`].
142	pub fn new_on(runtime: &Runtime, num_channels: usize, epsilon: f32) -> Result<Self> {
143		Ok(Self {
144			inner: GroupNorm::new_on(runtime, num_channels, num_channels, epsilon)?,
145		})
146	}
147
148	/// Construct on the current runtime.
149	///
150	/// # Errors
151	///
152	/// Returns an error under the same contract as [`Self::new_on`].
153	pub fn new(num_channels: usize) -> Result<Self> {
154		Self::new_on(&Runtime::current()?, num_channels, 1e-5)
155	}
156}
157
158impl Module for InstanceNorm {
159	fn forward(&self, input: &Matrix) -> Result<Matrix> {
160		self.inner.forward(input)
161	}
162
163	fn registry(&self) -> &ModuleRegistry {
164		GroupNorm::registry(&self.inner)
165	}
166}