1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use crate::PaddingConfig2d;
use ruda_model::config::Config;
use ruda_model::module::Module;
use ruda_model::module::{Content, DisplaySettings, ModuleDisplay};
use ruda_model::tensor::Tensor;
use ruda_model::tensor::backend::Backend;
use ruda_model::tensor::ops::PadMode;
use ruda_model::tensor::module::max_pool2d;
/// Configuration to create a [2D max pooling](MaxPool2d) layer using the [init function](MaxPool2dConfig::init).
#[derive(Debug, Config)]
pub struct MaxPool2dConfig {
/// The size of the kernel.
pub kernel_size: [usize; 2],
/// The strides.
#[config(default = "kernel_size")]
pub strides: [usize; 2],
/// The padding configuration.
///
/// Supports symmetric and asymmetric padding. `Same` padding with even kernel sizes
/// will automatically use asymmetric padding to preserve input dimensions.
#[config(default = "PaddingConfig2d::Valid")]
pub padding: PaddingConfig2d,
/// The dilation.
#[config(default = "[1, 1]")]
pub dilation: [usize; 2],
/// If true, use ceiling instead of floor for output size calculation.
#[config(default = "false")]
pub ceil_mode: bool,
}
/// Applies a 2D max pooling over input tensors.
///
/// Should be created with [MaxPool2dConfig](MaxPool2dConfig).
#[derive(Module, Clone, Debug)]
#[module(custom_display)]
pub struct MaxPool2d {
/// The strides.
pub stride: [usize; 2],
/// The size of the kernel.
pub kernel_size: [usize; 2],
/// The padding configuration.
pub padding: PaddingConfig2d,
/// The dilation.
pub dilation: [usize; 2],
/// If true, use ceiling instead of floor for output size calculation.
pub ceil_mode: bool,
}
impl ModuleDisplay for MaxPool2d {
fn custom_settings(&self) -> Option<DisplaySettings> {
DisplaySettings::new()
.with_new_line_after_attribute(false)
.optional()
}
fn custom_content(&self, content: Content) -> Option<Content> {
content
.add("kernel_size", &alloc::format!("{:?}", &self.kernel_size))
.add("stride", &alloc::format!("{:?}", &self.stride))
.add_debug_attribute("padding", &self.padding)
.add("dilation", &alloc::format!("{:?}", &self.dilation))
.add("ceil_mode", &self.ceil_mode)
.optional()
}
}
impl MaxPool2dConfig {
/// Initialize a new [max pool 2d](MaxPool2d) module.
pub fn init(&self) -> MaxPool2d {
MaxPool2d {
stride: self.strides,
kernel_size: self.kernel_size,
padding: self.padding.clone(),
dilation: self.dilation,
ceil_mode: self.ceil_mode,
}
}
}
impl MaxPool2d {
/// Applies the forward pass on the input tensor.
///
/// See [max_pool2d](ruda_tensor::api::module::max_pool2d) for more information.
///
/// # Shapes
///
/// - input: `[batch_size, channels, height_in, width_in]`
/// - output: `[batch_size, channels, height_out, width_out]`
pub fn forward<B: Backend>(&self, input: Tensor<B, 4>) -> Tensor<B, 4> {
let [_batch_size, _channels_in, height_in, width_in] = input.dims();
// Calculate padding as pairs - handles Same, Valid, and Explicit uniformly
let ((top, bottom), (left, right)) = self.padding.calculate_padding_2d_pairs(
height_in,
width_in,
&self.kernel_size,
&self.stride,
);
// TODO: Move asymmetric padding to functional level via PoolOptions
// See: https://github.com/shuqi2077/RUDA/blob/main/THIRD_PARTY_NOTICES.md
// Handle asymmetric padding by applying explicit pad operation first
if top != bottom || left != right {
// Ruda's pad takes (left, right, top, bottom) for the last two dimensions
// Use -inf for max pooling so padded values don't affect the max
let padded = input.pad(
(left, right, top, bottom),
PadMode::Constant(f32::NEG_INFINITY),
);
// Use zero padding for the pool operation since we already padded
max_pool2d(
padded,
self.kernel_size,
self.stride,
[0, 0],
self.dilation,
self.ceil_mode,
)
} else {
// Symmetric padding
max_pool2d(
input,
self.kernel_size,
self.stride,
[top, left],
self.dilation,
self.ceil_mode,
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::TestBackend;
use rstest::rstest;
#[test]
fn same_with_even_kernel_uses_asymmetric_padding() {
let device = Default::default();
let config = MaxPool2dConfig::new([2, 2])
.with_strides([1, 1])
.with_padding(PaddingConfig2d::Same);
let pool = config.init();
// Input: [batch=1, channels=2, height=5, width=5]
let input = Tensor::<TestBackend, 4>::ones([1, 2, 5, 5], &device);
let output = pool.forward(input);
// Same padding should preserve spatial dimensions
assert_eq!(output.dims(), [1, 2, 5, 5]);
}
#[test]
fn display() {
let config = MaxPool2dConfig::new([3, 3]);
let layer = config.init();
assert_eq!(
alloc::format!("{layer}"),
"MaxPool2d {kernel_size: [3, 3], stride: [3, 3], padding: Valid, dilation: [1, 1], ceil_mode: false}"
);
}
#[rstest]
#[case([2, 2])]
#[case([1, 2])]
fn default_strides_match_kernel_size(#[case] kernel_size: [usize; 2]) {
let config = MaxPool2dConfig::new(kernel_size);
assert_eq!(
config.strides, kernel_size,
"Expected strides ({:?}) to match kernel size ({:?}) in default MaxPool2dConfig::new constructor",
config.strides, config.kernel_size
);
}
#[test]
fn asymmetric_padding_forward() {
let device = Default::default();
// Create max pool with asymmetric padding: top=1, left=2, bottom=3, right=4
let config = MaxPool2dConfig::new([3, 3])
.with_strides([1, 1])
.with_padding(PaddingConfig2d::Explicit(1, 2, 3, 4));
let pool = config.init();
// Input: [batch=1, channels=2, height=4, width=5]
let input = Tensor::<TestBackend, 4>::ones([1, 2, 4, 5], &device);
let output = pool.forward(input);
// Height: 4 + 1 + 3 = 8, output = (8 - 3) / 1 + 1 = 6
// Width: 5 + 2 + 4 = 11, output = (11 - 3) / 1 + 1 = 9
assert_eq!(output.dims(), [1, 2, 6, 9]);
}
#[test]
fn symmetric_explicit_padding_forward() {
let device = Default::default();
// Create max pool with symmetric explicit padding: top=2, left=2, bottom=2, right=2
let config = MaxPool2dConfig::new([3, 3])
.with_strides([1, 1])
.with_padding(PaddingConfig2d::Explicit(2, 2, 2, 2));
let pool = config.init();
// Input: [batch=1, channels=2, height=4, width=5]
let input = Tensor::<TestBackend, 4>::ones([1, 2, 4, 5], &device);
let output = pool.forward(input);
// Height: 4 + 2 + 2 = 8, output = (8 - 3) / 1 + 1 = 6
// Width: 5 + 2 + 2 = 9, output = (9 - 3) / 1 + 1 = 7
assert_eq!(output.dims(), [1, 2, 6, 7]);
}
}