Skip to main content

onnx_ir/node/
comparison.rs

1//! # Comparison Operations (Equal, Greater, Less, GreaterOrEqual, LessOrEqual)
2//!
3//! Comparison operators perform element-wise comparisons between two input tensors and return
4//! boolean tensors indicating the result of the comparison at each position. These operations
5//! support broadcasting according to ONNX broadcasting rules.
6//!
7//! **ONNX Specs**:
8//! - Equal: <https://onnx.ai/onnx/operators/onnx__Equal.html>
9//! - Greater: <https://onnx.ai/onnx/operators/onnx__Greater.html>
10//! - Less: <https://onnx.ai/onnx/operators/onnx__Less.html>
11//! - GreaterOrEqual: <https://onnx.ai/onnx/operators/onnx__GreaterOrEqual.html>
12//! - LessOrEqual: <https://onnx.ai/onnx/operators/onnx__LessOrEqual.html>
13//!
14//! ## Opset Versions
15//!
16//! - **Equal**:
17//!   - Opset 7-10: Initial version with basic type support
18//!   - Opset 11-12: Extended type support for additional numeric types
19//!   - Opset 13-18: Added bfloat16 support
20//!   - Opset 19+: Added int4 and uint4 support
21//!
22//! - **Greater**:
23//!   - Opset 7-8: Initial version with basic type support
24//!   - Opset 9-12: Extended type support for additional numeric types
25//!   - Opset 13+: Added bfloat16 support
26//!
27//! - **Less**:
28//!   - Opset 7-8: Initial version with basic type support
29//!   - Opset 9-12: Extended type support for additional numeric types
30//!   - Opset 13+: Added bfloat16 support
31//!
32//! - **GreaterOrEqual**:
33//!   - Opset 12-15: Initial version
34//!   - Opset 16+: Added bfloat16 support
35//!
36//! - **LessOrEqual**:
37//!   - Opset 12-15: Initial version
38//!   - Opset 16+: Added bfloat16 support
39//!
40//! ## Implementation Notes
41//!
42//! - All comparison operations output boolean tensors (element type: bool)
43//! - The output rank is determined by the maximum rank of the input tensors
44//! - When both inputs are scalars, the output is a scalar boolean
45//! - Special handling for Shape-to-Shape comparisons where the output is also a Shape type
46
47use onnx_ir_derive::NodeBuilder;
48
49use crate::ir::{Argument, BoolStore, DType, Node, RawNode};
50use crate::processor::{
51    ArgPreference, InputPreferences, InputSpec, NodeProcessor, NodeSpec, OutputPreferences,
52    OutputSpec, ProcessError,
53};
54
55/// Node representation for Equal operation
56#[derive(Debug, Clone, NodeBuilder)]
57pub struct EqualNode {
58    pub name: String,
59    pub inputs: Vec<Argument>,
60    pub outputs: Vec<Argument>,
61}
62
63/// Node representation for Greater operation
64#[derive(Debug, Clone, NodeBuilder)]
65pub struct GreaterNode {
66    pub name: String,
67    pub inputs: Vec<Argument>,
68    pub outputs: Vec<Argument>,
69}
70
71/// Node representation for GreaterOrEqual operation
72#[derive(Debug, Clone, NodeBuilder)]
73pub struct GreaterOrEqualNode {
74    pub name: String,
75    pub inputs: Vec<Argument>,
76    pub outputs: Vec<Argument>,
77}
78
79/// Node representation for Less operation
80#[derive(Debug, Clone, NodeBuilder)]
81pub struct LessNode {
82    pub name: String,
83    pub inputs: Vec<Argument>,
84    pub outputs: Vec<Argument>,
85}
86
87/// Node representation for LessOrEqual operation
88#[derive(Debug, Clone, NodeBuilder)]
89pub struct LessOrEqualNode {
90    pub name: String,
91    pub inputs: Vec<Argument>,
92    pub outputs: Vec<Argument>,
93}
94
95/// Update output type for comparison operations (e.g., Equal, Greater) to max input rank.
96pub(crate) fn elementwise_comparison_outputs(node: &mut RawNode) {
97    node.outputs[0].ty =
98        crate::processor::broadcast_output_type(&node.inputs, Some(DType::Bool(BoolStore::Native)));
99}
100
101pub(crate) struct ComparisonProcessor;
102
103impl NodeProcessor for ComparisonProcessor {
104    type Config = ();
105
106    fn spec(&self) -> NodeSpec {
107        NodeSpec {
108            min_opset: 1,
109            max_opset: None,
110            inputs: InputSpec::Exact(2),
111            outputs: OutputSpec::Exact(1),
112        }
113    }
114
115    fn input_preferences(
116        &self,
117        node: &RawNode,
118        _opset: usize,
119    ) -> Result<Option<InputPreferences>, ProcessError> {
120        if node.inputs.len() != 2 {
121            return Ok(None);
122        }
123
124        let mut prefs = InputPreferences::new();
125
126        // When one input is on_device and the other is a scalar, prefer ScalarNative.
127        // This uses the more efficient `_elem` comparison methods and avoids dtype
128        // mismatch between ScalarTensor constants (loaded with ONNX dtype) and tensors
129        // produced by runtime casts (which use the backend's default element type).
130        if node.inputs[0].ty.is_on_device() && node.inputs[1].ty.is_scalar() {
131            prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
132        }
133        if node.inputs[1].ty.is_on_device() && node.inputs[0].ty.is_scalar() {
134            prefs = prefs.add(&node.inputs[0].name, ArgPreference::ScalarNative);
135        }
136
137        // When one input is ScalarNative and the other is also a scalar, prefer
138        // the other as ScalarNative too (avoids promoting to ScalarTensor).
139        if node.inputs[0].ty.is_scalar_native() && node.inputs[1].ty.is_scalar() {
140            prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
141        }
142        if node.inputs[1].ty.is_scalar_native() && node.inputs[0].ty.is_scalar() {
143            prefs = prefs.add(&node.inputs[0].name, ArgPreference::ScalarNative);
144        }
145
146        Ok(Some(prefs))
147    }
148
149    fn infer_types(
150        &self,
151        node: &mut RawNode,
152        opset: usize,
153        _output_preferences: &OutputPreferences,
154    ) -> Result<(), ProcessError> {
155        // Validate opset based on operation type (individual validation for specific ops)
156        let min_opset = match node.node_type {
157            crate::ir::NodeType::Equal => 1,
158            crate::ir::NodeType::Greater | crate::ir::NodeType::Less => 1,
159            crate::ir::NodeType::GreaterOrEqual | crate::ir::NodeType::LessOrEqual => 12,
160            _ => unreachable!(
161                "ComparisonProcessor should only be called for comparison operations, got: {:?}",
162                node.node_type
163            ),
164        };
165
166        if opset < min_opset {
167            return Err(ProcessError::UnsupportedOpset {
168                required: min_opset,
169                actual: opset,
170            });
171        }
172
173        node.outputs[0].ty = crate::processor::broadcast_output_type(
174            &node.inputs,
175            Some(DType::Bool(BoolStore::Native)),
176        );
177
178        Ok(())
179    }
180
181    fn build_node(&self, builder: RawNode, _opset: usize) -> Result<Node, ProcessError> {
182        Ok(match builder.node_type {
183            crate::ir::NodeType::Equal => Node::Equal(EqualNode {
184                name: builder.name,
185                inputs: builder.inputs,
186                outputs: builder.outputs,
187            }),
188            crate::ir::NodeType::Greater => Node::Greater(GreaterNode {
189                name: builder.name,
190                inputs: builder.inputs,
191                outputs: builder.outputs,
192            }),
193            crate::ir::NodeType::GreaterOrEqual => Node::GreaterOrEqual(GreaterOrEqualNode {
194                name: builder.name,
195                inputs: builder.inputs,
196                outputs: builder.outputs,
197            }),
198            crate::ir::NodeType::Less => Node::Less(LessNode {
199                name: builder.name,
200                inputs: builder.inputs,
201                outputs: builder.outputs,
202            }),
203            crate::ir::NodeType::LessOrEqual => Node::LessOrEqual(LessOrEqualNode {
204                name: builder.name,
205                inputs: builder.inputs,
206                outputs: builder.outputs,
207            }),
208            other => {
209                return Err(ProcessError::Custom(format!(
210                    "ComparisonProcessor called with unsupported node type {other:?}"
211                )));
212            }
213        })
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use crate::ir::{ArgType, NodeType};
221    use crate::node::test_utils::TestNodeBuilder;
222
223    fn create_test_node(input1_rank: usize, input2_rank: usize) -> RawNode {
224        TestNodeBuilder::new(NodeType::Equal, "test_comparison")
225            .input_tensor_f32("A", input1_rank, None)
226            .input_tensor_f32("B", input2_rank, None)
227            .output_tensor_bool("result", 0, None) // rank will be updated
228            .build()
229    }
230
231    #[test]
232    fn test_comparison_rank_broadcasting() {
233        let mut node = create_test_node(2, 3);
234
235        let processor = ComparisonProcessor;
236        let prefs = OutputPreferences::new();
237        processor.infer_types(&mut node, 16, &prefs).unwrap();
238
239        match &node.outputs[0].ty {
240            ArgType::Tensor(tensor) => {
241                assert_eq!(tensor.dtype, DType::Bool(BoolStore::Native));
242                assert_eq!(tensor.rank, 3); // max(2, 3) = 3
243            }
244            _ => panic!("Expected tensor output"),
245        }
246    }
247
248    #[test]
249    fn test_comparison_scalar_result() {
250        let mut node = create_test_node(0, 0);
251
252        // Convert inputs to scalars
253        node.inputs[0].ty = ArgType::ScalarNative(DType::F32);
254        node.inputs[1].ty = ArgType::ScalarNative(DType::F32);
255
256        let processor = ComparisonProcessor;
257        let prefs = OutputPreferences::new();
258        processor.infer_types(&mut node, 16, &prefs).unwrap();
259
260        match &node.outputs[0].ty {
261            ArgType::ScalarNative(elem_type) => {
262                assert_eq!(*elem_type, DType::Bool(BoolStore::Native));
263            }
264            _ => panic!("Expected scalar output"),
265        }
266    }
267
268    #[test]
269    fn test_comparison_with_shape_and_tensor() {
270        let mut node = create_test_node(2, 2);
271        node.inputs[0].ty = ArgType::Shape(3);
272        // node.inputs[1] remains as Tensor with rank 2
273
274        let processor = ComparisonProcessor;
275        let prefs = OutputPreferences::new();
276        processor.infer_types(&mut node, 16, &prefs).unwrap();
277
278        match &node.outputs[0].ty {
279            ArgType::Tensor(tensor) => {
280                assert_eq!(tensor.dtype, DType::Bool(BoolStore::Native));
281                assert_eq!(tensor.rank, 2); // max(1, 2) = 2 (Shape is rank 1, Tensor is rank 2)
282            }
283            _ => panic!("Expected tensor output"),
284        }
285    }
286
287    #[test]
288    fn test_comparison_both_shape_inputs() {
289        let mut node = create_test_node(0, 0);
290        node.inputs[0].ty = ArgType::Shape(3);
291        node.inputs[1].ty = ArgType::Shape(3);
292
293        let processor = ComparisonProcessor;
294        let prefs = OutputPreferences::new();
295        processor.infer_types(&mut node, 16, &prefs).unwrap();
296
297        match &node.outputs[0].ty {
298            ArgType::Shape(dim) => {
299                assert_eq!(*dim, 3); // Shape output with same dimension
300            }
301            _ => panic!("Expected shape output"),
302        }
303    }
304
305    #[test]
306    fn test_equal_opset_7() {
307        let mut node = TestNodeBuilder::new(NodeType::Equal, "test_equal")
308            .input_tensor_f32("A", 2, None)
309            .input_tensor_f32("B", 2, None)
310            .output_tensor_bool("result", 0, None)
311            .build();
312
313        let processor = ComparisonProcessor;
314        let prefs = OutputPreferences::new();
315
316        // Should work with opset 7
317        assert!(processor.infer_types(&mut node, 7, &prefs).is_ok());
318
319        // Should also work with opset 1
320        let mut node = TestNodeBuilder::new(NodeType::Equal, "test_equal")
321            .input_tensor_f32("A", 2, None)
322            .input_tensor_f32("B", 2, None)
323            .output_tensor_bool("result", 0, None)
324            .build();
325        assert!(processor.infer_types(&mut node, 1, &prefs).is_ok());
326    }
327
328    #[test]
329    fn test_greater_less_opset_7() {
330        let processor = ComparisonProcessor;
331        let prefs = OutputPreferences::new();
332
333        // Test Greater with opset 7
334        let mut node = TestNodeBuilder::new(NodeType::Greater, "test_greater")
335            .input_tensor_f32("A", 2, None)
336            .input_tensor_f32("B", 2, None)
337            .output_tensor_bool("result", 0, None)
338            .build();
339        assert!(processor.infer_types(&mut node, 7, &prefs).is_ok());
340
341        // Test Less with opset 7
342        let mut node = TestNodeBuilder::new(NodeType::Less, "test_less")
343            .input_tensor_f32("A", 2, None)
344            .input_tensor_f32("B", 2, None)
345            .output_tensor_bool("result", 0, None)
346            .build();
347        assert!(processor.infer_types(&mut node, 7, &prefs).is_ok());
348
349        // Should also work with opset 1
350        let mut node = TestNodeBuilder::new(NodeType::Greater, "test_greater")
351            .input_tensor_f32("A", 2, None)
352            .input_tensor_f32("B", 2, None)
353            .output_tensor_bool("result", 0, None)
354            .build();
355        assert!(processor.infer_types(&mut node, 1, &prefs).is_ok());
356    }
357
358    #[test]
359    fn test_input_preferences_tensor_and_scalar_tensor() {
360        let mut node = create_test_node(2, 2);
361        // Make the second input a ScalarTensor (on-device scalar)
362        node.inputs[1].ty = ArgType::ScalarTensor(DType::F32);
363
364        let processor = ComparisonProcessor;
365        let prefs = processor.input_preferences(&node, 16).unwrap().unwrap();
366
367        // Tensor + ScalarTensor: scalar should get ScalarNative preference
368        let b_prefs = prefs.get("B");
369        assert_eq!(b_prefs.len(), 1);
370        assert!(matches!(b_prefs[0], ArgPreference::ScalarNative));
371
372        // Tensor input should not get any preference
373        let a_prefs = prefs.get("A");
374        assert!(a_prefs.is_empty());
375    }
376
377    #[test]
378    fn test_input_preferences_two_tensors() {
379        let node = create_test_node(2, 2);
380
381        let processor = ComparisonProcessor;
382        let prefs = processor.input_preferences(&node, 16).unwrap().unwrap();
383
384        // Two tensors: no preferences should be set
385        assert!(prefs.get("A").is_empty());
386        assert!(prefs.get("B").is_empty());
387    }
388
389    #[test]
390    fn test_input_preferences_scalar_native_and_scalar_tensor() {
391        let mut node = create_test_node(2, 2);
392        node.inputs[0].ty = ArgType::ScalarNative(DType::F32);
393        node.inputs[1].ty = ArgType::ScalarTensor(DType::F32);
394
395        let processor = ComparisonProcessor;
396        let prefs = processor.input_preferences(&node, 16).unwrap().unwrap();
397
398        // ScalarNative + ScalarTensor: the ScalarTensor should get ScalarNative preference
399        let b_prefs = prefs.get("B");
400        assert!(
401            b_prefs
402                .iter()
403                .any(|p| matches!(p, ArgPreference::ScalarNative))
404        );
405    }
406
407    #[test]
408    fn test_greater_or_equal_less_or_equal_opset_12() {
409        let processor = ComparisonProcessor;
410        let prefs = OutputPreferences::new();
411
412        // Test GreaterOrEqual with opset 12
413        let mut node = TestNodeBuilder::new(NodeType::GreaterOrEqual, "test_gte")
414            .input_tensor_f32("A", 2, None)
415            .input_tensor_f32("B", 2, None)
416            .output_tensor_bool("result", 0, None)
417            .build();
418        assert!(processor.infer_types(&mut node, 12, &prefs).is_ok());
419
420        // Test LessOrEqual with opset 12
421        let mut node = TestNodeBuilder::new(NodeType::LessOrEqual, "test_lte")
422            .input_tensor_f32("A", 2, None)
423            .input_tensor_f32("B", 2, None)
424            .output_tensor_bool("result", 0, None)
425            .build();
426        assert!(processor.infer_types(&mut node, 12, &prefs).is_ok());
427
428        // Should fail with opset 11
429        let mut node = TestNodeBuilder::new(NodeType::GreaterOrEqual, "test_gte")
430            .input_tensor_f32("A", 2, None)
431            .input_tensor_f32("B", 2, None)
432            .output_tensor_bool("result", 0, None)
433            .build();
434        assert!(processor.infer_types(&mut node, 11, &prefs).is_err());
435    }
436}