Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387//! Learned separable/symmetric filters from component/core/upsampling.py.//! Includes learned weights and their derivatives. Transposed convolution uses//! reference replicate padding/crop.use super::Tensor;use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum FilterMode { Upsample, Residual,}
#[derive(Clone, Debug)]pub struct Filter { pub kernel: usize, /// Only the left half (including the middle value for odd kernels). pub half: Vec<f32>, pub mode: FilterMode,}
#[derive(Debug)]pub struct FilterGradient { pub input: Tensor, pub half: Vec<f32>,}
#[derive(Clone, Copy)]struct Tap { source: usize, weight: f32, half: usize,}struct AxisPlan { offsets: Vec<usize>, taps: Vec<Tap>,}impl AxisPlan { fn at(&self, target: usize) -> &[Tap] { &self.taps[self.offsets[target]..self.offsets[target + 1]] }}
impl Filter { fn axis_plan(&self, size: usize, targets: usize) -> AxisPlan { let mut plan = AxisPlan { offsets: Vec::with_capacity(targets + 1), taps: Vec::with_capacity(targets * self.kernel), }; for target in 0..targets { plan.offsets.push(plan.taps.len()); for k in 0..self.kernel { if let Some(source) = self.source(target, k, size) { let half = self.half_index(k); plan.taps.push(Tap { source, weight: self.half[half], half, }); } } } plan.offsets.push(plan.taps.len()); plan }
fn validate(&self) -> Result<()> { let valid = match self.mode { FilterMode::Upsample => self.kernel >= 4 && self.kernel.is_multiple_of(2), FilterMode::Residual => self.kernel % 2 == 1, }; if !valid || self.half.len() != self.kernel.div_ceil(2) { return Err(Error("Invalid reference upsampling filter")); } Ok(()) }
fn half_index(&self, k: usize) -> usize { k.min(self.kernel - k - 1) }
fn source(&self, target: usize, k: usize, size: usize) -> Option<usize> { match self.mode { FilterMode::Residual => { let source = target.checked_add(k)?.checked_sub(self.kernel / 2)?; (source < size).then_some(source) } FilterMode::Upsample => { let padding = self.kernel / 2; let crop = 2 * padding - 1 + self.kernel / 2; let coordinate = target.checked_add(crop)?.checked_sub(k)?; if coordinate % 2 != 0 { return None; } let padded = coordinate / 2; if padded >= size.checked_add(2 * padding)? { return None; } Some(padded.saturating_sub(padding).min(size - 1)) } } }
fn axis_forward(&self, input: &Tensor, horizontal: bool) -> Result<Tensor> { let factor = if self.mode == FilterMode::Upsample { 2 } else { 1 }; let height = input .height .checked_mul(if horizontal { 1 } else { factor }) .ok_or(Error("Reference upsampling dimensions overflow"))?; let width = input .width .checked_mul(if horizontal { factor } else { 1 }) .ok_or(Error("Reference upsampling dimensions overflow"))?; let mut output = Tensor::zeros(input.channels, height, width)?; // Geometry is identical on every row/channel. Build it once, not // once per sample/tap. Vertical and residual-horizontal passes stream // contiguous slices, enabling WASM SIMD without changing tap order. let plan = if !horizontal || self.mode == FilterMode::Upsample { Some(self.axis_plan( if horizontal { input.width } else { input.height }, if horizontal { width } else { height }, )) } else { None }; let row = |index: usize, values: &mut [f32]| { let channel = index / height; let y = index % height; if !horizontal { for tap in plan.as_ref().unwrap().at(y) { let start = input.index(channel, tap.source, 0); for (value, &sample) in values.iter_mut().zip(&input.data[start..start + width]) { *value += sample * tap.weight; } } } else if self.mode == FilterMode::Residual { let source = &input.data[index * input.width..(index + 1) * input.width]; for k in 0..self.kernel { let offset = k as isize - (self.kernel / 2) as isize; let dst = (-offset).max(0) as usize; let src = offset.max(0) as usize; if dst >= width || src >= input.width { continue; } let len = (width - dst).min(input.width - src); let weight = self.half[self.half_index(k)]; for (value, &sample) in values[dst..dst + len] .iter_mut() .zip(&source[src..src + len]) { *value += sample * weight; } } } else { let source = &input.data[index * input.width..(index + 1) * input.width]; for (x, value) in values.iter_mut().enumerate() { for tap in plan.as_ref().unwrap().at(x) { *value += source[tap.source] * tap.weight; } } } }; #[cfg(feature = "parallel")] if super::parallel::worthwhile(output.data.len() * self.kernel) { use rayon::prelude::*; output .data .par_chunks_mut(width) .enumerate() .for_each(|(i, values)| row(i, values)); return Ok(output); } output .data .chunks_mut(width) .enumerate() .for_each(|(i, values)| row(i, values)); Ok(output) }
fn axis_backward( &self, input: &Tensor, gradient: &Tensor, horizontal: bool, ) -> Result<FilterGradient> { #[cfg(feature = "parallel")] if super::parallel::worthwhile(gradient.data.len() * self.kernel) { return self.parallel_axis_backward(input, gradient, horizontal); } let mut result = FilterGradient { input: Tensor::zeros(input.channels, input.height, input.width)?, half: vec![0.0; self.half.len()], }; let plan = self.axis_plan( if horizontal { input.width } else { input.height }, if horizontal { gradient.width } else { gradient.height }, ); for channel in 0..gradient.channels { for y in 0..gradient.height { for x in 0..gradient.width { let g = gradient.data[gradient.index(channel, y, x)]; for tap in plan.at(if horizontal { x } else { y }) { let i = input.index( channel, if horizontal { y } else { tap.source }, if horizontal { tap.source } else { x }, ); result.input.data[i] += g * tap.weight; result.half[tap.half] += g * input.data[i]; } } } } Ok(result) }
#[cfg(feature = "parallel")] fn parallel_axis_backward( &self, input: &Tensor, gradient: &Tensor, horizontal: bool, ) -> Result<FilterGradient> { use rayon::prelude::*; // Independent rows/columns own their input gradients. Collect in raster // order for deterministic filter-gradient reduction, never float atomics. let lines = input.channels * if horizontal { input.height } else { input.width }; let size = if horizontal { input.width } else { input.height }; let targets = if horizontal { gradient.width } else { gradient.height }; let plan = self.axis_plan(size, targets); let parts: Vec<_> = (0..lines) .into_par_iter() .map(|line| { let c = line / if horizontal { input.height } else { input.width }; let fixed = line % if horizontal { input.height } else { input.width }; let mut values = vec![0.0; size]; let mut half = vec![0.0; self.half.len()]; for target in 0..targets { let g = gradient.data[gradient.index( c, if horizontal { fixed } else { target }, if horizontal { target } else { fixed }, )]; for tap in plan.at(target) { values[tap.source] += g * tap.weight; let i = input.index( c, if horizontal { fixed } else { tap.source }, if horizontal { tap.source } else { fixed }, ); half[tap.half] += g * input.data[i]; } } (values, half) }) .collect(); let mut result = FilterGradient { input: Tensor::zeros(input.channels, input.height, input.width)?, half: vec![0.0; self.half.len()], }; for (line, (values, half)) in parts.into_iter().enumerate() { if horizontal { result.input.data[line * input.width..(line + 1) * input.width] .copy_from_slice(&values); } else { let c = line / input.width; let x = line % input.width; for (y, value) in values.into_iter().enumerate() { result.input.data[(c * input.height + y) * input.width + x] = value; } } for (a, b) in result.half.iter_mut().zip(half) { *a += b; } } Ok(result) }
pub fn forward(&self, input: &Tensor) -> Result<Tensor> { self.validate()?; let horizontal = self.axis_forward(input, true)?; let mut output = self.axis_forward(&horizontal, false)?; if self.mode == FilterMode::Residual { output.add_assign(input)?; } Ok(output) }
pub fn backward(&self, input: &Tensor, gradient: &Tensor) -> Result<FilterGradient> { self.validate()?; let horizontal = self.axis_forward(input, true)?; let factor = if self.mode == FilterMode::Upsample { 2 } else { 1 }; if (gradient.channels, gradient.height, gradient.width) != (input.channels, horizontal.height * factor, horizontal.width) { return Err(Error("Invalid reference filter gradient shape")); } let vertical = self.axis_backward(&horizontal, gradient, false)?; let mut result = self.axis_backward(input, &vertical.input, true)?; for (a, b) in result.half.iter_mut().zip(vertical.half) { *a += b; } if self.mode == FilterMode::Residual { result.input.add_assign(gradient)?; } Ok(result) }}
#[cfg(test)]mod tests { use super::*;
#[test] fn nearest_neighbour_is_a_special_case_not_a_substitute() { let filter = Filter { kernel: 4, half: vec![0.0, 1.0], mode: FilterMode::Upsample, }; let input = Tensor::new(1, 1, 2, vec![2.0, 7.0]).unwrap(); assert_eq!( filter.forward(&input).unwrap().data, vec![2.0, 2.0, 7.0, 7.0, 2.0, 2.0, 7.0, 7.0] ); }
#[test] fn preconcat_has_a_residual_even_for_one_tap() { let filter = Filter { kernel: 1, half: vec![2.0], mode: FilterMode::Residual, }; let input = Tensor::new(1, 1, 1, vec![3.0]).unwrap(); assert_eq!(filter.forward(&input).unwrap().data, vec![15.0]); let gradient = Tensor::new(1, 1, 1, vec![1.0]).unwrap(); let g = filter.backward(&input, &gradient).unwrap(); assert_eq!(g.input.data, vec![5.0]); assert_eq!(g.half, vec![12.0]); }}