1use derive_new::new;
14use onnx_ir_derive::NodeBuilder;
15
16use crate::ir::{ArgType, Argument, DType, Node, OnnxGraph, RawNode};
17use crate::processor::{
18 NodeProcessor, OutputPreferences, ProcessError, build_outer_scope_from_inputs,
19 get_onnx_input_count,
20};
21
22fn add_concat_dimension(ty: ArgType) -> ArgType {
27 use crate::ir::TensorType;
28
29 match ty {
30 ArgType::ScalarTensor(dtype) | ArgType::ScalarNative(dtype) => {
32 ArgType::Tensor(TensorType {
33 dtype,
34 rank: 2, static_shape: None,
36 })
37 }
38 ArgType::Tensor(mut tensor_type) => {
40 tensor_type.static_shape = None;
42 ArgType::Tensor(tensor_type)
43 }
44 ArgType::Shape(_) => {
45 ArgType::Tensor(TensorType {
47 dtype: DType::I64,
48 rank: 1,
49 static_shape: None,
50 })
51 }
52 }
53}
54
55#[derive(Debug, Clone, new)]
57pub struct LoopConfig {
58 pub body: OnnxGraph,
59 #[new(default)]
62 pub scope_ref_names: Vec<String>,
63}
64
65#[derive(Debug, Clone, NodeBuilder)]
67pub struct LoopNode {
68 pub name: String,
69 pub inputs: Vec<Argument>,
70 pub outputs: Vec<Argument>,
71 pub config: LoopConfig,
72}
73
74pub(crate) struct LoopProcessor;
76
77impl NodeProcessor for LoopProcessor {
78 type Config = LoopConfig;
79
80 fn input_preferences(
81 &self,
82 node: &RawNode,
83 _opset: usize,
84 ) -> Result<Option<crate::processor::InputPreferences>, ProcessError> {
85 use crate::processor::{ArgPreference, InputPreferences};
86
87 let mut prefs = InputPreferences::new();
89 if !node.inputs.is_empty() {
90 prefs = prefs.add(&node.inputs[0].name, ArgPreference::ScalarNative);
91 }
92 if node.inputs.len() > 1 {
93 prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
94 }
95 Ok(Some(prefs))
96 }
97
98 fn infer_types(
99 &self,
100 node: &mut RawNode,
101 opset: usize,
102 _output_preferences: &OutputPreferences,
103 ) -> Result<(), ProcessError> {
104 crate::processor::validate_opset(opset, 1)?;
105
106 if node.inputs.len() < 2 {
109 return Err(ProcessError::Custom(format!(
110 "Loop node requires at least 2 inputs (M, cond), got {}",
111 node.inputs.len()
112 )));
113 }
114
115 if !node.inputs[0].is_optional() {
117 let m_type = &node.inputs[0].ty;
118 if !m_type.is_scalar() {
119 return Err(ProcessError::TypeMismatch {
120 expected: "Scalar I64 (rank-0 tensor or Scalar type) or empty".to_string(),
121 actual: format!("{:?}", m_type),
122 });
123 }
124 match m_type {
125 ArgType::ScalarNative(dtype) | ArgType::ScalarTensor(dtype)
126 if *dtype == DType::I64 =>
127 {
128 }
130 _ => {
131 return Err(ProcessError::TypeMismatch {
132 expected: "Scalar I64 or empty".to_string(),
133 actual: format!("{:?}", m_type),
134 });
135 }
136 }
137 }
138
139 if !node.inputs[1].is_optional() {
141 let cond_type = &node.inputs[1].ty;
142 if !cond_type.is_scalar() {
143 return Err(ProcessError::TypeMismatch {
144 expected: "Scalar Bool (rank-0 tensor or Scalar type) or empty".to_string(),
145 actual: format!("{:?}", cond_type),
146 });
147 }
148 match cond_type {
149 ArgType::ScalarNative(dtype) | ArgType::ScalarTensor(dtype) if dtype.is_bool() => {
150 }
152 _ => {
153 return Err(ProcessError::TypeMismatch {
154 expected: "Scalar Bool or empty".to_string(),
155 actual: format!("{:?}", cond_type),
156 });
157 }
158 }
159 }
160
161 let config = self.extract_config(node, opset)?;
163 let body_inputs = config.body.inputs.clone();
164 let body_outputs = config.body.outputs.clone();
165
166 if body_inputs.len() < 2 {
168 return Err(ProcessError::Custom(format!(
169 "Loop body must have at least 2 inputs (iter_num, cond_in), got {}",
170 body_inputs.len()
171 )));
172 }
173
174 let cond_in_type = &body_inputs[1].ty;
176 if !cond_in_type.is_scalar() {
177 return Err(ProcessError::TypeMismatch {
178 expected: "Loop body second input (cond_in) must be Scalar Bool (rank-0 tensor or Scalar type)".to_string(),
179 actual: format!("{:?}", cond_in_type),
180 });
181 }
182 match cond_in_type {
183 ArgType::ScalarNative(dtype) | ArgType::ScalarTensor(dtype) if dtype.is_bool() => {
184 }
186 _ => {
187 return Err(ProcessError::TypeMismatch {
188 expected: "Loop body second input (cond_in) must be Scalar Bool".to_string(),
189 actual: format!("{:?}", cond_in_type),
190 });
191 }
192 }
193
194 if body_outputs.is_empty() {
196 return Err(ProcessError::Custom(
197 "Loop body must have at least 1 output (cond_out)".to_string(),
198 ));
199 }
200
201 let cond_out_type = &body_outputs[0].ty;
203 if !cond_out_type.is_scalar() {
204 return Err(ProcessError::TypeMismatch {
205 expected: "Loop body first output (cond_out) must be Scalar Bool (rank-0 tensor or Scalar type)".to_string(),
206 actual: format!("{:?}", cond_out_type),
207 });
208 }
209 match cond_out_type {
210 ArgType::ScalarNative(dtype) | ArgType::ScalarTensor(dtype) if dtype.is_bool() => {
211 }
213 _ => {
214 return Err(ProcessError::TypeMismatch {
215 expected: "Loop body first output (cond_out) must be Scalar Bool".to_string(),
216 actual: format!("{:?}", cond_out_type),
217 });
218 }
219 }
220
221 let num_body_loop_inputs = body_inputs.len() - 2;
223
224 let num_body_loop_outputs = body_outputs.len() - 1;
227
228 if num_body_loop_outputs < num_body_loop_inputs {
231 return Err(ProcessError::Custom(format!(
232 "Loop body must have at least {} loop-carried outputs to match {} loop-carried inputs (got {})",
233 num_body_loop_inputs, num_body_loop_inputs, num_body_loop_outputs
234 )));
235 }
236
237 let num_loop_carried_outputs = num_body_loop_inputs;
245
246 if node.outputs.is_empty() {
247 for (i, body_output) in body_outputs.iter().skip(1).enumerate() {
248 let mut output = body_output.clone();
249
250 if i >= num_loop_carried_outputs {
252 output.ty = add_concat_dimension(output.ty);
253 }
254
255 node.outputs.push(output);
256 }
257 } else {
258 for (i, body_output) in body_outputs.iter().skip(1).enumerate() {
260 if i < node.outputs.len() {
261 let mut ty = body_output.ty.clone();
262
263 if i >= num_loop_carried_outputs {
265 ty = add_concat_dimension(ty);
266 }
267
268 node.outputs[i].ty = ty;
269 }
270 }
271 }
272
273 Ok(())
274 }
275
276 fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
277 let body_attr = node
279 .attrs
280 .get("body")
281 .ok_or_else(|| ProcessError::MissingAttribute("body".to_string()))?
282 .clone();
283
284 let mut outer_scope = build_outer_scope_from_inputs(node);
286
287 let body = match body_attr {
289 crate::ir::AttributeValue::DeferredGraph(deferred) => {
290 let onnx_input_count = get_onnx_input_count(node);
295 for (i, body_input) in deferred.proto.input.iter().enumerate().skip(2) {
296 let typed = body_input
297 .type_
298 .as_ref()
299 .is_some_and(|ty| ty.has_tensor_type());
300 if typed || i >= onnx_input_count {
301 continue;
302 }
303 let arg = Argument::new(body_input.name.clone(), node.inputs[i].ty.clone());
304 outer_scope.insert(body_input.name.clone(), arg);
305 }
306
307 log::debug!(
309 "Building deferred Loop body subgraph with {} outer-scope types",
310 outer_scope.len()
311 );
312 deferred
313 .build_graph_with_outer_scope(outer_scope)
314 .map_err(|e| {
315 ProcessError::Custom(format!("Failed to build Loop body: {}", e))
316 })?
317 }
318 crate::ir::AttributeValue::Graph(g) => g,
319 _ => {
320 return Err(ProcessError::Custom(
321 "Expected DeferredGraph or Graph for body".to_string(),
322 ));
323 }
324 };
325
326 let scope_ref_names: Vec<String> = node
328 .attrs
329 .get("__scope_ref_names")
330 .and_then(|v| match v {
331 crate::ir::AttributeValue::Strings(names) => Some(names.clone()),
332 _ => None,
333 })
334 .unwrap_or_default();
335
336 Ok(LoopConfig {
337 body,
338 scope_ref_names,
339 })
340 }
341
342 fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
343 let config = self.extract_config(&builder, opset)?;
344
345 Ok(Node::Loop(LoopNode {
346 name: builder.name,
347 inputs: builder.inputs,
348 outputs: builder.outputs,
349 config,
350 }))
351 }
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357 use crate::ir::AttributeValue;
358 use crate::ir::{Argument, Attributes, BoolStore, NodeType, OnnxGraph, TensorType};
359 use crate::node::test_utils::TestNodeBuilder;
360
361 fn create_test_body(_num_loop_vars: usize) -> OnnxGraph {
362 OnnxGraph {
363 nodes: vec![],
364 inputs: vec![
365 Argument {
367 name: "iter".to_string(),
368 ty: ArgType::ScalarNative(DType::I64),
369 value_source: crate::ir::ValueSource::Dynamic,
370 value_store: None,
371 },
372 Argument {
374 name: "cond_in".to_string(),
375 ty: ArgType::ScalarNative(DType::Bool(BoolStore::Native)),
376 value_source: crate::ir::ValueSource::Dynamic,
377 value_store: None,
378 },
379 Argument {
381 name: "v_in".to_string(),
382 ty: ArgType::Tensor(TensorType {
383 dtype: DType::F32,
384 rank: 2,
385 static_shape: None,
386 }),
387 value_source: crate::ir::ValueSource::Dynamic,
388 value_store: None,
389 },
390 ],
391 outputs: vec![
392 Argument {
394 name: "cond_out".to_string(),
395 ty: ArgType::ScalarNative(DType::Bool(BoolStore::Native)),
396 value_source: crate::ir::ValueSource::Dynamic,
397 value_store: None,
398 },
399 Argument {
401 name: "v_out".to_string(),
402 ty: ArgType::Tensor(TensorType {
403 dtype: DType::F32,
404 rank: 2,
405 static_shape: None,
406 }),
407 value_source: crate::ir::ValueSource::Dynamic,
408 value_store: None,
409 },
410 ],
411 value_store: None,
412 }
413 }
414
415 #[test]
416 fn test_loop_basic() {
417 let mut attrs = Attributes::new();
418 attrs.insert(
419 "body".to_string(),
420 AttributeValue::Graph(create_test_body(1)),
421 );
422
423 let mut node = TestNodeBuilder::new(NodeType::Loop, "test_loop")
424 .input_scalar("M", DType::I64)
425 .input_scalar("cond", DType::Bool(BoolStore::Native))
426 .input_tensor_f32("v_initial", 2, None)
427 .build();
428 node.attrs = attrs;
429
430 let processor = LoopProcessor;
431
432 let _config = processor.extract_config(&node, 16).unwrap();
434
435 let prefs = OutputPreferences::new();
436 processor.infer_types(&mut node, 16, &prefs).unwrap();
437
438 assert_eq!(node.outputs.len(), 1);
440 }
441
442 #[test]
443 fn test_loop_invalid_trip_count() {
444 let mut attrs = Attributes::new();
445 attrs.insert(
446 "body".to_string(),
447 AttributeValue::Graph(create_test_body(1)),
448 );
449
450 let mut node = TestNodeBuilder::new(NodeType::Loop, "test_loop")
451 .input_tensor_f32("M", 1, None) .input_scalar("cond", DType::Bool(BoolStore::Native))
453 .input_tensor_f32("v_initial", 2, None)
454 .build();
455 node.attrs = attrs;
456
457 let processor = LoopProcessor;
458
459 let _config = processor.extract_config(&node, 16).unwrap();
460
461 let prefs = OutputPreferences::new();
462 let result = processor.infer_types(&mut node, 16, &prefs);
463 assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
464 }
465}