onnx-runtime-loader 0.1.0-dev.3

ONNX protobuf loader for the ORT 2.0 runtime: model parsing, weight mmap, and shape inference into onnx-runtime-ir
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
//! Build an [`onnx_runtime_ir::Graph`] from a decoded `ModelProto` (§19.1).
//!
//! Responsible for the graph-construction invariants of `docs/ORT2.md` §3.5:
//! stable value ids, unique node outputs (SSA), source values for inputs and
//! initializers, and interning symbolic dims that share a protobuf name.

use std::collections::HashMap;

use onnx_runtime_ir::{
    Attribute, DataType, Dim, Graph, Node, NodeId, Shape, TensorData, TypeProto, ValueId,
};

use crate::LoaderError;
use crate::proto::onnx::{
    self, AttributeProto, GraphProto, ModelProto, TensorShapeProto, attribute_proto,
    tensor_shape_proto, type_proto,
};
use crate::weights::tensor_data_from_proto;

/// The result of building a graph: the IR graph plus the mapping from ONNX
/// tensor names to the value ids they were assigned (needed by the weight
/// loader).
pub(crate) struct BuiltGraph {
    pub(crate) graph: Graph,
    pub(crate) name_map: HashMap<String, ValueId>,
}

/// Build the IR graph (nodes, values, symbols, opsets) from a `ModelProto`.
///
/// Weights and shape inference are applied by later pipeline stages.
///
/// The graph returned here is **structurally incomplete**: top-level
/// initializers are created as named values, but their [`WeightRef`] source
/// data is attached later by the weight loader
/// ([`crate::weights::load_weights`] → `Graph::set_initializer`). Structural
/// validation ([`Graph::validate`]) is therefore deliberately deferred to the
/// full pipeline (see `build_from_bytes_with_weights`), where it runs *after*
/// initializers are registered — otherwise a legal initializer that is also a
/// graph output (or a pre-IR-4 input that is also an initializer) would be
/// mis-flagged as a producer-less value, because `Graph::validate` recognizes
/// an initializer as a valid value source only once it appears in
/// `graph.initializers`.
///
/// [`WeightRef`]: onnx_runtime_ir::WeightRef
/// [`Graph::validate`]: onnx_runtime_ir::Graph::validate
pub(crate) fn build_graph(model: &ModelProto) -> Result<BuiltGraph, LoaderError> {
    // Expand any model-local function calls into their primitive bodies before
    // building the IR, so the rest of the pipeline only ever sees ops the
    // runtime has kernels for. No-op (borrow) when the model declares no
    // functions.
    let inlined = crate::function_inline::inline_functions(model)?;
    let model = inlined.as_ref();

    let mut graph = Graph::new();

    // Opset imports: domain -> version.
    for opset in &model.opset_import {
        if opset.version > 0 {
            graph
                .opset_imports
                .insert(opset.domain.clone(), opset.version as u64);
        }
    }

    let graph_proto = model
        .graph
        .as_ref()
        .ok_or_else(|| LoaderError::GraphBuild("ModelProto has no graph".into()))?;

    let name_map = build_graph_proto(&mut graph, graph_proto, true)?;

    Ok(BuiltGraph { graph, name_map })
}

/// Populate `graph` from a `GraphProto`. When `is_top_level` is true, inputs
/// and outputs are registered as graph I/O. Returns the name→value map for the
/// values created in this graph scope.
fn build_graph_proto(
    graph: &mut Graph,
    gp: &GraphProto,
    is_top_level: bool,
) -> Result<HashMap<String, ValueId>, LoaderError> {
    let mut names: HashMap<String, ValueId> = HashMap::new();

    // 1. Initializers: fully-typed source values (producer = None).
    for init in &gp.initializer {
        if init.name.is_empty() {
            continue;
        }
        let dtype = decode_dtype(init.data_type, || format!("initializer '{}'", init.name))?;
        let dims_vec: Vec<usize> = init.dims.iter().map(|&d| d.max(0) as usize).collect();
        let shape: Shape = dims_vec.iter().copied().map(Dim::Static).collect();
        let vid = graph.create_named_value(init.name.clone(), dtype, shape);
        names.insert(init.name.clone(), vid);
        // Subgraph (non-top-level) initializers are not visited by the model's
        // top-level weight loader (`weights::load_weights` only walks the root
        // `GraphProto`), so a control-flow body's own constants would otherwise
        // be producer-less values with no data — indistinguishable from an
        // outer-scope capture, and unrunnable. Inline their bytes here so the
        // subgraph is a self-contained runnable graph. Only inline-encoded
        // initializers are supported inside subgraphs; an external-data body
        // initializer is left unbound and surfaces as a clear missing-source
        // error at execution rather than being silently mis-read.
        if !is_top_level
            && init.data_location != crate::proto::onnx::tensor_proto::DataLocation::External as i32
        {
            let td = crate::weights::tensor_data_from_proto(init, dtype, &dims_vec)?;
            graph.set_initializer(vid, onnx_runtime_ir::WeightRef::Inline(td));
        }
    }

    // 2. Graph inputs. Names that are also initializers are constants, not
    //    real graph inputs (invariant §3.5.3). Both the top-level graph and
    //    control-flow subgraph bodies record their formal input signature in
    //    `graph.inputs`, in declared order: a subgraph body's formal parameters
    //    (e.g. Loop's `iter_num`/`cond`/loop-carried, Scan's state/scan slices)
    //    are bound positionally at execution, so their order must survive load.
    for vi in &gp.input {
        if vi.name.is_empty() {
            continue;
        }
        if names.contains_key(&vi.name) {
            continue; // initializer-backed constant input
        }
        let (dtype, shape, type_known, shape_known) = value_info_type(graph, vi)?;
        let vid = graph.create_named_value(vi.name.clone(), dtype, shape);
        mark_unknown_type_info(graph, vid, type_known, shape_known);
        names.insert(vi.name.clone(), vid);
        graph.add_input(vid);
    }

    // 3. Declared value_info type hints for interior values.
    for vi in &gp.value_info {
        if vi.name.is_empty() || names.contains_key(&vi.name) {
            continue;
        }
        let (dtype, shape, type_known, shape_known) = value_info_type(graph, vi)?;
        let vid = graph.create_named_value(vi.name.clone(), dtype, shape);
        mark_unknown_type_info(graph, vid, type_known, shape_known);
        names.insert(vi.name.clone(), vid);
    }

    // 4. Graph outputs: typed values that a node will later produce by name.
    for vi in &gp.output {
        if vi.name.is_empty() {
            continue;
        }
        if !names.contains_key(&vi.name) {
            let (dtype, shape, type_known, shape_known) = value_info_type(graph, vi)?;
            let vid = graph.create_named_value(vi.name.clone(), dtype, shape);
            mark_unknown_type_info(graph, vid, type_known, shape_known);
            names.insert(vi.name.clone(), vid);
        }
    }

    // 5. Nodes: wire inputs/outputs, converting attributes.
    for np in &gp.node {
        let inputs: Vec<Option<ValueId>> = np
            .input
            .iter()
            .map(|name| {
                if name.is_empty() {
                    None
                } else {
                    Some(get_or_create(graph, &mut names, name))
                }
            })
            .collect();

        let outputs: Vec<ValueId> = np
            .output
            .iter()
            .map(|name| {
                if name.is_empty() {
                    // An omitted (unused) optional output: give it an anonymous
                    // value to preserve positional arity.
                    graph.create_value(DataType::Float32, Vec::new())
                } else {
                    get_or_create(graph, &mut names, name)
                }
            })
            .collect();

        let mut node = Node::new(NodeId(0), np.op_type.clone(), inputs, outputs);
        node.name = np.name.clone();
        node.domain = np.domain.clone();
        if !np.doc_string.is_empty() {
            node.doc_string = Some(np.doc_string.clone());
        }
        for ap in &np.attribute {
            if let Some((key, attr)) = convert_attribute(graph, ap)? {
                node.attributes.insert(key, attr);
            }
        }

        let nid = graph.insert_node(node);
        register_subgraphs(graph, nid);
    }

    // 6. Register graph outputs in order. Both the top-level graph and each
    //    control-flow subgraph body record their formal output signature here,
    //    in declared order: a body's outputs (e.g. Loop's
    //    `cond_out`/loop-carried/scan-outputs) are consumed positionally by the
    //    control-flow executor, so the order must survive load.
    for vi in &gp.output {
        if let Some(&vid) = names.get(&vi.name) {
            graph.add_output(vid);
        }
    }

    Ok(names)
}

/// After a node is inserted, move any `Graph`/`Graphs` attribute bodies into the
/// graph's `subgraphs` index so traversal/validation can reach them (§3.3).
fn register_subgraphs(graph: &mut Graph, nid: NodeId) {
    let attrs: Vec<(String, usize)> = graph
        .node(nid)
        .attributes
        .iter()
        .filter_map(|(k, v)| match v {
            Attribute::Graph(_) => Some((k.clone(), 1)),
            Attribute::Graphs(gs) => Some((k.clone(), gs.len())),
            _ => None,
        })
        .collect();
    for (key, count) in attrs {
        match graph.node(nid).attributes.get(&key) {
            Some(Attribute::Graph(g)) => {
                let sub = (**g).clone();
                graph.subgraphs.insert((nid, key), sub);
            }
            Some(Attribute::Graphs(_)) => {
                for i in 0..count {
                    if let Some(Attribute::Graphs(gs)) = graph.node(nid).attributes.get(&key) {
                        let sub = gs[i].clone();
                        graph.subgraphs.insert((nid, format!("{key}[{i}]")), sub);
                    }
                }
            }
            _ => {}
        }
    }
}

/// Fetch the value id for `name`, creating a placeholder value if it does not
/// exist yet (interior SSA value with as-yet-unknown type).
fn get_or_create(graph: &mut Graph, names: &mut HashMap<String, ValueId>, name: &str) -> ValueId {
    if let Some(&vid) = names.get(name) {
        return vid;
    }
    let vid = graph.create_named_value(name.to_string(), DataType::Float32, Vec::new());
    graph.mark_value_type_unknown(vid);
    graph.mark_value_shape_unknown(vid);
    names.insert(name.to_string(), vid);
    vid
}

fn mark_unknown_type_info(graph: &mut Graph, value: ValueId, type_known: bool, shape_known: bool) {
    if !type_known {
        graph.mark_value_type_unknown(value);
    }
    if !shape_known {
        graph.mark_value_shape_unknown(value);
    }
}

/// Decode a raw ONNX `TensorProto.DataType` integer into an IR [`DataType`],
/// failing closed when the runtime does not model the type. This prevents an
/// unmodeled dtype (e.g. `COMPLEX64` = 14) from being silently mislabeled as
/// `Float32` at any tensor-type decode site (§19.1).
fn decode_dtype(raw: i32, context: impl FnOnce() -> String) -> Result<DataType, LoaderError> {
    DataType::from_onnx(raw).ok_or_else(|| LoaderError::UnsupportedDataType {
        raw,
        context: context(),
    })
}

/// Extract `(dtype, shape, type_known, shape_known)` from a `ValueInfoProto`,
/// interning symbolic dims into `graph` by name.
fn value_info_type(
    graph: &mut Graph,
    vi: &onnx::ValueInfoProto,
) -> Result<(DataType, Shape, bool, bool), LoaderError> {
    match vi.r#type.as_ref() {
        Some(tp) => type_proto_to_dtype_shape(graph, tp, &vi.name),
        // A value-info with no type at all is genuinely untyped, not an
        // unmodeled dtype: keep the tensor-centric placeholder default.
        None => Ok((DataType::Float32, Vec::new(), false, false)),
    }
}

fn type_proto_to_dtype_shape(
    graph: &mut Graph,
    tp: &onnx::TypeProto,
    name: &str,
) -> Result<(DataType, Shape, bool, bool), LoaderError> {
    match tp.value.as_ref() {
        Some(type_proto::Value::TensorType(t)) => {
            let dtype = decode_dtype(t.elem_type, || format!("value-info '{name}'"))?;
            let shape_known = t.shape.is_some();
            let shape = t
                .shape
                .as_ref()
                .map(|s| tensor_shape_to_shape(graph, s))
                .unwrap_or_default();
            Ok((dtype, shape, true, shape_known))
        }
        Some(type_proto::Value::SparseTensorType(t)) => {
            let dtype = decode_dtype(t.elem_type, || format!("value-info '{name}'"))?;
            let shape_known = t.shape.is_some();
            let shape = t
                .shape
                .as_ref()
                .map(|s| tensor_shape_to_shape(graph, s))
                .unwrap_or_default();
            Ok((dtype, shape, true, shape_known))
        }
        // Non-tensor containers (sequence/map/optional): the IR value model is
        // tensor-centric; record a placeholder type. These do not occur in the
        // Phase-1 (BERT) op set.
        _ => Ok((DataType::Float32, Vec::new(), false, false)),
    }
}

/// Convert an ONNX `TensorShapeProto` to an IR [`Shape`], interning dim-params
/// by name (invariant §3.5.4) and allocating fresh anonymous symbols for
/// unknown dims.
fn tensor_shape_to_shape(graph: &mut Graph, tsp: &TensorShapeProto) -> Shape {
    tsp.dim
        .iter()
        .map(|d| match d.value.as_ref() {
            Some(tensor_shape_proto::dimension::Value::DimValue(v)) if *v >= 0 => {
                Dim::Static(*v as usize)
            }
            Some(tensor_shape_proto::dimension::Value::DimParam(name)) if !name.is_empty() => {
                Dim::Symbolic(graph.intern_symbol(name))
            }
            // Unknown dim (no value, negative, or empty param): fresh symbol.
            _ => Dim::Symbolic(graph.create_symbol(None)),
        })
        .collect()
}

/// Convert an `AttributeProto` to an IR `(name, Attribute)`. Returns `Ok(None)`
/// for empty/absent attributes.
fn convert_attribute(
    graph: &mut Graph,
    ap: &AttributeProto,
) -> Result<Option<(String, Attribute)>, LoaderError> {
    use attribute_proto::AttributeType as AT;

    // Determine the attribute kind, falling back to field-presence heuristics
    // for IR<0.0.2 protos where `type` may be unset.
    let ty = AT::try_from(ap.r#type).unwrap_or(AT::Undefined);

    let attr = match ty {
        AT::Float => Attribute::Float(ap.f),
        AT::Int => Attribute::Int(ap.i),
        // STRING attributes are arbitrary byte strings on the wire (an opaque
        // blob, a path, or text). Preserve the exact bytes rather than lossily
        // decoding as UTF-8, so encode is a byte-exact inverse of decode.
        AT::String => Attribute::String(ap.s.clone()),
        AT::Floats => Attribute::Floats(ap.floats.clone()),
        AT::Ints => Attribute::Ints(ap.ints.clone()),
        AT::Strings => Attribute::Strings(ap.strings.clone()),
        AT::Tensor => match ap.t.as_ref() {
            Some(t) => Attribute::Tensor(convert_tensor(t)?),
            None => return Ok(None),
        },
        AT::Tensors => Attribute::Tensors(
            ap.tensors
                .iter()
                .map(convert_tensor)
                .collect::<Result<_, _>>()?,
        ),
        AT::SparseTensor => match ap.sparse_tensor.as_ref() {
            Some(t) => Attribute::SparseTensor(convert_sparse_tensor(t)?),
            None => return Ok(None),
        },
        AT::SparseTensors => Attribute::SparseTensors(
            ap.sparse_tensors
                .iter()
                .map(convert_sparse_tensor)
                .collect::<Result<_, _>>()?,
        ),
        AT::Graph => match ap.g.as_ref() {
            Some(g) => Attribute::Graph(Box::new(build_subgraph(g)?)),
            None => return Ok(None),
        },
        AT::Graphs => Attribute::Graphs(
            ap.graphs
                .iter()
                .map(build_subgraph)
                .collect::<Result<_, _>>()?,
        ),
        AT::TypeProto => match ap.tp.as_ref() {
            Some(tp) => Attribute::TypeProto(convert_type_proto(graph, tp)?),
            None => return Ok(None),
        },
        AT::TypeProtos => Attribute::TypeProtos(
            ap.type_protos
                .iter()
                .map(|tp| convert_type_proto(graph, tp))
                .collect::<Result<_, _>>()?,
        ),
        // Field-presence fallback when `type` is UNDEFINED.
        AT::Undefined => {
            if let Some(g) = ap.g.as_ref() {
                Attribute::Graph(Box::new(build_subgraph(g)?))
            } else if !ap.graphs.is_empty() {
                Attribute::Graphs(
                    ap.graphs
                        .iter()
                        .map(build_subgraph)
                        .collect::<Result<_, _>>()?,
                )
            } else if let Some(t) = ap.t.as_ref() {
                Attribute::Tensor(convert_tensor(t)?)
            } else if !ap.floats.is_empty() {
                Attribute::Floats(ap.floats.clone())
            } else if !ap.ints.is_empty() {
                Attribute::Ints(ap.ints.clone())
            } else if !ap.strings.is_empty() {
                Attribute::Strings(ap.strings.clone())
            } else if !ap.s.is_empty() {
                Attribute::String(ap.s.clone())
            } else if ap.i != 0 {
                Attribute::Int(ap.i)
            } else if ap.f != 0.0 {
                Attribute::Float(ap.f)
            } else {
                return Ok(None);
            }
        }
    };
    Ok(Some((ap.name.clone(), attr)))
}

fn build_subgraph(gp: &GraphProto) -> Result<Graph, LoaderError> {
    let mut graph = Graph::new();
    build_graph_proto(&mut graph, gp, false)?;
    Ok(graph)
}

fn convert_tensor(t: &onnx::TensorProto) -> Result<TensorData, LoaderError> {
    let dtype = decode_dtype(t.data_type, || format!("attribute tensor '{}'", t.name))?;
    let dims: Vec<usize> = t.dims.iter().map(|&d| d.max(0) as usize).collect();
    tensor_data_from_proto(t, dtype, &dims)
}

fn convert_sparse_tensor(
    tensor: &onnx::SparseTensorProto,
) -> Result<onnx_runtime_ir::SparseTensorData, LoaderError> {
    let values = tensor
        .values
        .as_ref()
        .ok_or_else(|| LoaderError::GraphBuild("sparse tensor is missing values".into()))
        .and_then(convert_tensor)?;
    let indices = tensor
        .indices
        .as_ref()
        .ok_or_else(|| LoaderError::GraphBuild("sparse tensor is missing indices".into()))
        .and_then(convert_tensor)?;
    Ok(onnx_runtime_ir::SparseTensorData {
        values,
        indices,
        dims: tensor.dims.iter().map(|&dim| dim.max(0) as usize).collect(),
    })
}

fn convert_type_proto(graph: &mut Graph, tp: &onnx::TypeProto) -> Result<TypeProto, LoaderError> {
    let ty = match tp.value.as_ref() {
        Some(type_proto::Value::TensorType(t)) => {
            let dtype = decode_dtype(t.elem_type, || "type-proto attribute (tensor)".to_string())?;
            let shape = t
                .shape
                .as_ref()
                .map(|s| tensor_shape_to_shape(graph, s))
                .unwrap_or_default();
            TypeProto::Tensor { dtype, shape }
        }
        Some(type_proto::Value::SparseTensorType(t)) => {
            let dtype = decode_dtype(t.elem_type, || {
                "type-proto attribute (sparse tensor)".to_string()
            })?;
            let shape = t
                .shape
                .as_ref()
                .map(|s| tensor_shape_to_shape(graph, s))
                .unwrap_or_default();
            TypeProto::SparseTensor { dtype, shape }
        }
        Some(type_proto::Value::SequenceType(s)) => {
            let inner = s
                .elem_type
                .as_ref()
                .map(|e| convert_type_proto(graph, e))
                .transpose()?
                .unwrap_or(TypeProto::Tensor {
                    dtype: DataType::Float32,
                    shape: Vec::new(),
                });
            TypeProto::Sequence(Box::new(inner))
        }
        Some(type_proto::Value::OptionalType(o)) => {
            let inner = o
                .elem_type
                .as_ref()
                .map(|e| convert_type_proto(graph, e))
                .transpose()?
                .unwrap_or(TypeProto::Tensor {
                    dtype: DataType::Float32,
                    shape: Vec::new(),
                });
            TypeProto::Optional(Box::new(inner))
        }
        Some(type_proto::Value::MapType(m)) => {
            let key = decode_dtype(m.key_type, || "type-proto attribute (map key)".to_string())?;
            let value = m
                .value_type
                .as_ref()
                .map(|e| convert_type_proto(graph, e))
                .transpose()?
                .unwrap_or(TypeProto::Tensor {
                    dtype: DataType::Float32,
                    shape: Vec::new(),
                });
            TypeProto::Map {
                key,
                value: Box::new(value),
            }
        }
        Some(type_proto::Value::OpaqueType(_)) => TypeProto::Tensor {
            dtype: DataType::Float32,
            shape: Vec::new(),
        },
        None => TypeProto::Tensor {
            dtype: DataType::Float32,
            shape: Vec::new(),
        },
    };
    Ok(ty)
}