burn_core/nn/conv/
conv3d.rs

1use alloc::format;
2
3use crate as burn;
4
5use crate::config::Config;
6use crate::module::{Content, DisplaySettings, Ignored, Module, ModuleDisplay, Param};
7use crate::nn::Initializer;
8use crate::nn::PaddingConfig3d;
9use crate::tensor::Tensor;
10use crate::tensor::backend::Backend;
11use crate::tensor::module::conv3d;
12use crate::tensor::ops::ConvOptions;
13
14use crate::nn::conv::checks;
15
16/// Configuration to create a [3D convolution](Conv3d) layer, using the [init function](Conv3dConfig::init).
17#[derive(Config, Debug)]
18pub struct Conv3dConfig {
19    /// The number of channels.
20    pub channels: [usize; 2],
21    /// The size of the kernel.
22    pub kernel_size: [usize; 3],
23    /// The stride of the convolution.
24    #[config(default = "[1, 1, 1]")]
25    pub stride: [usize; 3],
26    /// Spacing between kernel elements.
27    #[config(default = "[1, 1, 1]")]
28    pub dilation: [usize; 3],
29    /// Controls the connections between input and output channels.
30    #[config(default = "1")]
31    pub groups: usize,
32    /// The padding configuration.
33    #[config(default = "PaddingConfig3d::Valid")]
34    pub padding: PaddingConfig3d,
35    /// If bias should be added to the output.
36    #[config(default = true)]
37    pub bias: bool,
38    /// The type of function used to initialize neural network parameters
39    #[config(
40        default = "Initializer::KaimingUniform{gain:1.0/num_traits::Float::sqrt(3.0),fan_out_only:false}"
41    )]
42    pub initializer: Initializer,
43}
44
45/// Applies a 3D convolution over input tensors.
46///
47/// Should be created with [Conv3dConfig].
48#[derive(Module, Debug)]
49#[module(custom_display)]
50pub struct Conv3d<B: Backend> {
51    /// Tensor of shape `[channels_out, channels_in / groups, kernel_size_1, kernel_size_2, kernel_size_3]`
52    pub weight: Param<Tensor<B, 5>>,
53    /// Tensor of shape `[channels_out]`
54    pub bias: Option<Param<Tensor<B, 1>>>,
55    /// Stride of the convolution.
56    pub stride: [usize; 3],
57    /// Size of the kernel.
58    pub kernel_size: [usize; 3],
59    /// Spacing between kernel elements.
60    pub dilation: [usize; 3],
61    /// Controls the connections between input and output channels.
62    pub groups: usize,
63    /// The padding configuration.
64    pub padding: Ignored<PaddingConfig3d>,
65}
66
67impl Conv3dConfig {
68    /// Initialize a new [conv3d](Conv3d) module.
69    pub fn init<B: Backend>(&self, device: &B::Device) -> Conv3d<B> {
70        checks::checks_channels_div_groups(self.channels[0], self.channels[1], self.groups);
71        if self.padding == PaddingConfig3d::Same {
72            checks::check_same_padding_support(&self.kernel_size);
73        }
74
75        let shape = [
76            self.channels[1],
77            self.channels[0] / self.groups,
78            self.kernel_size[0],
79            self.kernel_size[1],
80            self.kernel_size[2],
81        ];
82
83        let k = self.kernel_size.iter().product::<usize>();
84        let fan_in = self.channels[0] / self.groups * k;
85        let fan_out = self.channels[1] / self.groups * k;
86
87        let weight = self
88            .initializer
89            .init_with(shape, Some(fan_in), Some(fan_out), device);
90        let mut bias = None;
91
92        if self.bias {
93            bias = Some(self.initializer.init_with(
94                [self.channels[1]],
95                Some(fan_in),
96                Some(fan_out),
97                device,
98            ));
99        }
100
101        Conv3d {
102            weight,
103            bias,
104            stride: self.stride,
105            kernel_size: self.kernel_size,
106            dilation: self.dilation,
107            padding: Ignored(self.padding.clone()),
108            groups: self.groups,
109        }
110    }
111}
112
113impl<B: Backend> ModuleDisplay for Conv3d<B> {
114    fn custom_settings(&self) -> Option<DisplaySettings> {
115        DisplaySettings::new()
116            .with_new_line_after_attribute(false)
117            .optional()
118    }
119
120    fn custom_content(&self, content: Content) -> Option<Content> {
121        // Since padding does not implement ModuleDisplay, we need to format it manually.
122        let padding_formatted = format!("{}", &self.padding);
123
124        // Format the stride, kernel_size and dilation as strings, formatted as arrays instead of indexed.
125        let stride = format!("{:?}", self.stride);
126        let kernel_size = format!("{:?}", self.kernel_size);
127        let dilation = format!("{:?}", self.dilation);
128
129        content
130            .add("stride", &stride)
131            .add("kernel_size", &kernel_size)
132            .add("dilation", &dilation)
133            .add("groups", &self.groups)
134            .add("padding", &padding_formatted)
135            .optional()
136    }
137}
138
139impl<B: Backend> Conv3d<B> {
140    /// Applies the forward pass on the input tensor.
141    ///
142    /// See [conv3d](crate::tensor::module::conv3d) for more information.
143    ///
144    /// # Shapes
145    ///
146    /// - input: `[batch_size, channels_in, depth_in, height_in, width_in]`
147    /// - output: `[batch_size, channels_out, depth_out, height_out, width_out]`
148    pub fn forward(&self, input: Tensor<B, 5>) -> Tensor<B, 5> {
149        let [_batch_size, _channels_in, depth_in, height_in, width_in] = input.dims();
150        let padding = self.padding.calculate_padding_3d(
151            depth_in,
152            height_in,
153            width_in,
154            &self.kernel_size,
155            &self.stride,
156        );
157        conv3d(
158            input,
159            self.weight.val(),
160            self.bias.as_ref().map(|bias| bias.val()),
161            ConvOptions::new(self.stride, padding, self.dilation, self.groups),
162        )
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use burn_tensor::Tolerance;
169
170    use super::*;
171    use crate::TestBackend;
172    use crate::tensor::TensorData;
173
174    #[test]
175    fn initializer_default() {
176        TestBackend::seed(0);
177
178        let config = Conv3dConfig::new([5, 1], [5, 5, 5]);
179        let k = (config.channels[0]
180            * config.kernel_size[0]
181            * config.kernel_size[1]
182            * config.kernel_size[2]) as f64;
183        let k = (config.groups as f64 / k).sqrt() as f32;
184        let device = Default::default();
185        let conv = config.init::<TestBackend>(&device);
186
187        conv.weight.to_data().assert_within_range(-k..k);
188    }
189
190    #[test]
191    fn initializer_zeros() {
192        TestBackend::seed(0);
193
194        let config = Conv3dConfig::new([5, 2], [5, 5, 5]).with_initializer(Initializer::Zeros);
195        let device = Default::default();
196        let conv = config.init::<TestBackend>(&device);
197
198        assert_eq!(config.initializer, Initializer::Zeros);
199        conv.weight.to_data().assert_approx_eq::<f32>(
200            &TensorData::zeros::<f32, _>(conv.weight.shape()),
201            Tolerance::default(),
202        );
203    }
204
205    #[test]
206    fn initializer_fan_out() {
207        TestBackend::seed(0);
208
209        let init = Initializer::KaimingUniform {
210            gain: 1.0 / 3.0f64.sqrt(),
211            fan_out_only: true, // test that fan_out is passed to `init_with()`
212        };
213        let device = Default::default();
214        let config = Conv3dConfig::new([5, 1], [5, 5, 5]).with_initializer(init.clone());
215        let _ = config.init::<TestBackend>(&device);
216
217        assert_eq!(config.initializer, init);
218    }
219
220    #[test]
221    fn initializer_fan_with_groups_is_valid() {
222        TestBackend::seed(0);
223
224        let init = Initializer::KaimingUniform {
225            gain: 1.0 / 3.0f64.sqrt(),
226            fan_out_only: true,
227        };
228        let device = Default::default();
229        let config = Conv3dConfig::new([4, 4], [1, 1, 1])
230            .with_initializer(init.clone())
231            .with_groups(4);
232        let _ = config.init::<TestBackend>(&device);
233
234        assert_eq!(config.initializer, init);
235    }
236
237    #[test]
238    #[should_panic = "Same padding with an even kernel size is not supported"]
239    fn same_with_even_kernel_is_invalid() {
240        let device = Default::default();
241        let config = Conv3dConfig::new([4, 4], [2, 2, 2]).with_padding(PaddingConfig3d::Same);
242        let _ = config.init::<TestBackend>(&device);
243    }
244
245    #[test]
246    fn display() {
247        let config = Conv3dConfig::new([5, 1], [5, 5, 5]);
248        let conv = config.init::<TestBackend>(&Default::default());
249
250        assert_eq!(
251            alloc::format!("{}", conv),
252            "Conv3d {stride: [1, 1, 1], kernel_size: [5, 5, 5], dilation: [1, 1, 1], groups: 1, padding: Valid, params: 626}"
253        );
254    }
255
256    #[test]
257    #[should_panic = "Number of channels in input tensor and input channels of convolution must be equal. got: 4, expected: 5"]
258    fn input_channels_mismatch() {
259        let config = Conv3dConfig::new([5, 3], [3, 3, 3]);
260        let conv = config.init::<TestBackend>(&Default::default());
261
262        let input = Tensor::<TestBackend, 5>::zeros([1, 4, 10, 10, 10], &Default::default());
263        let _ = conv.forward(input);
264    }
265}