Skip to main content

oa/ml/nn/
pool_ext.rs

1//! One-dimensional pooling composed over slice + reduce ops.
2
3use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7fn pool_1d(
8	input: &Matrix,
9	kernel_size: usize,
10	stride: usize,
11	padding: usize,
12	operation: &str,
13) -> Result<Matrix> {
14	let &[batch, channels, length] = input.shape() else {
15		return Err(Error::invalid_argument(format!(
16			"{operation} requires [N, C, L]; found {:?}",
17			input.shape(),
18		)));
19	};
20	if kernel_size == 0 || stride == 0 {
21		return Err(Error::invalid_argument(format!(
22			"{operation} requires nonzero kernel and stride"
23		)));
24	}
25	let padded = length
26		.checked_add(2 * padding)
27		.ok_or_else(|| Error::invalid_argument(format!("{operation} length overflows usize")))?;
28	if kernel_size > padded {
29		return Err(Error::invalid_argument(format!(
30			"{operation} kernel {kernel_size} exceeds padded length {padded}"
31		)));
32	}
33	let window_count = (padded - kernel_size) / stride + 1;
34	let padded_input = if padding > 0 {
35		let zeros = Matrix::new_from_slice_handle(
36			input.runtime(),
37			vec![batch, channels, padding],
38			&vec![0.0_f32; batch * channels * padding],
39		)?;
40		matrix::concat(&[zeros.clone(), input.clone(), zeros], 2)?
41	} else {
42		input.clone()
43	};
44	let mut windows = Vec::with_capacity(window_count);
45	for window in 0..window_count {
46		let start = window * stride;
47		let region = matrix::slice(&padded_input, 2, start as i64, (start + kernel_size) as i64)?;
48		windows.push(matrix::mean(&region, 2)?);
49	}
50	matrix::concat(&windows, 2)
51}
52
53/// `nn.AvgPool1d`: `[N, C, L]` average pooling.
54///
55/// Composed over per-window `slice` + `mean` — the 2d pooling kernel rejects
56/// inputs shorter than the kernel, and `matrix::max` is full-reduction only,
57/// so a max variant stays planned until an axis-max op exists.
58pub struct AvgPool1d {
59	kernel_size: usize,
60	stride: usize,
61	padding: usize,
62	registry: ModuleRegistry,
63}
64
65impl AvgPool1d {
66	/// Construct with `stride == kernel_size` and no padding.
67	///
68	/// # Errors
69	///
70	/// Returns an error when `kernel_size` is zero.
71	pub fn new(kernel_size: usize) -> Result<Self> {
72		Self::new_with_options(kernel_size, kernel_size, 0)
73	}
74
75	/// Construct with explicit stride and symmetric zero padding.
76	///
77	/// # Errors
78	///
79	/// Returns an error when `kernel_size` or `stride` is zero.
80	pub fn new_with_options(kernel_size: usize, stride: usize, padding: usize) -> Result<Self> {
81		if kernel_size == 0 || stride == 0 {
82			return Err(Error::invalid_argument(
83				"avg_pool1d requires nonzero kernel and stride",
84			));
85		}
86		Ok(Self {
87			kernel_size,
88			stride,
89			padding,
90			registry: ModuleRegistry::new(),
91		})
92	}
93
94	/// Pool `[N, C, L]` to `[N, C, floor((L + 2p - k) / s) + 1]`.
95	///
96	/// # Errors
97	///
98	/// Returns an error unless `input` is rank three F32, or the composed
99	/// ops fail.
100	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
101		pool_1d(
102			input,
103			self.kernel_size,
104			self.stride,
105			self.padding,
106			"avg_pool1d",
107		)
108	}
109}
110
111impl Module for AvgPool1d {
112	fn forward(&self, input: &Matrix) -> Result<Matrix> {
113		AvgPool1d::forward(self, input)
114	}
115
116	fn registry(&self) -> &ModuleRegistry {
117		&self.registry
118	}
119}