Skip to main content

coeus_nn/conv/unfold_fold/
unfold2d.rs

1use super::validation::{checked_output_dim, invalid_window};
2use crate::module::{Module, ModuleError};
3use coeus_autograd::Var;
4use coeus_core::{MoiraiBackend, Scalar};
5use std::marker::PhantomData;
6
7/// Extracts sliding 2D windows from `[N, C, H, W]` into `[N, C*kH*kW, H_out*W_out]`.
8///
9/// Matches PyTorch `nn.Unfold`. Stateless; no learnable parameters.
10///
11/// # Shape
12/// - Input:  `[N, C, H, W]`
13/// - Output: `[N, C * kH * kW, H_out * W_out]`
14#[derive(Clone, Debug)]
15pub struct Unfold2d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
16    kernel_h: usize,
17    kernel_w: usize,
18    stride_h: usize,
19    stride_w: usize,
20    padding_h: usize,
21    padding_w: usize,
22    dilation_h: usize,
23    dilation_w: usize,
24    _marker: PhantomData<(T, B)>,
25}
26
27impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> Unfold2d<T, B> {
28    /// Create `Unfold2d` with a square kernel and equal per-axis parameters.
29    pub fn new(kernel_size: usize, stride: usize, padding: usize, dilation: usize) -> Self {
30        Self {
31            kernel_h: kernel_size,
32            kernel_w: kernel_size,
33            stride_h: stride,
34            stride_w: stride,
35            padding_h: padding,
36            padding_w: padding,
37            dilation_h: dilation,
38            dilation_w: dilation,
39            _marker: PhantomData,
40        }
41    }
42
43    /// Create `Unfold2d` with per-axis hyperparameters.
44    #[expect(
45        clippy::too_many_arguments,
46        reason = "ratchet ATLAS-COEUS-LINT-RATCHET-097"
47    )]
48    pub fn with_params(
49        kernel_h: usize,
50        kernel_w: usize,
51        stride_h: usize,
52        stride_w: usize,
53        padding_h: usize,
54        padding_w: usize,
55        dilation_h: usize,
56        dilation_w: usize,
57    ) -> Self {
58        Self {
59            kernel_h,
60            kernel_w,
61            stride_h,
62            stride_w,
63            padding_h,
64            padding_w,
65            dilation_h,
66            dilation_w,
67            _marker: PhantomData,
68        }
69    }
70}
71
72impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Unfold2d<T, B> {
73    fn parameters(&self) -> Vec<Var<T, B>> {
74        vec![]
75    }
76
77    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
78        let shape = input.tensor.shape();
79        if shape.len() != 4 {
80            return Err(ModuleError::InvalidRank {
81                module: "Unfold2d",
82                expected: "4",
83                actual: shape.len(),
84            });
85        }
86        let output_h = checked_output_dim(
87            shape[2],
88            self.kernel_h,
89            self.stride_h,
90            self.padding_h,
91            self.dilation_h,
92        );
93        let output_w = checked_output_dim(
94            shape[3],
95            self.kernel_w,
96            self.stride_w,
97            self.padding_w,
98            self.dilation_w,
99        );
100        let (output_h, output_w) = match (output_h, output_w) {
101            (Some(output_h), Some(output_w)) if output_h != 0 && output_w != 0 => {
102                (output_h, output_w)
103            }
104            _ => {
105                return Err(invalid_window(
106                    "Unfold2d",
107                    "spatial shape and window configuration",
108                    vec![
109                        shape[2],
110                        shape[3],
111                        self.kernel_h,
112                        self.kernel_w,
113                        self.stride_h,
114                        self.stride_w,
115                        self.padding_h,
116                        self.padding_w,
117                        self.dilation_h,
118                        self.dilation_w,
119                    ],
120                ));
121            }
122        };
123        shape[1]
124            .checked_mul(self.kernel_h)
125            .and_then(|channels| channels.checked_mul(self.kernel_w))
126            .and_then(|channels| channels.checked_mul(output_h))
127            .and_then(|elements| elements.checked_mul(output_w))
128            .ok_or_else(|| {
129                invalid_window(
130                    "Unfold2d",
131                    "output element count",
132                    vec![shape[1], self.kernel_h, self.kernel_w, output_h, output_w],
133                )
134            })?;
135
136        coeus_autograd::unfold2d(
137            input,
138            self.kernel_h,
139            self.kernel_w,
140            self.stride_h,
141            self.stride_w,
142            self.padding_h,
143            self.padding_w,
144            self.dilation_h,
145            self.dilation_w,
146        )
147        .map_err(|source| ModuleError::Backend {
148            module: "Unfold2d",
149            source,
150        })
151    }
152}