Skip to main content

coeus_nn/pool/
pool1d.rs

1// ── Pool1d ──
2// MaxPool1d and AvgPool1d for 1D spatial inputs `[N, C, L]`.
3
4use crate::module::{Module, ModuleError};
5use crate::pool::checked_out_dim;
6use coeus_autograd::Var;
7use coeus_core::{Float, MoiraiBackend, Scalar};
8use coeus_tensor::Tensor;
9use std::marker::PhantomData;
10
11// ── MaxPool1d ──
12
13/// 1D max pooling layer for inputs shaped `[N, C, L]`.
14///
15/// Slides a window of `kernel_size` along the length dimension and takes the maximum.
16///
17/// # Examples
18///
19/// ```
20/// use coeus_nn::{MaxPool1d, Module};
21/// use coeus_autograd::Var;
22/// use coeus_tensor::Tensor;
23/// use coeus_core::SequentialBackend;
24///
25/// let pool = MaxPool1d::<f32, SequentialBackend>::new(2);
26/// let x = Var::new(
27///     Tensor::from_slice([1, 1, 4], &[1.0_f32, 3.0, 2.0, 4.0])
28///         .expect("invariant: example shape matches data"),
29///     false,
30/// ).expect("invariant: constant example variable needs no gradient buffer");
31/// let y = pool.forward(&x).expect("valid MaxPool1d input");
32/// assert_eq!(y.tensor.shape(), &[1, 1, 2]);
33/// ```
34#[derive(Clone)]
35pub struct MaxPool1d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
36    /// Pooling window length.
37    kernel_size: usize,
38    /// Stride along the L dimension.
39    stride: usize,
40    /// Zero-padding applied to both sides.
41    padding: usize,
42    /// Spacing between pooling window elements.
43    dilation: usize,
44    _marker: PhantomData<(T, B)>,
45}
46
47impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> MaxPool1d<T, B> {
48    /// Create with stride equal to kernel_size, no padding, no dilation.
49    pub fn new(kernel_size: usize) -> Self {
50        Self::with_params(kernel_size, kernel_size, 0, 1)
51    }
52
53    /// Create with explicit hyperparameters.
54    pub fn with_params(kernel_size: usize, stride: usize, padding: usize, dilation: usize) -> Self {
55        Self {
56            kernel_size,
57            stride,
58            padding,
59            dilation,
60            _marker: PhantomData,
61        }
62    }
63}
64
65impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for MaxPool1d<T, B> {
66    fn parameters(&self) -> Vec<Var<T, B>> {
67        vec![]
68    }
69
70    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
71        let backend = B::default();
72        let shape = input.tensor.shape();
73        if shape.len() != 3 {
74            return Err(ModuleError::InvalidRank {
75                module: "MaxPool1d",
76                expected: "3",
77                actual: shape.len(),
78            });
79        }
80        let [n, c, l] = [shape[0], shape[1], shape[2]];
81        let l_out = checked_out_dim(
82            "MaxPool1d",
83            l,
84            self.kernel_size,
85            self.padding,
86            self.stride,
87            self.dilation,
88        )?;
89
90        // SAFETY: The following operation writes every output element before it is read.
91        let mut out_tensor = unsafe { Tensor::alloc_on([n, c, l_out], &backend) }?;
92        let (out_storage, out_layout) = out_tensor.storage_mut_and_layout()?;
93
94        backend
95            .max_pool1d(
96                input.tensor.storage(),
97                input.tensor.layout(),
98                self.kernel_size,
99                self.stride,
100                self.padding,
101                self.dilation,
102                out_storage,
103                out_layout,
104            )
105            .map_err(|source| ModuleError::Backend {
106                module: "MaxPool1d",
107                source,
108            })?;
109
110        Ok(coeus_autograd::max_pool1d(
111            input,
112            out_tensor,
113            self.kernel_size,
114            self.stride,
115            self.padding,
116            self.dilation,
117        )?)
118    }
119}
120
121// ── AvgPool1d ──
122
123/// 1D average pooling layer for inputs shaped `[N, C, L]`.
124///
125/// Slides a window of `kernel_size` along the length dimension and takes the average.
126///
127/// # Examples
128///
129/// ```
130/// use coeus_nn::{AvgPool1d, Module};
131/// use coeus_autograd::Var;
132/// use coeus_tensor::Tensor;
133/// use coeus_core::SequentialBackend;
134///
135/// let pool = AvgPool1d::<f32, SequentialBackend>::new(2);
136/// let x = Var::new(
137///     Tensor::from_slice([1, 1, 4], &[1.0_f32, 3.0, 2.0, 4.0])
138///         .expect("invariant: example shape matches data"),
139///     false,
140/// ).expect("invariant: constant example variable needs no gradient buffer");
141/// let y = pool.forward(&x).expect("valid AvgPool1d input");
142/// assert_eq!(y.tensor.shape(), &[1, 1, 2]);
143/// ```
144#[derive(Clone)]
145pub struct AvgPool1d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
146    /// Pooling window length.
147    kernel_size: usize,
148    /// Stride along the L dimension.
149    stride: usize,
150    /// Zero-padding applied to both sides.
151    padding: usize,
152    /// Spacing between pooling window elements.
153    dilation: usize,
154    _marker: PhantomData<(T, B)>,
155}
156
157impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> AvgPool1d<T, B> {
158    /// Create with stride equal to kernel_size, no padding, no dilation.
159    pub fn new(kernel_size: usize) -> Self {
160        Self::with_params(kernel_size, kernel_size, 0, 1)
161    }
162
163    /// Create with explicit hyperparameters.
164    pub fn with_params(kernel_size: usize, stride: usize, padding: usize, dilation: usize) -> Self {
165        Self {
166            kernel_size,
167            stride,
168            padding,
169            dilation,
170            _marker: PhantomData,
171        }
172    }
173}
174
175impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for AvgPool1d<T, B> {
176    fn parameters(&self) -> Vec<Var<T, B>> {
177        vec![]
178    }
179
180    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
181        let backend = B::default();
182        let shape = input.tensor.shape();
183        if shape.len() != 3 {
184            return Err(ModuleError::InvalidRank {
185                module: "AvgPool1d",
186                expected: "3",
187                actual: shape.len(),
188            });
189        }
190        let [n, c, l] = [shape[0], shape[1], shape[2]];
191        let l_out = checked_out_dim(
192            "AvgPool1d",
193            l,
194            self.kernel_size,
195            self.padding,
196            self.stride,
197            self.dilation,
198        )?;
199
200        // SAFETY: The following operation writes every output element before it is read.
201        let mut out_tensor = unsafe { Tensor::alloc_on([n, c, l_out], &backend) }?;
202        let (out_storage, out_layout) = out_tensor.storage_mut_and_layout()?;
203
204        backend
205            .avg_pool1d(
206                input.tensor.storage(),
207                input.tensor.layout(),
208                self.kernel_size,
209                self.stride,
210                self.padding,
211                self.dilation,
212                out_storage,
213                out_layout,
214            )
215            .map_err(|source| ModuleError::Backend {
216                module: "AvgPool1d",
217                source,
218            })?;
219
220        Ok(coeus_autograd::avg_pool1d(
221            input,
222            out_tensor,
223            self.kernel_size,
224            self.stride,
225            self.padding,
226            self.dilation,
227        )?)
228    }
229}