Skip to content

[GlobalOpt] Fold batch_matmul broadcasts through affine dequantization - #25197

Merged
Manewing merged 3 commits into
mainfrom
walbroel/fold-broadcast-through-dequantize
Nov 13, 2026
Merged

Manewing merged 3 commits into
mainfrom
walbroel/fold-broadcast-through-dequantize

Conversation

@Manewing

@Manewing Manewing commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #25099. Three commits: the first moves FoldBroadcastIntoBatchMatmul to after transpose and affine-quantization propagation (no test changes, can land separately), the second adds the fold through dequantize, the third applies the same fold to contractions that are already linalg.generic.

Problem

Shared quantized weights reach a batch_matmul in two forms. The existing fold handles only the first:

// Form A: already folded into the RHS map (b,m,n,k) -> (k,n)
%w  = dequantize_affine %w_q : tensor<KxNxi8> -> tensor<KxNxf32>
%wb = linalg.broadcast %w : tensor<BxKxNxf32>
%r  = linalg.batch_matmul %a, %wb

// Form B: not handled; the dequantize hides the broadcast
%wb = linalg.broadcast %w_q : tensor<BxKxNxi8>
%w  = dequantize_affine %wb : tensor<BxKxNxi8> -> tensor<BxKxNxf32>
%r  = linalg.batch_matmul %a, %w

With QDQ off, Form B dequantizes the weights once per batch element into a BxKxN f32 tensor. With QDQ on, the integer contraction reads a materialized BxKxN i8 broadcast until dispatch creation repairs it.

Fix

The producer matcher now looks through a dequantize_affine whose input is a broadcast (linalg.broadcast or a broadcasting, possibly permuting, generic). In one step it rebuilds the dequantize at the source rank, with scale and zero-point maps rebased onto the source dims, and composes the broadcast into the contraction operand map:

// Form B after the fold == Form A after the fold
%w = dequantize_affine %w_q : tensor<KxNxi8> -> tensor<KxNxf32>   // native rank
%r = linalg.batch_matmul {indexing_maps = [..., (b,m,n,k) -> (k,n), ...]} %a, %w

The named-or-generic decision is the same as for the direct fold. LHS broadcasts and transposes already folded into the dequantize maps are handled too.

Generic contractions. The fold used to match only the named linalg.batch_matmul. When contractions are generalized earlier in the pipeline (--iree-opt-generalize-matmul, on from -O2), the contraction is already a generic when the fold runs, so nothing folded: even Form A stayed a float matmul, because the QDQ rewrite did not see a dequantize as direct producer. A second pattern now matches generics through the contraction interface, reuses the same producer matching and keeps the op generic. It is skipped unless the operand still reads a reduction loop, the new maps still describe a contraction and every loop is still bound by an operand. The named path is unchanged.

The fold does not fire when

  • the dequantize has other users (it would add a dequantize instead of shrinking one),
  • a scale or zero-point map depends on a broadcast-introduced dim,
  • the consumer is not a contraction (nothing would absorb the broadcast).

A hoist-only rewrite (dequantize(broadcast(w)) -> broadcast(dequantize(w))) was tried and rejected: the QDQ matcher does not look through broadcasts, so it leaves a float matmul over broadcast f32 weights.

Why the pass moves. For transpose -> broadcast -> dequantize -> batch_matmul, transpose propagation first merges transpose and broadcast into one permuting-broadcast generic, which the fold then absorbs completely. In the old position a physical i8 transpose remained on the weight path. The fold runs before the sub-byte constant packing, which traces a dequantize input back to its constant through reshapes only: with the fold first, a Form B weight is packed at its native rank.

Tests and validation

  • Pass-level cases in fold_broadcast_into_batch_matmul.mlir: per-channel and per-tensor parameters, asymmetric, unsigned storage, transposed maps, dynamic dims, LHS, broadcasting generic, multi-use broadcast (fires), multi-use dequantize and batch-varying parameters (do not fire).
  • Generic-contraction cases in the same file: a broadcast input, a dequantize of a broadcast, and two that must not fold (contraction maps with another body, a broadcast along the reduction dim).
  • New fold_broadcast_into_batch_matmul_stages.mlir runs Forms A and B through the full global-opt pipeline with QDQ on and off and checks that both reach the same form. The QDQ-on run is repeated with generalize-matmul=true.
  • No existing expectations changed. After the rebase onto the current [GlobalOptimization] change pass ordering so img2col convolutions in quantized conv models will result in integer math #25099 and the third commit, the GlobalOptimization, DispatchCreation and LinalgExt lit tests pass; the e2e tests were last run before the rebase.
  • Form A and Form B now produce identical dispatches in both modes. Outputs are bit-identical to Form A and to the pre-change build; the integer path matches a float64 reference to 1.5e-5.

Performance

Apple M4, llvm-cpu, --task_topology_performance_level=performance (4 workers), median of 10 repetitions, default optimization level. QDQ batch matmul of an 8x384x768 activation with a constant 768x512 i8 weight shared across the batch, per-channel scale. Each cell is #25099 → this PR. "DT" is --iree-opt-data-tiling, "UK" adds --iree-llvmcpu-enable-ukernels=all, "float" is --iree-global-opt-enable-qdq-to-integer-math=false.

Case No DT DT DT + UK DT, float
Form A 13.9 → 13.8 ms 1.77 → 1.82 ms 2.12 → 2.09 ms 6.30 → 6.29 ms
Form B 10.4 → 13.8 ms 10.4 → 1.80 ms 10.4 → 2.09 ms 6.53 → 6.14 ms
Form B, per-channel weight zero point 10.9 → 14.0 ms 10.9 → 1.78 ms 10.8 → 1.98 ms 6.55 → 6.29 ms
Form B, weight stored [N, K] and transposed 13.9 → 9.88 ms 13.9 → 1.92 ms 14.1 → 2.20 ms 6.58 → 5.87 ms

Form A compiles to byte-identical modules before and after. Before, the Form B integer contraction kept the batch as its own loop (matmul_like_8x384x512x768) and was not data-tiled; now it collapses to the same matmul_like_3072x512x768 dispatch as Form A. With data tiling that is 5x to 8x faster. Without data tiling Form B now matches Form A, which is 1.3x slower than before for two of the three cases: the non-data-tiled integer matmul is slower than both the previous uncollapsed shape and the float path (about 6.4 ms). That gap exists for Form A on main as well and is not addressed here.

🤖 Generated with Claude Code

@Manewing
Manewing added this pull request to stack #25198 November 4, 2026 15:03
@Manewing Manewing changed the title Walbroel/fold broadcast through dequantize [GlobalOpt] Fold batch_matmul broadcasts through affine dequantization Nov 5, 2026
@Manewing
Manewing force-pushed the walbroel/fold-broadcast-through-dequantize branch from ad27126 to 814893c Compare November 5, 2026 10:39
@egebeysel egebeysel self-assigned this Nov 6, 2026
@Manewing
Manewing force-pushed the walbroel/fold-broadcast-through-dequantize branch from 814893c to aec3630 Compare November 12, 2026 13:05
Base automatically changed from manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math to main November 12, 2026 16:42
Manewing and others added 3 commits November 12, 2026 17:42
…tion propagation

Run FoldBroadcastIntoBatchMatmul after transpose propagation and affine
quantization propagation, immediately before the QDQ-to-integer conversion,
instead of before transpose propagation.

Transpose propagation merges a transpose feeding a broadcast into a single
broadcasting-and-permuting generic, and folds a transpose of a dequantized
value into the dequantize's output map. Running the broadcast fold after both
lets it see a transposed and broadcast contraction operand as one producer
whose map composes into the contraction map, rather than folding the
broadcast and leaving a physical transpose on the operand path. This is the
order the contraction operand normalization needs before the single QDQ
conversion: the contraction reads its operands at native rank and its
dequantize producers directly.

No existing test changes: for the broadcast-after-dequantize form the fold
reaches the same result in either position.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Florian Walbroel <[email protected]>
Shared quantized weights reach a batch_matmul in two forms: dequantized
at their native rank and then broadcast, or broadcast as integers and
then dequantized. FoldBroadcastIntoBatchMatmul already folds the first
form. The second left a batch-sized dequantize feeding a full-rank
batch_matmul: with QDQ conversion the integer contraction read a
materialized integer broadcast, and without it the weights were
dequantized once per batch element.

Extend the fold's producer matcher to recognize a dequantize whose value
input is a broadcast (a linalg.broadcast or a broadcasting, possibly
permuting, generic). In one step, the rewrite builds a dequantize of the
broadcast's source at the source's rank and composes the broadcast map,
through the dequantize's value maps, into the contraction operand map,
using the same named-or-generic decision as the direct fold. No broadcast
is ever placed between the dequantize and the contraction, so both forms
reach the same canonical form before QDQ conversion.

The rewrite fires only when:
- the dequantize result has the contraction as its only user, so the
  dequantize shrinks instead of being duplicated; the broadcast may have
  other users, which keep it;
- no scale or zero-point map depends on a dimension the broadcast
  introduces, since such parameters vary across the broadcast.
Scale and zero-point maps are rebased onto the source's dims; operands
and attributes (signedness, clamp bounds, zero-point presence) are
carried over verbatim. Dynamic dims are taken from the source.

Tests: pass-level cases for per-channel, asymmetric, per-tensor unsigned,
transposed input and output maps, dynamic batch, M and weight dims, LHS,
generic broadcasts, a multi-use broadcast, and the non-firing multi-use
dequantize and batch-varying scale and zero point. New stage-boundary
tests run Form A, Form B, asymmetric Form B, transposed weights in both
forms and a dynamic batch through the global optimization pipeline with
QDQ conversion off and on.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Florian Walbroel <[email protected]>
FoldBroadcastIntoBatchMatmul only matched the named linalg.batch_matmul.
When contractions are generalized earlier in the pipeline
(--iree-opt-generalize-matmul, on from -O2), the contraction is already
a linalg.generic by the time the fold runs, so neither a broadcast nor a
dequantize of a broadcast was folded: the QDQ rewrite then did not see a
dequantize as direct producer and left a float contraction, or the
integer contraction read a materialized batch-sized broadcast.

Add a second pattern for generics that pass the contraction interface.
It reuses the producer matching of the named path, composes the
broadcast into the operand map and leaves the op a generic. The fold is
skipped unless the operand still reads a reduction loop, the new maps
still describe a contraction and every loop is still bound by an
operand. The named batch_matmul path is unchanged.

The stage test gains a run with generalize-matmul=true against the same
integer-path expectations, so broadcast-after-dequantize and
broadcast-before-dequantize weights reach the same form whether or not
the contraction is still named when the fold sees it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Florian Walbroel <[email protected]>
@Manewing
Manewing force-pushed the walbroel/fold-broadcast-through-dequantize branch from aec3630 to 882ce42 Compare November 12, 2026 16:42

@egebeysel egebeysel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Manewing
Manewing merged commit 880996f into main Nov 13, 2026
60 checks passed
@Manewing
Manewing deleted the walbroel/fold-broadcast-through-dequantize branch November 13, 2026 08:49
@devtbi devtbi mentioned this pull request Nov 16, 2026
8 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants