Skip to content

Make Inductor WOQ quantization fusions extensible to third-party backends - #197775

Open
guohaifei-cmyk wants to merge 14 commits into
pytorch:mainfrom
guohaifei-cmyk:decouple-woq-quant-fusion
Open

guohaifei-cmyk wants to merge 14 commits into
pytorch:mainfrom
guohaifei-cmyk:decouple-woq-quant-fusion

Conversation

@guohaifei-cmyk

@guohaifei-cmyk guohaifei-cmyk commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

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 implement aten._weight_int8pack_mm
(e.g. via PrivateUse1) cannot enable the fusion.

Changes

  • Replace the hardcoded device list with a module-level allowlist plus
    register_woq_int8pack_fusion_device(device_type) /
    unregister_woq_int8pack_fusion_device(device_type), so third-party
    backends can opt in from their initialization code. The allowlist is
    hashed into the FX-graph cache key (FxGraphHashDetails), so compiles
    observe 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_fx entry points; the AOTAutograd-cache lazy-backward save,
    a window shared with every process-global compile input).
  • register/unregister are serialized against in-flight compilations:
    they acquire torch._dynamo.convert_frame.compile_lock, which the
    standard torch.compile path holds from cache-key hashing through
    pattern matching (dynamo around backend invocation) and which
    compile_fx_backward acquires explicitly, so a registration racing
    such 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_fx without
    dynamo (torch._inductor.compile, standalone_compile,
    compile_to_python) do not hold the lock, and with the AOTAutograd
    cache the lazily-lowered backward 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
    register docstring documents both, plus the import-lock deadlock
    hazard of registering from a package __init__.
  • The allowlist is also propagated to serialized (subprocess) compiles:
    _WireProtocolInput (torch/_inductor/compile_fx_ext.py) carries a
    sorted snapshot captured in the parent — the same wire precedent as
    backend_configs — and _run_in_child applies it before the pattern
    passes 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).
  • The concat-linear int8 fusion
    (_is_valid_concat_linear_int8_woq_optimization_pattern) keeps its
    hardcoded cpu/cuda list and deliberately has no registration hook: the
    cat([w1, w2, w3]) subgraph it matches is only produced by the freezing
    pass's int8_woq_fusion_replacement (freezing_patterns.py), whose
    check_int8_woq_concat_linear_weights extra_check rejects non-CPU inputs
    and additionally requires config.cpp.enable_concat_linear, so a
    registered third-party device type could never reach the check. Lifting
    that would require extending the freezing pass first (future work).
  • The concat-linear woq int4 pass is intentionally unchanged: it lowers to
    the CPU-specific aten._weight_int4pack_mm_for_cpu op.

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 int8
    model and asserts counters["inductor"]["woq_matcher_count"] is 1 by
    default, 0 after unregister_woq_int8pack_fusion_device("cpu"), and 1
    again 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 thread
    released exactly at the cache-key-hashing moment (a hook on
    _get_woq_int8pack_fusion_devices) must not complete while the
    compile 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_hit counter, which the matcher-count assertion alone
    could not prove). The test also asserts config.freezing (the setUp
    patch that bypasses the AOTAutograd cache, whose broad except
    around 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 the extension_device dummy backend — which provides PrivateUse1 kernels for aten.mm / aten.mm.out / aten._weight_int8pack_mm via CPU-storage aliasing — under FxCompileMode.SERIALIZE with 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 own aten._weight_int8pack_mm kernel 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. A serialize_compile spy pins that these WOQ compiles bypass serialization today (prims.convert_element_type is rejected by GraphPickler's _ops_filter_safe, so compiles fall back in-process), failing loudly if the ops filter is ever relaxed. register/unregister reject 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): under
    FxCompileMode.SERIALIZE (the same serialize → _run_in_child path a
    subprocess 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

…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]>
@pytorch-bot

pytorch-bot Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

PR Status: ready for maintainer review

A maintainer requested changes. Please address their feedback and ask for another review.

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - 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.

Findings (4):

[minor] torch/_inductor/fx_passes/quantization.py:1193
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).

[minor] torch/_inductor/fx_passes/quantization.py:1172
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.

[minor] test/inductor/test_mkldnn_pattern_matcher.py:2001
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.

[info] torch/_inductor/fx_passes/quantization.py:10
`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.

Reviewed commit: 45455b1 (NOT the current head e933210)

Review run

🔗 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 Failure

As of commit e933210 with merge base 1d2481c (image):

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.

@pytorch-bot

pytorch-bot Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Sep 20, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

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
ezyang requested a review from fffrog September 21, 2026 19:04
@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 21, 2026
@guohaifei-cmyk
guohaifei-cmyk marked this pull request as draft September 22, 2026 09:44
@guohaifei-cmyk
guohaifei-cmyk marked this pull request as ready for review September 24, 2026 02:18

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

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.

@pytorch-bot pytorch-bot Bot added in progress PR is being worked on by the author, until the automated review accepts it and removed ready for review Automated review passed, ready for a final review by a maintainer. labels Oct 27, 2026
github-actions[bot]

This comment was marked as outdated.

@amjames
amjames removed their request for review October 27, 2026 15:47
github-actions[bot]

This comment was marked as outdated.

github-actions[bot]

This comment was marked as outdated.

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]>
github-actions[bot]

This comment was marked as outdated.

- 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]>
Comment on lines +1179 to +1186
_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)

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.

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):

  1. Unregister CPU and begin compilation; Inductor computes the "CPU fusion disabled" cache key.
  2. Another thread registers CPU before code generation. Compilation emits _weight_int8pack_mm and caches it under that earlier key.
  3. 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Two follow-ups from the fresh automated review of d2e2537, both yours to call:

  1. Coverage: direct compile_fx callers (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 mirror compile_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.
  2. Home: the review escalated the public-API location question (the deferred round-5 thread). Where should register/unregister live — next to register_backend_for_device in 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]>
github-actions[bot]

This comment was marked as outdated.

- 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]>

@github-actions github-actions Bot 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.

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

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


def register_woq_int8pack_fusion_device(device_type: str) -> None:

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)


def test_register_waits_for_inflight_compile(self):

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

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.

@github-actions
github-actions Bot dismissed stale reviews from themself October 29, 2026 23:46

Withdrawn: the automated review of 45455b1 found nothing blocking.

@pytorch-bot pytorch-bot Bot added the ready for review Automated review passed, ready for a final review by a maintainer. label Oct 30, 2026
- 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]>
@guohaifei-cmyk

Copy link
Copy Markdown
Contributor Author

Addressed the round-11 automated review's four non-blocking findings:

  1. Lazy-backward / unlocked paths (quantization.py): the register docstring no longer makes the blanket cache-separation promise. It now names exactly 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 at all), and with the AOTAutograd cache the lazily-lowered 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 _patch_woq_int8pack_fusion_devices helper now states its compile_lock assumption as well (the SERIALIZE-mode swap/restore). Closing these gaps in code (a per-compile snapshot threaded into the matcher, or extending the lock to the direct entry points) remains @ezyang's call, as asked on r4413518068 / r4418965404.

  2. Hook location: no unilateral move — still a maintainer decision (asked directly in r4418965404). On the topic: not user facing label: it was added to satisfy the release-notes requirement; if the hooks are settled as a public extension point (codegen/common.py, a config entry, or here documented as public), the label is worth revisiting at that point — happy to do so on the maintainer's word.

  3. test_register_waits_for_inflight_compile:

    • assertTrue(config.freezing) now pins the dependency the review identified: setUp's freezing patch is what keeps the AOTAutograd cache bypassed (check_cacheable hard-bypasses frozen graphs), so the first hook call comes from FxGraphHashDetails in codecache; with the AOT cache active, autograd_cache_key's broad except Exception would swallow the hook's assertFalse and the test would falsely pass.
    • Phase 2 now asserts counters["inductor"]["fxgraph_cache_hit"] == 1, so the claimed cache hit is actually pinned — matcher_check(0) passed either way, and the counter only increments on a real hit, so passing proves phase 2 reuses the phase-1 entry.
    • The 1 s wait is documented as the deliberate detection window for a lock-free implementation.

    The lazy-backward window itself remains untested, as the review notes; it is the upstream-shared window documented in the docstring.

  4. compile_lock import: function-local at the use sites, matching the two existing precedents (compile_fx.py:compile_fx_backward, codegen/common.py). Round 10's finding was that the lazy-import comment was wrong (torch._dynamo.utils already loads convert_frame transitively); that comment is gone. The transitive load is unchanged either way, so this move is idiom consistency, not decoupling.

Verified locally: the full TestWoqFusionDeviceRegistry class passes with the hardened test (including the new phase-2 cache-hit assertion), and the pyfmt pipeline (isort 6.0.1 → usort 1.1.3 → ruff-format 0.14.4) is clean on both files.

@ezyang

ezyang commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

The AI reviewers are looping, I'm taking a look.

@ezyang

ezyang commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

This is probably ok. @EikanWang you should look though

@EikanWang

Copy link
Copy Markdown
Collaborator

The changes look good to me.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-refresh-hf-cache ciflow/b200 ciflow/docker ciflow/h100 ciflow/inductor ciflow/inductor-pallas ciflow/mps Run MPS tests (subset of trunk) ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: amp (automated mixed precision) autocast module: cpu CPU specific problem (e.g., perf, algorithm) module: inductor open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: quantization release notes category release notes: releng release notes category topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants