Skip to content

[CooR] Keep RNG ops working, and rank-agnostic, under compile_on_one_rank - #196152

Closed
aorenste wants to merge 21 commits into
gh/aorenste/381/basefrom
gh/aorenste/381/head
Closed

aorenste wants to merge 21 commits into
gh/aorenste/381/basefrom
gh/aorenste/381/head

Conversation

@aorenste

@aorenste aorenste commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Every RNG op failed to compile under compile_on_one_rank -- rand, randn, randint
and so dropout too:

RuntimeError: prims::inductor_seed() Expected a value of type 'Device'
for argument 'device' but instead found type 'Node'

replace_random and replace_randint run on the joint graph, where a factory op's
device operand is still a coor current_device() node: respecialize_current_device_nodes
does not concretise those until post_grad. Both handlers take that operand
straight off the matched node, so a graph node reached inductor_prims.seed(),
whose schema declares Device and cannot accept one.

Resolve the node (_concrete_device) where a real device is genuinely needed:
get_device(), which feeds inductor_prims.seed(), and the meta["val"] that
fuse_seed_creation_pass and fuse_offset_creation_pass (align_random_eager) build
for the fused op. The fused op's graph argument keeps the node. Any other graph
node as a device operand raises an AssertionError.

That alone leaves the seed's device baked into the joint graph, and so into the
graph the fx graph cache key hashes, because fwd_only -- the tracer behind every
replace_by_example -- disables compile_on_one_rank wholesale. That is right for a
pattern template, which is only ever matched against, but wrong for a replacement
spliced into a graph that is still rank-agnostic. replace_by_example now traces
its replacement with compile_on_one_rank live only while the graph still contains
current_device() nodes, i.e. before post_grad's respecialize. After respecialize
the graph holds concrete devices, so later replacements (post-grad patterns,
decompose_auto_functionalized) keep tracing with it off; tracing those live would
splice in a current_device() node that nothing concretises before lowering.

Each replacement trace brings its own current_device() node, so the seed and
offset fusion passes now group all of them as one device. Otherwise seeds stop
fusing under compile_on_one_rank and the random values differ from a compile
without it.

The RNG path is now device-agnostic in the joint graph:

inductor_seeds_default = prims.inductor_seeds.default(1, current_device_default_1)

where it previously read device(type='cuda', index=0).

Alternative considered: keep only the _concrete_device fix and leave
replacements traced with compile_on_one_rank off. The generated code is
identical, but the baked device in the AOT graph makes the fx graph cache key
differ per rank.

Not covered: register_replacement traces its replacement through the
caller-supplied trace_fn with compile_on_one_rank off, so a registered
replacement that creates a tensor on the device would bake the compiling rank's
device into the joint graph. That is unreachable today, because joint-graph
patterns that involve a device don't match under compile_on_one_rank at all;
making them match (e.g. the masked SDPA fusions) exposes it. Both are fixed in
the next PR.

Test Plan:

The new tests fail against the previous version of this commit (crash in the
post-grad cumsum replacement, auto_functionalized decomposition and
align_random_eager; changed RNG values from unfused seeds) and pass now.
test_rng_replacements_rank_agnostic_before_post_grad captures the graph before
post_grad respecializes it, on cuda:0 and cuda:1; it fails if replace_by_example
traces replacements with compile_on_one_rank off, which the output-code checks
alone do not catch.

TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/distributed/tensor/test_compile_on_one_rank.py
TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/inductor/test_pattern_matcher.py
TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/inductor/test_fused_attention.py
TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/inductor/test_torchinductor.py -k GPUTests.test_<rand|dropout|seed tests>_cuda

test_pattern_matcher's test_reciprocal_sqrt_to_rsqrt and the CPU fused-attention
tests fail identically without this change (local C++ toolchain).

Authored with the assistance of an AI assistant.

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 Sep 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (3 Unrelated Failures)

As of commit af70181 with merge base 1fbdb13 (image):

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

  • Scope of behavior change
    • fwd_only in torch/_inductor/pattern_matcher.py now keeps compile_on_one_rank live for every replace_by_example replacement trace, not just RNG
    • Every inductor pattern replacement is affected under compile_on_one_rank, and a reviewer should judge whether all of them trace cleanly with CooR live
  • Test coverage
    • test_rng_ops_compile_under_coor only asserts the output shape, so it does not check that the seed stays rank-agnostic, which is what the PR claims
    • No test runs a non-RNG replacement pattern under compile_on_one_rank with the new is_replacement=True path
  • Triviality
    • Compiler-pass logic in replace_random.py (get_device, _concrete_device, fuse_seed_creation_pass) is outside every trivial class and needs a human review

reason: not_trivial
Reviewed commit: d0740cd (NOT the current head af70181)

Inference job

🐛 Report a wrong verdict

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.

[ghstack-poisoned]
@aorenste aorenste added the topic: not user facing topic category label Sep 6, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@aorenste
aorenste marked this pull request as ready for review September 27, 2026 18:07
@aorenste
aorenste requested a review from bobrenjc93 September 27, 2026 18:07

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

accepting w/ comments

# needs a real torch.device.
combined.meta["val"] = torch.empty(
[len(seeds)], device=device, dtype=torch.int64
[len(seeds)], device=_concrete_device(device), dtype=torch.int64

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.

fuse_offset_creation_pass 50 lines up has the identical torch.empty(device=<Node>) and didn't get this treatment. Repro below; analysis produced with an AI assistant.

[important] fuse_offset_creation_pass has the same defect and was not fixed.
Line 104 builds combined.meta["val"] exactly the way this line does, from
`device = node.args[1]` of an inductor_prims.rand_eager_offset node -- which
under CooR is a coor.current_device() node, for precisely the reason the new
get_device() comment gives.

With config.align_random_eager=True:

    import torch
    import torch.compiler.config as ccfg
    import torch._inductor.config as icfg

    def f(x):
        return torch.rand_like(x) * x

    with ccfg.patch(compile_on_one_rank=True), \
         icfg.patch(align_random_eager=True), \
         torch.cuda.device(0):
        torch.compile(f, backend="inductor")(torch.randn(64, 128, device="cuda"))

    # TypeError: empty(): argument 'device' must be torch.device, not Node
    #   File ".../torch/_inductor/fx_passes/replace_random.py", line 103,
    #     in fuse_offset_creation_pass

align_random_eager defaults to False so nothing in CI reaches it, but it is the
same bug class the PR is about and the fix is the same one line:
_concrete_device(device) on line 104, with the graph argument on line 99 left
as the node -- the same split you made here.

Comment thread torch/_inductor/pattern_matcher.py Outdated
fwd_only, run_functional_passes=run_functional_passes
fwd_only,
run_functional_passes=run_functional_passes,
is_replacement=True,

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.

This covers replace_by_example, but register_replacement traces its replacement through the same trace_fn, so a flag on fwd_only can't separate the two roles there. A/B below; analysis produced with an AI assistant.

[important] This only covers the replace_by_example path. register_replacement
takes a single caller-supplied trace_fn and uses it for both roles -- template
at lines 2070, 2102 and 2395, and the *replacement* at line 2145 -- so a boolean
on fwd_only cannot distinguish them there. Every register_replacement caller
that passes fwd_only (misc_patterns, pad_mm, freezing_patterns, fuse_attention,
post_grad) still traces its replacement with CooR off.

misc_patterns.randperm_index_full_replacement is registered on
joint_graph_patterns with trace_fn=fwd_only and does
torch.randperm(x.shape[0], device=x.device):

    import torch, torch.compiler.config as ccfg
    from torch._inductor.pattern_matcher import fwd_only

    def repl(x):
        index = torch.randperm(x.shape[0], device=x.device)
        return torch.ops.aten._unsafe_index(x, (index,)), index

    with ccfg.patch(compile_on_one_rank=True), torch.cuda.device(0):
        args = [torch.randn(8, 4, device="cuda")]
        print(fwd_only(repl, args).code)
        print(fwd_only(repl, args, is_replacement=True).code)

    # register_replacement path (line 2145):
    #   randperm = aten.randperm.default(8, device = device(type='cuda', index=0), ...)
    #
    # replace_by_example path (this line):
    #   current_device_default = coor.current_device.default()
    #   randperm = aten.randperm.default(8, device = current_device_default, ...)

randperm_index_add_replacement and randperm_index_replacement are the same. So
"the fourteen template call sites are unaffected" in the description is not
quite right -- those are not purely template call sites.

Threading is_replacement into the line-2145 call, rather than only defaulting
it in replace_by_example, would cover both.

torch._dynamo.reset()
x = torch.randn(64, 128, device="cuda", requires_grad=True)
out = torch.compile(fn, backend="inductor")(x)
self.assertEqual(out.shape, torch.Size([]))

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.

This catches the crash but not the rank-agnosticism, which is the half of the fix that's easy to regress. Analysis produced with an AI assistant.

[important] Asserting only the shape covers the hard failure but not the
rank-agnosticism that the fwd_only template/replacement split exists for.

Revert just is_replacement=True in pattern_matcher.py and the trace still
succeeds -- it simply bakes device(type='cuda', index=0) into the seed. Compile
completes, out.shape is still torch.Size([]), and this test still passes. The
property the description demonstrates, prims.inductor_seeds.default(1,
current_device_default_1), is unasserted.

The sibling test at lines 533-534 is the right model: compile on cuda:0 and
cuda:1, assertEqual the two printed graphs, and assertNotIn("index=0", graph0).
Doing that for one of these four fns would pin both halves of the fix.



def get_device(device):
if isinstance(device, torch.fx.Node):

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.

Small one -- these twelve lines are _concrete_device verbatim. Analysis produced with an AI assistant.

[suggestion] Lines 189-201 duplicate _concrete_device (line 175) verbatim,
error message included. get_device is that function plus a default:

    def get_device(device):
        device = _concrete_device(device)
        if device is not None:
            return device
        return torch.empty([]).device  # default device

The long comment is worth keeping -- it is the one that explains why resolving
here pins nothing -- but it only needs to live in one of the two.

[ghstack-poisoned]
@aorenste aorenste changed the title Keep RNG ops working, and rank-agnostic, under compile_on_one_rank [Coor] Keep RNG ops working, and rank-agnostic, under compile_on_one_rank Sep 30, 2026
@aorenste aorenste changed the title [Coor] Keep RNG ops working, and rank-agnostic, under compile_on_one_rank [CooR] Keep RNG ops working, and rank-agnostic, under compile_on_one_rank Sep 30, 2026
[ghstack-poisoned]
aorenste added a commit that referenced this pull request Oct 6, 2026
…rank

Every RNG op failed to compile under compile_on_one_rank -- rand, randn, randint
and so dropout too:

  RuntimeError: prims::inductor_seed() Expected a value of type 'Device'
                for argument 'device' but instead found type 'Node'

replace_random and replace_randint run on the joint graph, where a factory op's
device operand is still a coor current_device() node: respecialize_current_device_nodes
does not concretise those until post_grad. Both handlers take that operand
straight off the matched node, so a graph node reached inductor_prims.seed(),
whose schema declares Device and cannot accept one.

Resolve the node (_concrete_device) where a real device is genuinely needed:
get_device(), which feeds inductor_prims.seed(), and the meta["val"] that
fuse_seed_creation_pass and fuse_offset_creation_pass (align_random_eager) build
for the fused op. The fused op's graph argument keeps the node. Any other graph
node as a device operand raises an AssertionError.

That alone leaves the seed's device baked into the joint graph, and so into the
graph the fx graph cache key hashes, because fwd_only -- the tracer behind every
replace_by_example -- disables compile_on_one_rank wholesale. That is right for a
pattern template, which is only ever matched against, but wrong for a replacement
spliced into a graph that is still rank-agnostic. replace_by_example now traces
its replacement with compile_on_one_rank live only while the graph still contains
current_device() nodes, i.e. before post_grad's respecialize. After respecialize
the graph holds concrete devices, so later replacements (post-grad patterns,
decompose_auto_functionalized) keep tracing with it off; tracing those live would
splice in a current_device() node that nothing concretises before lowering.

Each replacement trace brings its own current_device() node, so the seed and
offset fusion passes now group all of them as one device. Otherwise seeds stop
fusing under compile_on_one_rank and the random values differ from a compile
without it.

The RNG path is now device-agnostic in the joint graph:

  inductor_seeds_default = prims.inductor_seeds.default(1, current_device_default_1)

where it previously read device(type='cuda', index=0).

Alternative considered: keep only the _concrete_device fix and leave
replacements traced with compile_on_one_rank off. The generated code is
identical, but the baked device in the AOT graph makes the fx graph cache key
differ per rank.

register_replacement still traces its replacements with compile_on_one_rank off,
so a pattern whose replacement creates a device-bearing op can still bake the
device into the joint graph; that is left for a follow-up.

Test Plan:

The new tests fail against the previous version of this commit (crash in the
post-grad cumsum replacement, auto_functionalized decomposition and
align_random_eager; changed RNG values from unfused seeds) and pass now.

```shell
TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/distributed/tensor/test_compile_on_one_rank.py
```

```shell
TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/inductor/test_pattern_matcher.py
```

```shell
TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/inductor/test_fused_attention.py
```

```shell
TORCHINDUCTOR_COMPILE_THREADS=1 .venv/bin/python test/inductor/test_torchinductor.py -k GPUTests.test_<rand|dropout|seed tests>_cuda
```

test_pattern_matcher's test_reciprocal_sqrt_to_rsqrt and the CPU fused-attention
tests fail identically without this change (local C++ toolchain).

Authored with the assistance of an AI assistant.

ghstack-source-id: ddf70ac
Pull-Request: #196152
[ghstack-poisoned]
[ghstack-poisoned]
@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

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 Merged module: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants