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
//! Phase 4: Post-processing
//!
//! Eliminates no-op nodes by rewiring consumers. Identity nodes are always eliminated;
//! other processor-declared no-ops are only eliminated when `simplify=true`.

use std::{
    cell::RefCell,
    collections::{HashMap, HashSet},
    rc::Rc,
};

use crate::{
    graph_state::GraphState,
    ir::{Argument, NodeType, RawNode},
    processor::get_processor_registry,
    proto_conversion::DEFAULT_OPSET_VERSION,
};

/// Result of no-op elimination analysis
struct NoopEliminationPlan {
    /// Mapping from no-op output names to their input names (for rewiring)
    rewire_map: HashMap<String, String>,
    /// Indices of no-op nodes to remove
    nodes_to_remove: HashSet<usize>,
}

/// Rewire an argument to bypass removed Identity nodes
fn rewire_argument(
    arg: &mut Argument,
    rewire_map: &HashMap<String, String>,
    output_arg_map: &HashMap<String, Argument>,
) {
    if let Some(new_name) = rewire_map.get(&arg.name) {
        if let Some(source_arg) = output_arg_map.get(new_name) {
            arg.name = new_name.clone();
            arg.value_store = source_arg.value_store.clone();
            arg.ty = source_arg.ty.clone();
            arg.value_source = source_arg.value_source;
        } else {
            arg.name = new_name.clone();
        }
    }
}

/// Analyze which nodes are no-ops and create rewiring map
///
/// A node is a no-op if its processor's `is_noop()` returns true, meaning the node's
/// output equals its first input. These nodes are eliminated by rewiring consumers
/// to read directly from the no-op's input.
fn plan_noop_elimination(
    nodes: &[RawNode],
    node_output_map: &HashMap<String, (usize, usize)>,
    simplify: bool,
) -> NoopEliminationPlan {
    let mut rewire_map = HashMap::new();
    let mut nodes_to_remove = HashSet::new();

    let registry = get_processor_registry();

    // Find all no-op nodes via processor trait
    let noop_indices: Vec<usize> = nodes
        .iter()
        .enumerate()
        .filter_map(|(i, node)| {
            let processor = registry.get(&node.node_type);
            let is_noop = if simplify {
                processor.is_noop(node)
            } else {
                node.node_type == NodeType::Identity
            };
            if is_noop {
                log::debug!(
                    "No-op elimination: {:?} '{}' (output '{}' -> input '{}')",
                    node.node_type,
                    node.name,
                    node.outputs.first().map(|o| o.name.as_str()).unwrap_or("?"),
                    node.inputs.first().map(|i| i.name.as_str()).unwrap_or("?"),
                );
                Some(i)
            } else {
                None
            }
        })
        .collect();

    for &idx in &noop_indices {
        let node = &nodes[idx];

        if node.inputs.is_empty() {
            log::warn!("No-op node {} has no inputs, skipping", node.name);
            continue;
        }

        let input_name = &node.inputs[0].name;
        let output_name = &node.outputs[0].name;

        rewire_map.insert(output_name.clone(), input_name.clone());

        // IMPORTANT: Also map from the original ONNX output name to the input
        // onnx-ir renames node outputs to {node_name}_out{n}, but subgraphs may reference
        // the original ONNX names. We need to find the original name by reverse-looking up
        // the node_output_map (which maps original names to node indices).
        //
        // For this no-op node at index `idx` with output index 0, find the original name.
        for (original_name, &(node_idx, output_idx)) in node_output_map.iter() {
            if node_idx == idx && output_idx == 0 {
                // Found the original ONNX output name for this no-op node
                if original_name != output_name {
                    rewire_map.insert(original_name.clone(), input_name.clone());
                }
                break;
            }
        }

        nodes_to_remove.insert(idx);
    }

    NoopEliminationPlan {
        rewire_map,
        nodes_to_remove,
    }
}

/// Apply the no-op elimination plan to the graph
///
/// This function:
/// 1. Rewires all node inputs to bypass removed no-op nodes
/// 2. Updates graph outputs to bypass removed no-op nodes
/// 3. Filters out removed nodes
fn apply_noop_elimination(
    nodes: &mut Vec<RawNode>,
    outputs: &mut [Argument],
    plan: NoopEliminationPlan,
) {
    let NoopEliminationPlan {
        rewire_map,
        nodes_to_remove,
    } = plan;

    if nodes_to_remove.is_empty() {
        log::debug!("No-op elimination: nothing to remove");
        return;
    }

    log::info!(
        "No-op elimination: removing {} node(s)",
        nodes_to_remove.len()
    );

    // Step 1: Build a map from output names to Arguments
    // This allows us to look up data_id and value_store when rewiring
    let mut output_arg_map: HashMap<String, Argument> = HashMap::new();
    for node in nodes.iter() {
        for output in &node.outputs {
            output_arg_map.insert(output.name.clone(), output.clone());
        }
    }

    // Step 2: Resolve transitive rewiring
    // If A -> B and B -> C, we need to make sure we map A -> C directly
    let mut resolved_rewire_map = rewire_map.clone();
    for (output, input) in rewire_map.iter() {
        let mut current = input.clone();
        let mut visited = HashSet::new();
        visited.insert(output.clone());

        // Follow the chain until we reach a non-rewired input
        while let Some(next) = resolved_rewire_map.get(&current) {
            if visited.contains(next) {
                // Cycle detected, break
                log::warn!("Cycle detected in rewiring: {:?}", visited);
                break;
            }
            visited.insert(current.clone());
            current = next.clone();
        }

        resolved_rewire_map.insert(output.clone(), current);
    }

    // Step 3: Rewire node inputs
    for node in nodes.iter_mut() {
        for input in &mut node.inputs {
            rewire_argument(input, &resolved_rewire_map, &output_arg_map);
        }
    }

    // Step 4: Rewire graph outputs
    for output in outputs.iter_mut() {
        rewire_argument(output, &resolved_rewire_map, &output_arg_map);
    }

    // Step 5: Remove Identity nodes
    *nodes = nodes
        .drain(..)
        .enumerate()
        .filter_map(|(i, node)| (!nodes_to_remove.contains(&i)).then_some(node))
        .collect();
}

/// Post-process the graph: eliminate identities and re-lift constants
///
/// Returns (nodes, inputs, outputs) tuple ready for finalization
pub(crate) fn post_process(
    state_rc: &Rc<RefCell<GraphState>>,
    simplify: bool,
) -> (Vec<RawNode>, Vec<Argument>, Vec<Argument>) {
    // Extract graph data while preserving tensor_store, constant_map, and node_output_map
    let (mut nodes, inputs, mut outputs, node_output_map) = {
        let mut state = state_rc.borrow_mut();

        // Clone Rc references BEFORE consuming - these are cheap Rc clones, not data clones
        let tensor_store_rc = state.tensor_store.clone();
        let constant_map_rc = state.constant_map_rc();
        let node_output_map = state.node_output_map().clone();

        let result = std::mem::replace(&mut *state, GraphState::new(&[], &[], &[], &[])).consume();

        // Restore the Rc references to the new empty GraphState (no data copying)
        state.restore_stores(tensor_store_rc, constant_map_rc);
        (result.0, result.1, result.2, node_output_map)
    };

    // No-op elimination (includes Identity nodes and any processor-declared no-ops)
    log::debug!("Starting no-op elimination");
    {
        let elimination_plan = plan_noop_elimination(&nodes, &node_output_map, simplify);
        apply_noop_elimination(&mut nodes, &mut outputs, elimination_plan);
    }

    // Re-run constant lifting after no-op elimination
    log::debug!("Re-running constant lifting after no-op elimination");
    {
        let mut state = state_rc.borrow_mut();
        state.processed_nodes = nodes.clone();
        let value_store = state.build_value_store();
        drop(state);

        // Re-attach value_store and lift constants
        // For outer-scope Static arguments (constants converted from parent graph), preserve
        // their existing value_store since it contains the tensor data they reference.
        for node in &mut nodes {
            for arg in &mut node.inputs {
                // Preserve value_store for Static arguments that already have a store containing their data
                let should_preserve =
                    if let crate::ir::ValueSource::Static(data_id) = arg.value_source {
                        arg.value_store
                            .as_ref()
                            .map(|store| store.get_tensor_data(data_id).is_some())
                            .unwrap_or(false)
                    } else {
                        false
                    };

                if !should_preserve {
                    arg.set_value_store(value_store.clone());
                }
            }

            let registry = get_processor_registry();
            let processor = registry.get(&node.node_type);
            // Constant lifting is a best-effort optimization after identity elimination.
            // Not all arguments can be lifted (e.g., already Static, Dynamic), so we log
            // errors but don't fail the pipeline.
            if let Err(e) = processor.lift_constants(node, DEFAULT_OPSET_VERSION) {
                log::debug!(
                    "Could not lift constants for node '{}' (type: {:?}): {:?}",
                    node.name,
                    node.node_type,
                    e
                );
            }
        }
    }

    (nodes, inputs, outputs)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::{ArgType, Argument, DType, NodeType, RawNode, TensorType};

    fn create_identity_node(name: &str, input_name: &str, output_name: &str) -> RawNode {
        RawNode {
            node_type: NodeType::Identity,
            name: name.to_string(),
            inputs: vec![Argument {
                name: input_name.to_string(),
                ty: ArgType::Tensor(TensorType {
                    dtype: DType::F32,
                    rank: 2,
                    static_shape: None,
                }),
                value_source: crate::ir::ValueSource::Dynamic,
                value_store: None,
            }],
            outputs: vec![Argument {
                name: output_name.to_string(),
                ty: ArgType::Tensor(TensorType {
                    dtype: DType::F32,
                    rank: 2,
                    static_shape: None,
                }),
                value_source: crate::ir::ValueSource::Dynamic,
                value_store: None,
            }],
            attrs: Default::default(),
        }
    }

    fn create_add_node(name: &str, input1: &str, input2: &str, output: &str) -> RawNode {
        RawNode {
            node_type: NodeType::Add,
            name: name.to_string(),
            inputs: vec![
                Argument {
                    name: input1.to_string(),
                    ty: ArgType::Tensor(TensorType {
                        dtype: DType::F32,
                        rank: 2,
                        static_shape: None,
                    }),
                    value_source: crate::ir::ValueSource::Dynamic,
                    value_store: None,
                },
                Argument {
                    name: input2.to_string(),
                    ty: ArgType::Tensor(TensorType {
                        dtype: DType::F32,
                        rank: 2,
                        static_shape: None,
                    }),
                    value_source: crate::ir::ValueSource::Dynamic,
                    value_store: None,
                },
            ],
            outputs: vec![Argument {
                name: output.to_string(),
                ty: ArgType::Tensor(TensorType {
                    dtype: DType::F32,
                    rank: 2,
                    static_shape: None,
                }),
                value_source: crate::ir::ValueSource::Dynamic,
                value_store: None,
            }],
            attrs: Default::default(),
        }
    }

    #[test]
    fn test_remove_single_identity() {
        let nodes = vec![
            create_identity_node("identity1", "input1", "identity1_out"),
            create_add_node("add1", "identity1_out", "input2", "output1"),
        ];

        let node_output_map = HashMap::new();
        let plan = plan_noop_elimination(&nodes, &node_output_map, true);

        assert_eq!(plan.nodes_to_remove.len(), 1);
        assert!(plan.nodes_to_remove.contains(&0));
        assert_eq!(
            plan.rewire_map.get("identity1_out"),
            Some(&"input1".to_string())
        );
    }

    #[test]
    fn test_remove_all_identities_in_empty_graph() {
        let nodes = vec![
            create_identity_node("identity1", "input1", "output1"),
            create_identity_node("identity2", "input2", "output2"),
        ];

        let node_output_map = HashMap::new();
        let plan = plan_noop_elimination(&nodes, &node_output_map, true);

        // Should remove all Identity nodes (empty graph is allowed)
        assert_eq!(plan.nodes_to_remove.len(), 2);
        assert!(plan.nodes_to_remove.contains(&0));
        assert!(plan.nodes_to_remove.contains(&1));
    }

    #[test]
    fn test_apply_noop_elimination() {
        let mut nodes = vec![
            create_identity_node("identity1", "input1", "identity1_out"),
            create_add_node("add1", "identity1_out", "input2", "add1_out"),
        ];

        let mut outputs = vec![Argument {
            name: "add1_out".to_string(),
            ty: ArgType::Tensor(TensorType {
                dtype: DType::F32,
                rank: 2,
                static_shape: None,
            }),
            value_source: crate::ir::ValueSource::Dynamic,
            value_store: None,
        }];

        let node_output_map = HashMap::new();
        let plan = plan_noop_elimination(&nodes, &node_output_map, true);
        apply_noop_elimination(&mut nodes, &mut outputs, plan);

        // Identity should be removed
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].node_type, NodeType::Add);

        // Add node input should be rewired
        assert_eq!(nodes[0].inputs[0].name, "input1");
    }
}