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::{div, square, Mul, 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}
61
62impl Reducer {
63    pub fn reduce(&self, axes: &[usize], input: &Tensor) -> TractResult<Tensor> {
64        use Reducer::*;
65        let dt = input.datum_type();
66        let output_shape: Vec<usize> = input
67            .shape()
68            .iter()
69            .enumerate()
70            .map(|(ax, &d)| if axes.contains(&ax) { 1 } else { d })
71            .collect();
72        let (zp, scale) = input.datum_type().zp_scale();
73        unsafe {
74            let mut t = match self {
75                ArgMax(last) => {
76                    r!(Self::reduce_t(dt)(self, axes, &output_shape, input, argmax_t, *last))
77                }
78                ArgMin(last) => {
79                    r!(Self::reduce_t(dt)(self, axes, &output_shape, input, argmin_t, *last))
80                }
81                Min => r!(Self::reduce_t(dt)(self, axes, &output_shape, input, min_t, ())),
82                Max => r!(Self::reduce_t(dt)(self, axes, &output_shape, input, max_t, ())),
83                Prod => {
84                    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)))
85                }
86                Sum => {
87                    if dt.is_float() {
88                        dispatch_floatlike!(Self::sum(dt)(self, axes, input))
89                    } else {
90                        r!(Self::reduce_t(dt)(
91                            self,
92                            axes,
93                            &output_shape,
94                            input,
95                            q_sum_t,
96                            (zp, scale)
97                        ))
98                    }
99                }
100                MeanOfSquares => self.mean_of_squares(axes, input)?,
101            };
102            if input.datum_type().is_quantized()
103                && input.datum_type().unquantized() == t.datum_type().unquantized()
104            {
105                t.set_datum_type(input.datum_type());
106            }
107            Ok(t)
108        }
109    }
110
111    unsafe fn reduce_t<T, TO, F, A>(
112        &self,
113        axes: &[usize],
114        output_shape: &[usize],
115        input_tensor: &Tensor,
116        f: F,
117        args: A,
118    ) -> Tensor
119    where
120        F: for<'a> Fn(ArrayViewD<'a, T>, A) -> TO,
121        T: Copy + Datum,
122        TO: Copy + Datum,
123        A: Copy,
124    {
125        use ndarray::*;
126        let input = input_tensor.to_array_view_unchecked::<T>();
127        let result = Array::from_shape_fn(output_shape, |coords| {
128            let slice_spec: Vec<SliceInfoElem> = coords
129                .slice()
130                .iter()
131                .enumerate()
132                .map(|(ax, &d)| if axes.contains(&ax) { (..).into() } else { d.into() })
133                .collect();
134            let slice_info = SliceInfo::<_, IxDyn, IxDyn>::try_from(slice_spec).unwrap();
135            let slice = input.slice(&slice_info);
136            f(slice, args)
137        });
138        result.into_tensor()
139    }
140
141    // sum is a special citizen: enough activity that it gets "special"
142    // treatment. we could use the same "algo" for min, max and prod, to the
143    // price of more code in the library. argmax and argmin are more
144    // tricky (not associative)
145    unsafe fn sum<T>(&self, axes: &[usize], input: &Tensor) -> Tensor
146    where
147        T: Copy + Datum + num_traits::Zero + Sum,
148        f16: AsPrimitive<T>,
149        f32: AsPrimitive<T>,
150    {
151        if axes.len() == 0 {
152            return input.to_owned();
153        }
154
155        // use tract-optimized path only when single reuction axis and is at end
156        if axes.len() > 1 || axes[0] != input.rank() - 1 {
157            let mut operative_axes = vec![];
158            let mut operative_shape: Vec<usize> = vec![];
159            for (ix, dim) in input.shape().iter().enumerate() {
160                // axis is reduced, but is not the first of a series of reduced axes
161                if ix > 0 && axes.contains(&ix) && axes.contains(&(ix - 1)) {
162                    *operative_shape.last_mut().unwrap() *= *dim;
163                } else if axes.contains(&ix) {
164                    operative_axes.push(operative_shape.len());
165                    operative_shape.push(*dim);
166                } else {
167                    operative_shape.push(*dim);
168                }
169            }
170            let mut output = input
171                .to_array_view_unchecked::<T>()
172                .into_shape_with_order(operative_shape)
173                .unwrap()
174                .sum_axis(Axis(*operative_axes.iter().max().unwrap()));
175
176            for axis in operative_axes.iter().rev().skip(1) {
177                output = output.sum_axis(Axis(*axis));
178            }
179
180            let mut output = output.into_tensor();
181
182            for &axis in axes {
183                output.insert_axis(axis).unwrap();
184            }
185
186            output
187        } else {
188            let mut output: Option<ArrayD<T>> = None;
189            for axis in axes.iter().copied() {
190                let input_view = output
191                    .as_ref()
192                    .map(|o| o.view())
193                    .unwrap_or_else(|| input.to_array_view_unchecked::<T>());
194
195                // Create array that will contain intermidiate result
196                let reduced_dim = input_view.shape()[axis];
197                let input_stride = input_view.strides()[axis] as usize;
198                let output_shape = input_view
199                    .shape()
200                    .iter()
201                    .enumerate()
202                    .map(|(idx, dim)| if idx != axis { *dim } else { 1 })
203                    .collect_vec();
204
205                output = Some(ArrayD::from_shape_fn(output_shape.clone(), |coords| {
206                    let mut view = input_view.view();
207                    for ix in 0..output_shape.len() {
208                        if ix != axis {
209                            view.collapse_axis(Axis(ix), coords[ix]);
210                        }
211                    }
212
213                    if let Some(slice) = view.as_slice() {
214                        if T::datum_type() == f16::datum_type() {
215                            let slice: &[f16] = unsafe { std::mem::transmute(slice) };
216                            (tract_linalg::ops().sum_f16)()
217                                .run_with_params(slice, ())
218                                .unwrap()
219                                .as_()
220                        } else if T::datum_type() == f32::datum_type() {
221                            let slice: &[f32] = unsafe { std::mem::transmute(slice) };
222                            (tract_linalg::ops().sum_f32)()
223                                .run_with_params(slice, ())
224                                .unwrap()
225                                .as_()
226                        } else {
227                            slice.iter().cloned().sum::<T>()
228                        }
229                    } else {
230                        let first: *const T = &input_view[coords];
231                        let mut sum = T::zero();
232                        for i in 0..reduced_dim {
233                            sum = sum + *(first.add(i * input_stride));
234                        }
235                        sum
236                    }
237                }));
238            }
239            output.unwrap().into_tensor()
240        }
241    }
242
243    fn mean_of_squares(&self, axis: &[usize], input: &Tensor) -> TractResult<Tensor> {
244        let dt = input.datum_type();
245        let mut input = input.cast_to::<f32>()?.into_owned();
246        input.as_slice_mut::<f32>()?.iter_mut().for_each(|x| *x = *x * *x);
247        let mut output = unsafe { self.sum::<f32>(axis, &input) };
248        let norm = output.len() as f32 / input.len() as f32;
249        output.as_slice_mut::<f32>()?.iter_mut().for_each(|x| *x *= norm);
250        Ok(output.cast_to_dt(dt)?.into_owned())
251    }
252}
253
254fn argmax_t<T>(v: ArrayViewD<T>, last: bool) -> i64
255where
256    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
257{
258    v.iter()
259        .copied()
260        .enumerate()
261        .fold(
262            (0usize, T::min_value()),
263            |acc, v| {
264                if v.1 > acc.1 || (last && acc.1 == v.1) {
265                    v
266                } else {
267                    acc
268                }
269            },
270        )
271        .0 as i64
272}
273
274fn argmin_t<T>(v: ArrayViewD<T>, last: bool) -> i64
275where
276    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
277{
278    v.iter()
279        .copied()
280        .enumerate()
281        .fold(
282            (0usize, T::max_value()),
283            |acc, v| {
284                if v.1 < acc.1 || (last && acc.1 == v.1) {
285                    v
286                } else {
287                    acc
288                }
289            },
290        )
291        .0 as i64
292}
293
294fn max_t<T>(v: ArrayViewD<T>, _: ()) -> T
295where
296    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
297{
298    if T::datum_type() == f32::datum_type() {
299        if let Some(slice) = v.as_slice() {
300            let slice = unsafe { transmute::<&[T], &[f32]>(slice) };
301            (tract_linalg::ops().max_f32)().run(slice).unwrap();
302        }
303    }
304    v.fold(T::min_value(), |acc, &v| if acc > v { acc } else { v })
305}
306
307fn min_t<T>(v: ArrayViewD<T>, _: ()) -> T
308where
309    T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
310{
311    v.fold(T::max_value(), |acc, &v| if acc < v { acc } else { v })
312}
313
314fn prod_t<T>(v: ArrayViewD<T>, _: ()) -> T
315where
316    T: Copy + Datum + num_traits::One,
317{
318    v.fold(T::one(), |acc, &v| acc * v)
319}
320
321fn q_prod_t<T>(v: ArrayViewD<T>, zp_scale: (i32, f32)) -> T
322where
323    T: Copy + num_traits::AsPrimitive<f32> + Bounded + Datum,
324    f32: num_traits::AsPrimitive<T>,
325{
326    let (zp, scale) = zp_scale;
327    (v.fold(1f32, |acc, &v| acc * (v.as_() - zp as f32)) * scale.powi(v.len() as i32 - 1)
328        + zp as f32)
329        .clamp_cast()
330}
331
332fn q_sum_t<T>(v: ArrayViewD<T>, zp_scale: (i32, f32)) -> T
333where
334    T: Copy + Bounded + num_traits::AsPrimitive<i32> + Datum,
335    i32: num_traits::AsPrimitive<T>,
336{
337    let (zp, _) = zp_scale;
338    (v.fold(0i32, |acc, &v| acc + v.as_()) - zp * (v.len() as i32 - 1)).clamp_cast()
339}
340
341#[derive(Clone, Debug, new, Hash)]
342pub struct Reduce {
343    pub axes: TVec<usize>,
344    pub reducer: Reducer,
345}
346
347impl Op for Reduce {
348    fn name(&self) -> Cow<str> {
349        format!("Reduce<{:?}>", self.reducer).into()
350    }
351    fn info(&self) -> TractResult<Vec<String>> {
352        Ok(vec![format!("axes: {:?}", self.axes)])
353    }
354    op_as_typed_op!();
355}
356
357impl EvalOp for Reduce {
358    fn is_stateless(&self) -> bool {
359        true
360    }
361
362    fn eval(&self, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
363        Ok(tvec!(self.reducer.reduce(&self.axes, &inputs[0])?.into()))
364    }
365}
366
367impl TypedOp for Reduce {
368    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
369        ensure!(self.axes.iter().tuple_windows().all(|(a, b)| a < b));
370        if inputs[0].datum_type == TDim::datum_type() {
371            bail!("Reduce input must be cast from TDim to i64 beforehand")
372        }
373        let mut shape: TVec<_> = inputs[0].shape.to_tvec();
374        for &ax in &self.axes {
375            shape[ax] = 1.to_dim();
376        }
377        let dt = if let Reducer::ArgMax(_) | Reducer::ArgMin(_) = self.reducer {
378            DatumType::I64
379        } else {
380            inputs[0].datum_type
381        };
382        Ok(tvec!(dt.fact(shape)))
383    }
384
385    fn declutter(
386        &self,
387        model: &TypedModel,
388        node: &TypedNode,
389    ) -> TractResult<Option<TypedModelPatch>> {
390        if let Some(patch) = self.declutter_mean_of_square(model, node)? {
391            return Ok(Some(patch));
392        }
393        if let Some(patch) = self.declutter_scalar_mul_then_sum(model, node)? {
394            return Ok(Some(patch));
395        }
396        if let Some(patch) = self.declutter_reduce_reduce(model, node)? {
397            return Ok(Some(patch));
398        }
399        Ok(None)
400    }
401
402    fn axes_mapping(
403        &self,
404        inputs: &[&TypedFact],
405        outputs: &[&TypedFact],
406    ) -> TractResult<AxesMapping> {
407        let mut letters = 'a'..;
408        let axes = (0..inputs[0].rank())
409            .flat_map(|ix| {
410                if self.axes.contains(&ix) {
411                    tvec!(
412                        Axis::new(letters.next().unwrap(), inputs.len(), outputs.len())
413                            .input(0, ix),
414                        Axis::new(letters.next().unwrap(), inputs.len(), outputs.len())
415                            .output(0, ix),
416                    )
417                } else {
418                    tvec!(Axis::new(letters.next().unwrap(), inputs.len(), outputs.len())
419                        .input(0, ix)
420                        .output(0, ix))
421                }
422                .into_iter()
423            })
424            .collect_vec();
425        AxesMapping::new(1, 1, axes)
426    }
427
428    fn change_axes(
429        &self,
430        model: &TypedModel,
431        node: &TypedNode,
432        _io: InOut,
433        change: &AxisOp,
434    ) -> TractResult<Option<AxisChangeConsequence>> {
435        let mut axes = tvec!();
436        for reduced in &self.axes {
437            if let Some(axis) = change.transform_axis(*reduced) {
438                axes.push(axis);
439            } else {
440                return Ok(None);
441            }
442        }
443        axes.sort();
444        let op = Some(Box::new(Self { axes, ..self.clone() }) as _);
445        Ok(Some(AxisChangeConsequence::new(model, node, op, change)))
446    }
447
448    fn slice(
449        &self,
450        patch: &mut TypedModelPatch,
451        _model: &TypedModel,
452        node: &TypedNode,
453        _prefix: &str,
454        inputs: &[OutletId],
455        output_axis: usize,
456        _start: &TDim,
457        _end: &TDim,
458    ) -> TractResult<Option<TVec<OutletId>>> {
459        if self.axes.contains(&output_axis) {
460            return Ok(None);
461        }
462        patch.wire_node(&node.name, &node.op, inputs).map(Some)
463    }
464
465    as_op!();
466}
467
468impl Reduce {
469    fn declutter_reduce_reduce(
470        &self,
471        model: &TypedModel,
472        node: &TypedNode,
473    ) -> TractResult<Option<TypedModelPatch>> {
474        let Some(prec) = model.single_prec(node.id)? else {
475            return Ok(None);
476        };
477        let Some(prec_reduce) = prec.op_as::<Self>() else {
478            return Ok(None);
479        };
480        use Reducer::*;
481        if prec_reduce.reducer != self.reducer || ![Sum, Prod, Min, Max].contains(&self.reducer) {
482            return Ok(None);
483        }
484        let mut patch = TypedModelPatch::default();
485        let wire = patch.tap_model(model, prec.inputs[0])?;
486        let wire = patch.wire_node(
487            &node.name,
488            Self {
489                reducer: self.reducer,
490                axes: prec_reduce
491                    .axes
492                    .iter()
493                    .chain(self.axes.iter())
494                    .copied()
495                    .sorted()
496                    .dedup()
497                    .collect(),
498            },
499            &[wire],
500        )?;
501        patch.shunt_outside(model, node.id.into(), wire[0])?;
502        Ok(Some(patch))
503    }
504
505    fn declutter_scalar_mul_then_sum(
506        &self,
507        model: &TypedModel,
508        node: &TypedNode,
509    ) -> TractResult<Option<TypedModelPatch>> {
510        if self.reducer == Reducer::Sum {
511            let Some(prec) = model.single_prec(node.id)? else {
512                return Ok(None);
513            };
514            let Some(prec_bin) = prec.op_as::<TypedBinOp>() else {
515                return Ok(None);
516            };
517            if !prec_bin.0.is::<Mul>() {
518                return Ok(None);
519            }
520            let mul_input_fact = model.node_input_facts(prec.id)?;
521            let Some(scalar_slot) = mul_input_fact
522                .iter()
523                .position(|f| f.konst.as_ref().is_some_and(|k| k.volume() == 1))
524            else {
525                return Ok(None);
526            };
527            let mut patch = TypedModelPatch::default();
528            let scalar = patch.tap_model(model, prec.inputs[scalar_slot])?;
529            let wire = patch.tap_model(model, prec.inputs[1 - scalar_slot])?;
530            let wire = patch.wire_node(&node.name, self.clone(), &[wire])?[0];
531            let wire = patch.wire_node(&prec.name, prec_bin.clone(), &[wire, scalar])?[0];
532            patch.shunt_outside(model, node.id.into(), wire)?;
533            return Ok(Some(patch));
534        }
535        Ok(None)
536    }
537
538    fn declutter_mean_of_square(
539        &self,
540        model: &TypedModel,
541        node: &TypedNode,
542    ) -> TractResult<Option<TypedModelPatch>> {
543        if self.reducer == Reducer::Sum {
544            let Some(prec) = model.single_prec(node.id)? else {
545                return Ok(None);
546            };
547            let Some(prec_ew) = prec.op_as::<ElementWiseOp>() else {
548                return Ok(None);
549            };
550            if !prec_ew.0.is::<Square>() {
551                return Ok(None);
552            }
553            if node.outputs.len() != 1 || node.outputs[0].successors.len() != 1 {
554                return Ok(None);
555            }
556            let our_inlet = node.outputs[0].successors[0];
557            let succ = model.node(our_inlet.node);
558            let Some(succ_bin) = succ.op_as::<TypedBinOp>() else {
559                return Ok(None);
560            };
561            if !succ_bin.0.is::<Mul>() {
562                return Ok(None);
563            }
564            let other = succ.inputs[1 - our_inlet.slot];
565            let Some(other_konst) = model.outlet_fact(other)?.uniform.as_ref() else {
566                return Ok(None);
567            };
568            let norm: TDim = self.axes.iter().map(|&ax| &prec.outputs[0].fact.shape[ax]).product();
569            let Some(norm) = norm.as_i64() else {
570                return Ok(None);
571            };
572            if norm == 0 {
573                return Ok(None);
574            }
575            let norm = tensor0((norm as f32).recip());
576            if other_konst.close_enough(&norm, Approximation::Close).is_ok() {
577                let mut patch = TypedModelPatch::default();
578                let wire = patch.tap_model(model, prec.inputs[0])?;
579                let wire = patch.wire_node(
580                    &node.name,
581                    Reduce::new(self.axes.clone(), Reducer::MeanOfSquares),
582                    &[wire],
583                )?[0];
584                patch.shunt_outside(model, succ.id.into(), wire)?;
585                return Ok(Some(patch));
586            }
587        }
588        Ok(None)
589    }
590}
591
592pub fn expand_mean_of_squares(
593    _ctx: &(),
594    model: &TypedModel,
595    node: &TypedNode,
596    name: &str,
597    op: &Reduce,
598) -> TractResult<Option<TypedModelPatch>> {
599    if op.reducer == Reducer::MeanOfSquares {
600        let mut patch = TypedModelPatch::default();
601        let mut wire = tvec!(patch.tap_model(model, node.inputs[0])?);
602        let input_fact = model.outlet_fact(node.inputs[0])?;
603        let dt = input_fact.datum_type;
604        if dt != f32::datum_type() {
605            wire = patch.wire_node(format!("{name}.to_f32"), cast(f32::datum_type()), &wire)?;
606        }
607        wire = patch.wire_node(format!("{name}.sqr"), square(), &wire)?;
608        wire = patch.wire_node(
609            format!("{name}.sum"),
610            Reduce::new(op.axes.clone(), Reducer::Sum),
611            &wire,
612        )?;
613        let card = input_fact
614            .shape
615            .iter()
616            .enumerate()
617            .filter(|(ix, _dim)| op.axes.contains(ix))
618            .map(|(_ix, dim)| dim)
619            .product::<TDim>();
620        let card = patch.add_const(format!("{name}.card"), tensor0(card))?;
621        let card =
622            patch.wire_node(format!("{name}.card_to_f32"), cast(f32::datum_type()), &[card])?;
623
624        wire = wire_with_rank_broadcast(
625            format!("{name}.norm"),
626            &mut patch,
627            div(),
628            &[wire[0], card[0]],
629        )?;
630        if dt != f32::datum_type() {
631            wire = patch.wire_node(format!("{name}.from_f32"), cast(dt), &wire)?;
632        }
633        patch.shunt_outside(model, node.id.into(), wire[0])?;
634        Ok(Some(patch))
635    } else {
636        Ok(None)
637    }
638}