burn_core/nn/conv/
conv_transpose3d.rs

1use alloc::format;
2
3use crate as burn;
4
5use crate::config::Config;
6use crate::module::Content;
7use crate::module::DisplaySettings;
8use crate::module::Module;
9use crate::module::ModuleDisplay;
10use crate::module::Param;
11use crate::nn::Initializer;
12use crate::nn::conv::checks;
13use crate::tensor::Tensor;
14use crate::tensor::backend::Backend;
15use crate::tensor::module::conv_transpose3d;
16use crate::tensor::ops::ConvTransposeOptions;
17
18/// Configuration to create an [3D transposed convolution](ConvTranspose3d) layer
19/// using the [init function](ConvTranspose3dConfig::init).
20#[derive(Config, Debug)]
21pub struct ConvTranspose3dConfig {
22    /// The number of channels.
23    pub channels: [usize; 2],
24    /// The size of the kernel.
25    pub kernel_size: [usize; 3],
26    /// The stride of the convolution.
27    #[config(default = "[1, 1, 1]")]
28    pub stride: [usize; 3],
29    /// Spacing between kernel elements.
30    #[config(default = "[1, 1, 1]")]
31    pub dilation: [usize; 3],
32    /// Controls the connections between input and output channels.
33    #[config(default = "1")]
34    pub groups: usize,
35    /// The padding configuration.
36    #[config(default = "[0, 0, 0]")]
37    pub padding: [usize; 3],
38    /// The padding output configuration.
39    #[config(default = "[0, 0, 0]")]
40    pub padding_out: [usize; 3],
41    /// If bias should be added to the output.
42    #[config(default = true)]
43    pub bias: bool,
44    /// The type of function used to initialize neural network parameters
45    #[config(
46        default = "Initializer::KaimingUniform{gain:1.0/num_traits::Float::sqrt(3.0),fan_out_only:false}"
47    )]
48    pub initializer: Initializer,
49}
50
51/// Applies a 3D transposed convolution over input tensors.
52#[derive(Module, Debug)]
53#[module(custom_display)]
54pub struct ConvTranspose3d<B: Backend> {
55    /// Tensor of shape `[channels_in, channels_out / groups, kernel_size_1, kernel_size_2, kernel_size_3]`
56    pub weight: Param<Tensor<B, 5>>,
57    /// Tensor of shape `[channels_out]`
58    pub bias: Option<Param<Tensor<B, 1>>>,
59    /// Stride of the convolution.
60    pub stride: [usize; 3],
61    /// Size of the kernel.
62    pub kernel_size: [usize; 3],
63    /// Spacing between kernel elements.
64    pub dilation: [usize; 3],
65    /// Controls the connections between input and output channels.
66    pub groups: usize,
67    /// Padding configuration.
68    pub padding: [usize; 3],
69    /// Padding output configuration.
70    pub padding_out: [usize; 3],
71    /// Number of channels.
72    pub channels: [usize; 2],
73}
74
75impl<B: Backend> ModuleDisplay for ConvTranspose3d<B> {
76    fn custom_settings(&self) -> Option<DisplaySettings> {
77        DisplaySettings::new()
78            .with_new_line_after_attribute(false)
79            .optional()
80    }
81
82    fn custom_content(&self, content: Content) -> Option<Content> {
83        content
84            .add("channels", &format!("{:?}", &self.channels))
85            .add("stride", &format!("{:?}", &self.stride))
86            .add("kernel_size", &format!("{:?}", &self.kernel_size))
87            .add("dilation", &format!("{:?}", &self.dilation))
88            .add("groups", &self.groups)
89            .add("padding", &format!("{:?}", &self.padding))
90            .add("padding_out", &format!("{:?}", &self.padding_out))
91            .optional()
92    }
93}
94
95impl ConvTranspose3dConfig {
96    /// Initialize a new [conv transpose 2d](ConvTranspose3d) module.
97    pub fn init<B: Backend>(&self, device: &B::Device) -> ConvTranspose3d<B> {
98        checks::checks_channels_div_groups(self.channels[0], self.channels[1], self.groups);
99
100        let shape = [
101            self.channels[0],
102            self.channels[1] / self.groups,
103            self.kernel_size[0],
104            self.kernel_size[1],
105            self.kernel_size[2],
106        ];
107
108        let fan_in = self.channels[1] / self.groups * self.kernel_size.iter().product::<usize>();
109        let weight = self
110            .initializer
111            .init_with(shape, Some(fan_in), None, device);
112        let mut bias = None;
113
114        if self.bias {
115            bias = Some(
116                self.initializer
117                    .init_with([self.channels[1]], Some(fan_in), None, device),
118            );
119        }
120
121        ConvTranspose3d {
122            weight,
123            bias,
124            stride: self.stride,
125            kernel_size: self.kernel_size,
126            dilation: self.dilation,
127            groups: self.groups,
128            padding: self.padding,
129            padding_out: self.padding_out,
130            channels: self.channels,
131        }
132    }
133}
134
135impl<B: Backend> ConvTranspose3d<B> {
136    /// Applies the forward pass on the input tensor.
137    ///
138    /// See also [conv_transpose3d](crate::tensor::module::conv_transpose3d).
139    ///
140    /// # Shapes
141    ///
142    /// - input: `[batch_size, channels_in, depth_in, height_in, width_in]`
143    /// - output: `[batch_size, channels_out, depth_out, height_out, width_out]`
144    pub fn forward(&self, input: Tensor<B, 5>) -> Tensor<B, 5> {
145        conv_transpose3d(
146            input,
147            self.weight.val(),
148            self.bias.as_ref().map(|bias| bias.val()),
149            ConvTransposeOptions::new(
150                self.stride,
151                self.padding,
152                self.padding_out,
153                self.dilation,
154                self.groups,
155            ),
156        )
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use burn_tensor::Tolerance;
163
164    use super::*;
165    use crate::TestBackend;
166    use crate::tensor::TensorData;
167
168    #[test]
169    fn initializer_default() {
170        TestBackend::seed(0);
171
172        let config = ConvTranspose3dConfig::new([5, 1], [5, 5, 5]);
173        let k = (config.channels[1]
174            * config.kernel_size[0]
175            * config.kernel_size[1]
176            * config.kernel_size[2]) as f64;
177        let k = (config.groups as f64 / k).sqrt() as f32;
178        let conv = config.init::<TestBackend>(&Default::default());
179
180        conv.weight.to_data().assert_within_range(-k..k);
181    }
182
183    #[test]
184    fn initializer_zeros() {
185        TestBackend::seed(0);
186
187        let config =
188            ConvTranspose3dConfig::new([5, 2], [5, 5, 5]).with_initializer(Initializer::Zeros);
189        let conv = config.init::<TestBackend>(&Default::default());
190
191        assert_eq!(config.initializer, Initializer::Zeros);
192        conv.weight.to_data().assert_approx_eq::<f32>(
193            &TensorData::zeros::<f32, _>(conv.weight.shape()),
194            Tolerance::default(),
195        );
196    }
197
198    #[test]
199    fn display() {
200        let config = ConvTranspose3dConfig::new([5, 2], [5, 5, 5]);
201        let conv = config.init::<TestBackend>(&Default::default());
202
203        assert_eq!(
204            format!("{}", conv),
205            "ConvTranspose3d {channels: [5, 2], stride: [1, 1, 1], kernel_size: [5, 5, 5], dilation: [1, 1, 1], groups: 1, padding: [0, 0, 0], padding_out: [0, 0, 0], params: 1252}"
206        );
207    }
208
209    #[test]
210    #[should_panic = "Number of channels in input tensor and input channels of convolution must be equal. got: 4, expected: 5"]
211    fn input_channels_mismatch() {
212        let config = ConvTranspose3dConfig::new([5, 3], [3, 3, 3]);
213        let conv = config.init::<TestBackend>(&Default::default());
214
215        let input = Tensor::<TestBackend, 5>::zeros([1, 4, 10, 10, 10], &Default::default());
216        let _ = conv.forward(input);
217    }
218}