Skip to main content

coeus_nn/conv/unfold_fold/
fold1d.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*kernel_size, L_out]` back into `[N, C, output_size]`.
8///
9/// Inverse (adjoint) of [`super::Unfold1d`]. Overlapping window contributions are summed.
10/// Matches PyTorch `nn.Fold` in 1D.
11///
12/// # Shape
13/// - Input:  `[N, C * kernel_size, L_out]`
14/// - Output: `[N, C, output_size]`
15#[derive(Clone, Debug)]
16pub struct Fold1d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
17    output_size: usize,
18    kernel_size: usize,
19    stride: usize,
20    padding: usize,
21    dilation: usize,
22    _marker: PhantomData<(T, B)>,
23}
24
25impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> Fold1d<T, B> {
26    /// Create a `Fold1d` with the given hyperparameters.
27    pub fn new(
28        output_size: usize,
29        kernel_size: usize,
30        stride: usize,
31        padding: usize,
32        dilation: usize,
33    ) -> Self {
34        Self {
35            output_size,
36            kernel_size,
37            stride,
38            padding,
39            dilation,
40            _marker: PhantomData,
41        }
42    }
43}
44
45impl<T: Scalar, B: coeus_ops::BackendOps<T> + Default> Module<T, B> for Fold1d<T, B> {
46    fn parameters(&self) -> Vec<Var<T, B>> {
47        vec![]
48    }
49
50    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
51        let shape = input.tensor.shape();
52        if shape.len() != 3 {
53            return Err(ModuleError::InvalidRank {
54                module: "Fold1d",
55                expected: "3",
56                actual: shape.len(),
57            });
58        }
59        let expected_columns = checked_output_dim(
60            self.output_size,
61            self.kernel_size,
62            self.stride,
63            self.padding,
64            self.dilation,
65        )
66        .filter(|&output| output != 0)
67        .ok_or_else(|| {
68            invalid_window(
69                "Fold1d",
70                "output size, kernel, stride, padding, and dilation",
71                vec![
72                    self.output_size,
73                    self.kernel_size,
74                    self.stride,
75                    self.padding,
76                    self.dilation,
77                ],
78            )
79        })?;
80        if !shape[1].is_multiple_of(self.kernel_size) || shape[2] != expected_columns {
81            return Err(ModuleError::ShapeMismatch {
82                module: "Fold1d",
83                parameter: "folded channel and column dimensions",
84                expected: vec![self.kernel_size, expected_columns],
85                actual: vec![shape[1], shape[2]],
86            });
87        }
88
89        coeus_autograd::fold1d(
90            input,
91            self.output_size,
92            self.kernel_size,
93            self.stride,
94            self.padding,
95            self.dilation,
96        )
97        .map_err(|source| ModuleError::Backend {
98            module: "Fold1d",
99            source,
100        })
101    }
102}