oa/ml/nn/
local_response_norm.rs1use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7pub struct LocalResponseNorm {
15 size: usize,
16 alpha: f32,
17 beta: f32,
18 k: f32,
19 registry: ModuleRegistry,
20}
21
22impl LocalResponseNorm {
23 pub fn new(size: usize) -> Result<Self> {
30 Self::new_with_options(size, 1e-4, 0.75, 1.0)
31 }
32
33 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 pub const fn size(&self) -> usize {
60 self.size
61 }
62
63 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}