1use crate::{
7 ArgType,
8 ir::{Argument, Node, RawNode},
9};
10use std::collections::HashMap;
11
12pub use crate::registry::get_processor_registry;
14
15#[derive(Debug, Clone)]
21pub enum InputSpec {
22 Exact(usize),
24 AtLeast(usize),
26 Range(usize, usize),
28 OpsetDependent(Vec<(usize, InputSpec)>),
30}
31
32#[allow(dead_code)]
34#[derive(Debug, Clone)]
35pub enum OutputSpec {
36 Exact(usize),
38 Range(usize, usize),
40 OpsetDependent(Vec<(usize, OutputSpec)>),
42}
43
44#[derive(Debug, Clone)]
46pub struct NodeSpec {
47 pub min_opset: usize,
49 pub max_opset: Option<usize>,
51 pub inputs: InputSpec,
53 pub outputs: OutputSpec,
55}
56
57impl Default for NodeSpec {
58 fn default() -> Self {
59 Self {
60 min_opset: 1,
61 max_opset: None,
62 inputs: InputSpec::AtLeast(0),
63 outputs: OutputSpec::Range(0, 2147483647),
64 }
65 }
66}
67
68#[derive(Debug, Default, Clone)]
70pub struct InputPreferences {
71 preferences: HashMap<String, Vec<ArgPreference>>,
72}
73
74#[derive(Debug, Clone)]
75pub enum ArgPreference {
76 ScalarNative,
78 Shape,
79 Tensor,
80}
81
82impl InputPreferences {
83 pub fn new() -> Self {
84 Self::default()
85 }
86
87 pub fn add(mut self, input_name: impl Into<String>, ty: ArgPreference) -> Self {
88 self.preferences
89 .entry(input_name.into())
90 .or_default()
91 .push(ty);
92 self
93 }
94
95 pub fn get(&self, input_name: &str) -> &[ArgPreference] {
96 self.preferences
97 .get(input_name)
98 .map_or(&[], |v| v.as_slice())
99 }
100}
101
102#[derive(Debug, Default, Clone)]
104pub struct OutputPreferences {
105 requests: HashMap<String, Vec<(String, ArgPreference)>>,
107}
108
109impl OutputPreferences {
110 pub fn new() -> Self {
111 Self::default()
112 }
113
114 pub fn add(
115 &mut self,
116 output_name: impl Into<String>,
117 consumer: impl Into<String>,
118 ty: ArgPreference,
119 ) {
120 self.requests
121 .entry(output_name.into())
122 .or_default()
123 .push((consumer.into(), ty));
124 }
125
126 pub fn get(&self, output_name: &str) -> &[(String, ArgPreference)] {
127 self.requests.get(output_name).map_or(&[], |v| v.as_slice())
128 }
129}
130
131#[derive(Debug, Clone)]
133pub enum ProcessError {
134 UnsupportedOpset {
135 required: usize,
136 actual: usize,
137 },
138 MissingInput(String),
139 MissingOutput(String),
140 InvalidInputCount {
141 expected: usize,
142 actual: usize,
143 },
144 InvalidOutputCount {
145 expected: usize,
146 actual: usize,
147 },
148 TypeMismatch {
149 expected: String,
150 actual: String,
151 },
152 ConflictingPreferences {
153 output: String,
154 details: Vec<String>,
155 },
156 MissingAttribute(String),
157 InvalidAttribute {
158 name: String,
159 reason: String,
160 },
161 UnsupportedOps(Vec<String>),
162 Custom(String),
163}
164
165impl std::fmt::Display for ProcessError {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 match self {
168 ProcessError::UnsupportedOpset { required, actual } => {
169 write!(
170 f,
171 "Unsupported opset version: requires {required}, got {actual}"
172 )
173 }
174 ProcessError::MissingInput(name) => write!(f, "Missing input: {name}"),
175 ProcessError::MissingOutput(name) => write!(f, "Missing output: {name}"),
176 ProcessError::InvalidInputCount { expected, actual } => {
177 write!(f, "Invalid input count: expected {expected}, got {actual}")
178 }
179 ProcessError::InvalidOutputCount { expected, actual } => {
180 write!(f, "Invalid output count: expected {expected}, got {actual}")
181 }
182 ProcessError::TypeMismatch { expected, actual } => {
183 write!(f, "Type mismatch: expected {expected}, got {actual}")
184 }
185 ProcessError::ConflictingPreferences { output, details } => {
186 write!(
187 f,
188 "Conflicting preferences for output '{output}': {}",
189 details.join(", ")
190 )
191 }
192 ProcessError::MissingAttribute(name) => write!(f, "Missing attribute: {name}"),
193 ProcessError::InvalidAttribute { name, reason } => {
194 write!(f, "Invalid attribute '{name}': {reason}")
195 }
196 ProcessError::UnsupportedOps(ops) => {
197 write!(f, "Unsupported ONNX operation(s): {}", ops.join(", "))
198 }
199 ProcessError::Custom(msg) => write!(f, "{msg}"),
200 }
201 }
202}
203
204pub trait NodeProcessor: Send + Sync {
206 type Config: Clone;
210
211 fn spec(&self) -> NodeSpec {
216 NodeSpec::default()
217 }
218
219 fn input_preferences(
223 &self,
224 _node: &RawNode,
225 _opset: usize,
226 ) -> Result<Option<InputPreferences>, ProcessError> {
227 Ok(None)
228 }
229
230 fn lift_constants(&self, _node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
232 Ok(())
233 }
234
235 fn infer_types(
239 &self,
240 node: &mut RawNode,
241 opset: usize,
242 output_preferences: &OutputPreferences,
243 ) -> Result<(), ProcessError>;
244
245 fn extract_config(&self, _node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError>
255 where
256 Self: Sized,
257 {
258 Err(ProcessError::Custom(format!(
259 "extract_config not implemented for {} - processors with non-unit Config type must implement this method",
260 std::any::type_name::<Self>()
261 )))
262 }
263
264 fn is_noop(&self, _node: &RawNode) -> bool {
270 false
271 }
272
273 fn build_node(&self, node: RawNode, _opset: usize) -> Result<Node, ProcessError>
283 where
284 Self: Sized,
285 {
286 Err(ProcessError::Custom(format!(
287 "build_node not implemented for {:?} - each processor must implement this method",
288 node.node_type
289 )))
290 }
291}
292
293pub(crate) struct DefaultProcessor;
297
298impl NodeProcessor for DefaultProcessor {
299 type Config = ();
300
301 fn infer_types(
302 &self,
303 node: &mut RawNode,
304 _opset: usize,
305 _output_preferences: &OutputPreferences,
306 ) -> Result<(), ProcessError> {
307 same_as_input(node);
309 Ok(())
310 }
311}
312
313pub fn validate_opset(opset: usize, min_version: usize) -> Result<(), ProcessError> {
319 if opset < min_version {
320 Err(ProcessError::UnsupportedOpset {
321 required: min_version,
322 actual: opset,
323 })
324 } else {
325 Ok(())
326 }
327}
328
329pub fn validate_no_rank_zero_tensors(node: &RawNode) -> Result<(), ProcessError> {
334 use crate::ir::ArgType;
335
336 for output in &node.outputs {
338 if let ArgType::Tensor(tensor) = &output.ty
339 && tensor.rank == 0
340 {
341 return Err(ProcessError::Custom(format!(
342 "Invalid type inference: Node '{}' output '{}' has rank-0 tensor. \
343 Rank-0 tensors should be Scalar type instead.",
344 node.name, output.name
345 )));
346 }
347 }
348
349 Ok(())
350}
351
352pub fn validate_uniform_group(
360 node: &RawNode,
361 indices: &[usize],
362 required: &[usize],
363) -> Result<(), ProcessError> {
364 for &index in required {
365 let provided = node.inputs.get(index).is_some_and(|arg| !arg.is_optional());
366 if !provided {
367 return Err(ProcessError::Custom(format!(
368 "Node '{}': input #{index} is required but was not provided",
369 node.name
370 )));
371 }
372 }
373
374 let mut first: Option<(usize, bool)> = None;
375 for &index in indices {
376 let Some(arg) = node.inputs.get(index) else {
377 continue;
378 };
379 if arg.is_optional() {
380 continue;
381 }
382 let runtime = arg.is_dynamic();
383 match first {
384 None => first = Some((index, runtime)),
385 Some((first_index, first_runtime)) if first_runtime != runtime => {
386 let (build, run) = if runtime {
387 (first_index, index)
388 } else {
389 (index, first_index)
390 };
391 return Err(ProcessError::Custom(format!(
392 "Node '{}': input #{build} is a build-time value while input #{run} is \
393 supplied at run time. They are consumed as a group, so they must both \
394 be initializers or both be graph inputs.",
395 node.name
396 )));
397 }
398 _ => {}
399 }
400 }
401 Ok(())
402}
403
404pub fn validate_group_not_split(node: &RawNode, indices: &[usize]) -> Result<(), ProcessError> {
412 let provided = |index: &usize| {
413 node.inputs
414 .get(*index)
415 .filter(|arg| !arg.is_optional())
416 .map(|arg| (*index, arg))
417 };
418 let lifted = indices
419 .iter()
420 .filter_map(provided)
421 .find(|(_, arg)| arg.is_static());
422 let runtime = indices
423 .iter()
424 .filter_map(provided)
425 .find(|(_, arg)| arg.is_dynamic());
426 if let (Some((build, _)), Some((run, _))) = (lifted, runtime) {
427 return Err(ProcessError::Custom(format!(
428 "Node '{}': input #{build} is a build-time value captured from an outer graph \
429 while input #{run} is supplied at run time. They are consumed as a group, so \
430 this mixture is not supported.",
431 node.name
432 )));
433 }
434 Ok(())
435}
436
437pub fn lift_all_or_none(node: &mut RawNode, indices: &[usize]) -> Result<(), ProcessError> {
453 let liftable = |index: &usize| match node.inputs.get(*index) {
454 Some(arg) => arg.is_optional() || arg.is_constant() || arg.is_static(),
455 None => true,
456 };
457 if !indices.iter().all(liftable) {
458 return Ok(());
459 }
460
461 let to_lift: Vec<usize> = indices
462 .iter()
463 .copied()
464 .filter(|&index| node.inputs.get(index).is_some_and(|arg| arg.is_constant()))
465 .collect();
466 let restore: Vec<Argument> = to_lift
467 .iter()
468 .map(|&index| node.inputs[index].clone())
469 .collect();
470
471 for &index in &to_lift {
472 if let Err(e) = node.inputs[index].to_static() {
473 for (&index, arg) in to_lift.iter().zip(restore) {
474 node.inputs[index] = arg;
475 }
476 return Err(e);
477 }
478 }
479 Ok(())
480}
481
482pub fn validate_node_spec(
488 node: &RawNode,
489 opset: usize,
490 spec: &NodeSpec,
491) -> Result<(), ProcessError> {
492 if opset < spec.min_opset {
494 return Err(ProcessError::UnsupportedOpset {
495 required: spec.min_opset,
496 actual: opset,
497 });
498 }
499 if let Some(max) = spec.max_opset
500 && opset > max
501 {
502 return Err(ProcessError::UnsupportedOpset {
503 required: max,
504 actual: opset,
505 });
506 }
507
508 validate_input_spec(node, opset, &spec.inputs)?;
510
511 validate_output_spec(node, opset, &spec.outputs)?;
513
514 Ok(())
515}
516
517pub(crate) fn validate_input_spec(
519 node: &RawNode,
520 opset: usize,
521 spec: &InputSpec,
522) -> Result<(), ProcessError> {
523 let actual = get_onnx_input_count(node);
526
527 match spec {
528 InputSpec::Exact(expected) => {
529 if actual != *expected {
530 return Err(ProcessError::InvalidInputCount {
531 expected: *expected,
532 actual,
533 });
534 }
535 }
536 InputSpec::AtLeast(min) => {
537 if actual < *min {
538 return Err(ProcessError::InvalidInputCount {
539 expected: *min,
540 actual,
541 });
542 }
543 }
544 InputSpec::Range(min, max) => {
545 if actual < *min || actual > *max {
546 return Err(ProcessError::InvalidInputCount {
547 expected: *min, actual,
549 });
550 }
551 }
552 InputSpec::OpsetDependent(specs) => {
553 let applicable_spec = specs
555 .iter()
556 .filter(|(opset_version, _)| *opset_version <= opset)
557 .max_by_key(|(opset_version, _)| opset_version)
558 .map(|(_, spec)| spec);
559
560 if let Some(spec) = applicable_spec {
561 validate_input_spec(node, opset, spec)?;
562 }
563 }
564 }
565
566 Ok(())
567}
568
569fn validate_output_spec(
571 node: &RawNode,
572 opset: usize,
573 spec: &OutputSpec,
574) -> Result<(), ProcessError> {
575 let actual = node.outputs.len();
576
577 match spec {
578 OutputSpec::Exact(expected) => {
579 if actual != *expected {
580 return Err(ProcessError::InvalidOutputCount {
581 expected: *expected,
582 actual,
583 });
584 }
585 }
586 OutputSpec::Range(min, max) => {
587 if actual < *min || actual > *max {
588 return Err(ProcessError::InvalidOutputCount {
589 expected: *min, actual,
591 });
592 }
593 }
594 OutputSpec::OpsetDependent(specs) => {
595 let applicable_spec = specs
597 .iter()
598 .filter(|(opset_version, _)| *opset_version <= opset)
599 .max_by_key(|(opset_version, _)| opset_version)
600 .map(|(_, spec)| spec);
601
602 if let Some(spec) = applicable_spec {
603 validate_output_spec(node, opset, spec)?;
604 }
605 }
606 }
607
608 Ok(())
609}
610
611pub(crate) fn get_onnx_input_count(node: &RawNode) -> usize {
618 use crate::ir::AttributeValue;
619 match node.attrs.get("__onnx_input_count") {
620 Some(AttributeValue::Int64(n)) => *n as usize,
621 Some(other) => {
622 log::warn!(
623 "__onnx_input_count attribute has unexpected type {:?} in node '{}', falling back to inputs.len()",
624 other,
625 node.name
626 );
627 node.inputs.len()
628 }
629 None => node.inputs.len(),
630 }
631}
632
633pub fn build_outer_scope_from_inputs(node: &RawNode) -> crate::ir::OuterScopeTypes {
646 use crate::ir::AttributeValue;
647
648 let onnx_input_count = get_onnx_input_count(node);
649
650 let scope_ref_names: Vec<String> = node
652 .attrs
653 .get("__scope_ref_names")
654 .and_then(|v| match v {
655 AttributeValue::Strings(names) => Some(names.clone()),
656 _ => None,
657 })
658 .unwrap_or_default();
659
660 let mut outer_scope: HashMap<String, crate::ir::Argument> = HashMap::new();
662 let scope_ref_inputs: Vec<_> = node.inputs.iter().skip(onnx_input_count).collect();
663
664 for (i, input) in scope_ref_inputs.iter().enumerate() {
665 let name = scope_ref_names
667 .get(i)
668 .cloned()
669 .unwrap_or_else(|| input.name.clone());
670 log::debug!(
671 "Adding outer-scope arg: {} -> type={:?}, value_source={:?}, has_store={}",
672 name,
673 input.ty,
674 input.value_source,
675 input.value_store.is_some()
676 );
677 outer_scope.insert(name, (*input).clone());
679 }
680
681 outer_scope
682}
683
684pub fn same_as_input(node: &mut RawNode) {
686 node.outputs[0].ty = node.inputs[0].ty.clone();
687}
688
689pub fn compute_broadcast_rank(inputs: &[crate::ir::Argument]) -> usize {
691 use crate::ir::ArgType;
692 use core::cmp::max;
693
694 inputs.iter().fold(0, |acc, input| match &input.ty {
695 ArgType::Tensor(tensor) => max(acc, tensor.rank),
696 ArgType::ScalarTensor(_) => max(acc, 1),
697 ArgType::ScalarNative(_) => acc,
698 ArgType::Shape(_) => max(acc, 1),
699 })
700}
701
702pub fn logical_shape(arg_type: &ArgType, static_shape: Vec<Option<usize>>) -> Vec<Option<usize>> {
703 match arg_type {
704 ArgType::Tensor(_) => static_shape,
705 ArgType::ScalarTensor(_) => vec![Some(1)],
706 ArgType::ScalarNative(_) => vec![],
707 ArgType::Shape(r) => vec![Some(*r)],
708 }
709}
710
711pub fn compute_broadcast_static_shape(
713 inputs: &[crate::ir::Argument],
714) -> Option<Vec<Option<usize>>> {
715 let static_shapes: Vec<_> = inputs
716 .iter()
717 .map(|input| {
718 let concrete = input
719 .ty
720 .static_shape()
721 .cloned()
722 .unwrap_or_else(|| vec![None; input.ty.rank()]);
723 logical_shape(&input.ty, concrete)
724 })
725 .collect();
726
727 if static_shapes.is_empty() {
728 return None;
729 }
730
731 if static_shapes.len() == 1 {
732 let broadcast_rank = compute_broadcast_rank(inputs);
733 if broadcast_rank == static_shapes[0].len() {
734 return Some(static_shapes[0].clone());
735 }
736 return None;
737 }
738
739 if static_shapes.windows(2).all(|w| w[0] == w[1]) {
740 return Some(static_shapes[0].clone());
741 }
742
743 let max_rank = static_shapes.iter().map(|s| s.len()).max()?;
744 let mut result: Vec<Option<usize>> = vec![Some(1); max_rank];
745
746 for shape in &static_shapes {
747 let offset = max_rank - shape.len();
748 for (i, dim) in shape.iter().enumerate() {
749 let result_idx = offset + i;
750
751 match (result[result_idx], *dim) {
752 (Some(1), d) => result[result_idx] = d,
754 (_, Some(1)) => {}
755 (None, d) => result[result_idx] = d,
758 (Some(_), None) => {}
759 (Some(cur), Some(d)) if cur == d => {}
761 (Some(_), Some(_)) => return None,
763 }
764 }
765 }
766
767 Some(result)
768}
769
770pub fn broadcast_output_type(
782 inputs: &[crate::ir::Argument],
783 output_dtype: Option<crate::ir::DType>,
784) -> crate::ir::ArgType {
785 use crate::ir::ArgType;
786
787 let has_real_tensor = inputs
788 .iter()
789 .any(|input| matches!(&input.ty, ArgType::Tensor(_)));
790
791 let has_shape = inputs
792 .iter()
793 .any(|input| matches!(&input.ty, ArgType::Shape(_)));
794
795 if has_shape && !has_real_tensor {
796 let shape_rank = compute_broadcast_static_shape(inputs)
798 .and_then(|s| s.first().copied().flatten())
799 .unwrap_or_else(|| {
800 inputs
803 .iter()
804 .filter_map(|input| match &input.ty {
805 ArgType::Shape(rank) => Some(*rank),
806 _ => None,
807 })
808 .max()
809 .unwrap_or(1)
810 });
811
812 return ArgType::Shape(shape_rank);
813 }
814
815 let max_rank = compute_broadcast_rank(inputs);
816
817 let dtype = output_dtype.unwrap_or_else(|| {
818 inputs
819 .iter()
820 .find_map(|input| match &input.ty {
821 ArgType::Tensor(tensor) => Some(tensor.dtype),
822 ArgType::ScalarTensor(dtype) => Some(*dtype),
823 _ => None,
824 })
825 .unwrap_or_else(|| inputs[0].ty.elem_type())
826 });
827
828 if max_rank == 0 {
829 ArgType::ScalarNative(dtype)
830 } else if !has_real_tensor && max_rank == 1 {
831 ArgType::ScalarTensor(dtype)
832 } else {
833 let static_shape = compute_broadcast_static_shape(inputs);
834 ArgType::Tensor(crate::ir::TensorType {
835 dtype,
836 rank: max_rank,
837 static_shape,
838 })
839 }
840}
841
842pub fn same_as_input_broadcast(node: &mut RawNode) {
844 node.outputs[0].ty = broadcast_output_type(&node.inputs, None);
845}
846
847#[cfg(test)]
848mod tests {
849 use super::*;
850 use crate::ir::{ArgType, Argument, DType, NodeType, RawNode, TensorType};
851 use crate::registry::ProcessorRegistry;
852
853 struct TestProcessor;
854
855 impl NodeProcessor for TestProcessor {
856 type Config = ();
857
858 fn infer_types(
859 &self,
860 node: &mut RawNode,
861 _opset: usize,
862 _output_preferences: &OutputPreferences,
863 ) -> Result<(), ProcessError> {
864 if !node.inputs.is_empty() && !node.outputs.is_empty() {
866 node.outputs[0].ty = node.inputs[0].ty.clone();
867 }
868 Ok(())
869 }
870 }
871
872 #[test]
873 fn test_infer_outputs() {
874 let processor = TestProcessor;
875 let prefs = OutputPreferences::new();
876 let mut node = RawNode {
877 custom_identity: None,
878 node_type: NodeType::Add,
879 name: "test_node".to_string(),
880 inputs: vec![Argument {
881 name: "input".to_string(),
882 ty: ArgType::Tensor(TensorType {
883 dtype: DType::F32,
884 rank: 2,
885 static_shape: None,
886 }),
887 value_source: crate::ir::ValueSource::Dynamic,
888 value_store: None,
889 }],
890 outputs: vec![Argument {
891 name: "output".to_string(),
892 ty: ArgType::default(),
893 value_source: crate::ir::ValueSource::Dynamic,
894 value_store: None,
895 }],
896 attrs: Default::default(),
897 };
898
899 NodeProcessor::infer_types(&processor, &mut node, 16, &prefs).unwrap();
900
901 assert_eq!(node.outputs[0].ty, node.inputs[0].ty);
903 }
904
905 #[test]
906 fn test_processor_registry() {
907 let mut registry = ProcessorRegistry::new();
908
909 registry.register(NodeType::Add, Box::new(TestProcessor));
911
912 let add_processor = registry.get(&NodeType::Add);
914 let sub_processor = registry.get(&NodeType::Sub);
915
916 assert!(std::ptr::addr_of!(*add_processor) != std::ptr::addr_of!(*sub_processor));
920 }
921
922 #[test]
923 fn test_default_processor() {
924 let processor = DefaultProcessor;
925 let prefs = OutputPreferences::new();
926 let mut node = RawNode {
927 custom_identity: None,
928 node_type: NodeType::Relu,
929 name: "test_relu".to_string(),
930 inputs: vec![Argument {
931 name: "input".to_string(),
932 ty: ArgType::Tensor(TensorType {
933 dtype: DType::F32,
934 rank: 3,
935 static_shape: None,
936 }),
937 value_source: crate::ir::ValueSource::Dynamic,
938 value_store: None,
939 }],
940 outputs: vec![Argument {
941 name: "output".to_string(),
942 ty: ArgType::default(),
943 value_source: crate::ir::ValueSource::Dynamic,
944 value_store: None,
945 }],
946 attrs: Default::default(),
947 };
948
949 NodeProcessor::infer_types(&processor, &mut node, 16, &prefs).unwrap();
950
951 match &node.outputs[0].ty {
953 ArgType::Tensor(t) => {
954 assert_eq!(t.rank, 3);
955 assert_eq!(t.dtype, DType::F32);
956 }
957 _ => panic!("Expected tensor output"),
958 }
959 }
960
961 #[test]
962 fn test_broadcast_static_shape_rank_mismatch_right_aligns() {
963 let inputs = vec![
966 Argument {
967 name: "a".to_string(),
968 ty: ArgType::Tensor(TensorType {
969 dtype: DType::F32,
970 rank: 1,
971 static_shape: Some(vec![Some(2)]),
972 }),
973 value_source: crate::ir::ValueSource::Dynamic,
974 value_store: None,
975 },
976 Argument {
977 name: "b".to_string(),
978 ty: ArgType::Tensor(TensorType {
979 dtype: DType::F32,
980 rank: 4,
981 static_shape: None,
982 }),
983 value_source: crate::ir::ValueSource::Dynamic,
984 value_store: None,
985 },
986 ];
987
988 let result = compute_broadcast_static_shape(&inputs).expect("rank-aligned result");
989 assert_eq!(result.len(), compute_broadcast_rank(&inputs));
990 assert_eq!(result, vec![None, None, None, Some(2)]);
991 }
992
993 #[test]
994 fn test_broadcast_static_shape_matching_rank() {
995 let inputs = vec![
997 Argument {
998 name: "a".to_string(),
999 ty: ArgType::Tensor(TensorType {
1000 dtype: DType::F32,
1001 rank: 3,
1002 static_shape: Some(vec![Some(2), Some(3), Some(4)]),
1003 }),
1004 value_source: crate::ir::ValueSource::Dynamic,
1005 value_store: None,
1006 },
1007 Argument {
1008 name: "b".to_string(),
1009 ty: ArgType::Tensor(TensorType {
1010 dtype: DType::F32,
1011 rank: 3,
1012 static_shape: None,
1013 }),
1014 value_source: crate::ir::ValueSource::Dynamic,
1015 value_store: None,
1016 },
1017 ];
1018
1019 let result = compute_broadcast_static_shape(&inputs);
1020 assert_eq!(result, Some(vec![Some(2), Some(3), Some(4)]));
1021 }
1022}
1023
1024#[cfg(test)]
1025mod lift_all_or_none_tests {
1026 use super::lift_all_or_none;
1027 use crate::ir::NodeType;
1028 use crate::node::test_utils::TestNodeBuilder;
1029
1030 #[test]
1032 fn absent_tail_does_not_block_the_group() {
1033 let mut node = TestNodeBuilder::new(NodeType::Gru, "test_gru")
1034 .input_tensor_f32("X", 3, Some(vec![10, 2, 4]))
1035 .input_tensor_f32_data("W", vec![0.0; 12], vec![1, 3, 4])
1036 .input_tensor_f32_data("R", vec![0.0; 9], vec![1, 3, 3])
1037 .output_tensor_f32("Y", 4, None)
1038 .build_with_graph_data(14);
1039
1040 lift_all_or_none(&mut node, &[1, 2, 3]).unwrap();
1041
1042 assert!(node.inputs[1].is_static());
1043 assert!(node.inputs[2].is_static());
1044 }
1045
1046 #[test]
1049 fn lifting_twice_is_a_no_op() {
1050 let mut node = TestNodeBuilder::new(NodeType::Gru, "test_gru")
1051 .input_tensor_f32("X", 3, Some(vec![10, 2, 4]))
1052 .input_tensor_f32_data("W", vec![0.0; 12], vec![1, 3, 4])
1053 .input_tensor_f32_data("R", vec![0.0; 9], vec![1, 3, 3])
1054 .output_tensor_f32("Y", 4, None)
1055 .build_with_graph_data(14);
1056
1057 lift_all_or_none(&mut node, &[1, 2, 3]).unwrap();
1058 let after_first = node.inputs[1].value_source;
1059
1060 lift_all_or_none(&mut node, &[1, 2, 3]).expect("a second pass must not error");
1061
1062 assert_eq!(node.inputs[1].value_source, after_first);
1063 }
1064}