onnx-ir 0.21.0

ONNX-IR is a pure Rust library for parsing ONNX models into an intermediate representation that can be used to generate code for various ML/DL frameworks
Documentation
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! # Padding Configuration Utilities
//!
//! Padding configuration types for 1D, 2D, and 3D operations.
//!
//! Provides `PaddingConfig1d`, `PaddingConfig2d`, `PaddingConfig3d` enums and helper
//! functions to convert ONNX padding arrays.

use std::fmt;

use crate::processor::ProcessError;

/// ONNX auto_pad attribute value.
///
/// Specifies how padding should be computed automatically.
/// When set to anything other than `NotSet`, the `pads` attribute is ignored.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum AutoPad {
    /// Use explicit `pads` attribute (default).
    #[default]
    NotSet,
    /// Pad so output_size = ceil(input_size / stride). Extra padding at end.
    SameUpper,
    /// Pad so output_size = ceil(input_size / stride). Extra padding at start.
    SameLower,
    /// No padding (equivalent to all-zero pads).
    Valid,
}

impl AutoPad {
    /// Parse an ONNX auto_pad string attribute.
    pub fn parse(s: &str) -> Result<Self, ProcessError> {
        match s {
            "NOTSET" => Ok(AutoPad::NotSet),
            "SAME_UPPER" => Ok(AutoPad::SameUpper),
            "SAME_LOWER" => Ok(AutoPad::SameLower),
            "VALID" => Ok(AutoPad::Valid),
            _ => Err(ProcessError::InvalidAttribute {
                name: "auto_pad".to_string(),
                reason: format!("Unknown auto_pad value: {s}"),
            }),
        }
    }
}

impl fmt::Display for AutoPad {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AutoPad::NotSet => write!(f, "NOTSET"),
            AutoPad::SameUpper => write!(f, "SAME_UPPER"),
            AutoPad::SameLower => write!(f, "SAME_LOWER"),
            AutoPad::Valid => write!(f, "VALID"),
        }
    }
}

/// Padding configuration for 1D operations such as convolution
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum PaddingConfig1d {
    /// No padding (valid padding)
    #[default]
    Valid,
    /// Explicit padding with values for left and right sides
    /// Format: (left, right)
    /// For symmetric padding, use the same value for both (e.g., `Explicit(1, 1)`).
    Explicit(usize, usize),
}

impl fmt::Display for PaddingConfig1d {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PaddingConfig1d::Valid => write!(f, "Valid"),
            PaddingConfig1d::Explicit(left, right) => write!(f, "Explicit({left}, {right})"),
        }
    }
}

impl PaddingConfig1d {
    /// Returns true if this padding configuration is asymmetric (left != right)
    pub fn is_asymmetric(&self) -> bool {
        match self {
            PaddingConfig1d::Explicit(left, right) => left != right,
            _ => false,
        }
    }

    /// Returns the padding values as (left, right) tuple
    pub fn as_tuple(&self) -> (usize, usize) {
        match self {
            PaddingConfig1d::Valid => (0, 0),
            PaddingConfig1d::Explicit(left, right) => (*left, *right),
        }
    }
}

/// Calculate the padding configuration for a 1D operations such as Convolution and Pooling.
///
/// # Arguments
///
/// * `pads` - The padding values [left, right]
///
/// # Panics
///
/// * If the padding is negative
///
/// # Returns
///
/// * The padding configuration (Valid or Explicit)
///
/// # Remarks
///
/// This function is used when the padding is specified as a list of integers,
/// and not used when the padding is specified as a string, e.g. "SAME_UPPER".
pub(crate) fn padding_config_1d(pads: &[i64]) -> PaddingConfig1d {
    let [left, right] = [pads[0], pads[1]];

    if left < 0 || right < 0 {
        panic!("Negative pad values are not supported");
    } else if left == 0 && right == 0 {
        PaddingConfig1d::Valid
    } else {
        PaddingConfig1d::Explicit(left as usize, right as usize)
    }
}

/// Padding configuration for 2D operations such as convolution
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum PaddingConfig2d {
    /// No padding (valid padding)
    #[default]
    Valid,
    /// Explicit padding with values for each side
    /// Format: (top, left, bottom, right)
    /// For symmetric padding, use matching values (e.g., `Explicit(1, 1, 1, 1)`).
    Explicit(usize, usize, usize, usize),
}

impl fmt::Display for PaddingConfig2d {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PaddingConfig2d::Valid => write!(f, "Valid"),
            PaddingConfig2d::Explicit(top, left, bottom, right) => {
                write!(f, "Explicit({top}, {left}, {bottom}, {right})")
            }
        }
    }
}

impl PaddingConfig2d {
    /// Returns true if this padding configuration is asymmetric (top != bottom or left != right)
    pub fn is_asymmetric(&self) -> bool {
        match self {
            PaddingConfig2d::Explicit(top, left, bottom, right) => top != bottom || left != right,
            _ => false,
        }
    }

    /// Returns the padding values as (top, left, bottom, right) tuple
    pub fn as_tuple(&self) -> (usize, usize, usize, usize) {
        match self {
            PaddingConfig2d::Valid => (0, 0, 0, 0),
            PaddingConfig2d::Explicit(top, left, bottom, right) => (*top, *left, *bottom, *right),
        }
    }
}

/// Calculate the padding configuration for a 2D operations such as Convolution and Pooling.
///
/// # Arguments
///
/// * `pads` - The padding values [top, left, bottom, right] (ONNX format)
///
/// # Panics
///
/// * If the padding is negative
///
/// # Returns
///
/// * The padding configuration (Valid or Explicit)
///
/// # Remarks
///
/// This function is used when the padding is specified as a list of integers,
/// and not used when the padding is specified as a string, e.g. "SAME_UPPER".
pub(crate) fn padding_config_2d(pads: &[i64]) -> PaddingConfig2d {
    let [top, left, bottom, right] = [pads[0], pads[1], pads[2], pads[3]];

    if left < 0 || right < 0 || top < 0 || bottom < 0 {
        panic!("Negative pad values are not supported");
    } else if left == 0 && right == 0 && top == 0 && bottom == 0 {
        PaddingConfig2d::Valid
    } else {
        PaddingConfig2d::Explicit(top as usize, left as usize, bottom as usize, right as usize)
    }
}

/// Padding configuration for 3D operations such as convolution
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum PaddingConfig3d {
    /// No padding (valid padding)
    #[default]
    Valid,
    /// Explicit padding with values for each side
    /// Format: (front, top, left, back, bottom, right)
    /// For symmetric padding, use matching values (e.g., `Explicit(1, 1, 1, 1, 1, 1)`).
    Explicit(usize, usize, usize, usize, usize, usize),
}

impl fmt::Display for PaddingConfig3d {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PaddingConfig3d::Valid => write!(f, "Valid"),
            PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
                write!(
                    f,
                    "Explicit({front}, {top}, {left}, {back}, {bottom}, {right})"
                )
            }
        }
    }
}

impl PaddingConfig3d {
    /// Returns true if this padding configuration is asymmetric
    pub fn is_asymmetric(&self) -> bool {
        match self {
            PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
                front != back || top != bottom || left != right
            }
            _ => false,
        }
    }

    /// Returns the padding values as (front, top, left, back, bottom, right) tuple
    pub fn as_tuple(&self) -> (usize, usize, usize, usize, usize, usize) {
        match self {
            PaddingConfig3d::Valid => (0, 0, 0, 0, 0, 0),
            PaddingConfig3d::Explicit(front, top, left, back, bottom, right) => {
                (*front, *top, *left, *back, *bottom, *right)
            }
        }
    }
}

/// Calculate the padding configuration for a 3D operations such as Convolution and Pooling.
///
/// # Arguments
///
/// * `pads` - The padding values [front, top, left, back, bottom, right] (ONNX format)
///
/// # Panics
///
/// * If the padding is negative
///
/// # Returns
///
/// * The padding configuration (Valid or Explicit)
///
/// # Remarks
///
/// This function is used when the padding is specified as a list of integers,
/// and not used when the padding is specified as a string, e.g. "SAME_UPPER".
pub(crate) fn padding_config_3d(pads: &[i64]) -> PaddingConfig3d {
    let [front, top, left, back, bottom, right] =
        [pads[0], pads[1], pads[2], pads[3], pads[4], pads[5]];

    if left < 0 || right < 0 || top < 0 || bottom < 0 || front < 0 || back < 0 {
        panic!("Negative pad values are not supported");
    } else if left == 0 && right == 0 && top == 0 && bottom == 0 && front == 0 && back == 0 {
        PaddingConfig3d::Valid
    } else {
        PaddingConfig3d::Explicit(
            front as usize,
            top as usize,
            left as usize,
            back as usize,
            bottom as usize,
            right as usize,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // AutoPad tests
    #[test]
    fn test_auto_pad_parse() {
        assert_eq!(AutoPad::parse("NOTSET").unwrap(), AutoPad::NotSet);
        assert_eq!(AutoPad::parse("SAME_UPPER").unwrap(), AutoPad::SameUpper);
        assert_eq!(AutoPad::parse("SAME_LOWER").unwrap(), AutoPad::SameLower);
        assert_eq!(AutoPad::parse("VALID").unwrap(), AutoPad::Valid);
        assert!(AutoPad::parse("INVALID").is_err());
    }

    #[test]
    fn test_auto_pad_display() {
        assert_eq!(AutoPad::NotSet.to_string(), "NOTSET");
        assert_eq!(AutoPad::SameUpper.to_string(), "SAME_UPPER");
        assert_eq!(AutoPad::SameLower.to_string(), "SAME_LOWER");
        assert_eq!(AutoPad::Valid.to_string(), "VALID");
    }

    // 1D padding tests
    #[test]
    fn test_padding_config_1d_valid() {
        let pads = vec![0, 0];
        let config = padding_config_1d(&pads);
        assert!(matches!(config, PaddingConfig1d::Valid));
    }

    #[test]
    fn test_padding_config_1d_explicit_symmetric() {
        let pads = vec![2, 2];
        let config = padding_config_1d(&pads);
        assert!(matches!(config, PaddingConfig1d::Explicit(2, 2)));
        assert!(!config.is_asymmetric());
        assert_eq!(config.as_tuple(), (2, 2));
    }

    #[test]
    fn test_padding_config_1d_explicit_asymmetric() {
        let pads = vec![1, 2];
        let config = padding_config_1d(&pads);
        assert!(matches!(config, PaddingConfig1d::Explicit(1, 2)));
        assert!(config.is_asymmetric());
        assert_eq!(config.as_tuple(), (1, 2));
    }

    #[test]
    #[should_panic(expected = "Negative pad values are not supported")]
    fn test_padding_config_1d_negative() {
        let pads = vec![-1, -1];
        let _ = padding_config_1d(&pads);
    }

    // 2D padding tests
    #[test]
    fn test_padding_config_2d_valid() {
        let pads = vec![0, 0, 0, 0];
        let config = padding_config_2d(&pads);
        assert!(matches!(config, PaddingConfig2d::Valid));
        assert!(!config.is_asymmetric());
    }

    #[test]
    fn test_padding_config_2d_explicit_symmetric() {
        let pads = vec![2, 2, 2, 2];
        let config = padding_config_2d(&pads);
        assert!(matches!(config, PaddingConfig2d::Explicit(2, 2, 2, 2)));
        assert!(!config.is_asymmetric());
        assert_eq!(config.as_tuple(), (2, 2, 2, 2));
    }

    #[test]
    fn test_padding_config_2d_explicit_asymmetric() {
        // pads = [top, left, bottom, right]
        let pads = vec![1, 2, 3, 4];
        let config = padding_config_2d(&pads);
        assert!(matches!(config, PaddingConfig2d::Explicit(1, 2, 3, 4)));
        assert!(config.is_asymmetric());
        assert_eq!(config.as_tuple(), (1, 2, 3, 4));
    }

    #[test]
    fn test_padding_config_2d_explicit_asymmetric_top_bottom() {
        // top != bottom but left == right
        let pads = vec![1, 2, 3, 2];
        let config = padding_config_2d(&pads);
        assert!(matches!(config, PaddingConfig2d::Explicit(1, 2, 3, 2)));
        assert!(config.is_asymmetric());
    }

    #[test]
    fn test_padding_config_2d_explicit_asymmetric_left_right() {
        // left != right but top == bottom
        let pads = vec![2, 1, 2, 3];
        let config = padding_config_2d(&pads);
        assert!(matches!(config, PaddingConfig2d::Explicit(2, 1, 2, 3)));
        assert!(config.is_asymmetric());
    }

    #[test]
    #[should_panic(expected = "Negative pad values are not supported")]
    fn test_padding_config_2d_negative() {
        let pads = vec![-1, -1, -1, -1];
        let _ = padding_config_2d(&pads);
    }

    // 3D padding tests
    #[test]
    fn test_padding_config_3d_valid() {
        let pads = vec![0, 0, 0, 0, 0, 0];
        let config = padding_config_3d(&pads);
        assert!(matches!(config, PaddingConfig3d::Valid));
        assert!(!config.is_asymmetric());
    }

    #[test]
    fn test_padding_config_3d_explicit_symmetric() {
        let pads = vec![2, 3, 1, 2, 3, 1];
        let config = padding_config_3d(&pads);
        assert!(matches!(
            config,
            PaddingConfig3d::Explicit(2, 3, 1, 2, 3, 1)
        ));
        assert!(!config.is_asymmetric());
        assert_eq!(config.as_tuple(), (2, 3, 1, 2, 3, 1));
    }

    #[test]
    fn test_padding_config_3d_explicit_asymmetric() {
        // pads = [front, top, left, back, bottom, right]
        let pads = vec![1, 2, 3, 4, 5, 6];
        let config = padding_config_3d(&pads);
        assert!(matches!(
            config,
            PaddingConfig3d::Explicit(1, 2, 3, 4, 5, 6)
        ));
        assert!(config.is_asymmetric());
        assert_eq!(config.as_tuple(), (1, 2, 3, 4, 5, 6));
    }

    #[test]
    fn test_padding_config_3d_explicit_asymmetric_partial() {
        // Only front != back
        let pads = vec![1, 3, 1, 2, 3, 1];
        let config = padding_config_3d(&pads);
        assert!(matches!(
            config,
            PaddingConfig3d::Explicit(1, 3, 1, 2, 3, 1)
        ));
        assert!(config.is_asymmetric());
    }

    #[test]
    #[should_panic(expected = "Negative pad values are not supported")]
    fn test_padding_config_3d_negative() {
        let pads = vec![-1, -1, -1, -1, -1, -1];
        let _ = padding_config_3d(&pads);
    }
}