1use 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#[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 #[new(default)]
35 pub scope_ref_names: Vec<String>,
36}
37
38#[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
47pub(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 let config = self.extract_config(node, opset)?;
63 let num_scan_inputs = config.num_scan_inputs as usize;
64
65 let onnx_input_count = crate::processor::get_onnx_input_count(node);
67
68 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 let body_outputs = config.body.outputs.clone();
80
81 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 if node.outputs.is_empty() {
98 for body_output in body_outputs.iter().take(num_state_vars) {
100 node.outputs.push(body_output.clone());
101 }
102
103 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 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, });
117 }
118 _ => {
119 }
121 }
122
123 node.outputs.push(output);
124 }
125 } else {
126 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 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 let body_attr = node
162 .attrs
163 .get("body")
164 .ok_or_else(|| ProcessError::MissingAttribute("body".to_string()))?
165 .clone();
166
167 let outer_scope = build_outer_scope_from_inputs(node);
169
170 let body = match body_attr {
172 crate::ir::AttributeValue::DeferredGraph(deferred) => {
173 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 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 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 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 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 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 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 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 assert_eq!(node.outputs.len(), 2);
359 }
360
361 #[test]
362 fn test_scan_rejects_opset_8() {
363 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}