[RFC][Affine]Add legality-aware unroll-and-jam selection for shared-input reductions

Summary

We found a class of GPU reductions where multiple local outputs consume the same reduction input:

for f:
  for r:
    acc[f] += input[r] * weight[f, r]

When multiple f values are computed by the same thread, input[r] is shared across the output reductions.

However, ordinary full unrolling of the outer output loop can turn this into:

for r:
  acc0 += input[r] * weight[0, r]

for r:
  acc1 += input[r] * weight[1, r]

The equivalent input[r] accesses are now in different loops. Unless the inner reductions are also fully exposed later, ordinary CSE cannot recover the reuse.

Unroll-and-jam produces the more useful form:

for r:
  acc0 += input[r] * weight[0, r]
  acc1 += input[r] * weight[1, r]

which places the common input accesses in the same iteration and allows existing CSE/backend optimization to eliminate redundant loads.

MLIR already has the mechanical transformation needed for this through loopUnrollJamByFactor(). The missing piece is a conservative way to identify cases where this transformation is both legal and likely to expose reuse not already recovered downstream.


Motivation from real workloads

The issue was first observed while analyzing convolution kernels from real models.

A representative example is a ConvMixer stem convolution with:

input:   [1, 3, 224, 224]
weight:  [1536, 3, 7, 7]
output:  [1, 1536, 32, 32]

For each output:

Y[F, OH, OW] =
  sum(C, KH, KW)
    X[C, 7*OH + KH, 7*OW + KW] *
    W[F, C, KH, KW]

The input address does not depend on F, while the weight and accumulator do.

This makes adjacent local output channels a natural source of input reuse.

In prepared two-output-channel schedules, kernel-level measurements showed that this can be significant:

Kernel Runtime reduction
ConvMixer dispatch ~56%
RepVGG dispatch ~24%
Res2Net stem ~25%

Other kernels showed only small or negligible changes.

That distinction is important: this is not a proposal to apply unroll-and-jam indiscriminately. The measurements suggest that there are profitable cases, but also that selection matters.


Investigation

1. Output grouping alone is not the whole problem

The first suspected cause was producer scheduling.

For the motivating ConvMixer case, the observed GPU schedule assigned the innermost OW=32 dimension across 32 threads, leaving the output-channel thread tile at F=1.

We verified that changing the scheduling configuration can produce F=2, so creating a two-output local group does not require a new generic MLIR transformation.

Conceptually:

before:
  one thread -> one output channel

after:
  one thread -> two output channels

This creates the optimization opportunity, but it does not by itself expose input reuse.


2. Ordinary full unrolling destroys the useful loop relationship

With F=2, the relevant MLIR shape is:

affine.for %f = 0 to 2 {
  affine.for %r = ... {
    %x = affine.load %input[%r]
    %w = affine.load %weight[%f, %r]
    %old = affine.load %acc[%f]
    %prod = arith.mulf %x, %w
    %sum = arith.addf %old, %prod
    affine.store %sum, %acc[%f]
  }
}

At this point the important relationships are still explicit:

input[r]      -> invariant in f
weight[f,r]   -> dependent on f
acc[f]        -> distinct per f

Ordinary full unrolling of %f instead creates two separate reduction loops.

In a prepared seven-case corpus, the shared-input pattern was visible in six cases before the outer full-unroll step and in zero cases afterwards. The remaining case was intentionally rejected because the alias relationship could not be proven safely.

So the missed opportunity is not only that a producer may choose F=1.

There is also a later transformation-ordering problem:

local output grouping
        |
        v
ordinary full unroll
        |
        v
separate reduction loops
        |
        v
shared-input relation is no longer locally visible

3. LLVM can already remove the redundant load when the reuse is exposed

We also checked whether this should instead be treated as a backend CSE problem.

For small reductions, downstream compilation can fully expose the reduction body. Once equivalent loads appear in the same straight-line region, existing LLVM optimization removes them correctly.

For example, in one small case the shared-input loads were reduced from:

54 -> 27

without requiring a new NVPTX-specific optimization.

This shows that the backend already knows how to eliminate the redundant access once both uses are visible together.

The problem is larger reductions where the reduction loops remain.

Representative code-generation observations were:

Case Shared-input loads
ConvMixer 98 → 49
RepVGG dispatch 99 → 9
Res2Net stem 98 → 49
Small R=27 cases 27 → 27

The small cases already recovered the reuse without jamming. The larger cases retained a residual opportunity.

This suggests that the missing optimization is not a new load CSE rule. It is the loop restructuring required to expose the two uses in the same iteration.


Existing MLIR unroll-and-jam already provides the required transformation

We initially considered a custom interchange/coarsening transformation.

That turned out to be unnecessary.

MLIR already provides:

loopUnrollJamByFactor(...)

and the existing implementation can handle the relevant nested reductions.

A reduced SCF experiment confirmed that:

for f = 0..2:
  acc = for r iter_args(...)

can be transformed into a single inner loop carrying two independent accumulators.

Conceptually:

before:

for f:
  for r:
    acc[f] += ...

after:

for r:
  acc0 += ...
  acc1 += ...

This is exactly the loop structure needed for the common input to become visible to later CSE.

Therefore, a new unroll-and-jam implementation is not needed.


Why the existing utility cannot simply be called automatically

The remaining issue is legality.

loopUnrollJamByFactor() is a transformation primitive. It is not a general semantic legality analysis.

This is consistent with the original upstream discussion around MLIR unroll-and-jam support: the transformation does not require the outer loop to be parallel in all valid cases, and callers are expected to ensure that applying it is legal.

That distinction matters because unroll-and-jam can change execution order across outer iterations.

For example:

for f:
  Fore(f)

  for r:
    Body(f, r)

  Aft(f)

may be reordered when the inner loops are jammed.

A transformation can therefore produce well-formed IR while still being incorrect if there are relevant memory dependencies.

Checking only whether the transformation utility succeeds is not sufficient.


Why not add isLoopParallel() to generic unroll-and-jam?

A simple conservative solution would be:

if (!isLoopParallel(loop))
  return failure();

before every generic unroll-and-jam.

That would be too restrictive.

Parallelism is a sufficient condition for some unroll-and-jam cases, but it is not a necessary condition. A loop may have dependences that are still preserved by a particular unroll-and-jam transformation.

Adding this restriction to the generic utility would reject valid existing or future uses.

At the other extreme, implementing a complete MLIR equivalent of LLVM’s generic isSafeToUnrollAndJam() would substantially increase the scope of this optimization.

The motivating pattern is much narrower and allows stronger local proofs.


Proposed direction

Add an opt-in Affine pass that recognizes a restricted shared-input reduction pattern, proves the required independence properties, applies conservative effectiveness checks, and then delegates the actual transformation to the existing unroll-and-jam utility.

The intended flow is:

shared-input reduction candidate
               |
               v
        structural match
               |
               v
       storage / alias proof
               |
               v
        legality checks
               |
               v
   effectiveness / pressure guard
               |
               v
   loopUnrollJamByFactor()

The generic unroll-and-jam pass and utility remain unchanged.

Restricted pattern

The initial implementation only accepts regular memory-backed reductions of the form:

for output:
  for reduction:
    acc[output] +=
        shared[reduction] *
        perOutput[output, reduction]

with strong restrictions.

Legality requirements

The candidate is rejected unless the pass can establish all of the following:

  • static rectangular loop structure;
  • full local-output grouping for the requested jam factor;
  • no unsupported loop results / reassociation path;
  • exactly one accumulator load/store recurrence;
  • accumulator storage is local and has an injective supported layout;
  • different outer iterations update disjoint accumulator coordinates;
  • input storage does not alias the accumulator;
  • exactly one multiplicand is invariant with respect to the output loop;
  • no calls, atomics, barriers, extra stores, nested control-flow regions, or unknown effects.

If any proof fails, the loop is left unchanged.

The current implementation also contains negative tests for cases such as:

aliased subviews
unknown alias provenance
overlapping accumulator coordinates
reinterpret_cast accumulator layouts
calls inside the reduction
barriers
atomics
extra stores
nested conditionals
unsupported iter_args

This is intentionally narrower than a generic unroll-and-jam legality analysis.


Effectiveness and resource considerations

Legality and profitability should remain separate.

The experiments show why.

Small reductions can already be fully exposed downstream, allowing ordinary LLVM CSE to recover the shared load without jamming.

Larger reductions are more likely to retain separate loops and therefore retain the missed reuse.

The proposed pass therefore has an effectiveness guard based on the estimated fully-unrolled reduction size.

This is intentionally only a conservative proxy, not a target cost model.

Similarly, jamming introduces additional accumulator state, so the pass also limits estimated extra accumulator registers.

The intent is:

legality:
  is the transformation semantically safe?

effectiveness:
  is there likely to be reuse that the backend will not already recover?

resource guard:
  is the additional accumulator state bounded?

No profitability option should be able to bypass legality checks.


Why MLIR/Affine is the appropriate level

Before ordinary unrolling, Affine IR still explicitly represents:

outer IV       = local output
inner IVs      = reduction dimensions

shared input   = outer-IV invariant
weight         = outer-IV dependent
accumulator    = outer-IV dependent

This is exactly the information needed to recognize the opportunity and prove a restricted form of independence.

After ordinary unrolling and further lowering, the compiler largely sees separate reduction loops.

Recovering their original relationship in LLVM would require a more general loop-fusion/jamming transformation.

At the Affine level, the required mechanical transformation already exists.

This makes the pre-unroll Affine stage a natural place to make the decision.


Scope

This proposal does not attempt to:

  • change IREE’s output-channel scheduling policy;
  • automatically choose F=2 or another producer tile size;
  • modify generic affine-loop-unroll-jam;
  • change loopUnrollJamByFactor() semantics;
  • implement a general unroll-and-jam legality solver;
  • add an NVPTX-specific load optimization.

The producer scheduling decision and the loop-jamming decision are separate:

producer:
  should one thread own multiple outputs?

MLIR loop optimization:
  given multiple local outputs, should their reductions be jammed?

The first creates the opportunity.

The second determines whether that opportunity can be safely exposed to downstream optimization.


Performance context

The current measurements should be interpreted as evidence that this IR shape can matter, not as a claim of universal model-level speedup.

Prepared kernel-level experiments showed large wins in several cases, while others were neutral.

Full-model experiments were also mixed: RepVGG retained a meaningful improvement, while ConvMixer and Res2Net showed much smaller or noisy whole-model changes.

This is consistent with the proposed design: there are real profitable cases, but transformation selection is required.

The purpose of the pass is therefore not to make every shared-input reduction use unroll-and-jam.

It is to make it possible to safely exploit the cases where:

  1. the outer reductions are provably independent;
  2. the shared input reuse is real; and
  3. ordinary downstream optimization is unlikely to recover the same reuse on its own.

Conclusion

The investigation led to the following sequence:

real GPU workload shows a large kernel-level difference
            |
            v
shared-input reuse identified
            |
            v
producer F=1 scheduling investigated
            |
            v
F=2 grouping shown to be possible without a new transform
            |
            v
ordinary full-unroll shown to split the reductions
            |
            v
shared-input pattern disappears after that boundary
            |
            v
LLVM shown to recover duplicate loads only when sufficiently exposed
            |
            v
new backend CSE optimization ruled out
            |
            v
custom loop transform ruled out
            |
            v
existing MLIR unroll-and-jam shown to produce the desired loop shape
            |
            v
automatic use blocked by missing caller-side legality/selection
            |
            v
restricted legality-aware selector is the smallest practical solution

The proposed change therefore does not add a new transformation.

It adds the missing selection and legality layer needed to safely apply an existing MLIR transformation to a real optimization opportunity that can otherwise be destroyed by the current lowering sequence.

Apologies for posting the original RFC before fully familiarizing myself with the forum guidelines.

I can no longer edit the original post, so I’m posting a revised version below to clarify the proposal, its scope, and the specific questions I’d like feedback on. Please use this version as the basis for further discussion.

RFC Select shared-input reductions for unroll-and-jam

Summary

I propose an opt-in selection mode for affine-loop-unroll-jam that recognizes a restricted class of independent, memory-backed floating-point reductions sharing an input, checks their legality, and invokes the existing loopUnrollJamByFactor() utility.

The motivation is a phase-ordering problem: ordinary full unrolling of an output loop can separate reductions whose input accesses could otherwise be reused. Applying unroll-and-jam first exposes that reuse without changing the work assigned to a thread or the order of either output’s reduction.

The prototype adds select-shared-input-reductions, disabled by default. This RFC asks whether that restricted selection policy belongs in the existing Affine pass, with profitability left under pipeline control rather than introducing a default-on heuristic.

Motivating example

Consider two output channels computed at the same convolution position. They use different weights but read the same input patch. The relevant loop structure is, schematically:

for f in [0, 2):
  for k in [0, K):
    acc[f] += x[k] * w[f, k]

Ordinary full unrolling of f produces separate reductions:

for k in [0, K):
  acc[0] += x[k] * w[0, k]

for k in [0, K):
  acc[1] += x[k] * w[1, k]

Unroll-and-jam instead produces:

for k in [0, K):
  acc[0] += x[k] * w[0, k]
  acc[1] += x[k] * w[1, k]

The two x[k] accesses now occur in the same inner iteration. Subsequent load elimination can reuse the value when it proves the intervening store cannot modify it. The selector itself does not eliminate loads.

For each output, the updates still execute in the original k order. The change interleaves independent reductions; it does not reassociate a reduction.

Proposed selection policy

A pipeline would enable the option before ordinary output-loop unrolling and supply the existing unroll-jam-factor. The initial implementation targets the following subset:

Property Initial restriction
Loop nest Perfectly nested, constant bounds, and no loop-carried SSA results. The output loop is [0, F) with unit step, where F >= 2 equals the requested jam factor.
Computation One memory-backed update formed from three affine.load operations, arith.mulf, arith.addf, and one affine.store, matched through SSA definitions. No additional body operations or regions.
Accumulator The load and store access the same element. One complete access coordinate is the output-loop induction variable.
Shared input Exactly one multiplicand’s access is invariant with respect to the output loop.
Aliasing Alias analysis proves NoAlias between the accumulator and each input. The read-only inputs may alias each other.

These are sufficient conditions for initial support, not a claim that all other nests are unsafe. Unsupported candidates remain unchanged. In this mode, finding no candidate must not fall back to unfiltered unroll-and-jam. With the option disabled, existing behavior is preserved.

Legality argument

The proof must establish independence, not merely recognize a multiply-add expression.

An accumulator coordinate equal to f distinguishes the index tuples accessed by different output iterations. For valid in-bounds accesses, memref layout semantics guarantee that distinct tuples identify distinct elements. The alias checks additionally prevent accumulator writes from changing either input.

Under these conditions, operations from different outputs can be interleaved without changing the values they observe. Within each output, the inner-loop order and arithmetic operations remain unchanged. No additional floating-point reassociation permission is needed.

The perfect-nest and body restrictions also exclude intervening calls, synchronization, extra stores, and operations surrounding the inner loops whose movement would require additional reasoning.

The generic utility has structural transformation checks, but these are not a complete memory-dependence proof. I propose keeping this restricted proof at the selection boundary, rather than changing the utility’s contract or making a general unroll-and-jam legality solver a prerequisite.

Evidence and its limits

The kernel experiments used prepared two-output-channel schedules:

Case Shared-input load count, before → after Kernel runtime reduction
ConvMixer dispatch 98 → 49 approximately 56%
RepVGG dispatch 99 → 9 approximately 24%
Res2Net stem 98 → 49 approximately 25%
Small reductions with K = 27 27 → 27 No additional load-count benefit

These measurements demonstrate an opportunity, not an end-to-end A/B evaluation of the proposed selector. They also do not isolate how much of the runtime change comes from load elimination versus other generated-code changes.

A full-model RepVGG experiment reported a 9.85% runtime reduction in the PR description, while ConvMixer and Res2Net whole-model changes were small or noisy. The results do not establish a general model-level speedup or justify enabling the policy by default.

Pipeline observations and design rationale

Why scheduling alone did not settle the issue

The motivating producer configuration initially assigned one output channel per thread. Configuration changes could already produce two local outputs; a new work-distribution transformation was unnecessary.

In a prepared seven-case corpus, six cases exposed the target nest before ordinary full unrolling and none retained that nested form afterwards. The seventh lacked the required alias proof. This identified the unrolling boundary as the point to intervene, rather than motivating a new scheduling mechanism. These are targeted cases, not a corpus-wide prevalence estimate. Investigation.

Why not rely on later optimization?

Small reductions did recover reuse downstream: one experiment reduced 54 shared-input loads to 27 without a new NVPTX rule. Larger examined cases retained separate reduction loops. This is an observation about the tested pipeline, not a claim that LLVM could never recover the relationship. Investigation.

The proposed placement avoids making that recovery necessary: it uses the grouping while it is explicit.

Why Affine, and how does this relate to fusion?

Affine retains loop bounds and structured memory accesses suitable for expressing the selection conditions. The policy would depend on those properties, not on convolution names, IREE-specific metadata, or a GPU architecture.

Existing affine-loop-fusion also supports sibling fusion of independent loops reading the same memref. That is a relevant alternative, not something this RFC assumes is incapable of exposing the reuse. The proposed selector instead acts on an existing output group and explicit jam factor before unrolling separates it. Whether an existing fusion pipeline already covers the motivating cases is therefore a useful review question.

Related work

Anthimopoulos et al., Register Blocking: A Source-to-Source Analytical Modelling Approach for Affine Loop Kernels (ACM TECS, 2025), study analytical selection of blocking factors and loop order. This proposal is a restricted application of the same established register-blocking/unroll-and-jam approach, not an implementation of that broader optimization strategy. The paper provides context; its CPU evaluation does not validate this GPU selection policy.

Profitability and scope

Legality answers whether the change is safe; shared-input reuse identifies a reason it may help. Neither guarantees a speedup.

I propose keeping the initial mode structural and opt-in. Choosing the factor and enabling the pass would remain pipeline decisions. Reduction-size and additional-live-accumulator limits could be evaluated separately, but should be treated as profitability proxies, never as substitutes for legality checks.

This change would not select producer tiles, redistribute work across threads, add target-specific load elimination, or change generic unroll-and-jam semantics. It would not introduce automatic profitability thresholds in the initial patch.

Validation and next steps

Before landing, regression coverage should establish both successful transformation and conservative rejection: uncertain aliasing, non-disjoint accumulator coordinates, unsupported bodies or bounds, and loop-carried SSA values. It should also check option handling, multiple candidates, and unchanged behavior when the option is disabled.

Performance evaluation should then compare otherwise identical pipelines with the selector off and on, including cases where downstream optimization already recovers the reuse. Broader automatic selection would need evidence from those comparisons, including regressions and resource usage.

Feedback requested

  1. Is an opt-in mode in affine-loop-unroll-jam the appropriate home for this policy, or can existing Affine fusion infrastructure cover the motivating cases without a new selector?
  2. Are the proposed independence and alias conditions an appropriate initial boundary, and are there existing analysis utilities that could express the proof more directly?
  3. Is a structural, pipeline-controlled first step acceptable, with automatic profitability heuristics considered separately?

The proposed contribution is a restricted selection and legality layer around an existing transformation: expose shared-input reuse while the loop relationship is explicit, without requiring a new scheduling strategy or a general profitability model.

So the short version of this is that you want to contribute legality checks and profitability heuristics for affine unroll and jam. I’d say legality checks can go directly intro the existing pass and profitability heuristic may become a pass option. In future, it may be a switch or some sort of smarter selector, no need to be blocked on this now.

The long list of legality requirements in the original post looks excessive and tailored to the particular usecase listed as the motivation, in particular with its “exactly one” and “full” restrictions. These need to be relaxed to the justifiably minimal and realistic set of conditions.

IMO, FP reassociation should remain an option somehow and not block the transformation. Either as a dedicated flag controlling the heuristic or thinking about an analysis that walks FP operations and looks at their fast-math flags (not sure we have a generic way for this right now, needs exploration).

Similarly, a lot of Affine-driven flows assume memrefs that are function arguments do not alias even in absence of the noalias argument attribute, so it should be an option or there should be a mechanism to identify this attribute.

In Affine, legality can, and likely should, be based on preserving the order of dependencies as computed by the polyhedral model, so focusing some invariance or locality properties sounds off to me.

Thanks, this clarifies the direction. I’ll separate legality from the motivating pattern and split the work into small patches:

  1. Dependence-based legality in the existing pass. Conservatively reject unsupported cases, keeping only structural restrictions required by the transformation or analysis. Include accepted and rejected cases.

  2. Aliasing policy. Add an explicit way to express non-aliasing assumptions for function-argument memrefs, after checking existing Affine conventions.

  3. Shared-input selection. Add a simple opt-in heuristic for invariant loads with potential reuse, separate from legality.

  4. FP reassociation policy. Check whether existing fast-math flags suffice and whether an additional option is needed. Order-preserving FP transformations would not require reassociation permission.

I plan to apply the legality checks by default. This may stop transforming some nests the pass currently jams, including cases the analysis cannot prove safe. Is that acceptable, or are there compatibility constraints I should account for?

Would it also be okay to create sub-issues under llvm/llvm-project#225396 to track these patches?