1use 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#[derive(Debug, Clone, NodeBuilder)]
38pub struct AddNode {
39 pub name: String,
40 pub inputs: Vec<Argument>,
41 pub outputs: Vec<Argument>,
42}
43
44#[derive(Debug, Clone, NodeBuilder)]
46pub struct SubNode {
47 pub name: String,
48 pub inputs: Vec<Argument>,
49 pub outputs: Vec<Argument>,
50}
51
52#[derive(Debug, Clone, NodeBuilder)]
54pub struct MulNode {
55 pub name: String,
56 pub inputs: Vec<Argument>,
57 pub outputs: Vec<Argument>,
58}
59
60#[derive(Debug, Clone, NodeBuilder)]
62pub struct DivNode {
63 pub name: String,
64 pub inputs: Vec<Argument>,
65 pub outputs: Vec<Argument>,
66}
67
68pub(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 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 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 if node.inputs[0].ty.is_scalar_native() {
135 prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
136 }
137
138 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 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}