Repository navigation
Make Inductor WOQ quantization fusions extensible to third-party backends - #197775
guohaifei-cmyk wants to merge 14 commits into
Conversation
…ends The freezing-pass WOQ (weight-only quantization) fusion checks in torch/_inductor/fx_passes/quantization.py gate on hardcoded device whitelists: the concat-linear int8 fusion allows only cpu/cuda while the woq int8pack-mm fusion allows cpu/cuda/xpu. Backends that implement aten._weight_int8pack_mm (e.g. via PrivateUse1) cannot enable these fusions. Replace the hardcoded lists with small registries and expose register_concat_linear_int8_woq_device() / register_woq_int8pack_fusion_device() so third-party backends can opt in. The default sets are unchanged, so cpu/cuda/xpu behavior is identical. The concat-linear woq int4 pass is intentionally left unchanged: it lowers to the CPU-specific aten._weight_int4pack_mm_for_cpu op. Signed-off-by: g00883433 <[email protected]>
PR Status: ready for maintainer reviewA maintainer requested changes. Please address their feedback and ask for another review. ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (4): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197775
Note: Links to docs will display an error until the docs builds have been completed. ❌ 4 New Failures, 1 Cancelled Job, 10 Unrelated Failures, 1 Unclassified FailureAs of commit e933210 with merge base 1d2481c ( NEW FAILURES - The following jobs have failed:
NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following jobs failed, but the AI CI Advisor judged the failures not to be evidence against this change:
UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:
CANCELLED JOB - The following job was cancelled. Please retry:
UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
ezyang
left a comment
There was a problem hiding this comment.
Posted by Astra, an AI assistant, on behalf of @ezyang. @ezyang reviewed this request and asked that it be posted.
Requesting changes for the subprocess propagation issue: the allowlist used by the compiler worker must match the state included in the parent's cache key.
Please follow the existing precedent, already present in PyTorch 2.7.0: _LoweringSerializer captures forced-fallback registrations and reapplies them in the worker; alternatively, Inductor config serialization already carries config state across this boundary. Either explicitly serialize and restore the WOQ registry or put the allowlist in config. Add a subprocess regression covering the generated operator and subsequent cache reuse.
The blocker is the mismatch between the cache key and compilation state; moving the registry into config is not required if explicit serialization fixes that mismatch. This finding is based on source inspection; runtime tests were not run.
Address ezyang's review: the allowlist hashed into FxGraphHashDetails in the parent must also reach the compile worker, otherwise the worker pattern-matches against its own default allowlist while the cache key describes the parent's state. - _WireProtocolInput gains a woq_int8pack_fusion_devices field: the parent captures a sorted snapshot (quantization. _get_woq_int8pack_fusion_devices) next to backend_configs, following the same wire precedent; _run_in_child applies it via quantization._patch_woq_int8pack_fusion_devices before compiling, so the worker's pattern matching and cache-key computation agree with the parent's allowlist state. - test_compile_fx_ext_propagates_woq_allowlist (test_compile_options.py) covers the wire level with a plain-aten graph under FxCompileMode.SERIALIZE: a serialize spy asserts the wire carries the parent's snapshot (cpu unregistered, mtia registered), and a patch spy asserts the child applies exactly that snapshot. - test_woq_int8pack_fusion_propagates_to_worker (test_extension_backend.py) is the end-to-end counterpart under SERIALIZE: fused dispatch, then cache reuse while the allowlist is unchanged, then a miss with the generic path after unregistering. The assertions hold both when the WOQ graph serializes and when it bypasses to in-process (prims.convert_element_type is not picklable yet, so the serialized compile falls back today). - review fixes: a non-str device_type now raises TypeError; both validation tests assert the message via assertRaisesRegex; the e2e test resets the shared op counter through addCleanup so it also runs when an assertion fails. Signed-off-by: g00883433 <[email protected]>
Address the automated review of dd65b69: the SERIALIZE-mode WOQ test claimed the worker applies the allowlist received over the wire, but WOQ graphs cannot cross the serialization boundary yet - every graph the pattern matches contains prims.convert_element_type, which GraphPickler's _ops_filter_safe rejects, so serialize_compile returns None and the compile falls back to in-process. - Rename the test to test_woq_int8pack_fusion_serialize_mode_falls_back_in_process and pin the actual path with a serialize_compile spy: the final assertion requires each SERIALIZE-mode compile to bypass serialization (the middle compile hits the FX graph cache in the parent and never reaches codegen), so the test fails loudly if the ops filter is ever relaxed and should then be rewritten for the worker path. The miss/hit/miss cache sequence is unchanged and still regression-tests that the cache key (computed in the parent) tracks the allowlist state. - FxGraphHashDetails takes its snapshot via the shared quantization._get_woq_int8pack_fusion_devices() helper, so the cache-key snapshot and the wire snapshot cannot drift apart. - Correct comments that claimed the worker computes the cache key: the parent computes it (_compile_fx_inner) and the worker only runs the post-grad pattern passes (docstrings, compile_fx_ext comment, test comments, PR description). Signed-off-by: g00883433 <[email protected]>
- test_woq_int8pack_fusion_on_registered_device now runs under
FxCompileMode.SERIALIZE with the FX graph cache on and asserts the
deterministic counters directly (miss before registration, new-key
miss with the matcher firing after registering, hit while the
allowlist is unchanged, hit of the pre-registration artifact after
unregistering); the serialize_compile spy keeps pinning the
serialization bypass. The separate SERIALIZE-mode test is folded into
it: the two mostly duplicated each other, and every test runs under
fresh_cache(), so the defensive cold/hot-cache comments, the
distinct-shapes note and the FxGraphCache.clear() call defended
against states that cannot happen.
- _validate_woq_device_type errors state the requirement for backend
authors ("expected a bare device type such as 'cuda'; ... register
after rename_privateuse1_backend") instead of naming private
internals.
- Trim comment volume: drop the repeated "parent hashed into
FxGraphHashDetails" explanations, keeping one line at each site.
Signed-off-by: g00883433 <[email protected]>
| _validate_woq_device_type(device_type) | ||
| _woq_int8pack_fusion_devices.add(device_type) | ||
|
|
||
|
|
||
| def unregister_woq_int8pack_fusion_device(device_type: str) -> None: | ||
| """Disable the WOQ int8pack-mm fusion on ``device_type`` (e.g. teardown).""" | ||
| _validate_woq_device_type(device_type) | ||
| _woq_int8pack_fusion_devices.discard(device_type) |
There was a problem hiding this comment.
Posted by Astra, an AI assistant, on behalf of @ezyang. @ezyang reviewed this request and asked that it be posted.
[P2] Concurrent registration can save an artifact under the wrong cache key.
The registration functions mutate the global allowlist without coordinating with compilation. Cache hashing and pattern matching read it at different times; using the same snapshot helper does not make those reads atomic.
I reproduced this interleaving with the PR's Python changes applied to today's CPU nightly (2.16.0.dev20261029):
- Unregister CPU and begin compilation; Inductor computes the "CPU fusion disabled" cache key.
- Another thread registers CPU before code generation. Compilation emits
_weight_int8pack_mmand caches it under that earlier key. - Unregister CPU again and recompile. Inductor reports a cache hit and returns code containing
_weight_int8pack_mm.
This defeats the allowlist's cache-separation guarantee. Coordinate register/unregister with the existing compiler lock and add a regression for this interleaving. A lock around set mutation alone would not cover the interval between hashing and matching.
There was a problem hiding this comment.
Fixed in d2e2537: register/unregister_woq_int8pack_fusion_device now acquire torch._dynamo.convert_frame.compile_lock — the lock you pointed at, which compilation already holds across the interval in question: dynamo acquires it around backend invocation (CatchErrorsWrapper.__call__), which covers every torch.compile-driven compile from FX-graph cache-key hashing through the post-grad pattern passes and the artifact save, and compile_fx_backward acquires the same lock explicitly for the runtime-invoked backward. A registration racing an in-flight compile now blocks until the compile finishes, so the key, the matcher and the wire snapshot (serialize_compile captures it inside the same critical section) all observe one consistent allowlist state per compile.
Regression test: test_mkldnn_pattern_matcher.py::TestWoqFusionDeviceRegistry::test_register_waits_for_inflight_compile pins your interleaving deterministically. It unregisters cpu and compiles a WOQ graph with the FX graph cache on; a hook at the key-hashing moment (FxGraphHashDetails calls _get_woq_int8pack_fusion_devices, mocked with a pass-through side effect) releases a second thread that calls register("cpu"). The hook asserts, while the compile is still in flight, that the registration has not completed; after the compile finishes, the registration completes, the test re-unregisters, and a second compile under the original registry state hits the phase-1 cache entry and returns the non-fused artifact that key promised. I verified locally that the test fails on the pre-fix code with exactly your scenario (the registration lands mid-compile) and passes with the lock.
One residual worth naming: compiles invoked directly through compile_fx without dynamo (e.g. AOTInductor paths) don't hold the lock today; mutating other global compile inputs such as config against those callers has the same pre-existing hole. I can add explicit acquisition in the forward path (compile_fx_forward, mirroring compile_fx_backward) if you want that closed as well.
There was a problem hiding this comment.
Two follow-ups from the fresh automated review of d2e2537, both yours to call:
- Coverage: direct
compile_fxcallers (torch._inductor.compile,standalone_compile,compile_to_python) don't take compile_lock, so a registration can still tear those compiles (the residual from my previous reply). Say the word and I'll mirrorcompile_fx_backward's explicit acquisition in the forward path. The automated review also named the lazy-backward compile-and-save pair in_functorch— that window exists for every global compile input (config included), so if you want it closed it belongs upstream. - Home: the review escalated the public-API location question (the deferred round-5 thread). Where should
register/unregisterlive — next toregister_backend_for_devicein codegen/common.py, or here with a documented import path? Out-of-tree backends need a stable path before this lands.
Both are addressed in 45455b1 documentation-wise in the meantime: the docstring states exactly which paths hold the lock, and documents the import-lock deadlock hazard of registering from a package __init__.
register/unregister_woq_int8pack_fusion_device acquire torch._dynamo.convert_frame.compile_lock, the lock compilation already holds from FX-graph cache-key hashing through pattern matching (dynamo acquires it around backend invocation; compile_fx_backward acquires it explicitly). A registration racing an in-flight compile now waits for the compile to finish instead of mutating the allowlist between the key and the matcher, which could save the fused artifact under the pre-mutation key and later resurrect the fusion on a cache hit under the original registry state. test_register_waits_for_inflight_compile pins the interleaving: a registration thread released at the key-hashing moment (a hook on _get_woq_int8pack_fusion_devices) must not complete while the compile is in flight; a second compile under the original registry state then reuses the phase-1 cache entry. Verified locally that the test fails on the pre-fix code with the race and passes with the lock. Signed-off-by: g00883433 <[email protected]>
- compile_lock is imported at module top: the lazy import claimed torch._dynamo was kept off this module's import path, but the module already imports torch._dynamo.utils, which loads convert_frame via torch/_dynamo/__init__.py, so the comment was wrong and the local imports bought nothing. - The register docstring states exactly which compile paths hold compile_lock (dynamo around backend invocation on the torch.compile path; compile_fx_backward explicitly) and that compiles invoked directly through compile_fx without dynamo do not take it, instead of the over-broad "compilation already holds that lock" claim. It also documents the import-lock deadlock hazard of registering from a package __init__. Signed-off-by: g00883433 <[email protected]>
There was a problem hiding this comment.
Automated review of 45455b1: nothing blocking; ready for human review.
The PR replaces the hardcoded cpu/cuda/xpu check in the WOQ int8pack-mm fusion with an allowlist that third-party backends can change through register/unregister hooks. The allowlist is hashed into the cache key, sent to compile workers, and changed only while holding compile_lock. Recommendation: Needs Discussion, because the lazy-backward path can still save under a stale key, ezyang hasn't ruled on which unlocked paths are acceptable, and the public hooks have no agreed home.
⚪ 4 non-blocking findings
pytorch/torch/_inductor/fx_passes/quantization.py
Line 1193 in 45455b1
Lazy backward saves the cache entry outside the lock, under the key computed at forward time. compile_fx_backward holds compile_lock only inside bw_compiler (compile_fx.py:3002-3004). try_save_cache_entry runs at runtime_wrappers.py:2951 after the lock is released, under the AOTAutograd key, which includes the allowlist. enable_autograd_cache defaults to True, so with default settings: the forward compiles under S0; register runs, making S1; the first .backward() compiles fused under S1; the entry is saved under the S0 key; a later S0 process hits it and gets the fused backward. The docstring's promise of cache separation is false here. Other unlocked paths: torch._inductor.compile and standalone_compile. In SERIALIZE mode, _patch_woq_int8pack_fusion_devices clear()s and refills the live set, which can expose an empty set to readers, and its finally block undoes a concurrent register. Fix: have the matcher read a per-compile snapshot taken with the cache key, or document every unlocked path and drop the guarantee from both docstrings. ezyang should approve which gaps are acceptable (asked on r4413518068, no answer yet).
pytorch/torch/_inductor/fx_passes/quantization.py
Line 1172 in 45455b1
Un-underscored, backend-facing hooks in a private pattern module. register_/unregister_woq_int8pack_fusion_device are meant to be called from out-of-tree backend init, but they live in torch._inductor.fx_passes.quantization, with no all, no docs and no stable import path. Once backends import them from there, any refactor of this file is a BC break. The author has deferred the location to maintainers (r4374327457, r4418965208) without a decision. Settle this before merge. Options: put them next to register_backend_for_device in codegen/common.py (where _inductor_backend_init() could call them); use an Inductor config list, which gets cache-key inclusion and subprocess propagation for free but is ContextVar-based, which changes the process-wide semantics; or keep them here, explicitly documented as public. The PR is also labelled "topic: not user facing" even though it adds an extension point.
An earlier comment near this line has replies: #197775 (comment)
test_register_waits_for_inflight_compile depends on unstated setup and doesn't check what its comments claim. The hook fires first in FxGraphHashDetails only because TestPatternMatcherBase.setUp enables freezing=True, which bypasses the AOTAutograd cache. If that cache were active, AOTAutogradCacheDetails would call the hook first, inside the except Exception at autograd_cache.py:1078/:1244, swallowing the assertFalse, so the test would falsely pass. Add a comment stating the dependency on freezing. Phase 2 claims a cache hit but only asserts matcher_check(0), which passes either way; assert counters["inductor"]["fxgraph_cache_hit"] == 1. The test also sleeps a deliberate 1 s on every run, and the check is probabilistic. Nothing covers the lazy-backward window.
from torch._dynamo.convert_frame import compile_lock is a module-level import. The existing idiom in torch/_inductor is a function-local import at the use site (compile_fx.py:3002, codegen/common.py:760). Follow it, so this pattern module doesn't pull Dynamo's frame-conversion machinery into its import graph.
This review is AI-generated and advisory. Each new automated review replaces the previous one.
Withdrawn: the automated review of 45455b1 found nothing blocking.
- register/unregister import compile_lock at the use sites (function-local, matching compile_fx.py and codegen/common.py) instead of at module top; the lazy-import comment the round-10 review flagged is gone with it. - The register docstring drops the blanket cache-separation promise: it now names the paths where a registration can still land between a key and the compile filed under it - the direct compile_fx entry points (torch._inductor.compile, standalone_compile, compile_to_python, no lock) and the AOTAutograd-cache lazy backward, whose entry is saved after compile_fx_backward releases the lock under the forward-time key (a window every process-global compile input, config included, already shares). The SERIALIZE-mode patch helper states its compile_lock assumption too. - test_register_waits_for_inflight_compile pins its freezing=True dependency (the AOTAutograd cache would swallow the hook's assertion through autograd_cache_key's broad except) and asserts the phase-2 fxgraph_cache_hit counter, so the cache hit it claims is actually verified. Signed-off-by: g00883433 <[email protected]>
|
Addressed the round-11 automated review's four non-blocking findings:
Verified locally: the full |
|
The AI reviewers are looping, I'm taking a look. |
|
This is probably ok. @EikanWang you should look though |
|
The changes look good to me. |
Motivation
The freezing-pass WOQ (weight-only quantization) int8pack-mm fusion check in
torch/_inductor/fx_passes/quantization.py(
_is_valid_woq_optimization_pattern) gates on a hardcoded device allowlist(
cpu/cuda/xpu). Backends that implementaten._weight_int8pack_mm(e.g. via PrivateUse1) cannot enable the fusion.
Changes
register_woq_int8pack_fusion_device(device_type)/unregister_woq_int8pack_fusion_device(device_type), so third-partybackends can opt in from their initialization code. The allowlist is
hashed into the FX-graph cache key (
FxGraphHashDetails), so compilesobserve the allowlist state they were compiled under and changing it
produces new cache entries instead of reusing stale ones, except on
the unlocked paths documented in the register docstring (direct
compile_fxentry points; the AOTAutograd-cache lazy-backward save,a window shared with every process-global compile input).
register/unregisterare serialized against in-flight compilations:they acquire
torch._dynamo.convert_frame.compile_lock, which thestandard torch.compile path holds from cache-key hashing through
pattern matching (dynamo around backend invocation) and which
compile_fx_backwardacquires explicitly, so a registration racingsuch a compile waits for it to finish instead of mutating the
allowlist between the key and the matcher (which could save the fused
artifact under the pre-mutation key and later resurrect the fusion on
a cache hit). Compiles invoked directly through
compile_fxwithoutdynamo (
torch._inductor.compile,standalone_compile,compile_to_python) do not hold the lock, and with the AOTAutogradcache the lazily-lowered backward is saved after
compile_fx_backwardreleases the lock, under the forward-time key - a window every
process-global compile input (
configincluded) already shares; theregister docstring documents both, plus the import-lock deadlock
hazard of registering from a package
__init__._WireProtocolInput(torch/_inductor/compile_fx_ext.py) carries asorted snapshot captured in the parent — the same wire precedent as
backend_configs— and_run_in_childapplies it before the patternpasses run, so the compile worker's pattern matching always matches the
allowlist state the parent hashed into the FX-graph cache key (the
parent computes the key; the worker only runs the post-grad pattern
passes).
(
_is_valid_concat_linear_int8_woq_optimization_pattern) keeps itshardcoded
cpu/cudalist and deliberately has no registration hook: thecat([w1, w2, w3])subgraph it matches is only produced by the freezingpass's
int8_woq_fusion_replacement(freezing_patterns.py), whosecheck_int8_woq_concat_linear_weightsextra_check rejects non-CPU inputsand additionally requires
config.cpp.enable_concat_linear, so aregistered third-party device type could never reach the check. Lifting
that would require extending the freezing pass first (future work).
the CPU-specific
aten._weight_int4pack_mm_for_cpuop.Behavior equivalence
The default allowlist contents are exactly the previous hardcoded list, so
cpu/cuda/xpu behavior is identical.
Testing
Compile-level test (
test/inductor/test_mkldnn_pattern_matcher.py,test_int8pack_fusion_gated_by_device_registry): compiles a WOQ int8model and asserts
counters["inductor"]["woq_matcher_count"]is 1 bydefault, 0 after
unregister_woq_int8pack_fusion_device("cpu"), and 1again after re-registering. The FX graph cache is disabled for the
recompiles because the re-registered compile has the same cache key as
the first one, and a cache hit would skip re-running the pattern passes.
Concurrency regression (
test/inductor/test_mkldnn_pattern_matcher.py,test_register_waits_for_inflight_compile): a registration threadreleased exactly at the cache-key-hashing moment (a hook on
_get_woq_int8pack_fusion_devices) must not complete while thecompile is in flight; after it finishes, a second compile under the
original registry state hits the phase-1 cache entry and gets the
non-fused artifact the key promised (pinned by the
fxgraph_cache_hitcounter, which the matcher-count assertion alonecould not prove). The test also asserts
config.freezing(the setUppatch that bypasses the AOTAutograd cache, whose broad
exceptaround cache-key construction would otherwise swallow the mid-compile
assertion). It fails on the pre-fix code (the registration lands
mid-compile) and passes with the lock.
End-to-end test on a renamed PrivateUse1 device (
test/inductor/test_extension_backend.py,test_woq_int8pack_fusion_on_registered_device): compiles a WOQ int8 model on theextension_devicedummy backend — which provides PrivateUse1 kernels foraten.mm/aten.mm.out/aten._weight_int8pack_mmvia CPU-storage aliasing — underFxCompileMode.SERIALIZEwith the FX graph cache enabled. Before registration the generic path is used (cache miss); registering turns the fusion on with a new cache key (the device's ownaten._weight_int8pack_mmkernel dispatches, via a dedicated counter in the extension module); recompiling reuses the fused artifact (cache hit); unregistering returns to the pre-registration key and reuses its generic artifact. Aserialize_compilespy pins that these WOQ compiles bypass serialization today (prims.convert_element_typeis rejected by GraphPickler's_ops_filter_safe, so compiles fall back in-process), failing loudly if the ops filter is ever relaxed.register/unregisterreject arguments that could never match the device-type check (e.g."extension_device:0").Wire-level propagation test (
test/inductor/test_compile_options.py,test_compile_fx_ext_propagates_woq_allowlist): underFxCompileMode.SERIALIZE(the same serialize →_run_in_childpath asubprocess worker takes), a serialize spy asserts the wire carries the
parent's allowlist snapshot (cpu unregistered, mtia registered) and a
patch spy asserts the child applies exactly that snapshot.
cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01 @mcarilli @ptrblck @leslie-fang-intel @voznesenskym @penguinwu @EikanWang @Guobing-Chen @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo