1use derive_new::new;
19use onnx_ir_derive::NodeBuilder;
20
21use crate::ir::{ArgType, Argument, AttributeValue, DType, Node, RawNode, TensorType};
22use crate::processor::{
23 InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
24};
25
26#[derive(Debug, Clone, Default, new)]
28pub struct OneHotEncoderConfig {
29 pub cats_int64s: Option<Vec<i64>>,
31 pub cats_strings: Option<Vec<String>>,
33 pub zeros: Option<i64>,
36}
37
38#[derive(Debug, Clone, new, NodeBuilder)]
40pub struct OneHotEncoderNode {
41 pub name: String,
42 pub inputs: Vec<Argument>,
43 pub outputs: Vec<Argument>,
44 pub config: OneHotEncoderConfig,
45}
46
47pub(crate) struct OneHotEncoderProcessor;
48
49impl NodeProcessor for OneHotEncoderProcessor {
50 type Config = OneHotEncoderConfig;
51
52 fn spec(&self) -> NodeSpec {
53 NodeSpec {
54 min_opset: 1,
55 max_opset: None,
56 inputs: InputSpec::Exact(1),
57 outputs: OutputSpec::Exact(1),
58 }
59 }
60
61 fn infer_types(
62 &self,
63 node: &mut RawNode,
64 opset: usize,
65 _output_preferences: &OutputPreferences,
66 ) -> Result<(), ProcessError> {
67 let config = self.extract_config(node, opset)?;
68
69 let (input_rank, num_categories) = match &node.inputs[0].ty {
72 ArgType::Tensor(t) => {
73 match t.dtype {
74 DType::F32 | DType::F64 | DType::I32 | DType::I64 => {}
75 other => {
76 return Err(ProcessError::TypeMismatch {
77 expected: "tensor(float | double | int32 | int64)".to_string(),
78 actual: format!("tensor({other:?})"),
79 });
80 }
81 }
82
83 let num_cats = self.get_num_categories(&config);
85
86 (t.rank, num_cats)
87 }
88 other => {
89 return Err(ProcessError::TypeMismatch {
90 expected: "tensor(float | double | int32 | int64)".to_string(),
91 actual: format!("{other:?}"),
92 });
93 }
94 };
95
96 let output_rank = input_rank + 1;
97
98 let static_shape = match &node.inputs[0].ty {
100 ArgType::Tensor(t) => {
101 if let Some(input_shape) = &t.static_shape {
102 let mut shape = input_shape.clone();
103 shape.push(Some(num_categories));
104 Some(shape)
105 } else {
106 let mut shape: Vec<Option<usize>> = vec![None; input_rank];
108 shape.push(Some(num_categories));
109 Some(shape)
110 }
111 }
112 _ => None,
113 };
114
115 node.outputs[0].ty = ArgType::Tensor(TensorType {
116 dtype: DType::F32,
117 rank: output_rank,
118 static_shape,
119 });
120
121 Ok(())
122 }
123
124 fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
125 let mut cats_int64s: Option<Vec<i64>> = None;
126 let mut cats_strings: Option<Vec<String>> = None;
127 let mut zeros: Option<i64> = None;
128
129 for (key, value) in node.attrs.iter() {
130 match key.as_str() {
131 "cats_int64s" => {
132 if let AttributeValue::Int64s(ints) = value {
133 cats_int64s = Some(ints.clone());
134 } else {
135 return Err(ProcessError::InvalidAttribute {
136 name: "cats_int64s".to_string(),
137 reason: format!("expected Int64s, got {value:?}"),
138 });
139 }
140 }
141 "cats_strings" => {
142 if let AttributeValue::Strings(strings) = value {
143 cats_strings = Some(strings.clone());
144 } else {
145 return Err(ProcessError::InvalidAttribute {
146 name: "cats_strings".to_string(),
147 reason: format!("expected Strings, got {value:?}"),
148 });
149 }
150 }
151 "zeros" => {
152 if let AttributeValue::Int64(i) = value {
153 zeros = Some(*i);
154 } else {
155 return Err(ProcessError::InvalidAttribute {
156 name: "zeros".to_string(),
157 reason: format!("expected Int64, got {value:?}"),
158 });
159 }
160 }
161 _ => {}
162 }
163 }
164
165 let config = OneHotEncoderConfig::new(cats_int64s, cats_strings, zeros);
166 self.validate_config(&config)?;
167
168 Ok(config)
169 }
170
171 fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
172 let config = self.extract_config(&builder, opset)?;
173 Ok(Node::OneHotEncoder(OneHotEncoderNode::new(
174 builder.name,
175 builder.inputs,
176 builder.outputs,
177 config,
178 )))
179 }
180}
181
182impl OneHotEncoderProcessor {
183 fn validate_config(&self, config: &OneHotEncoderConfig) -> Result<(), ProcessError> {
184 let has_ints = config.cats_int64s.is_some();
185 let has_strings = config.cats_strings.is_some();
186
187 if has_ints == has_strings {
188 return Err(ProcessError::InvalidAttribute {
189 name: "cats_int64s/cats_strings".to_string(),
190 reason: "exactly one of cats_int64s or cats_strings must be provided".to_string(),
191 });
192 }
193
194 if has_strings {
195 return Err(ProcessError::Custom(
196 "OneHotEncoder with cats_strings is not supported in burn-onnx; \
197 only numeric categories (cats_int64s) are supported"
198 .to_string(),
199 ));
200 }
201
202 if let Some(ints) = &config.cats_int64s
203 && ints.is_empty()
204 {
205 return Err(ProcessError::InvalidAttribute {
206 name: "cats_int64s".to_string(),
207 reason: "must not be empty".to_string(),
208 });
209 }
210
211 let zeros = config.zeros.unwrap_or(1);
212 if zeros != 1 {
213 return Err(ProcessError::Custom(
214 "OneHotEncoder zeros=0 is not supported in burn-onnx because unknown \
215 categories must raise at runtime"
216 .to_string(),
217 ));
218 }
219
220 Ok(())
221 }
222
223 fn get_num_categories(&self, config: &OneHotEncoderConfig) -> usize {
225 config
228 .cats_int64s
229 .as_ref()
230 .expect("OneHotEncoder config must contain cats_int64s")
231 .len()
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238 use crate::ir::NodeType;
239 use crate::node::test_utils::TestNodeBuilder;
240 use crate::processor::OutputPreferences;
241
242 fn make_node_builder(
243 input_dtype: DType,
244 input_rank: usize,
245 input_static_shape: Option<Vec<usize>>,
246 ) -> TestNodeBuilder {
247 let builder =
248 TestNodeBuilder::new(NodeType::OneHotEncoder, "test_ohe").output_default("output");
249
250 match input_dtype {
251 DType::F32 => builder.input_tensor_f32("input", input_rank, input_static_shape),
252 DType::F64 => builder.input_tensor_f64("input", input_rank, input_static_shape),
253 DType::I32 => builder.input_tensor_i32("input", input_rank, input_static_shape),
254 DType::I64 => builder.input_tensor_i64("input", input_rank, input_static_shape),
255 DType::Bool(_) => builder.input_tensor_bool("input", input_rank, input_static_shape),
256 _ => panic!("unsupported test dtype"),
257 }
258 }
259
260 #[test]
261 fn test_onehotencoder_config_int_categories() {
262 let config = OneHotEncoderConfig::new(Some(vec![0, 1, 2, 3]), None, Some(1));
263 assert_eq!(config.cats_int64s.as_ref().unwrap().len(), 4);
264 assert!(config.cats_strings.is_none());
265 assert_eq!(config.zeros, Some(1));
266 }
267
268 #[test]
269 fn test_onehotencoder_config_default() {
270 let config = OneHotEncoderConfig::default();
271 assert!(config.cats_int64s.is_none());
272 assert!(config.cats_strings.is_none());
273 assert!(config.zeros.is_none());
274 }
275
276 #[test]
277 fn test_onehotencoder_node_builder() {
278 let config = OneHotEncoderConfig::new(Some(vec![0, 1, 2]), None, None);
279 let node = OneHotEncoderNode::new("test_ohe".to_string(), vec![], vec![], config);
280 assert_eq!(node.name, "test_ohe");
281 assert_eq!(node.config.cats_int64s.as_ref().unwrap().len(), 3);
282 }
283
284 #[test]
285 fn test_spec_is_opset1_single_input_single_output() {
286 let processor = OneHotEncoderProcessor;
287 let spec = processor.spec();
288
289 assert_eq!(spec.min_opset, 1);
290 assert_eq!(spec.max_opset, None);
291 assert!(matches!(spec.inputs, InputSpec::Exact(1)));
292 assert!(matches!(spec.outputs, OutputSpec::Exact(1)));
293 }
294
295 #[test]
296 fn test_extract_config_rejects_both_category_attributes() {
297 let node = make_node_builder(DType::I64, 1, Some(vec![4]))
298 .attr_ints("cats_int64s", vec![0, 1, 2])
299 .attr_strings("cats_strings", vec!["a".to_string(), "b".to_string()])
300 .attr_int("zeros", 1)
301 .build();
302
303 let processor = OneHotEncoderProcessor;
304 let err = processor.extract_config(&node, 1).unwrap_err();
305
306 assert!(matches!(err, ProcessError::InvalidAttribute { .. }));
307 assert!(
308 err.to_string()
309 .contains("exactly one of cats_int64s or cats_strings")
310 );
311 }
312
313 #[test]
314 fn test_extract_config_reads_single_category_attribute() {
315 let node = make_node_builder(DType::I64, 1, Some(vec![4]))
316 .attr_ints("cats_int64s", vec![0, 1, 2])
317 .attr_int("zeros", 1)
318 .build();
319
320 let processor = OneHotEncoderProcessor;
321 let config = processor.extract_config(&node, 1).unwrap();
322
323 assert_eq!(config.cats_int64s, Some(vec![0, 1, 2]));
324 assert!(config.cats_strings.is_none());
325 assert_eq!(config.zeros, Some(1));
326 }
327
328 #[test]
329 fn test_extract_config_rejects_zeros_zero() {
330 let node = make_node_builder(DType::I64, 1, Some(vec![4]))
331 .attr_ints("cats_int64s", vec![0, 1, 2])
332 .attr_int("zeros", 0)
333 .build();
334
335 let processor = OneHotEncoderProcessor;
336 let err = processor.extract_config(&node, 1).unwrap_err();
337
338 assert!(matches!(err, ProcessError::Custom(_)));
339 assert!(err.to_string().contains("zeros=0 is not supported"));
340 }
341
342 #[test]
343 fn test_extract_config_rejects_empty_cats_int64s() {
344 let node = make_node_builder(DType::I64, 1, Some(vec![4]))
345 .attr_ints("cats_int64s", vec![])
346 .build();
347
348 let processor = OneHotEncoderProcessor;
349 let err = processor.extract_config(&node, 1).unwrap_err();
350
351 assert!(matches!(err, ProcessError::InvalidAttribute { .. }));
352 assert!(err.to_string().contains("cats_int64s"));
353 assert!(err.to_string().contains("must not be empty"));
354 }
355
356 #[test]
357 fn test_extract_config_rejects_cats_strings() {
358 let node = make_node_builder(DType::F32, 1, Some(vec![2]))
359 .attr_strings("cats_strings", vec!["a".to_string(), "b".to_string()])
360 .build();
361
362 let processor = OneHotEncoderProcessor;
363 let err = processor.extract_config(&node, 1).unwrap_err();
364
365 assert!(matches!(err, ProcessError::Custom(_)));
366 assert!(err.to_string().contains("cats_strings is not supported"));
367 }
368
369 #[test]
370 fn test_infer_types_sets_rank_and_static_shape_from_int_categories() {
371 let mut node = make_node_builder(DType::F32, 2, Some(vec![2, 3]))
372 .attr_ints("cats_int64s", vec![10, 20, 30, 40])
373 .build();
374
375 let processor = OneHotEncoderProcessor;
376 let prefs = OutputPreferences::new();
377 processor.infer_types(&mut node, 1, &prefs).unwrap();
378
379 match &node.outputs[0].ty {
380 ArgType::Tensor(t) => {
381 assert_eq!(t.dtype, DType::F32);
382 assert_eq!(t.rank, 3);
383 assert_eq!(t.static_shape, Some(vec![Some(2), Some(3), Some(4)]));
384 }
385 other => panic!("expected tensor output, got {other:?}"),
386 }
387 }
388
389 #[test]
390 fn test_infer_types_sets_partial_static_shape_when_input_shape_unknown() {
391 let mut node = make_node_builder(DType::I64, 1, None)
392 .attr_ints("cats_int64s", vec![0, 1, 2])
393 .build();
394
395 let processor = OneHotEncoderProcessor;
396 let prefs = OutputPreferences::new();
397 processor.infer_types(&mut node, 1, &prefs).unwrap();
398
399 match &node.outputs[0].ty {
400 ArgType::Tensor(t) => {
401 assert_eq!(t.rank, 2);
402 assert_eq!(t.static_shape, Some(vec![None, Some(3)]));
403 }
404 other => panic!("expected tensor output, got {other:?}"),
405 }
406 }
407
408 #[test]
409 fn test_infer_types_rejects_unsupported_input_dtype() {
410 let mut node =
411 make_node_builder(DType::Bool(crate::ir::BoolStore::Native), 1, Some(vec![3]))
412 .attr_ints("cats_int64s", vec![0, 1])
413 .build();
414
415 let processor = OneHotEncoderProcessor;
416 let prefs = OutputPreferences::new();
417 let err = processor.infer_types(&mut node, 1, &prefs).unwrap_err();
418
419 assert!(matches!(err, ProcessError::TypeMismatch { .. }));
420 }
421
422 #[test]
423 fn test_infer_types_requires_categories_attribute() {
424 let mut node = make_node_builder(DType::F32, 1, Some(vec![3])).build();
425
426 let processor = OneHotEncoderProcessor;
427 let prefs = OutputPreferences::new();
428 let err = processor.infer_types(&mut node, 1, &prefs).unwrap_err();
429
430 assert!(matches!(err, ProcessError::InvalidAttribute { .. }));
431 assert!(
432 err.to_string()
433 .contains("exactly one of cats_int64s or cats_strings")
434 );
435 }
436}