Repository navigation
Conversation
Manewing
requested review from
AGindinson,
egebeysel,
phemashekar and
ziereis
as code owners
October 21, 2026 08:48
Manewing
force-pushed
the
manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math
branch
from
October 21, 2026 09:57
387b34f to
aeb73de
Compare
…volutions in quantized conv models will result in integer math Signed-off-by: Florian Walbroel <[email protected]>
Manewing
force-pushed
the
manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math
branch
from
October 21, 2026 11:54
aeb73de to
c2a9931
Compare
ziereis
reviewed
Oct 23, 2026
ziereis
reviewed
Oct 23, 2026
ziereis
reviewed
Oct 23, 2026
ziereis
reviewed
Oct 23, 2026
ziereis
previously requested changes
Oct 23, 2026
ziereis
left a comment
Contributor
There was a problem hiding this comment.
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]>
…optimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math Signed-off-by: Florian Walbroel <[email protected]>
Manewing
force-pushed
the
manewing/25034-globaloptimization-pass-ordering-keeps-im2col-convolutions-in-quantized-conv-models-from-lowering-to-integer-math
branch
from
November 10, 2026 12:17
40b8a13 to
bd439fb
Compare
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]>
Manewing
enabled stacked auto-merge (squash)
November 12, 2026 11:44
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]>
8 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
expand_shapebetween 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.ConvertConvToIm2Colrewrites 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.(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).ConvertConvToIm2Colnow 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.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.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
mainat 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.With data tiling these cases take 0.23x to 0.59x of the time on
main, because they now run asi8 x i8 -> i32matmuls. 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:
Assisted by Codex
🤖 Generated with Claude Code