Skip to content

[GlobalOptimization] change pass ordering so img2col convolutions in quantized conv models will result in integer math - #25099

Merged
Manewing merged 7 commits into
mainfrom
manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math
Nov 12, 2026
Merged

Manewing merged 7 commits into
mainfrom
manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math

Conversation

@Manewing

@Manewing Manewing commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Addresses #25034

Move im2col after the late QDQ conversion and remove the redundant early QDQ pass, so biased QDQ convolutions convert to integer matmuls after bias detachment and transpose normalization. Move input demotion afterward and extend it to generic contractions, preserving f32 accumulation.

Four changes make the single conversion hold up:

  • Unit-dim folding shrinks a 1x1 dequantize to rank 0 and leaves an expand_shape between it and the matmul. Reshape fusion by expansion now handles an empty reassociation for ops without loops, for every op it supports and in both directions. Only operands that must span every loop (inits, and the value operand of quantize/dequantize) gain the new unit dims; scalar parameters stay broadcasts.
  • A quantized convolution with a weight zero point needs the sum of every input window. With QDQ conversion before im2col, that sum re-gathered every window in its own dispatch and cost about as much as the im2col itself. The window sum now reads like a ones-filter convolution, and ConvertConvToIm2Col rewrites a convolution without output-channel reuse when its gather is identical to that of another rewritten convolution. CSE merges the gathers and the sum becomes a row reduction over the shared im2col result. Unshared pooling and depthwise convolutions, dynamic gather shapes and plain matmul sums are unaffected.
  • With im2col after generalization and unit-dim folding, a strided convolution with a unit window is left with an input access such as (c, oh * 2, ow * 2), which no longer passes the convolution interface check. im2col skipped it, and the strided access kept the op from being data-tiled (the regression reported in review for strided 1x1 shortcut convolutions). ConvertConvToIm2Col now matches on the indexing maps: an input, a filter and an output, with filter and output maps that are projected permutations and an input map that is not one but is a sum of loops scaled by positive constants. Plain contractions, named matmuls and elementwise ops are left alone; the output-channel reuse and shared-gather rules are unchanged.
  • Unit-dim folding skips named contractions, so the generic that the QDQ conversion creates from an M = 1 matmul kept its unit loop when contractions are not generalized. Unit-dim folding now runs on the function again after the QDQ conversion.

The demotion pass classifies by the contraction and convolution interfaces and does one rewrite. The multiply-accumulate body check stays because the convolution interface only inspects indexing maps; without it a mul+max pooling-like generic would be demoted.

Pipeline regression tests require integer im2col and i8×i8→i32 contractions for biased NHWC/NCHW convolutions, that the window sum reads the shared gather, and cover generic demotion.

Performance on Apple M4 with llvm-cpu, data tiling and all ukernels, --task_topology_performance_level=performance, median of medians. NCHW, C_in 16, 28x28 input, C_out 32, activation scale 0.125 and zero point −1, per-channel weight scale 0.0625 and zero point 2. "Float" is this branch with --iree-global-opt-enable-qdq-to-integer-math=false.

Case 1 worker integer 1 worker float 4 workers integer 4 workers float
3x3 symmetric 0.103 ms 0.117 ms 0.057 ms 0.062 ms
3x3 activation zero point only 0.095 ms 0.118 ms 0.052 ms 0.063 ms
3x3 weight zero point only 0.063 ms 0.119 ms 0.042 ms 0.070 ms
3x3 both zero points 0.065 ms 0.116 ms 0.041 ms 0.063 ms
5x5 both zero points 0.125 ms 0.241 ms 0.060 ms 0.098 ms
7x7 both zero points 0.197 ms 0.369 ms 0.081 ms 0.194 ms
matmul 676x144x32, both zero points 0.056 ms 0.149 ms 0.045 ms 0.074 ms

The gather merges for NCHW and NHWC with stride 2, dilation 2 and batch 2. The integer output is bit-identical to the float path on the tested inputs; the scales are powers of two, so this does not exercise rounding.

Comparison against main

main at b4f03e3 against this branch, same machine and runtime flags as above, default task topology restricted to the 4 performance cores, median of 5 repetitions. All cases use --iree-global-opt-use-im2col-for-convs; "DT" adds --iree-opt-data-tiling, "DT + UK" also adds --iree-llvmcpu-enable-ukernels=all. Shortcut cases are 1x1 QDQ convolutions with bias and relu, written as channels in → out, input height, stride.

QDQ case No DT: main → PR DT: main → PR DT + UK: main → PR
shortcut 256 → 512, 56x56, stride 1 14.9 → 14.9 ms 2.35 → 0.79 ms 2.38 → 0.79 ms
shortcut 512 → 1024, 28x28, stride 1 15.9 → 15.9 ms 2.15 → 0.66 ms 2.15 → 0.66 ms
shortcut 1024 → 2048, 14x14, stride 1 14.2 → 14.8 ms 2.11 → 0.55 ms 2.13 → 0.55 ms
shortcut 256 → 512, 56x56, stride 2 3.99 → 4.26 ms 0.67 → 0.22 ms 0.68 → 0.22 ms
shortcut 512 → 1024, 28x28, stride 2 5.70 → 6.01 ms 0.71 → 0.20 ms 0.71 → 0.20 ms
shortcut 1024 → 2048, 14x14, stride 2 4.01 → 4.35 ms 0.70 → 0.16 ms 0.71 → 0.16 ms
NHWC 1x1, 512 → 1024, 28x28, stride 2 0.71 → 1.23 ms 0.70 → 0.19 ms 0.70 → 0.19 ms
NCHW 3x3, 64 → 64, 56x56, stride 1, pad 1 5.20 → 5.56 ms 0.92 → 0.52 ms 0.92 → 0.54 ms

With data tiling these cases take 0.23x to 0.59x of the time on main, because they now run as i8 x i8 -> i32 matmuls. Without data tiling the integer matmul is not faster than the float one: most cases are within 8%, and the NHWC 1x1 stride 2 case is 1.7x slower.

The run covered 237 case and configuration pairs (quantized and float convolutions, shortcuts, linear layers, each with and without im2col, data tiling and ukernels). 192 compile to byte-identical modules on both sides. The other 45 are the 8 QDQ cases above and 7 float convolutions with bias, in the three im2col configurations; the float ones are within noise of main. No case loses data tiling. The full ResNet-50 from the review has not been re-measured.

Compiled with:

build/tools/iree-compile input.mlir \
  --iree-hal-target-backends=llvm-cpu \
  --iree-llvmcpu-target-cpu=host \
  --iree-global-opt-use-im2col-for-convs \
  --iree-opt-data-tiling \
  --iree-llvmcpu-enable-ukernels=all \
  -o model.vmfb

Assisted by Codex

🤖 Generated with Claude Code

@Manewing
Manewing force-pushed the manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math branch from 387b34f to aeb73de Compare October 21, 2026 09:57
…volutions in quantized conv models will result in integer math

Signed-off-by: Florian Walbroel <[email protected]>
@Manewing
Manewing force-pushed the manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math branch from aeb73de to c2a9931 Compare October 21, 2026 11:54

@ziereis ziereis 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.

Thanks for working on this, the general pipeline order look much better now, however i think some of the fixes in this PR are more treating the symptom instead of the cause and could be cleaned up to put the fix at the right place.

Also could you create an issue with a reproducer so investigating the performance regression for the asymmetric case doesn't get lost?

A side note, i think for benchmarking on heterogenous core architecture we should only benchmark on the performance cores (--task_topology_performance_level=performance)

…optimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math

Signed-off-by: Florian Walbroel <[email protected]>
Replace the dequantize-only rank-zero special case in
FoldWithConsumerReshapeByExpansion with support in ExpansionInfo, which
all ops handled by the reshape-by-expansion patterns share.

A reshape of a rank-0 operand has an empty reassociation and only adds
unit dimensions, so it refines none of the op's loops. An op with loops
still rejects it, as upstream linalg does. An op without loops instead
gains the unit dimensions as its whole iteration space; the operands the
op requires to be indexed by every loop (DPS inits and, for
quantize/dequantize, the quantized value) gain them too, and other rank-0
operands broadcast over them. This covers producer collapse_shapes as
well as consumer expand_shapes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Signed-off-by: Florian Walbroel <[email protected]>
Classify the op as matmul-like or convolution-like first and then apply
a single rewrite, instead of dispatching through a per-op template
chain. Generic ops are classified by the upstream contraction and
convolution interface matchers; named ops keep the same list as before.

Drop hasFloatMultiplyAccumulateBody. The convolution interface matcher
checks only indexing maps and iterator types, which pooling-like
reductions share, so generic convolutions still need the upstream
linalg::detail::isContractionBody mul/add check. The extra operand-count
and three-operation guards are dropped: isContractionBody already
requires two inputs and one init, and since the rewrite preserves the
payload, intervening unary ops are as safe as they already were for
generic matmuls. conv_with_unary_op is now demoted accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Signed-off-by: Florian Walbroel <[email protected]>
A quantized convolution with a weight zero point needs the sum of every
input window, which ConvertQDQToIntegerMath emits as a conv-shaped
reduction over the original input. With the QDQ rewrite now running
before im2col, that reduction gathered every window a second time in
its own dispatch, which cost about as much as the im2col itself and
made asymmetric convolutions slower than the float path.

Give the window sum's shape-only operand the partner operand's map
restricted to the sum's loops, so the sum reads like a convolution with
a ones filter and convolution dimension inference recognizes it. Then
let ConvertConvToIm2Col rewrite a convolution without output channel
reuse when its gather is identical to the gather of another rewritten
convolution: the pass collects those gather keys (input value, read
map, static sizes) before applying patterns, and CSE merges the two
gathers. The window sum becomes a row reduction over the shared
im2col result. Unshared pooling and depthwise convolutions, dynamic
gather shapes, and plain matmul sums are unchanged.

Apple M4, llvm-cpu, data tiling and ukernels, one worker, asymmetric
NCHW 3x3 with C_in 16, 28x28, C_out 32: 0.138 ms before, 0.065 ms
after, against 0.116 ms for the float path. 5x5 and 7x7 improve
similarly; symmetric and matmul cases are unchanged. The gather merges
for NCHW and NHWC with stride 2, dilation 2 and batch 2, and the
output is bit-identical to the float path on the tested inputs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

Signed-off-by: Florian Walbroel <[email protected]>
@Manewing
Manewing added this pull request to stack #25198 November 4, 2026 15:03
@egebeysel egebeysel changed the title fix(compiler/GlobalOptimization): change pass ordering so img2col convolutions in quantized conv models will result in integer math [GlobalOptimization] change pass ordering so img2col convolutions in quantized conv models will result in integer math Nov 6, 2026
@egebeysel egebeysel self-assigned this Nov 6, 2026
…optimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math

Signed-off-by: Florian Walbroel <[email protected]>
@Manewing
Manewing force-pushed the manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math branch from 40b8a13 to bd439fb Compare November 10, 2026 12:17
@egebeysel

Copy link
Copy Markdown
Contributor

Thanks! LGTM % a regression my agent uncovered.

Could you maybe take a look at this my agent found a regression on the models I ran end-to-end with this.

With im2col now running after the QDQ rewrite, convolutions reach it
generalized and with their unit filter loops folded. A strided
convolution with a unit window is then left with an input access such
as (c, oh * 2, ow * 2), which no longer passes the convolution
interface check, so im2col skipped it. The strided access that remained
kept those ops from being data-tiled: strided 1x1 shortcut convolutions
in quantized ResNet-style models became much slower than before the
reordering.

Match on the indexing maps instead. ConvertConvToIm2Col now rewrites an
op with an input, a filter and an output whose filter and output maps
are projected permutations and whose input map is not one but is a sum
of loops scaled by positive constants. Plain contractions, named
matmuls and elementwise ops are left alone, and the existing output
channel reuse and shared gather rules are unchanged.

Also run unit dim folding on the function after the QDQ rewrite. The
rewrite replaces named contractions, which unit dim folding skips, with
generics, so an M = 1 quantized matmul kept its unit loop when
contractions are not generalized and picked a slower vectorization
without data tiling.

Apple M4, llvm-cpu, default optimization level, data tiling, ukernels
and im2col, QDQ 1x1 stride 2 shortcut 1024 to 2048 at 14x14: 0.58 ms
before the reordering, 36.2 ms with it, 0.23 ms with this change.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Florian Walbroel <[email protected]>

@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.

Thanks, LGTM!

@Manewing
Manewing enabled stacked auto-merge (squash) November 12, 2026 11:44
@Manewing
Manewing removed the request for review from ziereis November 12, 2026 16:38
@Manewing
Manewing dismissed ziereis’s stale review November 12, 2026 16:39

Not part of org anymore

@Manewing
Manewing merged commit 3a74322 into main Nov 12, 2026
59 checks passed
@Manewing
Manewing deleted the manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math branch November 12, 2026 16:42
Manewing added a commit that referenced this pull request Nov 13, 2026
#25197)

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
#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](https://claude.com/claude-code)

---------

Signed-off-by: Florian Walbroel <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
@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.

3 participants