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::{ElementConversion, Tolerance, ops::FloatElem};
169    type FT = FloatElem<TestBackend>;
170
171    use super::*;
172    use crate::TestBackend;
173    use crate::tensor::TensorData;
174
175    #[test]
176    fn initializer_default() {
177        TestBackend::seed(0);
178
179        let config = Conv3dConfig::new([5, 1], [5, 5, 5]);
180        let k = (config.channels[0]
181            * config.kernel_size[0]
182            * config.kernel_size[1]
183            * config.kernel_size[2]) as f64;
184        let k = (config.groups as f64 / k).sqrt().elem::<FT>();
185        let device = Default::default();
186        let conv = config.init::<TestBackend>(&device);
187
188        conv.weight.to_data().assert_within_range(-k..k);
189    }
190
191    #[test]
192    fn initializer_zeros() {
193        TestBackend::seed(0);
194
195        let config = Conv3dConfig::new([5, 2], [5, 5, 5]).with_initializer(Initializer::Zeros);
196        let device = Default::default();
197        let conv = config.init::<TestBackend>(&device);
198
199        assert_eq!(config.initializer, Initializer::Zeros);
200        conv.weight.to_data().assert_approx_eq::<FT>(
201            &TensorData::zeros::<f32, _>(conv.weight.shape()),
202            Tolerance::default(),
203        );
204    }
205
206    #[test]
207    fn initializer_fan_out() {
208        TestBackend::seed(0);
209
210        let init = Initializer::KaimingUniform {
211            gain: 1.0 / 3.0f64.sqrt(),
212            fan_out_only: true, // test that fan_out is passed to `init_with()`
213        };
214        let device = Default::default();
215        let config = Conv3dConfig::new([5, 1], [5, 5, 5]).with_initializer(init.clone());
216        let _ = config.init::<TestBackend>(&device);
217
218        assert_eq!(config.initializer, init);
219    }
220
221    #[test]
222    fn initializer_fan_with_groups_is_valid() {
223        TestBackend::seed(0);
224
225        let init = Initializer::KaimingUniform {
226            gain: 1.0 / 3.0f64.sqrt(),
227            fan_out_only: true,
228        };
229        let device = Default::default();
230        let config = Conv3dConfig::new([4, 4], [1, 1, 1])
231            .with_initializer(init.clone())
232            .with_groups(4);
233        let _ = config.init::<TestBackend>(&device);
234
235        assert_eq!(config.initializer, init);
236    }
237
238    #[test]
239    #[should_panic = "Same padding with an even kernel size is not supported"]
240    fn same_with_even_kernel_is_invalid() {
241        let device = Default::default();
242        let config = Conv3dConfig::new([4, 4], [2, 2, 2]).with_padding(PaddingConfig3d::Same);
243        let _ = config.init::<TestBackend>(&device);
244    }
245
246    #[test]
247    fn display() {
248        let config = Conv3dConfig::new([5, 1], [5, 5, 5]);
249        let conv = config.init::<TestBackend>(&Default::default());
250
251        assert_eq!(
252            alloc::format!("{conv}"),
253            "Conv3d {stride: [1, 1, 1], kernel_size: [5, 5, 5], dilation: [1, 1, 1], groups: 1, padding: Valid, params: 626}"
254        );
255    }
256
257    #[test]
258    #[should_panic = "Number of channels in input tensor and input channels of convolution must be equal. got: 4, expected: 5"]
259    fn input_channels_mismatch() {
260        let config = Conv3dConfig::new([5, 3], [3, 3, 3]);
261        let conv = config.init::<TestBackend>(&Default::default());
262
263        let input = Tensor::<TestBackend, 5>::zeros([1, 4, 10, 10, 10], &Default::default());
264        let _ = conv.forward(input);
265    }
266}