Skip to main content

onnx_ir/node/
if_node.rs

1//! # If
2//!
3//! Conditional execution - executes either then_branch or else_branch based on a boolean condition.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__If.html>
6//!
7//! ## Opset Versions
8//! - **Opset 1**: Initial version
9//! - **Opset 11**: Adds support for sequence types
10//! - **Opset 13**: Clarified scoping rules
11//! - **Opset 16**: Further refinements
12
13use derive_new::new;
14use onnx_ir_derive::NodeBuilder;
15
16use crate::ir::{ArgType, Argument, Node, OnnxGraph, RawNode};
17use crate::processor::{
18    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
19    build_outer_scope_from_inputs,
20};
21
22/// Configuration for If operation
23#[derive(Debug, Clone, new)]
24pub struct IfConfig {
25    pub then_branch: OnnxGraph,
26    pub else_branch: OnnxGraph,
27    /// Names of outer-scope references (in order corresponding to inputs[1..])
28    /// These are the original sanitized ONNX names that subgraphs reference
29    #[new(default)]
30    pub scope_ref_names: Vec<String>,
31}
32
33/// Node representation for If operation
34#[derive(Debug, Clone, NodeBuilder)]
35pub struct IfNode {
36    pub name: String,
37    pub inputs: Vec<Argument>,
38    pub outputs: Vec<Argument>,
39    pub config: IfConfig,
40}
41
42/// If node processor
43pub(crate) struct IfProcessor;
44
45impl NodeProcessor for IfProcessor {
46    type Config = IfConfig;
47
48    fn spec(&self) -> NodeSpec {
49        NodeSpec {
50            min_opset: 1,
51            max_opset: None,
52            inputs: InputSpec::Exact(1),
53            outputs: OutputSpec::Range(1, 2147483647),
54        }
55    }
56
57    fn input_preferences(
58        &self,
59        node: &RawNode,
60        _opset: usize,
61    ) -> Result<Option<crate::processor::InputPreferences>, ProcessError> {
62        use crate::processor::{ArgPreference, InputPreferences};
63
64        // If condition must be a native bool (Rust `if` statement)
65        if !node.inputs.is_empty() {
66            let prefs =
67                InputPreferences::new().add(&node.inputs[0].name, ArgPreference::ScalarNative);
68            return Ok(Some(prefs));
69        }
70        Ok(None)
71    }
72
73    fn infer_types(
74        &self,
75        node: &mut RawNode,
76        opset: usize,
77        _output_preferences: &OutputPreferences,
78    ) -> Result<(), ProcessError> {
79        // Validate condition input is bool (or a Shape used as bool from comparison).
80        // Per ONNX spec, the condition must be a tensor containing a single element,
81        // but we allow any bool tensor/scalar as some models may not be strictly conformant.
82        // Shape values from comparisons (e.g., Equal on shapes) use 0/1 as false/true.
83        let condition = &node.inputs[0].ty;
84        let is_bool_like = match condition {
85            ArgType::ScalarTensor(dtype) | ArgType::ScalarNative(dtype) => dtype.is_bool(),
86            ArgType::Tensor(tensor) => tensor.dtype.is_bool(),
87            // Shape comparison results (e.g., Equal on shapes) use 0/1 as false/true.
88            // Require rank >= 1 so that codegen can safely read the first element.
89            ArgType::Shape(rank) => *rank >= 1,
90        };
91
92        if !is_bool_like {
93            return Err(ProcessError::TypeMismatch {
94                expected: "Bool tensor, scalar, or Shape".to_string(),
95                actual: format!("{:?}", condition),
96            });
97        }
98
99        // Get branches from config (clone to avoid borrow checker issues)
100        let config = self.extract_config(node, opset)?;
101        let then_outputs = config.then_branch.outputs.clone();
102        let else_outputs = config.else_branch.outputs.clone();
103
104        // Both branches must produce the same number of outputs
105        if then_outputs.len() != else_outputs.len() {
106            return Err(ProcessError::Custom(format!(
107                "If node branches must have same number of outputs: then={}, else={}",
108                then_outputs.len(),
109                else_outputs.len()
110            )));
111        }
112
113        // Infer output types from branches.
114        // Use the branch output with the higher rank so that both branches can be
115        // reconciled at codegen time (the lower-rank branch gets unsqueezed).
116        // At runtime, only one branch executes, so the types should be compatible.
117
118        // If outputs don't exist yet, create them from branch outputs
119        if node.outputs.is_empty() {
120            for (then_output, else_output) in then_outputs.iter().zip(else_outputs.iter()) {
121                if else_output.ty.rank() > then_output.ty.rank() {
122                    node.outputs.push(else_output.clone());
123                } else {
124                    node.outputs.push(then_output.clone());
125                }
126            }
127        } else {
128            // Update types for existing outputs (preserves names set by add_node)
129            for (i, (then_output, else_output)) in
130                then_outputs.iter().zip(else_outputs.iter()).enumerate()
131            {
132                if i < node.outputs.len() {
133                    if else_output.ty.rank() > then_output.ty.rank() {
134                        node.outputs[i].ty = else_output.ty.clone();
135                    } else {
136                        node.outputs[i].ty = then_output.ty.clone();
137                    }
138                }
139            }
140        }
141
142        Ok(())
143    }
144
145    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
146        // Extract then_branch and else_branch from attributes
147        let then_attr = node
148            .attrs
149            .get("then_branch")
150            .ok_or_else(|| ProcessError::MissingAttribute("then_branch".to_string()))?
151            .clone();
152
153        let else_attr = node
154            .attrs
155            .get("else_branch")
156            .ok_or_else(|| ProcessError::MissingAttribute("else_branch".to_string()))?
157            .clone();
158
159        // Build outer scope types map from additional inputs (beyond ONNX inputs)
160        // These are outer-scope references that were added during node conversion
161        let outer_scope = build_outer_scope_from_inputs(node);
162
163        // Handle DeferredGraph and Graph
164        let then_branch = match then_attr {
165            crate::ir::AttributeValue::DeferredGraph(deferred) => {
166                // Build the subgraph now with outer-scope types
167                log::debug!(
168                    "Building deferred then_branch subgraph with {} outer-scope types",
169                    outer_scope.len()
170                );
171                deferred
172                    .build_graph_with_outer_scope(outer_scope.clone())
173                    .map_err(|e| {
174                        ProcessError::Custom(format!("Failed to build then_branch: {}", e))
175                    })?
176            }
177            crate::ir::AttributeValue::Graph(g) => g,
178            _ => {
179                return Err(ProcessError::Custom(
180                    "Expected DeferredGraph or Graph for then_branch".to_string(),
181                ));
182            }
183        };
184
185        let else_branch = match else_attr {
186            crate::ir::AttributeValue::DeferredGraph(deferred) => {
187                // Build the subgraph now with outer-scope types
188                log::debug!(
189                    "Building deferred else_branch subgraph with {} outer-scope types",
190                    outer_scope.len()
191                );
192                deferred
193                    .build_graph_with_outer_scope(outer_scope)
194                    .map_err(|e| {
195                        ProcessError::Custom(format!("Failed to build else_branch: {}", e))
196                    })?
197            }
198            crate::ir::AttributeValue::Graph(g) => g,
199            _ => {
200                return Err(ProcessError::Custom(
201                    "Expected DeferredGraph or Graph for else_branch".to_string(),
202                ));
203            }
204        };
205
206        // Get the scope ref names for use in code generation
207        let scope_ref_names: Vec<String> = node
208            .attrs
209            .get("__scope_ref_names")
210            .and_then(|v| match v {
211                crate::ir::AttributeValue::Strings(names) => Some(names.clone()),
212                _ => None,
213            })
214            .unwrap_or_default();
215
216        Ok(IfConfig {
217            then_branch,
218            else_branch,
219            scope_ref_names,
220        })
221    }
222
223    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
224        let config = self.extract_config(&builder, opset)?;
225
226        Ok(Node::If(IfNode {
227            name: builder.name,
228            inputs: builder.inputs,
229            outputs: builder.outputs,
230            config,
231        }))
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use crate::ir::AttributeValue;
239    use crate::ir::{Argument, Attributes, NodeType, OnnxGraph, TensorType};
240    use crate::node::test_utils::TestNodeBuilder;
241    use crate::{BoolStore, DType};
242
243    fn create_test_branch(output_rank: usize, dtype: DType) -> OnnxGraph {
244        OnnxGraph {
245            nodes: vec![],
246            inputs: vec![],
247            outputs: vec![Argument {
248                name: "output".to_string(),
249                ty: ArgType::Tensor(TensorType {
250                    dtype,
251                    rank: output_rank,
252                    static_shape: None,
253                }),
254                value_source: crate::ir::ValueSource::Dynamic,
255                value_store: None,
256            }],
257            value_store: None,
258        }
259    }
260
261    #[test]
262    fn test_if_basic() {
263        let mut attrs = Attributes::new();
264        attrs.insert(
265            "then_branch".to_string(),
266            AttributeValue::Graph(create_test_branch(2, DType::F32)),
267        );
268        attrs.insert(
269            "else_branch".to_string(),
270            AttributeValue::Graph(create_test_branch(2, DType::F32)),
271        );
272
273        let mut node = TestNodeBuilder::new(NodeType::If, "test_if")
274            .input_scalar("cond", DType::Bool(BoolStore::Native))
275            .build();
276        node.attrs = attrs;
277
278        let processor = IfProcessor;
279
280        // Extract config first
281        let _config = processor.extract_config(&node, 16).unwrap();
282
283        let prefs = OutputPreferences::new();
284        processor.infer_types(&mut node, 16, &prefs).unwrap();
285
286        assert_eq!(node.outputs.len(), 1);
287        match &node.outputs[0].ty {
288            ArgType::Tensor(tensor) => {
289                assert_eq!(tensor.dtype, DType::F32);
290                assert_eq!(tensor.rank, 2);
291            }
292            _ => panic!("Expected tensor output"),
293        }
294    }
295
296    #[test]
297    fn test_if_invalid_condition() {
298        let mut attrs = Attributes::new();
299        attrs.insert(
300            "then_branch".to_string(),
301            AttributeValue::Graph(create_test_branch(2, DType::F32)),
302        );
303        attrs.insert(
304            "else_branch".to_string(),
305            AttributeValue::Graph(create_test_branch(2, DType::F32)),
306        );
307
308        let mut node = TestNodeBuilder::new(NodeType::If, "test_if")
309            .input_tensor_f32("cond", 1, None) // Tensor instead of scalar
310            .build();
311        node.attrs = attrs;
312
313        let processor = IfProcessor;
314
315        // Extract config first
316        let _config = processor.extract_config(&node, 16).unwrap();
317
318        let prefs = OutputPreferences::new();
319        let result = processor.infer_types(&mut node, 16, &prefs);
320        assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
321    }
322
323    #[test]
324    fn test_if_branch_output_count_mismatch() {
325        let mut attrs = Attributes::new();
326        // then_branch has 1 output
327        attrs.insert(
328            "then_branch".to_string(),
329            AttributeValue::Graph(create_test_branch(2, DType::F32)),
330        );
331
332        // else_branch has 2 outputs
333        let mut else_branch = create_test_branch(2, DType::F32);
334        else_branch.outputs.push(Argument {
335            name: "output2".to_string(),
336            ty: ArgType::Tensor(TensorType {
337                dtype: DType::F32,
338                rank: 2,
339                static_shape: None,
340            }),
341            value_source: crate::ir::ValueSource::Dynamic,
342            value_store: None,
343        });
344        attrs.insert(
345            "else_branch".to_string(),
346            AttributeValue::Graph(else_branch),
347        );
348
349        let mut node = TestNodeBuilder::new(NodeType::If, "test_if")
350            .input_scalar("cond", DType::Bool(BoolStore::Native))
351            .build();
352        node.attrs = attrs;
353
354        let processor = IfProcessor;
355
356        // Extract config first
357        let _config = processor.extract_config(&node, 16).unwrap();
358
359        let prefs = OutputPreferences::new();
360        let result = processor.infer_types(&mut node, 16, &prefs);
361        assert!(matches!(result, Err(ProcessError::Custom(_))));
362    }
363}