burn_core/nn/pool/
avg_pool2d.rs1use crate as burn;
2use crate::nn::conv::checks::check_same_padding_support;
3
4use crate::config::Config;
5use crate::module::{Content, DisplaySettings, ModuleDisplay};
6use crate::module::{Ignored, Module};
7use crate::nn::PaddingConfig2d;
8use crate::tensor::Tensor;
9use crate::tensor::backend::Backend;
10
11use crate::tensor::module::avg_pool2d;
12
13#[derive(Config, Debug)]
15pub struct AvgPool2dConfig {
16 pub kernel_size: [usize; 2],
18 #[config(default = "[1, 1]")]
20 pub strides: [usize; 2],
21 #[config(default = "PaddingConfig2d::Valid")]
27 pub padding: PaddingConfig2d,
28 #[config(default = "true")]
30 pub count_include_pad: bool,
31}
32
33#[derive(Module, Clone, Debug)]
45#[module(custom_display)]
46pub struct AvgPool2d {
47 pub stride: [usize; 2],
49 pub kernel_size: [usize; 2],
51 pub padding: Ignored<PaddingConfig2d>,
53 pub count_include_pad: bool,
55}
56
57impl ModuleDisplay for AvgPool2d {
58 fn custom_settings(&self) -> Option<DisplaySettings> {
59 DisplaySettings::new()
60 .with_new_line_after_attribute(false)
61 .optional()
62 }
63
64 fn custom_content(&self, content: Content) -> Option<Content> {
65 content
66 .add("kernel_size", &alloc::format!("{:?}", &self.kernel_size))
67 .add("stride", &alloc::format!("{:?}", &self.stride))
68 .add("padding", &self.padding)
69 .add("count_include_pad", &self.count_include_pad)
70 .optional()
71 }
72}
73
74impl AvgPool2dConfig {
75 pub fn init(&self) -> AvgPool2d {
77 if self.padding == PaddingConfig2d::Same {
78 check_same_padding_support(&self.kernel_size);
79 }
80 AvgPool2d {
81 stride: self.strides,
82 kernel_size: self.kernel_size,
83 padding: Ignored(self.padding.clone()),
84 count_include_pad: self.count_include_pad,
85 }
86 }
87}
88
89impl AvgPool2d {
90 pub fn forward<B: Backend>(&self, input: Tensor<B, 4>) -> Tensor<B, 4> {
99 let [_batch_size, _channels_in, height_in, width_in] = input.dims();
100 let padding =
101 self.padding
102 .calculate_padding_2d(height_in, width_in, &self.kernel_size, &self.stride);
103
104 avg_pool2d(
105 input,
106 self.kernel_size,
107 self.stride,
108 padding,
109 self.count_include_pad,
110 )
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[test]
119 #[should_panic = "Same padding with an even kernel size is not supported"]
120 fn same_with_even_kernel_is_invalid() {
121 let config = AvgPool2dConfig::new([2, 2]).with_padding(PaddingConfig2d::Same);
122 let _ = config.init();
123 }
124
125 #[test]
126 fn display() {
127 let config = AvgPool2dConfig::new([3, 3]);
128
129 let layer = config.init();
130
131 assert_eq!(
132 alloc::format!("{}", layer),
133 "AvgPool2d {kernel_size: [3, 3], stride: [1, 1], padding: Valid, count_include_pad: true}"
134 );
135 }
136}