Skip to main content

onnx_ir/node/
padding.rs

1//! # Padding Configuration Utilities
2//!
3//! Padding configuration types for 1D, 2D, and 3D operations.
4//!
5//! Provides `PaddingConfig1d`, `PaddingConfig2d`, `PaddingConfig3d` enums and helper
6//! functions to convert ONNX padding arrays.
7//!
8//! [`forward_time_same_blocker`] encodes what burn's `PaddingConfig::Same` can serve, which is
9//! burn knowledge in a crate that otherwise mirrors ONNX. That is deliberate: `NodeCodegen`
10//! returns no `Result`, so burn-onnx cannot reject anything without panicking, and rejecting
11//! here is the only way to give the user a `ProcessError` naming the node. Treat it as an
12//! exception forced by the missing error channel, not as licence to move more burn knowledge in.
13
14use std::fmt;
15
16use crate::ir::{ArgType, AttributeValue, RawNode};
17use crate::processor::ProcessError;
18
19/// ONNX auto_pad attribute value.
20///
21/// Specifies how padding should be computed automatically.
22/// When set to anything other than `NotSet`, the `pads` attribute is ignored.
23#[derive(Debug, Clone, PartialEq, Eq, Default)]
24pub enum AutoPad {
25    /// Use explicit `pads` attribute (default).
26    #[default]
27    NotSet,
28    /// Pad so output_size = ceil(input_size / stride). Extra padding at end.
29    SameUpper,
30    /// Pad so output_size = ceil(input_size / stride). Extra padding at start.
31    SameLower,
32    /// No padding (equivalent to all-zero pads).
33    Valid,
34}
35
36impl AutoPad {
37    /// Parse an ONNX auto_pad string attribute.
38    pub fn parse(s: &str) -> Result<Self, ProcessError> {
39        match s {
40            "NOTSET" => Ok(AutoPad::NotSet),
41            "SAME_UPPER" => Ok(AutoPad::SameUpper),
42            "SAME_LOWER" => Ok(AutoPad::SameLower),
43            "VALID" => Ok(AutoPad::Valid),
44            _ => Err(ProcessError::InvalidAttribute {
45                name: "auto_pad".to_string(),
46                reason: format!("Unknown auto_pad value: {s}"),
47            }),
48        }
49    }
50}
51
52impl fmt::Display for AutoPad {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            AutoPad::NotSet => write!(f, "NOTSET"),
56            AutoPad::SameUpper => write!(f, "SAME_UPPER"),
57            AutoPad::SameLower => write!(f, "SAME_LOWER"),
58            AutoPad::Valid => write!(f, "VALID"),
59        }
60    }
61}
62
63/// Spatial dimensions of a convolution or pooling input, when all of them are known.
64///
65/// Only the dimensions after N and C are inspected: a dynamic batch size does not stop the
66/// padding from being computed at import time.
67pub fn static_spatial_dims(ty: &ArgType) -> Option<Vec<usize>> {
68    ty.static_shape()?.get(2..)?.iter().copied().collect()
69}
70
71/// Why burn cannot defer a `SAME_UPPER`/`SAME_LOWER` padding to forward time.
72///
73/// Each variant names a property of burn's `calculate_same_padding`, verified against the pinned
74/// burn revision. `Display` renders the sentence that goes into the user-facing `ProcessError`.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum SameBlocker {
77    /// ONNX puts the extra pad of an odd total at the start, burn puts it at the end.
78    SameLower,
79    /// burn's forward-time padding takes no dilation, so the effective kernel would be wrong.
80    Dilated,
81    /// burn's 3D padding is symmetric-only, so an odd total has nowhere to go.
82    ThreeSpatialDims,
83}
84
85impl fmt::Display for SameBlocker {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            SameBlocker::SameLower => write!(
89                f,
90                "SAME_LOWER puts the extra pad at the start of the dimension, while padding \
91                 computed at forward time puts it at the end"
92            ),
93            SameBlocker::Dilated => {
94                write!(
95                    f,
96                    "padding computed at forward time does not account for dilation"
97                )
98            }
99            SameBlocker::ThreeSpatialDims => write!(
100                f,
101                "padding computed at forward time is symmetric-only over 3 spatial dimensions"
102            ),
103        }
104    }
105}
106
107/// Why burn cannot defer this `SAME_UPPER`/`SAME_LOWER` padding to forward time, if it cannot.
108///
109/// `PaddingConfig::Same` derives the pads from the real input size during `forward`, which is the
110/// only option left when the spatial dimensions are unknown at import time. It reproduces ONNX
111/// for `SAME_UPPER` over one or two spatial dimensions without dilation.
112///
113/// Other cases can coincide with ONNX without being listed as safe here: an even total makes
114/// SAME_LOWER and SAME_UPPER identical, and a stride-1 odd kernel is always symmetric even in 3D.
115/// This check stays conservative rather than reasoning about pad parity, so it rejects them.
116///
117/// The answer assumes the burn module routes padding through `calculate_padding_1d_pair` or
118/// `calculate_padding_2d_pairs`, which keep the two sides separate. Every module burn-onnx
119/// targets today does; `DeformConv2d` does not, and would need its own check.
120///
121/// onnx-ir turns a blocker into a `ProcessError`; burn-onnx codegen asserts there is none before
122/// emitting `Same`. Both consult this function so the rule is stated once, but each gathers its
123/// arguments separately, so every op reaching a `resolve_auto_pad_*` must also call
124/// `validate_auto_pad` for the two to agree.
125pub fn forward_time_same_blocker(
126    auto_pad: &AutoPad,
127    dilated: bool,
128    spatial_rank: usize,
129) -> Option<SameBlocker> {
130    if *auto_pad == AutoPad::SameLower {
131        Some(SameBlocker::SameLower)
132    } else if dilated {
133        Some(SameBlocker::Dilated)
134    } else if spatial_rank > 2 {
135        Some(SameBlocker::ThreeSpatialDims)
136    } else {
137        None
138    }
139}
140
141/// Reject a `SAME_UPPER`/`SAME_LOWER` auto_pad whose input spatial dimensions are unknown and
142/// that burn cannot resolve at forward time either.
143///
144/// Known spatial dimensions let the pads be computed during import, which covers every mode over
145/// one or two spatial dimensions. 3D still requires the resulting pads to come out symmetric;
146/// `PaddingConfig3d::to_tokens` in burn-onnx rejects the rest.
147pub(crate) fn validate_auto_pad(node: &RawNode) -> Result<(), ProcessError> {
148    let auto_pad = match node.attrs.get("auto_pad") {
149        None => return Ok(()),
150        Some(AttributeValue::String(value)) => AutoPad::parse(value)?,
151        Some(other) => {
152            return Err(ProcessError::InvalidAttribute {
153                name: "auto_pad".to_string(),
154                reason: format!("expected a string, got {other:?}"),
155            });
156        }
157    };
158
159    let input = &node.inputs[0].ty;
160    if !matches!(auto_pad, AutoPad::SameUpper | AutoPad::SameLower)
161        || static_spatial_dims(input).is_some()
162    {
163        return Ok(());
164    }
165
166    let dilated = match node.attrs.get("dilations") {
167        None => false,
168        Some(AttributeValue::Int64s(dilations)) => dilations.iter().any(|&d| d != 1),
169        Some(other) => {
170            return Err(ProcessError::InvalidAttribute {
171                name: "dilations".to_string(),
172                reason: format!("expected a list of ints, got {other:?}"),
173            });
174        }
175    };
176
177    match forward_time_same_blocker(&auto_pad, dilated, input.rank().saturating_sub(2)) {
178        None => Ok(()),
179        Some(blocker) => Err(ProcessError::InvalidAttribute {
180            name: "auto_pad".to_string(),
181            reason: format!(
182                "{auto_pad} needs the input spatial dimensions, but they are dynamic, and the \
183                 padding cannot be deferred to forward time either: {blocker}. Re-export the \
184                 model with a static input shape, or with explicit pads."
185            ),
186        }),
187    }
188}
189
190/// An integer list attribute of a ConvTranspose as `usize`s, each at least `min`.
191pub(crate) fn conv_transpose_ints(
192    name: &str,
193    values: &[i64],
194    min: i64,
195) -> Result<Vec<usize>, ProcessError> {
196    if values.iter().any(|&value| value < min) {
197        return Err(ProcessError::InvalidAttribute {
198            name: name.to_string(),
199            reason: format!("values must be at least {min}, got {values:?}"),
200        });
201    }
202    Ok(values.iter().map(|&value| value as usize).collect())
203}
204
205/// The spatial `output_shape` attribute of a ConvTranspose over `spatial_rank` axes.
206pub(crate) fn conv_transpose_output_shape(
207    output_shape: &[i64],
208    spatial_rank: usize,
209) -> Result<Vec<usize>, ProcessError> {
210    if output_shape.len() != spatial_rank {
211        return Err(ProcessError::InvalidAttribute {
212            name: "output_shape".to_string(),
213            reason: format!("expected {spatial_rank} spatial dimensions, got {output_shape:?}"),
214        });
215    }
216    conv_transpose_ints("output_shape", output_shape, 0)
217}
218
219/// Reject a ConvTranspose whose pads derive from the input size while that size is unknown.
220///
221/// `SAME_UPPER`/`SAME_LOWER` and `output_shape` both compute the pads from the input spatial
222/// dimensions. burn's conv-transpose has no padding mode that could resolve them at forward
223/// time, so those dimensions must be static and non-zero.
224pub(crate) fn validate_conv_transpose_pads(
225    node: &RawNode,
226    auto_pad: &AutoPad,
227    has_output_shape: bool,
228) -> Result<(), ProcessError> {
229    let derived = matches!(auto_pad, AutoPad::SameUpper | AutoPad::SameLower);
230    if !derived && !has_output_shape {
231        return Ok(());
232    }
233    let source = if has_output_shape {
234        "output_shape".to_string()
235    } else {
236        format!("auto_pad {auto_pad}")
237    };
238    match static_spatial_dims(&node.inputs[0].ty) {
239        Some(dims) if !dims.contains(&0) => Ok(()),
240        Some(dims) => Err(ProcessError::Custom(format!(
241            "ConvTranspose pads from {source} need non-empty input spatial dimensions, got {dims:?}"
242        ))),
243        None => Err(ProcessError::Custom(format!(
244            "ConvTranspose pads from {source} need the input spatial dimensions, but they are \
245             dynamic. Re-export the model with a static input shape, or with explicit pads."
246        ))),
247    }
248}
249
250/// Set a MaxPool or LpPool output type: the input's `[N, C]` followed by each spatial size.
251///
252/// A spatial size is known when its input size is known and the attributes give a valid
253/// window. SAME gives `ceil(input / stride)`. Otherwise the size is
254/// `floor((input + pads - (kernel - 1) * dilation - 1) / stride) + 1` (no pads for VALID), with
255/// ceil instead of floor under `ceil_mode`, which also drops a last window that would start in
256/// the end padding.
257pub(crate) fn pool_output_type(node: &mut RawNode) -> Result<(), ProcessError> {
258    let tensor = match &node.inputs[0].ty {
259        ArgType::Tensor(tensor) => tensor.clone(),
260        other => {
261            return Err(ProcessError::TypeMismatch {
262                expected: "Tensor".to_string(),
263                actual: format!("{other:?}"),
264            });
265        }
266    };
267    let ints = |name: &str| match node.attrs.get(name) {
268        Some(AttributeValue::Int64s(values)) => Some(values.clone()),
269        _ => None,
270    };
271    let kernel = ints("kernel_shape");
272    let strides = ints("strides");
273    let pads = ints("pads");
274    let dilations = ints("dilations");
275    // Processors disagree on other values (MaxPool reads `== 1`, LpPool `!= 0`).
276    let ceil_mode = match node.attrs.get("ceil_mode") {
277        None | Some(AttributeValue::Int64(0)) => Some(false),
278        Some(AttributeValue::Int64(1)) => Some(true),
279        _ => None,
280    };
281    let auto_pad = match node.attrs.get("auto_pad") {
282        Some(AttributeValue::String(value)) => AutoPad::parse(value)?,
283        _ => AutoPad::NotSet,
284    };
285
286    let spatial_rank = tensor.rank.saturating_sub(2);
287    let spatial_size = |axis: usize, input: usize| -> Option<usize> {
288        let at = |values: &Option<Vec<i64>>, index: usize, default: i64| match values {
289            Some(values) => values.get(index).copied(),
290            None => Some(default),
291        };
292        let input = input as i64;
293        let kernel = kernel.as_ref()?.get(axis).copied()?;
294        let stride = at(&strides, axis, 1)?;
295        let dilation = at(&dilations, axis, 1)?;
296        if kernel < 1 || stride < 1 || dilation < 1 {
297            return None;
298        }
299        // SAME pads make the span a multiple of the stride, so floor and ceil agree and
300        // `ceil_mode`, however a processor reads it, cannot change the size.
301        if matches!(auto_pad, AutoPad::SameUpper | AutoPad::SameLower) {
302            return usize::try_from((input + stride - 1) / stride).ok();
303        }
304        let (pad_begin, pad_end) = match auto_pad {
305            AutoPad::Valid => (0, 0),
306            _ => (at(&pads, axis, 0)?, at(&pads, axis + spatial_rank, 0)?),
307        };
308        let span = input + pad_begin + pad_end - ((kernel - 1) * dilation + 1);
309        let size = if ceil_mode? {
310            let size = (span + stride - 1).div_euclid(stride) + 1;
311            if (size - 1) * stride >= input + pad_begin {
312                size - 1
313            } else {
314                size
315            }
316        } else {
317            span.div_euclid(stride) + 1
318        };
319        usize::try_from(size).ok().filter(|&size| size > 0)
320    };
321
322    let static_shape = tensor.static_shape.as_ref().map(|shape| {
323        shape
324            .iter()
325            .enumerate()
326            .map(|(axis, &dim)| match axis {
327                0 | 1 => dim,
328                _ => dim.and_then(|input| spatial_size(axis - 2, input)),
329            })
330            .collect()
331    });
332
333    node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
334        dtype: tensor.dtype,
335        rank: tensor.rank,
336        static_shape,
337    });
338    Ok(())
339}
340
341/// The geometry of a ConvTranspose, one entry per spatial axis, as ONNX gives it.
342pub(crate) struct ConvTransposeDims<'a> {
343    pub kernel: &'a [usize],
344    pub stride: &'a [usize],
345    pub dilation: &'a [usize],
346    /// Symmetric explicit pads, used when neither `auto_pad` nor `output_shape` is set.
347    pub padding: &'a [usize],
348    pub output_padding: &'a [usize],
349    pub groups: usize,
350    pub auto_pad: &'a AutoPad,
351    pub output_shape: Option<&'a [usize]>,
352}
353
354/// Set a ConvTranspose's output type: `[N, W[1] * groups, spatial...]`, with each dimension
355/// known only when what it derives from is known.
356///
357/// An explicit `output_shape` fixes the spatial size, SAME makes it `input * stride`, and
358/// otherwise it is `stride * (input - 1) + output_padding + (kernel - 1) * dilation + 1` less
359/// the pads (none for VALID).
360pub(crate) fn conv_transpose_output_type(
361    node: &mut RawNode,
362    dims: ConvTransposeDims<'_>,
363) -> Result<(), ProcessError> {
364    let tensor = match &node.inputs[0].ty {
365        ArgType::Tensor(tensor) => tensor.clone(),
366        other => {
367            return Err(ProcessError::TypeMismatch {
368                expected: "Tensor".to_string(),
369                actual: format!("{other:?}"),
370            });
371        }
372    };
373    let input_dim = |axis: usize| {
374        tensor
375            .static_shape
376            .as_ref()
377            .and_then(|shape| shape.get(axis).copied().flatten())
378    };
379    let out_channels = known_weight_shape(&node.inputs[1])
380        .and_then(|shape| shape.get(1).map(|per_group| per_group * dims.groups));
381
382    let mut static_shape = vec![input_dim(0), out_channels];
383    for axis in 0..dims.kernel.len() {
384        let size = match dims.output_shape {
385            Some(shape) => Some(shape[axis]),
386            None => input_dim(axis + 2).map(|input| match dims.auto_pad {
387                AutoPad::SameUpper | AutoPad::SameLower => input * dims.stride[axis],
388                _ => {
389                    let pads = match dims.auto_pad {
390                        AutoPad::Valid => 0,
391                        _ => 2 * dims.padding[axis],
392                    };
393                    (dims.stride[axis] * input.saturating_sub(1)
394                        + dims.output_padding[axis]
395                        + (dims.kernel[axis] - 1) * dims.dilation[axis]
396                        + 1)
397                    .saturating_sub(pads)
398                }
399            }),
400        };
401        static_shape.push(size);
402    }
403
404    node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
405        dtype: tensor.dtype,
406        rank: tensor.rank,
407        static_shape: Some(static_shape),
408    });
409    Ok(())
410}
411
412/// Padding configuration for 1D operations such as convolution
413#[derive(Debug, Clone, PartialEq, Eq, Default)]
414pub enum PaddingConfig1d {
415    /// No padding (valid padding)
416    #[default]
417    Valid,
418    /// Explicit padding with values for left and right sides
419    /// Format: (left, right)
420    /// For symmetric padding, use the same value for both (e.g., `Explicit(1, 1)`).
421    Explicit(usize, usize),
422}
423
424impl fmt::Display for PaddingConfig1d {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        match self {
427            PaddingConfig1d::Valid => write!(f, "Valid"),
428            PaddingConfig1d::Explicit(left, right) => write!(f, "Explicit({left}, {right})"),
429        }
430    }
431}
432
433impl PaddingConfig1d {
434    /// Returns true if this padding configuration is asymmetric (left != right)
435    pub fn is_asymmetric(&self) -> bool {
436        match self {
437            PaddingConfig1d::Explicit(left, right) => left != right,
438            _ => false,
439        }
440    }
441
442    /// Returns the padding values as (left, right) tuple
443    pub fn as_tuple(&self) -> (usize, usize) {
444        match self {
445            PaddingConfig1d::Valid => (0, 0),
446            PaddingConfig1d::Explicit(left, right) => (*left, *right),
447        }
448    }
449}
450/// Check that a per-spatial-dimension attribute has at least `expected` entries, the most the
451/// config reads, so a short array from a malformed model is an error rather than a panic.
452pub(crate) fn check_attr_len<T>(
453    name: &str,
454    values: &[T],
455    expected: usize,
456) -> Result<(), ProcessError> {
457    if values.len() < expected {
458        return Err(ProcessError::InvalidAttribute {
459            name: name.to_string(),
460            reason: format!("expected {expected} values, got {}", values.len()),
461        });
462    }
463    Ok(())
464}
465
466/// Calculate the padding configuration for a 1D operations such as Convolution and Pooling.
467///
468/// # Arguments
469///
470/// * `pads` - The padding values [left, right]
471///
472/// # Panics
473///
474/// * If the padding is negative
475///
476/// # Returns
477///
478/// * The padding configuration (Valid or Explicit)
479///
480/// # Remarks
481///
482/// This function is used when the padding is specified as a list of integers,
483/// and not used when the padding is specified as a string, e.g. "SAME_UPPER".
484pub(crate) fn padding_config_1d(pads: &[i64]) -> Result<PaddingConfig1d, ProcessError> {
485    check_attr_len("pads", pads, 2)?;
486    let [left, right] = [pads[0], pads[1]];
487
488    if left < 0 || right < 0 {
489        Err(ProcessError::InvalidAttribute {
490            name: "pads".to_string(),
491            reason: format!("negative pad values are not supported: {pads:?}"),
492        })
493    } else if left == 0 && right == 0 {
494        Ok(PaddingConfig1d::Valid)
495    } else {
496        Ok(PaddingConfig1d::Explicit(left as usize, right as usize))
497    }
498}
499
500/// Padding configuration for 2D operations such as convolution
501#[derive(Debug, Clone, PartialEq, Eq, Default)]
502pub enum PaddingConfig2d {
503    /// No padding (valid padding)
504    #[default]
505    Valid,
506    /// Explicit padding with values for each side
507    /// Format: (top, left, bottom, right)
508    /// For symmetric padding, use matching values (e.g., `Explicit(1, 1, 1, 1)`).
509    Explicit(usize, usize, usize, usize),
510}
511
512impl fmt::Display for PaddingConfig2d {
513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514        match self {
515            PaddingConfig2d::Valid => write!(f, "Valid"),
516            PaddingConfig2d::Explicit(top, left, bottom, right) => {
517                write!(f, "Explicit({top}, {left}, {bottom}, {right})")
518            }
519        }
520    }
521}
522
523impl PaddingConfig2d {
524    /// Returns true if this padding configuration is asymmetric (top != bottom or left != right)
525    pub fn is_asymmetric(&self) -> bool {
526        match self {
527            PaddingConfig2d::Explicit(top, left, bottom, right) => top != bottom || left != right,
528            _ => false,
529        }
530    }
531
532    /// Returns the padding values as (top, left, bottom, right) tuple
533    pub fn as_tuple(&self) -> (usize, usize, usize, usize) {
534        match self {
535            PaddingConfig2d::Valid => (0, 0, 0, 0),
536            PaddingConfig2d::Explicit(top, left, bottom, right) => (*top, *left, *bottom, *right),
537        }
538    }
539}
540
541/// Calculate the padding configuration for a 2D operations such as Convolution and Pooling.
542///
543/// # Arguments
544///
545/// * `pads` - The padding values [top, left, bottom, right] (ONNX format)
546///
547/// # Panics
548///
549/// * If the padding is negative
550///
551/// # Returns
552///
553/// * The padding configuration (Valid or Explicit)
554///
555/// # Remarks
556///
557/// This function is used when the padding is specified as a list of integers,
558/// and not used when the padding is specified as a string, e.g. "SAME_UPPER".
559pub(crate) fn padding_config_2d(pads: &[i64]) -> Result<PaddingConfig2d, ProcessError> {
560    check_attr_len("pads", pads, 4)?;
561    let [top, left, bottom, right] = [pads[0], pads[1], pads[2], pads[3]];
562
563    if left < 0 || right < 0 || top < 0 || bottom < 0 {
564        Err(ProcessError::InvalidAttribute {
565            name: "pads".to_string(),
566            reason: format!("negative pad values are not supported: {pads:?}"),
567        })
568    } else if left == 0 && right == 0 && top == 0 && bottom == 0 {
569        Ok(PaddingConfig2d::Valid)
570    } else {
571        Ok(PaddingConfig2d::Explicit(
572            top as usize,
573            left as usize,
574            bottom as usize,
575            right as usize,
576        ))
577    }
578}
579
580/// Padding configuration for 3D operations such as convolution
581#[derive(Debug, Clone, PartialEq, Eq, Default)]
582pub enum PaddingConfig3d {
583    /// No padding (valid padding)
584    #[default]
585    Valid,
586    /// Explicit padding with values for each side
587    /// Format: (front, top, left, back, bottom, right)
588    /// For symmetric padding, use matching values (e.g., `Explicit(1, 1, 1, 1, 1, 1)`).
589    Explicit(usize, usize, usize, usize, usize, usize),
590}
591
592impl fmt::Display for PaddingConfig3d {
593    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594        match self {
595            PaddingConfig3d::Valid => write!(f, "Valid"),
596            PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
597                write!(
598                    f,
599                    "Explicit({front}, {top}, {left}, {back}, {bottom}, {right})"
600                )
601            }
602        }
603    }
604}
605
606impl PaddingConfig3d {
607    /// Returns true if this padding configuration is asymmetric
608    pub fn is_asymmetric(&self) -> bool {
609        match self {
610            PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
611                front != back || top != bottom || left != right
612            }
613            _ => false,
614        }
615    }
616
617    /// Returns the padding values as (front, top, left, back, bottom, right) tuple
618    pub fn as_tuple(&self) -> (usize, usize, usize, usize, usize, usize) {
619        match self {
620            PaddingConfig3d::Valid => (0, 0, 0, 0, 0, 0),
621            PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
622                (*front, *top, *left, *back, *bottom, *right)
623            }
624        }
625    }
626}
627
628/// Calculate the padding configuration for a 3D operations such as Convolution and Pooling.
629///
630/// # Arguments
631///
632/// * `pads` - The padding values [front, top, left, back, bottom, right] (ONNX format)
633///
634/// # Panics
635///
636/// * If the padding is negative
637///
638/// # Returns
639///
640/// * The padding configuration (Valid or Explicit)
641///
642/// # Remarks
643///
644/// This function is used when the padding is specified as a list of integers,
645/// and not used when the padding is specified as a string, e.g. "SAME_UPPER".
646pub(crate) fn padding_config_3d(pads: &[i64]) -> Result<PaddingConfig3d, ProcessError> {
647    check_attr_len("pads", pads, 6)?;
648    let [front, top, left, back, bottom, right] =
649        [pads[0], pads[1], pads[2], pads[3], pads[4], pads[5]];
650
651    if left < 0 || right < 0 || top < 0 || bottom < 0 || front < 0 || back < 0 {
652        Err(ProcessError::InvalidAttribute {
653            name: "pads".to_string(),
654            reason: format!("negative pad values are not supported: {pads:?}"),
655        })
656    } else if left == 0 && right == 0 && top == 0 && bottom == 0 && front == 0 && back == 0 {
657        Ok(PaddingConfig3d::Valid)
658    } else {
659        Ok(PaddingConfig3d::Explicit(
660            front as usize,
661            top as usize,
662            left as usize,
663            back as usize,
664            bottom as usize,
665            right as usize,
666        ))
667    }
668}
669
670/// A conv weight's shape: from a fully known static shape, or from its constant value,
671/// which is only read (and copied) when the type does not carry the shape.
672pub(crate) fn known_weight_shape(weight: &crate::ir::Argument) -> Option<Vec<usize>> {
673    weight
674        .ty
675        .static_shape_known()
676        .or_else(|| weight.value().map(|data| data.shape().to_vec()))
677}
678
679#[cfg(test)]
680mod tests {
681    use super::*;
682    use crate::ir::{DType, NodeType, TensorType};
683    use crate::node::test_utils::TestNodeBuilder;
684
685    /// Conv node whose input spatial dimensions are `spatial` (`None` = dynamic). The spatial
686    /// rank, which decides the 3D blocker, follows from how many are given. The node type is
687    /// always Conv2d even for other ranks; `validate_auto_pad` does not inspect it.
688    fn conv_node(auto_pad: &str, spatial: &[Option<usize>], dilations: Vec<i64>) -> RawNode {
689        let mut static_shape = vec![None, Some(3)];
690        static_shape.extend_from_slice(spatial);
691        let rank = static_shape.len();
692        TestNodeBuilder::new(NodeType::Conv2d, "test_conv")
693            .add_input(
694                "data",
695                ArgType::Tensor(TensorType {
696                    dtype: DType::F32,
697                    rank,
698                    static_shape: Some(static_shape),
699                }),
700            )
701            .output_tensor_f32("output", rank, None)
702            .attr_string("auto_pad", auto_pad)
703            .attr_ints("dilations", dilations)
704            .build()
705    }
706
707    #[test]
708    fn test_static_spatial_dims_ignores_dynamic_batch() {
709        let node = conv_node("SAME_UPPER", &[Some(7), Some(9)], vec![1, 1]);
710        assert_eq!(static_spatial_dims(&node.inputs[0].ty), Some(vec![7, 9]));
711    }
712
713    #[test]
714    fn test_static_spatial_dims_dynamic() {
715        let node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
716        assert_eq!(static_spatial_dims(&node.inputs[0].ty), None);
717    }
718
719    #[test]
720    fn test_validate_auto_pad_accepts_static_spatial() {
721        // Over 1 or 2 spatial dimensions every mode is fine once the dimensions are known:
722        // the pads are computed during import.
723        for auto_pad in ["SAME_UPPER", "SAME_LOWER"] {
724            let node = conv_node(auto_pad, &[Some(7), Some(7)], vec![2, 2]);
725            assert!(validate_auto_pad(&node).is_ok());
726        }
727    }
728
729    #[test]
730    fn test_validate_auto_pad_accepts_same_upper_dynamic() {
731        let node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
732        assert!(validate_auto_pad(&node).is_ok());
733    }
734
735    #[test]
736    fn test_validate_auto_pad_rejects_same_lower_dynamic() {
737        let node = conv_node("SAME_LOWER", &[None, None], vec![1, 1]);
738        let err = validate_auto_pad(&node).unwrap_err().to_string();
739        assert!(err.contains(&SameBlocker::SameLower.to_string()), "{err}");
740    }
741
742    #[test]
743    fn test_validate_auto_pad_rejects_dilation_dynamic() {
744        let node = conv_node("SAME_UPPER", &[None, None], vec![2, 2]);
745        let err = validate_auto_pad(&node).unwrap_err().to_string();
746        assert!(err.contains(&SameBlocker::Dilated.to_string()), "{err}");
747    }
748
749    #[test]
750    fn test_validate_auto_pad_rejects_3d_dynamic() {
751        let node = conv_node("SAME_UPPER", &[None, None, None], vec![1, 1, 1]);
752        let err = validate_auto_pad(&node).unwrap_err().to_string();
753        assert!(
754            err.contains(&SameBlocker::ThreeSpatialDims.to_string()),
755            "{err}"
756        );
757    }
758
759    #[test]
760    fn test_forward_time_same_blocker_precedence() {
761        // SAME_LOWER is reported before dilation, and dilation before the 3D limit, so the
762        // message names the first thing the user has to change.
763        assert_eq!(
764            forward_time_same_blocker(&AutoPad::SameLower, true, 3),
765            Some(SameBlocker::SameLower)
766        );
767        assert_eq!(
768            forward_time_same_blocker(&AutoPad::SameUpper, true, 3),
769            Some(SameBlocker::Dilated)
770        );
771        assert_eq!(
772            forward_time_same_blocker(&AutoPad::SameUpper, false, 3),
773            Some(SameBlocker::ThreeSpatialDims)
774        );
775        assert_eq!(
776            forward_time_same_blocker(&AutoPad::SameUpper, false, 2),
777            None
778        );
779    }
780
781    #[test]
782    fn test_validate_auto_pad_rejects_wrong_attribute_types() {
783        let mut node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
784        node.attrs
785            .insert("auto_pad".to_string(), AttributeValue::Int64(1));
786        let err = validate_auto_pad(&node).unwrap_err().to_string();
787        assert!(err.contains("expected a string"), "{err}");
788
789        let mut node = conv_node("SAME_UPPER", &[None, None], vec![1, 1]);
790        node.attrs
791            .insert("dilations".to_string(), AttributeValue::Int64(1));
792        let err = validate_auto_pad(&node).unwrap_err().to_string();
793        assert!(err.contains("expected a list of ints"), "{err}");
794    }
795
796    #[test]
797    fn test_validate_auto_pad_ignores_other_modes() {
798        for auto_pad in ["NOTSET", "VALID"] {
799            let node = conv_node(auto_pad, &[None, None], vec![1, 1]);
800            assert!(validate_auto_pad(&node).is_ok());
801        }
802    }
803
804    // AutoPad tests
805    #[test]
806    fn test_auto_pad_parse() {
807        assert_eq!(AutoPad::parse("NOTSET").unwrap(), AutoPad::NotSet);
808        assert_eq!(AutoPad::parse("SAME_UPPER").unwrap(), AutoPad::SameUpper);
809        assert_eq!(AutoPad::parse("SAME_LOWER").unwrap(), AutoPad::SameLower);
810        assert_eq!(AutoPad::parse("VALID").unwrap(), AutoPad::Valid);
811        assert!(AutoPad::parse("INVALID").is_err());
812    }
813
814    #[test]
815    fn test_auto_pad_display() {
816        assert_eq!(AutoPad::NotSet.to_string(), "NOTSET");
817        assert_eq!(AutoPad::SameUpper.to_string(), "SAME_UPPER");
818        assert_eq!(AutoPad::SameLower.to_string(), "SAME_LOWER");
819        assert_eq!(AutoPad::Valid.to_string(), "VALID");
820    }
821
822    // 1D padding tests
823    #[test]
824    fn test_padding_config_1d_valid() {
825        let pads = vec![0, 0];
826        let config = padding_config_1d(&pads).unwrap();
827        assert!(matches!(config, PaddingConfig1d::Valid));
828    }
829
830    #[test]
831    fn test_padding_config_1d_explicit_symmetric() {
832        let pads = vec![2, 2];
833        let config = padding_config_1d(&pads).unwrap();
834        assert!(matches!(config, PaddingConfig1d::Explicit(2, 2)));
835        assert!(!config.is_asymmetric());
836        assert_eq!(config.as_tuple(), (2, 2));
837    }
838
839    #[test]
840    fn test_padding_config_1d_explicit_asymmetric() {
841        let pads = vec![1, 2];
842        let config = padding_config_1d(&pads).unwrap();
843        assert!(matches!(config, PaddingConfig1d::Explicit(1, 2)));
844        assert!(config.is_asymmetric());
845        assert_eq!(config.as_tuple(), (1, 2));
846    }
847
848    #[test]
849    fn test_padding_config_1d_negative() {
850        let pads = vec![-1, -1];
851        let err = padding_config_1d(&pads).unwrap_err();
852        assert!(err.to_string().contains("negative pad values"), "{err}");
853    }
854
855    // 2D padding tests
856    #[test]
857    fn test_padding_config_2d_valid() {
858        let pads = vec![0, 0, 0, 0];
859        let config = padding_config_2d(&pads).unwrap();
860        assert!(matches!(config, PaddingConfig2d::Valid));
861        assert!(!config.is_asymmetric());
862    }
863
864    #[test]
865    fn test_padding_config_2d_explicit_symmetric() {
866        let pads = vec![2, 2, 2, 2];
867        let config = padding_config_2d(&pads).unwrap();
868        assert!(matches!(config, PaddingConfig2d::Explicit(2, 2, 2, 2)));
869        assert!(!config.is_asymmetric());
870        assert_eq!(config.as_tuple(), (2, 2, 2, 2));
871    }
872
873    #[test]
874    fn test_padding_config_2d_explicit_asymmetric() {
875        // pads = [top, left, bottom, right]
876        let pads = vec![1, 2, 3, 4];
877        let config = padding_config_2d(&pads).unwrap();
878        assert!(matches!(config, PaddingConfig2d::Explicit(1, 2, 3, 4)));
879        assert!(config.is_asymmetric());
880        assert_eq!(config.as_tuple(), (1, 2, 3, 4));
881    }
882
883    #[test]
884    fn test_padding_config_2d_explicit_asymmetric_top_bottom() {
885        // top != bottom but left == right
886        let pads = vec![1, 2, 3, 2];
887        let config = padding_config_2d(&pads).unwrap();
888        assert!(matches!(config, PaddingConfig2d::Explicit(1, 2, 3, 2)));
889        assert!(config.is_asymmetric());
890    }
891
892    #[test]
893    fn test_padding_config_2d_explicit_asymmetric_left_right() {
894        // left != right but top == bottom
895        let pads = vec![2, 1, 2, 3];
896        let config = padding_config_2d(&pads).unwrap();
897        assert!(matches!(config, PaddingConfig2d::Explicit(2, 1, 2, 3)));
898        assert!(config.is_asymmetric());
899    }
900
901    #[test]
902    fn test_padding_config_2d_negative() {
903        let pads = vec![-1, -1, -1, -1];
904        let err = padding_config_2d(&pads).unwrap_err();
905        assert!(err.to_string().contains("negative pad values"), "{err}");
906    }
907
908    // 3D padding tests
909    #[test]
910    fn test_padding_config_3d_valid() {
911        let pads = vec![0, 0, 0, 0, 0, 0];
912        let config = padding_config_3d(&pads).unwrap();
913        assert!(matches!(config, PaddingConfig3d::Valid));
914        assert!(!config.is_asymmetric());
915    }
916
917    #[test]
918    fn test_padding_config_3d_explicit_symmetric() {
919        let pads = vec![2, 3, 1, 2, 3, 1];
920        let config = padding_config_3d(&pads).unwrap();
921        assert!(matches!(
922            config,
923            PaddingConfig3d::Explicit(2, 3, 1, 2, 3, 1)
924        ));
925        assert!(!config.is_asymmetric());
926        assert_eq!(config.as_tuple(), (2, 3, 1, 2, 3, 1));
927    }
928
929    #[test]
930    fn test_padding_config_3d_explicit_asymmetric() {
931        // pads = [front, top, left, back, bottom, right]
932        let pads = vec![1, 2, 3, 4, 5, 6];
933        let config = padding_config_3d(&pads).unwrap();
934        assert!(matches!(
935            config,
936            PaddingConfig3d::Explicit(1, 2, 3, 4, 5, 6)
937        ));
938        assert!(config.is_asymmetric());
939        assert_eq!(config.as_tuple(), (1, 2, 3, 4, 5, 6));
940    }
941
942    #[test]
943    fn test_padding_config_3d_explicit_asymmetric_partial() {
944        // Only front != back
945        let pads = vec![1, 3, 1, 2, 3, 1];
946        let config = padding_config_3d(&pads).unwrap();
947        assert!(matches!(
948            config,
949            PaddingConfig3d::Explicit(1, 3, 1, 2, 3, 1)
950        ));
951        assert!(config.is_asymmetric());
952    }
953
954    #[test]
955    fn test_padding_config_3d_negative() {
956        let pads = vec![-1, -1, -1, -1, -1, -1];
957        let err = padding_config_3d(&pads).unwrap_err();
958        assert!(err.to_string().contains("negative pad values"), "{err}");
959    }
960
961    /// Output static shape of a MaxPool with input `[None, 3, spatial...]` and the attributes
962    /// `attrs` adds.
963    fn pool_shape(
964        spatial: &[Option<usize>],
965        attrs: impl FnOnce(TestNodeBuilder) -> TestNodeBuilder,
966    ) -> Vec<Option<usize>> {
967        let mut static_shape = vec![None, Some(3)];
968        static_shape.extend_from_slice(spatial);
969        let rank = static_shape.len();
970        let builder = TestNodeBuilder::new(NodeType::MaxPool2d, "test_pool")
971            .add_input(
972                "data",
973                ArgType::Tensor(TensorType {
974                    dtype: DType::F32,
975                    rank,
976                    static_shape: Some(static_shape),
977                }),
978            )
979            .output_tensor_f32("output", rank, None);
980        let mut node = attrs(builder).build();
981        pool_output_type(&mut node).unwrap();
982        node.outputs[0].ty.static_shape().unwrap().clone()
983    }
984
985    #[test]
986    fn test_pool_output_type_asymmetric_pads_and_dilation() {
987        // H: 10 + 1 + 2 - 5 = 8, / 2 + 1 = 5. W: 10 - 3 = 7, / 1 + 1 = 8.
988        let shape = pool_shape(&[Some(10), Some(10)], |node| {
989            node.attr_ints("kernel_shape", vec![3, 3])
990                .attr_ints("strides", vec![2, 1])
991                .attr_ints("pads", vec![1, 0, 2, 0])
992                .attr_ints("dilations", vec![2, 1])
993        });
994        assert_eq!(shape, vec![None, Some(3), Some(5), Some(8)]);
995    }
996
997    #[test]
998    fn test_pool_output_type_ceil_mode_asymmetric_pads_drops_window() {
999        // 5 + 0 + 2 - 3 = 4, ceil(4 / 3) + 1 = 3, but the 3rd window starts at 6 >= 5.
1000        let shape = pool_shape(&[Some(5)], |node| {
1001            node.attr_ints("kernel_shape", vec![3])
1002                .attr_ints("strides", vec![3])
1003                .attr_ints("pads", vec![0, 2])
1004                .attr_int("ceil_mode", 1)
1005        });
1006        assert_eq!(shape, vec![None, Some(3), Some(2)]);
1007    }
1008
1009    #[test]
1010    fn test_pool_output_type_valid_ignores_pads() {
1011        let shape = pool_shape(&[Some(6), Some(6), Some(6)], |node| {
1012            node.attr_ints("kernel_shape", vec![2, 2, 2])
1013                .attr_ints("pads", vec![1, 1, 1, 1, 1, 1])
1014                .attr_string("auto_pad", "VALID")
1015        });
1016        assert_eq!(shape, vec![None, Some(3), Some(5), Some(5), Some(5)]);
1017    }
1018
1019    #[test]
1020    fn test_pool_output_type_unknown_spatial_dims() {
1021        // A dynamic input dim, and a kernel larger than the input, both leave the size unknown.
1022        let shape = pool_shape(&[None, Some(2)], |node| {
1023            node.attr_ints("kernel_shape", vec![3, 3])
1024        });
1025        assert_eq!(shape, vec![None, Some(3), None, None]);
1026    }
1027
1028    #[test]
1029    fn test_pool_output_type_unrecognized_ceil_mode() {
1030        let shape = pool_shape(&[Some(7)], |node| {
1031            node.attr_ints("kernel_shape", vec![2])
1032                .attr_ints("strides", vec![2])
1033                .attr_int("ceil_mode", 2)
1034        });
1035        assert_eq!(shape, vec![None, Some(3), None]);
1036    }
1037}