Skip to main content

onnx_ir/node/
arithmetic.rs

1//! # Arithmetic Operations (Add, Sub, Mul, Div)
2//!
3//! Implements element-wise binary arithmetic operations with multidirectional (Numpy-style)
4//! broadcasting support. These operators share the same type propagation semantics and handle
5//! special cases for Shape and Scalar types to preserve semantics through arithmetic operations.
6//!
7//! **ONNX Specs**:
8//! - Add: <https://onnx.ai/onnx/operators/onnx__Add.html>
9//! - Sub: <https://onnx.ai/onnx/operators/onnx__Sub.html>
10//! - Mul: <https://onnx.ai/onnx/operators/onnx__Mul.html>
11//! - Div: <https://onnx.ai/onnx/operators/onnx__Div.html>
12//!
13//! ## Type Constraints
14//!
15//! T: Numeric tensor types (float16, float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
16//!
17//! ## Opset Versions
18//! - **Opset 1-6**: Limited broadcast support (unidirectional only)
19//! - **Opset 7-12**: Added multidirectional (Numpy-style) broadcasting for Add, Sub, Div
20//! - **Opset 13**: Multidirectional broadcasting for Mul, extended type support (bfloat16)
21//! - **Opset 14+**: Extended type support to include uint8, int8, uint16, int16, uint32, uint64
22//!
23//! ## Special Handling
24//!
25//! This implementation includes type preference propagation for:
26//! - **Shape arithmetic**: When operating on Shape types with constants, prefers constants as Shape
27//! - **Scalar arithmetic**: When operating on Scalar types with constants, prefers constants as Scalar
28
29use crate::ir::{Argument, Node, RawNode};
30use crate::processor::{
31    InputPreferences, InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec,
32    ProcessError, same_as_input_broadcast,
33};
34use onnx_ir_derive::NodeBuilder;
35
36/// Node representation for Add operation
37#[derive(Debug, Clone, NodeBuilder)]
38pub struct AddNode {
39    pub name: String,
40    pub inputs: Vec<Argument>,
41    pub outputs: Vec<Argument>,
42}
43
44/// Node representation for Sub operation
45#[derive(Debug, Clone, NodeBuilder)]
46pub struct SubNode {
47    pub name: String,
48    pub inputs: Vec<Argument>,
49    pub outputs: Vec<Argument>,
50}
51
52/// Node representation for Mul operation
53#[derive(Debug, Clone, NodeBuilder)]
54pub struct MulNode {
55    pub name: String,
56    pub inputs: Vec<Argument>,
57    pub outputs: Vec<Argument>,
58}
59
60/// Node representation for Div operation
61#[derive(Debug, Clone, NodeBuilder)]
62pub struct DivNode {
63    pub name: String,
64    pub inputs: Vec<Argument>,
65    pub outputs: Vec<Argument>,
66}
67
68/// Node processor for basic arithmetic binary operations
69///
70/// Handles type inference for element-wise arithmetic operations with special support for:
71/// - Shape arithmetic (e.g., adding offsets to tensor shapes, dividing shapes)
72/// - Scalar arithmetic (preserving scalar types through operations)
73/// - Standard tensor broadcasting
74///
75/// This processor is used for Add, Sub, Mul, and Div operations as they all
76/// share the same type propagation semantics.
77pub(crate) struct ArithmeticBinaryProcessor;
78
79impl NodeProcessor for ArithmeticBinaryProcessor {
80    type Config = ();
81
82    fn spec(&self) -> NodeSpec {
83        NodeSpec {
84            min_opset: 1,
85            max_opset: None,
86            inputs: InputSpec::Exact(2),
87            outputs: OutputSpec::Exact(1),
88        }
89    }
90
91    fn input_preferences(
92        &self,
93        node: &RawNode,
94        _opset: usize,
95    ) -> Result<Option<InputPreferences>, ProcessError> {
96        use crate::processor::ArgPreference;
97
98        if node.inputs.len() != 2 {
99            return Ok(None);
100        }
101
102        let mut prefs = InputPreferences::new();
103
104        // Type propagation for Shape arithmetic:
105        // When performing arithmetic on a Shape with a constant, prefer the constant to be Shape type.
106        // This is common in dynamic shape calculations like:
107        // - new_shape = old_shape + offset
108        // - half_shape = old_shape / 2
109
110        // Case 1: Shape op Constant => prefer Constant as Shape (or ScalarNative for scalars)
111        if node.inputs[0].ty.is_shape() {
112            if node.inputs[1].ty.is_scalar() {
113                prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
114            } else {
115                prefs = prefs.add(&node.inputs[1].name, ArgPreference::Shape);
116            }
117        }
118
119        // Case 2: Constant op Shape => prefer Constant as Shape (or ScalarNative for scalars)
120        if node.inputs[1].ty.is_shape() {
121            if node.inputs[0].ty.is_scalar() {
122                prefs = prefs.add(&node.inputs[0].name, ArgPreference::ScalarNative);
123            } else {
124                prefs = prefs.add(&node.inputs[0].name, ArgPreference::Shape);
125            }
126        }
127
128        // Type propagation for ScalarNative arithmetic:
129        // When one input is ScalarNative, the other should also be ScalarNative
130        // to keep CPU-side arithmetic chains on CPU.
131        // ScalarTensor inputs don't need preferences (they're the performant default).
132
133        // Case 3: ScalarNative op Constant => prefer Constant as ScalarNative
134        if node.inputs[0].ty.is_scalar_native() {
135            prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
136        }
137
138        // Case 4: Constant op ScalarNative => prefer Constant as ScalarNative
139        if node.inputs[1].ty.is_scalar_native() {
140            prefs = prefs.add(&node.inputs[0].name, ArgPreference::ScalarNative);
141        }
142
143        Ok(Some(prefs))
144    }
145
146    fn infer_types(
147        &self,
148        node: &mut RawNode,
149        _opset: usize,
150        _output_preferences: &OutputPreferences,
151    ) -> Result<(), ProcessError> {
152        // Apply standard broadcasting rules to infer output type
153        same_as_input_broadcast(node);
154
155        Ok(())
156    }
157
158    fn build_node(&self, builder: RawNode, _opset: usize) -> Result<Node, ProcessError> {
159        Ok(match builder.node_type {
160            crate::ir::NodeType::Add => Node::Add(AddNode {
161                name: builder.name,
162                inputs: builder.inputs,
163                outputs: builder.outputs,
164            }),
165            crate::ir::NodeType::Sub => Node::Sub(SubNode {
166                name: builder.name,
167                inputs: builder.inputs,
168                outputs: builder.outputs,
169            }),
170            crate::ir::NodeType::Mul => Node::Mul(MulNode {
171                name: builder.name,
172                inputs: builder.inputs,
173                outputs: builder.outputs,
174            }),
175            crate::ir::NodeType::Div => Node::Div(DivNode {
176                name: builder.name,
177                inputs: builder.inputs,
178                outputs: builder.outputs,
179            }),
180            other => {
181                return Err(ProcessError::Custom(format!(
182                    "ArithmeticBinaryProcessor called with unsupported node type {other:?}"
183                )));
184            }
185        })
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use crate::ir::{ArgType, NodeType};
193    use crate::node::test_utils::TestNodeBuilder;
194
195    #[test]
196    fn test_arithmetic_add() {
197        let node = TestNodeBuilder::new(NodeType::Add, "test_add")
198            .input_tensor_f32("a", 2, None)
199            .input_tensor_f32("b", 2, None)
200            .output_default("c")
201            .process(ArithmeticBinaryProcessor, 16);
202
203        match &node.outputs[0].ty {
204            ArgType::Tensor(t) => assert_eq!(t.rank, 2),
205            _ => panic!("Expected tensor output"),
206        }
207    }
208
209    #[test]
210    fn test_arithmetic_sub() {
211        let node = TestNodeBuilder::new(NodeType::Sub, "test_sub")
212            .input_tensor_f32("a", 3, None)
213            .input_tensor_f32("b", 3, None)
214            .output_default("c")
215            .process(ArithmeticBinaryProcessor, 16);
216
217        match &node.outputs[0].ty {
218            ArgType::Tensor(t) => assert_eq!(t.rank, 3),
219            _ => panic!("Expected tensor output"),
220        }
221    }
222
223    #[test]
224    fn test_arithmetic_mul() {
225        let node = TestNodeBuilder::new(NodeType::Mul, "test_mul")
226            .input_tensor_f32("a", 4, None)
227            .input_tensor_f32("b", 4, None)
228            .output_default("c")
229            .process(ArithmeticBinaryProcessor, 16);
230
231        match &node.outputs[0].ty {
232            ArgType::Tensor(t) => assert_eq!(t.rank, 4),
233            _ => panic!("Expected tensor output"),
234        }
235    }
236
237    #[test]
238    fn test_arithmetic_div() {
239        let node = TestNodeBuilder::new(NodeType::Div, "test_div")
240            .input_tensor_f32("a", 2, None)
241            .input_tensor_f32("b", 2, None)
242            .output_default("c")
243            .process(ArithmeticBinaryProcessor, 16);
244
245        match &node.outputs[0].ty {
246            ArgType::Tensor(t) => assert_eq!(t.rank, 2),
247            _ => panic!("Expected tensor output"),
248        }
249    }
250
251    #[test]
252    fn test_invalid_opset() {
253        let node = TestNodeBuilder::new(NodeType::Add, "test_add")
254            .input_tensor_f32("a", 2, None)
255            .input_tensor_f32("b", 2, None)
256            .output_default("c")
257            .build();
258
259        let processor = ArithmeticBinaryProcessor;
260        let spec = processor.spec();
261        let result = crate::processor::validate_node_spec(&node, 1, &spec);
262        assert!(result.is_ok(), "Add should be supported at opset 1");
263    }
264
265    #[test]
266    fn test_invalid_input_count() {
267        let node = TestNodeBuilder::new(NodeType::Add, "test_add")
268            .input_tensor_f32("a", 2, None)
269            .output_default("c")
270            .build();
271
272        let processor = ArithmeticBinaryProcessor;
273        let spec = processor.spec();
274        let result = crate::processor::validate_node_spec(&node, 16, &spec);
275        assert!(matches!(
276            result,
277            Err(ProcessError::InvalidInputCount {
278                expected: 2,
279                actual: 1
280            })
281        ));
282    }
283}