1use std::collections::HashMap;
27use std::io::Read;
28use std::sync::Arc;
29use std::{fmt, fs::File, path::Path};
30
31use protobuf::Message;
32
33use crate::{
34 ir::{NodeType, OnnxGraph},
35 node::custom::{CustomOpInference, HookedCustomProcessor},
36 processor::ProcessError,
37 protos::ModelProto,
38 registry::{ProcessorMethods, ProcessorRegistry},
39};
40
41use super::phases::{
42 finalization, initialization, node_conversion, post_processing, type_inference,
43};
44
45pub(crate) struct PipelineHooks {
52 custom: HookedCustomProcessor,
54}
55
56impl PipelineHooks {
57 pub(crate) fn new(inference: Option<Arc<dyn CustomOpInference>>) -> Self {
58 Self {
59 custom: HookedCustomProcessor::new(inference),
60 }
61 }
62
63 pub(crate) fn inference(&self) -> Option<Arc<dyn CustomOpInference>> {
66 self.custom.hooks()
67 }
68
69 pub(crate) fn resolve<'a>(
72 &'a self,
73 node_type: &NodeType,
74 registry: &'a ProcessorRegistry,
75 ) -> &'a dyn ProcessorMethods {
76 match node_type {
77 NodeType::Custom => &self.custom,
78 other => registry.get(other),
79 }
80 }
81}
82
83#[derive(Debug, Clone)]
85#[non_exhaustive]
86pub struct MissingHook {
87 pub op_type: String,
89 pub domain: String,
91 pub node_count: usize,
93 pub model_opset: usize,
95 pub reason: crate::node::custom::MissingReason,
97}
98
99impl MissingHook {
100 pub fn new(
103 op_type: impl Into<String>,
104 domain: impl Into<String>,
105 node_count: usize,
106 model_opset: usize,
107 reason: crate::node::custom::MissingReason,
108 ) -> Self {
109 Self {
110 op_type: op_type.into(),
111 domain: domain.into(),
112 node_count,
113 model_opset,
114 reason,
115 }
116 }
117}
118
119impl fmt::Display for MissingHook {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 if self.domain.is_empty() {
122 write!(f, "{}", self.op_type)?;
123 } else {
124 write!(f, "{}::{}", self.domain, self.op_type)?;
125 }
126 write!(f, " used by {} node(s)", self.node_count)?;
127 if let crate::node::custom::MissingReason::OpsetMismatch { supported } = &self.reason {
128 write!(
129 f,
130 " (hook covers opsets {supported}, model uses {})",
131 self.model_opset
132 )?;
133 }
134 Ok(())
135 }
136}
137
138#[derive(Debug)]
140#[non_exhaustive]
141pub enum Error {
142 Io { path: String, error: std::io::Error },
144
145 InvalidFormat { path: Option<String>, error: String },
147
148 InvalidGraphStructure { reason: String },
150
151 MissingOpsetVersion,
153
154 TypeInference(ProcessError),
156
157 Processing(ProcessError),
159
160 MissingCustomOpHooks(Vec<MissingHook>),
166}
167
168impl fmt::Display for Error {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 match self {
171 Error::Io { path, error } => {
172 write!(f, "Failed to open ONNX file '{}': {}", path, error)
173 }
174 Error::InvalidFormat { path, error } => {
175 if let Some(p) = path {
176 write!(f, "Invalid ONNX format in '{}': {}", p, error)
177 } else {
178 write!(f, "Invalid ONNX format: {}", error)
179 }
180 }
181 Error::InvalidGraphStructure { reason } => {
182 write!(f, "Invalid ONNX graph structure: {}", reason)
183 }
184 Error::MissingOpsetVersion => {
185 write!(
186 f,
187 "ONNX model uses default-domain operators but its opset_import \
188 declares no version for the default domain (\"\" or \"ai.onnx\")"
189 )
190 }
191 Error::TypeInference(e) => {
192 write!(f, "Type inference failed: {e}")
193 }
194 Error::Processing(e) => {
195 write!(f, "Processing error: {e}")
196 }
197 Error::MissingCustomOpHooks(missing) => {
198 write!(
202 f,
203 "model contains {} custom op(s) with no covering inference hook:",
204 missing.len()
205 )?;
206 for hook in missing {
207 write!(f, "\n - {hook}")?;
208 }
209 Ok(())
210 }
211 }
212 }
213}
214
215impl std::error::Error for Error {
216 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
217 match self {
218 Error::Io { error, .. } => Some(error),
219 _ => None,
220 }
221 }
222}
223
224impl From<ProcessError> for Error {
225 fn from(error: ProcessError) -> Self {
226 Error::Processing(error)
227 }
228}
229
230#[derive(Clone)]
250pub struct OnnxGraphBuilder {
251 simplify: bool,
253 custom_op_inference: Option<Arc<dyn CustomOpInference>>,
255}
256
257impl fmt::Debug for OnnxGraphBuilder {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 f.debug_struct("OnnxGraphBuilder")
260 .field("simplify", &self.simplify)
261 .field(
262 "custom_op_inference",
263 &self.custom_op_inference.as_ref().map(|_| "<hooks>"),
264 )
265 .finish()
266 }
267}
268
269impl Default for OnnxGraphBuilder {
270 fn default() -> Self {
271 Self {
272 simplify: true,
273 custom_op_inference: None,
274 }
275 }
276}
277
278impl OnnxGraphBuilder {
279 pub fn new() -> Self {
281 Self::default()
282 }
283
284 pub fn simplify(mut self, simplify: bool) -> Self {
290 self.simplify = simplify;
291 self
292 }
293
294 pub fn with_custom_op_inference(mut self, hooks: Arc<dyn CustomOpInference>) -> Self {
300 self.custom_op_inference = Some(hooks);
301 self
302 }
303
304 pub fn parse_file(self, path: impl AsRef<Path>) -> Result<OnnxGraph, Error> {
317 let path = path.as_ref();
318 log::info!("Parsing ONNX file: {}", path.display());
319
320 #[cfg(feature = "mmap")]
322 let buffer = {
323 let file = File::open(path).map_err(|error| Error::Io {
324 path: path.display().to_string(),
325 error,
326 })?;
327 let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(|error| Error::Io {
330 path: path.display().to_string(),
331 error,
332 })?;
333 log::debug!("Memory-mapped ONNX file ({} bytes)", mmap.len());
334 bytes::Bytes::from_owner(mmap)
335 };
336
337 #[cfg(not(feature = "mmap"))]
338 let buffer = {
339 let mut file = File::open(path).map_err(|error| Error::Io {
340 path: path.display().to_string(),
341 error,
342 })?;
343 let mut buf = Vec::new();
344 file.read_to_end(&mut buf).map_err(|error| Error::Io {
345 path: path.display().to_string(),
346 error,
347 })?;
348 log::debug!("Read ONNX file into memory ({} bytes)", buf.len());
349 bytes::Bytes::from(buf)
350 };
351
352 self.parse_buffer(buffer, Some(path))
353 }
354
355 pub fn parse_bytes(self, data: &[u8]) -> Result<OnnxGraph, Error> {
367 let buffer = bytes::Bytes::copy_from_slice(data);
368 self.parse_buffer(buffer, None)
369 }
370
371 pub fn parse_reader<R: Read>(self, mut reader: R) -> Result<OnnxGraph, Error> {
383 let mut buf = Vec::new();
384 reader.read_to_end(&mut buf).map_err(|error| Error::Io {
385 path: "<reader>".to_string(),
386 error,
387 })?;
388 log::debug!("Read ONNX from reader ({} bytes)", buf.len());
389 let buffer = bytes::Bytes::from(buf);
390 self.parse_buffer(buffer, None)
391 }
392
393 fn parse_buffer(
395 self,
396 buffer: bytes::Bytes,
397 source_path: Option<&Path>,
398 ) -> Result<OnnxGraph, Error> {
399 let path_str = source_path.map(|p| p.display().to_string());
400
401 let base_path = source_path.and_then(|p| p.parent());
403
404 let model: ModelProto =
405 Message::parse_from_tokio_bytes(&buffer).map_err(|e| Error::InvalidFormat {
406 path: path_str.clone(),
407 error: e.to_string(),
408 })?;
409
410 if !model.graph.node.is_top_sorted() {
413 return Err(Error::InvalidGraphStructure {
414 reason: "Nodes are not topologically sorted (ONNX spec violation)".to_string(),
415 });
416 }
417
418 let hooks = PipelineHooks::new(self.custom_op_inference.clone());
419 let graph = build_graph_with_options(&model, base_path, self.simplify, &hooks)?;
420
421 if let Some(path) = path_str {
422 log::info!("Finished parsing ONNX file: {}", path);
423 } else {
424 log::info!("Finished parsing ONNX from bytes");
425 }
426 Ok(graph)
427 }
428}
429
430fn build_graph_with_options(
432 model: &ModelProto,
433 base_path: Option<&Path>,
434 simplify: bool,
435 hooks: &PipelineHooks,
436) -> Result<OnnxGraph, Error> {
437 let (opset_version, domain_opsets) = extract_opset_versions(model)?;
438 let graph_builder = build_graph_builder_from_proto(
439 &model.graph,
440 opset_version,
441 &domain_opsets,
442 None,
443 base_path,
444 simplify,
445 hooks,
446 )?;
447
448 log::debug!(" PHASE 6: Node Conversion (RawNode -> Node) ");
449 graph_builder
450 .convert_to_graph(opset_version)
451 .map_err(Error::Processing)
452}
453
454pub(crate) fn build_graph_builder_from_proto(
463 graph: &crate::protos::GraphProto,
464 opset_version: usize,
465 domain_opsets: &DomainOpsets,
466 name_registry: Option<crate::graph_state::NameRegistry>,
467 base_path: Option<&Path>,
468 simplify: bool,
469 hooks: &PipelineHooks,
470) -> Result<crate::ir::OnnxGraphBuilder, Error> {
471 build_graph_builder_from_proto_with_outer_scope(
472 graph,
473 opset_version,
474 domain_opsets,
475 name_registry,
476 crate::ir::OuterScopeTypes::new(),
477 base_path,
478 simplify,
479 hooks,
480 )
481}
482
483#[allow(clippy::too_many_arguments)] pub(crate) fn build_graph_builder_from_proto_with_outer_scope(
497 graph: &crate::protos::GraphProto,
498 opset_version: usize,
499 domain_opsets: &DomainOpsets,
500 name_registry: Option<crate::graph_state::NameRegistry>,
501 outer_scope: crate::ir::OuterScopeTypes,
502 base_path: Option<&Path>,
503 simplify: bool,
504 hooks: &PipelineHooks,
505) -> Result<crate::ir::OnnxGraphBuilder, Error> {
506 log::debug!(" PHASE 1: Initialization ");
507 let state_rc = initialization::initialize_from_graph_with_registry_and_outer_scope(
508 graph,
509 name_registry,
510 outer_scope,
511 base_path,
512 )
513 .map_err(|error| Error::InvalidFormat { path: None, error })?;
514
515 log::debug!(" PHASE 2: Node Conversion (Proto -> RawNode) ");
516 node_conversion::convert_nodes_from_graph(
517 graph,
518 &state_rc,
519 opset_version,
520 domain_opsets,
521 hooks,
522 )?;
523
524 log::debug!(" PHASE 2b: Early Constant Folding ");
529 {
530 let mut state = state_rc.borrow_mut();
531 let mut nodes = std::mem::take(&mut state.processed_nodes);
532 drop(state);
533
534 let max_iterations = 10;
536 let mut converged = false;
537 for _ in 0..max_iterations {
538 let const_count_before = nodes
539 .iter()
540 .filter(|n| n.node_type == crate::ir::NodeType::Constant)
541 .count();
542 nodes = crate::simplify::constant_fold::fold_weight_rearrangements(nodes, &state_rc);
543 let const_count_after = nodes
544 .iter()
545 .filter(|n| n.node_type == crate::ir::NodeType::Constant)
546 .count();
547 if const_count_after == const_count_before {
548 converged = true;
549 break;
550 }
551 }
552 if !converged {
553 log::debug!(
554 "Early constant folding: reached max iterations ({max_iterations}) without converging"
555 );
556 }
557
558 let mut state = state_rc.borrow_mut();
559 state.processed_nodes = nodes;
560 }
561
562 log::debug!(" PHASE 2c: SplitToSequence rewrite ");
566 crate::simplify::split_to_sequence::rewrite_split_to_sequence(&mut state_rc.borrow_mut());
567
568 if let Some(inference) = hooks.inference() {
574 log::debug!(" PHASE 2d: Custom-op coverage check ");
575 check_custom_op_coverage(&state_rc.borrow().processed_nodes, inference.as_ref())?;
576 }
577
578 log::debug!(" PHASE 3: Type Inference ");
579 type_inference::infer_types(&state_rc, opset_version, hooks).map_err(Error::TypeInference)?;
580
581 log::debug!(" PHASE 4: Post-processing ");
582 let (nodes, inputs, outputs) =
583 post_processing::post_process(&state_rc, simplify, opset_version);
584
585 let (mut nodes, inputs, mut outputs) = if simplify {
586 log::debug!(" PHASE 4b: Simplification ");
587 crate::simplify::simplify_graph(nodes, inputs, outputs, &state_rc, opset_version)
588 } else {
589 (nodes, inputs, outputs)
590 };
591
592 log::debug!(" PHASE 5: Finalization ");
593 Ok(finalization::finalize(
594 &mut nodes,
595 inputs,
596 &mut outputs,
597 state_rc,
598 ))
599}
600
601fn check_custom_op_coverage(
607 nodes: &[crate::ir::RawNode],
608 hooks: &dyn CustomOpInference,
609) -> Result<(), Error> {
610 use std::collections::BTreeMap;
611
612 let mut missing: BTreeMap<(String, String), MissingHook> = BTreeMap::new();
613
614 for node in nodes.iter().filter(|n| n.node_type == NodeType::Custom) {
615 let identity = node
619 .custom_identity
620 .as_ref()
621 .expect("RawNode with NodeType::Custom must carry a CustomIdentity (parser invariant)");
622 match hooks.coverage(&identity.op_type, &identity.domain, identity.domain_opset) {
623 crate::node::custom::HookCoverage::Covered => {}
624 crate::node::custom::HookCoverage::Missing(reason) => {
625 missing
626 .entry((identity.domain.clone(), identity.op_type.clone()))
627 .and_modify(|m| m.node_count += 1)
628 .or_insert_with(|| MissingHook {
629 op_type: identity.op_type.clone(),
630 domain: identity.domain.clone(),
631 node_count: 1,
632 model_opset: identity.domain_opset,
633 reason,
634 });
635 }
636 }
637 }
638
639 if missing.is_empty() {
640 Ok(())
641 } else {
642 Err(Error::MissingCustomOpHooks(missing.into_values().collect()))
643 }
644}
645
646const AI_ONNX_DOMAIN: &str = "ai.onnx";
656
657const LATEST_DEFAULT_OPSET: usize = 24;
665
666pub fn normalize_domain(domain: &str) -> &str {
672 if domain == AI_ONNX_DOMAIN { "" } else { domain }
673}
674
675#[derive(Debug, Clone)]
686pub(crate) struct DomainOpsets {
687 versions: Arc<HashMap<String, usize>>,
688 default_opset: usize,
689}
690
691impl DomainOpsets {
692 pub(crate) fn new(mut versions: HashMap<String, usize>, default_opset: usize) -> Self {
693 versions.entry(String::new()).or_insert(default_opset);
696 Self {
697 versions: Arc::new(versions),
698 default_opset,
699 }
700 }
701
702 pub(crate) fn opset_for(&self, domain: &str) -> usize {
707 let domain = normalize_domain(domain);
708 if let Some(version) = self.versions.get(domain) {
709 return *version;
710 }
711 log::warn!(
712 "Domain '{domain}' has no opset_import entry (malformed model); \
713 falling back to default-domain opset {}",
714 self.default_opset
715 );
716 self.default_opset
717 }
718}
719
720fn uses_default_domain(graph: &crate::protos::GraphProto) -> bool {
729 graph.node.iter().any(|node| {
730 normalize_domain(&node.domain).is_empty()
731 || node.attribute.iter().any(|attr| {
732 attr.g.as_ref().is_some_and(uses_default_domain)
733 || attr.graphs.iter().any(uses_default_domain)
734 })
735 })
736}
737
738fn collect_domain_versions(model: &ModelProto) -> HashMap<String, usize> {
744 let mut versions: HashMap<String, usize> = HashMap::new();
745 for opset in &model.opset_import {
746 let domain = normalize_domain(&opset.domain);
747 let version = opset.version as usize;
748 match versions.get(domain) {
749 Some(&existing) if existing != version => {
750 let kept = existing.max(version);
751 if domain.is_empty() {
754 log::warn!(
755 "The default domain is imported at conflicting opset \
756 versions {existing} and {version} (\"\" and \"ai.onnx\" \
757 name the same domain); using {kept}"
758 );
759 } else {
760 log::warn!(
761 "Domain '{domain}' is imported at conflicting opset \
762 versions {existing} and {version}; using {kept}"
763 );
764 }
765 versions.insert(domain.to_string(), kept);
766 }
767 Some(_) => {}
768 None => {
769 versions.insert(domain.to_string(), version);
770 }
771 }
772 }
773 versions
774}
775
776fn extract_opset_versions(model: &ModelProto) -> Result<(usize, DomainOpsets), Error> {
779 let versions = collect_domain_versions(model);
780
781 let default_opset = match versions.get("") {
782 Some(version) => *version,
783 None if !uses_default_domain(&model.graph) => {
795 log::warn!(
796 "Model imports no default-domain opset; assuming opset \
797 {LATEST_DEFAULT_OPSET} for node specs. Operators whose semantics \
798 depend on the default opset may be interpreted incorrectly."
799 );
800 LATEST_DEFAULT_OPSET
801 }
802 None => return Err(Error::MissingOpsetVersion),
803 };
804
805 Ok((default_opset, DomainOpsets::new(versions, default_opset)))
806}
807
808pub(crate) trait TopologicalSortable {
810 fn is_top_sorted(&self) -> bool;
811}
812
813use crate::protos::NodeProto;
814
815impl TopologicalSortable for Vec<NodeProto> {
816 fn is_top_sorted(&self) -> bool {
817 for (node_position, node) in self.iter().enumerate() {
819 for output in &node.output {
821 if output.is_empty() {
824 continue;
825 }
826 for (other_node_position, other_node) in self.iter().enumerate() {
828 if other_node.input.contains(output) {
830 if node_position > other_node_position {
832 return false;
834 }
835 }
836 }
837 }
838 }
839
840 true
842 }
843}
844
845#[cfg(test)]
846mod tests {
847 use super::*;
848 use crate::ir::{ArgType, DType, Node};
849 use crate::protos::{
850 GraphProto, ModelProto, NodeProto, OperatorSetIdProto, TypeProto, ValueInfoProto,
851 };
852 use crate::protos::{TensorShapeProto, tensor_shape_proto, type_proto};
853
854 fn tensor_value_info(name: &str, dims: &[i64]) -> ValueInfoProto {
855 let mut shape = TensorShapeProto::new();
856 for d in dims {
857 let mut dim = tensor_shape_proto::Dimension::new();
858 dim.set_dim_value(*d);
859 shape.dim.push(dim);
860 }
861 let mut tensor = type_proto::Tensor::new();
862 tensor.elem_type = 1; tensor.shape = ::protobuf::MessageField::some(shape);
864 let mut ty = TypeProto::new();
865 ty.set_tensor_type(tensor);
866 let mut vi = ValueInfoProto::new();
867 vi.name = name.to_string();
868 vi.type_ = ::protobuf::MessageField::some(ty);
869 vi
870 }
871
872 fn single_node_model(domain: &str, op_type: &str, opset_imports: &[(&str, i64)]) -> Vec<u8> {
874 let mut node = NodeProto::new();
875 node.name = "the_node".to_string();
876 node.op_type = op_type.to_string();
877 node.domain = domain.to_string();
878 node.input.push("input".to_string());
879 node.output.push("output".to_string());
880
881 let mut graph = GraphProto::new();
882 graph.name = "test_graph".to_string();
883 graph.input.push(tensor_value_info("input", &[2, 3]));
884 graph.output.push(tensor_value_info("output", &[2, 3]));
885 graph.node.push(node);
886
887 let mut model = ModelProto::new();
888 model.graph = ::protobuf::MessageField::some(graph);
889 for (domain, version) in opset_imports {
890 let mut op = OperatorSetIdProto::new();
891 op.domain = domain.to_string();
892 op.version = *version;
893 model.opset_import.push(op);
894 }
895 model.write_to_bytes().unwrap()
896 }
897
898 fn parse_single_custom(bytes: &[u8]) -> crate::node::custom::CustomNode {
899 let graph = OnnxGraphBuilder::new().parse_bytes(bytes).unwrap();
900 graph
901 .nodes
902 .iter()
903 .find_map(|n| match n {
904 Node::Custom(c) => Some(c.clone()),
905 _ => None,
906 })
907 .expect("graph should contain a Custom node")
908 }
909
910 #[test]
911 fn custom_domain_node_parses_as_custom() {
912 let bytes = single_node_model(
913 "custom.domain",
914 "FftLike",
915 &[("", 16), ("custom.domain", 2)],
916 );
917 let custom = parse_single_custom(&bytes);
918
919 assert_eq!(custom.op_type, "FftLike");
920 assert_eq!(custom.domain, "custom.domain");
921 assert_eq!(custom.opset, 2);
923 assert!(matches!(
925 &custom.outputs[0].ty,
926 ArgType::Tensor(t) if t.dtype == DType::F32 && t.rank == 2
927 ));
928 }
929
930 #[test]
931 fn unknown_default_domain_op_parses_as_custom() {
932 let bytes = single_node_model("", "TotallyUnknownOp", &[("", 16)]);
933 let custom = parse_single_custom(&bytes);
934
935 assert_eq!(custom.op_type, "TotallyUnknownOp");
936 assert_eq!(custom.domain, "");
937 assert_eq!(custom.opset, 16);
938 }
939
940 #[test]
941 fn builtin_name_in_custom_domain_stays_custom() {
942 let bytes = single_node_model("my.domain", "MatMul", &[("", 16), ("my.domain", 5)]);
945 let custom = parse_single_custom(&bytes);
946
947 assert_eq!(custom.op_type, "MatMul");
948 assert_eq!(custom.domain, "my.domain");
949 assert_eq!(custom.opset, 5);
950 }
951
952 #[test]
953 fn missing_domain_import_falls_back_to_default_opset() {
954 let bytes = single_node_model("no.import.domain", "SomeOp", &[("", 16)]);
956 let custom = parse_single_custom(&bytes);
957
958 assert_eq!(custom.opset, 16);
959 }
960
961 #[test]
962 fn builtin_op_still_resolves_normally() {
963 let bytes = single_node_model("", "Relu", &[("", 16)]);
964 let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
965 assert!(graph.nodes.iter().any(|n| matches!(n, Node::Relu(_))));
966 assert!(!graph.nodes.iter().any(|n| matches!(n, Node::Custom(_))));
967 }
968
969 #[test]
970 fn ai_onnx_import_is_the_default_domain() {
971 let bytes = single_node_model("", "Relu", &[("ai.onnx", 16)]);
974 let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
975 assert!(graph.nodes.iter().any(|n| matches!(n, Node::Relu(_))));
976
977 let bytes = single_node_model("no.import.domain", "SomeOp", &[("ai.onnx", 16)]);
980 assert_eq!(parse_single_custom(&bytes).opset, 16);
981 }
982
983 #[test]
984 fn duplicate_default_domain_spellings_merge_by_max() {
985 for imports in [[("", 13), ("ai.onnx", 17)], [("ai.onnx", 17), ("", 13)]] {
989 let bytes = single_node_model("no.import.domain", "SomeOp", &imports);
990 assert_eq!(
991 parse_single_custom(&bytes).opset,
992 17,
993 "import order {imports:?} changed the resolved opset"
994 );
995 }
996 }
997
998 #[test]
999 fn duplicate_non_default_domain_imports_merge_by_max() {
1000 for imports in [
1003 [("", 16), ("custom.domain", 2), ("custom.domain", 5)],
1004 [("", 16), ("custom.domain", 5), ("custom.domain", 2)],
1005 ] {
1006 let bytes = single_node_model("custom.domain", "SomeOp", &imports);
1007 assert_eq!(
1008 parse_single_custom(&bytes).opset,
1009 5,
1010 "import order {imports:?} changed the resolved opset"
1011 );
1012 }
1013 }
1014
1015 #[test]
1016 fn no_imports_at_all_uses_the_latest_opset() {
1017 let bytes = single_node_model("custom.domain", "SomeOp", &[]);
1020 assert_eq!(parse_single_custom(&bytes).opset, LATEST_DEFAULT_OPSET);
1021 }
1022
1023 #[test]
1024 fn ai_onnx_node_domain_gets_the_default_opset() {
1025 let bytes = single_node_model("ai.onnx", "TotallyUnknownOp", &[("", 16)]);
1026 let custom = parse_single_custom(&bytes);
1027
1028 assert_eq!(custom.opset, 16);
1031 assert_eq!(custom.domain, "");
1034 }
1035
1036 #[test]
1037 fn ml_only_model_needs_no_default_domain_import() {
1038 let bytes = single_node_model("ai.onnx.ml", "TreeEnsembleRegressor", &[("ai.onnx.ml", 1)]);
1042 let custom = parse_single_custom(&bytes);
1043
1044 assert_eq!(custom.op_type, "TreeEnsembleRegressor");
1045 assert_eq!(custom.domain, "ai.onnx.ml");
1046 assert_eq!(custom.opset, 1);
1047 }
1048
1049 #[test]
1050 fn default_domain_node_without_import_errors() {
1051 let bytes = single_node_model("", "Relu", &[("ai.onnx.ml", 1)]);
1054 let err = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap_err();
1055
1056 assert!(matches!(err, Error::MissingOpsetVersion), "got: {err}");
1057 }
1058
1059 fn subgraph_model(use_graphs_field: bool, opset_imports: &[(&str, i64)]) -> Vec<u8> {
1062 let mut inner_node = NodeProto::new();
1063 inner_node.name = "inner".to_string();
1064 inner_node.op_type = "Relu".to_string();
1065 inner_node.input.push("input".to_string());
1066 inner_node.output.push("inner_output".to_string());
1067
1068 let mut inner_graph = GraphProto::new();
1069 inner_graph.name = "inner_graph".to_string();
1070 inner_graph.node.push(inner_node);
1071
1072 let mut attr = crate::protos::AttributeProto::new();
1073 attr.name = "body".to_string();
1074 if use_graphs_field {
1075 attr.type_ = ::protobuf::EnumOrUnknown::new(
1076 crate::protos::attribute_proto::AttributeType::GRAPHS,
1077 );
1078 attr.graphs.push(inner_graph);
1079 } else {
1080 attr.type_ = ::protobuf::EnumOrUnknown::new(
1081 crate::protos::attribute_proto::AttributeType::GRAPH,
1082 );
1083 attr.g = ::protobuf::MessageField::some(inner_graph);
1084 }
1085
1086 let mut node = NodeProto::new();
1087 node.name = "outer".to_string();
1088 node.op_type = "SomeOp".to_string();
1089 node.domain = "custom.domain".to_string();
1090 node.input.push("input".to_string());
1091 node.output.push("output".to_string());
1092 node.attribute.push(attr);
1093
1094 let mut graph = GraphProto::new();
1095 graph.name = "test_graph".to_string();
1096 graph.input.push(tensor_value_info("input", &[2, 3]));
1097 graph.output.push(tensor_value_info("output", &[2, 3]));
1098 graph.node.push(node);
1099
1100 let mut model = ModelProto::new();
1101 model.graph = ::protobuf::MessageField::some(graph);
1102 for (domain, version) in opset_imports {
1103 let mut op = OperatorSetIdProto::new();
1104 op.domain = domain.to_string();
1105 op.version = *version;
1106 model.opset_import.push(op);
1107 }
1108 model.write_to_bytes().unwrap()
1109 }
1110
1111 #[test]
1112 fn default_domain_node_nested_in_subgraph_errors() {
1113 for use_graphs_field in [false, true] {
1117 let bytes = subgraph_model(use_graphs_field, &[("custom.domain", 3)]);
1118 let err = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap_err();
1119
1120 assert!(
1121 matches!(err, Error::MissingOpsetVersion),
1122 "graphs field: {use_graphs_field}, got: {err}"
1123 );
1124 }
1125 }
1126
1127 #[test]
1128 fn custom_domain_subgraph_without_default_domain_nodes_parses() {
1129 for use_graphs_field in [false, true] {
1133 let bytes = subgraph_model(use_graphs_field, &[("custom.domain", 3), ("", 16)]);
1134 let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
1135
1136 assert!(graph.nodes.iter().any(|n| matches!(n, Node::Custom(_))));
1137 }
1138 }
1139
1140 struct RankThreeInference;
1142
1143 impl crate::node::custom::CustomOpInference for RankThreeInference {
1144 fn coverage(
1145 &self,
1146 _op_type: &str,
1147 _domain: &str,
1148 _opset: usize,
1149 ) -> crate::node::custom::HookCoverage {
1150 crate::node::custom::HookCoverage::Covered
1151 }
1152
1153 fn infer(
1154 &self,
1155 node: &crate::node::custom::CustomNode,
1156 ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1157 Ok(Some(vec![
1158 ArgType::Tensor(crate::ir::TensorType::new(
1159 DType::F64,
1160 3,
1161 None
1162 ));
1163 node.outputs.len()
1164 ]))
1165 }
1166 }
1167
1168 #[test]
1169 fn registered_inference_hook_overrides_fallback() {
1170 let bytes = single_node_model(
1171 "custom.domain",
1172 "FftLike",
1173 &[("", 16), ("custom.domain", 2)],
1174 );
1175 let graph = OnnxGraphBuilder::new()
1178 .simplify(false)
1179 .with_custom_op_inference(Arc::new(RankThreeInference))
1180 .parse_bytes(&bytes)
1181 .unwrap();
1182
1183 let custom = graph
1184 .nodes
1185 .iter()
1186 .find_map(|n| match n {
1187 Node::Custom(c) => Some(c),
1188 _ => None,
1189 })
1190 .expect("graph should contain a Custom node");
1191
1192 assert!(matches!(
1194 &custom.outputs[0].ty,
1195 ArgType::Tensor(t) if t.dtype == DType::F64 && t.rank == 3
1196 ));
1197 }
1198
1199 struct NoCoverageInference;
1201
1202 impl crate::node::custom::CustomOpInference for NoCoverageInference {
1203 fn coverage(
1204 &self,
1205 _op_type: &str,
1206 _domain: &str,
1207 _opset: usize,
1208 ) -> crate::node::custom::HookCoverage {
1209 crate::node::custom::HookCoverage::Missing(crate::node::custom::MissingReason::NoHook)
1210 }
1211
1212 fn infer(
1213 &self,
1214 _node: &crate::node::custom::CustomNode,
1215 ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1216 Ok(None)
1217 }
1218 }
1219
1220 #[test]
1221 fn coverage_pre_pass_reports_uncovered_ops() {
1222 let bytes = single_node_model(
1223 "custom.domain",
1224 "FftLike",
1225 &[("", 16), ("custom.domain", 2)],
1226 );
1227 let err = OnnxGraphBuilder::new()
1228 .with_custom_op_inference(Arc::new(NoCoverageInference))
1229 .parse_bytes(&bytes)
1230 .unwrap_err();
1231
1232 assert!(matches!(err, Error::MissingCustomOpHooks(_)));
1233 let msg = format!("{err}");
1234 assert!(msg.contains("custom.domain::FftLike"), "got: {msg}");
1235 assert!(msg.contains("used by 1 node(s)"), "got: {msg}");
1236 assert!(!msg.contains("register"), "got: {msg}");
1239 assert!(msg.trim_end() == msg, "message must not end in whitespace");
1240 }
1241
1242 #[test]
1243 fn coverage_pre_pass_reports_opset_mismatch() {
1244 struct MismatchInference;
1245
1246 impl crate::node::custom::CustomOpInference for MismatchInference {
1247 fn coverage(
1248 &self,
1249 _op_type: &str,
1250 _domain: &str,
1251 _opset: usize,
1252 ) -> crate::node::custom::HookCoverage {
1253 crate::node::custom::HookCoverage::Missing(
1254 crate::node::custom::MissingReason::OpsetMismatch {
1255 supported: crate::node::custom::OpsetRange {
1256 min: 1,
1257 max: Some(1),
1258 },
1259 },
1260 )
1261 }
1262
1263 fn infer(
1264 &self,
1265 _node: &crate::node::custom::CustomNode,
1266 ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1267 Ok(None)
1268 }
1269 }
1270
1271 let bytes = single_node_model(
1272 "custom.domain",
1273 "FftLike",
1274 &[("", 16), ("custom.domain", 3)],
1275 );
1276 let err = OnnxGraphBuilder::new()
1277 .with_custom_op_inference(Arc::new(MismatchInference))
1278 .parse_bytes(&bytes)
1279 .unwrap_err();
1280
1281 let msg = format!("{err}");
1282 assert!(
1283 msg.contains("hook covers opsets 1..=1, model uses 3"),
1284 "got: {msg}"
1285 );
1286 }
1287
1288 #[test]
1289 fn hookless_parse_skips_coverage_pre_pass() {
1290 let bytes = single_node_model(
1293 "custom.domain",
1294 "FftLike",
1295 &[("", 16), ("custom.domain", 2)],
1296 );
1297 assert!(OnnxGraphBuilder::new().parse_bytes(&bytes).is_ok());
1298 }
1299
1300 #[test]
1301 fn hook_error_fails_the_parse() {
1302 struct FailingInference;
1303
1304 impl crate::node::custom::CustomOpInference for FailingInference {
1305 fn coverage(
1306 &self,
1307 _op_type: &str,
1308 _domain: &str,
1309 _opset: usize,
1310 ) -> crate::node::custom::HookCoverage {
1311 crate::node::custom::HookCoverage::Covered
1312 }
1313
1314 fn infer(
1315 &self,
1316 _node: &crate::node::custom::CustomNode,
1317 ) -> Result<Option<Vec<ArgType>>, ProcessError> {
1318 Err(ProcessError::MissingAttribute("n_fft".to_string()))
1319 }
1320 }
1321
1322 let bytes = single_node_model(
1323 "custom.domain",
1324 "FftLike",
1325 &[("", 16), ("custom.domain", 2)],
1326 );
1327 let err = OnnxGraphBuilder::new()
1328 .with_custom_op_inference(Arc::new(FailingInference))
1329 .parse_bytes(&bytes)
1330 .unwrap_err();
1331
1332 let msg = format!("{err}");
1333 assert!(msg.contains("n_fft"), "got: {msg}");
1334 }
1335
1336 fn runtime_reshape_model(output: ValueInfoProto) -> Vec<u8> {
1339 let mut node = NodeProto::new();
1340 node.name = "reshape".to_string();
1341 node.op_type = "Reshape".to_string();
1342 node.input.push("x".to_string());
1343 node.input.push("s".to_string());
1344 node.output.push(output.name.clone());
1345
1346 let mut s_dim = tensor_shape_proto::Dimension::new();
1347 s_dim.set_dim_param("N".to_string());
1348 let mut s_shape = TensorShapeProto::new();
1349 s_shape.dim.push(s_dim);
1350 let mut s_tensor = type_proto::Tensor::new();
1351 s_tensor.elem_type = 7; s_tensor.shape = ::protobuf::MessageField::some(s_shape);
1353 let mut s_ty = TypeProto::new();
1354 s_ty.set_tensor_type(s_tensor);
1355 let mut s = ValueInfoProto::new();
1356 s.name = "s".to_string();
1357 s.type_ = ::protobuf::MessageField::some(s_ty);
1358
1359 let mut graph = GraphProto::new();
1360 graph.name = "test_graph".to_string();
1361 graph.input.push(tensor_value_info("x", &[2, 3]));
1362 graph.input.push(s);
1363 graph.output.push(output);
1364 graph.node.push(node);
1365
1366 let mut model = ModelProto::new();
1367 model.graph = ::protobuf::MessageField::some(graph);
1368 let mut op = OperatorSetIdProto::new();
1369 op.version = 16;
1370 model.opset_import.push(op);
1371 model.write_to_bytes().unwrap()
1372 }
1373
1374 #[test]
1378 fn runtime_reshape_uses_declared_rank_of_sanitized_output() {
1379 let bytes = runtime_reshape_model(tensor_value_info("Mean", &[3, 2]));
1380 let graph = OnnxGraphBuilder::new().parse_bytes(&bytes).unwrap();
1381
1382 assert!(
1383 matches!(&graph.outputs[0].ty, ArgType::Tensor(t) if t.rank == 2),
1384 "got: {:?}",
1385 graph.outputs[0].ty
1386 );
1387 }
1388
1389 #[test]
1392 fn runtime_reshape_with_shapeless_output_declaration_errors() {
1393 let mut output = tensor_value_info("y", &[]);
1394 output
1395 .type_
1396 .mut_or_insert_default()
1397 .mut_tensor_type()
1398 .shape
1399 .clear();
1400
1401 let err = OnnxGraphBuilder::new()
1402 .parse_bytes(&runtime_reshape_model(output))
1403 .unwrap_err();
1404
1405 let msg = format!("{err}");
1406 assert!(
1407 msg.contains("output rank cannot be determined"),
1408 "got: {msg}"
1409 );
1410 }
1411}