Skip to main content

onnx_ir/node/
loop_node.rs

1//! # Loop
2//!
3//! Generic looping construct - executes loop body graph for a specified number of iterations.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__Loop.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, DType, Node, OnnxGraph, RawNode};
17use crate::processor::{
18    NodeProcessor, OutputPreferences, ProcessError, build_outer_scope_from_inputs,
19    get_onnx_input_count,
20};
21
22/// Helper function to transform type for scan output concatenation
23/// Per ONNX Loop spec, scan outputs are concatenated along axis 0:
24/// - Scalars (rank 0): unsqueezed to [1], then concatenated → [N, 1] (rank 2)
25/// - Tensors (rank K): concatenated along axis 0 → [N*D0, D1, ...] (rank K, same rank)
26fn add_concat_dimension(ty: ArgType) -> ArgType {
27    use crate::ir::TensorType;
28
29    match ty {
30        // Scalar (rank 0) → unsqueeze to [1] → concat → [N, 1] (rank 2)
31        ArgType::ScalarTensor(dtype) | ArgType::ScalarNative(dtype) => {
32            ArgType::Tensor(TensorType {
33                dtype,
34                rank: 2, // ONNX unsqueezes scalars before concat, resulting in rank 2
35                static_shape: None,
36            })
37        }
38        // Tensors: concatenated along axis 0 (same rank, first dim changes)
39        ArgType::Tensor(mut tensor_type) => {
40            // Clear static shape since num_iterations affects first dimension
41            tensor_type.static_shape = None;
42            ArgType::Tensor(tensor_type)
43        }
44        ArgType::Shape(_) => {
45            // Shapes become rank-1 tensors when concatenated
46            ArgType::Tensor(TensorType {
47                dtype: DType::I64,
48                rank: 1,
49                static_shape: None,
50            })
51        }
52    }
53}
54
55/// Configuration for Loop operation
56#[derive(Debug, Clone, new)]
57pub struct LoopConfig {
58    pub body: OnnxGraph,
59    /// Names of outer-scope references (in order corresponding to inputs after ONNX inputs)
60    /// These are the original sanitized ONNX names that subgraphs reference
61    #[new(default)]
62    pub scope_ref_names: Vec<String>,
63}
64
65/// Node representation for Loop operation
66#[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
74/// Loop node processor
75pub(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        // Loop's max_trip_count (input 0) and condition (input 1) must be native
88        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        // Loop has at least 2 inputs: M (optional), cond (optional), v_initial... (variadic)
107        // But M and cond can be empty strings in ONNX, so we need at least 2 inputs
108        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        // Validate M input (max trip count) - should be scalar int64 or optional
116        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                    // Valid scalar int64
129                }
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        // Validate cond input - should be scalar bool or optional
140        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                    // Valid scalar bool
151                }
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        // Get body graph from config
162        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        // Body must have at least 2 inputs (iter_num, cond_in)
167        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        // Second body input must be scalar bool (cond_in)
175        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                // Valid
185            }
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        // Body must have at least 1 output (cond_out)
195        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        // First body output must be scalar bool (cond_out)
202        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                // Valid
212            }
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        // Number of loop-carried dependencies in the body (excluding iter_num and cond_in)
222        let num_body_loop_inputs = body_inputs.len() - 2;
223
224        // Number of loop-carried outputs from body (excluding cond_out)
225        // Body outputs = [cond_out, v_out..., scan_outputs...]
226        let num_body_loop_outputs = body_outputs.len() - 1;
227
228        // The body must output at least as many values as it takes as loop-carried inputs
229        // (it can output more due to scan outputs)
230        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        // Create outputs based on body outputs (excluding cond_out)
238        // Per ONNX spec:
239        // - Loop-carried dependencies: final value matches body output type
240        // - Scan outputs: concatenated along axis 0, adding a new dimension
241        //
242        // Body outputs: [cond_out, v_out_1, ..., v_out_N, scan_out_1, ..., scan_out_K]
243        // Loop outputs: [v_final_1, ..., v_final_N, scan_1, ..., scan_K]
244        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                // Scan outputs get concatenated, adding a dimension at axis 0
251                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            // Update types for existing outputs
259            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                    // Scan outputs get concatenated, adding a dimension at axis 0
264                    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        // Extract body graph from attributes
278        let body_attr = node
279            .attrs
280            .get("body")
281            .ok_or_else(|| ProcessError::MissingAttribute("body".to_string()))?
282            .clone();
283
284        // Build outer scope types map from additional inputs (beyond ONNX inputs)
285        let mut outer_scope = build_outer_scope_from_inputs(node);
286
287        // Handle DeferredGraph and Graph
288        let body = match body_attr {
289            crate::ir::AttributeValue::DeferredGraph(deferred) => {
290                // ONNX lets a body omit the type of a loop-carried input; it then takes the
291                // type of the matching v_initial. Without this the input would default to a
292                // rank-0 tensor. Graph inputs resolve before outer scope, so these entries
293                // only supply the type.
294                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                // Build the subgraph now with outer-scope types
308                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        // Get the scope ref names for use in code generation
327        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                // iter_num
366                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                // cond_in
373                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                // v_in (loop-carried variable)
380                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                // cond_out
393                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                // v_out (loop-carried variable output)
400                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        // Extract config first
433        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        // Loop should have 1 output (v_final)
439        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) // Should be scalar, not tensor
452            .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}