Skip to main content

onnx_ir/node/
shape.rs

1//! # Shape
2//!
3//! Extracts the shape of an input tensor as a 1D int64 tensor.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__Shape.html>
6//!
7//! ## Special Features
8//! - `start` attribute (int, optional, opset 15+): Starting dimension for partial shape extraction.
9//!   If omitted, defaults to 0. Negative values count from the end. Values are clamped to [0, rank].
10//! - `end` attribute (int, optional, opset 15+): Ending dimension (exclusive) for partial shape extraction.
11//!   If omitted, defaults to rank. Negative values count from the end. Values are clamped to [0, rank].
12//!
13//! ## Opset Versions
14//! - **Opset 1-14**: Outputs full shape as 1D int64 tensor (no attributes).
15//! - **Opset 15**: Added `start` and `end` attributes to enable partial shape extraction,
16//!   allowing selection of a slice of dimensions from the input shape.
17//! - **Opset 19**: Added support for bfloat16 input data type.
18//! - **Opset 21**: Added support for int4, uint4, and float8 input data types.
19
20use onnx_ir_derive::NodeBuilder;
21
22use crate::ir::{ArgType, Argument, Node, RawNode};
23use crate::processor::{
24    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
25};
26
27/// Configuration for the Shape operation.
28#[derive(Debug, Clone)]
29pub struct ShapeConfig {
30    pub start: usize,
31    pub end: usize,
32}
33
34/// Node representation for Shape operation
35#[derive(Debug, Clone, NodeBuilder)]
36pub struct ShapeNode {
37    pub name: String,
38    pub inputs: Vec<Argument>,
39    pub outputs: Vec<Argument>,
40    pub config: ShapeConfig,
41}
42
43pub(crate) struct ShapeProcessor;
44
45impl NodeProcessor for ShapeProcessor {
46    type Config = ShapeConfig;
47
48    fn spec(&self) -> NodeSpec {
49        NodeSpec {
50            min_opset: 1,
51            max_opset: None,
52            inputs: InputSpec::Exact(1),
53            outputs: OutputSpec::Exact(1),
54        }
55    }
56
57    fn infer_types(
58        &self,
59        node: &mut RawNode,
60        opset: usize,
61        _output_preferences: &OutputPreferences,
62    ) -> Result<(), ProcessError> {
63        // Determine output dimension based on input type
64        let dim = match &node.inputs[0].ty {
65            ArgType::Tensor(_) => {
66                // Shape of a Tensor: output has (end - start) elements
67                let config = self.extract_config(node, opset)?;
68                config.end - config.start
69            }
70            ArgType::Shape(_) => {
71                // Shape of a Shape: output is always a 1-element array containing the length
72                1
73            }
74            ArgType::ScalarTensor(_) => {
75                // ScalarTensor is rank 1; apply start/end like a rank-1 Tensor
76                let config = self.extract_config(node, opset)?;
77                config.end - config.start
78            }
79            _ => {
80                return Err(ProcessError::TypeMismatch {
81                    expected: "Tensor, Shape, or ScalarTensor".to_string(),
82                    actual: format!("{:?}", node.inputs[0].ty),
83                });
84            }
85        };
86
87        // Infer output type - Shape always outputs Shape type
88        node.outputs[0].ty = ArgType::Shape(dim);
89
90        Ok(())
91    }
92
93    fn extract_config(&self, node: &RawNode, opset: usize) -> Result<Self::Config, ProcessError> {
94        // Extract the rank/dimension count from the input
95        let rank = match &node.inputs[0].ty {
96            ArgType::Tensor(tensor) => tensor.rank,
97            ArgType::Shape(rank) => *rank,
98            ArgType::ScalarTensor(_) => 1,
99            _ => {
100                return Err(ProcessError::TypeMismatch {
101                    expected: "Tensor, Shape, or ScalarTensor".to_string(),
102                    actual: format!("{:?}", node.inputs[0].ty),
103                });
104            }
105        };
106
107        // Extract start/end attributes (opset 15+ only)
108        let mut start_dim: i64 = 0;
109        let mut end_dim: i64 = rank as i64;
110
111        if opset >= 15 {
112            for (key, value) in node.attrs.iter() {
113                match key.as_str() {
114                    "start" => start_dim = value.clone().into_i64()?,
115                    "end" => end_dim = value.clone().into_i64()?,
116                    _ => {}
117                }
118            }
119        }
120
121        // Handle negative indices
122        if start_dim < 0 {
123            start_dim += rank as i64;
124        }
125        if end_dim < 0 {
126            end_dim += rank as i64;
127        }
128
129        // Clamp to [0, rank] per ONNX spec, then ensure end >= start
130        let rank_i64 = rank as i64;
131        start_dim = start_dim.max(0).min(rank_i64);
132        end_dim = end_dim.max(start_dim).min(rank_i64);
133
134        // Calculate dimensions
135        let start = start_dim as usize;
136        let end = end_dim as usize;
137
138        let config = ShapeConfig { start, end };
139        Ok(config)
140    }
141
142    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
143        let config = self.extract_config(&builder, opset)?;
144
145        Ok(Node::Shape(ShapeNode {
146            name: builder.name,
147            inputs: builder.inputs,
148            outputs: builder.outputs,
149            config,
150        }))
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use crate::ir::NodeType;
158    use crate::node::test_utils::TestNodeBuilder;
159
160    fn create_test_node(start: Option<i64>, end: Option<i64>, rank: usize) -> RawNode {
161        let mut builder = TestNodeBuilder::new(NodeType::Shape, "test_shape")
162            .input_tensor_f32("data", rank, None)
163            .output_tensor_i64("shape", 1, None);
164
165        if let Some(start_val) = start {
166            builder = builder.attr_int("start", start_val);
167        }
168
169        if let Some(end_val) = end {
170            builder = builder.attr_int("end", end_val);
171        }
172
173        builder.build()
174    }
175
176    #[test]
177    fn test_shape_config_defaults() {
178        let mut node = create_test_node(None, None, 4);
179        let processor = ShapeProcessor;
180        let prefs = OutputPreferences::new();
181
182        let config = processor.extract_config(&node, 16).unwrap();
183        processor.infer_types(&mut node, 16, &prefs).unwrap();
184
185        assert_eq!(config.start, 0);
186        assert_eq!(config.end, 4);
187
188        // Should always output Shape
189        assert!(matches!(node.outputs[0].ty, ArgType::Shape(4)));
190    }
191
192    #[test]
193    fn test_shape_config_with_start() {
194        let mut node = create_test_node(Some(1), None, 4);
195
196        let processor = ShapeProcessor;
197
198        let prefs = OutputPreferences::new();
199        let config = processor.extract_config(&node, 16).unwrap();
200        processor.infer_types(&mut node, 16, &prefs).unwrap();
201
202        assert_eq!(config.start, 1);
203        assert_eq!(config.end, 4);
204    }
205
206    #[test]
207    fn test_shape_config_with_end() {
208        let mut node = create_test_node(None, Some(3), 4);
209
210        let processor = ShapeProcessor;
211
212        let prefs = OutputPreferences::new();
213        let config = processor.extract_config(&node, 16).unwrap();
214        processor.infer_types(&mut node, 16, &prefs).unwrap();
215
216        assert_eq!(config.start, 0);
217        assert_eq!(config.end, 3);
218    }
219
220    #[test]
221    fn test_shape_config_with_start_and_end() {
222        let mut node = create_test_node(Some(1), Some(3), 4);
223
224        let processor = ShapeProcessor;
225
226        let prefs = OutputPreferences::new();
227        let config = processor.extract_config(&node, 16).unwrap();
228        processor.infer_types(&mut node, 16, &prefs).unwrap();
229
230        assert_eq!(config.start, 1);
231        assert_eq!(config.end, 3);
232    }
233
234    #[test]
235    fn test_shape_config_negative_dims() {
236        let mut node = create_test_node(Some(-2), Some(-1), 4);
237
238        let processor = ShapeProcessor;
239
240        let prefs = OutputPreferences::new();
241        let config = processor.extract_config(&node, 16).unwrap();
242        processor.infer_types(&mut node, 16, &prefs).unwrap();
243
244        assert_eq!(config.start, 2); // -2 + 4 = 2
245        assert_eq!(config.end, 3); // -1 + 4 = 3
246    }
247
248    #[test]
249    fn test_shape_config_multiple_inputs() {
250        let mut node = create_test_node(None, None, 4);
251        // Add an extra input to cause error
252        node.inputs.push(Argument {
253            name: "extra".to_string(),
254            ty: crate::ir::ArgType::Tensor(crate::ir::TensorType {
255                dtype: crate::ir::DType::F32,
256                rank: 4,
257                static_shape: None,
258            }),
259            value_source: crate::ir::ValueSource::Dynamic,
260            value_store: None,
261        });
262
263        let processor = ShapeProcessor;
264        let spec = processor.spec();
265        let result = crate::processor::validate_node_spec(&node, 16, &spec);
266        assert!(matches!(
267            result,
268            Err(ProcessError::InvalidInputCount {
269                expected: 1,
270                actual: 2
271            })
272        ));
273    }
274
275    #[test]
276    fn test_shape_clamp_start_exceeds_rank() {
277        // start=10 on rank-4 tensor should clamp to 4
278        let node = create_test_node(Some(10), None, 4);
279        let processor = ShapeProcessor;
280        let config = processor.extract_config(&node, 16).unwrap();
281        assert_eq!(config.start, 4);
282        assert_eq!(config.end, 4);
283    }
284
285    #[test]
286    fn test_shape_clamp_end_exceeds_rank() {
287        // end=10 on rank-4 tensor should clamp to 4
288        let node = create_test_node(None, Some(10), 4);
289        let processor = ShapeProcessor;
290        let config = processor.extract_config(&node, 16).unwrap();
291        assert_eq!(config.start, 0);
292        assert_eq!(config.end, 4);
293    }
294
295    #[test]
296    fn test_shape_clamp_both_exceed_rank() {
297        let node = create_test_node(Some(5), Some(10), 4);
298        let processor = ShapeProcessor;
299        let config = processor.extract_config(&node, 16).unwrap();
300        assert_eq!(config.start, 4);
301        assert_eq!(config.end, 4);
302    }
303
304    #[test]
305    fn test_shape_clamp_negative_below_neg_rank() {
306        // start=-10 on rank-4: -10+4=-6, clamped to 0
307        let node = create_test_node(Some(-10), Some(-5), 4);
308        let processor = ShapeProcessor;
309        let config = processor.extract_config(&node, 16).unwrap();
310        assert_eq!(config.start, 0);
311        assert_eq!(config.end, 0);
312    }
313
314    #[test]
315    fn test_shape_clamp_start_greater_than_end() {
316        // start=3, end=1 on rank-4: end clamped up to start, yielding empty slice
317        let node = create_test_node(Some(3), Some(1), 4);
318        let processor = ShapeProcessor;
319        let config = processor.extract_config(&node, 16).unwrap();
320        assert_eq!(config.start, 3);
321        assert_eq!(config.end, 3);
322    }
323
324    #[test]
325    fn test_shape_opset_below_15_ignores_start_end() {
326        // Opset 14: start/end attributes should be ignored, full shape returned
327        let node = create_test_node(Some(1), Some(3), 4);
328        let processor = ShapeProcessor;
329        let config = processor.extract_config(&node, 14).unwrap();
330        assert_eq!(config.start, 0);
331        assert_eq!(config.end, 4);
332    }
333
334    #[test]
335    fn test_shape_output_type() {
336        // Shape operation always outputs Shape type
337        let mut node = TestNodeBuilder::new(NodeType::Shape, "test_shape")
338            .input_tensor_f32("data", 3, None)
339            .output_tensor_i64("shape", 1, None)
340            .build();
341
342        let processor = ShapeProcessor;
343        let prefs = OutputPreferences::new();
344
345        let _config = processor.extract_config(&node, 16).unwrap();
346        processor.infer_types(&mut node, 16, &prefs).unwrap();
347
348        // Should always output Shape type
349        assert!(matches!(node.outputs[0].ty, ArgType::Shape(3)));
350    }
351
352    #[test]
353    fn test_shape_scalar_tensor_input() {
354        // ScalarTensor is rank 1, so Shape should return Shape(1)
355        let mut node = TestNodeBuilder::new(NodeType::Shape, "test_shape")
356            .add_input("data", ArgType::ScalarTensor(crate::ir::DType::I64))
357            .output_tensor_i64("shape", 1, None)
358            .build();
359
360        let processor = ShapeProcessor;
361        let prefs = OutputPreferences::new();
362        processor.infer_types(&mut node, 16, &prefs).unwrap();
363
364        assert!(matches!(node.outputs[0].ty, ArgType::Shape(1)));
365    }
366}