Skip to main content

onnx_ir/node/
custom.rs

1//! # Custom (non-built-in) operators
2//!
3//! Nodes whose `(domain, op_type)` does not map to a built-in `NodeType` are
4//! preserved as `NodeType::Custom` / `Node::Custom(CustomNode)` instead of
5//! failing the parse. Type inference for them is supplied by user hooks
6//! registered in `burn-onnx` (see `DESIGN-CUSTOM-OPS.md`); without a hook, a
7//! best-effort same-as-input fallback keeps the graph buildable for inspection.
8
9use std::sync::Arc;
10
11use crate::ir::{ArgType, Argument, Node, PublicAttributesOwned, RawNode};
12use crate::processor::{NodeProcessor, NodeSpec, OutputPreferences, ProcessError};
13
14/// Inclusive opset range a hook supports.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct OpsetRange {
17    /// Lowest supported opset.
18    pub min: usize,
19    /// Highest supported opset (`None` = unbounded).
20    pub max: Option<usize>,
21}
22
23impl OpsetRange {
24    /// Range from `min` with no upper bound.
25    pub fn from_min(min: usize) -> Self {
26        Self { min, max: None }
27    }
28
29    /// Whether `opset` falls inside the range.
30    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/// Why a custom op is not covered by the registered hooks.
45#[derive(Debug, Clone, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum MissingReason {
48    /// No hook is registered for this `(op_type, domain)`.
49    NoHook,
50    /// A hook is registered but its opset range excludes the node's opset.
51    OpsetMismatch {
52        /// The opset range the registered hook supports.
53        supported: OpsetRange,
54    },
55}
56
57/// Coverage answer for a `(op_type, domain, opset)` triple.
58#[derive(Debug, Clone, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum HookCoverage {
61    /// A hook is registered and its opset range covers the node.
62    Covered,
63    /// The node is not covered, with the reason for diagnostics.
64    Missing(MissingReason),
65}
66
67/// Type-inference hooks for custom (non-built-in) operators.
68///
69/// Implemented by the hook registry in `burn-onnx` and passed to the parse
70/// pipeline via `OnnxGraphBuilder::with_custom_op_inference`. Output
71/// preferences from consumers are not consulted for custom ops: the hook is
72/// the sole authority on its output types.
73///
74/// Contract: for any node, `coverage(..) == Covered` must imply
75/// `infer(..)` returns `Ok(Some(_))`. The pipeline checks coverage for the
76/// whole graph before inference runs, and treats `Ok(None)` after a passed
77/// coverage check as an error rather than silently falling back.
78pub trait CustomOpInference: Send + Sync {
79    /// Coverage for this `(op_type, domain)` at the node's domain opset.
80    fn coverage(&self, op_type: &str, domain: &str, opset: usize) -> HookCoverage;
81
82    /// Infer output types. `Ok(None)` means no hook is registered for this
83    /// node.
84    ///
85    /// Constant inputs are readable via `node.inputs[i].value()`. May be
86    /// called more than once per node: type inference runs in an iterative
87    /// fixed-point loop, so implementations must be deterministic and
88    /// side-effect free.
89    fn infer(&self, node: &CustomNode) -> Result<Option<Vec<ArgType>>, ProcessError>;
90}
91
92/// Public view of a custom (non-built-in) ONNX node.
93///
94/// Inputs are full [`Argument`] values with their value stores attached, so
95/// constant input data is readable via `Argument::value()`.
96///
97/// During `infer_output_types` / [`CustomOpInference::infer`], the `outputs`
98/// carry placeholder types: only their names and count are meaningful. Output
99/// types are valid once inference has completed (i.e. in every codegen-side
100/// hook method).
101#[derive(Debug, Clone)]
102#[non_exhaustive]
103pub struct CustomNode {
104    /// Node name (sanitized, unique within the graph)
105    pub name: String,
106    /// Raw ONNX op_type, e.g. "FftReal"
107    pub op_type: String,
108    /// Raw ONNX domain, e.g. "custom_domain" ("" = default domain)
109    pub domain: String,
110    /// The inputs of the node.
111    pub inputs: Vec<Argument>,
112    /// The outputs of the node.
113    pub outputs: Vec<Argument>,
114    /// ONNX attributes, exposed read-only.
115    pub attrs: PublicAttributesOwned,
116    /// Opset version of `domain` from the model's opset_import.
117    pub opset: usize,
118}
119
120impl CustomNode {
121    /// Construct a custom node view, e.g. for hook unit tests.
122    ///
123    /// Inside the pipeline, views are built from parsed nodes; hand-built
124    /// nodes carry no attribute values or constant-input data unless the
125    /// arguments were constructed with value stores.
126    #[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
158/// Build the public CustomNode view from a RawNode at any pipeline stage.
159pub(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
175/// Hook-free processor for `NodeType::Custom`, registered in the global registry.
176///
177/// Everything a processor must do for a custom node is hook-independent except
178/// type inference: the spec is permissive, constants are never lifted, the node
179/// is never a no-op, and `build_node` just snapshots the raw node into the
180/// public `CustomNode` view. Type inference here is a best-effort fallback for
181/// runs without registered hooks; the hook-aware path overrides it during the
182/// type-inference phase.
183pub(crate) struct CustomProcessor;
184
185impl NodeProcessor for CustomProcessor {
186    type Config = ();
187
188    fn spec(&self) -> NodeSpec {
189        // Permissive: unknown schema, so any opset and any I/O count.
190        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        // Best-effort fallback when no inference hook is in play. Types the
200        // model declared (graph outputs / value_info, seeded during proto
201        // conversion) are authoritative and never overwritten; only outputs
202        // still carrying the placeholder default type get the guess.
203        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                // debug, not warn: inference reruns in a fixed-point loop, so
216                // this fires repeatedly; the once-per-node signal is the
217                // "treating as custom op" log at proto conversion.
218                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
241/// Hook-aware processor used by the type-inference phase in place of the
242/// globally registered [`CustomProcessor`]; behaves identically to it when no
243/// hooks are registered.
244///
245/// Only `infer_types` differs from the hook-free processor; every other
246/// `NodeProcessor` responsibility is hook-independent.
247pub(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    /// The registered inference hook, if any.
257    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            // No hooks registered at all: hook-free fallback.
277            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            // The coverage pre-pass already verified this node is covered, so
310            // a hook declining to infer here is a coverage()/infer() contract
311            // violation, not a reason to silently fall back to a guess.
312            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        // Must not panic on the empty-input case.
364        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    /// Inference stub that returns a fixed set of output types for "FftReal".
407    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        // With hooks registered, reaching inference means the coverage
460        // pre-pass passed; a hook then returning Ok(None) is a
461        // coverage()/infer() contract violation, not a fallback case.
462        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        // A type the model declared (e.g. via value_info) must not be
525        // clobbered by the same-as-input guess.
526        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}