Hi all,
I’m Charitha. I work with Intel’s MLIR team focusing on MLIR GPU lowering pipeline as well as exploring improvements to Linalg’s tiling and fusion infrastructure to support critical use cases.
TL;DR
- Linalg’s tiling/fusion infrastructure does not offer a way to fuse two reductions that share a reduction axis when the second depends on the first. This pattern of reductions is quite important in modern ML kernels.
- We propose one composable Transform dialect op,
structured.fuse_dependent_reduction_op, that fuses anR1 -> E -> R2chain (producer reduction, elementwise term, consumer reduction) intoR1’s already tiled reduction loop, emitting the required online correction automatically. The correction is derived fromE, not hard-coded per kernel. - It composes with the existing tiling/fusion flow: tile
R1withstructured.tile_using_for, then apply the new op once per dependent reduction. Applied repeatedly, it can turn standard attention into a flash-attention-style single online loop. We show the generality of the approach through some other examples. - Current legality:
R2must be a sum reduction andR1must be used in each of its summed terms in a factorizable way. Both may be relaxed later with more general correction logic.
Motivation
Today, MLIR’s Linalg and Transform dialects have mature, composable support for
tiling and fusing producer–consumer chains, especially along parallel dimensions. A typical workflow involves tiling a consumer and then fusing all the producer slices along the parallel dimensions into the resulting tiled loop. There is also support for tiling a single reduction along its reduction dimension, which splits the reduction into a tiled loop that accumulates partial results. To the best of our knowledge, there is no existing support in Linalg tile/fuse infrastructure for fusing dependent reductions (here dependent second reduction is data-dependent on the first reduction) where both reductions share the same reduction axis (e.g. sum of exp(x-max) reduction found in softmax).
However, for certain dependent reduction chains found in modern AI kernels, such as softmax and attention mechanisms, it is possible to fuse the computation into a single online loop by applying a transformation commonly referred to as online correction [1]. This optimization drastically reduces memory traffic and significantly improves performance. The key idea in online correction is that whenever we find an update for the first reduction, the accumulator for the second reduction (which was so far computed based on the previous value of the first reduction) must be corrected to account for the new update. This update is straightforward for a certain class of reductions, such as the max reduction followed by a sum-of-exponentials reduction (found in softmax).
The goal of this proposal is to improve the existing Linalg tiling and fusion infrastructure
to support tiling and fusion of such dependent reductions. The proposal achieves this by providing a composable primitive that can be used to fuse a dependent consumer reduction into an already tiled producer reduction by automatically emitting the necessary online correction.
Proposed Changes
We propose a new Linalg Transform dialect op, structured.fuse_dependent_reduction_op.
This operation takes 3 operand handles:
- Already tiled producer reduction (
R1). It is expected that
along the shared reduction axis reduction happens sequentially
(i.e. produced bystructured.tile_using_forthat uses theFullReduction
strategy, so the running accumulator is carried as aniter_arg).
It is possible thatR1returns multiple reduction results (that are already fused in previous steps). - An all-parallel elementwise op
Ethat consumes one of the producer’s reduction results as a broadcast
input along the reduction axis. - A reduction op, a still-untiled consumer reduction
R2over the same
axis asR1that reducesE’s result.
This operation returns a single handle, fused loop, to the producer loop now also carrying E and the consumer reduction (R2), fused and online. This also allows the user to apply the transform op repeatedly to fuse chains of dependent reductions.
%r1_loop = ..... -> !transform.any_op
%e = ..... -> !transform.any_op
%r2 = ..... -> !transform.any_op
%fused_loop = transform.structured.fuse_dependent_reduction_op %e, %r2 into %r1_loop
: (!transform.any_op, !transform.any_op, !transform.any_op) -> !transform.any_op
Apart from the constraints mentioned above, the following is also assumed for the
structure of the reduction chain.
- It is expected that
R2is anaddreduction (e.g.linalg.reduce <add>,linalg.matmul). R1is used in each summed term ofR2in a factorizable way (e.g. sum ofexp(x-max)==exp(x).exp(-max)orR1is used as either A or B operand of matmul reduction). More precisely, factorizability ofR1use allows us to isolate the effect of a staleR1and eliminate it by rescaling.
Why factorizability is important?
It allows us to automatically emit the necessary online correction for fusion as a factor of old vs new R1 values. In general, given that second reduction (R2) is a sum reduction and the first
reduction is used in R2’s each sum term as a factorizable component, online correction can be applied to fuse the reductions efficiently. In such cases, the each summed term of R2 can be expresssed as E(x, R1) = f(x) * E'(R1). This means if the R1 value changes, we can compute the correction factor E' = E'(R1_new) / E'(R1_old) to update the R2 accumulator online (because of the distributivity of multiplication over addition). Here function E' simply isolates the the effects of R1 on the original E and it can be derived based on E.
How do we decide the factorizability?
Factorizability is decided by a forward pass over E’s body that propagates, for
each intermediate value, whether R1’s result enters it additively or multiplicatively. Only a subset of arith/math ops carry these facts – addf/subf preserve the additive
form, mulf/divf the multiplicative one, and exp converts the former into the latter, with absf,
sqrt, log and constant-exponent powf handled similarly; anything else is opaque and rejects the chain. E is factorizable iff its yielded value carries the multiplicative form, which accepts softmax’s exp(x - m) and a norm’s abs(x / m) while rejecting a variance-shaped (x - m)^2.
Note that these limitations are imposed due to the current class of reductions supported in
our implementation and it can be generalized in the future to support other types of R2 reductions with more sophisticated online correction mechanisms.
Main Stages of the Fusion Transformation
Given R1, E, and R2 operand handles, we check if the given operations satisfy the fusibility criteria described above. If the conditions are met, we process the chain one op at a time, E first and then R2. Each op is first naively fused into R1’s loop (which recomputes it on every iteration of the loop) and then immediately re-tiled to match the tiling of R1. E is handled first, so that R2 can be fused against the slice E yields from the loop. At this stage, the program is not numerically accurate. The final stage is inserting online correction for fused R2 accumulator. Because R1 is used in each term of R2 in a factorizable way, E essentially can be factored into two factors where only one factor depends on R1. For example in softmax, exp(x - max) can be factored as exp(x) * exp(-max). We can define a new elementwise op E' which isolates the effect of this factor in E by setting all other inputs of E to their natural element at each use point (e.g., 1 for multiplication, 0 for addition). In the exp(x - max) case, this gives us E' = exp(0.0 - m). Now evaluating E' with old R1 and new R1 and computing the factor between them gives us the correction factor for the online adjustment for R2’s running accumulator. In the softmax case, this will compute exp(0.0 - max_new) / exp(0.0 - max_old) = exp(max_old - max_new). We show how this approach can be used to tile/fuse the attention kernel (which contains 3 chained dependent reductions) in the section below.
Implementation
The transformation is implemented as an OpRewritePattern matched on the consumer reduction R2. The pattern takes a control function which can be used to filter out chains that the user does not want to fuse. The proposed transform op uses this filtering to constrain fusion to the ops pointed to by the given op handles. Rather than re-implement tiling and fusion machinery, we attempt to reuse the already existing upstream utilities as much as possible. The user is expected to first tile the producer reduction R1 using the standard structured.tile_using_for (with the FullReduction strategy). We check that the given loop is a full-reduction loop by analyzing its body (i.e. it carries the running accumulator as an iter_arg and yields it back from a reduction inside the loop). To pull E and R2 into that loop we reuse the fusion utility scf::tileAndFuseConsumer. This clones the op into the loop body, naively recomputing it in every reduction iteration and yielding its result as a new iter_arg. Any E/R2 destination operand that tiling leaves defined below the loop is hoisted above it first.
Right after an op is fused, we re-adjust its tile sizes in-place using the corresponding tensor.extract_slice operations to match the tile size of R1. This is done for E first and then for R2, since R2 is fused against the slice that the already re-tiled E yields from the loop. Note that for E the output shape also changes because it is an elementwise operation, therefore corresponding tensor.insert_slice operations also need to be adjusted accordingly.
The next step is adding the online correction code to restore numerical validity. As described above, we construct new elementwise op E' based on fused E that isolates the contribution of R1. Evaluating E'(R1_new)/E'(R1_old) gives us the correction factor for R2’s accumulator which we re-route. For example, in the softmax case, the updated sum accumulator generated here looks like current_acc * (exp(0.0 - m_new) / exp(0.0 - m_old)).
Prototype implementation of the proposed approach is available here.
Example: Standard Attention to Fused Attention Using the Proposed Approach
We use the standard attention example to illustrate how the proposed approach
can be used to fuse the reductions in the attention computation. The high-level computation is shown below. Following flash-attention-v2 [1], max and sum reductions of the score matrix
x = Q @ K^T are done on the inner reduction axis j. The normalization division is done after these reductions.
R1 (max): m[i] = max_j x[i,j]
E (term): p[i,j] = exp(x[i,j] - m[i])
R2a (sum): s[i] = sum_j p[i,j]
R2b (P@V): o'[i,d] = sum_j p[i,j] * V[j,d]
div: o[i,d] = o'[i,d] / s[i]
The single term E feeds two consumer reductions over the same axis, so the transform op is applied twice: once for the R1 -> E -> R2a chain and once for the R1 -> E -> R2b chain.
1. Input IR and the transform schedule
R1 is already tiled along the reduction dimension with tile_using_for (the tile size, 32, is the loop’s step); everything else is untiled, with E materialized at the full [64, 512] extent.
// R1: the row max, tiled along the reduction axis.
%m = scf.for %iv = 0 to 512 step 32 iter_args(%acc_m = %ninf_64) {
%xt = tensor.extract_slice %x[0, %iv] [64, 32] // score tile
%mold = tensor.extract_slice %acc_m[0] [64]
%mt = linalg.generic ins(%xt) outs(%mold) // max(x_tile, acc_m)
%im = tensor.insert_slice %mt into %acc_m[0] [64]
scf.yield %im
}
// E: the term, at the full [64, 512] extent, read by BOTH reductions below.
%p = linalg.generic ins(%x, %m) outs(%empty_64x512) // exp(x - m)
// R2a: the row sum of E.
%s = linalg.generic ins(%p) outs(%zero_64) // sum_j p
// R2b: the P @ V contraction over E, reducing the same axis.
%o = linalg.generic ins(%p, %V) outs(%zero_64x128) // sum_j p * V
// The deferred normalization, downstream of both reductions.
%out = linalg.generic ins(%o, %s) outs(%empty_64x128) // o / s
The schedule names one chain per application. Fusing E moves it into the loop, so the second application cannot reuse the first handle to it; it re-derives the one left in place from the contraction’s operand. The loop returned by the first application is the producer reduction of the second chain.
%gen = transform.structured.match ops{["linalg.generic"]} in %arg0 .....
// #1 = max (R1), #2 = E, #3 = row sum (R2a), #4 = contraction (R2b),
// #5 = the normalizing divide.
%r1, %e, %r2a, %r2b, %div = transform.split_handle %gen .....
%loop = transform.structured.match ops{["scf.for"]} in %arg0 .....
// Chain 1: fuse E and the row sum into the tiled max loop.
// The returned loop is the producer reduction of the second chain.
%fused_a = transform.structured.fuse_dependent_reduction_op %e, %r2a into %loop .....
// The first fusion consumed the handle to E; the original E is still the
// contraction's operand, so re-derive it from there.
%e_again = transform.get_producer_of_operand %r2b[0] .....
// Chain 2: fuse E and the P @ V contraction into the same loop.
%fused_b = transform.structured.fuse_dependent_reduction_op %e_again, %r2b into %fused_a .....
2. E fused, still at full extent
scf::tileAndFuseConsumer clones E into the loop. It still computes the whole [64, 512] extent on every iteration. The loop grows an iter_arg to carry the result. Because E also feeds the
contraction, what is fused is a clone of E; the original stays outside for the second application.
// A second iter_arg (%acc_p) now carries E's full-extent result.
%r:2 = scf.for %iv = 0 to 512 step 32 iter_args(%acc_m = %ninf_64, %acc_p = %empty_64x512) {
%xt = tensor.extract_slice %x[0, %iv] [64, 32]
%mold = tensor.extract_slice %acc_m[0] [64]
%mt = linalg.generic ins(%xt) outs(%mold) // max(x_tile, acc_m)
// The fused clone of E: reads all 512 columns, writes the whole extent.
%xf = tensor.extract_slice %x[0, 0] [64, 512]
%pdst = tensor.extract_slice %acc_p[0, 0] [64, 512]
%pt = linalg.generic ins(%xf, %mt) outs(%pdst) // exp(x - m_new), FULL row
%im = tensor.insert_slice %mt into %acc_m[0] [64]
%ip = tensor.insert_slice %pt into %acc_p[0, 0] [64, 512]
scf.yield %im, %ip
}
// ... still outside the loop: the row sum (now reading %r#1), the original E,
// the P @ V contraction and the normalizing divide.
3. E re-tiled to the reduction tile
Next, the fused E is cut down to the current tile right after it is fused. It reads the
[64, 32] tile of x and also writes a [64, 32] tile of the carried p. At this point, the IR is
numerically invalid because earlier tiles of the carried p were computed against older maxes.
%r:2 = scf.for %iv = 0 to 512 step 32 iter_args(%acc_m = %ninf_64, %acc_p = %empty_64x512) {
%xt = tensor.extract_slice %x[0, %iv] [64, 32]
%mold = tensor.extract_slice %acc_m[0] [64]
%mt = linalg.generic ins(%xt) outs(%mold) // max(x_tile, acc_m)
// E, cut to the tile: reads the [64, 32] tile of x, writes a [64, 32] tile.
%pdst = tensor.extract_slice %acc_p[0, %iv] [64, 32]
%pt = linalg.generic ins(%xt, %mt) outs(%pdst) // exp(x_tile - m_new)
%im = tensor.insert_slice %mt into %acc_m[0] [64]
%ip = tensor.insert_slice %pt into %acc_p[0, %iv] [64, 32]
scf.yield %im, %ip
}
4. The row sum fused
The sum is fused next, against the tile that the re-tiled E yields, and its running accumulator becomes a third iter_arg of the fused loop.
%r:3 = scf.for %iv = 0 to 512 step 32
iter_args(%acc_m = %ninf_64, %acc_p = %empty_64x512, %acc_s = %zero_64) {
%xt = tensor.extract_slice %x[0, %iv] [64, 32]
%mold = tensor.extract_slice %acc_m[0] [64]
%mt = linalg.generic ins(%xt) outs(%mold) // max(x_tile, acc_m)
%pdst = tensor.extract_slice %acc_p[0, %iv] [64, 32]
%pt = linalg.generic ins(%xt, %mt) outs(%pdst) // exp(x_tile - m_new)
// The fused row sum, reducing this tile into the (stale) running sum.
%sold = tensor.extract_slice %acc_s[0] [64]
%st = linalg.generic ins(%pt) outs(%sold) // acc_s + sum_j p_tile
%im = tensor.insert_slice %mt into %acc_m[0] [64]
%ip = tensor.insert_slice %pt into %acc_p[0, %iv] [64, 32]
%is = tensor.insert_slice %st into %acc_s[0] [64]
scf.yield %im, %ip, %is
}
Note that tile size adjustment (i.e. re-tiling) only updates the tile sizes for the reduction dim. For the row sum there is no change in this step because its only input is E’s result, already cut to the tile in step 3. But for the P @ V contraction (step 6 below), re-tiling does impact the tile size of V because V is another independent input, so it must be re-tiled to match the new tile size. This re-adjusts V from [512, 128] down to the [32, 128] tile.
5. After the online correction
As explained above, the correction is derived from the fused E. This produces an elementwise operation that computes exp(0.0 - m) where m is the max. This expression is then evaluated at the new max and at the previous running max. Their ratio is the rescale factor, and the rescaled accumulator becomes the fused sum’s DPS init, which restores numerical validity.
%r:3 = scf.for %iv = 0 to 512 step 32
iter_args(%acc_m = %ninf_64, %acc_p = %empty_64x512, %acc_s = %zero_64) {
%xt = tensor.extract_slice %x[0, %iv] [64, 32]
%mold = tensor.extract_slice %acc_m[0] [64]
%mt = linalg.generic ins(%xt) outs(%mold) // max(x_tile, acc_m)
%pdst = tensor.extract_slice %acc_p[0, %iv] [64, 32]
%pt = linalg.generic ins(%xt, %mt) outs(%pdst) // exp(x_tile - m_new)
%sold = tensor.extract_slice %acc_s[0] [64]
// The correction term: E isolated on the max (x := 0), evaluated at the new
// max and at the previous running max.
%tnew = linalg.generic ins(%mt) outs(%empty_64) // exp(0 - m_new)
%told = linalg.generic ins(%mold) outs(%empty_64) // exp(0 - m_old)
%f = linalg.elementwise <div> ins(%tnew, %told) // exp(m_old - m_new)
// The rescaled running sum becomes the fused sum's DPS init.
%sc = linalg.elementwise <mul> ins(%sold, %f) // acc_s * factor
%st = linalg.generic ins(%pt) outs(%sc) // sc + sum_j p_tile
%im = tensor.insert_slice %mt into %acc_m[0] [64]
%ip = tensor.insert_slice %pt into %acc_p[0, %iv] [64, 32]
%is = tensor.insert_slice %st into %acc_s[0] [64]
scf.yield %im, %ip, %is
}
// ... unchanged: the original E, the P @ V contraction, the divide.
6. After the second application: fusing the P @ V contraction
The second application repeats the same three steps for the R1 -> E -> R2b
chain, this time fusing the original E and the contraction. The correction is numerically the same as before (exp(m_old - m_new)) but this time applied to P @ V accumulator re-scaling. The result is a single online loop carrying five iteration args. The normalizing division is left outside.
%r:5 = scf.for %iv = 0 to 512 step 32
iter_args(%acc_m = %ninf_64, %acc_p1 = %empty_64x512, %acc_s = %zero_64,
%acc_p2 = %empty_64x512, %acc_o = %zero_64x128) {
%xt = tensor.extract_slice %x[0, %iv] [64, 32]
%mold = tensor.extract_slice %acc_m[0] [64]
%mt = linalg.generic ins(%xt) outs(%mold) // max(x_tile, acc_m)
// One E per fused chain: the clone for the row sum, the original for P @ V.
%p1dst = tensor.extract_slice %acc_p1[0, %iv] [64, 32]
%p1 = linalg.generic ins(%xt, %mt) outs(%p1dst) // exp(x_tile - m_new)
%p2dst = tensor.extract_slice %acc_p2[0, %iv] [64, 32]
%p2 = linalg.generic ins(%xt, %mt) outs(%p2dst) // exp(x_tile - m_new)
// Chain 1: correction over the row sum's [64] accumulator shape.
%sold = tensor.extract_slice %acc_s[0] [64]
%tnew = linalg.generic ins(%mt) outs(%empty_64) // exp(0 - m_new)
%told = linalg.generic ins(%mold) outs(%empty_64) // exp(0 - m_old)
%f1 = linalg.elementwise <div> ins(%tnew, %told) // exp(m_old - m_new)
%sc = linalg.elementwise <mul> ins(%sold, %f1) // acc_s * factor
%st = linalg.generic ins(%p1) outs(%sc) // sc + sum_j p1
// Chain 2: the same term, correction over the [64, 128] accumulator shape.
%vt = tensor.extract_slice %V[%iv, 0] [32, 128] // value tile
%oold = tensor.extract_slice %acc_o[0, 0] [64, 128]
%tnew2 = linalg.generic ins(%mt) outs(%empty_64x128) // exp(0 - m_new), broadcast
%told2 = linalg.generic ins(%mold) outs(%empty_64x128)// exp(0 - m_old), broadcast
%f2 = linalg.elementwise <div> ins(%tnew2, %told2) // exp(m_old - m_new)
%oc = linalg.elementwise <mul> ins(%oold, %f2) // acc_o * factor
%ot = linalg.generic ins(%p2, %vt) outs(%oc) // oc + sum_j p2 * V_tile
%im = tensor.insert_slice %mt into %acc_m[0] [64]
%ip1 = tensor.insert_slice %p1 into %acc_p1[0, %iv] [64, 32]
%is = tensor.insert_slice %st into %acc_s[0] [64]
%ip2 = tensor.insert_slice %p2 into %acc_p2[0, %iv] [64, 32]
%io = tensor.insert_slice %ot into %acc_o[0, 0] [64, 128]
scf.yield %im, %ip1, %is, %ip2, %io
}
// Only the normalizing divide is left outside.
%out = linalg.generic ins(%r#4, %r#2) outs(%empty_64x128) // o / s
Evaluation
Two cases are evaluated. Both are generated from Linalg-level ops and lowered to the XeGPU backend for end-to-end execution, with results checked against NumPy. Attention is the motivating case; case 2 covers the smaller R1 -> E -> R2 chains, where three kernels differ only in the elementwise term E.
| Kernel | E |
Correction derived from E |
|---|---|---|
| softmax | exp(x - m) |
exp(m_old - m_new) |
| L1 normalize | abs(x / m) |
m_old / m_new |
| L2 normalize | (x / m)^2 |
(m_old / m_new)^2 |
The same code path produces all three; nothing in the implementation is specific to exp.
Both cases were measured on the same Intel Battlemage (BMG) GPU.
Case 1: Attention (BMG)
The chain is max -> exp(S - m) -> {sum, attn @ V}: two consumer reductions over one elementwise term, fused into one loop by applying the transform twice.
- Hardware: Intel Battlemage (BMG) GPU.
- Problem sizes:
Z = 2(batch),H = 8heads, head dim= 64,f16, withn_ctxswept over 1024, 4096, 8192 and 16384. - Baseline (unfused): the same kernel tiled and fused with the existing upstream transforms only. This version does not do any fusion on the reduction dim, so the score matrix is recomputed for each reduction.
- This RFC (reduction fusion): the schedule from this proposal that fuses the max, sum and
attn * Vreductions into a single fused loop.
| n_ctx | unfused | reduction fusion (this RFC) |
|---|---|---|
| 1024 | 1.00x | 2.49x |
| 4096 | 1.00x | 2.69x |
| 8192 | 1.00x | 2.59x |
| 16384 | 1.00x | 2.19x |
Fusing the dependent reductions into a single online loop gives a 2.2x–2.7x speedup over the unfused baseline across the sweep.
Case 2: Softmax and L1/L2 normalization (BMG)
Each is a max -> E -> sum chain fused into one loop by a single application of the transform. The epilogue – softmax’s normalizing divide, or the division by the norm – stays outside and recomputes the term from the final max, so each kernel goes from three passes over the input to two.
- Hardware: Intel Battlemage (BMG) GPU, as in case 1.
- Problem sizes:
f32, parallel dim fixed at 4096, reduction dim swept over 4096, 8192 and 16384. Work-group 64 rows, subgroup 8 rows, subgroup size 16. - Baseline (two-pass): the existing upstream schedule, one loop over the reduction axis per reduction –
max, thensum, then the epilogue: 3 passes. - This RFC (reduction fusion):
maxandsumaccumulated together in one loop with the online correction: 2 passes.
| reduction dim | baseline (two-pass) | softmax | L1 normalize | L2 normalize |
|---|---|---|---|---|
| 4096 | 1.00x | 1.23x | 1.22x | 1.22x |
| 8192 | 1.00x | 1.23x | 1.22x | 1.23x |
| 16384 | 1.00x | 1.21x | 1.20x | 1.21x |
Eliminating one of the three passes gives a 1.20x–1.23x speedup, flat across the sweep.
References
[1]: Tri Dao. FlashAttention-2: Faster Attention with Better Parallelism and
Work Partitioning. arXiv preprint arXiv:2307.08691, 2023.