Skip to main content

oa/ml/nn/
local_response_norm.rs

1//! Local response normalization (`nn.LocalResponseNorm`) over the channel axis.
2
3use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7/// Cross-channel normalization `x_c / (k + (alpha / size) * sum_j x_j^2)^beta`
8/// where the sum spans the `size`-wide neighborhood centered at channel `c`,
9/// clipped at the borders.
10///
11/// The window sum is composed over a zero `PadMode::Constant` channel pad and
12/// `size` shifted slices, so gradients flow through the pad and slice
13/// adjoints.
14pub struct LocalResponseNorm {
15	size: usize,
16	alpha: f32,
17	beta: f32,
18	k: f32,
19	registry: ModuleRegistry,
20}
21
22impl LocalResponseNorm {
23	/// Construct with the donor defaults (`alpha = 1e-4`, `beta = 0.75`,
24	/// `k = 1.0`).
25	///
26	/// # Errors
27	///
28	/// Returns an error when `size` is zero.
29	pub fn new(size: usize) -> Result<Self> {
30		Self::new_with_options(size, 1e-4, 0.75, 1.0)
31	}
32
33	/// Construct with explicit normalization coefficients.
34	///
35	/// # Errors
36	///
37	/// Returns an error when `size` is zero or a coefficient is not finite.
38	pub fn new_with_options(size: usize, alpha: f32, beta: f32, k: f32) -> Result<Self> {
39		if size == 0 {
40			return Err(Error::invalid_argument(
41				"local response norm requires a nonzero window size",
42			));
43		}
44		if !alpha.is_finite() || !beta.is_finite() || !k.is_finite() {
45			return Err(Error::invalid_argument(
46				"local response norm coefficients must be finite",
47			));
48		}
49		Ok(Self {
50			size,
51			alpha,
52			beta,
53			k,
54			registry: ModuleRegistry::new(),
55		})
56	}
57
58	/// Return the configured window size.
59	pub const fn size(&self) -> usize {
60		self.size
61	}
62
63	/// Normalize channels of a rank-at-least-two `[N, C, *]` input.
64	///
65	/// # Errors
66	///
67	/// Returns an error for a rank-below-two input or a composed dispatch
68	/// failure.
69	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
70		let operation = "LocalResponseNorm";
71		let shape = input.shape();
72		if shape.len() < 2 {
73			return Err(Error::invalid_argument(format!(
74				"{operation} requires an input of rank at least two"
75			)));
76		}
77		let half = self.size / 2;
78		let squared = matrix::mul(input, input)?;
79		let mut pads = vec![0_usize; 2 * shape.len()];
80		pads[2] = half;
81		pads[3] = half;
82		let padded = matrix::pad(&squared, &pads, matrix::PadMode::Constant, 0.0)?;
83		let channels = shape[1] as i64;
84		let mut sum: Option<Matrix> = None;
85		for offset in 0..self.size {
86			let window = matrix::slice(&padded, 1, offset as i64, offset as i64 + channels)?;
87			sum = Some(match sum {
88				None => window,
89				Some(total) => matrix::add(&total, &window)?,
90			});
91		}
92		let sum = sum.ok_or_else(|| {
93			Error::invalid_argument(format!("{operation} requires a nonzero window size"))
94		})?;
95		let denominator = matrix::pow(
96			&matrix::add_scalar(&matrix::scale(&sum, self.alpha / self.size as f32)?, self.k)?,
97			self.beta,
98		)?;
99		matrix::div(input, &denominator)
100	}
101}
102
103impl Module for LocalResponseNorm {
104	fn forward(&self, input: &Matrix) -> Result<Matrix> {
105		LocalResponseNorm::forward(self, input)
106	}
107
108	fn registry(&self) -> &ModuleRegistry {
109		&self.registry
110	}
111}