Skip to main content

onnx_ir/node/
modulo.rs

1//! # Mod
2//!
3//! Element-wise binary modulus operation with Numpy-style broadcasting support.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__Mod.html>
6//!
7//! ## Opset Versions
8//! - **Opset 10-12**: Initial implementation with fmod attribute
9//! - **Opset 13+**: Extended type support (added bfloat16)
10//!
11//! ## Missing Test Coverage
12//! - TODO: No test for fmod values other than 0 or 1 - Spec only defines 0 and 1, other values should be rejected
13//! - TODO: No test for dtype validation - Should ensure both inputs have compatible numeric types
14//! - TODO: No test for zero divisor - Division by zero handling not tested
15//! - TODO: No test for negative divisors with both fmod modes - Sign handling edge cases
16//! - TODO: No test for integer types - Spec supports int8, int16, int32, int64, uint8, uint16, uint32, uint64
17//! - TODO: No test for mixed sign operands - fmod=0 vs fmod=1 produces different results
18
19use onnx_ir_derive::NodeBuilder;
20
21use crate::ir::{ArgType, Argument, AttributeValue, Node, RawNode};
22use crate::processor::{
23    InputPreferences, InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec,
24    ProcessError,
25};
26
27/// Configuration for Mod operations
28#[derive(Debug, Clone)]
29pub struct ModConfig {
30    /// Determines the modulo operation behavior:
31    /// false (default): Integer modulo - sign follows divisor (Python-style %)
32    /// true: Floating-point modulo (C-style fmod) - sign follows dividend
33    pub fmod: bool,
34}
35
36/// Node representation for Mod operation
37#[derive(Debug, Clone, NodeBuilder)]
38pub struct ModNode {
39    pub name: String,
40    pub inputs: Vec<Argument>,
41    pub outputs: Vec<Argument>,
42    pub config: ModConfig,
43}
44
45impl ModConfig {
46    /// Create a new ModConfig
47    pub fn new(fmod: bool) -> Self {
48        Self { fmod }
49    }
50}
51
52pub(crate) struct ModuloProcessor;
53
54impl NodeProcessor for ModuloProcessor {
55    type Config = ModConfig;
56
57    fn spec(&self) -> NodeSpec {
58        NodeSpec {
59            min_opset: 10,
60            max_opset: None,
61            inputs: InputSpec::Exact(2),
62            outputs: OutputSpec::Exact(1),
63        }
64    }
65
66    fn input_preferences(
67        &self,
68        node: &RawNode,
69        _opset: usize,
70    ) -> Result<Option<InputPreferences>, ProcessError> {
71        use crate::processor::ArgPreference;
72
73        if node.inputs.len() != 2 {
74            return Ok(None);
75        }
76
77        let mut prefs = InputPreferences::new();
78
79        // Type propagation for Shape arithmetic (same as Add/Sub/Mul/Div)
80        // Case 1: Shape op Constant => prefer Constant as Shape (or ScalarNative for scalars)
81        if node.inputs[0].ty.is_shape() {
82            if node.inputs[1].ty.is_scalar() {
83                prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
84            } else {
85                prefs = prefs.add(&node.inputs[1].name, ArgPreference::Shape);
86            }
87        }
88
89        // Case 2: Constant op Shape => prefer Constant as Shape (or ScalarNative for scalars)
90        if node.inputs[1].ty.is_shape() {
91            if node.inputs[0].ty.is_scalar() {
92                prefs = prefs.add(&node.inputs[0].name, ArgPreference::ScalarNative);
93            } else {
94                prefs = prefs.add(&node.inputs[0].name, ArgPreference::Shape);
95            }
96        }
97
98        // Type propagation for ScalarNative arithmetic
99        if node.inputs[0].ty.is_scalar_native() {
100            prefs = prefs.add(&node.inputs[1].name, ArgPreference::ScalarNative);
101        }
102
103        if node.inputs[1].ty.is_scalar_native() {
104            prefs = prefs.add(&node.inputs[0].name, ArgPreference::ScalarNative);
105        }
106
107        Ok(Some(prefs))
108    }
109
110    fn infer_types(
111        &self,
112        node: &mut RawNode,
113        _opset: usize,
114        _output_preferences: &OutputPreferences,
115    ) -> Result<(), ProcessError> {
116        // TODO: Validate input dtypes are numeric - Integer and floating-point types supported - burn/crates/onnx-ir/src/node/modulo.rs:100
117        // TODO: Validate both inputs have same dtype - Mixed types should be rejected - burn/crates/onnx-ir/src/node/modulo.rs:100
118        // TODO: Add validation that fmod attribute, if present, is either 0 or 1 - Other values are undefined - burn/crates/onnx-ir/src/node/modulo.rs:100
119
120        // Structural validation for Shape combined with an on-device tensor.
121        // burn-onnx codegen for these arms always materializes the Shape as
122        // a rank-1 Int tensor, so it can only handle a rank-1 integer
123        // counterpart. Reject mismatches here (rather than panicking deep
124        // inside codegen or producing silently wrong code) so users see a
125        // clean ProcessError.
126        let lhs_ty = &node.inputs[0].ty;
127        let rhs_ty = &node.inputs[1].ty;
128        if let (ArgType::Shape(_), other) | (other, ArgType::Shape(_)) = (lhs_ty, rhs_ty)
129            && other.is_on_device()
130        {
131            let other_dtype = other.elem_type();
132            if !(other_dtype.is_int() || other_dtype.is_uint()) {
133                return Err(ProcessError::TypeMismatch {
134                    expected: "integer-typed tensor when combined with Shape".to_string(),
135                    actual: format!("{other_dtype:?}"),
136                });
137            }
138            if other.rank() != 1 {
139                return Err(ProcessError::Custom(format!(
140                    "Mod: Shape combined with rank-{} {other_dtype:?} tensor is not supported (expected rank 1)",
141                    other.rank()
142                )));
143            }
144        }
145
146        // Output type is same as input with broadcasting
147        crate::processor::same_as_input_broadcast(node);
148
149        Ok(())
150    }
151
152    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
153        // Extract fmod attribute
154        let fmod = match node.attrs.get("fmod") {
155            Some(AttributeValue::Int64(value)) => {
156                // TODO: Validate fmod is 0 or 1 - Values other than 0 or 1 are undefined in spec - burn/crates/onnx-ir/src/node/modulo.rs:120
157                *value != 0
158            }
159            _ => false, // Default value as per ONNX spec
160        };
161
162        let config = ModConfig::new(fmod);
163        Ok(config)
164    }
165
166    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
167        let config = self.extract_config(&builder, opset)?;
168
169        Ok(Node::Mod(ModNode {
170            name: builder.name,
171            inputs: builder.inputs,
172            outputs: builder.outputs,
173            config,
174        }))
175    }
176}
177
178#[cfg(test)]
179#[allow(clippy::bool_assert_comparison)]
180mod tests {
181    use super::*;
182    use crate::ir::{AttributeValue, NodeType};
183    use crate::node::test_utils::TestNodeBuilder;
184
185    fn create_test_node() -> crate::ir::RawNode {
186        TestNodeBuilder::new(NodeType::Mod, "test_mod")
187            .input_tensor_f32("A", 2, None)
188            .input_tensor_f32("B", 2, None)
189            .output_tensor_f32("result", 2, None)
190            .build()
191    }
192
193    #[test]
194    fn test_mod_config_default() {
195        let node = create_test_node();
196        let mut node = node;
197        let processor = ModuloProcessor;
198        let prefs = OutputPreferences::new();
199        let config = processor.extract_config(&node, 16).unwrap();
200        processor.infer_types(&mut node, 16, &prefs).unwrap();
201        assert_eq!(config.fmod, false); // Should default to false
202    }
203
204    #[test]
205    fn test_mod_config_with_fmod_0() {
206        let mut node = create_test_node();
207        node.attrs
208            .insert("fmod".to_string(), AttributeValue::Int64(0));
209        let mut node = node;
210        let processor = ModuloProcessor;
211        let prefs = OutputPreferences::new();
212        let config = processor.extract_config(&node, 16).unwrap();
213        processor.infer_types(&mut node, 16, &prefs).unwrap();
214        assert_eq!(config.fmod, false);
215    }
216
217    #[test]
218    fn test_mod_config_with_fmod_1() {
219        let mut node = create_test_node();
220        node.attrs
221            .insert("fmod".to_string(), AttributeValue::Int64(1));
222        let mut node = node;
223        let processor = ModuloProcessor;
224        let prefs = OutputPreferences::new();
225        let config = processor.extract_config(&node, 16).unwrap();
226        processor.infer_types(&mut node, 16, &prefs).unwrap();
227        assert_eq!(config.fmod, true);
228    }
229
230    /// Mod on Shape + float tensor must be rejected. The codegen arm
231    /// for this combination materializes the Shape as a rank-1 Int
232    /// tensor and calls `.remainder()` / `.fmod()` on it, so the
233    /// counterpart must be integer-typed.
234    #[test]
235    fn shape_mod_float_tensor_rejected() {
236        let mut node = TestNodeBuilder::new(NodeType::Mod, "mod_shape_float")
237            .input_shape("lhs", 3)
238            .input_tensor_f32("rhs", 1, None)
239            .output_tensor_f32("out", 1, None)
240            .build();
241
242        let processor = ModuloProcessor;
243        let prefs = OutputPreferences::new();
244        let result = processor.infer_types(&mut node, 16, &prefs);
245        assert!(
246            matches!(result, Err(ProcessError::TypeMismatch { .. })),
247            "expected TypeMismatch, got {result:?}"
248        );
249    }
250
251    /// Mod on Shape + rank-2 int tensor must be rejected. Codegen
252    /// assumes the counterpart is rank 1.
253    #[test]
254    fn shape_mod_rank2_int_tensor_rejected() {
255        let mut node = TestNodeBuilder::new(NodeType::Mod, "mod_shape_rank2")
256            .input_shape("lhs", 3)
257            .input_tensor_i64("rhs", 2, None)
258            .output_tensor_i64("out", 2, None)
259            .build();
260
261        let processor = ModuloProcessor;
262        let prefs = OutputPreferences::new();
263        let result = processor.infer_types(&mut node, 16, &prefs);
264        match result {
265            Err(ProcessError::Custom(msg)) => assert!(
266                msg.contains("rank-2") && msg.contains("Mod"),
267                "expected rank-2 message, got: {msg}"
268            ),
269            other => panic!("expected Custom ProcessError, got {other:?}"),
270        }
271    }
272
273    /// Mod on Shape + rank-1 int tensor is the legitimate case and
274    /// must be accepted.
275    #[test]
276    fn shape_mod_rank1_int_tensor_accepted() {
277        let mut node = TestNodeBuilder::new(NodeType::Mod, "mod_shape_rank1")
278            .input_shape("lhs", 3)
279            .input_tensor_i64("rhs", 1, None)
280            .output_tensor_i64("out", 1, None)
281            .build();
282
283        let processor = ModuloProcessor;
284        let prefs = OutputPreferences::new();
285        let result = processor.infer_types(&mut node, 16, &prefs);
286        assert!(result.is_ok(), "expected Ok, got {result:?}");
287    }
288}