Skip to content

[CooR] Keep joint-graph constant folding and pattern replacement working, and rank-agnostic - #201491

Closed
aorenste wants to merge 6 commits into
gh/aorenste/432/basefrom
gh/aorenste/432/head
Closed

aorenste wants to merge 6 commits into
gh/aorenste/432/basefrom
gh/aorenste/432/head

Conversation

@aorenste

@aorenste aorenste commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Under compile_on_one_rank, the joint graph carries device operands as
coor.current_device() nodes until post_grad's respecialize_current_device_nodes.
Several joint-graph passes didn't understand that node, so register_replacement
patterns that depend on them (e.g. the masked SDPA fusions) silently stopped
firing: _sfdp_pattern_15 fused with CooR off and not with it on.

There were three blockers, plus one latent bug that became reachable once they
were fixed:

  1. UniformValueConstantFolder treated current_device() as unknown, so every
    constructor fed by it (here the masked_fill fill value, a scalar_tensor) was
    left unfolded. The sfdp patterns expect the folded aten.full, so the coarse
    match failed. The folder now evaluates current_device(). This also fixes the
    full() case, which passed the raw node.kwargs (a Node as device) instead of
    the evaluated kwargs.

  2. constant_fold_uniform_value reinserted folded tensors as full(device=
    fake_tensor.device), which bakes the compiling rank's device into the
    graph that the FX graph cache key hashes. It now takes the device from a new
    rank_agnostic_device(graph, device) helper in fx_utils.py, which turns the
    current accelerator into a current_device() node at the top of the graph,
    reused by later calls on the same graph. The
    node carries meta["val"] like the ones make_fx creates: the partitioner only
    exempts a device node from the recompute ban when it has one, so without it
    a folded constant feeding the backward is saved instead of recomputed.

  3. register_replacement's exact recheck re-traces the search function with
    CooR off, so its pattern holds the concrete device (cuda:0) where the graph
    holds a current_device() node, and the constant comparison rejected it. The
    matcher now accepts a current_device() node against a pattern device equal
    to this rank's current device. Re-tracing the recheck with CooR on instead
    was rejected: the traced device node would carry a _users count that the
    graph's shared device node never satisfies.

  4. With matching working, replacements were still traced with CooR off, so a
    replacement that creates a tensor on the device (the sfdp replacement builds
    an additive -inf mask) baked cuda:0 into the pre-post_grad graph. Both
    register_replacement and replace_by_example now swap every device in the
    traced replacement through rank_agnostic_device, as (2) does, so this rank's
    current accelerator becomes the current_device() node a CooR trace would have
    emitted. Under CooR the inputs are on the current accelerator by invariant, so
    such a device can only have come from there. The replacement graph carries its
    own node, which Replacer copies to each match site, so each fired replacement
    adds one; respecialization handles them all.

    Doing this after tracing, rather than tracing with CooR on, makes it work
    for every trace_fn: joint_fwd_bwd hard-codes CooR off, and a
    functools.partial of fwd_only can't be recognized by identity. So
    replace_by_example no longer traces with CooR live, and fwd_only loses its
    is_replacement flag. An earlier version rejected the match for any trace_fn
    but a bare fwd_only, which kept the graph rank-agnostic but gave up the
    fusion.

rank_agnostic_device only swaps while the graph is still rank-agnostic, which
joint_graph_passes now marks with a rank_agnostic_passes() context. That can't
be read off the graph: one with no device operands (pad_mm's addmm, whose
replacement calls new_zeros) has no current_device() node before
respecialization or after, and a GraphModule.meta flag would be lost on every
GraphModule(root, graph) rebuild, such as prepare_for_partitioner's right before
the joint passes. "CooR is on" isn't enough either, because post_grad pattern
passes run after respecialization, where an inserted current_device() node would
never be concretized. freeze()'s constant folding and replacements also run
outside the window, after joint_graph_passes, and still bake the device; frozen
parameters are per-rank data anyway.

Every pass inside the window that inserts a device now goes through
rank_agnostic_device: constant folding, both replacement paths, fix_iota_device
and the auto-chunker's factory nodes. fix_iota_device also compared device.type,
where device can be a current_device() node whose .type is its (None) type
annotation, so it rewrote even a cuda arange with a concrete device; it now
compares the iota's meta["val"] device.

There is deliberately no assertion at the end of the window that no node holds
this rank's device. It can't tell a device a pass inserted from one already in
the incoming graph: HOP proxy implementations (auto_functionalized, with_effects,
...) build their nodes with create_proxy directly, bypassing make_fx's CooR
rewrite, so an explicit torch.device("cuda", idx) passed to a mutable custom op
reaches the joint graph with its index. An assertion turned those programs into
crashes, where a leak only costs cross-rank cache sharing -- post_grad
respecializes the device before lowering either way. That HOP leak predates this
change and is left for a follow-up; the rank_agnostic_passes docstring records
both, and _use_current_device_node notes that a replacement containing a HOP
still bakes the device inside its subgraph.

Test Plan:

The new test compiles the SDPA rewriter-15 model in inference under CooR on
cuda:0 and cuda:1 and checks numerics, that fuse_attention fires, and that the
graph before post_grad has no index=0 and is identical on both devices.
Reverting any one of the four parts fails it.

Two single-GPU tests cover the rest, and each fails with its fix reverted:
test_constant_folding_feeds_backward_under_coor checks that a folded constant
feeding the backward is recomputed there, and
test_replacement_with_device_rank_agnostic_under_coor checks, for fwd_only,
partial(fwd_only) and joint_fwd_bwd, and with and without a device operand in
the search pattern, that a replacement creating a tensor on the device fires,
leaves no concrete device in the graph's args or kwargs, and feeds from a
current_device() node. Gating on the presence of a current_device() node
fails the no-device-operand cases; gating on CooR alone fails the existing
test_post_grad_replacement_with_device_under_coor; dropping the
replace_by_example swap fails test_rng_replacements_rank_agnostic_before_post_grad.

test_iota_device_fix_rank_agnostic_under_coor indexes with an arange on cpu and
on cuda and checks that the iota ends up on a current_device() node; both fail
with the old fix_iota_device, and the cpu case fails if fix_iota_device doesn't
fire. test_auto_chunker_rank_agnostic_under_coor runs the auto-chunker under
CooR and checks that chunking fires and that no concrete cuda device reaches the
joint graph; it fails with the auto-chunker's old fake_tensor.device.
test_current_device_matches_only_this_ranks_pattern_device checks that a
current_device() node matches a pattern on this rank's device and not on another
index; the other-index case fails if the matcher accepts any device.

python test/distributed/tensor/test_compile_on_one_rank.py -k test_constant_folding_and_sdpa_fusion_under_coor
python test/distributed/tensor/test_compile_on_one_rank.py -k replacement -k constant_folding -k rng
python test/distributed/tensor/test_compile_on_one_rank.py -k iota_device_fix -k current_device_matches_only -k auto_chunker_rank_agnostic
python test/distributed/tensor/test_compile_on_one_rank.py
python test/inductor/test_auto_chunker.py
python test/inductor/test_fused_attention.py
python test/inductor/test_pattern_matcher.py
python test/inductor/test_pad_mm.py

All pass.

This PR was authored with the assistance of an AI coding assistant (Claude).

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

Under compile-on-one-rank, this PR makes the joint-graph passes (uniform-value
constant folding, pattern matcher constant-arg comparison,
register_replacement/replace_by_example, fix_iota_device, auto-chunker) handle
`coor.current_device()` nodes, routing any inserted device through
`rank_agnostic_device` inside a new `rank_agnostic_passes()` window. No issues
were found. Recommendation: Approve  nothing blocks merging.

Reviewed commit: 69cd0fa

Review run

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/201491

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (10 Unrelated Failures)

As of commit 69cd0fa with merge base 807c466 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Triviality
    • Four separate fixes, not one root cause: constant folding, _match device matching, replacement device swapping, and fix_iota_device
    • _match in torch/_inductor/pattern_matcher.py now accepts a coor.current_device() node against a torch.device pattern constant
  • Scope
    • Adds a contextvar rank_agnostic_passes() window on joint_graph_passes, plus the rank_agnostic_device and _use_current_device_node helpers
    • Touches joint_graph.py, auto_chunker/applier.py, replace_random.py, and both replacement paths in pattern_matcher.py
  • Consequential design
    • fwd_only drops its is_replacement keyword, and replace_by_example no longer traces with compile-on-one-rank live
    • _deduce_value now evaluates current_device() and passes the evaluated kwargs to full(), which changes what gets constant-folded

reason: not_trivial
Reviewed commit: 61cfb44 (NOT the current head 69cd0fa)

Inference job

🐛 Report a wrong verdict

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:

  • inductor / unit-test / inductor-cpu-test / test (inductor_amx, 2, 7, mt-l-x86iamx-8-64) (gh)
    test/test_modules.py::TestJitReplaceSubmodule::test_jit_replace_submodule_empty_qualified_name

    AI verdict: AI verdict: not related

    The failing test actually passes. Right after it, pytest crashes with an INTERNALERROR KeyError in junitxml's finalize, called from test/conftest.py, under pytest-9.2.0. The merge base without the suspect commit fails in exactly the same way on the same shard and the same test, and the suspect only changes inductor fx-pass code.

    Full reasoning on HUD →

  • inductor / unit-test / inductor-cpu-test / test (inductor_amx, 3, 7, mt-l-x86iamx-8-64) (gh)
    test/test_modules.py::TestJitReplaceSubmodule::test_jit_replace_submodule

    AI verdict: AI verdict: not related

    test_jit_replace_submodule actually PASSED. The job failed because pytest crashed with an INTERNALERROR (a KeyError in junitxml's node_reporters.pop, reached through pytest_rerunfailures and test/conftest.py). The same crash shows up 1,957 times at the merge base, which failed every amx shard. So it predates the suspect, and the suspect only moves inductor rank-agnostic helpers between modules.

    Full reasoning on HUD →

  • inductor / unit-test / inductor-test-cuda132 / test (inductor_cpp_wrapper, 2, 2, mt-l-x86aavx2-11-41-a10g) (gh)
    test/inductor/test_torchinductor_opinfo.py::TestInductorOpInfoCUDA::test_comprehensive_linalg_cross_cuda_float64

    AI verdict: AI verdict: not related

    The suspect commit's job log shows test_comprehensive_linalg_cross_cuda_float64 PASSING every time it ran. Each run then hit a pytest INTERNALERROR (a KeyError in junitxml's node_reporters.pop, called from test/conftest.py's pytest_runtest_logreport). The merge base already shows the same harness KeyError on other tests in this job, so the problem predates the suspect. The suspect only moves rank_agnostic helpers from pattern_matcher.py to fx_utils.py and cannot reach the pytest reporting code.

    Full reasoning on HUD →

  • inductor / unit-test / inductor-test-cuda132 / test (inductor_distributed, 1, 1, mt-l-x86aavx2-45-167-a10g-4) (gh)
    test/inductor/test_aot_inductor.py::AOTInductorTestABICompatibleCpu::test_replicate_on_devices_cpu

    AI verdict: AI verdict: not related

    The suspect's failure is a pytest INTERNALERROR (a KeyError in junitxml's node_reporters.pop for a skipped test_replicate_on_devices test). The merge-base run 807c466 of the same job hits the exact same traceback, so the failure was already there before the suspect. The suspect only touches inductor pattern_matcher/fx_utils/joint_graph/auto_chunker and a distributed test, none of which is in the pytest reporting path.

    Full reasoning on HUD →

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs failed but was present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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 Oct 21, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

@aorenste
aorenste marked this pull request as ready for review October 21, 2026 00:33
@aorenste
aorenste requested a review from bobrenjc93 October 21, 2026 00:33
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 21, 2026
github-actions[bot]

This comment was marked as outdated.

@aorenste aorenste added the topic: not user facing topic category label Oct 23, 2026
[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
aorenste added a commit that referenced this pull request Oct 26, 2026
…ing, and rank-agnostic

Under compile_on_one_rank, the joint graph carries device operands as
coor.current_device() nodes until post_grad's respecialize_current_device_nodes.
Several joint-graph passes didn't understand that node, so register_replacement
patterns that depend on them (e.g. the masked SDPA fusions) silently stopped
firing: _sfdp_pattern_15 fused with CooR off and not with it on.

There were three blockers, plus one latent bug that became reachable once they
were fixed:

1. UniformValueConstantFolder treated current_device() as unknown, so every
   constructor fed by it (here the masked_fill fill value, a scalar_tensor) was
   left unfolded. The sfdp patterns expect the folded aten.full, so the coarse
   match failed. The folder now evaluates current_device(). This also fixes the
   full() case, which passed the raw node.kwargs (a Node as device) instead of
   the evaluated kwargs.
2. constant_fold_uniform_value reinserted folded tensors as full(device=
   fake_tensor.device), which bakes the compiling rank's device into the
   graph that the FX graph cache key hashes. It now gives the new full()s one
   shared current_device() node when the device is the current accelerator. The
   node carries meta["val"] like the ones make_fx creates: the partitioner only
   exempts a device node from the recompute ban when it has one, so without it
   a folded constant feeding the backward is saved instead of recomputed.
3. register_replacement's exact recheck re-traces the search function with
   CooR off, so its pattern holds the concrete device (cuda:0) where the graph
   holds a current_device() node, and the constant comparison rejected it. The
   matcher now accepts a current_device() node against a pattern device equal
   to this rank's current device. Re-tracing the recheck with CooR on instead
   was rejected: the traced device node would carry a _users count that the
   graph's shared device node never satisfies.
4. With matching working, replacements were still traced with CooR off, so a
   replacement that creates a tensor on the device (the sfdp replacement builds
   an additive -inf mask) baked cuda:0 into the pre-post_grad graph. Both
   register_replacement and replace_by_example now swap every device in the
   traced replacement that is this rank's current accelerator for a
   current_device() node -- the node a CooR trace would have emitted, and the
   same rule (2) uses. Under CooR the inputs are on the current accelerator by
   invariant, so such a device can only have come from there.

   Doing this after tracing, rather than tracing with CooR on, makes it work
   for every trace_fn: joint_fwd_bwd hard-codes CooR off, and a
   functools.partial of fwd_only can't be recognized by identity. So
   replace_by_example no longer traces with CooR live, and fwd_only loses its
   is_replacement flag. An earlier version rejected the match for any trace_fn
   but a bare fwd_only, which kept the graph rank-agnostic but gave up the
   fusion.

(2) and (4) apply only while the graph is still rank-agnostic, which
joint_graph_passes now marks with a rank_agnostic_passes() context. That can't
be read off the graph -- one with no device operands (pad_mm's addmm, whose
replacement calls new_zeros) has no current_device() node before
respecialization or after -- and "CooR is on" isn't enough either, because
post_grad pattern passes run after respecialization, where an inserted
current_device() node would never be concretized. freeze()'s constant folding
and replacements also run outside the window, after joint_graph_passes, and
still bake the device; frozen parameters are per-rank data anyway.

Test Plan:

The new test compiles the SDPA rewriter-15 model in inference under CooR on
cuda:0 and cuda:1 and checks numerics, that fuse_attention fires, and that the
graph before post_grad has no index=0 and is identical on both devices.
Reverting any one of the four parts fails it.

Two single-GPU tests cover the rest, and each fails with its fix reverted:
test_constant_folding_feeds_backward_under_coor checks that a folded constant
feeding the backward is recomputed there, and
test_replacement_with_device_rank_agnostic_under_coor checks, for fwd_only,
partial(fwd_only) and joint_fwd_bwd, and with and without a device operand in
the search pattern, that a replacement creating a tensor on the device fires,
leaves no concrete device in the graph's args or kwargs, and feeds from a
current_device() node. Gating on the presence of a current_device() node
fails the no-device-operand cases; gating on CooR alone fails the existing
test_post_grad_replacement_with_device_under_coor; dropping the
replace_by_example swap fails test_rng_replacements_rank_agnostic_before_post_grad.

```
python test/distributed/tensor/test_compile_on_one_rank.py -k test_constant_folding_and_sdpa_fusion_under_coor
python test/distributed/tensor/test_compile_on_one_rank.py -k replacement -k constant_folding -k rng
python test/distributed/tensor/test_compile_on_one_rank.py
python test/inductor/test_fused_attention.py
python test/inductor/test_pattern_matcher.py
python test/inductor/test_pad_mm.py
```

All but test_pattern_matcher pass. test_pattern_matcher has one error,
test_auto_functionalized_default_kwarg_matches, which uses
unittest.enterContext (Python 3.11+) and can't run in the local 3.10 venv.

This PR was authored with the assistance of an AI coding assistant (Claude).

ghstack-source-id: 36d285d
Pull-Request: #201491
github-actions[bot]

This comment was marked as outdated.

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 27, 2026
[ghstack-poisoned]
aorenste added a commit that referenced this pull request Oct 28, 2026
…ing, and rank-agnostic

Under compile_on_one_rank, the joint graph carries device operands as
coor.current_device() nodes until post_grad's respecialize_current_device_nodes.
Several joint-graph passes didn't understand that node, so register_replacement
patterns that depend on them (e.g. the masked SDPA fusions) silently stopped
firing: _sfdp_pattern_15 fused with CooR off and not with it on.

There were three blockers, plus one latent bug that became reachable once they
were fixed:

1. UniformValueConstantFolder treated current_device() as unknown, so every
   constructor fed by it (here the masked_fill fill value, a scalar_tensor) was
   left unfolded. The sfdp patterns expect the folded aten.full, so the coarse
   match failed. The folder now evaluates current_device(). This also fixes the
   full() case, which passed the raw node.kwargs (a Node as device) instead of
   the evaluated kwargs.
2. constant_fold_uniform_value reinserted folded tensors as full(device=
   fake_tensor.device), which bakes the compiling rank's device into the
   graph that the FX graph cache key hashes. It now takes the device from a new
   rank_agnostic_device(graph, device) helper, which turns the current
   accelerator into a current_device() node at the top of the graph, reused by
   later insertions. The
   node carries meta["val"] like the ones make_fx creates: the partitioner only
   exempts a device node from the recompute ban when it has one, so without it
   a folded constant feeding the backward is saved instead of recomputed.
3. register_replacement's exact recheck re-traces the search function with
   CooR off, so its pattern holds the concrete device (cuda:0) where the graph
   holds a current_device() node, and the constant comparison rejected it. The
   matcher now accepts a current_device() node against a pattern device equal
   to this rank's current device. Re-tracing the recheck with CooR on instead
   was rejected: the traced device node would carry a _users count that the
   graph's shared device node never satisfies.
4. With matching working, replacements were still traced with CooR off, so a
   replacement that creates a tensor on the device (the sfdp replacement builds
   an additive -inf mask) baked cuda:0 into the pre-post_grad graph. Both
   register_replacement and replace_by_example now swap every device in the
   traced replacement through rank_agnostic_device, as (2) does, so this rank's
   current accelerator becomes the current_device() node a CooR trace would have
   emitted. Under CooR the inputs are on the current accelerator by invariant, so
   such a device can only have come from there.

   Doing this after tracing, rather than tracing with CooR on, makes it work
   for every trace_fn: joint_fwd_bwd hard-codes CooR off, and a
   functools.partial of fwd_only can't be recognized by identity. So
   replace_by_example no longer traces with CooR live, and fwd_only loses its
   is_replacement flag. An earlier version rejected the match for any trace_fn
   but a bare fwd_only, which kept the graph rank-agnostic but gave up the
   fusion.

rank_agnostic_device only swaps while the graph is still rank-agnostic, which
joint_graph_passes now marks with a rank_agnostic_passes() context. That can't
be read off the graph: one with no device operands (pad_mm's addmm, whose
replacement calls new_zeros) has no current_device() node before
respecialization or after, and a GraphModule.meta flag would be lost on every
GraphModule(root, graph) rebuild, such as prepare_for_partitioner's right before
the joint passes. "CooR is on" isn't enough either, because post_grad pattern
passes run after respecialization, where an inserted current_device() node would
never be concretized. freeze()'s constant folding and replacements also run
outside the window, after joint_graph_passes, and still bake the device; frozen
parameters are per-rank data anyway.

Every pass inside the window that inserts a device now goes through
rank_agnostic_device: constant folding, both replacement paths, fix_iota_device
and the auto-chunker's factory nodes. fix_iota_device also compared device.type,
where device can be a current_device() node whose .type is its (None) type
annotation, so it rewrote even a cuda arange with a concrete device; it now
compares the iota's meta["val"] device.

There is deliberately no assertion at the end of the window that no node holds
this rank's device. It can't tell a device a pass inserted from one already in
the incoming graph: HOP proxy implementations (auto_functionalized, with_effects,
...) build their nodes with create_proxy directly, bypassing make_fx's CooR
rewrite, so an explicit torch.device("cuda", idx) passed to a mutable custom op
reaches the joint graph with its index. An assertion turned those programs into
crashes, where a leak only costs cross-rank cache sharing -- post_grad
respecializes the device before lowering either way. That HOP leak predates this
change and is left for a follow-up.

Test Plan:

The new test compiles the SDPA rewriter-15 model in inference under CooR on
cuda:0 and cuda:1 and checks numerics, that fuse_attention fires, and that the
graph before post_grad has no index=0 and is identical on both devices.
Reverting any one of the four parts fails it.

Two single-GPU tests cover the rest, and each fails with its fix reverted:
test_constant_folding_feeds_backward_under_coor checks that a folded constant
feeding the backward is recomputed there, and
test_replacement_with_device_rank_agnostic_under_coor checks, for fwd_only,
partial(fwd_only) and joint_fwd_bwd, and with and without a device operand in
the search pattern, that a replacement creating a tensor on the device fires,
leaves no concrete device in the graph's args or kwargs, and feeds from a
current_device() node. Gating on the presence of a current_device() node
fails the no-device-operand cases; gating on CooR alone fails the existing
test_post_grad_replacement_with_device_under_coor; dropping the
replace_by_example swap fails test_rng_replacements_rank_agnostic_before_post_grad.

test_iota_device_fix_rank_agnostic_under_coor indexes with an arange on cpu and
on cuda and checks that the iota ends up on a current_device() node; both fail
with the old fix_iota_device, and the cpu case fails if fix_iota_device doesn't
fire.
test_current_device_matches_only_this_ranks_pattern_device checks that a
current_device() node matches a pattern on this rank's device and not on another
index; the other-index case fails if the matcher accepts any device.

```
python test/distributed/tensor/test_compile_on_one_rank.py -k test_constant_folding_and_sdpa_fusion_under_coor
python test/distributed/tensor/test_compile_on_one_rank.py -k replacement -k constant_folding -k rng
python test/distributed/tensor/test_compile_on_one_rank.py -k iota_device_fix -k current_device_matches_only
python test/distributed/tensor/test_compile_on_one_rank.py
python test/inductor/test_auto_chunker.py
python test/inductor/test_fused_attention.py
python test/inductor/test_pattern_matcher.py
python test/inductor/test_pad_mm.py
```

All but test_pattern_matcher pass. test_pattern_matcher has one error,
test_auto_functionalized_default_kwarg_matches, which uses
unittest.enterContext (Python 3.11+) and can't run in the local 3.10 venv.

This PR was authored with the assistance of an AI coding assistant (Claude).

ghstack-source-id: d4cb831
Pull-Request: #201491
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
aorenste added a commit that referenced this pull request Oct 28, 2026
…ing, and rank-agnostic

Under compile_on_one_rank, the joint graph carries device operands as
coor.current_device() nodes until post_grad's respecialize_current_device_nodes.
Several joint-graph passes didn't understand that node, so register_replacement
patterns that depend on them (e.g. the masked SDPA fusions) silently stopped
firing: _sfdp_pattern_15 fused with CooR off and not with it on.

There were three blockers, plus one latent bug that became reachable once they
were fixed:

1. UniformValueConstantFolder treated current_device() as unknown, so every
   constructor fed by it (here the masked_fill fill value, a scalar_tensor) was
   left unfolded. The sfdp patterns expect the folded aten.full, so the coarse
   match failed. The folder now evaluates current_device(). This also fixes the
   full() case, which passed the raw node.kwargs (a Node as device) instead of
   the evaluated kwargs.
2. constant_fold_uniform_value reinserted folded tensors as full(device=
   fake_tensor.device), which bakes the compiling rank's device into the
   graph that the FX graph cache key hashes. It now takes the device from a new
   rank_agnostic_device(graph, device) helper, which turns the current
   accelerator into a current_device() node at the top of the graph, reused by
   later insertions. The
   node carries meta["val"] like the ones make_fx creates: the partitioner only
   exempts a device node from the recompute ban when it has one, so without it
   a folded constant feeding the backward is saved instead of recomputed.
3. register_replacement's exact recheck re-traces the search function with
   CooR off, so its pattern holds the concrete device (cuda:0) where the graph
   holds a current_device() node, and the constant comparison rejected it. The
   matcher now accepts a current_device() node against a pattern device equal
   to this rank's current device. Re-tracing the recheck with CooR on instead
   was rejected: the traced device node would carry a _users count that the
   graph's shared device node never satisfies.
4. With matching working, replacements were still traced with CooR off, so a
   replacement that creates a tensor on the device (the sfdp replacement builds
   an additive -inf mask) baked cuda:0 into the pre-post_grad graph. Both
   register_replacement and replace_by_example now swap every device in the
   traced replacement through rank_agnostic_device, as (2) does, so this rank's
   current accelerator becomes the current_device() node a CooR trace would have
   emitted. Under CooR the inputs are on the current accelerator by invariant, so
   such a device can only have come from there.

   Doing this after tracing, rather than tracing with CooR on, makes it work
   for every trace_fn: joint_fwd_bwd hard-codes CooR off, and a
   functools.partial of fwd_only can't be recognized by identity. So
   replace_by_example no longer traces with CooR live, and fwd_only loses its
   is_replacement flag. An earlier version rejected the match for any trace_fn
   but a bare fwd_only, which kept the graph rank-agnostic but gave up the
   fusion.

rank_agnostic_device only swaps while the graph is still rank-agnostic, which
joint_graph_passes now marks with a rank_agnostic_passes() context. That can't
be read off the graph: one with no device operands (pad_mm's addmm, whose
replacement calls new_zeros) has no current_device() node before
respecialization or after, and a GraphModule.meta flag would be lost on every
GraphModule(root, graph) rebuild, such as prepare_for_partitioner's right before
the joint passes. "CooR is on" isn't enough either, because post_grad pattern
passes run after respecialization, where an inserted current_device() node would
never be concretized. freeze()'s constant folding and replacements also run
outside the window, after joint_graph_passes, and still bake the device; frozen
parameters are per-rank data anyway.

Every pass inside the window that inserts a device now goes through
rank_agnostic_device: constant folding, both replacement paths, fix_iota_device
and the auto-chunker's factory nodes. fix_iota_device also compared device.type,
where device can be a current_device() node whose .type is its (None) type
annotation, so it rewrote even a cuda arange with a concrete device; it now
compares the iota's meta["val"] device.

There is deliberately no assertion at the end of the window that no node holds
this rank's device. It can't tell a device a pass inserted from one already in
the incoming graph: HOP proxy implementations (auto_functionalized, with_effects,
...) build their nodes with create_proxy directly, bypassing make_fx's CooR
rewrite, so an explicit torch.device("cuda", idx) passed to a mutable custom op
reaches the joint graph with its index. An assertion turned those programs into
crashes, where a leak only costs cross-rank cache sharing -- post_grad
respecializes the device before lowering either way. That HOP leak predates this
change and is left for a follow-up; the rank_agnostic_passes docstring records
both, and _use_current_device_node notes that a replacement containing a HOP
still bakes the device inside its subgraph.

Test Plan:

The new test compiles the SDPA rewriter-15 model in inference under CooR on
cuda:0 and cuda:1 and checks numerics, that fuse_attention fires, and that the
graph before post_grad has no index=0 and is identical on both devices.
Reverting any one of the four parts fails it.

Two single-GPU tests cover the rest, and each fails with its fix reverted:
test_constant_folding_feeds_backward_under_coor checks that a folded constant
feeding the backward is recomputed there, and
test_replacement_with_device_rank_agnostic_under_coor checks, for fwd_only,
partial(fwd_only) and joint_fwd_bwd, and with and without a device operand in
the search pattern, that a replacement creating a tensor on the device fires,
leaves no concrete device in the graph's args or kwargs, and feeds from a
current_device() node. Gating on the presence of a current_device() node
fails the no-device-operand cases; gating on CooR alone fails the existing
test_post_grad_replacement_with_device_under_coor; dropping the
replace_by_example swap fails test_rng_replacements_rank_agnostic_before_post_grad.

test_iota_device_fix_rank_agnostic_under_coor indexes with an arange on cpu and
on cuda and checks that the iota ends up on a current_device() node; both fail
with the old fix_iota_device, and the cpu case fails if fix_iota_device doesn't
fire. test_auto_chunker_rank_agnostic_under_coor runs the auto-chunker under
CooR and checks that chunking fires and that no concrete cuda device reaches the
joint graph; it fails with the auto-chunker's old fake_tensor.device.
test_current_device_matches_only_this_ranks_pattern_device checks that a
current_device() node matches a pattern on this rank's device and not on another
index; the other-index case fails if the matcher accepts any device.

```
python test/distributed/tensor/test_compile_on_one_rank.py -k test_constant_folding_and_sdpa_fusion_under_coor
python test/distributed/tensor/test_compile_on_one_rank.py -k replacement -k constant_folding -k rng
python test/distributed/tensor/test_compile_on_one_rank.py -k iota_device_fix -k current_device_matches_only -k auto_chunker_rank_agnostic
python test/distributed/tensor/test_compile_on_one_rank.py
python test/inductor/test_auto_chunker.py
python test/inductor/test_fused_attention.py
python test/inductor/test_pattern_matcher.py
python test/inductor/test_pad_mm.py
```

All but test_pattern_matcher pass. test_pattern_matcher has one error,
test_auto_functionalized_default_kwarg_matches, which uses
unittest.enterContext (Python 3.11+) and can't run in the local 3.10 venv.

This PR was authored with the assistance of an AI coding assistant (Claude).

ghstack-source-id: 9a65234
Pull-Request: #201491
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed their stale review October 28, 2026 17:34

Withdrawn: the automated review of 61cfb44 found nothing blocking.

@github-actions
github-actions Bot dismissed stale reviews from themself October 28, 2026 17:34

Withdrawn: the automated review of 61cfb44 found nothing blocking.

Comment thread torch/_inductor/pattern_matcher.py Outdated
Inside rank_agnostic_passes under compile-on-one-rank, this rank's current
accelerator becomes a coor.current_device() node, the one a CooR trace would have
emitted. It goes before the first non-placeholder, so it precedes every use and
later calls reuse it. It carries meta["val"] like the nodes make_fx creates: the

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.

AI-drafted review comment:

[suggestion] This docstring (and the PR description) says later insertions reuse the top-of-graph current_device() node. That's true for direct callers like constant folding, fix_iota_device and the auto-chunker. But _use_current_device_node puts the node inside the replacement graph, and Replacer.run_node in replace_with_graph copies every call_function node at each match site. So each fired replacement (e.g. one per fused attention layer) adds its own current_device() node. Output stays rank-agnostic, so this is only cleanliness. Either have Replacer.run_node map a replacement-graph coor.current_device node to rank_agnostic_device(graph, node.meta["val"]), or narrow the docstring to the callers that actually share the node.

import torch
from torch import Tensor
from torch._dynamo.utils import detect_fake_mode
from torch._inductor.pattern_matcher import rank_agnostic_device

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.

AI-drafted review comment:

[suggestion] rank_agnostic_device, rank_agnostic_passes and rank_agnostic describe a compile-on-one-rank pipeline phase, not pattern matching. Constant folding and the auto-chunker use them as well, and this module now imports pattern_matcher only for this helper. Consider moving them next to respecialize_current_device_nodes, or into torch/_inductor/fx_utils.py, so the window's start and end live together.

replaced, devices, device_nodes_used = [], [], []
current_device = torch.ops.coor.current_device.default

class Apply(CustomGraphPass):

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.

AI-drafted review comment:

[nit] CaptureGraphs was added to cut the inline CustomGraphPass boilerplate, but Apply here and the two Record classes (lines 794, 829) bring it back. The pytree.tree_leaves(...) device-operand collection appears twice. Consider letting CaptureGraphs take a callback, or adding a small DeviceOperands pass that both tests share.

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

approve w/ comments

[ghstack-poisoned]
aorenste added a commit that referenced this pull request Oct 28, 2026
…ing, and rank-agnostic

Under compile_on_one_rank, the joint graph carries device operands as
coor.current_device() nodes until post_grad's respecialize_current_device_nodes.
Several joint-graph passes didn't understand that node, so register_replacement
patterns that depend on them (e.g. the masked SDPA fusions) silently stopped
firing: _sfdp_pattern_15 fused with CooR off and not with it on.

There were three blockers, plus one latent bug that became reachable once they
were fixed:

1. UniformValueConstantFolder treated current_device() as unknown, so every
   constructor fed by it (here the masked_fill fill value, a scalar_tensor) was
   left unfolded. The sfdp patterns expect the folded aten.full, so the coarse
   match failed. The folder now evaluates current_device(). This also fixes the
   full() case, which passed the raw node.kwargs (a Node as device) instead of
   the evaluated kwargs.
2. constant_fold_uniform_value reinserted folded tensors as full(device=
   fake_tensor.device), which bakes the compiling rank's device into the
   graph that the FX graph cache key hashes. It now takes the device from a new
   rank_agnostic_device(graph, device) helper in fx_utils.py, which turns the
   current accelerator into a current_device() node at the top of the graph,
   reused by later calls on the same graph. The
   node carries meta["val"] like the ones make_fx creates: the partitioner only
   exempts a device node from the recompute ban when it has one, so without it
   a folded constant feeding the backward is saved instead of recomputed.
3. register_replacement's exact recheck re-traces the search function with
   CooR off, so its pattern holds the concrete device (cuda:0) where the graph
   holds a current_device() node, and the constant comparison rejected it. The
   matcher now accepts a current_device() node against a pattern device equal
   to this rank's current device. Re-tracing the recheck with CooR on instead
   was rejected: the traced device node would carry a _users count that the
   graph's shared device node never satisfies.
4. With matching working, replacements were still traced with CooR off, so a
   replacement that creates a tensor on the device (the sfdp replacement builds
   an additive -inf mask) baked cuda:0 into the pre-post_grad graph. Both
   register_replacement and replace_by_example now swap every device in the
   traced replacement through rank_agnostic_device, as (2) does, so this rank's
   current accelerator becomes the current_device() node a CooR trace would have
   emitted. Under CooR the inputs are on the current accelerator by invariant, so
   such a device can only have come from there. The replacement graph carries its
   own node, which Replacer copies to each match site, so each fired replacement
   adds one; respecialization handles them all.

   Doing this after tracing, rather than tracing with CooR on, makes it work
   for every trace_fn: joint_fwd_bwd hard-codes CooR off, and a
   functools.partial of fwd_only can't be recognized by identity. So
   replace_by_example no longer traces with CooR live, and fwd_only loses its
   is_replacement flag. An earlier version rejected the match for any trace_fn
   but a bare fwd_only, which kept the graph rank-agnostic but gave up the
   fusion.

rank_agnostic_device only swaps while the graph is still rank-agnostic, which
joint_graph_passes now marks with a rank_agnostic_passes() context. That can't
be read off the graph: one with no device operands (pad_mm's addmm, whose
replacement calls new_zeros) has no current_device() node before
respecialization or after, and a GraphModule.meta flag would be lost on every
GraphModule(root, graph) rebuild, such as prepare_for_partitioner's right before
the joint passes. "CooR is on" isn't enough either, because post_grad pattern
passes run after respecialization, where an inserted current_device() node would
never be concretized. freeze()'s constant folding and replacements also run
outside the window, after joint_graph_passes, and still bake the device; frozen
parameters are per-rank data anyway.

Every pass inside the window that inserts a device now goes through
rank_agnostic_device: constant folding, both replacement paths, fix_iota_device
and the auto-chunker's factory nodes. fix_iota_device also compared device.type,
where device can be a current_device() node whose .type is its (None) type
annotation, so it rewrote even a cuda arange with a concrete device; it now
compares the iota's meta["val"] device.

There is deliberately no assertion at the end of the window that no node holds
this rank's device. It can't tell a device a pass inserted from one already in
the incoming graph: HOP proxy implementations (auto_functionalized, with_effects,
...) build their nodes with create_proxy directly, bypassing make_fx's CooR
rewrite, so an explicit torch.device("cuda", idx) passed to a mutable custom op
reaches the joint graph with its index. An assertion turned those programs into
crashes, where a leak only costs cross-rank cache sharing -- post_grad
respecializes the device before lowering either way. That HOP leak predates this
change and is left for a follow-up; the rank_agnostic_passes docstring records
both, and _use_current_device_node notes that a replacement containing a HOP
still bakes the device inside its subgraph.

Test Plan:

The new test compiles the SDPA rewriter-15 model in inference under CooR on
cuda:0 and cuda:1 and checks numerics, that fuse_attention fires, and that the
graph before post_grad has no index=0 and is identical on both devices.
Reverting any one of the four parts fails it.

Two single-GPU tests cover the rest, and each fails with its fix reverted:
test_constant_folding_feeds_backward_under_coor checks that a folded constant
feeding the backward is recomputed there, and
test_replacement_with_device_rank_agnostic_under_coor checks, for fwd_only,
partial(fwd_only) and joint_fwd_bwd, and with and without a device operand in
the search pattern, that a replacement creating a tensor on the device fires,
leaves no concrete device in the graph's args or kwargs, and feeds from a
current_device() node. Gating on the presence of a current_device() node
fails the no-device-operand cases; gating on CooR alone fails the existing
test_post_grad_replacement_with_device_under_coor; dropping the
replace_by_example swap fails test_rng_replacements_rank_agnostic_before_post_grad.

test_iota_device_fix_rank_agnostic_under_coor indexes with an arange on cpu and
on cuda and checks that the iota ends up on a current_device() node; both fail
with the old fix_iota_device, and the cpu case fails if fix_iota_device doesn't
fire. test_auto_chunker_rank_agnostic_under_coor runs the auto-chunker under
CooR and checks that chunking fires and that no concrete cuda device reaches the
joint graph; it fails with the auto-chunker's old fake_tensor.device.
test_current_device_matches_only_this_ranks_pattern_device checks that a
current_device() node matches a pattern on this rank's device and not on another
index; the other-index case fails if the matcher accepts any device.

```
python test/distributed/tensor/test_compile_on_one_rank.py -k test_constant_folding_and_sdpa_fusion_under_coor
python test/distributed/tensor/test_compile_on_one_rank.py -k replacement -k constant_folding -k rng
python test/distributed/tensor/test_compile_on_one_rank.py -k iota_device_fix -k current_device_matches_only -k auto_chunker_rank_agnostic
python test/distributed/tensor/test_compile_on_one_rank.py
python test/inductor/test_auto_chunker.py
python test/inductor/test_fused_attention.py
python test/inductor/test_pattern_matcher.py
python test/inductor/test_pad_mm.py
```

All pass.

This PR was authored with the assistance of an AI coding assistant (Claude).

ghstack-source-id: 7756164
Pull-Request: #201491
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Oct 28, 2026

@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 69cd0fa: nothing blocking; ready for human review.

Under compile-on-one-rank, this PR makes the joint-graph passes (uniform-value constant folding, pattern matcher constant-arg comparison, register_replacement/replace_by_example, fix_iota_device, auto-chunker) handle coor.current_device() nodes, routing any inserted device through rank_agnostic_device inside a new rank_agnostic_passes() window. No issues were found. Recommendation: Approve nothing blocks merging.

This review is AI-generated and advisory. Each new automated review replaces the previous one.

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

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…ing, and rank-agnostic (pytorch#201491)

Under compile_on_one_rank, the joint graph carries device operands as
coor.current_device() nodes until post_grad's respecialize_current_device_nodes.
Several joint-graph passes didn't understand that node, so register_replacement
patterns that depend on them (e.g. the masked SDPA fusions) silently stopped
firing: _sfdp_pattern_15 fused with CooR off and not with it on.

There were three blockers, plus one latent bug that became reachable once they
were fixed:

1. UniformValueConstantFolder treated current_device() as unknown, so every
   constructor fed by it (here the masked_fill fill value, a scalar_tensor) was
   left unfolded. The sfdp patterns expect the folded aten.full, so the coarse
   match failed. The folder now evaluates current_device(). This also fixes the
   full() case, which passed the raw node.kwargs (a Node as device) instead of
   the evaluated kwargs.
2. constant_fold_uniform_value reinserted folded tensors as full(device=
   fake_tensor.device), which bakes the compiling rank's device into the
   graph that the FX graph cache key hashes. It now takes the device from a new
   rank_agnostic_device(graph, device) helper in fx_utils.py, which turns the
   current accelerator into a current_device() node at the top of the graph,
   reused by later calls on the same graph. The
   node carries meta["val"] like the ones make_fx creates: the partitioner only
   exempts a device node from the recompute ban when it has one, so without it
   a folded constant feeding the backward is saved instead of recomputed.
3. register_replacement's exact recheck re-traces the search function with
   CooR off, so its pattern holds the concrete device (cuda:0) where the graph
   holds a current_device() node, and the constant comparison rejected it. The
   matcher now accepts a current_device() node against a pattern device equal
   to this rank's current device. Re-tracing the recheck with CooR on instead
   was rejected: the traced device node would carry a _users count that the
   graph's shared device node never satisfies.
4. With matching working, replacements were still traced with CooR off, so a
   replacement that creates a tensor on the device (the sfdp replacement builds
   an additive -inf mask) baked cuda:0 into the pre-post_grad graph. Both
   register_replacement and replace_by_example now swap every device in the
   traced replacement through rank_agnostic_device, as (2) does, so this rank's
   current accelerator becomes the current_device() node a CooR trace would have
   emitted. Under CooR the inputs are on the current accelerator by invariant, so
   such a device can only have come from there. The replacement graph carries its
   own node, which Replacer copies to each match site, so each fired replacement
   adds one; respecialization handles them all.

   Doing this after tracing, rather than tracing with CooR on, makes it work
   for every trace_fn: joint_fwd_bwd hard-codes CooR off, and a
   functools.partial of fwd_only can't be recognized by identity. So
   replace_by_example no longer traces with CooR live, and fwd_only loses its
   is_replacement flag. An earlier version rejected the match for any trace_fn
   but a bare fwd_only, which kept the graph rank-agnostic but gave up the
   fusion.

rank_agnostic_device only swaps while the graph is still rank-agnostic, which
joint_graph_passes now marks with a rank_agnostic_passes() context. That can't
be read off the graph: one with no device operands (pad_mm's addmm, whose
replacement calls new_zeros) has no current_device() node before
respecialization or after, and a GraphModule.meta flag would be lost on every
GraphModule(root, graph) rebuild, such as prepare_for_partitioner's right before
the joint passes. "CooR is on" isn't enough either, because post_grad pattern
passes run after respecialization, where an inserted current_device() node would
never be concretized. freeze()'s constant folding and replacements also run
outside the window, after joint_graph_passes, and still bake the device; frozen
parameters are per-rank data anyway.

Every pass inside the window that inserts a device now goes through
rank_agnostic_device: constant folding, both replacement paths, fix_iota_device
and the auto-chunker's factory nodes. fix_iota_device also compared device.type,
where device can be a current_device() node whose .type is its (None) type
annotation, so it rewrote even a cuda arange with a concrete device; it now
compares the iota's meta["val"] device.

There is deliberately no assertion at the end of the window that no node holds
this rank's device. It can't tell a device a pass inserted from one already in
the incoming graph: HOP proxy implementations (auto_functionalized, with_effects,
...) build their nodes with create_proxy directly, bypassing make_fx's CooR
rewrite, so an explicit torch.device("cuda", idx) passed to a mutable custom op
reaches the joint graph with its index. An assertion turned those programs into
crashes, where a leak only costs cross-rank cache sharing -- post_grad
respecializes the device before lowering either way. That HOP leak predates this
change and is left for a follow-up; the rank_agnostic_passes docstring records
both, and _use_current_device_node notes that a replacement containing a HOP
still bakes the device inside its subgraph.

Test Plan:

The new test compiles the SDPA rewriter-15 model in inference under CooR on
cuda:0 and cuda:1 and checks numerics, that fuse_attention fires, and that the
graph before post_grad has no index=0 and is identical on both devices.
Reverting any one of the four parts fails it.

Two single-GPU tests cover the rest, and each fails with its fix reverted:
test_constant_folding_feeds_backward_under_coor checks that a folded constant
feeding the backward is recomputed there, and
test_replacement_with_device_rank_agnostic_under_coor checks, for fwd_only,
partial(fwd_only) and joint_fwd_bwd, and with and without a device operand in
the search pattern, that a replacement creating a tensor on the device fires,
leaves no concrete device in the graph's args or kwargs, and feeds from a
current_device() node. Gating on the presence of a current_device() node
fails the no-device-operand cases; gating on CooR alone fails the existing
test_post_grad_replacement_with_device_under_coor; dropping the
replace_by_example swap fails test_rng_replacements_rank_agnostic_before_post_grad.

test_iota_device_fix_rank_agnostic_under_coor indexes with an arange on cpu and
on cuda and checks that the iota ends up on a current_device() node; both fail
with the old fix_iota_device, and the cpu case fails if fix_iota_device doesn't
fire. test_auto_chunker_rank_agnostic_under_coor runs the auto-chunker under
CooR and checks that chunking fires and that no concrete cuda device reaches the
joint graph; it fails with the auto-chunker's old fake_tensor.device.
test_current_device_matches_only_this_ranks_pattern_device checks that a
current_device() node matches a pattern on this rank's device and not on another
index; the other-index case fails if the matcher accepts any device.

```
python test/distributed/tensor/test_compile_on_one_rank.py -k test_constant_folding_and_sdpa_fusion_under_coor
python test/distributed/tensor/test_compile_on_one_rank.py -k replacement -k constant_folding -k rng
python test/distributed/tensor/test_compile_on_one_rank.py -k iota_device_fix -k current_device_matches_only -k auto_chunker_rank_agnostic
python test/distributed/tensor/test_compile_on_one_rank.py
python test/inductor/test_auto_chunker.py
python test/inductor/test_fused_attention.py
python test/inductor/test_pattern_matcher.py
python test/inductor/test_pad_mm.py
```

All pass.

This PR was authored with the assistance of an AI coding assistant (Claude).

Pull Request resolved: pytorch#201491
Approved by: https://github.com/bobrenjc93
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…ing, and rank-agnostic (pytorch#201491)

Under compile_on_one_rank, the joint graph carries device operands as
coor.current_device() nodes until post_grad's respecialize_current_device_nodes.
Several joint-graph passes didn't understand that node, so register_replacement
patterns that depend on them (e.g. the masked SDPA fusions) silently stopped
firing: _sfdp_pattern_15 fused with CooR off and not with it on.

There were three blockers, plus one latent bug that became reachable once they
were fixed:

1. UniformValueConstantFolder treated current_device() as unknown, so every
   constructor fed by it (here the masked_fill fill value, a scalar_tensor) was
   left unfolded. The sfdp patterns expect the folded aten.full, so the coarse
   match failed. The folder now evaluates current_device(). This also fixes the
   full() case, which passed the raw node.kwargs (a Node as device) instead of
   the evaluated kwargs.
2. constant_fold_uniform_value reinserted folded tensors as full(device=
   fake_tensor.device), which bakes the compiling rank's device into the
   graph that the FX graph cache key hashes. It now takes the device from a new
   rank_agnostic_device(graph, device) helper in fx_utils.py, which turns the
   current accelerator into a current_device() node at the top of the graph,
   reused by later calls on the same graph. The
   node carries meta["val"] like the ones make_fx creates: the partitioner only
   exempts a device node from the recompute ban when it has one, so without it
   a folded constant feeding the backward is saved instead of recomputed.
3. register_replacement's exact recheck re-traces the search function with
   CooR off, so its pattern holds the concrete device (cuda:0) where the graph
   holds a current_device() node, and the constant comparison rejected it. The
   matcher now accepts a current_device() node against a pattern device equal
   to this rank's current device. Re-tracing the recheck with CooR on instead
   was rejected: the traced device node would carry a _users count that the
   graph's shared device node never satisfies.
4. With matching working, replacements were still traced with CooR off, so a
   replacement that creates a tensor on the device (the sfdp replacement builds
   an additive -inf mask) baked cuda:0 into the pre-post_grad graph. Both
   register_replacement and replace_by_example now swap every device in the
   traced replacement through rank_agnostic_device, as (2) does, so this rank's
   current accelerator becomes the current_device() node a CooR trace would have
   emitted. Under CooR the inputs are on the current accelerator by invariant, so
   such a device can only have come from there. The replacement graph carries its
   own node, which Replacer copies to each match site, so each fired replacement
   adds one; respecialization handles them all.

   Doing this after tracing, rather than tracing with CooR on, makes it work
   for every trace_fn: joint_fwd_bwd hard-codes CooR off, and a
   functools.partial of fwd_only can't be recognized by identity. So
   replace_by_example no longer traces with CooR live, and fwd_only loses its
   is_replacement flag. An earlier version rejected the match for any trace_fn
   but a bare fwd_only, which kept the graph rank-agnostic but gave up the
   fusion.

rank_agnostic_device only swaps while the graph is still rank-agnostic, which
joint_graph_passes now marks with a rank_agnostic_passes() context. That can't
be read off the graph: one with no device operands (pad_mm's addmm, whose
replacement calls new_zeros) has no current_device() node before
respecialization or after, and a GraphModule.meta flag would be lost on every
GraphModule(root, graph) rebuild, such as prepare_for_partitioner's right before
the joint passes. "CooR is on" isn't enough either, because post_grad pattern
passes run after respecialization, where an inserted current_device() node would
never be concretized. freeze()'s constant folding and replacements also run
outside the window, after joint_graph_passes, and still bake the device; frozen
parameters are per-rank data anyway.

Every pass inside the window that inserts a device now goes through
rank_agnostic_device: constant folding, both replacement paths, fix_iota_device
and the auto-chunker's factory nodes. fix_iota_device also compared device.type,
where device can be a current_device() node whose .type is its (None) type
annotation, so it rewrote even a cuda arange with a concrete device; it now
compares the iota's meta["val"] device.

There is deliberately no assertion at the end of the window that no node holds
this rank's device. It can't tell a device a pass inserted from one already in
the incoming graph: HOP proxy implementations (auto_functionalized, with_effects,
...) build their nodes with create_proxy directly, bypassing make_fx's CooR
rewrite, so an explicit torch.device("cuda", idx) passed to a mutable custom op
reaches the joint graph with its index. An assertion turned those programs into
crashes, where a leak only costs cross-rank cache sharing -- post_grad
respecializes the device before lowering either way. That HOP leak predates this
change and is left for a follow-up; the rank_agnostic_passes docstring records
both, and _use_current_device_node notes that a replacement containing a HOP
still bakes the device inside its subgraph.

Test Plan:

The new test compiles the SDPA rewriter-15 model in inference under CooR on
cuda:0 and cuda:1 and checks numerics, that fuse_attention fires, and that the
graph before post_grad has no index=0 and is identical on both devices.
Reverting any one of the four parts fails it.

Two single-GPU tests cover the rest, and each fails with its fix reverted:
test_constant_folding_feeds_backward_under_coor checks that a folded constant
feeding the backward is recomputed there, and
test_replacement_with_device_rank_agnostic_under_coor checks, for fwd_only,
partial(fwd_only) and joint_fwd_bwd, and with and without a device operand in
the search pattern, that a replacement creating a tensor on the device fires,
leaves no concrete device in the graph's args or kwargs, and feeds from a
current_device() node. Gating on the presence of a current_device() node
fails the no-device-operand cases; gating on CooR alone fails the existing
test_post_grad_replacement_with_device_under_coor; dropping the
replace_by_example swap fails test_rng_replacements_rank_agnostic_before_post_grad.

test_iota_device_fix_rank_agnostic_under_coor indexes with an arange on cpu and
on cuda and checks that the iota ends up on a current_device() node; both fail
with the old fix_iota_device, and the cpu case fails if fix_iota_device doesn't
fire. test_auto_chunker_rank_agnostic_under_coor runs the auto-chunker under
CooR and checks that chunking fires and that no concrete cuda device reaches the
joint graph; it fails with the auto-chunker's old fake_tensor.device.
test_current_device_matches_only_this_ranks_pattern_device checks that a
current_device() node matches a pattern on this rank's device and not on another
index; the other-index case fails if the matcher accepts any device.

```
python test/distributed/tensor/test_compile_on_one_rank.py -k test_constant_folding_and_sdpa_fusion_under_coor
python test/distributed/tensor/test_compile_on_one_rank.py -k replacement -k constant_folding -k rng
python test/distributed/tensor/test_compile_on_one_rank.py -k iota_device_fix -k current_device_matches_only -k auto_chunker_rank_agnostic
python test/distributed/tensor/test_compile_on_one_rank.py
python test/inductor/test_auto_chunker.py
python test/inductor/test_fused_attention.py
python test/inductor/test_pattern_matcher.py
python test/inductor/test_pad_mm.py
```

All pass.

This PR was authored with the assistance of an AI coding assistant (Claude).

Pull Request resolved: pytorch#201491
Approved by: https://github.com/bobrenjc93
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged module: inductor ready for review Automated review passed, ready for a final review by a maintainer. topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants