Skip to main content

onnx_ir/
processor.rs

1//! Node processor trait and infrastructure for node-centric processing.
2//!
3//! This module defines the `NodeProcessor` trait with support for type preferences
4//! and proper error handling.
5
6use crate::{
7    ArgType,
8    ir::{Argument, Node, RawNode},
9};
10use std::collections::HashMap;
11
12// Re-export registry types for backward compatibility
13pub use crate::registry::get_processor_registry;
14
15// ============================================================================
16// Node Specification System
17// ============================================================================
18
19/// Specification for input count validation
20#[derive(Debug, Clone)]
21pub enum InputSpec {
22    /// Exact count required
23    Exact(usize),
24    /// Minimum count required
25    AtLeast(usize),
26    /// Range of valid counts (min, max inclusive)
27    Range(usize, usize),
28    /// Different specs for different opset versions (opset_version, spec)
29    OpsetDependent(Vec<(usize, InputSpec)>),
30}
31
32/// Specification for output count validation
33#[allow(dead_code)]
34#[derive(Debug, Clone)]
35pub enum OutputSpec {
36    /// Exact count required
37    Exact(usize),
38    /// Range of valid counts (min, max inclusive)
39    Range(usize, usize),
40    /// Different specs for different opset versions (opset_version, spec)
41    OpsetDependent(Vec<(usize, OutputSpec)>),
42}
43
44/// Specification for node validation and metadata
45#[derive(Debug, Clone)]
46pub struct NodeSpec {
47    /// Minimum supported opset version
48    pub min_opset: usize,
49    /// Maximum supported opset version (None = no max)
50    pub max_opset: Option<usize>,
51    /// Input count validation
52    pub inputs: InputSpec,
53    /// Output count validation
54    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/// Type preferences for node inputs
69#[derive(Debug, Default, Clone)]
70pub struct InputPreferences {
71    preferences: HashMap<String, Vec<ArgPreference>>,
72}
73
74#[derive(Debug, Clone)]
75pub enum ArgPreference {
76    /// Must be native scalar (for shape ops, arange bounds, conditions, indices)
77    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/// Type preferences requested by consumers for a node's outputs
103#[derive(Debug, Default, Clone)]
104pub struct OutputPreferences {
105    // output_name -> [(consumer_name, requested_type)]
106    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/// Errors that can occur during node processing
132#[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
204/// Node-specific processing logic for type inference and configuration extraction
205pub trait NodeProcessor: Send + Sync {
206    /// Associated config type for this processor
207    ///
208    /// For operations without config, use `()` as the type.
209    type Config: Clone;
210
211    /// Return the node specification for validation
212    ///
213    /// This defines the supported opset versions, input/output counts, etc.
214    /// Validation is automatically performed before processing.
215    fn spec(&self) -> NodeSpec {
216        NodeSpec::default()
217    }
218
219    /// Declare preferred types for inputs (propagated to producers as `output_preferences`)
220    ///
221    /// Preferences are requests, not requirements. Producers may honor them (e.g., Constant→Shape).
222    fn input_preferences(
223        &self,
224        _node: &RawNode,
225        _opset: usize,
226    ) -> Result<Option<InputPreferences>, ProcessError> {
227        Ok(None)
228    }
229
230    /// Convert constant inputs to static values (embedded in config, unreferenced constants removed later)
231    fn lift_constants(&self, _node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
232        Ok(())
233    }
234
235    /// Infer output types given preferences from consumers
236    ///
237    /// This method should call `extract_config()` internally if it needs the config.
238    fn infer_types(
239        &self,
240        node: &mut RawNode,
241        opset: usize,
242        output_preferences: &OutputPreferences,
243    ) -> Result<(), ProcessError>;
244
245    /// Extract config dynamically (not cached in RawNode)
246    ///
247    /// This is called by `infer_types()` and `build_node()` as needed.
248    /// Processors with non-trivial config must implement this method.
249    ///
250    /// # Default Implementation
251    ///
252    /// The default implementation returns an error. Only processors with `type Config = ()`
253    /// should rely on never calling this method.
254    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    /// Returns true if this node is a no-op (output equals input).
265    ///
266    /// When true, the node will be eliminated during post-processing and its output
267    /// rewired to its first input, similar to Identity elimination.
268    /// Called after type inference when input/output types are known.
269    fn is_noop(&self, _node: &RawNode) -> bool {
270        false
271    }
272
273    /// Build the final Node enum from a RawNode
274    ///
275    /// This method converts the RawNode into the final immutable Node enum.
276    /// It should call `extract_config()` internally to get the config.
277    ///
278    /// # Default Implementation
279    ///
280    /// The default implementation returns an error naming the node type.
281    /// Each processor should implement this method to build its specific Node variant.
282    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
293/// Default processor for nodes without specific implementations.
294///
295/// This processor passes through the input type to output.
296pub(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        // Default: preserve input type
308        same_as_input(node);
309        Ok(())
310    }
311}
312
313// ============================================================================
314// Processor Utilities
315// ============================================================================
316
317/// Validate opset version
318pub 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
329/// Validate that no rank-0 tensors exist in the node
330///
331/// Rank-0 tensors should be represented as Scalars instead.
332/// This is an invariant of the ONNX IR - there should never be Tensor(rank=0) in the graph.
333pub fn validate_no_rank_zero_tensors(node: &RawNode) -> Result<(), ProcessError> {
334    use crate::ir::ArgType;
335
336    // Check all outputs for rank-0 tensors
337    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
352/// Validate the group of inputs that [`lift_all_or_none`] treats as a unit.
353///
354/// `required` names the members that must be provided; the rest may be absent or left
355/// optional. Every provided member must agree on where its value comes from, because a
356/// consumer takes the group either entirely at build time or entirely at run time and
357/// has nowhere to put a mixture. A subgraph is the way one arises: a body that captures
358/// an already-lifted outer value alongside a body input.
359pub 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
404/// Reject a group that pairs an already-lifted input with one supplied at run time.
405///
406/// For operators whose codegen can read a whole group at run time, a constant next to a
407/// graph input is fine: [`lift_all_or_none`] leaves both unlifted and named. An input that
408/// arrives already `Static` cannot be un-lifted, though, so it has no runtime name to be
409/// read by. A subgraph is the way one arises: a body that captures an already-lifted outer
410/// value alongside a body input. Stricter operators use [`validate_uniform_group`].
411pub 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
437/// Lift the inputs at `indices` to static values, but only if every one of them can be.
438///
439/// Some operators split a group of inputs across the same piece of generated code, so
440/// codegen needs them to be uniformly static or uniformly named. Lifting only part of
441/// the group would leave the rest referring to an input whose name `to_static` cleared.
442/// Absent and optional inputs count as liftable, so a missing tail does not block the
443/// group.
444///
445/// Idempotent: `lift_constants` re-runs after no-op elimination
446/// (`phases/post_processing.rs`). An already-lifted input is `Static`, which is liftable
447/// in the sense that matters - it is already where this wants it - so a second pass over
448/// a fully lifted group is a no-op rather than an error.
449///
450/// Atomic: if any `to_static` fails, the group is restored, so a caller that logs the
451/// error rather than propagating it does not observe a half-lifted node.
452pub 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
482// ============================================================================
483// NodeSpec Validation
484// ============================================================================
485
486/// Validate node against its specification
487pub fn validate_node_spec(
488    node: &RawNode,
489    opset: usize,
490    spec: &NodeSpec,
491) -> Result<(), ProcessError> {
492    // Validate opset version
493    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 count
509    validate_input_spec(node, opset, &spec.inputs)?;
510
511    // Validate output count
512    validate_output_spec(node, opset, &spec.outputs)?;
513
514    Ok(())
515}
516
517/// Validate input count against specification
518pub(crate) fn validate_input_spec(
519    node: &RawNode,
520    opset: usize,
521    spec: &InputSpec,
522) -> Result<(), ProcessError> {
523    // Use __onnx_input_count if available (for control flow nodes with outer-scope refs)
524    // This ensures we only validate the original ONNX inputs, not extra scope refs
525    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, // Report minimum as expected
548                    actual,
549                });
550            }
551        }
552        InputSpec::OpsetDependent(specs) => {
553            // Find the applicable spec for this opset (use the highest opset <= current)
554            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
569/// Validate output count against specification
570fn 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, // Report minimum as expected
590                    actual,
591                });
592            }
593        }
594        OutputSpec::OpsetDependent(specs) => {
595            // Find the applicable spec for this opset (use the highest opset <= current)
596            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
611/// Get the count of original ONNX inputs (excluding outer-scope references)
612///
613/// For control flow nodes (If, Loop, Scan), outer-scope references used by subgraphs
614/// are added as additional inputs during node conversion. The `__onnx_input_count`
615/// attribute stores how many inputs are "real" ONNX inputs. This function returns
616/// that count, or falls back to the total input count if the attribute isn't present.
617pub(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
633/// Build outer scope arguments map from additional inputs added during node conversion.
634///
635/// During node conversion, outer-scope references used by subgraphs are extracted
636/// and added as additional inputs to If/Loop/Scan nodes. The `__onnx_input_count`
637/// attribute stores how many of the inputs are "real" ONNX inputs. Inputs beyond
638/// that count are outer-scope references with resolved types.
639///
640/// The `__scope_ref_names` attribute stores the original sanitized ONNX names
641/// for these scope refs, which are needed because subgraphs reference these
642/// original names, not the renamed node output names.
643///
644/// Returns full Arguments (not just types) to preserve constant values for LSTM weights etc.
645pub 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    // Get the original ONNX names for the scope refs
651    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    // Build outer scope map using original names and full arguments from inputs
661    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        // Use the original ONNX name if available, otherwise fall back to input name
666        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        // Clone the full Argument to preserve value_source and value_store
678        outer_scope.insert(name, (*input).clone());
679    }
680
681    outer_scope
682}
683
684/// Copy input type to output (for operations that preserve type)
685pub fn same_as_input(node: &mut RawNode) {
686    node.outputs[0].ty = node.inputs[0].ty.clone();
687}
688
689/// Compute broadcast output rank from multiple inputs
690pub 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
711/// Compute broadcast static shape from multiple inputs (NumPy-style broadcasting)
712pub 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                // 1 bc to anything
753                (Some(1), d) => result[result_idx] = d,
754                (_, Some(1)) => {}
755                // a symbolic dim resolves to the known one
756                // in a valid model it must be 1 or equal to it
757                (None, d) => result[result_idx] = d,
758                (Some(_), None) => {}
759                // both known and equal, nothing to do
760                (Some(cur), Some(d)) if cur == d => {}
761                // Incompatible broadcast
762                (Some(_), Some(_)) => return None,
763            }
764        }
765    }
766
767    Some(result)
768}
769
770/// Compute the broadcast output ArgType for a set of inputs.
771///
772/// Rules:
773/// - Shape + no real Tensor -> Shape
774/// - All rank-0 (ScalarNative) -> ScalarNative(output_dtype)
775/// - All on-device rank-1 with no real Tensor -> ScalarTensor(output_dtype)
776/// - Otherwise -> Tensor(output_dtype, max_rank)
777///
778/// `output_dtype` is the dtype to use for the output. Pass `None` to infer
779/// from the inputs (first on-device element type). Pass `Some(dtype)` to
780/// override (e.g., `DType::Bool` for comparison ops).
781pub 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        // logical shape is [] or [Some(k)] so the bc result is a single concrete length
797        let shape_rank = compute_broadcast_static_shape(inputs)
798            .and_then(|s| s.first().copied().flatten())
799            .unwrap_or_else(|| {
800                // incompatible shapes
801                // degrade to longest instead of panicking
802                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
842/// Update output type for broadcasting operations to max input rank
843pub 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            // Simple test: copy input type to output
865            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        // Output should match input type
902        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        // Register a processor
910        registry.register(NodeType::Add, Box::new(TestProcessor));
911
912        // Verify the processor is registered by checking the type
913        let add_processor = registry.get(&NodeType::Add);
914        let sub_processor = registry.get(&NodeType::Sub);
915
916        // Add should return our TestProcessor (we can't directly check type, but can verify behavior)
917        // Sub should return DefaultProcessor since it's not registered
918        // Both should be valid processor references
919        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        // Default processor should preserve input type
952        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        // Regression: a rank 1 static shape must not be propagated against a rank 4 static shape
964        // it is right aligned into the bc rank, so the result is bc rank long
965        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        // When one input has a static shape matching the broadcast rank, use it.
996        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    /// A group whose tail is simply absent still lifts: "missing" is not "unliftable".
1031    #[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    /// The second `lift_constants` pass sees `Static`, not `Constant`, and must leave the
1047    /// group alone rather than erroring on it.
1048    #[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}