Skip to main content

onnx_ir/node/
max_pool2d.rs

1//! # MaxPool (2D)
2//!
3//! 2D max pooling operation.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__MaxPool.html>
6//!
7//! ## Opset Versions
8//! - **Opset 1**: Initial version with basic max pooling operation.
9//! - **Opset 8**: Added optional Indices output and the `storage_order` attribute.
10//! - **Opset 10**: Added `ceil_mode` attribute to use ceiling instead of floor for output shape calculation.
11//! - **Opset 11**: Added support for dilation; updated padding semantics.
12//! - **Opset 12**: Added support for int8, uint8 data types; clarified behavior with negative padding.
13//!
14//! **Implementation Note**: Accepts 1-2 outputs (Y required, optional Indices output).
15//! Indices are typed as int64 with the input's rank.
16//!
17//! ## Missing Test Coverage
18//! - TODO: No test for dilation > 1 with opset < 11 - Should reject dilation in older opsets
19//! - TODO: No test for int8/uint8 dtypes - Opset 12+ supports integer types
20//! - TODO: No test for kernel_shape validation - Missing kernel_shape attribute should be rejected
21//! - TODO: No test for negative padding values - Opset 12+ allows negative padding
22//! - TODO: No test for edge case: kernel larger than input dimension
23//! - TODO: No test validating input is 4D (N x C x H x W) - Lower/higher rank should be rejected
24//! - TODO: No test for asymmetric kernel sizes - e.g., kernel=[3, 5]
25use derive_new::new;
26use onnx_ir_derive::NodeBuilder;
27
28use crate::ir::{ArgType, Argument, DType, Node, RawNode, TensorType};
29use crate::node::padding::{AutoPad, PaddingConfig2d, padding_config_2d};
30use crate::processor::{
31    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
32};
33
34/// Configuration for MaxPool2d operations
35#[derive(Debug, Clone, new)]
36pub struct MaxPool2dConfig {
37    /// Kernel size [height, width]
38    pub kernel_size: [usize; 2],
39    /// Stride [height, width]
40    pub strides: [usize; 2],
41    /// Padding configuration
42    pub padding: PaddingConfig2d,
43    /// Dilation [height, width]
44    pub dilation: [usize; 2],
45    /// Whether to use ceil mode for output size calculation (opset 10+)
46    pub ceil_mode: bool,
47    /// Auto padding mode
48    pub auto_pad: AutoPad,
49    /// Layout of the optional Indices output: 0 flattens row-major (default), 1
50    /// column-major within each spatial plane.
51    #[new(default)]
52    pub storage_order: i64,
53}
54
55/// Node representation for MaxPool2d operation
56#[derive(Debug, Clone, NodeBuilder)]
57pub struct MaxPool2dNode {
58    pub name: String,
59    pub inputs: Vec<Argument>,
60    pub outputs: Vec<Argument>,
61    pub config: MaxPool2dConfig,
62}
63
64impl MaxPool2dConfig {
65    /// Set the strides
66    pub fn with_strides(mut self, strides: [usize; 2]) -> Self {
67        self.strides = strides;
68        self
69    }
70
71    /// Set the padding configuration
72    pub fn with_padding(mut self, padding: PaddingConfig2d) -> Self {
73        self.padding = padding;
74        self
75    }
76
77    /// Set the dilation
78    pub fn with_dilation(mut self, dilation: [usize; 2]) -> Self {
79        self.dilation = dilation;
80        self
81    }
82}
83
84pub(crate) struct MaxPool2dProcessor;
85
86impl NodeProcessor for MaxPool2dProcessor {
87    type Config = MaxPool2dConfig;
88
89    fn spec(&self) -> NodeSpec {
90        NodeSpec {
91            min_opset: 1,
92            max_opset: None,
93            inputs: InputSpec::AtLeast(1),
94            outputs: OutputSpec::Range(1, 2),
95        }
96    }
97
98    fn infer_types(
99        &self,
100        node: &mut RawNode,
101        opset: usize,
102        _output_preferences: &OutputPreferences,
103    ) -> Result<(), ProcessError> {
104        // TODO: Validate input tensor is 4D (N x C x H x W) - Lower or higher rank should be rejected - burn/crates/onnx-ir/src/node/max_pool2d.rs:101
105        // TODO: Validate input dtype - int8/uint8 support requires opset 12+ - burn/crates/onnx-ir/src/node/max_pool2d.rs:101
106
107        // Validate attributes before extracting config
108        // TODO: Validate required kernel_shape attribute is present - Missing kernel_shape should cause error - burn/crates/onnx-ir/src/node/max_pool2d.rs:112
109        for (key, value) in node.attrs.iter() {
110            match key.as_str() {
111                "kernel_shape" | "strides" | "pads" => {}
112                "storage_order" => {}
113                "dilations" => {
114                    // Dilation support requires opset 11+
115                    let dilations = value.clone().into_i64s()?;
116                    if dilations.iter().any(|&d| d != 1) && opset < 11 {
117                        return Err(ProcessError::Custom(format!(
118                            "MaxPool: dilation requires opset 11+, got opset {}",
119                            opset
120                        )));
121                    }
122                }
123                "auto_pad" => {
124                    AutoPad::parse(&value.clone().into_string()?)?;
125                }
126                "ceil_mode" => {
127                    // ceil_mode support requires opset 10+
128                    let ceil_mode = value.clone().into_i64()?;
129                    if ceil_mode != 0 && opset < 10 {
130                        return Err(ProcessError::Custom(format!(
131                            "MaxPool: ceil_mode requires opset 10+, got opset {}",
132                            opset
133                        )));
134                    }
135                }
136                _ => {}
137            }
138        }
139
140        crate::node::padding::validate_auto_pad(node)?;
141
142        crate::node::padding::pool_output_type(node)?;
143
144        // The optional Indices output holds int64 positions into the flattened input.
145        if let Some(indices) = node.outputs.get_mut(1) {
146            let rank = node.inputs[0].ty.rank();
147            indices.ty = ArgType::Tensor(TensorType {
148                dtype: DType::I64,
149                rank,
150                static_shape: None,
151            });
152        }
153
154        Ok(())
155    }
156
157    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
158        let mut kernel_shape = Vec::new();
159        let mut strides = vec![1, 1];
160        let mut pads = vec![0, 0, 0, 0];
161        let mut dilations = vec![1, 1];
162        let mut ceil_mode: i64 = 0;
163        let mut auto_pad = AutoPad::NotSet;
164        let mut storage_order = 0;
165
166        for (key, value) in node.attrs.iter() {
167            match key.as_str() {
168                "kernel_shape" => kernel_shape = value.clone().into_i64s()?,
169                "strides" => strides = value.clone().into_i64s()?,
170                "pads" => pads = value.clone().into_i64s()?,
171                "dilations" => dilations = value.clone().into_i64s()?,
172                "ceil_mode" => ceil_mode = value.clone().into_i64()?,
173                "auto_pad" => auto_pad = AutoPad::parse(&value.clone().into_string()?)?,
174                "storage_order" => storage_order = value.clone().into_i64()?,
175                _ => {}
176            }
177        }
178
179        if !matches!(storage_order, 0 | 1) {
180            return Err(ProcessError::InvalidAttribute {
181                name: "storage_order".to_string(),
182                reason: format!("expected 0 (row major) or 1 (column major), got {storage_order}"),
183            });
184        }
185
186        crate::node::padding::check_attr_len("kernel_shape", &kernel_shape, 2)?;
187        crate::node::padding::check_attr_len("strides", &strides, 2)?;
188        crate::node::padding::check_attr_len("dilations", &dilations, 2)?;
189
190        let padding = padding_config_2d(&pads)?;
191
192        let mut config = MaxPool2dConfig::new(
193            [kernel_shape[0] as usize, kernel_shape[1] as usize],
194            [strides[0] as usize, strides[1] as usize],
195            padding,
196            [dilations[0] as usize, dilations[1] as usize],
197            ceil_mode == 1,
198            auto_pad,
199        );
200        config.storage_order = storage_order;
201
202        Ok(config)
203    }
204
205    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
206        let config = self.extract_config(&builder, opset)?;
207
208        Ok(Node::MaxPool2d(MaxPool2dNode {
209            name: builder.name,
210            inputs: builder.inputs,
211            outputs: builder.outputs,
212            config,
213        }))
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use crate::ir::NodeType;
221    use crate::node::test_utils::TestNodeBuilder;
222
223    fn create_test_node(
224        kernel_shape: Vec<i64>,
225        strides: Vec<i64>,
226        pads: Vec<i64>,
227        dilations: Vec<i64>,
228        ceil_mode: i64,
229        auto_pad: Option<&str>,
230    ) -> RawNode {
231        let mut builder = TestNodeBuilder::new(NodeType::MaxPool2d, "test_maxpool2d")
232            .input_tensor_f32("data", 4, None)
233            .output_tensor_f32("output", 4, None)
234            .attr_ints("kernel_shape", kernel_shape)
235            .attr_ints("strides", strides)
236            .attr_ints("pads", pads)
237            .attr_int("ceil_mode", ceil_mode)
238            .attr_ints("dilations", dilations);
239        if let Some(auto_pad) = auto_pad {
240            builder = builder.attr_string("auto_pad", auto_pad);
241        }
242        builder.build()
243    }
244
245    #[test]
246    fn test_max_pool2d_config_basic() {
247        let node = create_test_node(
248            vec![3, 3],
249            vec![1, 1],
250            vec![0, 0, 0, 0],
251            vec![1, 1],
252            0,
253            None,
254        );
255        let mut node = node;
256        let processor = MaxPool2dProcessor;
257        let prefs = OutputPreferences::new();
258        let config = processor.extract_config(&node, 16).unwrap();
259        processor.infer_types(&mut node, 16, &prefs).unwrap();
260
261        assert_eq!(config.kernel_size, [3, 3]);
262        assert_eq!(config.strides, [1, 1]);
263        assert_eq!(config.dilation, [1, 1]);
264        assert!(!config.ceil_mode);
265        assert!(matches!(config.padding, PaddingConfig2d::Valid));
266    }
267
268    #[test]
269    fn test_max_pool2d_config_with_padding() {
270        let node = create_test_node(
271            vec![2, 2],
272            vec![2, 2],
273            vec![1, 1, 1, 1],
274            vec![1, 1],
275            0,
276            None,
277        );
278        let mut node = node;
279        let processor = MaxPool2dProcessor;
280        let prefs = OutputPreferences::new();
281        let config = processor.extract_config(&node, 16).unwrap();
282        processor.infer_types(&mut node, 16, &prefs).unwrap();
283
284        assert_eq!(config.kernel_size, [2, 2]);
285        assert_eq!(config.strides, [2, 2]);
286        assert_eq!(config.dilation, [1, 1]);
287        assert!(matches!(
288            config.padding,
289            PaddingConfig2d::Explicit(1, 1, 1, 1)
290        ));
291    }
292
293    #[test]
294    fn test_max_pool2d_config_with_dilation() {
295        let node = create_test_node(
296            vec![3, 3],
297            vec![1, 1],
298            vec![0, 0, 0, 0],
299            vec![2, 2],
300            0,
301            None,
302        );
303        let mut node = node;
304        let processor = MaxPool2dProcessor;
305        let prefs = OutputPreferences::new();
306        let config = processor.extract_config(&node, 16).unwrap();
307        processor.infer_types(&mut node, 16, &prefs).unwrap();
308
309        assert_eq!(config.kernel_size, [3, 3]);
310        assert_eq!(config.strides, [1, 1]);
311        assert_eq!(config.dilation, [2, 2]);
312        assert!(matches!(config.padding, PaddingConfig2d::Valid));
313    }
314
315    #[test]
316    fn test_max_pool2d_config_auto_pad_not_set() {
317        let node = create_test_node(
318            vec![3, 3],
319            vec![1, 1],
320            vec![0, 0, 0, 0],
321            vec![1, 1],
322            0,
323            Some("NOTSET"),
324        );
325        let mut node = node;
326        let processor = MaxPool2dProcessor;
327        let prefs = OutputPreferences::new();
328        let config = processor.extract_config(&node, 16).unwrap();
329        processor.infer_types(&mut node, 16, &prefs).unwrap();
330
331        assert_eq!(config.kernel_size, [3, 3]);
332        assert_eq!(config.strides, [1, 1]);
333        assert_eq!(config.dilation, [1, 1]);
334        assert!(matches!(config.padding, PaddingConfig2d::Valid));
335    }
336
337    #[test]
338    fn test_max_pool2d_config_auto_pad_same_upper() {
339        let node = create_test_node(
340            vec![3, 3],
341            vec![1, 1],
342            vec![0, 0, 0, 0],
343            vec![1, 1],
344            0,
345            Some("SAME_UPPER"),
346        );
347        let mut node = node;
348        let processor = MaxPool2dProcessor;
349        let prefs = OutputPreferences::new();
350        processor.infer_types(&mut node, 16, &prefs).unwrap();
351        let config = processor.extract_config(&node, 16).unwrap();
352        assert_eq!(config.auto_pad, AutoPad::SameUpper);
353    }
354
355    #[test]
356    fn test_max_pool2d_config_with_ceil_mode() {
357        let node = create_test_node(
358            vec![3, 3],
359            vec![1, 1],
360            vec![0, 0, 0, 0],
361            vec![1, 1],
362            1,
363            None,
364        );
365        let mut node = node;
366        let processor = MaxPool2dProcessor;
367        let prefs = OutputPreferences::new();
368        let config = processor.extract_config(&node, 16).unwrap();
369        processor.infer_types(&mut node, 16, &prefs).unwrap();
370
371        assert_eq!(config.kernel_size, [3, 3]);
372        assert_eq!(config.strides, [1, 1]);
373        assert_eq!(config.dilation, [1, 1]);
374        assert!(config.ceil_mode);
375        assert!(matches!(config.padding, PaddingConfig2d::Valid));
376    }
377
378    #[test]
379    fn test_max_pool2d_ceil_mode_opset_validation() {
380        // Test that ceil_mode=1 with opset < 10 is rejected
381        let node = create_test_node(
382            vec![3, 3],
383            vec![1, 1],
384            vec![0, 0, 0, 0],
385            vec![1, 1],
386            1,
387            None,
388        );
389        let mut node = node;
390        let processor = MaxPool2dProcessor;
391        let prefs = OutputPreferences::new();
392        let result = processor.infer_types(&mut node, 9, &prefs);
393        assert!(matches!(result, Err(ProcessError::Custom(_))));
394        if let Err(ProcessError::Custom(msg)) = result {
395            assert!(msg.contains("ceil_mode requires opset 10+"));
396        }
397    }
398
399    #[test]
400    fn test_max_pool2d_rejects_unknown_storage_order() {
401        let node = TestNodeBuilder::new(NodeType::MaxPool2d, "test_storage_order")
402            .input_tensor_f32("data", 4, None)
403            .output_tensor_f32("output", 4, None)
404            .attr_ints("kernel_shape", vec![2, 2])
405            .attr_int("storage_order", 2)
406            .build();
407        let result = MaxPool2dProcessor.extract_config(&node, 16);
408        assert!(matches!(
409            result,
410            Err(ProcessError::InvalidAttribute { ref name, .. }) if name == "storage_order"
411        ));
412    }
413
414    #[test]
415    fn test_max_pool2d_ceil_mode_zero_accepted_old_opset() {
416        // Test that ceil_mode=0 is accepted even with old opset
417        let node = create_test_node(
418            vec![3, 3],
419            vec![1, 1],
420            vec![0, 0, 0, 0],
421            vec![1, 1],
422            0,
423            None,
424        );
425        let mut node = node;
426        let processor = MaxPool2dProcessor;
427        let prefs = OutputPreferences::new();
428        let result = processor.infer_types(&mut node, 1, &prefs);
429        assert!(result.is_ok());
430    }
431
432    /// Pins `validate_auto_pad` into this processor's `infer_types`. Without the call the node
433    /// reaches burn-onnx codegen, which panics instead of reporting a `ProcessError`.
434    #[test]
435    fn test_max_pool2d_rejects_unsupported_auto_pad_on_dynamic_shape() {
436        let mut node = TestNodeBuilder::new(NodeType::MaxPool2d, "test_auto_pad")
437            .input_tensor_f32("data", 4, None)
438            .output_tensor_f32("output", 4, None)
439            .attr_ints("kernel_shape", vec![3, 3])
440            .attr_string("auto_pad", "SAME_LOWER")
441            .build_with_graph_data(16);
442        let processor = MaxPool2dProcessor;
443        let prefs = OutputPreferences::new();
444        let err = processor
445            .infer_types(&mut node, 16, &prefs)
446            .expect_err("SAME_LOWER over a dynamic input must be rejected")
447            .to_string();
448        assert!(
449            err.contains(&crate::node::padding::SameBlocker::SameLower.to_string()),
450            "{err}"
451        );
452    }
453}