1use onnx_ir_derive::NodeBuilder;
2
3use crate::ir::{ArgType, Argument, AttributeValue, DType, Node, RawNode, TensorType};
4use crate::processor::{
5 InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
6};
7use crate::proto_conversion::element_type_from_proto;
8
9#[derive(Debug, Clone, Default)]
10pub struct QuantizeLinearConfig {
11 pub axis: Option<i64>,
12 pub block_size: Option<i64>,
13 pub output_dtype: Option<DType>,
14 pub precision: Option<DType>,
15 pub saturate: Option<i64>,
16}
17
18#[derive(Debug, Clone, NodeBuilder)]
19pub struct QuantizeLinearNode {
20 pub name: String,
21 pub inputs: Vec<Argument>,
22 pub outputs: Vec<Argument>,
23 pub config: QuantizeLinearConfig,
24}
25
26pub(crate) struct QuantizeLinearProcessor;
27
28impl NodeProcessor for QuantizeLinearProcessor {
29 type Config = QuantizeLinearConfig;
30
31 fn spec(&self) -> NodeSpec {
32 NodeSpec {
33 min_opset: 10,
34 max_opset: None,
35 inputs: InputSpec::Range(2, 3),
36 outputs: OutputSpec::Exact(1),
37 }
38 }
39
40 fn infer_types(
41 &self,
42 node: &mut RawNode,
43 opset: usize,
44 _output_preferences: &OutputPreferences,
45 ) -> Result<(), ProcessError> {
46 let config = self.extract_config(node, opset)?;
47
48 if config.saturate.is_some() && opset < 19 {
49 return Err(ProcessError::Custom(format!(
50 "QuantizeLinear: saturate requires opset 19+, got {opset}"
51 )));
52 }
53
54 if let Some(block_size) = config.block_size
55 && block_size > 0
56 {
57 return Err(ProcessError::Custom(format!(
58 "QuantizeLinear: blocked quantization (block_size={block_size}) is not supported yet"
59 )));
60 }
61
62 if !node.inputs[0].ty.is_on_device() {
63 return Err(ProcessError::TypeMismatch {
64 expected: "on-device tensor for x".to_string(),
65 actual: format!("{:?}", node.inputs[0].ty),
66 });
67 }
68
69 if !node.inputs[1].ty.is_on_device() {
70 return Err(ProcessError::TypeMismatch {
71 expected: "on-device tensor for y_scale".to_string(),
72 actual: format!("{:?}", node.inputs[1].ty),
73 });
74 }
75
76 let x_dtype = node.inputs[0].ty.elem_type();
77 if !(x_dtype.is_float() || x_dtype.is_int()) {
78 return Err(ProcessError::TypeMismatch {
79 expected: "float or int tensor for x".to_string(),
80 actual: format!("{:?}", x_dtype),
81 });
82 }
83
84 let scale_dtype = node.inputs[1].ty.elem_type();
85 if !(scale_dtype.is_float() || scale_dtype == DType::I32) {
86 return Err(ProcessError::TypeMismatch {
87 expected: "float or int32 tensor for y_scale".to_string(),
88 actual: format!("{:?}", scale_dtype),
89 });
90 }
91
92 let zero_dtype = node.get_input(2).map(|arg| arg.ty.elem_type());
93 let output_dtype = if let Some(dtype) = config.output_dtype {
94 if let Some(zero) = zero_dtype
95 && zero != dtype
96 {
97 return Err(ProcessError::TypeMismatch {
98 expected: format!("y_zero_point dtype {:?}", dtype),
99 actual: format!("{:?}", zero),
100 });
101 }
102 dtype
103 } else if let Some(zero) = zero_dtype {
104 zero
105 } else {
106 DType::U8
107 };
108
109 let supported = matches!(
110 output_dtype,
111 DType::U8 | DType::I8 | DType::U16 | DType::I16
112 );
113 if !supported {
114 return Err(ProcessError::Custom(format!(
115 "QuantizeLinear: output dtype {:?} is not supported yet",
116 output_dtype
117 )));
118 }
119
120 node.outputs[0].ty = match node.inputs[0].ty.clone() {
121 ArgType::Tensor(tensor) => ArgType::Tensor(TensorType {
122 dtype: output_dtype,
123 rank: tensor.rank,
124 static_shape: tensor.static_shape,
125 }),
126 ArgType::ScalarTensor(_) => ArgType::ScalarTensor(output_dtype),
127 other => {
128 return Err(ProcessError::TypeMismatch {
129 expected: "tensor/scalar tensor input".to_string(),
130 actual: format!("{:?}", other),
131 });
132 }
133 };
134
135 Ok(())
136 }
137
138 fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
139 let mut config = QuantizeLinearConfig::default();
140
141 for (key, value) in node.attrs.iter() {
142 match key.as_str() {
143 "axis" => {
144 config.axis = Some(value.clone().into_i64()?);
145 }
146 "block_size" => {
147 config.block_size = Some(value.clone().into_i64()?);
148 }
149 "output_dtype" => {
150 let dtype = match value {
151 AttributeValue::Int64(type_id) => element_type_from_proto(*type_id as i32)
152 .map_err(|_| ProcessError::InvalidAttribute {
153 name: "output_dtype".to_string(),
154 reason: format!("unsupported dtype: {type_id}"),
155 })?,
156 _ => {
157 return Err(ProcessError::InvalidAttribute {
158 name: "output_dtype".to_string(),
159 reason: "must be Int64".to_string(),
160 });
161 }
162 };
163 config.output_dtype = Some(dtype);
164 }
165 "precision" => {
166 let dtype = match value {
167 AttributeValue::Int64(type_id) => element_type_from_proto(*type_id as i32)
168 .map_err(|_| ProcessError::InvalidAttribute {
169 name: "precision".to_string(),
170 reason: format!("unsupported dtype: {type_id}"),
171 })?,
172 _ => {
173 return Err(ProcessError::InvalidAttribute {
174 name: "precision".to_string(),
175 reason: "must be Int64".to_string(),
176 });
177 }
178 };
179 config.precision = Some(dtype);
180 }
181 "saturate" => {
182 config.saturate = Some(value.clone().into_i64()?);
183 }
184 _ => {}
185 }
186 }
187
188 Ok(config)
189 }
190
191 fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
192 let config = self.extract_config(&builder, opset)?;
193
194 Ok(Node::QuantizeLinear(QuantizeLinearNode {
195 name: builder.name,
196 inputs: builder.inputs,
197 outputs: builder.outputs,
198 config,
199 }))
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206 use crate::ir::NodeType;
207 use crate::node::test_utils::TestNodeBuilder;
208 use crate::protos::tensor_proto::DataType;
209 use protobuf::Enum;
210
211 #[test]
212 fn test_quantize_linear_default_output_dtype() {
213 let mut node = TestNodeBuilder::new(NodeType::QuantizeLinear, "q")
214 .input_tensor_f32("x", 2, None)
215 .input_tensor_f32("y_scale", 0, None)
216 .output_tensor_f32("y", 2, None)
217 .build();
218
219 let processor = QuantizeLinearProcessor;
220 processor
221 .infer_types(&mut node, 16, &OutputPreferences::new())
222 .unwrap();
223
224 assert_eq!(node.outputs[0].ty.elem_type(), DType::U8);
225 }
226
227 #[test]
228 fn test_quantize_linear_uses_zero_point_dtype() {
229 let mut node = TestNodeBuilder::new(NodeType::QuantizeLinear, "q")
230 .input_tensor_f32("x", 2, None)
231 .input_tensor_f32("y_scale", 0, None)
232 .input_tensor_i32("y_zero_point", 0, None)
233 .output_tensor_f32("y", 2, None)
234 .build();
235
236 node.inputs[2].ty = ArgType::Tensor(TensorType::new(DType::I8, 0, None));
237
238 let processor = QuantizeLinearProcessor;
239 processor
240 .infer_types(&mut node, 16, &OutputPreferences::new())
241 .unwrap();
242
243 assert_eq!(node.outputs[0].ty.elem_type(), DType::I8);
244 }
245
246 #[test]
247 fn test_quantize_linear_output_dtype_must_match_zero_point() {
248 let mut node = TestNodeBuilder::new(NodeType::QuantizeLinear, "q")
249 .input_tensor_f32("x", 2, None)
250 .input_tensor_f32("y_scale", 0, None)
251 .input_tensor_i32("y_zero_point", 0, None)
252 .output_tensor_f32("y", 2, None)
253 .attr_int("output_dtype", DataType::UINT8.value() as i64)
254 .build();
255
256 node.inputs[2].ty = ArgType::Tensor(TensorType::new(DType::I8, 0, None));
257
258 let processor = QuantizeLinearProcessor;
259 let err = processor
260 .infer_types(&mut node, 16, &OutputPreferences::new())
261 .unwrap_err();
262
263 assert!(matches!(err, ProcessError::TypeMismatch { .. }));
264 }
265
266 #[test]
267 fn test_quantize_linear_rejects_blocked_quantization() {
268 let mut node = TestNodeBuilder::new(NodeType::QuantizeLinear, "q")
269 .input_tensor_f32("x", 2, None)
270 .input_tensor_f32("y_scale", 0, None)
271 .output_tensor_f32("y", 2, None)
272 .attr_int("block_size", 8)
273 .build();
274
275 let processor = QuantizeLinearProcessor;
276 let err = processor
277 .infer_types(&mut node, 21, &OutputPreferences::new())
278 .unwrap_err();
279
280 let err_msg = format!("{}", err);
281 assert!(err_msg.contains("blocked quantization"));
282 }
283}