Skip to main content

onnx_ir/node/
scan_node.rs

1//! # Scan
2//!
3//! Generic scan construct - iterates over input sequences while maintaining state variables.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__Scan.html>
6//!
7//! ## Opset Versions
8//! - **Opset 8**: Initial version, with a batch axis on every input and a leading
9//!   `sequence_lens` input. Not supported: the processor requires opset 9+.
10//! - **Opset 9**: Added scan_input_axes
11//! - **Opset 11**: Clarified behavior
12//! - **Opset 16**: Further refinements
13use derive_new::new;
14use onnx_ir_derive::NodeBuilder;
15
16use crate::ir::Argument;
17
18use crate::ir::{ArgType, Node, OnnxGraph, RawNode};
19use crate::processor::{
20    NodeProcessor, OutputPreferences, ProcessError, build_outer_scope_from_inputs,
21};
22
23/// Configuration for Scan operation
24#[derive(Debug, Clone, new)]
25pub struct ScanConfig {
26    pub body: OnnxGraph,
27    pub num_scan_inputs: i64,
28    pub scan_input_directions: Vec<i64>,
29    pub scan_output_directions: Vec<i64>,
30    pub scan_input_axes: Vec<i64>,
31    pub scan_output_axes: Vec<i64>,
32    /// Names of outer-scope references (in order corresponding to inputs after ONNX inputs)
33    /// These are the original sanitized ONNX names that subgraphs reference
34    #[new(default)]
35    pub scope_ref_names: Vec<String>,
36}
37
38/// Node representation for Scan operation
39#[derive(Debug, Clone, NodeBuilder)]
40pub struct ScanNode {
41    pub name: String,
42    pub inputs: Vec<Argument>,
43    pub outputs: Vec<Argument>,
44    pub config: ScanConfig,
45}
46
47/// Scan node processor
48pub(crate) struct ScanProcessor;
49
50impl NodeProcessor for ScanProcessor {
51    type Config = ScanConfig;
52
53    fn infer_types(
54        &self,
55        node: &mut RawNode,
56        opset: usize,
57        _output_preferences: &OutputPreferences,
58    ) -> Result<(), ProcessError> {
59        crate::processor::validate_opset(opset, 9)?;
60
61        // Get config to determine number of state variables and scan inputs
62        let config = self.extract_config(node, opset)?;
63        let num_scan_inputs = config.num_scan_inputs as usize;
64
65        // Get the count of original ONNX inputs (excluding outer-scope refs we added)
66        let onnx_input_count = crate::processor::get_onnx_input_count(node);
67
68        // Total ONNX inputs = num_state_vars + num_scan_inputs
69        if onnx_input_count < num_scan_inputs {
70            return Err(ProcessError::Custom(format!(
71                "Scan requires at least {} inputs (num_scan_inputs), got {}",
72                num_scan_inputs, onnx_input_count
73            )));
74        }
75
76        let num_state_vars = onnx_input_count - num_scan_inputs;
77
78        // Get body outputs to determine output types
79        let body_outputs = config.body.outputs.clone();
80
81        // Body outputs = [state_vars_out..., scan_outputs...]
82        // Minimum: num_state_vars (state variables must be preserved)
83        if body_outputs.len() < num_state_vars {
84            return Err(ProcessError::Custom(format!(
85                "Scan body must have at least {} outputs (state variables), got {}",
86                num_state_vars,
87                body_outputs.len()
88            )));
89        }
90
91        let _num_scan_outputs = body_outputs.len() - num_state_vars;
92
93        // Scan node outputs = [final_state_vars..., scan_output_sequences...]
94        // Final state vars have same type as body output state vars
95        // Scan output sequences have rank increased by 1 for the sequence dimension
96
97        if node.outputs.is_empty() {
98            // Create outputs: first the final state variables
99            for body_output in body_outputs.iter().take(num_state_vars) {
100                node.outputs.push(body_output.clone());
101            }
102
103            // Then the scan output sequences
104            // Scan outputs have rank increased by 1 compared to body outputs
105            for body_scan_output in body_outputs.iter().skip(num_state_vars) {
106                let mut output = body_scan_output.clone();
107                output.name = format!("{}_sequence", body_scan_output.name);
108
109                // Increase rank by 1 for sequence dimension
110                match &body_scan_output.ty {
111                    ArgType::Tensor(body_tensor) => {
112                        output.ty = ArgType::Tensor(crate::ir::TensorType {
113                            dtype: body_tensor.dtype,
114                            rank: body_tensor.rank + 1,
115                            static_shape: None, // Dynamic shape for now
116                        });
117                    }
118                    _ => {
119                        // Keep same type if not a tensor
120                    }
121                }
122
123                node.outputs.push(output);
124            }
125        } else {
126            // Update types for existing outputs
127            for (output, body_output) in node
128                .outputs
129                .iter_mut()
130                .zip(body_outputs.iter())
131                .take(num_state_vars)
132            {
133                output.ty = body_output.ty.clone();
134            }
135
136            // Update scan output sequence types
137            for i in num_state_vars..node.outputs.len() {
138                let body_idx = i;
139                if body_idx < body_outputs.len() {
140                    match &body_outputs[body_idx].ty {
141                        ArgType::Tensor(body_tensor) => {
142                            node.outputs[i].ty = ArgType::Tensor(crate::ir::TensorType {
143                                dtype: body_tensor.dtype,
144                                rank: body_tensor.rank + 1,
145                                static_shape: None,
146                            });
147                        }
148                        _ => {
149                            node.outputs[i].ty = body_outputs[body_idx].ty.clone();
150                        }
151                    }
152                }
153            }
154        }
155
156        Ok(())
157    }
158
159    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
160        // Extract body graph from attributes
161        let body_attr = node
162            .attrs
163            .get("body")
164            .ok_or_else(|| ProcessError::MissingAttribute("body".to_string()))?
165            .clone();
166
167        // Build outer scope types map from additional inputs (beyond ONNX inputs)
168        let outer_scope = build_outer_scope_from_inputs(node);
169
170        // Handle DeferredGraph and Graph
171        let body = match body_attr {
172            crate::ir::AttributeValue::DeferredGraph(deferred) => {
173                // Build the subgraph now with outer-scope types
174                log::debug!(
175                    "Building deferred Scan body subgraph with {} outer-scope types",
176                    outer_scope.len()
177                );
178                deferred
179                    .build_graph_with_outer_scope(outer_scope)
180                    .map_err(|e| {
181                        ProcessError::Custom(format!("Failed to build Scan body: {}", e))
182                    })?
183            }
184            crate::ir::AttributeValue::Graph(g) => g,
185            _ => {
186                return Err(ProcessError::Custom(
187                    "Expected DeferredGraph or Graph for body".to_string(),
188                ));
189            }
190        };
191
192        // Extract num_scan_inputs (required)
193        let num_scan_inputs = node
194            .attrs
195            .get("num_scan_inputs")
196            .ok_or_else(|| ProcessError::MissingAttribute("num_scan_inputs".to_string()))?
197            .clone()
198            .into_i64()?;
199
200        // Extract optional direction attributes
201        let scan_input_directions = node
202            .attrs
203            .get("scan_input_directions")
204            .map(|v| v.clone().into_i64s())
205            .transpose()?
206            .unwrap_or_default();
207
208        let scan_output_directions = node
209            .attrs
210            .get("scan_output_directions")
211            .map(|v| v.clone().into_i64s())
212            .transpose()?
213            .unwrap_or_default();
214
215        let scan_input_axes = node
216            .attrs
217            .get("scan_input_axes")
218            .map(|v| v.clone().into_i64s())
219            .transpose()?
220            .unwrap_or_default();
221
222        let scan_output_axes = node
223            .attrs
224            .get("scan_output_axes")
225            .map(|v| v.clone().into_i64s())
226            .transpose()?
227            .unwrap_or_default();
228
229        // Get the scope ref names for use in code generation
230        let scope_ref_names: Vec<String> = node
231            .attrs
232            .get("__scope_ref_names")
233            .and_then(|v| match v {
234                crate::ir::AttributeValue::Strings(names) => Some(names.clone()),
235                _ => None,
236            })
237            .unwrap_or_default();
238
239        Ok(ScanConfig {
240            body,
241            num_scan_inputs,
242            scan_input_directions,
243            scan_output_directions,
244            scan_input_axes,
245            scan_output_axes,
246            scope_ref_names,
247        })
248    }
249
250    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
251        let config = self.extract_config(&builder, opset)?;
252
253        Ok(Node::Scan(ScanNode {
254            name: builder.name,
255            inputs: builder.inputs,
256            outputs: builder.outputs,
257            config,
258        }))
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use crate::ir::AttributeValue;
266    use crate::ir::{Argument, DType, NodeType, OnnxGraph, TensorType};
267    use crate::node::test_utils::TestNodeBuilder;
268
269    fn create_test_body(num_state_vars: usize, num_scan_inputs: usize) -> OnnxGraph {
270        let mut body_inputs = Vec::new();
271        let mut body_outputs = Vec::new();
272
273        // State variable inputs and outputs
274        for i in 0..num_state_vars {
275            body_inputs.push(Argument {
276                name: format!("state_{}", i),
277                ty: ArgType::Tensor(TensorType {
278                    dtype: DType::F32,
279                    rank: 2,
280                    static_shape: Some(vec![Some(2), Some(3)]),
281                }),
282                value_source: crate::ir::ValueSource::Dynamic,
283                value_store: None,
284            });
285
286            body_outputs.push(Argument {
287                name: format!("state_{}_out", i),
288                ty: ArgType::Tensor(TensorType {
289                    dtype: DType::F32,
290                    rank: 2,
291                    static_shape: Some(vec![Some(2), Some(3)]),
292                }),
293                value_source: crate::ir::ValueSource::Dynamic,
294                value_store: None,
295            });
296        }
297
298        // Scan input elements
299        for i in 0..num_scan_inputs {
300            body_inputs.push(Argument {
301                name: format!("scan_in_{}", i),
302                ty: ArgType::Tensor(TensorType {
303                    dtype: DType::F32,
304                    rank: 2,
305                    static_shape: Some(vec![Some(2), Some(3)]),
306                }),
307                value_source: crate::ir::ValueSource::Dynamic,
308                value_store: None,
309            });
310        }
311
312        // Scan outputs
313        for i in 0..num_scan_inputs {
314            body_outputs.push(Argument {
315                name: format!("scan_out_{}", i),
316                ty: ArgType::Tensor(TensorType {
317                    dtype: DType::F32,
318                    rank: 2,
319                    static_shape: Some(vec![Some(2), Some(3)]),
320                }),
321                value_source: crate::ir::ValueSource::Dynamic,
322                value_store: None,
323            });
324        }
325
326        OnnxGraph {
327            nodes: vec![],
328            inputs: body_inputs,
329            outputs: body_outputs,
330            value_store: None,
331        }
332    }
333
334    #[test]
335    fn test_scan_infer_types_basic() {
336        let num_state_vars = 1;
337        let num_scan_inputs = 1;
338        let body = create_test_body(num_state_vars, num_scan_inputs);
339
340        let mut node = TestNodeBuilder::new(NodeType::Scan, "test_scan")
341            .input_tensor_f32("initial_state", 2, Some(vec![2, 3]))
342            .input_tensor_f32("scan_input_seq", 3, Some(vec![4, 2, 3]))
343            .build();
344
345        node.attrs
346            .insert("body".to_string(), AttributeValue::Graph(body));
347        node.attrs
348            .insert("num_scan_inputs".to_string(), AttributeValue::Int64(1));
349
350        let processor = ScanProcessor;
351        // Extract config first
352        let _config = processor.extract_config(&node, 9).unwrap();
353
354        let result = processor.infer_types(&mut node, 9, &OutputPreferences::default());
355
356        assert!(result.is_ok());
357        // Should have 2 outputs: final_state and scan_output_seq
358        assert_eq!(node.outputs.len(), 2);
359    }
360
361    #[test]
362    fn test_scan_rejects_opset_8() {
363        // Opset 8 adds a batch axis and a sequence_lens input that the processor does not model
364        let body = create_test_body(1, 1);
365        let mut node = TestNodeBuilder::new(NodeType::Scan, "test_scan")
366            .input_tensor_f32("initial_state", 2, Some(vec![2, 3]))
367            .input_tensor_f32("scan_input_seq", 3, Some(vec![4, 2, 3]))
368            .build();
369        node.attrs
370            .insert("body".to_string(), AttributeValue::Graph(body));
371        node.attrs
372            .insert("num_scan_inputs".to_string(), AttributeValue::Int64(1));
373
374        let result = ScanProcessor.infer_types(&mut node, 8, &OutputPreferences::default());
375
376        assert!(matches!(
377            result,
378            Err(ProcessError::UnsupportedOpset {
379                required: 9,
380                actual: 8
381            })
382        ));
383    }
384}