Skip to main content

coeus_nn/conv/unfold_fold/
fold2d.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/// Accumulates `[N, C*kH*kW, H_out*W_out]` back into `[N, C, output_h, output_w]`.
8///
9/// Inverse (adjoint) of [`super::Unfold2d`]. Overlapping contributions are summed.
10/// Matches PyTorch `nn.Fold`.
11#[derive(Clone, Debug)]
12pub struct Fold2d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
13    output_h: usize,
14    output_w: usize,
15    kernel_h: usize,
16    kernel_w: usize,
17    stride_h: usize,
18    stride_w: usize,
19    padding_h: usize,
20    padding_w: usize,
21    dilation_h: usize,
22    dilation_w: usize,
23    _marker: PhantomData<(T, B)>,
24}
25
26impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> Fold2d<T, B> {
27    /// Create `Fold2d` with the target output size and square kernel parameters.
28    pub fn new(
29        output_h: usize,
30        output_w: usize,
31        kernel_size: usize,
32        stride: usize,
33        padding: usize,
34        dilation: usize,
35    ) -> Self {
36        Self {
37            output_h,
38            output_w,
39            kernel_h: kernel_size,
40            kernel_w: kernel_size,
41            stride_h: stride,
42            stride_w: stride,
43            padding_h: padding,
44            padding_w: padding,
45            dilation_h: dilation,
46            dilation_w: dilation,
47            _marker: PhantomData,
48        }
49    }
50}
51
52impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Fold2d<T, B> {
53    fn parameters(&self) -> Vec<Var<T, B>> {
54        vec![]
55    }
56
57    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
58        let shape = input.tensor.shape();
59        if shape.len() != 3 {
60            return Err(ModuleError::InvalidRank {
61                module: "Fold2d",
62                expected: "3",
63                actual: shape.len(),
64            });
65        }
66        let kernel_area = self
67            .kernel_h
68            .checked_mul(self.kernel_w)
69            .filter(|&area| area != 0)
70            .ok_or_else(|| {
71                invalid_window(
72                    "Fold2d",
73                    "kernel dimensions",
74                    vec![self.kernel_h, self.kernel_w],
75                )
76            })?;
77        let output_rows = checked_output_dim(
78            self.output_h,
79            self.kernel_h,
80            self.stride_h,
81            self.padding_h,
82            self.dilation_h,
83        );
84        let output_columns = checked_output_dim(
85            self.output_w,
86            self.kernel_w,
87            self.stride_w,
88            self.padding_w,
89            self.dilation_w,
90        );
91        let expected_windows = output_rows
92            .zip(output_columns)
93            .and_then(|(rows, columns)| rows.checked_mul(columns))
94            .filter(|&windows| windows != 0)
95            .ok_or_else(|| {
96                invalid_window(
97                    "Fold2d",
98                    "output shape and window configuration",
99                    vec![
100                        self.output_h,
101                        self.output_w,
102                        self.kernel_h,
103                        self.kernel_w,
104                        self.stride_h,
105                        self.stride_w,
106                        self.padding_h,
107                        self.padding_w,
108                        self.dilation_h,
109                        self.dilation_w,
110                    ],
111                )
112            })?;
113        if !shape[1].is_multiple_of(kernel_area) || shape[2] != expected_windows {
114            return Err(ModuleError::ShapeMismatch {
115                module: "Fold2d",
116                parameter: "folded channel and window dimensions",
117                expected: vec![kernel_area, expected_windows],
118                actual: vec![shape[1], shape[2]],
119            });
120        }
121
122        coeus_autograd::fold2d(
123            input,
124            self.output_h,
125            self.output_w,
126            self.kernel_h,
127            self.kernel_w,
128            self.stride_h,
129            self.stride_w,
130            self.padding_h,
131            self.padding_w,
132            self.dilation_h,
133            self.dilation_w,
134        )
135        .map_err(|source| ModuleError::Backend {
136            module: "Fold2d",
137            source,
138        })
139    }
140}