Skip to main content

onnx_ir/node/
matmulinteger.rs

1//! # MatMulInteger
2//!
3//! Matrix multiplication for quantized integer tensors with zero-point support.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__MatMulInteger.html>
6//!
7//! ## Opset Versions
8//! - **Opset 10**: Initial version introducing quantized integer matrix multiplication with zero-point
9//!   support. Outputs int32 results from int8/uint8 inputs.
10//!
11//! **Implementation Note**: This implementation validates opset 10+. Accepts 2-4 inputs
12//! (A, B, optional a_zero_point, optional b_zero_point).
13
14use onnx_ir_derive::NodeBuilder;
15
16use crate::ir::{ArgType, Argument, DType, Node, RawNode, TensorType};
17use crate::processor::{NodeProcessor, OutputPreferences, ProcessError};
18
19use core::cmp::max;
20
21/// Node representation for MatMulInteger operation
22#[derive(Debug, Clone, NodeBuilder)]
23pub struct MatMulIntegerNode {
24    pub name: String,
25    pub inputs: Vec<Argument>,
26    pub outputs: Vec<Argument>,
27}
28
29pub(crate) struct MatMulIntegerProcessor;
30
31impl NodeProcessor for MatMulIntegerProcessor {
32    type Config = ();
33
34    fn infer_types(
35        &self,
36        node: &mut RawNode,
37        opset: usize,
38        _output_preferences: &OutputPreferences,
39    ) -> Result<(), ProcessError> {
40        // MatMulInteger implementation supports opset 10+
41        if opset < 10 {
42            return Err(ProcessError::UnsupportedOpset {
43                required: 10,
44                actual: opset,
45            });
46        }
47
48        // Validate input count: 2-4 inputs (A, B, optional a_zero_point, optional b_zero_point)
49        if node.inputs.len() < 2 || node.inputs.len() > 4 {
50            return Err(ProcessError::Custom(format!(
51                "MatMulInteger: expected 2-4 inputs, got {}",
52                node.inputs.len()
53            )));
54        }
55
56        // Validate output count
57        if node.outputs.len() != 1 {
58            return Err(ProcessError::InvalidOutputCount {
59                expected: 1,
60                actual: node.outputs.len(),
61            });
62        }
63
64        match (&node.inputs[0].ty, &node.inputs[1].ty) {
65            (ArgType::Tensor(a), ArgType::Tensor(b)) => {
66                let mut out_rank = max(a.rank, b.rank);
67
68                // Special cases: vector–matrix or matrix–vector reduces rank by 1
69                if (a.rank >= 2 && b.rank == 1) || (a.rank == 1 && b.rank >= 2) {
70                    out_rank -= 1;
71                }
72
73                // ONNX spec: MatMulInteger output is always int32
74                node.outputs[0].ty = ArgType::Tensor(TensorType {
75                    dtype: DType::I32,
76                    rank: out_rank,
77                    static_shape: None,
78                });
79
80                Ok(())
81            }
82            _ => Err(ProcessError::TypeMismatch {
83                expected: "Tensor".to_string(),
84                actual: "MatMulInteger expects tensor inputs".to_string(),
85            }),
86        }
87    }
88
89    fn build_node(&self, builder: RawNode, _opset: usize) -> Result<Node, ProcessError> {
90        Ok(Node::MatMulInteger(MatMulIntegerNode {
91            name: builder.name,
92            inputs: builder.inputs,
93            outputs: builder.outputs,
94        }))
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::ir::{DType, NodeType};
102    use crate::node::test_utils::TestNodeBuilder;
103
104    fn create_test_node(a_rank: usize, b_rank: usize) -> RawNode {
105        TestNodeBuilder::new(NodeType::MatMulInteger, "test_matmulinteger")
106            .input_tensor_i32("A", a_rank, None)
107            .input_tensor_i32("B", b_rank, None)
108            .output_tensor_i32("Y", 0, None) // rank will be updated
109            .build()
110    }
111
112    #[test]
113    fn test_update_outputs_standard_case() {
114        let mut node = create_test_node(2, 2);
115        let processor = MatMulIntegerProcessor;
116        let prefs = OutputPreferences::new();
117        processor.infer_types(&mut node, 16, &prefs).unwrap();
118
119        match &node.outputs[0].ty {
120            ArgType::Tensor(tensor) => {
121                assert_eq!(tensor.dtype, DType::I32);
122                assert_eq!(tensor.rank, 2);
123            }
124            _ => panic!("Expected tensor output"),
125        }
126    }
127
128    #[test]
129    fn test_update_outputs_vector_matrix() {
130        let mut node = create_test_node(1, 2);
131        let processor = MatMulIntegerProcessor;
132        let prefs = OutputPreferences::new();
133        processor.infer_types(&mut node, 16, &prefs).unwrap();
134
135        match &node.outputs[0].ty {
136            ArgType::Tensor(tensor) => {
137                assert_eq!(tensor.dtype, DType::I32);
138                assert_eq!(tensor.rank, 1);
139            }
140            _ => panic!("Expected tensor output"),
141        }
142    }
143
144    #[test]
145    fn test_too_many_inputs_rejected() {
146        let mut node = create_test_node(2, 2);
147        // Add 3 extra inputs (a_zero_point, b_zero_point, and one too many)
148        node.inputs.push(
149            TestNodeBuilder::new(NodeType::Identity, "tmp")
150                .input_tensor_i32("a_zp", 1, None)
151                .build()
152                .inputs
153                .pop()
154                .unwrap(),
155        );
156        node.inputs.push(
157            TestNodeBuilder::new(NodeType::Identity, "tmp")
158                .input_tensor_i32("b_zp", 1, None)
159                .build()
160                .inputs
161                .pop()
162                .unwrap(),
163        );
164        node.inputs.push(
165            TestNodeBuilder::new(NodeType::Identity, "tmp")
166                .input_tensor_i32("extra", 1, None)
167                .build()
168                .inputs
169                .pop()
170                .unwrap(),
171        );
172        let processor = MatMulIntegerProcessor;
173        let prefs = OutputPreferences::new();
174        let result = processor.infer_types(&mut node, 16, &prefs);
175        assert!(matches!(result, Err(ProcessError::Custom(ref msg)) if msg.contains("2-4 inputs")));
176    }
177
178    #[test]
179    fn test_invalid_input() {
180        let mut node = create_test_node(2, 2);
181        node.inputs[0].ty = ArgType::ScalarNative(DType::I32);
182        let processor = MatMulIntegerProcessor;
183        let prefs = OutputPreferences::new();
184        let result = processor.infer_types(&mut node, 16, &prefs);
185        assert!(matches!(result, Err(ProcessError::TypeMismatch { .. })));
186    }
187}