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
//! Phase 3: Type Inference
//!
//! Iterative type inference with preference propagation until convergence.
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::Rc,
};
use crate::{
graph_state::GraphState,
ir::{ArgType, RawNode},
processor::{ArgPreference, ProcessError, get_processor_registry},
};
/// Infer types for all nodes (extracts nodes to avoid borrow conflicts)
pub(crate) fn infer_types(
state_rc: &Rc<RefCell<GraphState>>,
opset_version: usize,
) -> Result<(), ProcessError> {
// Extract nodes temporarily to avoid holding mutable borrow during type inference
// (type inference may call .value() which needs immutable borrows)
let mut nodes = std::mem::take(&mut state_rc.borrow_mut().processed_nodes);
iterative_type_inference_with_preferences(&mut nodes, opset_version)?;
state_rc.borrow_mut().processed_nodes = nodes;
Ok(())
}
/// Iterative type inference with preference propagation
///
/// Algorithm: Build preferences → Sync types → Infer → Collect new preferences → Check convergence
///
/// This allows runtime preference collection (e.g., Concat requests Shape after seeing Shape inputs).
pub(super) fn iterative_type_inference_with_preferences(
nodes: &mut [RawNode],
opset: usize,
) -> Result<(), ProcessError> {
let registry = get_processor_registry();
// Check for unregistered (unsupported) node types before running inference
let unsupported: Vec<_> = nodes
.iter()
.filter(|n| !registry.contains(&n.node_type))
.map(|n| format!("{:?} (node '{}')", n.node_type, n.name))
.collect();
if !unsupported.is_empty() {
return Err(ProcessError::UnsupportedOps(unsupported));
}
// Track collected preferences: (producer_output_name, consumer_name, pref_type_str)
let mut collected_preferences: HashSet<(String, String, String)> = HashSet::new();
let max_iterations = 10; // Safety limit to prevent infinite loops
for iteration in 1..=max_iterations {
// Step 1: Build OutputPreferences map from collected preferences
let mut node_preferences: HashMap<String, crate::processor::OutputPreferences> =
HashMap::new();
for (output_name, consumer_name, pref_type_str) in &collected_preferences {
let pref = match pref_type_str.as_str() {
"ScalarNative" => ArgPreference::ScalarNative,
"Shape" => ArgPreference::Shape,
"Tensor" => ArgPreference::Tensor,
_ => continue,
};
// Find producer node for this output
for node in nodes.iter() {
if node.outputs.iter().any(|o| &o.name == output_name) {
node_preferences.entry(node.name.clone()).or_default().add(
output_name.clone(),
consumer_name.clone(),
pref,
);
break;
}
}
}
// Step 2: Sync input types from producer outputs (skipped on iteration 1)
// Iteration 1: Let nodes infer from proto defaults first
// Iteration 2+: Pre-sync ensures nodes see inferred types, not stale defaults
if iteration > 1 {
let output_types: HashMap<String, ArgType> = nodes
.iter()
.flat_map(|n| n.outputs.iter().map(|o| (o.name.clone(), o.ty.clone())))
.collect();
for node in nodes.iter_mut() {
for input in &mut node.inputs {
if let Some(new_type) = output_types.get(&input.name) {
// Merge static_shape: keep more informative dimension values
// from the existing input type (which may come from value_info)
let mut merged_type = new_type.clone();
merged_type.merge_static_shape(&input.ty);
input.ty = merged_type;
}
}
}
}
// Step 3: Run infer_types on all nodes with current preferences
// AND sync types after each node to allow downstream nodes to see updated types
// within the same iteration (intra-iteration propagation)
let mut types_changed = false;
for i in 0..nodes.len() {
// Get preferences for this node
let prefs = node_preferences
.get(&nodes[i].name)
.cloned()
.unwrap_or_else(crate::processor::OutputPreferences::new);
// Validate node against its spec before processing
let processor = registry.get(&nodes[i].node_type);
let spec = processor.spec();
crate::processor::validate_node_spec(&nodes[i], opset, &spec)?;
// Run type inference on this node
processor
.infer_types(&mut nodes[i], opset, &prefs)
.map_err(|e| {
ProcessError::Custom(format!(
"Node '{}' ({}): {}",
nodes[i].name, nodes[i].node_type, e
))
})?;
// Validate that no rank-0 tensors were created (invariant: should be Scalars)
crate::processor::validate_no_rank_zero_tensors(&nodes[i])?;
// Immediately sync this node's output types to downstream nodes' inputs
// This allows downstream nodes to see correct types in the same iteration
let current_outputs: Vec<(String, ArgType)> = nodes[i]
.outputs
.iter()
.map(|o| (o.name.clone(), o.ty.clone()))
.collect();
for output_pair in ¤t_outputs {
let (output_name, output_ty) = output_pair;
// Update all downstream nodes that use this output
for downstream_node in &mut nodes[i + 1..] {
for input in &mut downstream_node.inputs {
if &input.name == output_name {
// Merge static_shape: keep more informative dimension values
let mut merged_type = output_ty.clone();
merged_type.merge_static_shape(&input.ty);
if input.ty != merged_type {
types_changed = true;
input.ty = merged_type;
}
}
}
}
}
}
// Step 3.5: Final sync pass to catch any cross-iteration changes
// This handles cases where earlier nodes were updated by later nodes' outputs
let output_types: HashMap<String, ArgType> = nodes
.iter()
.flat_map(|n| n.outputs.iter().map(|o| (o.name.clone(), o.ty.clone())))
.collect();
for node in nodes.iter_mut() {
for input in &mut node.inputs {
if let Some(new_type) = output_types.get(&input.name) {
// Merge static_shape: keep more informative dimension values
let mut merged_type = new_type.clone();
merged_type.merge_static_shape(&input.ty);
if input.ty != merged_type {
types_changed = true;
input.ty = merged_type;
}
}
}
}
// Step 4: Collect NEW input_preferences based on inferred types
let mut new_preferences_found = false;
for consumer_node in nodes.iter() {
let processor = registry.get(&consumer_node.node_type);
if let Ok(Some(input_prefs)) = processor.input_preferences(consumer_node, opset) {
// For each input this consumer has preferences for
for input in &consumer_node.inputs {
let requested_types = input_prefs.get(&input.name);
if requested_types.is_empty() {
continue;
}
// Find which node produces this input
for producer_node in nodes.iter() {
if let Some(output) =
producer_node.outputs.iter().find(|o| o.name == input.name)
{
// Check each requested preference type
for req_type in requested_types {
let pref_type_str = match req_type {
ArgPreference::ScalarNative => "ScalarNative",
ArgPreference::Shape => "Shape",
ArgPreference::Tensor => "Tensor",
}
.to_string();
let key = (
output.name.clone(),
consumer_node.name.clone(),
pref_type_str,
);
// Only add if this is a NEW preference
if !collected_preferences.contains(&key) {
collected_preferences.insert(key.clone());
new_preferences_found = true;
}
}
break;
}
}
}
}
}
// Step 5: Check convergence
// Continue iterating if either types changed or new preferences were found
if !types_changed && !new_preferences_found {
log::debug!("Type inference converged after {} iterations", iteration);
return Ok(());
}
}
log::warn!(
"Type inference iteration limit ({}) reached without convergence",
max_iterations
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::{Argument, NodeType, RawNode, TensorType};
use burn_tensor::DType;
#[test]
fn test_static_shape_merge_preserves_value_info() {
// Scenario: Producer sets static_shape to None, but consumer's input
// (from value_info) has partial shape info [None, Some(1)].
// The merge should preserve the value_info shape.
let mut nodes = vec![
// Producer: Relu outputs a tensor with unknown shape
RawNode {
node_type: NodeType::Relu,
name: "relu1".to_string(),
inputs: vec![Argument::new(
"input",
ArgType::Tensor(TensorType::new(DType::F32, 2, None)),
)],
outputs: vec![Argument::new(
"relu1_out",
ArgType::Tensor(TensorType::new(DType::F32, 2, None)),
)],
attrs: Default::default(),
},
// Consumer: Another Relu whose input has shape info from value_info
RawNode {
node_type: NodeType::Relu,
name: "relu2".to_string(),
inputs: vec![Argument::new(
"relu1_out", // References relu1's output
ArgType::Tensor(TensorType::new(
DType::F32,
2,
Some(vec![None, Some(10)]), // value_info provided this
)),
)],
outputs: vec![Argument::new(
"relu2_out",
ArgType::Tensor(TensorType::new(DType::F32, 2, None)),
)],
attrs: Default::default(),
},
];
iterative_type_inference_with_preferences(&mut nodes, 17).unwrap();
// The consumer's input should have merged shape info preserved
let consumer_input = &nodes[1].inputs[0];
let shape = consumer_input
.ty
.static_shape()
.expect("shape should exist");
assert_eq!(shape, &vec![None, Some(10)]);
}
#[test]
fn test_static_shape_merge_combines_dimension_info() {
// Scenario: Producer infers static_shape [Some(5), None], but consumer's
// input has [None, Some(10)] from value_info. Merge should give [Some(5), Some(10)].
let mut nodes = vec![
// Producer: Relu with partially known output shape
RawNode {
node_type: NodeType::Relu,
name: "relu1".to_string(),
inputs: vec![Argument::new(
"input",
ArgType::Tensor(TensorType::new(
DType::F32,
2,
Some(vec![Some(5), None]), // Known first dim
)),
)],
outputs: vec![Argument::new(
"relu1_out",
ArgType::Tensor(TensorType::new(
DType::F32,
2,
Some(vec![Some(5), None]), // Relu preserves shape
)),
)],
attrs: Default::default(),
},
// Consumer: Input has different partial shape from value_info
RawNode {
node_type: NodeType::Relu,
name: "relu2".to_string(),
inputs: vec![Argument::new(
"relu1_out",
ArgType::Tensor(TensorType::new(
DType::F32,
2,
Some(vec![None, Some(10)]), // value_info knows second dim
)),
)],
outputs: vec![Argument::new(
"relu2_out",
ArgType::Tensor(TensorType::new(DType::F32, 2, None)),
)],
attrs: Default::default(),
},
];
iterative_type_inference_with_preferences(&mut nodes, 17).unwrap();
// The consumer's input should have merged shape: [Some(5), Some(10)]
let consumer_input = &nodes[1].inputs[0];
let shape = consumer_input
.ty
.static_shape()
.expect("shape should exist");
assert_eq!(shape, &vec![Some(5), Some(10)]);
}
#[test]
fn test_unsupported_ops_detected_before_inference() {
let mut nodes = vec![
RawNode {
node_type: NodeType::AffineGrid,
name: "affine1".to_string(),
inputs: vec![],
outputs: vec![],
attrs: Default::default(),
},
RawNode {
node_type: NodeType::CenterCropPad,
name: "ccp1".to_string(),
inputs: vec![],
outputs: vec![],
attrs: Default::default(),
},
];
let result = iterative_type_inference_with_preferences(&mut nodes, 17);
let err = result.unwrap_err();
match &err {
ProcessError::UnsupportedOps(ops) => {
assert_eq!(ops.len(), 2);
assert!(ops[0].contains("AffineGrid"));
assert!(ops[1].contains("CenterCropPad"));
}
other => panic!("Expected UnsupportedOps, got: {other:?}"),
}
// Verify Display output is clean (no "Custom(...)" wrapper)
let msg = format!("{err}");
assert!(msg.starts_with("Unsupported ONNX operation(s):"));
assert!(msg.contains("AffineGrid"));
assert!(msg.contains("CenterCropPad"));
}
}