use crate::{PaddingConfig2d, padding::dilated_kernel_size};
use ruda_model::config::Config;
use ruda_model::module::Module;
use ruda_model::module::{Content, DisplaySettings, ModuleDisplay};
use ruda_model::tensor::{Int, Tensor};
use ruda_model::tensor::backend::Backend;
use ruda_model::tensor::module::{max_pool2d_padded, max_pool2d_with_indices_padded};
#[derive(Debug, Config)]
pub struct MaxPool2dConfig {
pub kernel_size: [usize; 2],
#[config(default = "kernel_size")]
pub strides: [usize; 2],
#[config(default = "PaddingConfig2d::Valid")]
pub padding: PaddingConfig2d,
#[config(default = "[1, 1]")]
pub dilation: [usize; 2],
#[config(default = "false")]
pub ceil_mode: bool,
}
#[derive(Module, Clone, Debug)]
#[module(custom_display)]
pub struct MaxPool2d {
pub stride: [usize; 2],
pub kernel_size: [usize; 2],
pub padding: PaddingConfig2d,
pub dilation: [usize; 2],
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 {
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 {
pub fn forward_with_indices<B: Backend>(&self, input: Tensor<B, 4>)
-> (Tensor<B, 4>, Tensor<B, 4, Int>) {
let [_, _, height, width] = input.dims();
let effective = core::array::from_fn(|axis| {
dilated_kernel_size(self.kernel_size[axis], self.dilation[axis])
});
let (height_padding, width_padding) = self.padding.calculate_padding_2d_pairs(
height, width, &effective, &self.stride,
);
max_pool2d_with_indices_padded(input, self.kernel_size, self.stride,
[height_padding, width_padding], self.dilation, self.ceil_mode)
}
pub fn forward<B: Backend>(&self, input: Tensor<B, 4>) -> Tensor<B, 4> {
let [_batch_size, _channels_in, height_in, width_in] = input.dims();
let effective = core::array::from_fn(|axis| {
dilated_kernel_size(self.kernel_size[axis], self.dilation[axis])
});
let ((top, bottom), (left, right)) = self.padding.calculate_padding_2d_pairs(
height_in,
width_in,
&effective,
&self.stride,
);
max_pool2d_padded(input, self.kernel_size, self.stride, [(top, bottom), (left, right)],
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();
let input = Tensor::<TestBackend, 4>::ones([1, 2, 5, 5], &device);
let output = pool.forward(input);
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();
let config = MaxPool2dConfig::new([3, 3])
.with_strides([1, 1])
.with_padding(PaddingConfig2d::Explicit(1, 2, 3, 4));
let pool = config.init();
let input = Tensor::<TestBackend, 4>::ones([1, 2, 4, 5], &device);
let output = pool.forward(input);
assert_eq!(output.dims(), [1, 2, 6, 9]);
}
#[test]
fn symmetric_explicit_padding_forward() {
let device = Default::default();
let config = MaxPool2dConfig::new([3, 3])
.with_strides([1, 1])
.with_padding(PaddingConfig2d::Explicit(2, 2, 2, 2));
let pool = config.init();
let input = Tensor::<TestBackend, 4>::ones([1, 2, 4, 5], &device);
let output = pool.forward(input);
assert_eq!(output.dims(), [1, 2, 6, 7]);
}
}