Skip to main content

onnx_ir/node/
reduce.rs

1//! # Reduce Operations (ReduceSum, ReduceMean, ReduceMax, ReduceMin, ReduceProd, ReduceSumSquare)
2//!
3//! Reduction operations that compute aggregates along specified axes of a tensor. These operations
4//! reduce the input tensor by applying an aggregation function (sum, mean, max, min, product, or
5//! sum of squares) along the specified axes.
6//!
7//! **ONNX Specs**:
8//! - ReduceSum: <https://onnx.ai/onnx/operators/onnx__ReduceSum.html>
9//! - ReduceMean: <https://onnx.ai/onnx/operators/onnx__ReduceMean.html>
10//! - ReduceMax: <https://onnx.ai/onnx/operators/onnx__ReduceMax.html>
11//! - ReduceMin: <https://onnx.ai/onnx/operators/onnx__ReduceMin.html>
12//! - ReduceProd: <https://onnx.ai/onnx/operators/onnx__ReduceProd.html>
13//! - ReduceSumSquare: <https://onnx.ai/onnx/operators/onnx__ReduceSumSquare.html>
14//!
15//! ## Opset Versions
16//! - **Opset 1-10**: Earlier versions with different attribute handling
17//! - **Opset 11-12**: Standardized behavior with axes attribute, added noop_with_empty_axes
18//! - **Opset 13-17**: Extended type support (bfloat16, uint/int types)
19//! - **Opset 18+**: Axes moved from attribute to optional input tensor for dynamic shapes
20//!
21
22use derive_new::new;
23use onnx_ir_derive::NodeBuilder;
24
25use crate::ir::{ArgType, Argument, Node, NodeType, RawNode, RuntimeInputRef, TensorType};
26use crate::processor::{
27    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
28};
29
30/// Axes a reduction runs over.
31#[derive(Debug, Clone, PartialEq)]
32pub enum ReduceAxes {
33    /// Axes known at build time, normalized to non-negative indices. An empty list is
34    /// ONNX's "empty axes", which reduces every dimension unless `noop_with_empty_axes`
35    /// is set.
36    Static(Vec<usize>),
37    /// Axes supplied by a runtime input. Values are unknown at build time and are *not*
38    /// normalized: negative entries reach the backend as written, and Burn's dimension
39    /// APIs wrap them.
40    Runtime(RuntimeInputRef),
41}
42
43impl Default for ReduceAxes {
44    fn default() -> Self {
45        ReduceAxes::Static(Vec::new())
46    }
47}
48
49#[derive(Debug, Clone, new)]
50pub struct ReduceConfig {
51    pub axes: ReduceAxes,
52    pub keepdims: bool,
53    /// ONNX `noop_with_empty_axes`: when set, an empty `axes` makes the op an identity
54    /// instead of a full reduction.
55    pub noop_with_empty_axes: bool,
56}
57
58/// Node representation for ReduceMax operation
59#[derive(Debug, Clone, NodeBuilder)]
60pub struct ReduceMaxNode {
61    pub name: String,
62    pub inputs: Vec<Argument>,
63    pub outputs: Vec<Argument>,
64    pub config: ReduceConfig,
65}
66
67/// Node representation for ReduceMin operation
68#[derive(Debug, Clone, NodeBuilder)]
69pub struct ReduceMinNode {
70    pub name: String,
71    pub inputs: Vec<Argument>,
72    pub outputs: Vec<Argument>,
73    pub config: ReduceConfig,
74}
75
76/// Node representation for ReduceMean operation
77#[derive(Debug, Clone, NodeBuilder)]
78pub struct ReduceMeanNode {
79    pub name: String,
80    pub inputs: Vec<Argument>,
81    pub outputs: Vec<Argument>,
82    pub config: ReduceConfig,
83}
84
85/// Node representation for ReduceSum operation
86#[derive(Debug, Clone, NodeBuilder)]
87pub struct ReduceSumNode {
88    pub name: String,
89    pub inputs: Vec<Argument>,
90    pub outputs: Vec<Argument>,
91    pub config: ReduceConfig,
92}
93
94/// Node representation for ReduceProd operation
95#[derive(Debug, Clone, NodeBuilder)]
96pub struct ReduceProdNode {
97    pub name: String,
98    pub inputs: Vec<Argument>,
99    pub outputs: Vec<Argument>,
100    pub config: ReduceConfig,
101}
102
103/// Node representation for ReduceSumSquare operation
104#[derive(Debug, Clone, NodeBuilder)]
105pub struct ReduceSumSquareNode {
106    pub name: String,
107    pub inputs: Vec<Argument>,
108    pub outputs: Vec<Argument>,
109    pub config: ReduceConfig,
110}
111
112/// Node representation for ReduceL1 operation
113#[derive(Debug, Clone, NodeBuilder)]
114pub struct ReduceL1Node {
115    pub name: String,
116    pub inputs: Vec<Argument>,
117    pub outputs: Vec<Argument>,
118    pub config: ReduceConfig,
119}
120
121/// Node representation for ReduceL2 operation
122#[derive(Debug, Clone, NodeBuilder)]
123pub struct ReduceL2Node {
124    pub name: String,
125    pub inputs: Vec<Argument>,
126    pub outputs: Vec<Argument>,
127    pub config: ReduceConfig,
128}
129
130/// Node representation for ReduceLogSum operation
131#[derive(Debug, Clone, NodeBuilder)]
132pub struct ReduceLogSumNode {
133    pub name: String,
134    pub inputs: Vec<Argument>,
135    pub outputs: Vec<Argument>,
136    pub config: ReduceConfig,
137}
138
139/// Node representation for ReduceLogSumExp operation
140#[derive(Debug, Clone, NodeBuilder)]
141pub struct ReduceLogSumExpNode {
142    pub name: String,
143    pub inputs: Vec<Argument>,
144    pub outputs: Vec<Argument>,
145    pub config: ReduceConfig,
146}
147
148/// Whether codegen can read this argument's value at run time.
149///
150/// Reading the axes back on the host needs a rank-1 integer tensor or a Shape. A float
151/// axes input would otherwise reach `iter::<i64>()` in the generated code and truncate
152/// silently, and ONNX types this input `tensor(int64)` anyway.
153fn is_readable_axes(ty: &ArgType) -> bool {
154    match ty {
155        ArgType::Tensor(tensor) => tensor.rank == 1 && tensor.dtype.is_int(),
156        ArgType::Shape(_) => true,
157        _ => false,
158    }
159}
160
161/// Length of a runtime `axes` input, read from its static shape.
162///
163/// The values are unknown at build time but the count usually is not, and the count is
164/// what fixes the output rank when `keepdims` is off.
165fn runtime_axes_len(node: &RawNode) -> Option<usize> {
166    let ty = &node.get_input(1)?.ty;
167    is_readable_axes(ty).then(|| ty.first_dim_static_len())?
168}
169
170/// Normalize an ONNX axis against the input rank, rejecting anything outside
171/// the spec's `[-r, r-1]`.
172fn normalize_axis(axis: i64, rank: usize) -> Result<usize, ProcessError> {
173    let normalized = if axis < 0 { axis + rank as i64 } else { axis };
174    if normalized < 0 || normalized >= rank as i64 {
175        return Err(ProcessError::InvalidAttribute {
176            name: "axes".to_string(),
177            reason: format!("axis {axis} is out of range for a rank-{rank} input"),
178        });
179    }
180    Ok(normalized as usize)
181}
182
183pub(crate) struct ReduceProcessor;
184
185impl NodeProcessor for ReduceProcessor {
186    type Config = ReduceConfig;
187
188    fn spec(&self) -> NodeSpec {
189        NodeSpec {
190            min_opset: 1,
191            max_opset: None,
192            inputs: InputSpec::Range(1, 2),
193            outputs: OutputSpec::Exact(1),
194        }
195    }
196
197    fn is_noop(&self, node: &RawNode) -> bool {
198        // ONNX `noop_with_empty_axes` with an empty `axes` skips the reduction. For the
199        // plain reductions that leaves the input untouched, so the node can be dropped
200        // entirely. The composite reductions still perform their elementwise part -
201        // ReduceSumSquare squares, ReduceL1 and ReduceL2 take an absolute value,
202        // ReduceLogSum takes a log - so they are not no-ops and codegen has to emit them.
203        if !matches!(
204            node.node_type,
205            NodeType::ReduceSum
206                | NodeType::ReduceMean
207                | NodeType::ReduceMax
208                | NodeType::ReduceMin
209                | NodeType::ReduceProd
210                | NodeType::ReduceLogSumExp
211        ) {
212            return false;
213        }
214
215        // `extract_config` ignores the opset, and it is what knows that a runtime axes
216        // input whose shape proves it empty is the empty-axes case.
217        match self.extract_config(node, 0) {
218            Ok(config) => {
219                config.noop_with_empty_axes
220                    && matches!(&config.axes, ReduceAxes::Static(dims) if dims.is_empty())
221            }
222            Err(_) => false,
223        }
224    }
225
226    fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
227        // Lift axes input (input[1]) if present
228        if node.inputs.len() > 1 && node.inputs[1].is_constant() {
229            node.inputs[1].to_static()?;
230        }
231
232        Ok(())
233    }
234
235    fn infer_types(
236        &self,
237        node: &mut RawNode,
238        opset: usize,
239        _output_preferences: &OutputPreferences,
240    ) -> Result<(), ProcessError> {
241        // TODO: Validate the input count per opset. `InputSpec::Range(1, 2)` already
242        // rejects 3+ inputs; what is missing is that the `axes` input only exists from
243        // opset 18 (13 for ReduceSum), so 2 inputs before that is malformed.
244
245        // Validate input type and extract tensor info
246        let (tensor_rank, tensor_elem_type, tensor_static_shape) = match &node.inputs[0].ty {
247            ArgType::Tensor(tensor) => (tensor.rank, tensor.dtype, tensor.static_shape.clone()),
248            _ => {
249                return Err(ProcessError::TypeMismatch {
250                    expected: "Tensor".to_string(),
251                    actual: format!("{:?}", node.inputs[0].ty),
252                });
253            }
254        };
255
256        let config = self.extract_config(node, opset)?;
257        let keepdims = config.keepdims;
258
259        // Axes known at build time, if any. `None` means they arrive at run time.
260        let dims = match &config.axes {
261            ReduceAxes::Static(dims) => Some(dims),
262            ReduceAxes::Runtime(axes) => {
263                let axes_ty = &node.inputs[axes.input_index].ty;
264                if !is_readable_axes(axes_ty) {
265                    return Err(ProcessError::TypeMismatch {
266                        expected: "rank-1 Tensor or Shape for the runtime 'axes' input".to_string(),
267                        actual: format!("{axes_ty:?}"),
268                    });
269                }
270                None
271            }
272        };
273
274        // How many axes the reduction names. `None` means the axes arrive at runtime
275        // and their count is not recoverable from the axes input's shape.
276        let axis_count = match dims {
277            Some(dims) => Some(dims.len()),
278            None => runtime_axes_len(node),
279        };
280
281        // Only usable when it describes every dimension of the input.
282        let static_shape = tensor_static_shape.filter(|shape| shape.len() == tensor_rank);
283
284        // ONNX: an empty `axes` is an identity when `noop_with_empty_axes` is set,
285        // and reduces every dimension otherwise.
286        if axis_count == Some(0) {
287            if config.noop_with_empty_axes {
288                node.outputs[0].ty = node.inputs[0].ty.clone();
289                return Ok(());
290            }
291
292            node.outputs[0].ty = if keepdims {
293                ArgType::Tensor(TensorType {
294                    dtype: tensor_elem_type,
295                    rank: tensor_rank,
296                    static_shape: Some(vec![Some(1); tensor_rank]),
297                })
298            } else {
299                ArgType::ScalarTensor(tensor_elem_type)
300            };
301            return Ok(());
302        }
303
304        if keepdims {
305            // Every named axis collapses to 1, so the rank is unchanged whether or not
306            // the axes themselves are known.
307            let static_shape = dims.zip(static_shape).map(|(dims, mut shape)| {
308                for dim in dims {
309                    shape[*dim] = Some(1);
310                }
311                shape
312            });
313
314            node.outputs[0].ty = ArgType::Tensor(TensorType {
315                dtype: tensor_elem_type,
316                rank: tensor_rank,
317                static_shape,
318            });
319            return Ok(());
320        }
321
322        // keepdims=0: the output rank depends on how many axes are reduced, so an
323        // unknown axis count is not recoverable.
324        let Some(axis_count) = axis_count else {
325            return Err(ProcessError::Custom(format!(
326                "'{}' takes 'axes' as a runtime input of unknown length with keepdims=0, \
327                 so the output rank cannot be determined at build time",
328                node.name
329            )));
330        };
331
332        if axis_count > tensor_rank {
333            return Err(ProcessError::InvalidAttribute {
334                name: "axes".to_string(),
335                reason: format!(
336                    "'{}' names {axis_count} axes but the input has rank {tensor_rank}",
337                    node.name
338                ),
339            });
340        }
341
342        if axis_count == tensor_rank {
343            node.outputs[0].ty = ArgType::ScalarTensor(tensor_elem_type);
344            return Ok(());
345        }
346
347        let static_shape = dims.zip(static_shape).map(|(dims, mut shape)| {
348            for dim in dims.iter().rev() {
349                shape.remove(*dim);
350            }
351            shape
352        });
353
354        node.outputs[0].ty = ArgType::Tensor(TensorType {
355            dtype: tensor_elem_type,
356            rank: tensor_rank - axis_count,
357            static_shape,
358        });
359
360        Ok(())
361    }
362
363    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
364        // Validate input type and extract tensor info
365        let tensor_rank = match &node.inputs[0].ty {
366            ArgType::Tensor(tensor) => tensor.rank,
367            _ => {
368                return Err(ProcessError::TypeMismatch {
369                    expected: "Tensor".to_string(),
370                    actual: format!("{:?}", node.inputs[0].ty),
371                });
372            }
373        };
374
375        // Extract attributes. `axes` moved to an input in opset 18 (13 for ReduceSum),
376        // so a model may carry it either way.
377        let mut axes_attr = None;
378        let mut keepdims = 1;
379        let mut noop_with_empty_axes = 0;
380
381        for (key, value) in node.attrs.iter() {
382            match key.as_str() {
383                "axes" => axes_attr = Some(value.clone().into_i64s()?),
384                "keepdims" => keepdims = value.clone().into_i64()?,
385                "noop_with_empty_axes" => noop_with_empty_axes = value.clone().into_i64()?,
386                _ => {}
387            }
388        }
389
390        // The axes input wins over the attribute when both are present. A value that is
391        // not statically known stays `Runtime` so codegen reads it at run time, except
392        // when the input's shape already proves the list is empty.
393        let static_axes: Vec<i64> = match node.get_input(1) {
394            Some(axes_arg) => match axes_arg.value() {
395                Some(value) => value.try_into_vec::<i64>().map_err(|e| {
396                    ProcessError::Custom(format!("Failed to read 'axes' of '{}': {e}", node.name))
397                })?,
398                None if runtime_axes_len(node) == Some(0) => Vec::new(),
399                None => {
400                    return Ok(ReduceConfig::new(
401                        ReduceAxes::Runtime(RuntimeInputRef::new(axes_arg.name.clone(), 1)),
402                        keepdims == 1,
403                        noop_with_empty_axes == 1,
404                    ));
405                }
406            },
407            None => axes_attr.unwrap_or_default(),
408        };
409
410        let mut dims = static_axes
411            .into_iter()
412            .map(|axis| normalize_axis(axis, tensor_rank))
413            .collect::<Result<Vec<usize>, _>>()?;
414
415        // Sort the dimensions to ensure consistent order
416        dims.sort();
417
418        // The output rank is derived from the number of axes, and Burn's `squeeze_dims`
419        // deduplicates internally, so a repeated axis would make the declared rank
420        // disagree with the tensor Burn produces. ONNX's reference evaluator rejects
421        // duplicates too.
422        if dims.windows(2).any(|pair| pair[0] == pair[1]) {
423            return Err(ProcessError::InvalidAttribute {
424                name: "axes".to_string(),
425                reason: format!("duplicate axis in {dims:?}"),
426            });
427        }
428
429        Ok(ReduceConfig::new(
430            ReduceAxes::Static(dims),
431            keepdims == 1,
432            noop_with_empty_axes == 1,
433        ))
434    }
435
436    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
437        // `lift_constants` runs again after identity elimination without re-running type
438        // inference, so a config check can first become possible here.
439        let config = self.extract_config(&builder, opset)?;
440
441        Ok(match builder.node_type {
442            NodeType::ReduceMax => Node::ReduceMax(ReduceMaxNode {
443                name: builder.name,
444                inputs: builder.inputs,
445                outputs: builder.outputs,
446                config,
447            }),
448            NodeType::ReduceMin => Node::ReduceMin(ReduceMinNode {
449                name: builder.name,
450                inputs: builder.inputs,
451                outputs: builder.outputs,
452                config,
453            }),
454            NodeType::ReduceMean => Node::ReduceMean(ReduceMeanNode {
455                name: builder.name,
456                inputs: builder.inputs,
457                outputs: builder.outputs,
458                config,
459            }),
460            NodeType::ReduceSum => Node::ReduceSum(ReduceSumNode {
461                name: builder.name,
462                inputs: builder.inputs,
463                outputs: builder.outputs,
464                config,
465            }),
466            NodeType::ReduceProd => Node::ReduceProd(ReduceProdNode {
467                name: builder.name,
468                inputs: builder.inputs,
469                outputs: builder.outputs,
470                config,
471            }),
472            NodeType::ReduceSumSquare => Node::ReduceSumSquare(ReduceSumSquareNode {
473                name: builder.name,
474                inputs: builder.inputs,
475                outputs: builder.outputs,
476                config,
477            }),
478            NodeType::ReduceL1 => Node::ReduceL1(ReduceL1Node {
479                name: builder.name,
480                inputs: builder.inputs,
481                outputs: builder.outputs,
482                config,
483            }),
484            NodeType::ReduceL2 => Node::ReduceL2(ReduceL2Node {
485                name: builder.name,
486                inputs: builder.inputs,
487                outputs: builder.outputs,
488                config,
489            }),
490            NodeType::ReduceLogSum => Node::ReduceLogSum(ReduceLogSumNode {
491                name: builder.name,
492                inputs: builder.inputs,
493                outputs: builder.outputs,
494                config,
495            }),
496            NodeType::ReduceLogSumExp => Node::ReduceLogSumExp(ReduceLogSumExpNode {
497                name: builder.name,
498                inputs: builder.inputs,
499                outputs: builder.outputs,
500                config,
501            }),
502            other => {
503                return Err(ProcessError::Custom(format!(
504                    "ReduceProcessor called with unsupported node type {other:?}"
505                )));
506            }
507        })
508    }
509}
510
511#[cfg(test)]
512mod tests {
513    #![allow(clippy::bool_assert_comparison)]
514
515    use super::*;
516    use crate::node::test_utils::TestNodeBuilder;
517    use NodeType;
518
519    fn create_test_node(axes: Option<Vec<i64>>, keepdims: Option<i64>) -> RawNode {
520        let mut builder = TestNodeBuilder::new(NodeType::ReduceMax, "test_reduce_max")
521            .input_tensor_f32("data", 3, None)
522            .output_tensor_f32("reduced", 3, None);
523
524        if let Some(axes_val) = axes {
525            builder = builder.attr_ints("axes", axes_val);
526        }
527        if let Some(kd) = keepdims {
528            builder = builder.attr_int("keepdims", kd);
529        }
530
531        builder.build()
532    }
533
534    #[test]
535    fn test_reduce_config_basic() {
536        let node = create_test_node(Some(vec![1]), Some(1));
537        let mut node = node;
538
539        let processor = ReduceProcessor;
540        let prefs = OutputPreferences::new();
541        let config = processor.extract_config(&node, 16).unwrap();
542        processor.infer_types(&mut node, 16, &prefs).unwrap();
543
544        assert_eq!(config.axes, ReduceAxes::Static(vec![1]));
545        assert_eq!(config.keepdims, true);
546    }
547
548    #[test]
549    fn test_reduce_config_negative_axis() {
550        let node = create_test_node(Some(vec![-2]), Some(1));
551        let mut node = node;
552
553        let processor = ReduceProcessor;
554        let prefs = OutputPreferences::new();
555        let config = processor.extract_config(&node, 16).unwrap();
556        processor.infer_types(&mut node, 16, &prefs).unwrap();
557
558        assert_eq!(config.axes, ReduceAxes::Static(vec![1])); // -2 + 3 = 1
559        assert_eq!(config.keepdims, true);
560    }
561
562    #[test]
563    fn test_reduce_config_no_axes() {
564        let node = create_test_node(None, Some(1));
565        let mut node = node;
566
567        let processor = ReduceProcessor;
568        let prefs = OutputPreferences::new();
569        let config = processor.extract_config(&node, 16).unwrap();
570        processor.infer_types(&mut node, 16, &prefs).unwrap();
571
572        assert_eq!(config.axes, ReduceAxes::Static(Vec::new()));
573        assert_eq!(config.keepdims, true);
574    }
575
576    #[test]
577    fn test_reduce_config_multiple_axes() {
578        let node = create_test_node(Some(vec![0, 1]), Some(1));
579        let mut node = node;
580
581        let processor = ReduceProcessor;
582        let prefs = OutputPreferences::new();
583        let config = processor.extract_config(&node, 16).unwrap();
584        processor.infer_types(&mut node, 16, &prefs).unwrap();
585
586        assert_eq!(config.axes, ReduceAxes::Static(vec![0, 1]));
587        assert_eq!(config.keepdims, true);
588    }
589
590    #[test]
591    fn test_reduce_config_no_keepdims() {
592        let node = create_test_node(Some(vec![1]), Some(0));
593        let mut node = node;
594
595        let processor = ReduceProcessor;
596        let prefs = OutputPreferences::new();
597        let config = processor.extract_config(&node, 16).unwrap();
598        processor.infer_types(&mut node, 16, &prefs).unwrap();
599
600        assert_eq!(config.axes, ReduceAxes::Static(vec![1]));
601        assert_eq!(config.keepdims, false);
602    }
603
604    #[test]
605    fn test_reduce_update_outputs_scalar_no_axes_no_keepdims() {
606        // Test that reduce with no axes and keepdims=false produces a scalar output
607        let mut node = create_test_node(None, Some(0));
608        let processor = ReduceProcessor;
609        let prefs = OutputPreferences::new();
610        let _config = processor.extract_config(&node, 16).unwrap();
611        processor.infer_types(&mut node, 16, &prefs).unwrap();
612
613        match &node.outputs[0].ty {
614            ArgType::ScalarTensor(_) => {
615                // This is the expected case - scalar tensor output (stays on device)
616            }
617            ArgType::Tensor(_) => {
618                panic!("Expected scalar output but got tensor");
619            }
620            _ => {
621                panic!("Unexpected output type");
622            }
623        }
624    }
625
626    #[test]
627    fn test_reduce_update_outputs_scalar_all_dims_no_keepdims() {
628        // Test that reduce with all dimensions and keepdims=false produces a scalar output
629        let mut node = create_test_node(Some(vec![0, 1, 2]), Some(0));
630        let processor = ReduceProcessor;
631        let prefs = OutputPreferences::new();
632        let _config = processor.extract_config(&node, 16).unwrap();
633        processor.infer_types(&mut node, 16, &prefs).unwrap();
634
635        match &node.outputs[0].ty {
636            ArgType::ScalarTensor(_) => {
637                // This is the expected case - scalar tensor output (stays on device)
638            }
639            ArgType::Tensor(_) => {
640                panic!("Expected scalar output but got tensor");
641            }
642            _ => {
643                panic!("Unexpected output type");
644            }
645        }
646    }
647
648    #[test]
649    fn test_reduce_update_outputs_tensor_partial_dims_no_keepdims() {
650        // Test that reduce with partial dimensions and keepdims=false produces a tensor output
651        let mut node = create_test_node(Some(vec![1]), Some(0));
652        let processor = ReduceProcessor;
653        let prefs = OutputPreferences::new();
654        let _config = processor.extract_config(&node, 16).unwrap();
655        processor.infer_types(&mut node, 16, &prefs).unwrap();
656
657        match &node.outputs[0].ty {
658            ArgType::Tensor(tensor) => {
659                // Should be rank 2 (3 - 1 = 2)
660                assert_eq!(tensor.rank, 2);
661            }
662            ArgType::ScalarTensor(_) | ArgType::ScalarNative(_) => {
663                panic!("Expected tensor output but got scalar");
664            }
665            _ => {
666                panic!("Unexpected output type");
667            }
668        }
669    }
670
671    #[test]
672    fn test_reduce_update_outputs_tensor_with_keepdims() {
673        // Test that reduce with keepdims=true always produces a tensor output
674        let mut node = create_test_node(None, Some(1));
675        let processor = ReduceProcessor;
676        let prefs = OutputPreferences::new();
677        let _config = processor.extract_config(&node, 16).unwrap();
678        processor.infer_types(&mut node, 16, &prefs).unwrap();
679
680        match &node.outputs[0].ty {
681            ArgType::Tensor(tensor) => {
682                // Should maintain original rank when keepdims=true
683                assert_eq!(tensor.rank, 3);
684            }
685            ArgType::ScalarTensor(_) | ArgType::ScalarNative(_) => {
686                panic!("Expected tensor output but got scalar when keepdims=true");
687            }
688            _ => {
689                panic!("Unexpected output type");
690            }
691        }
692    }
693
694    #[test]
695    fn test_reduce_update_outputs_partial_static_shape_keepdims() {
696        // Regression test for partial static_shape with keepdims=true
697        // This was causing "index out of bounds" panic before the fix
698        let mut node = TestNodeBuilder::new(NodeType::ReduceMean, "test_reduce_mean")
699            .input_tensor_f32("data", 3, Some(vec![768])) // Rank 3 but only last dim known
700            .output_tensor_f32("reduced", 3, None)
701            .attr_ints("axes", vec![2]) // Reduce on dimension 2
702            .attr_int("keepdims", 1)
703            .build();
704
705        // This should not panic
706        let processor = ReduceProcessor;
707        let prefs = OutputPreferences::new();
708        let _config = processor.extract_config(&node, 16).unwrap();
709        processor.infer_types(&mut node, 16, &prefs).unwrap();
710
711        match &node.outputs[0].ty {
712            ArgType::Tensor(tensor) => {
713                // Should maintain rank 3 with keepdims=true
714                assert_eq!(tensor.rank, 3);
715                // Static shape should be None since input shape was partial
716                assert_eq!(tensor.static_shape, None);
717            }
718            _ => {
719                panic!("Expected tensor output");
720            }
721        }
722    }
723
724    #[test]
725    fn test_reduce_update_outputs_partial_static_shape_no_keepdims() {
726        // Regression test for partial static_shape without keepdims
727        let mut node = TestNodeBuilder::new(NodeType::ReduceMean, "test_reduce_mean")
728            .input_tensor_f32("data", 3, Some(vec![768])) // Rank 3 but only last dim known
729            .output_tensor_f32("reduced", 3, None)
730            .attr_ints("axes", vec![1]) // Reduce on dimension 1
731            .attr_int("keepdims", 0)
732            .build();
733
734        // This should not panic
735        let processor = ReduceProcessor;
736        let prefs = OutputPreferences::new();
737        let _config = processor.extract_config(&node, 16).unwrap();
738        processor.infer_types(&mut node, 16, &prefs).unwrap();
739
740        match &node.outputs[0].ty {
741            ArgType::Tensor(tensor) => {
742                // Should be rank 2 (3 - 1 = 2) without keepdims
743                assert_eq!(tensor.rank, 2);
744                // Static shape should be None since input shape was partial
745                assert_eq!(tensor.static_shape, None);
746            }
747            _ => {
748                panic!("Expected tensor output");
749            }
750        }
751    }
752
753    #[test]
754    fn test_reduce_update_outputs_complete_static_shape_keepdims() {
755        // Test that complete static_shape is properly updated with keepdims=true
756        let mut node = TestNodeBuilder::new(NodeType::ReduceMean, "test_reduce_mean")
757            .input_tensor_f32("data", 3, Some(vec![2, 4, 768])) // Complete shape
758            .output_tensor_f32("reduced", 3, None)
759            .attr_ints("axes", vec![2]) // Reduce on dimension 2
760            .attr_int("keepdims", 1)
761            .build();
762
763        let processor = ReduceProcessor;
764        let prefs = OutputPreferences::new();
765        let _config = processor.extract_config(&node, 16).unwrap();
766        processor.infer_types(&mut node, 16, &prefs).unwrap();
767
768        match &node.outputs[0].ty {
769            ArgType::Tensor(tensor) => {
770                // Should maintain rank 3 with keepdims=true
771                assert_eq!(tensor.rank, 3);
772                // Static shape should be updated: [2, 4, 768] -> [2, 4, 1]
773                assert_eq!(tensor.static_shape, Some(vec![Some(2), Some(4), Some(1)]));
774            }
775            _ => {
776                panic!("Expected tensor output");
777            }
778        }
779    }
780    /// Build a Reduce node whose `axes` arrives as a runtime input (opset 18 shape),
781    /// with `axes_len` naming the statically known length of that input.
782    fn create_runtime_axes_node(
783        axes_len: Option<usize>,
784        keepdims: i64,
785        noop_with_empty_axes: Option<i64>,
786    ) -> RawNode {
787        let mut builder = TestNodeBuilder::new(NodeType::ReduceSum, "test_reduce_sum")
788            .input_tensor_f32("data", 3, Some(vec![2, 3, 4]))
789            .input_tensor_i64("axes", 1, axes_len.map(|len| vec![len]))
790            .output_tensor_f32("reduced", 3, None)
791            .attr_int("keepdims", keepdims);
792
793        if let Some(noop) = noop_with_empty_axes {
794            builder = builder.attr_int("noop_with_empty_axes", noop);
795        }
796
797        builder.build()
798    }
799
800    #[test]
801    fn test_reduce_runtime_axes_leaves_dims_unknown() {
802        let node = create_runtime_axes_node(Some(1), 1, None);
803
804        let config = ReduceProcessor.extract_config(&node, 18).unwrap();
805
806        // The whole point of #459: this must not collapse to "no axes given".
807        assert!(
808            matches!(&config.axes, ReduceAxes::Runtime(axes) if axes.name == "axes"),
809            "expected runtime axes, got {:?}",
810            config.axes
811        );
812        assert_eq!(config.keepdims, true);
813    }
814
815    #[test]
816    fn test_reduce_runtime_axes_keepdims_preserves_rank() {
817        let mut node = create_runtime_axes_node(Some(1), 1, None);
818        let prefs = OutputPreferences::new();
819
820        ReduceProcessor.infer_types(&mut node, 18, &prefs).unwrap();
821
822        match &node.outputs[0].ty {
823            ArgType::Tensor(tensor) => {
824                assert_eq!(tensor.rank, 3);
825                // Which dimension collapses is only known at run time.
826                assert_eq!(tensor.static_shape, None);
827            }
828            other => panic!("Expected tensor output, got {other:?}"),
829        }
830    }
831
832    #[test]
833    fn test_reduce_runtime_axes_no_keepdims_uses_axes_length() {
834        let mut node = create_runtime_axes_node(Some(2), 0, None);
835        let prefs = OutputPreferences::new();
836
837        ReduceProcessor.infer_types(&mut node, 18, &prefs).unwrap();
838
839        match &node.outputs[0].ty {
840            ArgType::Tensor(tensor) => assert_eq!(tensor.rank, 1), // 3 - 2
841            other => panic!("Expected tensor output, got {other:?}"),
842        }
843    }
844
845    #[test]
846    fn test_reduce_runtime_axes_no_keepdims_unknown_length_is_rejected() {
847        let mut node = create_runtime_axes_node(None, 0, None);
848        let prefs = OutputPreferences::new();
849
850        let err = ReduceProcessor
851            .infer_types(&mut node, 18, &prefs)
852            .expect_err("output rank is not knowable without the axes length");
853
854        assert!(
855            err.to_string().contains("output rank"),
856            "unexpected error: {err}"
857        );
858    }
859
860    #[test]
861    fn test_reduce_runtime_axes_empty_input_is_static() {
862        // A runtime axes input whose shape proves it is empty is the ONNX "empty axes"
863        // case, not an unknown one.
864        let node = create_runtime_axes_node(Some(0), 1, None);
865
866        let config = ReduceProcessor.extract_config(&node, 18).unwrap();
867
868        assert_eq!(config.axes, ReduceAxes::Static(Vec::new()));
869    }
870
871    #[test]
872    fn test_reduce_noop_with_empty_axes_is_identity() {
873        let mut node = create_runtime_axes_node(Some(0), 1, Some(1));
874        let prefs = OutputPreferences::new();
875
876        let config = ReduceProcessor.extract_config(&node, 18).unwrap();
877        assert_eq!(config.noop_with_empty_axes, true);
878
879        ReduceProcessor.infer_types(&mut node, 18, &prefs).unwrap();
880
881        assert_eq!(node.outputs[0].ty, node.inputs[0].ty);
882    }
883
884    #[test]
885    fn test_reduce_empty_axes_without_noop_reduces_everything() {
886        let mut node = create_runtime_axes_node(Some(0), 1, Some(0));
887        let prefs = OutputPreferences::new();
888
889        ReduceProcessor.infer_types(&mut node, 18, &prefs).unwrap();
890
891        match &node.outputs[0].ty {
892            ArgType::Tensor(tensor) => {
893                assert_eq!(tensor.rank, 3);
894                assert_eq!(
895                    tensor.static_shape,
896                    Some(vec![Some(1), Some(1), Some(1)]),
897                    "reducing every dimension with keepdims collapses each to 1"
898                );
899            }
900            other => panic!("Expected tensor output, got {other:?}"),
901        }
902    }
903
904    #[test]
905    fn test_reduce_axis_out_of_range_is_rejected() {
906        let node = create_test_node(Some(vec![3]), Some(1));
907
908        let err = ReduceProcessor
909            .extract_config(&node, 16)
910            .expect_err("axis 3 is out of range for a rank-3 input");
911
912        assert!(err.to_string().contains("out of range"), "got: {err}");
913    }
914    #[test]
915    fn test_reduce_runtime_axes_longer_than_rank_is_rejected() {
916        // The output rank is `tensor_rank - axis_count`; a longer axes list used to
917        // underflow that subtraction and panic with no node name.
918        let mut node = create_runtime_axes_node(Some(5), 0, None);
919        let prefs = OutputPreferences::new();
920
921        let err = ReduceProcessor
922            .infer_types(&mut node, 18, &prefs)
923            .expect_err("5 axes cannot apply to a rank-3 input");
924
925        assert!(err.to_string().contains("names 5 axes"), "got: {err}");
926    }
927
928    #[test]
929    fn test_reduce_duplicate_axes_are_rejected() {
930        // Burn's `squeeze_dims` deduplicates, so a repeated axis would make the declared
931        // output rank disagree with the tensor it actually produces.
932        let node = create_test_node(Some(vec![1, 1]), Some(0));
933
934        let err = ReduceProcessor
935            .extract_config(&node, 16)
936            .expect_err("duplicate axes have no well-defined output rank");
937
938        assert!(err.to_string().contains("duplicate axis"), "got: {err}");
939    }
940
941    #[test]
942    fn test_reduce_float_axes_input_is_rejected() {
943        // Codegen reads the axes with `iter::<i64>()`, which would truncate floats
944        // rather than fail. ONNX types this input `tensor(int64)`.
945        let mut node = TestNodeBuilder::new(NodeType::ReduceSum, "test_reduce_sum")
946            .input_tensor_f32("data", 3, Some(vec![2, 3, 4]))
947            .input_tensor_f32("axes", 1, Some(vec![1]))
948            .output_tensor_f32("reduced", 3, None)
949            .attr_int("keepdims", 1)
950            .build();
951        let prefs = OutputPreferences::new();
952
953        let err = ReduceProcessor
954            .infer_types(&mut node, 18, &prefs)
955            .expect_err("a float axes input is not readable as an axis list");
956
957        assert!(err.to_string().contains("rank-1 Tensor"), "got: {err}");
958    }
959    #[test]
960    fn test_reduce_sum_noop_with_empty_axes_is_eliminated() {
961        // A plain reduction that skips its reduction leaves the input untouched, so the
962        // framework can drop the node instead of codegen emitting a rebinding.
963        let node = create_runtime_axes_node(Some(0), 1, Some(1));
964        assert!(ReduceProcessor.is_noop(&node));
965    }
966
967    #[test]
968    fn test_reduce_sum_square_noop_with_empty_axes_is_not_eliminated() {
969        // "no reduction is applied, but other operations will be performed":
970        // ReduceSumSquare still squares, so the node has real work to do.
971        let node = TestNodeBuilder::new(NodeType::ReduceSumSquare, "test_reduce_sum_square")
972            .input_tensor_f32("data", 3, Some(vec![2, 3, 4]))
973            .output_tensor_f32("reduced", 3, None)
974            .attr_int("keepdims", 1)
975            .attr_int("noop_with_empty_axes", 1)
976            .build();
977        assert!(!ReduceProcessor.is_noop(&node));
978    }
979
980    #[test]
981    fn test_reduce_sum_without_noop_flag_is_not_eliminated() {
982        // Empty axes without the flag reduces every dimension, which is not a no-op.
983        let node = create_runtime_axes_node(Some(0), 1, Some(0));
984        assert!(!ReduceProcessor.is_noop(&node));
985    }
986
987    #[test]
988    fn test_reduce_sum_noop_with_named_axes_is_not_eliminated() {
989        // The flag only applies when the axes list is empty.
990        let node = create_test_node(Some(vec![1]), Some(1));
991        assert!(!ReduceProcessor.is_noop(&node));
992    }
993}