Skip to main content

tract_core/ops/nn/
reduce.rs

1use crate::internal::Axis;
2use crate::internal::*;
3use crate::ops::binary::TypedBinOp;
4use crate::ops::cast::cast;
5use crate::ops::change_axes::wire_with_rank_broadcast;
6use crate::ops::element_wise::ElementWiseOp;
7use crate::ops::math::{Mul, Square, div, square};
8use std::convert::TryFrom;
9use std::iter::Sum;
10use std::mem::transmute;
11use tract_data::internal::ClampCast;
12use tract_data::itertools::Itertools;
13use tract_ndarray::prelude::*;
14use tract_num_traits::{AsPrimitive, Bounded};
15
16macro_rules! r {
17    ($($path:ident)::* ($dt:expr) ($($args:expr),*)) => {
18        match $dt {
19            DatumType::U8   => $($path)::*::<u8,_,_,_>($($args),*),
20            DatumType::I8   => $($path)::*::<i8,_,_,_>($($args),*),
21            DatumType::U16  => $($path)::*::<u16,_,_,_>($($args),*),
22            DatumType::I16  => $($path)::*::<i16,_,_,_>($($args),*),
23            DatumType::I32  => $($path)::*::<i32,_,_,_>($($args),*),
24            DatumType::I64  => $($path)::*::<i64,_,_,_>($($args),*),
25            DatumType::F16  => $($path)::*::<f16,_,_,_>($($args),*),
26            DatumType::F32  => $($path)::*::<f32,_,_,_>($($args),*),
27            DatumType::F64  => $($path)::*::<f64,_,_,_>($($args),*),
28            DatumType::QI8(_)  => $($path)::*::<i8,_,_,_>($($args),*),
29            DatumType::QU8(_)  => $($path)::*::<u8,_,_,_>($($args),*),
30            _ => bail!("{:?} is not a number", $dt)
31        }
32    };
33    ($($path:ident)::* ($dt:expr) ($($args:expr),*); $($q_path:ident)::* ($($q_args:expr),*)) => {
34        match $dt {
35            DatumType::U8   => $($path)::*::<u8,_,_,_>($($args),*),
36            DatumType::I8   => $($path)::*::<i8,_,_,_>($($args),*),
37            DatumType::U16  => $($path)::*::<u16,_,_,_>($($args),*),
38            DatumType::I16  => $($path)::*::<i16,_,_,_>($($args),*),
39            DatumType::I32  => $($path)::*::<i32,_,_,_>($($args),*),
40            DatumType::I64  => $($path)::*::<i64,_,_,_>($($args),*),
41            DatumType::F16  => $($path)::*::<f16,_,_,_>($($args),*),
42            DatumType::F32  => $($path)::*::<f32,_,_,_>($($args),*),
43            DatumType::F64  => $($path)::*::<f64,_,_,_>($($args),*),
44            DatumType::QI8(_)  => $($q_path)::*::<i8,_,_,_>($($q_args),*),
45            DatumType::QU8(_)  => $($q_path)::*::<u8,_,_,_>($($q_args),*),
46            _ => bail!("{:?} is not a number", $dt)
47        }
48    }
49}
50
51#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
52pub enum Reducer {
53    ArgMax(bool), // take last
54    ArgMin(bool),
55    Max,
56    Min,
57    Prod,
58    Sum,
59    MeanOfSquares,
60    All,
61    Any,
62}
63
64impl Reducer {
65    pub fn reduce(&self, axes: &[usize], input: &Tensor) -> TractResult<Tensor> {
66        use Reducer::*;
67        let dt = input.datum_type();
68        let output_shape: Vec<usize> = input
69            .shape()
70            .iter()
71            .enumerate()
72            .map(|(ax, &d)| if axes.contains(&ax) { 1 } else { d })
73            .collect();
74        let (zp, scale) = input.datum_type().zp_scale();
75        unsafe {
76            let mut t = match self {
77                ArgMax(last) => {
78                    r!(Self::reduce_t(dt)(self, axes, &output_shape, input, argmax_t, *last))
79                }
80                ArgMin(last) => {
81                    r!(Self::reduce_t(dt)(self, axes, &output_shape, input, argmin_t, *last))
82                }
83                Min => r!(Self::reduce_t(dt)(self, axes, &output_shape, input, min_t, ())),
84                Max => r!(Self::reduce_t(dt)(self, axes, &output_shape, input, max_t, ())),
85                Prod => {
86                    r!(Self::reduce_t(dt)(self, axes, &output_shape, input, prod_t, ()); Self::reduce_t(self, axes, &output_shape, input, q_prod_t, (zp, scale)))
87                }
88                Sum => {
89                    if dt.is_float() {
90                        dispatch_floatlike!(Self::sum(dt)(self, axes, input))
91                    } else {
92                        r!(Self::reduce_t(dt)(
93                            self,
94                            axes,
95                            &output_shape,
96                            input,
97                            q_sum_t,
98                            (zp, scale)
99                        ))
100                    }
101                }
102                MeanOfSquares => self.mean_of_squares(axes, input)?,
103                All => Self::reduce_t(self, axes, &output_shape, input, all_bool, ()),
104                Any => Self::reduce_t(self, axes, &output_shape, input, any_bool, ()),
105            };
106            if input.datum_type().is_quantized()
107                && input.datum_type().unquantized() == t.datum_type().unquantized()
108            {
109                t.set_datum_type(input.datum_type());
110            }
111            Ok(t)
112        }
113    }
114
115    unsafe fn reduce_t<T, TO, F, A>(
116        &self,
117        axes: &[usize],
118        output_shape: &[usize],
119        input_tensor: &Tensor,
120        f: F,
121        args: A,
122    ) -> Tensor
123    where
124        F: for<'a> Fn(ArrayViewD<'a, T>, A) -> TO,
125        T: Copy + Datum,
126        TO: Copy + Datum,
127        A: Copy,
128    {
129        use ndarray::*;
130        let input = unsafe { input_tensor.to_array_view_unchecked::<T>() };
131        let result = Array::from_shape_fn(output_shape, |coords| {
132            let slice_spec: Vec<SliceInfoElem> = coords
133                .slice()
134                .iter()
135                .enumerate()
136                .map(|(ax, &d)| if axes.contains(&ax) { (..).into() } else { d.into() })
137                .collect();
138            let slice_info = SliceInfo::<_, IxDyn, IxDyn>::try_from(slice_spec).unwrap();
139            let slice = input.slice(&slice_info);
140            f(slice, args)
141        });
142        result.into_tensor()
143    }
144
145    // sum is a special citizen: enough activity that it gets "special"
146    // treatment. we could use the same "algo" for min, max and prod, to the
147    // price of more code in the library. argmax and argmin are more
148    // tricky (not associative)
149    unsafe fn sum<T>(&self, axes: &[usize], input: &Tensor) -> Tensor
150    where
151        T: Copy + Datum + num_traits::Zero + Sum,
152        f16: AsPrimitive<T>,
153        f32: AsPrimitive<T>,
154    {
155        if axes.len() == 0 {
156            return input.to_owned();
157        }
158
159        // use tract-optimized path only when single reuction axis and is at end
160        if axes.len() > 1 || axes[0] != input.rank() - 1 {
161            let mut operative_axes = vec![];
162            let mut operative_shape: Vec<usize> = vec![];
163            for (ix, dim) in input.shape().iter().enumerate() {
164                // axis is reduced, but is not the first of a series of reduced axes
165                if ix > 0 && axes.contains(&ix) && axes.contains(&(ix - 1)) {
166                    *operative_shape.last_mut().unwrap() *= *dim;
167                } else if axes.contains(&ix) {
168                    operative_axes.push(operative_shape.len());
169                    operative_shape.push(*dim);
170                } else {
171                    operative_shape.push(*dim);
172                }
173            }
174            let mut output = unsafe {
175                input
176                    .to_array_view_unchecked::<T>()
177                    .into_shape_with_order(operative_shape)
178                    .unwrap()
179                    .sum_axis(Axis(*operative_axes.iter().max().unwrap()))
180            };
181
182            for axis in operative_axes.iter().rev().skip(1) {
183                output = output.sum_axis(Axis(*axis));
184            }
185
186            let mut output = output.into_tensor();
187
188            for &axis in axes {
189                output.insert_axis(axis).unwrap();
190            }
191
192            output
193        } else {
194            let mut output: Option<ArrayD<T>> = None;
195            for axis in axes.iter().copied() {
196                let input_view = output
197                    .as_ref()
198                    .map(|o| o.view())
199                    .unwrap_or_else(|| unsafe { input.to_array_view_unchecked::<T>() });
200
201                // Create array that will contain intermidiate result
202                let reduced_dim = input_view.shape()[axis];
203                let input_stride = input_view.strides()[axis] as usize;
204                let output_shape = input_view
205                    .shape()
206                    .iter()
207                    .enumerate()
208                    .map(|(idx, dim)| if idx != axis { *dim } else { 1 })
209                    .collect_vec();
210
211                output = Some(ArrayD::from_shape_fn(output_shape.clone(), |coords| {
212                    let mut view = input_view.view();
213                    for ix in 0..output_shape.len() {
214                        if ix != axis {
215                            view.collapse_axis(Axis(ix), coords[ix]);
216                        }
217                    }
218
219                    if let Some(slice) = view.as_slice() {
220                        if T::datum_type() == f16::datum_type() {
221                            let slice: &[f16] = unsafe { std::mem::transmute(slice) };
222                            (tract_linalg::ops().sum_f16)()
223                                .run_with_params(slice, ())
224                                .unwrap()
225                                .as_()
226                        } else if T::datum_type() == f32::datum_type() {
227                            let slice: &[f32] = unsafe { std::mem::transmute(slice) };
228                            (tract_linalg::ops().sum_f32)()
229                                .run_with_params(slice, ())
230                                .unwrap()
231                                .as_()
232                        } else {
233                            slice.iter().cloned().sum::<T>()
234                        }
235                    } else {
236                        let first: *const T = &input_view[coords];
237                        let mut sum = T::zero();
238                        for i in 0..reduced_dim {
239                            sum = sum + unsafe { *(first.add(i * input_stride)) };
240                        }
241                        sum
242                    }
243                }));
244            }
245            output.unwrap().into_tensor()
246        }
247    }
248
249    fn mean_of_squares(&self, axis: &[usize], input: &Tensor) -> TractResult<Tensor> {
250        let dt = input.datum_type();
251        let mut input = input.cast_to::<f32>()?.into_owned();
252        input.try_as_plain_mut()?.as_slice_mut::<f32>()?.iter_mut().for_each(|x| *x = *x * *x);
253        let mut output = unsafe { self.sum::<f32>(axis, &input) };
254        let norm = output.len() as f32 / input.len() as f32;
255        output.try_as_plain_mut()?.as_slice_mut::<f32>()?.iter_mut().for_each(|x| *x *= norm);
256        Ok(output.cast_to_dt(dt)?.into_owned())
257    }
258}
259
260fn argmax_t<T>(v: ArrayViewD<T>, last: bool) -> i64
261where
262    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
263{
264    v.iter()
265        .copied()
266        .enumerate()
267        .fold(
268            (0usize, T::min_value()),
269            |acc, v| {
270                if v.1 > acc.1 || (last && acc.1 == v.1) { v } else { acc }
271            },
272        )
273        .0 as i64
274}
275
276fn argmin_t<T>(v: ArrayViewD<T>, last: bool) -> i64
277where
278    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
279{
280    v.iter()
281        .copied()
282        .enumerate()
283        .fold(
284            (0usize, T::max_value()),
285            |acc, v| {
286                if v.1 < acc.1 || (last && acc.1 == v.1) { v } else { acc }
287            },
288        )
289        .0 as i64
290}
291
292fn max_t<T>(v: ArrayViewD<T>, _: ()) -> T
293where
294    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
295{
296    if T::datum_type() == f32::datum_type()
297        && let Some(slice) = v.as_slice()
298        && !slice.is_empty()
299    {
300        let slice = unsafe { transmute::<&[T], &[f32]>(slice) };
301        let max = (tract_linalg::ops().max_f32)().run(slice).unwrap();
302        // SAFETY: T is f32 in this branch (checked above).
303        return unsafe { std::mem::transmute_copy::<f32, T>(&max) };
304    }
305    v.fold(T::min_value(), |acc, &v| if acc > v { acc } else { v })
306}
307
308fn min_t<T>(v: ArrayViewD<T>, _: ()) -> T
309where
310    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
311{
312    if T::datum_type() == f32::datum_type()
313        && let Some(slice) = v.as_slice()
314        && !slice.is_empty()
315    {
316        let slice = unsafe { transmute::<&[T], &[f32]>(slice) };
317        let min = (tract_linalg::ops().min_f32)().run(slice).unwrap();
318        // SAFETY: T is f32 in this branch (checked above).
319        return unsafe { std::mem::transmute_copy::<f32, T>(&min) };
320    }
321    v.fold(T::max_value(), |acc, &v| if acc < v { acc } else { v })
322}
323
324fn prod_t<T>(v: ArrayViewD<T>, _: ()) -> T
325where
326    T: Copy + Datum + num_traits::One,
327{
328    v.fold(T::one(), |acc, &v| acc * v)
329}
330
331fn q_prod_t<T>(v: ArrayViewD<T>, zp_scale: (i32, f32)) -> T
332where
333    T: Copy + num_traits::AsPrimitive<f32> + Bounded + Datum,
334    f32: num_traits::AsPrimitive<T>,
335{
336    let (zp, scale) = zp_scale;
337    (v.fold(1f32, |acc, &v| acc * (v.as_() - zp as f32)) * scale.powi(v.len() as i32 - 1)
338        + zp as f32)
339        .clamp_cast()
340}
341
342fn q_sum_t<T>(v: ArrayViewD<T>, zp_scale: (i32, f32)) -> T
343where
344    T: Copy + Bounded + num_traits::AsPrimitive<i32> + Datum,
345    i32: num_traits::AsPrimitive<T>,
346{
347    let (zp, _) = zp_scale;
348    (v.fold(0i32, |acc, &v| acc + v.as_()) - zp * (v.len() as i32 - 1)).clamp_cast()
349}
350
351fn all_bool(v: ArrayViewD<bool>, _: ()) -> bool {
352    v.iter().all(|v| *v)
353}
354
355fn any_bool(v: ArrayViewD<bool>, _: ()) -> bool {
356    v.iter().any(|v| *v)
357}
358
359#[derive(Clone, Debug, new, Hash, PartialEq, Eq)]
360pub struct Reduce {
361    pub axes: TVec<usize>,
362    pub reducer: Reducer,
363}
364
365impl Op for Reduce {
366    fn name(&self) -> StaticName {
367        format!("Reduce<{:?}>", self.reducer).into()
368    }
369    fn info(&self) -> TractResult<Vec<String>> {
370        Ok(vec![format!("axes: {:?}", self.axes)])
371    }
372    op_as_typed_op!();
373}
374
375impl EvalOp for Reduce {
376    fn is_stateless(&self) -> bool {
377        true
378    }
379
380    fn eval(&self, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
381        Ok(tvec!(self.reducer.reduce(&self.axes, &inputs[0])?.into()))
382    }
383}
384
385impl TypedOp for Reduce {
386    fn input_roi(
387        &self,
388        model: &TypedModel,
389        node: &TypedNode,
390    ) -> TractResult<Option<TVec<Option<TDim>>>> {
391        crate::optim::propagate_roi::bubble_roi(model, node)
392    }
393
394    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
395        ensure!(self.axes.iter().tuple_windows().all(|(a, b)| a < b));
396        if inputs[0].datum_type == TDim::datum_type() {
397            bail!("Reduce input must be cast from TDim to i64 beforehand")
398        }
399        let mut shape: TVec<_> = inputs[0].shape.to_tvec();
400        for &ax in &self.axes {
401            shape[ax] = 1.to_dim();
402        }
403        let dt = if let Reducer::ArgMax(_) | Reducer::ArgMin(_) = self.reducer {
404            DatumType::I64
405        } else {
406            inputs[0].datum_type
407        };
408        Ok(tvec!(dt.fact(shape)))
409    }
410
411    fn declutter(
412        &self,
413        model: &TypedModel,
414        node: &TypedNode,
415    ) -> TractResult<Option<TypedModelPatch>> {
416        if let Some(patch) = self.declutter_mean_of_square(model, node)? {
417            return Ok(Some(patch));
418        }
419        if let Some(patch) = self.declutter_scalar_mul_then_sum(model, node)? {
420            return Ok(Some(patch));
421        }
422        if let Some(patch) = self.declutter_reduce_reduce(model, node)? {
423            return Ok(Some(patch));
424        }
425        if let Some(patch) = super::rms_norm::detect_rms_norm(self, model, node)? {
426            return Ok(Some(patch));
427        }
428        Ok(None)
429    }
430
431    fn cost(&self, inputs: &[&TypedFact]) -> TractResult<TVec<(Cost, TDim)>> {
432        let dt = inputs[0].datum_type;
433        let count: TDim = inputs[0].shape.iter().product();
434        match self.reducer {
435            Reducer::Sum
436            | Reducer::Prod
437            | Reducer::Min
438            | Reducer::Max
439            | Reducer::All
440            | Reducer::Any => Ok(tvec!((Cost::FMA(dt), count))),
441            Reducer::MeanOfSquares => Ok(tvec!((Cost::FMA(dt), count * 2))),
442            Reducer::ArgMax(_) | Reducer::ArgMin(_) => Ok(tvec!((Cost::FMA(dt), count))),
443        }
444    }
445
446    fn axes_mapping(
447        &self,
448        inputs: &[&TypedFact],
449        outputs: &[&TypedFact],
450    ) -> TractResult<AxesMapping> {
451        let mut letters = 'a'..;
452        let axes = (0..inputs[0].rank())
453            .flat_map(|ix| {
454                if self.axes.contains(&ix) {
455                    tvec!(
456                        Axis::new(letters.next().unwrap(), inputs.len(), outputs.len())
457                            .input(0, ix),
458                        Axis::new(letters.next().unwrap(), inputs.len(), outputs.len())
459                            .output(0, ix),
460                    )
461                } else {
462                    tvec!(
463                        Axis::new(letters.next().unwrap(), inputs.len(), outputs.len())
464                            .input(0, ix)
465                            .output(0, ix)
466                    )
467                }
468                .into_iter()
469            })
470            .collect_vec();
471        AxesMapping::new(1, 1, axes)
472    }
473
474    fn change_axes(
475        &self,
476        model: &TypedModel,
477        node: &TypedNode,
478        _io: InOut,
479        change: &AxisOp,
480    ) -> TractResult<Option<AxisChangeConsequence>> {
481        let mut axes = tvec!();
482        for reduced in &self.axes {
483            rule_if_some!(axis = change.transform_axis(*reduced));
484            axes.push(axis);
485        }
486        axes.sort();
487        let op = Some(Box::new(Self { axes, ..self.clone() }) as _);
488        Ok(Some(AxisChangeConsequence::new(model, node, op, change)))
489    }
490
491    fn slice(
492        &self,
493        patch: &mut TypedModelPatch,
494        _model: &TypedModel,
495        node: &TypedNode,
496        _prefix: &str,
497        inputs: &[OutletId],
498        output_axis: usize,
499        _start: &TDim,
500        _end: &TDim,
501    ) -> TractResult<Option<TVec<OutletId>>> {
502        rule_if!(!self.axes.contains(&output_axis));
503        patch.wire_node(&node.name, &node.op, inputs).map(Some)
504    }
505
506    as_op!();
507}
508
509impl Reduce {
510    fn declutter_reduce_reduce(
511        &self,
512        model: &TypedModel,
513        node: &TypedNode,
514    ) -> TractResult<Option<TypedModelPatch>> {
515        use Reducer::*;
516        rule_if_some!(prec = model.linear_prec(node.id)?);
517        rule_if_some!(prec_reduce = prec.op_as::<Self>());
518        rule_if!(prec_reduce.reducer == self.reducer);
519        rule_if!([Sum, Prod, Min, Max].contains(&self.reducer));
520        let mut patch = TypedModelPatch::default();
521        let wire = patch.tap_model(model, prec.inputs[0])?;
522        let wire = patch.wire_node(
523            &node.name,
524            Self {
525                reducer: self.reducer,
526                axes: prec_reduce
527                    .axes
528                    .iter()
529                    .chain(self.axes.iter())
530                    .copied()
531                    .sorted()
532                    .dedup()
533                    .collect(),
534            },
535            &[wire],
536        )?;
537        patch.shunt_outside(model, node.id.into(), wire[0])?;
538        Ok(Some(patch))
539    }
540
541    fn declutter_scalar_mul_then_sum(
542        &self,
543        model: &TypedModel,
544        node: &TypedNode,
545    ) -> TractResult<Option<TypedModelPatch>> {
546        if self.reducer == Reducer::Sum {
547            rule_if_some!(prec = model.linear_prec(node.id)?);
548            rule_if_some!(prec_bin = prec.op_as::<TypedBinOp>());
549            rule_if!(prec_bin.0.is::<Mul>());
550            let mul_input_fact = model.node_input_facts(prec.id)?;
551            rule_if_some!(
552                scalar_slot = mul_input_fact
553                    .iter()
554                    .position(|f| f.konst.as_ref().is_some_and(|k| k.volume() == 1))
555            );
556            let mut patch = TypedModelPatch::default();
557            let scalar = patch.tap_model(model, prec.inputs[scalar_slot])?;
558            let wire = patch.tap_model(model, prec.inputs[1 - scalar_slot])?;
559            let wire = patch.wire_node(&node.name, self.clone(), &[wire])?[0];
560            let wire = patch.wire_node(&prec.name, prec_bin.clone(), &[wire, scalar])?[0];
561            patch.shunt_outside(model, node.id.into(), wire)?;
562            return Ok(Some(patch));
563        }
564        Ok(None)
565    }
566
567    fn declutter_mean_of_square(
568        &self,
569        model: &TypedModel,
570        node: &TypedNode,
571    ) -> TractResult<Option<TypedModelPatch>> {
572        if self.reducer == Reducer::Sum {
573            rule_if_some!(prec = model.linear_prec(node.id)?);
574            rule_if_some!(prec_ew = prec.op_as::<ElementWiseOp>());
575            rule_if!(prec_ew.0.is::<Square>());
576            rule_if!(node.outputs.len() == 1);
577            rule_if!(node.outputs[0].successors.len() == 1);
578            let our_inlet = node.outputs[0].successors[0];
579            let succ = model.node(our_inlet.node);
580            rule_if_some!(succ_bin = succ.op_as::<TypedBinOp>());
581            rule_if!(succ_bin.0.is::<Mul>());
582            let other = succ.inputs[1 - our_inlet.slot];
583            rule_if_some!(other_konst = model.outlet_fact(other)?.uniform.as_ref());
584            let norm: TDim = self.axes.iter().map(|&ax| &prec.outputs[0].fact.shape[ax]).product();
585            rule_if_some!(norm = norm.as_i64());
586            rule_if!(norm > 0);
587            let norm = tensor0((norm as f32).recip());
588            if other_konst.close_enough(&norm, Approximation::Close).is_ok() {
589                let mut patch = TypedModelPatch::default();
590                let wire = patch.tap_model(model, prec.inputs[0])?;
591                let wire = patch.wire_node(
592                    &node.name,
593                    Reduce::new(self.axes.clone(), Reducer::MeanOfSquares),
594                    &[wire],
595                )?[0];
596                patch.shunt_outside(model, succ.id.into(), wire)?;
597                return Ok(Some(patch));
598            }
599        }
600        Ok(None)
601    }
602}
603
604pub fn expand_mean_of_squares(
605    _ctx: &(),
606    model: &TypedModel,
607    node: &TypedNode,
608    name: &str,
609    op: &Reduce,
610) -> TractResult<Option<TypedModelPatch>> {
611    rule_if!(op.reducer == Reducer::MeanOfSquares);
612    let mut patch = TypedModelPatch::default();
613    let mut wire = tvec!(patch.tap_model(model, node.inputs[0])?);
614    let input_fact = model.outlet_fact(node.inputs[0])?;
615    let dt = input_fact.datum_type;
616    if dt != f32::datum_type() {
617        wire = patch.wire_node(format!("{name}.to_f32"), cast(f32::datum_type()), &wire)?;
618    }
619    wire = patch.wire_node(format!("{name}.sqr"), square(), &wire)?;
620    wire = patch.wire_node(
621        format!("{name}.sum"),
622        Reduce::new(op.axes.clone(), Reducer::Sum),
623        &wire,
624    )?;
625    let card = input_fact
626        .shape
627        .iter()
628        .enumerate()
629        .filter(|(ix, _dim)| op.axes.contains(ix))
630        .map(|(_ix, dim)| dim)
631        .product::<TDim>();
632    let card = patch.add_const(format!("{name}.card"), tensor0(card))?;
633    let card = patch.wire_node(format!("{name}.card_to_f32"), cast(f32::datum_type()), &[card])?;
634
635    wire =
636        wire_with_rank_broadcast(format!("{name}.norm"), &mut patch, div(), &[wire[0], card[0]])?;
637    if dt != f32::datum_type() {
638        wire = patch.wire_node(format!("{name}.from_f32"), cast(dt), &wire)?;
639    }
640    patch.shunt_outside(model, node.id.into(), wire[0])?;
641    Ok(Some(patch))
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    // Guards the f32 max reduction (max_t): the SIMD `max_f32` kernel result must
649    // be returned (contiguous path), with the scalar fold used only for strided
650    // slices. Checked against explicit per-row / per-col references.
651    #[test]
652    fn reduce_max_f32_contiguous_and_strided() {
653        let (r, c) = (5usize, 37usize); // c not a multiple of the SIMD width (tail)
654        let data: Vec<f32> = (0..r * c).map(|i| ((i * 31 % 97) as f32) - 48.0).collect();
655        let t = Tensor::from_shape(&[r, c], &data).unwrap();
656
657        // axis 1: per-row max — contiguous slices -> SIMD path.
658        let got = Reducer::Max.reduce(&[1], &t).unwrap();
659        assert_eq!(got.shape(), &[r, 1]);
660        for (i, &g) in unsafe { got.as_slice_unchecked::<f32>() }.iter().enumerate() {
661            let want = data[i * c..(i + 1) * c].iter().copied().fold(f32::MIN, f32::max);
662            assert_eq!(g, want, "row {i}");
663        }
664
665        // axis 0: per-col max — strided slices -> scalar fold.
666        let got = Reducer::Max.reduce(&[0], &t).unwrap();
667        assert_eq!(got.shape(), &[1, c]);
668        for (j, &g) in unsafe { got.as_slice_unchecked::<f32>() }.iter().enumerate() {
669            let want = (0..r).map(|i| data[i * c + j]).fold(f32::MIN, f32::max);
670            assert_eq!(g, want, "col {j}");
671        }
672
673        // k == 1 (single-element reduction) exercises the SIMD-path length guard.
674        let t1 = Tensor::from_shape(&[3, 1], &[1.0f32, -2.0, 3.0]).unwrap();
675        let got = Reducer::Max.reduce(&[1], &t1).unwrap();
676        assert_eq!(unsafe { got.as_slice_unchecked::<f32>() }, &[1.0, -2.0, 3.0]);
677    }
678
679    // Same coverage for the f32 min reduction (min_t -> SIMD min_f32 / scalar fold).
680    #[test]
681    fn reduce_min_f32_contiguous_and_strided() {
682        let (r, c) = (5usize, 37usize); // c not a multiple of the SIMD width (tail)
683        let data: Vec<f32> = (0..r * c).map(|i| ((i * 31 % 97) as f32) - 48.0).collect();
684        let t = Tensor::from_shape(&[r, c], &data).unwrap();
685
686        // axis 1: per-row min — contiguous slices -> SIMD path.
687        let got = Reducer::Min.reduce(&[1], &t).unwrap();
688        assert_eq!(got.shape(), &[r, 1]);
689        for (i, &g) in unsafe { got.as_slice_unchecked::<f32>() }.iter().enumerate() {
690            let want = data[i * c..(i + 1) * c].iter().copied().fold(f32::MAX, f32::min);
691            assert_eq!(g, want, "row {i}");
692        }
693
694        // axis 0: per-col min — strided slices -> scalar fold.
695        let got = Reducer::Min.reduce(&[0], &t).unwrap();
696        assert_eq!(got.shape(), &[1, c]);
697        for (j, &g) in unsafe { got.as_slice_unchecked::<f32>() }.iter().enumerate() {
698            let want = (0..r).map(|i| data[i * c + j]).fold(f32::MAX, f32::min);
699            assert_eq!(g, want, "col {j}");
700        }
701    }
702}