Skip to main content

tract_core/ops/matmul/
optimized.rs

1use crate::internal::*;
2use crate::ops::cast::{Cast, cast};
3use crate::ops::change_axes::wire_with_rank_broadcast;
4use crate::ops::element_wise::ElementWiseOp;
5use crate::ops::nn::LeakyRelu;
6use ndarray::*;
7use tract_itertools::Itertools;
8
9use tract_linalg::mmm::{
10    AsInputValue, EagerPackedInput, FusedSpec, MMMInputValue, MatMatMul, OutputStore,
11    OutputStoreSpec, PackedMatrixStorage, PanelExtractInput, PanelExtractor,
12};
13use tract_linalg::pack::PackedFormat;
14use tract_linalg::{BinOp, Scaler};
15use tract_smallvec::ToSmallVec;
16
17use super::ModePicker;
18
19/// If `new` is `old` with only size-1 axes dropped (non-unit axes untouched, in
20/// order, nothing added or merged), return the removed axis indices; otherwise
21/// `None`. Such a reshape is a pure metadata squeeze the matmul store can absorb.
22fn pure_squeeze_removed(old: &[usize], new: &[usize]) -> Option<TVec<usize>> {
23    let mut removed: TVec<usize> = tvec!();
24    let mut j = 0;
25    for (i, &d) in old.iter().enumerate() {
26        if j < new.len() && d == new[j] {
27            j += 1;
28        } else if d == 1 {
29            removed.push(i);
30        } else {
31            return None;
32        }
33    }
34    (j == new.len() && !removed.is_empty()).then_some(removed)
35}
36
37/// A matmul operand: either an index into the runtime inputs, or a constant
38/// packed value baked in at `fuse()` time (its source outlet was `konst`), so
39/// it is never re-resolved per call. Only non-batched operands are baked.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum MatMulOperand {
42    Input(usize),
43    Const(Box<dyn MMMInputValue>),
44}
45
46impl MatMulOperand {
47    /// Base packed value for the trivial (non-batched) path.
48    #[inline]
49    unsafe fn trivial_value<'t>(&'t self, inputs: &'t [TValue]) -> &'t dyn MMMInputValue {
50        match self {
51            MatMulOperand::Input(i) => unsafe {
52                inputs
53                    .get_unchecked(*i)
54                    .try_storage_as::<PackedMatrixStorage>()
55                    .unwrap_unchecked()
56                    .value()
57            },
58            MatMulOperand::Const(v) => &**v,
59        }
60    }
61}
62
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub enum ProtoFusedSpec {
65    AddMatMul {
66        geo: AddMatMulGeometry,
67        a: MatMulOperand,
68        b: MatMulOperand,
69        packings: Vec<(usize, Option<PanelExtractor>)>,
70    },
71    BinScalar(usize, BinOp),
72    LeakyRelu(usize),
73    BinPerRow(usize, BinOp, MapOutputAxisToInput),
74    BinPerCol(usize, BinOp, MapOutputAxisToInput),
75    AddRowColProducts(usize, usize),
76    AddUnicast(OutputStoreSpec, usize, MapOutputAxisToInput),
77    Scaler(Scaler),
78    Store(Vec<OutputStoreSpec>),
79}
80
81impl ProtoFusedSpec {
82    pub fn format(&self, mmm: &dyn MatMatMul, mode: usize) -> String {
83        use ProtoFusedSpec::*;
84        match self {
85            AddMatMul { geo, packings: packing, .. } => {
86                let (a, b) = &mmm.packings()[packing[mode].0];
87                format!("matmul(k={}, {a:?}•{b:?})", geo.k)
88            }
89            BinScalar(_, op) => format!("scalar{op:?}"),
90            LeakyRelu(alpha) => format!("leaky_relu({alpha:?})"),
91            BinPerRow(_, op, _) => format!("row{op:?}"),
92            BinPerCol(_, op, _) => format!("col{op:?}"),
93            AddRowColProducts(_, _) => "add_row_col_product".to_string(),
94            AddUnicast(_, _, _) => "add_to_matrix".to_string(),
95            Scaler(s) => format!("scale({})", 1f32 * *s),
96            Store(_oss) => "store".to_string(),
97        }
98    }
99
100    pub fn resolve<'t>(
101        &'t self,
102        inputs: &'t [TValue],
103        output_coords: &[usize],
104        output: &Tensor,
105        mmm: &dyn MatMatMul,
106        mode: usize,
107    ) -> FusedSpec<'t> {
108        #[allow(clippy::let_and_return)]
109        let fs = match self {
110            ProtoFusedSpec::AddMatMul { geo, a, b, packings } => {
111                let resolve =
112                    |operand: &'t MatMulOperand, mapping: &MapOutputAxisToInput| match operand {
113                        MatMulOperand::Input(i) => {
114                            let storage =
115                                inputs[*i].try_storage_as::<PackedMatrixStorage>().unwrap();
116                            let idx = mapping.flat_index(output_coords, storage.batch_strides());
117                            storage.value_at_flat(idx)
118                        }
119                        MatMulOperand::Const(v) => &**v,
120                    };
121                let a = resolve(a, &geo.c_to_a_axis_mapping);
122                let b = resolve(b, &geo.c_to_b_axis_mapping);
123
124                let (_a_packing, b_packing) = &mmm.packings()[packings[mode].0];
125                let pa = if let Some(extractor) = &packings[mode].1 {
126                    let data = a.downcast_ref::<EagerPackedInput>().unwrap();
127                    AsInputValue::Owned(Box::new(PanelExtractInput {
128                        format: extractor.clone(),
129                        data: data.clone(),
130                    }))
131                } else {
132                    AsInputValue::Borrowed(a)
133                };
134                assert!(
135                    b_packing.dyn_eq(b.format())
136                        || (b_packing.is::<PackedFormat>() && b_packing.r() == b.format().r())
137                );
138                debug_assert!(pa.k().to_dim().compatible_with(&geo.k.to_dim()));
139                debug_assert!(b.k().to_dim().compatible_with(&geo.k.to_dim()));
140                FusedSpec::AddMatMul {
141                    a: pa,
142                    b: AsInputValue::Borrowed(b),
143                    packing: packings[mode].0,
144                }
145            }
146            ProtoFusedSpec::BinScalar(v, op) => FusedSpec::BinScalar(&inputs[*v], *op),
147            ProtoFusedSpec::LeakyRelu(v) => FusedSpec::LeakyRelu(&inputs[*v]),
148            ProtoFusedSpec::BinPerRow(v, op, map) => {
149                let mut v = inputs[*v].view();
150                unsafe { map.translate_view(output_coords, &mut v) }
151                FusedSpec::BinPerRow(v, *op)
152            }
153            ProtoFusedSpec::BinPerCol(v, op, map) => {
154                let mut v = inputs[*v].view();
155                unsafe { map.translate_view(output_coords, &mut v) }
156                FusedSpec::BinPerCol(v, *op)
157            }
158            ProtoFusedSpec::AddRowColProducts(row, col) => {
159                FusedSpec::AddRowColProducts(&inputs[*row], &inputs[*col])
160            }
161            ProtoFusedSpec::AddUnicast(store, v, map) => unsafe {
162                let mut view = inputs[*v].view();
163                map.translate_view(output_coords, &mut view);
164                FusedSpec::AddUnicast(store.wrap(&view))
165            },
166            ProtoFusedSpec::Scaler(scaler) => scaler.as_fused_spec(),
167            ProtoFusedSpec::Store(oss) => unsafe {
168                let view = output.view_offsetting_unchecked(output_coords);
169                FusedSpec::Store(oss[mode].wrap(&view))
170            },
171        };
172        fs
173    }
174
175    pub fn is_trivial(&self) -> bool {
176        match self {
177            ProtoFusedSpec::AddMatMul { geo, .. } => geo.k.as_i64().is_some(),
178            _ => true,
179        }
180    }
181
182    pub fn resolve_trivial<'t>(
183        &'t self,
184        inputs: &'t [TValue],
185        output: &mut Tensor,
186        _mmm: &dyn MatMatMul,
187        mode: usize,
188    ) -> FusedSpec<'t> {
189        #[allow(clippy::let_and_return)]
190        let fs = match self {
191            ProtoFusedSpec::AddMatMul { a, b, packings, .. } => unsafe {
192                let a = a.trivial_value(inputs);
193                let b = b.trivial_value(inputs);
194                debug_assert!(packings.len() == 1);
195                debug_assert!(packings[0].1.is_none()); // no panel extraction
196                #[cfg(debug_assertions)]
197                {
198                    let (a_packing, b_packing) = &_mmm.packings()[packings[mode].0];
199                    debug_assert!(
200                        a_packing.dyn_eq(a.format())
201                            || (a_packing.is::<PackedFormat>() && a_packing.r() == a.format().r())
202                    );
203                    debug_assert!(
204                        b_packing.dyn_eq(b.format())
205                            || (b_packing.is::<PackedFormat>() && b_packing.r() == b.format().r())
206                    );
207                }
208                FusedSpec::AddMatMul {
209                    a: AsInputValue::Borrowed(a),
210                    b: AsInputValue::Borrowed(b),
211                    packing: packings[mode].0,
212                }
213            },
214            ProtoFusedSpec::BinScalar(v, op) => FusedSpec::BinScalar(&inputs[*v], *op),
215            ProtoFusedSpec::LeakyRelu(v) => FusedSpec::LeakyRelu(&inputs[*v]),
216            ProtoFusedSpec::BinPerRow(v, op, _) => {
217                let v = inputs[*v].view();
218                FusedSpec::BinPerRow(v, *op)
219            }
220            ProtoFusedSpec::BinPerCol(v, op, _) => {
221                let v = inputs[*v].view();
222                FusedSpec::BinPerCol(v, *op)
223            }
224            ProtoFusedSpec::AddRowColProducts(row, col) => {
225                FusedSpec::AddRowColProducts(&inputs[*row], &inputs[*col])
226            }
227            ProtoFusedSpec::AddUnicast(store, v, _) => unsafe {
228                let view = inputs[*v].view();
229                FusedSpec::AddUnicast(store.wrap(&view))
230            },
231            ProtoFusedSpec::Scaler(scaler) => scaler.as_fused_spec(),
232            ProtoFusedSpec::Store(oss) => unsafe {
233                FusedSpec::Store(oss[mode].wrap(&output.view_mut()))
234            },
235        };
236        fs
237    }
238
239    /// Like [`resolve_trivial`], but a `Store` reuses a cached [`OutputStore`]
240    /// whose strides/layout are fixed for the output shape, refreshing only its
241    /// base pointer from `output`. Everything else defers to [`resolve_trivial`]
242    /// (constant operands are already baked into the op, so no per-call work).
243    fn resolve_trivial_cached<'t>(
244        &'t self,
245        inputs: &'t [TValue],
246        output: &mut Tensor,
247        mmm: &dyn MatMatMul,
248        mode: usize,
249        store: Option<OutputStore>,
250    ) -> FusedSpec<'t> {
251        match self {
252            ProtoFusedSpec::Store(oss) => unsafe {
253                FusedSpec::Store(match store {
254                    Some(cached) => cached.with_tensor(&output.view()),
255                    None => oss[mode].wrap(&output.view_mut()),
256                })
257            },
258            _ => self.resolve_trivial(inputs, output, mmm, mode),
259        }
260    }
261
262    fn check_inputs(&self, inputs: &[&TypedFact]) -> TractResult<()> {
263        use ProtoFusedSpec::*;
264        match self {
265            AddMatMul { a, b, .. } => {
266                for operand in [a, b] {
267                    if let MatMulOperand::Input(ix) = operand {
268                        ensure!(inputs[*ix].is_exotic());
269                    }
270                }
271            }
272            BinScalar(v, _)
273            | LeakyRelu(v)
274            | BinPerCol(v, _, _)
275            | BinPerRow(v, _, _)
276            | AddUnicast(_, v, _) => {
277                ensure!(inputs[*v].datum_type.is_number());
278            }
279            AddRowColProducts(row, col) => {
280                ensure!(inputs[*row].datum_type.is_number());
281                ensure!(inputs[*col].datum_type.is_number());
282            }
283            _ => (),
284        };
285        Ok(())
286    }
287
288    fn cost(&self, m: &TDim, n: &TDim, idt: DatumType) -> TVec<(Cost, TDim)> {
289        match self {
290            ProtoFusedSpec::AddMatMul { geo, .. } => {
291                tvec!((Cost::FMA(idt), m.clone() * n * &geo.k))
292            }
293            _ => tvec!(), /* FIXME maybe */
294        }
295    }
296
297    /// Collect the C axes this op reads through an output→input mapping — i.e.
298    /// the matmul batch axes. `rm_c_axis` only shifts indices past a removed
299    /// axis; it assumes none of these is the one being removed, so a fusion that
300    /// folds a C axis away must first check it is absent here.
301    fn push_mapped_c_axes(&self, out: &mut TVec<usize>) {
302        use ProtoFusedSpec::*;
303        match self {
304            AddMatMul { geo, .. } => {
305                out.extend(geo.c_to_a_axis_mapping.0.iter().map(|(c, _)| *c));
306                out.extend(geo.c_to_b_axis_mapping.0.iter().map(|(c, _)| *c));
307            }
308            BinPerRow(_, _, map) | BinPerCol(_, _, map) | AddUnicast(_, _, map) => {
309                out.extend(map.0.iter().map(|(c, _)| *c));
310            }
311            BinScalar(..) | Scaler(..) | AddRowColProducts(_, _) | LeakyRelu(_) | Store(..) => {}
312        }
313    }
314
315    fn rm_c_axis(&mut self, axis: usize) {
316        use ProtoFusedSpec::*;
317        match self {
318            AddMatMul { geo, .. } => {
319                geo.c_to_a_axis_mapping.rm_c_axis(axis);
320                geo.c_to_b_axis_mapping.rm_c_axis(axis);
321            }
322            BinScalar(..) | Scaler(..) | AddRowColProducts(_, _) | LeakyRelu(_) => {}
323            BinPerRow(_, _, map) | BinPerCol(_, _, map) => map.rm_c_axis(axis),
324            AddUnicast(_, _, map) => {
325                map.rm_c_axis(axis);
326            }
327            Store(oss, ..) => {
328                for oss in oss {
329                    match oss {
330                        OutputStoreSpec::View { m_axis, n_axis, .. } => {
331                            if let Some(m) = m_axis {
332                                *m -= (*m > axis) as usize
333                            };
334                            if let Some(n) = n_axis {
335                                *n -= (*n > axis) as usize
336                            }
337                        }
338                        OutputStoreSpec::Strides { .. } => {}
339                    }
340                }
341            }
342        }
343    }
344}
345
346#[derive(Clone, Debug, PartialEq, Eq)]
347pub struct MapOutputAxisToInput(pub TVec<(usize, usize)>);
348
349impl MapOutputAxisToInput {
350    #[inline]
351    unsafe fn translate_view(&self, output_coords: &[usize], v: &mut TensorView) {
352        for &(out_axis, in_axis) in &self.0 {
353            unsafe { v.offset_axis(in_axis, output_coords[out_axis] as isize) }
354        }
355    }
356
357    #[inline]
358    fn rm_c_axis(&mut self, axis: usize) {
359        for (c, _) in &mut self.0 {
360            *c -= (*c > axis) as usize;
361        }
362    }
363
364    /// Compute a flat index into a PackedMatrixStorage from output coordinates and batch strides.
365    #[inline]
366    pub fn flat_index(&self, output_coords: &[usize], batch_strides: &[isize]) -> usize {
367        self.0
368            .iter()
369            .map(|&(out_axis, in_axis)| output_coords[out_axis] * batch_strides[in_axis] as usize)
370            .sum()
371    }
372}
373
374#[derive(Clone, Debug, PartialEq, Eq)]
375pub struct AddMatMulGeometry {
376    pub k: TDim,
377    pub c_to_a_axis_mapping: MapOutputAxisToInput,
378    pub c_to_b_axis_mapping: MapOutputAxisToInput,
379}
380
381#[derive(Clone, Debug, PartialEq, Eq)]
382pub struct OptMatMul {
383    pub c_fact: TypedFact,
384    pub micro_ops: Vec<ProtoFusedSpec>,
385    pub mmm: Vec<Box<dyn MatMatMul>>,
386    pub mode_picker: ModePicker,
387    pub c_m_axis: Option<usize>,
388    pub c_n_axis: Option<usize>,
389    pub trivial_packing: bool,
390    pub trivial_path: bool,
391}
392
393impl Op for OptMatMul {
394    fn name(&self) -> StaticName {
395        "OptMatMul".into()
396    }
397
398    fn info(&self) -> TractResult<Vec<String>> {
399        let m = self.c_m_axis.map(|ix| &self.c_fact.shape[ix]).unwrap_or(&TDim::Val(1));
400        let n = self.c_n_axis.map(|ix| &self.c_fact.shape[ix]).unwrap_or(&TDim::Val(1));
401        let mut infos = vec![format!(
402            "c_shape:{:?}, c_m_axis:{:?} c_n_axis:{:?} m:{} n:{}",
403            self.c_fact, self.c_m_axis, self.c_n_axis, m, n,
404        )];
405        if let Some(k) = self.guess_k() {
406            infos.push(format!("Mult: m:{} k:{} n:{} with {:?}", m, k, n, self.mmm));
407        } else {
408            infos.push(format!("Mult: {:?}", self.mmm));
409        }
410        for (mode, mmm) in self.mmm.iter().enumerate() {
411            infos.push(format!(
412                "Ops: {}",
413                self.micro_ops.iter().map(|o| o.format(&**mmm, mode)).join(" >>> ")
414            ));
415        }
416        Ok(infos)
417    }
418
419    op_as_typed_op!();
420}
421
422/// Per-execution state for [`OptMatMul`]: on the trivial path it caches each
423/// micro-op's `Store` [`OutputStore`] layout (strides fixed for the output
424/// shape), so only the base pointer is refreshed per call. Constant operands
425/// are baked into the op at `fuse()`, so they need no per-call state here.
426///
427/// Scratch the op manages itself, per session: `space` is one reusable kernel
428/// buffer -- only one op evaluates at a time, and it is reallocated whenever the
429/// picked kernel cannot use the one already there -- and `stores` memoizes the
430/// trivial path's output-store descriptors per node, since those depend on that
431/// node's micro-ops. Thread-local, so nothing here has to be `Send`; a session's
432/// entry goes when the plan calls [`EvalOp::drop_session`].
433#[derive(Default)]
434struct MmmScratch {
435    space: Option<Box<dyn tract_linalg::mmm::ScratchSpace>>,
436    stores: HashMap<usize, TVec<Option<OutputStore>>>,
437}
438
439thread_local! {
440    static MMM_SCRATCH: std::cell::RefCell<HashMap<SessionId, MmmScratch>> =
441        std::cell::RefCell::new(HashMap::new());
442}
443
444impl EvalOp for OptMatMul {
445    not_out_of_plan!();
446
447    fn eval(&self, ctx: &EvalContext, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
448        MMM_SCRATCH.with_borrow_mut(|per_session| {
449            self.eval_with_scratch(ctx, inputs, per_session.entry(ctx.session).or_default())
450        })
451    }
452
453    fn drop_session(&self, session: SessionId, _node_id: usize) {
454        MMM_SCRATCH.with_borrow_mut(|per_session| per_session.remove(&session));
455    }
456}
457
458impl OptMatMul {
459    fn eval_with_scratch(
460        &self,
461        ctx: &EvalContext,
462        inputs: TVec<TValue>,
463        scratch: &mut MmmScratch,
464    ) -> TractResult<TVec<TValue>> {
465        unsafe {
466            let c_shape = self.c_fact.shape.eval_to_usize(ctx.symbols)?;
467            let mut c = Tensor::uninitialized_dt(self.c_fact.datum_type, &c_shape)?;
468            let m = self.c_m_axis.map(|c_m| c.shape()[c_m]).unwrap_or(1);
469            let n = self.c_n_axis.map(|c_n| c.shape()[c_n]).unwrap_or(1);
470            let mode = self.mode_picker.pick(n)?;
471            let mmm = &*self.mmm[mode];
472            let MmmScratch { space, stores } = scratch;
473            if !space.as_ref().is_some_and(|s| mmm.can_use_scratch_space(&**s)) {
474                *space = Some(mmm.allocate_scratch_space());
475            }
476            let scratch = space.as_mut().unwrap();
477            if self.trivial_path {
478                let stores = stores.entry(ctx.node_id).or_insert_with(|| {
479                    self.micro_ops
480                        .iter()
481                        .map(|o| match o {
482                            ProtoFusedSpec::Store(oss) => Some(oss[mode].wrap(&c.view())),
483                            _ => None,
484                        })
485                        .collect()
486                });
487                let uops: TVec<FusedSpec> = self
488                    .micro_ops
489                    .iter()
490                    .zip(stores.iter())
491                    .map(|(o, store)| o.resolve_trivial_cached(&inputs, &mut c, mmm, mode, *store))
492                    .collect();
493                mmm.run_with_scratch_space(m, n, scratch.as_mut(), &uops)?;
494                Ok(tvec!(c.into_tvalue()))
495            } else {
496                let mut uops = vec![FusedSpec::ShiftLeft(0); self.micro_ops.len()];
497                let mut looping_shape: TVec<usize> = c_shape.to_smallvec();
498                if let Some(ax) = self.c_m_axis {
499                    looping_shape[ax] = 1;
500                }
501                if let Some(ax) = self.c_n_axis {
502                    looping_shape[ax] = 1;
503                }
504                for c_coords in indices(&*looping_shape) {
505                    for ix in 0..self.micro_ops.len() {
506                        *uops.get_unchecked_mut(ix) = self.micro_ops.get_unchecked(ix).resolve(
507                            &inputs,
508                            c_coords.slice(),
509                            &c,
510                            mmm,
511                            mode,
512                        );
513                    }
514                    mmm.run_with_scratch_space(m, n, scratch.as_mut(), &uops)
515                        .context("In mmm.run_with_scratch_space")?;
516                }
517                Ok(tvec!(c.into_tvalue()))
518            }
519        }
520    }
521}
522
523impl TypedOp for OptMatMul {
524    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
525        ensure!(self.c_m_axis.map(|ax| ax < self.c_fact.rank()).unwrap_or(true));
526        ensure!(self.c_n_axis.map(|ax| ax < self.c_fact.rank()).unwrap_or(true));
527        ensure!(self.trivial_path == self.can_use_trivial_path());
528        ensure!(self.mmm.iter().map(|mmm| mmm.internal_type()).all_equal());
529        for op in &self.micro_ops {
530            op.check_inputs(inputs)?;
531        }
532        Ok(tvec!(self.c_fact.clone()))
533    }
534
535    fn cost(&self, _inputs: &[&TypedFact]) -> TractResult<TVec<(Cost, TDim)>> {
536        let mut sums = HashMap::new();
537        for op in &self.micro_ops {
538            for (cost, count) in op.cost(self.m(), self.n(), self.mmm[0].internal_type()) {
539                *sums.entry(cost).or_default() += count;
540            }
541        }
542        let loops = self
543            .c_fact
544            .shape
545            .iter()
546            .enumerate()
547            .map(|(ix, d)| {
548                if Some(ix) == self.c_m_axis || Some(ix) == self.c_n_axis {
549                    1.to_dim()
550                } else {
551                    d.clone()
552                }
553            })
554            .product::<TDim>();
555        for s in &mut sums.values_mut() {
556            *s *= &loops;
557        }
558        Ok(sums.into_iter().collect())
559    }
560
561    fn fuse(&self, model: &TypedModel, node: &TypedNode) -> TractResult<Option<TypedModelPatch>> {
562        use crate::ops;
563        if let Some(patch) = self.bake_const_operands(model, node)? {
564            return Ok(Some(patch));
565        }
566        rule_if!(node.outputs.len() == 1);
567        rule_if!(node.outputs[0].successors.len() == 1);
568        rule_if!(!model.output_outlets()?.contains(&node.id.into()));
569        let succ = model.node(node.outputs[0].successors[0].node);
570        let mut patch = TypedModelPatch::new(format!("fusing {succ}"));
571
572        if let Some(op) = succ.op_as::<ops::binary::TypedBinOp>() {
573            rule_if_some!(mut binop = op.0.as_linalg_binop());
574            let flipped = succ.inputs[0].node == node.id;
575            if flipped {
576                binop = binop.flip();
577            }
578            let other_outlet = succ.inputs[flipped as usize];
579            return self.fuse_binary(model, node, patch, other_outlet, binop);
580        }
581        if let Some(op) = succ.op_as::<ops::binary::OptBinByScalar>() {
582            rule_if_some!(mut binop = op.binop.as_linalg_binop());
583            let flipped = succ.inputs[0].node == node.id;
584            if flipped {
585                binop = binop.flip();
586            }
587            let other_outlet = succ.inputs[flipped as usize];
588            return self.fuse_binary(model, node, patch, other_outlet, binop);
589        }
590
591        if let Some(op) = succ.op_as::<ops::element_wise::ElementWiseOp>().map(|ew| ew.0.as_ref()) {
592            if let Some(op) = op.downcast_ref::<ops::math::QScale>() {
593                return self.fuse_op(
594                    model,
595                    node,
596                    patch,
597                    vec![ProtoFusedSpec::Scaler(op.scaler)],
598                    &[],
599                );
600            }
601            if let Some(op) = op.downcast_ref::<LeakyRelu>() {
602                rule_if!(
603                    self.mmm
604                        .iter()
605                        .all(|mmm| mmm.can_fuse(&FusedSpec::LeakyRelu(&tensor0(op.alpha))))
606                );
607                let alpha = patch.add_const(
608                    node.name.to_string() + ".alpha",
609                    tensor0(op.alpha).cast_to_dt(self.mmm[0].internal_type())?.into_owned(),
610                )?;
611                return self.fuse_op(
612                    model,
613                    node,
614                    patch,
615                    vec![ProtoFusedSpec::LeakyRelu(node.inputs.len())],
616                    &[alpha],
617                );
618            }
619        }
620        if let Some(cast_to) = succ.op_as::<ops::cast::Cast>().map(|cast| cast.to)
621            && (((cast_to.unquantized() == i8::datum_type()
622                || cast_to.unquantized() == u8::datum_type())
623                && self.c_fact.datum_type == i32::datum_type())
624                || self.mmm.iter().all(|m| m.stores().contains(&cast_to)))
625            && let Some(ProtoFusedSpec::Store(stores)) = self.micro_ops.last()
626        {
627            rule_if!(stores.iter().all(|s| !matches!(s, OutputStoreSpec::Strides { .. })));
628            let c_fact = cast_to.fact(self.c_fact.shape.clone());
629            let mut patch =
630                TypedModelPatch::fuse_with_next(model, node, Self { c_fact, ..self.clone() })?;
631            patch.dont_apply_twice = Some(format!("Fuse {succ} into {node}"));
632            return Ok(Some(patch));
633        }
634        if let Some(AxisOp::Rm(axis)) = succ.op_as::<ops::AxisOp>() {
635            rule_if!(Some(*axis) != self.c_m_axis);
636            rule_if!(Some(*axis) != self.c_n_axis);
637            let mut new_op = self.clone();
638            new_op.c_fact.shape.remove_axis(*axis)?;
639            if let Some(c_m_axis) = &mut new_op.c_m_axis {
640                *c_m_axis -= (*c_m_axis > *axis) as usize;
641            }
642            if let Some(c_n_axis) = &mut new_op.c_n_axis {
643                *c_n_axis -= (*c_n_axis > *axis) as usize;
644            }
645            for uop in &mut new_op.micro_ops {
646                uop.rm_c_axis(*axis);
647            }
648            let mut patch = TypedModelPatch::fuse_with_next(model, node, new_op)?;
649            patch.dont_apply_twice = Some(format!("Fuse {succ} into {node}"));
650            return Ok(Some(patch));
651        }
652        if let Some(into) = succ.op_as::<IntoShape>()
653            && let Some(new_op) = self.absorb_squeeze(into)
654        {
655            let mut patch = TypedModelPatch::fuse_with_next(model, node, new_op)?;
656            patch.dont_apply_twice = Some(format!("Fuse {succ} into {node}"));
657            return Ok(Some(patch));
658        }
659        // Reach over a shape-agnostic elementwise (Tanh/Sigmoid/Cast/…) to absorb
660        // a squeeze reshape into the store: matmul → ew → squeeze becomes
661        // matmul(squeezed) → ew, unchanged since the op is per-element. With the
662        // direct arm above, squeeze reshapes fuse whether before or after the ew.
663        if (succ.op_is::<ElementWiseOp>() || succ.op_is::<Cast>())
664            && succ.outputs.len() == 1
665            && let &[next] = &*succ.outputs[0].successors
666        {
667            let into_node = model.node(next.node);
668            if let Some(into) = into_node.op_as::<IntoShape>()
669                && let Some(new_op) = self.absorb_squeeze(into)
670            {
671                let mut patch = TypedModelPatch::default();
672                let inputs = node
673                    .inputs
674                    .iter()
675                    .map(|i| patch.tap_model(model, *i))
676                    .collect::<TractResult<TVec<_>>>()?;
677                let mm = patch.wire_node(&node.name, new_op, &inputs)?[0];
678                let ew = patch.wire_node(&succ.name, succ.op.clone(), &[mm])?[0];
679                patch.shunt_outside(model, into_node.id.into(), ew)?;
680                patch.dont_apply_twice = Some(format!("Reach {into_node} into {node}"));
681                return Ok(Some(patch));
682            }
683        }
684        if (succ.op_is::<AxisOp>() || succ.op_is::<IntoShape>())
685            && let &[next] = &*succ.outputs[0].successors
686        {
687            let next_node = model.node(next.node);
688            if let Some(cast) = next_node.op_as::<Cast>() {
689                let mut patch = TypedModelPatch::default();
690                let mut wire = patch.tap_model(model, node.id.into())?;
691                wire = patch.wire_node(&next_node.name, cast.clone(), &[wire])?[0];
692                wire = patch.wire_node(&succ.name, succ.op.clone(), &[wire])?[0];
693                patch.shunt_outside(model, next_node.id.into(), wire)?;
694                return Ok(Some(patch));
695            } else if let Some(op) = next_node.op_as::<ops::binary::TypedBinOp>() {
696                rule_if!(op.0.as_linalg_binop().is_some());
697                let flipped = succ.inputs[0].node == node.id;
698                let other_outlet = next_node.inputs[flipped as usize];
699                if let Some(uni) = &model.outlet_fact(other_outlet)?.uniform {
700                    let mut patch = TypedModelPatch::default();
701                    let cst = patch.add_const(&model.node(other_outlet.node).name, uni.clone())?;
702                    let output = patch.tap_model(model, node.id.into())?;
703                    let wire = wire_with_rank_broadcast(
704                        &next_node.name,
705                        &mut patch,
706                        op.clone(),
707                        &if flipped { [output, cst] } else { [cst, output] },
708                    )?;
709                    let wire = patch.wire_node(&succ.name, succ.op.clone(), &wire)?[0];
710                    patch.shunt_outside(model, next_node.id.into(), wire)?;
711                    return Ok(Some(patch));
712                }
713            }
714        }
715        if let Some(op) = succ.op_as::<ops::binary::OptBinUnicast>() {
716            let in_1_fact = model.outlet_fact(succ.inputs[0])?;
717            let in_2_fact = model.outlet_fact(succ.inputs[1])?;
718            if op.binop.is::<ops::math::Add>()
719                && self.mmm.len() == 1
720                && in_1_fact.without_value() == in_2_fact.without_value()
721            {
722                let other_slot = 1 - node.outputs[0].successors[0].slot;
723                let other_input = succ.inputs[other_slot];
724                let other_input = patch.tap_model(model, other_input)?;
725                let other_fact = patch.outlet_fact(other_input)?;
726
727                if other_fact.shape == self.c_fact.shape {
728                    let other_storage = unsafe { self.mmm[0].c_view(self.c_m_axis, self.c_n_axis) };
729                    let mapping =
730                        MapOutputAxisToInput((0..other_fact.rank()).map(|x| (x, x)).collect());
731                    return self.fuse_op(
732                        model,
733                        node,
734                        patch,
735                        vec![ProtoFusedSpec::AddUnicast(other_storage, node.inputs.len(), mapping)],
736                        &[other_input],
737                    );
738                }
739            } else {
740                rule_if_some!(mut binop = op.binop.as_linalg_binop());
741                let flipped = succ.inputs[0].node == node.id;
742                if flipped {
743                    binop = binop.flip();
744                }
745                let other_outlet = succ.inputs[flipped as usize];
746                return self.fuse_binary(model, node, patch, other_outlet, binop);
747            }
748        };
749        Ok(None)
750    }
751
752    as_op!();
753}
754
755impl OptMatMul {
756    pub fn new(
757        mmm: Vec<Box<dyn MatMatMul>>,
758        mode_picker: ModePicker,
759        c_fact: TypedFact,
760        c_m_axis: Option<usize>,
761        c_n_axis: Option<usize>,
762        micro_ops: Vec<ProtoFusedSpec>,
763        trivial_packing: bool,
764    ) -> TractResult<Self> {
765        if let Some(m) = c_m_axis {
766            ensure!(m < c_fact.rank());
767        }
768        if let Some(n) = c_n_axis {
769            ensure!(n < c_fact.rank());
770        }
771        let mut it = OptMatMul {
772            mmm,
773            mode_picker,
774            c_fact,
775            c_m_axis,
776            c_n_axis,
777            micro_ops,
778            trivial_path: false,
779            trivial_packing,
780        };
781        it.update_trivial_path();
782        Ok(it)
783    }
784
785    // for auditing only (may return None if no AddMatMul is found)
786    pub fn guess_k(&self) -> Option<TDim> {
787        self.micro_ops
788            .iter()
789            .find_map(
790                |o| {
791                    if let ProtoFusedSpec::AddMatMul { geo, .. } = o { Some(geo) } else { None }
792                },
793            )
794            .map(|geo| geo.k.clone())
795    }
796
797    #[inline]
798    pub fn m(&self) -> &TDim {
799        self.c_m_axis.map(|ax| &self.c_fact.shape[ax]).unwrap_or(&TDim::Val(1))
800    }
801
802    #[inline]
803    pub fn n(&self) -> &TDim {
804        self.c_n_axis.map(|ax| &self.c_fact.shape[ax]).unwrap_or(&TDim::Val(1))
805    }
806
807    fn update_trivial_path(&mut self) {
808        self.trivial_path = self.can_use_trivial_path();
809    }
810
811    /// If `into` is a pure unit-axis squeeze of this op's (concrete) output that
812    /// leaves the m/n axes intact, return a clone whose store produces the
813    /// squeezed shape directly. `None` when the reshape can't be absorbed.
814    fn absorb_squeeze(&self, into: &IntoShape) -> Option<Self> {
815        if into.strides != Tensor::natural_strides(&into.dims) {
816            return None;
817        }
818        let old = self.c_fact.shape.as_concrete()?;
819        let removed = pure_squeeze_removed(old, &into.dims)?;
820        if removed.iter().any(|ax| Some(*ax) == self.c_m_axis || Some(*ax) == self.c_n_axis) {
821            return None;
822        }
823        // A non-unit matmul batch axis (e.g. grouped conv) makes the packed
824        // inputs per-batch; folding any axis then desyncs that batch indexing.
825        // Only fuse when every batch axis is trivial (size 1).
826        let mut batch_axes: TVec<usize> = tvec!();
827        self.micro_ops.iter().for_each(|uop| uop.push_mapped_c_axes(&mut batch_axes));
828        if batch_axes.iter().any(|ax| old.get(*ax).copied().unwrap_or(1) > 1) {
829            return None;
830        }
831        let mut new_op = self.clone();
832        for axis in removed.iter().rev() {
833            new_op.c_fact.shape.remove_axis(*axis).ok()?;
834            if let Some(c_m_axis) = &mut new_op.c_m_axis {
835                *c_m_axis -= (*c_m_axis > *axis) as usize;
836            }
837            if let Some(c_n_axis) = &mut new_op.c_n_axis {
838                *c_n_axis -= (*c_n_axis > *axis) as usize;
839            }
840            for uop in &mut new_op.micro_ops {
841                uop.rm_c_axis(*axis);
842            }
843        }
844        Some(new_op)
845    }
846
847    fn can_use_trivial_path(&self) -> bool {
848        self.c_fact.shape.is_concrete()
849            && self.c_fact.shape.iter().enumerate().all(|(ax, dim)| {
850                Some(ax) == self.c_m_axis || Some(ax) == self.c_n_axis || dim.is_one()
851            })
852            && self.trivial_packing
853            && self.micro_ops.iter().all(|o| o.is_trivial())
854    }
855
856    /// Bake matmul operands that are fed by a constant, non-batched input into
857    /// the op as [`MatMulOperand::Const`], dropping the corresponding graph
858    /// input. Runs once the packing has const-folded so the operand's outlet
859    /// carries a packed `konst`. Returns a patch that rewires the node with the
860    /// remaining inputs, or `None` if nothing is bakeable.
861    fn bake_const_operands(
862        &self,
863        model: &TypedModel,
864        node: &TypedNode,
865    ) -> TractResult<Option<TypedModelPatch>> {
866        let bakeable = |operand: &MatMulOperand, mapping: &MapOutputAxisToInput| -> bool {
867            if let MatMulOperand::Input(i) = operand {
868                mapping.0.is_empty()
869                    && model.outlet_fact(node.inputs[*i]).is_ok_and(|f| {
870                        f.konst
871                            .as_ref()
872                            .and_then(|k| k.try_storage_as::<PackedMatrixStorage>().ok())
873                            .is_some()
874                    })
875            } else {
876                false
877            }
878        };
879        let mut baked: TVec<usize> = tvec!();
880        for op in &self.micro_ops {
881            if let ProtoFusedSpec::AddMatMul { geo, a, b, .. } = op {
882                if bakeable(a, &geo.c_to_a_axis_mapping) {
883                    let MatMulOperand::Input(i) = a else { unreachable!() };
884                    baked.push(*i);
885                }
886                if bakeable(b, &geo.c_to_b_axis_mapping) {
887                    let MatMulOperand::Input(i) = b else { unreachable!() };
888                    baked.push(*i);
889                }
890            }
891        }
892        if baked.is_empty() {
893            return Ok(None);
894        }
895        baked.sort();
896        baked.dedup();
897        let remap: Vec<Option<usize>> = {
898            let mut ni = 0;
899            (0..node.inputs.len())
900                .map(|i| {
901                    (!baked.contains(&i)).then(|| {
902                        let cur = ni;
903                        ni += 1;
904                        cur
905                    })
906                })
907                .collect()
908        };
909        let const_value = |i: usize| -> TractResult<Box<dyn MMMInputValue>> {
910            let konst = model.outlet_fact(node.inputs[i])?.konst.clone().unwrap();
911            Ok(dyn_clone::clone_box(konst.try_storage_as::<PackedMatrixStorage>()?.value()))
912        };
913        let map_operand = |operand: &MatMulOperand| -> TractResult<MatMulOperand> {
914            Ok(match operand {
915                MatMulOperand::Input(i) if baked.contains(i) => {
916                    MatMulOperand::Const(const_value(*i)?)
917                }
918                MatMulOperand::Input(i) => MatMulOperand::Input(remap[*i].unwrap()),
919                MatMulOperand::Const(v) => MatMulOperand::Const(v.clone()),
920            })
921        };
922        let micro_ops = self
923            .micro_ops
924            .iter()
925            .map(|op| -> TractResult<ProtoFusedSpec> {
926                use ProtoFusedSpec::*;
927                Ok(match op {
928                    AddMatMul { geo, a, b, packings } => AddMatMul {
929                        geo: geo.clone(),
930                        a: map_operand(a)?,
931                        b: map_operand(b)?,
932                        packings: packings.clone(),
933                    },
934                    BinScalar(v, op) => BinScalar(remap[*v].unwrap(), *op),
935                    LeakyRelu(v) => LeakyRelu(remap[*v].unwrap()),
936                    BinPerRow(v, op, m) => BinPerRow(remap[*v].unwrap(), *op, m.clone()),
937                    BinPerCol(v, op, m) => BinPerCol(remap[*v].unwrap(), *op, m.clone()),
938                    AddRowColProducts(r, c) => {
939                        AddRowColProducts(remap[*r].unwrap(), remap[*c].unwrap())
940                    }
941                    AddUnicast(s, v, m) => AddUnicast(*s, remap[*v].unwrap(), m.clone()),
942                    Scaler(s) => Scaler(*s),
943                    Store(o) => Store(o.clone()),
944                })
945            })
946            .collect::<TractResult<Vec<_>>>()?;
947        let new_op = OptMatMul { micro_ops, ..self.clone() };
948        let kept: TVec<OutletId> =
949            (0..node.inputs.len()).filter(|i| !baked.contains(i)).map(|i| node.inputs[i]).collect();
950        let mut patch = TypedModelPatch::new(format!("bake const operands into {}", node.name));
951        let taps = patch.taps(model, &kept)?;
952        let output = patch.wire_node(&node.name, new_op, &taps)?;
953        patch.shunt_outside(model, node.id.into(), output[0])?;
954        Ok(Some(patch))
955    }
956
957    fn fuse_op(
958        &self,
959        model: &TypedModel,
960        node: &TypedNode,
961        mut patch: TypedModelPatch,
962        fused_micro_op: Vec<ProtoFusedSpec>,
963        additional_inputs: &[OutletId],
964    ) -> TractResult<Option<TypedModelPatch>> {
965        let succ = model.node(node.outputs[0].successors[0].node);
966        let mut new_op = self.clone();
967        let before_last = new_op.micro_ops.len() - 1..new_op.micro_ops.len() - 1;
968        new_op.micro_ops.splice(before_last, fused_micro_op);
969        new_op.c_fact = succ.outputs[0].fact.clone();
970        new_op.update_trivial_path();
971        let mut inputs = patch.taps(model, &node.inputs)?;
972        inputs.extend(additional_inputs.iter().cloned());
973        let output = patch.wire_node(&succ.name, new_op, &inputs)?;
974        patch.shunt_outside(model, succ.id.into(), output[0])?;
975        Ok(Some(patch))
976    }
977
978    fn fuse_binary(
979        &self,
980        model: &TypedModel,
981        node: &TypedNode,
982        mut patch: TypedModelPatch,
983        value: OutletId,
984        binop: BinOp,
985    ) -> TractResult<Option<TypedModelPatch>> {
986        let fact = model.outlet_fact(value)?;
987        let mut v = patch.tap_model(model, value)?;
988        if fact.datum_type != self.mmm[0].internal_type() {
989            v = patch.wire_node(
990                format!("{}.cast-input-{}", node.name, node.inputs.len()),
991                cast(self.mmm[0].internal_type()),
992                &[v],
993            )?[0];
994        }
995        let value = node.inputs.len();
996        let additional_input = tvec!(v);
997        if fact.shape.volume() == 1.to_dim() {
998            return self.fuse_op(
999                model,
1000                node,
1001                patch,
1002                vec![ProtoFusedSpec::BinScalar(value, binop)],
1003                &additional_input,
1004            );
1005        }
1006        let other_shape = fact.shape.to_owned();
1007        if self.c_m_axis.is_some_and(|ax| {
1008            other_shape[ax] == self.c_fact.shape[ax] && other_shape[ax] == other_shape.volume()
1009        }) {
1010            return self.fuse_op(
1011                model,
1012                node,
1013                patch,
1014                vec![ProtoFusedSpec::BinPerRow(
1015                    value,
1016                    binop,
1017                    MapOutputAxisToInput(tvec!((self.c_m_axis.unwrap(), self.c_m_axis.unwrap()))),
1018                )],
1019                &additional_input,
1020            );
1021        }
1022        if self.c_n_axis.is_some_and(|ax| {
1023            other_shape[ax] == self.c_fact.shape[ax] && other_shape[ax] == other_shape.volume()
1024        }) {
1025            return self.fuse_op(
1026                model,
1027                node,
1028                patch,
1029                vec![ProtoFusedSpec::BinPerCol(
1030                    value,
1031                    binop,
1032                    MapOutputAxisToInput(tvec!((self.c_n_axis.unwrap(), self.c_n_axis.unwrap()))),
1033                )],
1034                &additional_input,
1035            );
1036        }
1037        Ok(None)
1038    }
1039}