Skip to main content

coeus_nn/pool/
avg.rs

1use crate::module::{Module, ModuleError};
2use crate::pool::checked_out_dim;
3use coeus_autograd::Var;
4use coeus_core::{Float, MoiraiBackend, Scalar};
5use coeus_tensor::Tensor;
6use std::marker::PhantomData;
7
8// ── AvgPool2d ──
9
10/// 2D average pooling layer.
11#[derive(Clone)]
12pub struct AvgPool2d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
13    /// Pooling window side length.
14    kernel_size: usize,
15    /// Stride along H and W dimensions.
16    stride: usize,
17    /// Zero-padding applied to all spatial sides.
18    padding: usize,
19    /// Spacing between pooling window elements.
20    dilation: usize,
21    _marker: PhantomData<(T, B)>,
22}
23
24impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> AvgPool2d<T, B> {
25    /// Create with stride equal to kernel_size, no padding, no dilation.
26    pub fn new(kernel_size: usize) -> Self {
27        Self::with_params(kernel_size, kernel_size, 0, 1)
28    }
29
30    /// Create with explicit hyperparameters.
31    pub fn with_params(kernel_size: usize, stride: usize, padding: usize, dilation: usize) -> Self {
32        Self {
33            kernel_size,
34            stride,
35            padding,
36            dilation,
37            _marker: PhantomData,
38        }
39    }
40}
41
42impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for AvgPool2d<T, B> {
43    fn parameters(&self) -> Vec<Var<T, B>> {
44        vec![]
45    }
46
47    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
48        let backend = B::default();
49        let shape = input.tensor.shape();
50        if shape.len() != 4 {
51            return Err(ModuleError::InvalidRank {
52                module: "AvgPool2d",
53                expected: "4",
54                actual: shape.len(),
55            });
56        }
57        let [n, c, h, w] = [shape[0], shape[1], shape[2], shape[3]];
58        let h_out = checked_out_dim(
59            "AvgPool2d",
60            h,
61            self.kernel_size,
62            self.padding,
63            self.stride,
64            self.dilation,
65        )?;
66        let w_out = checked_out_dim(
67            "AvgPool2d",
68            w,
69            self.kernel_size,
70            self.padding,
71            self.stride,
72            self.dilation,
73        )?;
74
75        let mut out_tensor = Tensor::zeros_on([n, c, h_out, w_out], &backend)?;
76        let (out_storage, out_layout) = out_tensor.storage_mut_and_layout()?;
77
78        backend
79            .avg_pool2d(
80                input.tensor.storage(),
81                input.tensor.layout(),
82                self.kernel_size,
83                self.stride,
84                self.padding,
85                self.dilation,
86                out_storage,
87                out_layout,
88            )
89            .map_err(|source| ModuleError::Backend {
90                module: "AvgPool2d",
91                source,
92            })?;
93
94        Ok(coeus_autograd::avg_pool2d(
95            input,
96            out_tensor,
97            self.kernel_size,
98            self.stride,
99            self.padding,
100            self.dilation,
101        )?)
102    }
103}
104
105// ── AvgPool3d ──
106
107/// 3D average pooling layer.
108#[derive(Clone)]
109pub struct AvgPool3d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
110    /// Cubic pooling window side length.
111    kernel_size: usize,
112    /// Stride along D, H, and W dimensions.
113    stride: usize,
114    /// Zero-padding applied to all spatial sides.
115    padding: usize,
116    /// Spacing between pooling window elements.
117    dilation: usize,
118    _marker: PhantomData<(T, B)>,
119}
120
121impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> AvgPool3d<T, B> {
122    /// Create with stride equal to kernel_size, no padding, no dilation.
123    pub fn new(kernel_size: usize) -> Self {
124        Self::with_params(kernel_size, kernel_size, 0, 1)
125    }
126
127    /// Create with explicit hyperparameters.
128    pub fn with_params(kernel_size: usize, stride: usize, padding: usize, dilation: usize) -> Self {
129        Self {
130            kernel_size,
131            stride,
132            padding,
133            dilation,
134            _marker: PhantomData,
135        }
136    }
137}
138
139impl<T: Float, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for AvgPool3d<T, B> {
140    fn parameters(&self) -> Vec<Var<T, B>> {
141        vec![]
142    }
143
144    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
145        let backend = B::default();
146        let shape = input.tensor.shape();
147        if shape.len() != 5 {
148            return Err(ModuleError::InvalidRank {
149                module: "AvgPool3d",
150                expected: "5",
151                actual: shape.len(),
152            });
153        }
154        let [n, c, d, h, w] = [shape[0], shape[1], shape[2], shape[3], shape[4]];
155        let d_out = checked_out_dim(
156            "AvgPool3d",
157            d,
158            self.kernel_size,
159            self.padding,
160            self.stride,
161            self.dilation,
162        )?;
163        let h_out = checked_out_dim(
164            "AvgPool3d",
165            h,
166            self.kernel_size,
167            self.padding,
168            self.stride,
169            self.dilation,
170        )?;
171        let w_out = checked_out_dim(
172            "AvgPool3d",
173            w,
174            self.kernel_size,
175            self.padding,
176            self.stride,
177            self.dilation,
178        )?;
179
180        let mut out_tensor = Tensor::zeros_on([n, c, d_out, h_out, w_out], &backend)?;
181        let (out_storage, out_layout) = out_tensor.storage_mut_and_layout()?;
182
183        backend
184            .avg_pool3d(
185                input.tensor.storage(),
186                input.tensor.layout(),
187                self.kernel_size,
188                self.stride,
189                self.padding,
190                self.dilation,
191                out_storage,
192                out_layout,
193            )
194            .map_err(|source| ModuleError::Backend {
195                module: "AvgPool3d",
196                source,
197            })?;
198
199        Ok(coeus_autograd::avg_pool3d(
200            input,
201            out_tensor,
202            self.kernel_size,
203            self.stride,
204            self.padding,
205            self.dilation,
206        )?)
207    }
208}