1use std::sync::Arc;
10
11use crate::ir::{ArgType, Argument, Node, PublicAttributesOwned, RawNode};
12use crate::processor::{NodeProcessor, NodeSpec, OutputPreferences, ProcessError};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct OpsetRange {
17 pub min: usize,
19 pub max: Option<usize>,
21}
22
23impl OpsetRange {
24 pub fn from_min(min: usize) -> Self {
26 Self { min, max: None }
27 }
28
29 pub fn contains(&self, opset: usize) -> bool {
31 opset >= self.min && self.max.is_none_or(|max| opset <= max)
32 }
33}
34
35impl core::fmt::Display for OpsetRange {
36 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
37 match self.max {
38 Some(max) => write!(f, "{}..={max}", self.min),
39 None => write!(f, "{}..", self.min),
40 }
41 }
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum MissingReason {
48 NoHook,
50 OpsetMismatch {
52 supported: OpsetRange,
54 },
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum HookCoverage {
61 Covered,
63 Missing(MissingReason),
65}
66
67pub trait CustomOpInference: Send + Sync {
79 fn coverage(&self, op_type: &str, domain: &str, opset: usize) -> HookCoverage;
81
82 fn infer(&self, node: &CustomNode) -> Result<Option<Vec<ArgType>>, ProcessError>;
90}
91
92#[derive(Debug, Clone)]
102#[non_exhaustive]
103pub struct CustomNode {
104 pub name: String,
106 pub op_type: String,
108 pub domain: String,
110 pub inputs: Vec<Argument>,
112 pub outputs: Vec<Argument>,
114 pub attrs: PublicAttributesOwned,
116 pub opset: usize,
118}
119
120impl CustomNode {
121 #[allow(clippy::too_many_arguments)]
127 pub fn new(
128 name: impl Into<String>,
129 op_type: impl Into<String>,
130 domain: impl Into<String>,
131 inputs: Vec<Argument>,
132 outputs: Vec<Argument>,
133 attrs: PublicAttributesOwned,
134 opset: usize,
135 ) -> Self {
136 Self {
137 name: name.into(),
138 op_type: op_type.into(),
139 domain: domain.into(),
140 inputs,
141 outputs,
142 attrs,
143 opset,
144 }
145 }
146}
147
148impl core::fmt::Display for CustomNode {
149 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
150 if self.domain.is_empty() {
151 write!(f, "Custom({})", self.op_type)
152 } else {
153 write!(f, "Custom({}::{})", self.domain, self.op_type)
154 }
155 }
156}
157
158pub(crate) fn custom_node_view(node: &RawNode) -> CustomNode {
160 let identity = node
161 .custom_identity
162 .as_ref()
163 .expect("RawNode with NodeType::Custom must carry a CustomIdentity (parser invariant)");
164 CustomNode {
165 name: node.name.clone(),
166 op_type: identity.op_type.clone(),
167 domain: identity.domain.clone(),
168 inputs: node.inputs.clone(),
169 outputs: node.outputs.clone(),
170 attrs: PublicAttributesOwned::from_internal(&node.attrs),
171 opset: identity.domain_opset,
172 }
173}
174
175pub(crate) struct CustomProcessor;
184
185impl NodeProcessor for CustomProcessor {
186 type Config = ();
187
188 fn spec(&self) -> NodeSpec {
189 NodeSpec::default()
191 }
192
193 fn infer_types(
194 &self,
195 node: &mut RawNode,
196 _opset: usize,
197 _output_preferences: &OutputPreferences,
198 ) -> Result<(), ProcessError> {
199 let placeholder = ArgType::default();
204 if let Some(input_ty) = node.inputs.first().map(|input| input.ty.clone()) {
205 let mut guessed = 0usize;
206 for output in node
207 .outputs
208 .iter_mut()
209 .filter(|output| output.ty == placeholder)
210 {
211 output.ty = input_ty.clone();
212 guessed += 1;
213 }
214 if guessed > 0 {
215 log::debug!(
219 "No inference hook for custom op '{}'; assuming input type for {guessed} undeclared output(s)",
220 node.name
221 );
222 }
223 } else if node.outputs.iter().any(|output| output.ty == placeholder) {
224 log::debug!(
225 "No inference hook for custom op '{}' and no inputs to mirror; keeping declared/default output types",
226 node.name
227 );
228 }
229 Ok(())
230 }
231
232 fn extract_config(&self, _node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
233 Ok(())
234 }
235
236 fn build_node(&self, builder: RawNode, _opset: usize) -> Result<Node, ProcessError> {
237 Ok(Node::Custom(custom_node_view(&builder)))
238 }
239}
240
241pub(crate) struct HookedCustomProcessor {
248 hooks: Option<Arc<dyn CustomOpInference>>,
249}
250
251impl HookedCustomProcessor {
252 pub(crate) fn new(hooks: Option<Arc<dyn CustomOpInference>>) -> Self {
253 Self { hooks }
254 }
255
256 pub(crate) fn hooks(&self) -> Option<Arc<dyn CustomOpInference>> {
258 self.hooks.clone()
259 }
260}
261
262impl NodeProcessor for HookedCustomProcessor {
263 type Config = ();
264
265 fn spec(&self) -> NodeSpec {
266 NodeSpec::default()
267 }
268
269 fn infer_types(
270 &self,
271 node: &mut RawNode,
272 opset: usize,
273 output_preferences: &OutputPreferences,
274 ) -> Result<(), ProcessError> {
275 let Some(hooks) = &self.hooks else {
276 return CustomProcessor.infer_types(node, opset, output_preferences);
278 };
279
280 let view = custom_node_view(node);
281 let identity = format!(
282 "custom op '{}' ({})",
283 node.name,
284 if view.domain.is_empty() {
285 view.op_type.clone()
286 } else {
287 format!("{}::{}", view.domain, view.op_type)
288 }
289 );
290
291 let inferred = hooks
292 .infer(&view)
293 .map_err(|e| ProcessError::Custom(format!("{identity}: {e}")))?;
294
295 match inferred {
296 Some(types) => {
297 if types.len() != node.outputs.len() {
298 return Err(ProcessError::Custom(format!(
299 "{identity}: hook returned {} output type(s) but the node has {} output(s)",
300 types.len(),
301 node.outputs.len(),
302 )));
303 }
304 for (out, ty) in node.outputs.iter_mut().zip(types) {
305 out.ty = ty;
306 }
307 Ok(())
308 }
309 None => Err(ProcessError::Custom(format!(
313 "{identity}: coverage() reported the op covered but infer() declined to infer \
314 (contract violation in the CustomOpInference implementation)",
315 ))),
316 }
317 }
318
319 fn extract_config(&self, _node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
320 Ok(())
321 }
322
323 fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
324 CustomProcessor.build_node(builder, opset)
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331 use crate::ir::{ArgType, CustomIdentity, DType, NodeType, TensorType};
332 use crate::node::test_utils::TestNodeBuilder;
333
334 fn make_custom_node() -> RawNode {
335 let mut node = TestNodeBuilder::new(NodeType::Custom, "test_custom")
336 .input_tensor_f32("input", 3, None)
337 .output_tensor_f32("output", 0, None)
338 .attr_int("n_fft", 1024)
339 .build();
340 node.custom_identity = Some(CustomIdentity {
341 op_type: "FftReal".to_string(),
342 domain: "custom_domain".to_string(),
343 domain_opset: 2,
344 });
345 node
346 }
347
348 #[test]
349 fn infer_types_falls_back_to_same_as_input() {
350 let mut node = make_custom_node();
351 let processor = CustomProcessor;
352 processor
353 .infer_types(&mut node, 16, &OutputPreferences::new())
354 .unwrap();
355 assert_eq!(node.outputs[0].ty, node.inputs[0].ty);
356 }
357
358 #[test]
359 fn infer_types_tolerates_no_inputs() {
360 let mut node = make_custom_node();
361 node.inputs.clear();
362 let processor = CustomProcessor;
363 processor
365 .infer_types(&mut node, 16, &OutputPreferences::new())
366 .unwrap();
367 }
368
369 #[test]
370 fn build_node_preserves_identity_and_attrs() {
371 let node = make_custom_node();
372 let built = CustomProcessor.build_node(node, 16).unwrap();
373 let Node::Custom(custom) = built else {
374 panic!("expected Node::Custom");
375 };
376 assert_eq!(custom.op_type, "FftReal");
377 assert_eq!(custom.domain, "custom_domain");
378 assert_eq!(custom.opset, 2);
379 assert_eq!(custom.attrs.get_i64("n_fft"), Some(1024));
380 assert_eq!(custom.name, "test_custom");
381 assert_eq!(custom.inputs.len(), 1);
382 assert!(matches!(
383 custom.inputs[0].ty,
384 ArgType::Tensor(TensorType {
385 dtype: DType::F32,
386 rank: 3,
387 ..
388 })
389 ));
390 }
391
392 #[test]
393 fn node_type_accessor_and_display() {
394 let built = CustomProcessor.build_node(make_custom_node(), 16).unwrap();
395 assert_eq!(built.node_type(), NodeType::Custom);
396 assert_eq!(built.to_string(), "Custom(custom_domain::FftReal)");
397 }
398
399 #[test]
400 fn from_str_never_resolves_to_custom() {
401 use core::str::FromStr;
402 assert!(NodeType::from_str("Custom").is_err());
403 assert!(NodeType::from_str("custom").is_err());
404 }
405
406 struct FixedInference {
408 types: Vec<ArgType>,
409 }
410
411 impl CustomOpInference for FixedInference {
412 fn coverage(&self, op_type: &str, _domain: &str, _opset: usize) -> HookCoverage {
413 if op_type == "FftReal" {
414 HookCoverage::Covered
415 } else {
416 HookCoverage::Missing(MissingReason::NoHook)
417 }
418 }
419
420 fn infer(&self, node: &CustomNode) -> Result<Option<Vec<ArgType>>, ProcessError> {
421 if node.op_type == "FftReal" {
422 Ok(Some(self.types.clone()))
423 } else {
424 Ok(None)
425 }
426 }
427 }
428
429 #[test]
430 fn hooked_processor_applies_hook_types() {
431 let mut node = make_custom_node();
432 let hook_ty = ArgType::Tensor(TensorType::new(DType::F64, 5, None));
433 let processor = HookedCustomProcessor::new(Some(Arc::new(FixedInference {
434 types: vec![hook_ty.clone()],
435 })));
436 processor
437 .infer_types(&mut node, 16, &OutputPreferences::new())
438 .unwrap();
439 assert_eq!(node.outputs[0].ty, hook_ty);
440 }
441
442 #[test]
443 fn hooked_processor_rejects_output_count_mismatch() {
444 let mut node = make_custom_node();
445 let ty = ArgType::Tensor(TensorType::new(DType::F32, 1, None));
446 let processor = HookedCustomProcessor::new(Some(Arc::new(FixedInference {
447 types: vec![ty.clone(), ty],
448 })));
449 let err = processor
450 .infer_types(&mut node, 16, &OutputPreferences::new())
451 .unwrap_err();
452 let msg = format!("{err}");
453 assert!(msg.contains("returned 2 output type(s)"), "got: {msg}");
454 assert!(msg.contains("custom_domain::FftReal"), "got: {msg}");
455 }
456
457 #[test]
458 fn hooked_processor_errors_when_covered_hook_declines_to_infer() {
459 let mut node = make_custom_node();
463 node.custom_identity.as_mut().unwrap().op_type = "OtherOp".to_string();
464 let processor =
465 HookedCustomProcessor::new(Some(Arc::new(FixedInference { types: vec![] })));
466 let err = processor
467 .infer_types(&mut node, 16, &OutputPreferences::new())
468 .unwrap_err();
469 let msg = format!("{err}");
470 assert!(msg.contains("contract violation"), "got: {msg}");
471 assert!(msg.contains("custom_domain::OtherOp"), "got: {msg}");
472 }
473
474 #[test]
475 fn hooked_processor_wraps_hook_errors_with_op_identity() {
476 struct FailingInference;
477
478 impl CustomOpInference for FailingInference {
479 fn coverage(&self, _: &str, _: &str, _: usize) -> HookCoverage {
480 HookCoverage::Covered
481 }
482
483 fn infer(&self, _: &CustomNode) -> Result<Option<Vec<ArgType>>, ProcessError> {
484 Err(ProcessError::MissingAttribute("n_fft".to_string()))
485 }
486 }
487
488 let mut node = make_custom_node();
489 let err = HookedCustomProcessor::new(Some(Arc::new(FailingInference)))
490 .infer_types(&mut node, 16, &OutputPreferences::new())
491 .unwrap_err();
492 let msg = format!("{err}");
493 assert!(msg.contains("custom_domain::FftReal"), "got: {msg}");
494 assert!(msg.contains("n_fft"), "got: {msg}");
495 }
496
497 #[test]
498 fn hooked_processor_applies_types_to_multiple_outputs() {
499 let mut node = make_custom_node();
500 node.outputs
501 .push(crate::ir::Argument::new("output2", ArgType::default()));
502 let ty0 = ArgType::Tensor(TensorType::new(DType::F64, 2, None));
503 let ty1 = ArgType::Tensor(TensorType::new(DType::I64, 1, None));
504 HookedCustomProcessor::new(Some(Arc::new(FixedInference {
505 types: vec![ty0.clone(), ty1.clone()],
506 })))
507 .infer_types(&mut node, 16, &OutputPreferences::new())
508 .unwrap();
509 assert_eq!(node.outputs[0].ty, ty0);
510 assert_eq!(node.outputs[1].ty, ty1);
511 }
512
513 #[test]
514 fn hooked_processor_with_no_hooks_matches_hook_free() {
515 let mut node = make_custom_node();
516 HookedCustomProcessor::new(None)
517 .infer_types(&mut node, 16, &OutputPreferences::new())
518 .unwrap();
519 assert_eq!(node.outputs[0].ty, node.inputs[0].ty);
520 }
521
522 #[test]
523 fn fallback_preserves_declared_output_types() {
524 let mut node = make_custom_node();
527 let declared = ArgType::Tensor(TensorType::new(DType::I64, 4, None));
528 node.outputs[0].ty = declared.clone();
529 CustomProcessor
530 .infer_types(&mut node, 16, &OutputPreferences::new())
531 .unwrap();
532 assert_eq!(node.outputs[0].ty, declared);
533 }
534
535 #[test]
536 fn fallback_fills_all_undeclared_outputs() {
537 let mut node = make_custom_node();
538 node.outputs
539 .push(crate::ir::Argument::new("output2", ArgType::default()));
540 CustomProcessor
541 .infer_types(&mut node, 16, &OutputPreferences::new())
542 .unwrap();
543 assert_eq!(node.outputs[0].ty, node.inputs[0].ty);
544 assert_eq!(node.outputs[1].ty, node.inputs[0].ty);
545 }
546}