Here is a matmul with two ops, producer_lhs and producer_rhs, fused into it. The producers have a cost.
They could be just reading constant data (e.g. weights of a conv op) or they could be more expensive math
(e.g. math-function activation function of preceding layer). Either way, they have non-negligible cost
(even reading constant data has the cost of memory accesses).
for (int i = 0; i < M; i++) {
  for (int j = 0; j < N; j++) {
    for (int k = 0; k < K; k++) {
      result[i, j] += producer_lhs(i, k) * producer_rhs(k, j);
    }
  }
}
Claim: to perform efficiently this N^3 work on N^2 data we need:
- the output of producer_lhsandproducer_rhsto be materialized as a plain buffer as large as the source matrices.
- the loop nest to be transformed into a traversal that is suitably local in both i and j.
- structuring the loop nest to have the nicest scanline traversal of one lhs/rhs side results in a worst-case traversal of the opposite side.
- example: the above loop nest has the outer most loop over i, which nicest for lhs - each row is accessed only in one iteration of the outer loop, so no need to materialize the entire producer_lhs output buffer at once. But that causes the entire RHS to be fully retraversed M times.
 
Conclusions:
- while the packing op may not exist anymore as a discrete op during execution, the packed matrices will have to exist in memory at runtime (possibly as constant data), the whole matrix not just a block at a time.
agree?
There's an important distinction that it's not that the "packed matrices must exist in memory" but that the "inputs to an dispatch must exist in memory and for matmuls those inputs should have a specific layout." There's no such thing as a packed matrix buffer here and instead there are just input buffers to this matrix multiply that are packed. It's almost never helpful to then think of this in isolation and instead for any operation to think of what produces its inputs (and also what is consuming its outputs). If this were a simple set of expressions in C like
int t = a * b; int u = t * c;you wouldn't treat it any differently as a compiler thanint u = (a * b) + c;, and you wouldn't make any assertion (or even mention) the registers that must be allocated until much later in the process as you also need to factor in what producesa/b/cand what consumesu. It's the same here at the level we are talking about in linalg: you must think of all loopy operations acting on tensors - some of which may be matrix multiplies - together as a whole. That's the superpower of linalg :)The loop above is already a bit lower than the level of detail needed to reason about data layout efficiently with respect to packing, though. Instead if you thought of this as:
Then what you want to express is that the lhs and rhs must be packed:
(there may be a packing named op, or just a transformation that inserts layout changes, etc)
Normal compiler transformations will then be able to work on those, like CSE. Say you used the rhs twice:
But so too can linalg-specific transformations operate on this and sink the packing into the producer (or, more correctly, use the packing as the root into which linalg.foo and linalg.bar are pulled in to):
(it's unlikely that there is a foo_and_pack named op, but instead that there's a linalg.generic/etc with the packing applied as index mapping changes/additional operations in the loop body)
Now there's no intermediates that are ever unpacked and thus later on there are no buffers that will be required that were not already required to begin with to hold the lhs and rhs. There's no need to worry about the
rhs(k, j)being reused inside of theinest, as you are just loading the input and always had to do that anyway regardless of whether it is packed or not - it's just bytes to fetch like any others. Conceptually and literally this is like folding the ruy prepacking into the producer and then only having a code path in the matmul to use prepacked inputs.All of this is to say that packing is just another operation to perform on data, linalg is exceedingly good at manipulating operations on data, and which operations are performed and in what order is the stuff ntv@ was mentioning and what actually matters. For example here that the packing should be treated as a root that feeds into a consumer matmul is a very important distinction from the case where the matmul is the root that the packs are folded into. That's the expert knowledge that then gets combined with searchable parameters (what is the form of the packing, tile sizes, etc).
In the case above both lhs and rhs are fully dynamic, but you can see how when treating them as just operations on data anything you've done in things like toco can now be performed too. For example:
Results after constant folding:
The whole-program transformation also works (this is effectively ruy prepacking):
->
->
And now again there's no intermediates used solely for packing - there's just inputs and outputs and sometimes the layout of those inputs and outputs is in a certain form. Now, if the input to be packed comes from outside the program a dedicated packing dispatch may be required. I'm fine with that: if there is literally nothing else you are doing to your raw program-provided input besides passing it directly to a matmul you probably don't need to (and should not) be using IREE at all, but ruy as a library. We of course still work and will do the packing but won't lose sleep if there's some cache misses as again IREE is not a BLAS library and inefficiencies around the external ABI are something for the application to fix (if they care). The transient allocations will get reused too when not longer live - and if there's no other work that could reuse it again things fall into the too-simple-for-IREE-to-care-about category. So if it helps I'll say it on record: yes there is a case where packing can absolutely not be fused with any other operation and as such there is an additional transient allocation required to store that packed intermediate input to the matmul, but it's vanishingly unlikely to occur in anything but microbenchmarks and 🤷 :) Think of it like how exported C functions use the cdecl calling convention even if internal functions can use better ones that more aggressively use registers/etc -- if the bottleneck of the application is the infrequent cdecl call vs the entire compute complexity of the work being done then the entire application architecture is at fault, not the C compiler emitting the code in accordance with the calling convention.
All that said, the majority of cases can be handled by the above strategies and those are the interesting ones to generalize and tackle (and poke holes in/experiment with/etc). The statement here gives the freedom to eliminate the case of where producers of inputs are entirely unknowable and instead focus on the case where producers are mutable and can do whatever we want. The problem statement is to figure out what we want :)
Finally worth mention is that in the dynamic cases where you want to vary the packing based on runtime parameters (cache line size, etc) you have several options. The simplest is just to take the packing parameter as an SSA value:
->
-> linalg ops with affine maps that have some slightly different math
If you specify the size at compile-time (for a specific arch) that hal.device.query folds to a constant and it's no different than if you had specified it directly, only now this code is tolerant to the runtime variants. No different than ruy: your block map takes at runtime a bunch of parameters (rows, kernel_rows, etc) and does some math on them - the same is happening here. You could also specialize these cases if there was benefit - for example:
(but none of that may be needed - just as you don't template your BlockMap)
Now as Ahmed mentioned for strict back-to-back execution of producer and consumer there's the possibility to keep caches warmer by ensuring they run tilewise together, but in many cases that doesn't matter in the face of all the other extreme efficiencies now possible with this approach. There's also many other ways to much more strictly control that behavior. For example in your loop you can easily ensure you get good locality on outputs by folding in subsequent operations:
Better locality on the inputs can be done by rearranging your loops; if what you want to say is that all i's for a particular j,k should happen after j,k is produced and in cache, then flip your loops:
(don't concentrate on whether the specific example above is valid for matmul - I don't know - but there's a lot of good documentation spanning back 15 years on how this is done in the CUDA/GPGPU world and the point is to use linalg to do/discover such things :)
The point here is that yes you can do crazier things (cross-thread/dispatch fine-grained barriers for inter-tile communication) but there are also other ways and some of them may entirely obviate the need for that. First hit the wall and then find out what kind of door to put in it and how, and the wall is still a few km away at this point :)