1use crate::{DType, Error, Matrix, Result, Runtime, matrix};
4
5use super::super::{Module, ModuleRegistry, Parameter, autograd};
6
7pub 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 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 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 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(¢ered, ¢ered)?, 1)?;
103 let inv_std = matrix::sqrt(&matrix::add_scalar(&variance, self.epsilon)?)?;
104 let normalized = matrix::div(¢ered, &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
128pub struct InstanceNorm {
133 inner: GroupNorm,
134}
135
136impl InstanceNorm {
137 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 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}