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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! ONNX argument types
//!
//! This module contains types for representing node inputs and outputs,
//! including their types, data sources, and metadata.

use core::fmt;
use std::fmt::Formatter;

use burn_tensor::DType;

use super::tensor_data_ext::TensorData;
use crate::tensor_store::ValueStore;

pub type Rank = usize;
pub type Shape = Vec<Option<usize>>;

/// Unique identifier for tensor data in the central store
pub type DataId = usize;

/// Describes where an argument's value comes from
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueSource {
    /// Static constant value embedded in the argument (name="" with embedded data)
    Static(DataId),
    /// Points to a constant node output (name="constant1_out1")
    Constant,
    /// Points to a runtime node output (name="conv1_out1")
    Dynamic,
    /// Optional/not provided (name="")
    Optional,
}

/// A node input or output.
#[derive(Clone)]
pub struct Argument {
    /// The name of the node input.
    pub name: String,

    /// The type of the argument.
    pub ty: ArgType,

    /// Describes where this argument's value comes from
    /// For Static values, contains the tensor data ID directly
    pub value_source: ValueSource,

    /// Reference to value storage for constant lookup
    /// This is an Rc-wrapped immutable store - no RefCell needed since we only read
    pub(crate) value_store: Option<ValueStore>,
}

impl fmt::Debug for Argument {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Argument")
            .field("name", &self.name)
            .field("ty", &self.ty)
            .field("value_source", &self.value_source)
            .finish()
    }
}

impl fmt::Display for TensorType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}[", self.dtype)?;
        match &self.static_shape {
            Some(dims) => {
                for (i, dim) in dims.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    match dim {
                        Some(val) => write!(f, "{val}")?,
                        None => write!(f, "?")?,
                    }
                }
            }
            None => {
                for i in 0..self.rank {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "?")?;
                }
            }
        }
        write!(f, "]")
    }
}

impl fmt::Display for ArgType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ArgType::ScalarTensor(dtype) => write!(f, "ScalarTensor({dtype:?})"),
            ArgType::ScalarNative(dtype) => write!(f, "ScalarNative({dtype:?})"),
            ArgType::Shape(rank) => write!(f, "Shape({rank})"),
            ArgType::Tensor(t) => write!(f, "{t}"),
        }
    }
}

impl fmt::Display for ValueSource {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ValueSource::Dynamic => Ok(()),
            ValueSource::Static(id) => write!(f, " [static({id})]"),
            ValueSource::Constant => write!(f, " [constant]"),
            ValueSource::Optional => write!(f, "<optional>"),
        }
    }
}

impl fmt::Display for Argument {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if self.is_optional() {
            return write!(f, "<optional>");
        }
        let name = if self.name.is_empty() {
            "_"
        } else {
            &self.name
        };
        write!(f, "{name}: {}{}", self.ty, self.value_source)
    }
}

impl Argument {
    /// Copy everything except the name from the other argument
    pub fn copy_value(&mut self, other_arg: &Argument) {
        self.ty = other_arg.ty.clone();
        self.value_source = other_arg.value_source;
    }
}

/// The type of an argument.
#[derive(Debug, Clone, PartialEq)]
pub enum ArgType {
    /// A 1D tensor on device (rank 1, shape \[1\]). Used for scalar constants and
    /// intermediate values that participate in tensor arithmetic via broadcasting.
    ScalarTensor(DType),
    /// A native Rust scalar (rank 0). Used for shape computations, indices,
    /// control flow conditions, and graph I/O boundaries.
    ScalarNative(DType),
    Shape(Rank),
    Tensor(TensorType),
}

/// Represents the type of a tensor.
#[derive(Debug, Clone, PartialEq)]
pub struct TensorType {
    /// The data type of the tensor values (e.g. F32, F64, I64, etc.)
    pub dtype: DType,

    /// The number of dimensions in the tensor
    pub rank: Rank,

    /// Static shape if known (populated during shape inference).
    /// Each dimension is independently `Some(val)` or `None` (symbolic).
    pub static_shape: Option<Vec<Option<usize>>>,
}

impl Default for TensorType {
    fn default() -> Self {
        Self {
            dtype: DType::F32,
            rank: 0,
            static_shape: None,
        }
    }
}

impl TensorType {
    pub fn new(dtype: DType, rank: Rank, static_shape: Option<Vec<Option<usize>>>) -> Self {
        Self {
            dtype,
            rank,
            static_shape,
        }
    }

    /// Create a TensorType with a fully-known static shape (all dims concrete).
    pub fn new_known(dtype: DType, shape: Vec<usize>) -> Self {
        let rank = shape.len();
        Self {
            dtype,
            rank,
            static_shape: Some(shape.into_iter().map(Some).collect()),
        }
    }

    /// Returns the static shape only if ALL dimensions are known (no symbolic dims).
    pub fn static_shape_known(&self) -> Option<Vec<usize>> {
        self.static_shape
            .as_ref()
            .and_then(|dims| dims.iter().copied().collect::<Option<Vec<usize>>>())
    }

    /// Merge static_shape from another TensorType, keeping the most informative value
    /// for each dimension. Returns true if any dimension was updated.
    ///
    /// Merge rules:
    /// - If self has no shape info but other does, use other's shape
    /// - If both have shape info with matching rank, merge dimension by dimension
    ///   (prefer known values over unknown)
    /// - If ranks differ, no merge is possible (other types like dtype/rank take precedence)
    pub fn merge_static_shape(&mut self, other: &TensorType) -> bool {
        // Ranks must match for any merge to be valid
        if self.rank != other.rank {
            return false;
        }

        match (&mut self.static_shape, &other.static_shape) {
            // self has no shape info, other does -> take other's shape
            (None, Some(other_shape)) if other_shape.len() == self.rank => {
                self.static_shape = Some(other_shape.clone());
                true
            }
            // Both have shape info with matching length -> merge dimension by dimension
            (Some(self_shape), Some(other_shape)) if self_shape.len() == other_shape.len() => {
                let mut changed = false;
                for (self_dim, other_dim) in self_shape.iter_mut().zip(other_shape.iter()) {
                    // If self doesn't know this dimension but other does, take other's value
                    if self_dim.is_none() && other_dim.is_some() {
                        *self_dim = *other_dim;
                        changed = true;
                    }
                }
                changed
            }
            // Other cases: no merge possible or nothing to merge
            _ => false,
        }
    }
}

impl Default for ArgType {
    fn default() -> Self {
        Self::Tensor(TensorType::default())
    }
}

impl ArgType {
    /// Merge static_shape information from another ArgType.
    ///
    /// Used during type inference to preserve shape info from value_info when
    /// syncing inferred types. The inferred type (self) provides the base
    /// dtype/rank, but we merge in any more-specific dimension info from other.
    ///
    /// Returns true if any shape dimension was updated.
    pub fn merge_static_shape(&mut self, other: &ArgType) -> bool {
        match (self, other) {
            (ArgType::Tensor(self_tensor), ArgType::Tensor(other_tensor)) => {
                self_tensor.merge_static_shape(other_tensor)
            }
            // Non-tensor types have no static_shape to merge
            _ => false,
        }
    }

    /// Check if this is any scalar type (ScalarTensor or ScalarNative)
    pub fn is_scalar(&self) -> bool {
        matches!(self, Self::ScalarTensor(_) | Self::ScalarNative(_))
    }

    /// Check if this is a ScalarTensor (1D tensor on device)
    pub fn is_scalar_tensor(&self) -> bool {
        matches!(self, Self::ScalarTensor(_))
    }

    /// Check if this is a ScalarNative (native Rust type)
    pub fn is_scalar_native(&self) -> bool {
        matches!(self, Self::ScalarNative(_))
    }

    /// Check if this type lives on the device (Tensor or ScalarTensor)
    pub fn is_on_device(&self) -> bool {
        matches!(self, Self::Tensor(_) | Self::ScalarTensor(_))
    }

    /// Check if this is a tensor type
    pub fn is_tensor(&self) -> bool {
        matches!(self, Self::Tensor(_))
    }

    /// Check if this is a shape type
    pub fn is_shape(&self) -> bool {
        matches!(self, Self::Shape(_))
    }

    /// Get the rank (number of dimensions)
    pub fn rank(&self) -> usize {
        match self {
            ArgType::ScalarTensor(_) => 1,
            ArgType::ScalarNative(_) => 0,
            ArgType::Shape(_) => 1,
            ArgType::Tensor(t) => t.rank,
        }
    }

    //TODO Element kind

    /// Get the data type
    pub fn elem_type(&self) -> DType {
        match self {
            ArgType::ScalarTensor(d) | ArgType::ScalarNative(d) => *d,
            ArgType::Shape(_) => panic!("ArgType::Shape has no DType"),
            ArgType::Tensor(t) => t.dtype,
        }
    }

    /// Get the static shape if available (per-dim, may contain `None` for symbolic dims)
    pub fn static_shape(&self) -> Option<&Vec<Option<usize>>> {
        match self {
            ArgType::Tensor(t) => t.static_shape.as_ref(),
            _ => None,
        }
    }

    /// Get the static shape only if ALL dimensions are known (no symbolic dims)
    pub fn static_shape_known(&self) -> Option<Vec<usize>> {
        match self {
            ArgType::Tensor(t) => t.static_shape_known(),
            _ => None,
        }
    }
}

impl Argument {
    /// Create a new argument with a specific type
    pub fn new(name: impl Into<String>, ty: ArgType) -> Self {
        let name = name.into();
        // Default to Dynamic (points to a node output by name)
        let value_source = if name.is_empty() {
            ValueSource::Optional
        } else {
            ValueSource::Dynamic
        };

        Self {
            name,
            ty,
            value_source,
            value_store: None,
        }
    }

    /// Create a new argument with default type (F32 tensor rank 0)
    pub fn from_name(name: impl Into<String>) -> Self {
        Self::new(name, ArgType::default())
    }

    /// Get the constant value from the central tensor store
    pub fn value(&self) -> Option<TensorData> {
        if self.value_store.is_none() {
            if matches!(
                self.value_source,
                ValueSource::Constant | ValueSource::Static(_)
            ) {
                log::warn!(
                    "value() called on '{}' (value_source={:?}) but value_store is None",
                    self.name,
                    self.value_source
                );
            }
            return None;
        }
        let store = self.value_store.as_ref()?;

        match &self.value_source {
            // Static: data is embedded directly
            ValueSource::Static(data_id) => {
                let result = store.get_tensor_data(*data_id);
                if result.is_none() {
                    log::warn!(
                        "value() for Static({}) on '{}' returned None - store has {} tensors",
                        data_id,
                        self.name,
                        store.tensor_count()
                    );
                }
                result
            }
            // Constant: look up the constant node by output name
            ValueSource::Constant => {
                let data_id = store.get_constant_data_id(&self.name);
                if data_id.is_none() {
                    log::warn!(
                        "value() lookup failed for '{}': constant not found in store (constant_map has {} entries)",
                        self.name,
                        store.constant_map_len()
                    );
                }
                let data_id = data_id?;
                store.get_tensor_data(data_id)
            }
            // Dynamic/Optional: no constant data
            ValueSource::Dynamic | ValueSource::Optional => None,
        }
    }

    /// Set the value store
    pub(crate) fn set_value_store(&mut self, store: ValueStore) {
        self.value_store = Some(store);
    }

    /// Check if this is a static constant (embedded value)
    pub fn is_static(&self) -> bool {
        matches!(self.value_source, ValueSource::Static(_))
    }

    /// Check if this argument points to a constant node output
    pub fn is_constant(&self) -> bool {
        self.value_source == ValueSource::Constant
    }

    /// Check if this argument points to a runtime node output
    pub fn is_dynamic(&self) -> bool {
        self.value_source == ValueSource::Dynamic
    }

    /// Check if this argument is optional/not provided
    pub fn is_optional(&self) -> bool {
        self.value_source == ValueSource::Optional
    }

    /// Convert a Constant argument to Static by embedding the constant's data
    ///
    /// This looks up the constant node by name, retrieves its data_id,
    /// and embeds it in this argument, clearing the name.
    ///
    /// Returns an error if this is not a Constant argument.
    pub fn to_static(&mut self) -> Result<(), crate::processor::ProcessError> {
        use crate::processor::ProcessError;

        if !self.is_constant() {
            return Err(ProcessError::Custom(format!(
                "Cannot convert {:?} argument to Static (only Constant can be converted)",
                self.value_source
            )));
        }

        // Look up the constant node by name
        let store = self.value_store.as_ref().ok_or_else(|| {
            ProcessError::Custom("No value store available to look up constant".to_string())
        })?;

        // Get the data_id from the constant map using the output name
        let data_id = store.get_constant_data_id(&self.name).ok_or_else(|| {
            ProcessError::Custom(format!(
                "Constant node not found or has no data_id for output name: {}",
                self.name
            ))
        })?;

        // Embed the data_id in ValueSource::Static, clear the name
        // The name is cleared because Static values are accessed via data_id, not by name
        self.value_source = ValueSource::Static(data_id);
        self.name.clear();

        Ok(())
    }

    /// Create an argument with a constant i64 scalar value embedded.
    pub fn from_const_i64(name: impl Into<String>, value: i64) -> Self {
        Self::from_const_i64s(name, &[value], ArgType::ScalarNative(DType::I64))
    }

    /// Create an argument with a constant 1D i64 tensor embedded.
    pub fn from_const_i64_shape(name: impl Into<String>, values: &[i64]) -> Self {
        Self::from_const_i64s(name, values, ArgType::Shape(values.len()))
    }

    fn from_const_i64s(name: impl Into<String>, values: &[i64], ty: ArgType) -> Self {
        use crate::tensor_store::{TensorDataRef, TensorStore, ValueStore};
        use std::collections::HashMap;
        use std::sync::Arc;

        let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_ne_bytes()).collect();
        let shape = if values.len() == 1 && ty.is_scalar() {
            vec![]
        } else {
            vec![values.len()]
        };
        let data_ref = TensorDataRef::new(bytes::Bytes::from(bytes), shape, DType::I64);

        let mut tensor_store = TensorStore::new();
        let data_id = tensor_store.store(data_ref);

        let value_store = ValueStore::new(Arc::new(tensor_store), Arc::new(HashMap::new()));

        Self {
            name: name.into(),
            ty,
            value_source: ValueSource::Static(data_id),
            value_store: Some(value_store),
        }
    }
}

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

    #[test]
    fn test_merge_static_shape_none_with_some() {
        // Inferred type has no shape info, value_info has partial shape
        let mut inferred = TensorType::new(DType::F32, 2, None);
        let value_info = TensorType::new(DType::F32, 2, Some(vec![None, Some(1)]));

        let changed = inferred.merge_static_shape(&value_info);

        assert!(changed);
        assert_eq!(inferred.static_shape, Some(vec![None, Some(1)]));
    }

    #[test]
    fn test_merge_static_shape_some_with_none() {
        // Inferred type has shape info, value_info has none
        let mut inferred = TensorType::new(DType::F32, 2, Some(vec![Some(5), None]));
        let value_info = TensorType::new(DType::F32, 2, None);

        let changed = inferred.merge_static_shape(&value_info);

        assert!(!changed);
        assert_eq!(inferred.static_shape, Some(vec![Some(5), None]));
    }

    #[test]
    fn test_merge_static_shape_dimension_by_dimension() {
        // Both have partial info, different dimensions known
        let mut inferred = TensorType::new(DType::F32, 2, Some(vec![Some(5), None]));
        let value_info = TensorType::new(DType::F32, 2, Some(vec![None, Some(1)]));

        let changed = inferred.merge_static_shape(&value_info);

        assert!(changed);
        assert_eq!(inferred.static_shape, Some(vec![Some(5), Some(1)]));
    }

    #[test]
    fn test_merge_static_shape_no_change_when_same() {
        // Both have the same info
        let mut inferred = TensorType::new(DType::F32, 2, Some(vec![Some(5), Some(1)]));
        let value_info = TensorType::new(DType::F32, 2, Some(vec![Some(5), Some(1)]));

        let changed = inferred.merge_static_shape(&value_info);

        assert!(!changed);
        assert_eq!(inferred.static_shape, Some(vec![Some(5), Some(1)]));
    }

    #[test]
    fn test_merge_static_shape_inferred_takes_precedence_when_both_known() {
        // Both know a dimension but with different values - inferred wins
        let mut inferred = TensorType::new(DType::F32, 2, Some(vec![Some(5), Some(2)]));
        let value_info = TensorType::new(DType::F32, 2, Some(vec![Some(10), Some(1)]));

        let changed = inferred.merge_static_shape(&value_info);

        // Inferred already has values, so no change
        assert!(!changed);
        assert_eq!(inferred.static_shape, Some(vec![Some(5), Some(2)]));
    }

    #[test]
    fn test_merge_static_shape_rank_mismatch_no_merge() {
        // Ranks don't match - can't merge
        let mut inferred = TensorType::new(DType::F32, 3, None);
        let value_info = TensorType::new(DType::F32, 2, Some(vec![None, Some(1)]));

        let changed = inferred.merge_static_shape(&value_info);

        assert!(!changed);
        assert_eq!(inferred.static_shape, None);
    }

    #[test]
    fn test_merge_argtype_tensor() {
        let mut inferred =
            ArgType::Tensor(TensorType::new(DType::F32, 2, Some(vec![Some(5), None])));
        let value_info = ArgType::Tensor(TensorType::new(DType::F32, 2, Some(vec![None, Some(1)])));

        let changed = inferred.merge_static_shape(&value_info);

        assert!(changed);
        assert_eq!(
            inferred,
            ArgType::Tensor(TensorType::new(DType::F32, 2, Some(vec![Some(5), Some(1)])))
        );
    }

    #[test]
    fn test_merge_argtype_non_tensor_no_op() {
        let mut inferred = ArgType::ScalarNative(DType::F32);
        let value_info = ArgType::ScalarNative(DType::F32);

        let changed = inferred.merge_static_shape(&value_info);

        assert!(!changed);
    }

    #[test]
    fn test_display_tensor_type_known_shape() {
        let t = TensorType::new(DType::F32, 3, Some(vec![Some(2), Some(3), Some(4)]));
        assert_eq!(format!("{t}"), "F32[2, 3, 4]");
    }

    #[test]
    fn test_display_tensor_type_partial_shape() {
        let t = TensorType::new(DType::I64, 3, Some(vec![None, Some(3), None]));
        assert_eq!(format!("{t}"), "I64[?, 3, ?]");
    }

    #[test]
    fn test_display_tensor_type_no_shape() {
        let t = TensorType::new(DType::F32, 2, None);
        assert_eq!(format!("{t}"), "F32[?, ?]");
    }

    #[test]
    fn test_display_argtype_scalar() {
        let a = ArgType::ScalarNative(DType::F32);
        assert_eq!(format!("{a}"), "ScalarNative(F32)");

        let b = ArgType::ScalarTensor(DType::F32);
        assert_eq!(format!("{b}"), "ScalarTensor(F32)");
    }

    #[test]
    fn test_display_argtype_shape() {
        let a = ArgType::Shape(3);
        assert_eq!(format!("{a}"), "Shape(3)");
    }

    #[test]
    fn test_display_argument_dynamic() {
        let arg = Argument::new(
            "input",
            ArgType::Tensor(TensorType::new(DType::F32, 2, Some(vec![Some(2), Some(3)]))),
        );
        assert_eq!(format!("{arg}"), "input: F32[2, 3]");
    }

    #[test]
    fn test_display_argument_static() {
        let mut arg = Argument::new(
            "",
            ArgType::Tensor(TensorType::new_known(DType::F32, vec![16])),
        );
        arg.value_source = ValueSource::Static(0);
        assert_eq!(format!("{arg}"), "_: F32[16] [static(0)]");
    }

    #[test]
    fn test_display_argument_constant() {
        let mut arg = Argument::new(
            "bias",
            ArgType::Tensor(TensorType::new_known(DType::F32, vec![16])),
        );
        arg.value_source = ValueSource::Constant;
        assert_eq!(format!("{arg}"), "bias: F32[16] [constant]");
    }

    #[test]
    fn test_display_argument_optional() {
        let arg = Argument::new("", ArgType::default());
        assert_eq!(format!("{arg}"), "<optional>");
    }
}