1use 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#[derive(Debug, Clone, new)]
24pub struct IfConfig {
25 pub then_branch: OnnxGraph,
26 pub else_branch: OnnxGraph,
27 #[new(default)]
30 pub scope_ref_names: Vec<String>,
31}
32
33#[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
42pub(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 !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 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 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 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 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 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 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 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 let outer_scope = build_outer_scope_from_inputs(node);
162
163 let then_branch = match then_attr {
165 crate::ir::AttributeValue::DeferredGraph(deferred) => {
166 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 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 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 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) .build();
311 node.attrs = attrs;
312
313 let processor = IfProcessor;
314
315 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 attrs.insert(
328 "then_branch".to_string(),
329 AttributeValue::Graph(create_test_branch(2, DType::F32)),
330 );
331
332 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 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}