Skip to content

[inductor] Generalize reinplacing to functional ATen ops with an in-place variant - #189080

Closed
jbschlosser wants to merge 2 commits into
gh/jbschlosser/279/basefrom
gh/jbschlosser/279/head
Closed

jbschlosser wants to merge 2 commits into
gh/jbschlosser/279/basefrom
gh/jbschlosser/279/head

Conversation

@jbschlosser

@jbschlosser jbschlosser commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Broader fix for #188495

Under torch.compile, functionalization rewrites in-place ops (e.g. uniform_) into functional ones that clone self before writing. For write-only ops, that clone is wasted and survives as an Inductor fallback, doubling peak memory. Inductor's reinplacing pass only undid this for a hand-maintained inplaceable_ops registry.

This PR generalizes this to any functional op with a valid in-place variant when the buffer is dead:

  • Introduces new property OpOverload._inplace_variant using a naming convention + schema validation to identify an in-place variant
  • Marks reinplaced nodes in node.meta so GraphLowering can pass override_decomp appropriately, avoiding an error for reintroduced in-place ops with make_fallback's fallback-vs-decomp assertion

Covers _philox_uniform / _philox_normal, uniform / normal, and fallbacks like digamma / gcd. Note that bernoulli.Tensor is excluded because reinplacing to eager would break RNG determinism; a decomp should be added for this op variant instead (bernoulli.default already has one). This is left to a future PR.

Test Plan:

python -m pytest test/inductor/test_inplacing_pass.py \
  test/test_stateless_rng.py test/test_functionalization_of_rng_ops.py \
  "test/test_python_dispatch.py::TestDispatcherPythonBindings" -q

Alternative approach: signal to functionalization some other way that an op is write-only rather than read-modify-write, avoiding the need for reinplacing entirely.

Authored with assistance from 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 Jul 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 7 New Failures

As of commit 3b817f5 with merge base caf9663 (image):

NEW FAILURES - The following jobs have failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/torchtitan Run TorchTitan integration tests module: inductor labels Jul 6, 2026
@jbschlosser
jbschlosser requested a review from zou3519 July 6, 2026 19:54
@jbschlosser jbschlosser added module: performance Issues related to performance, either of kernel code or framework glue release notes: inductor topic: performance topic category labels Jul 6, 2026
pytorchmergebot pushed a commit that referenced this pull request Jul 7, 2026
Benchmark script (P2398638090) shows a performance issue with the new stateless RNG APIs within torch.compile. Tracked this down to the auto-generated functional variants of the new ops performing an extra clone. To address this, this PR:
* ~~Introduces explicit, non-autogenerated functional variants for the in-place ops that use `empty_like(self)` instead of `self.clone()` to indicate to functionalization that the data is completely overwritten and is not needed for correctness. This addresses the performance issue for the in-place ops, but still (briefly) results in a 2x allocation for an unused buffer alongside the output when the out-of-place APIs call the in-place ops.~~
* ~~Introduces new size-based overloads for the out-of-place APIs. Now they bypass the in-place ops entirely (preferring the size-based, out-of-place ops), avoiding the aforementioned 2x allocation.~~
* Adds `inplaceable_ops` registry entries for the philox uniform / normal ops. These will be unneeded once we land Inductor lowerings or a more general fix (e.g. #189080).

Pull Request resolved: #188495
Approved by: https://github.com/ngimel, https://github.com/zou3519
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude root-cause the CI failures

@claude

claude Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Claude finished @jbschlosser's task in 10m 45s —— View job


Root cause of the CI failures

Summary: The _maybe_inplaceable_op guard wrongly classifies aten.cumsum (and any op that has both a real lowering and a registered fallback handler) as reinplaceable, and reinplacing it to cumsum_ is invalid because cumsum on a bool/int input dtype-promotes to int64 — a result the in-place self buffer cannot hold.

Full analysis

The failing tests

All ~37 new failures collapse to one family: test_cumprod_backward* (plain, with_zeros, dynamic-shapes, cpp-wrapper, halide, triton-cpu variants). The DistillGPT2 / timm / torchbench / torchtitan failures are the same defect surfacing through models that hit cumprod backward or another dtype-promoting cumulative op.

Why cumprod backward triggers it

aten::cumprod_backward (aten/src/ATen/native/ReduceOps.cpp:684) contains:

const auto is_zero = input == 0;   // Bool tensor
...
const auto cumsum = is_zero.cumsum(dim);

So the backward graph contains an aten.cumsum.default node whose input is a Bool tensor. Inductor's cumsum lowering promotes bool/int to int64 (torch/_inductor/lowering.py:7686-7688):

if (is_integer_dtype(...) or is_boolean_dtype(...)) and dtype is None:
    dtype = torch.int64

The functional cumsum therefore returns an int64 tensor from a bool self.

The two-part root cause

1. The reinplacing guard fails to exclude cumsum.

In torch/_inductor/fx_passes/reinplace.py, _maybe_inplaceable_op is meant to skip ops that have a real lowering (the comment says "Reinplace only fallbacks (a real lowering allocates cleanly)"):

if (
    (target in lowerings and target not in fallbacks)
    or torch.Tag.inplace_view in inplace.tags
    or (inplace in lowerings and inplace not in fallbacks)
):
    return None

But cumsum has a real scan-based lowering and registers a fallback handler for the scan-failure path (torch/_inductor/lowering.py:7676):

fallback_cumsum = fallback_handler(aten.cumsum.default)   # adds cumsum.default to `fallbacks`

fallback_handler(..., add_to_fallback_set=True) puts aten.cumsum.default into the fallbacks set (lowering.py:2692-2694). So for cumsum:

  • target in lowerings → True (registered via @register_lowering(aten.cumsum))
  • target not in fallbacks → False (it's in fallbacks too)

True and False → the first clause is False, so the guard does not fire, and cumsum is treated as reinplaceable. cumsum.default._inplace_variant resolves to cumsum_.default (same arg/return shape, mutable arg0), so an InplaceableOp(cumsum_, 0) is synthesized. The class of ops with a real lowering that also seed a fallback handler (cumsum, cumprod, logcumsumexp, cummax, cummin, pow.Scalar, cat, ...) all slip through this way.

2. Reinplacing a dtype-promoting op is semantically invalid.

When is_zero is dead after the cumsum, the pass rewrites cumsum(bool) -> int64 into cumsum_ mutating the bool buffer in place. But cumsum promoted the result to int64, and the bool self cannot hold it — so the eager cumsum_out_cpu kernel receives a Bool self where int64 output is expected (exactly the HUD AI verdict: "a Bool-typed tensor reaches cumsum_out_cpu directly"). The schema check in OpOverload._inplace_variant (torch/_ops.py) only matches argument/return types structurally — it never verifies that the op's runtime output dtype equals self's dtype, which is precisely what breaks for type-promoting ops on integer/bool inputs.

override_decomp=True (via node.meta["reinplaced_from_functional"] in graph.py:1447-1451) then lets cumsum_ register as a fallback without tripping the decomp-vs-fallback assertion, so the bad rewrite reaches codegen instead of erroring earlier.

Suggested fixes (either or both)

  • Tighten the guard so an op with a genuine lowering is excluded even when it also appears in fallbacks. The and target not in fallbacks clause is the culprit — it was intended to let pure-fallback ops through, but membership in fallbacks is not mutually exclusive with having a real lowering. Consider a dedicated "pure fallback" predicate (in fallbacks and not registered as a real, non-fallback lowering), or track fallback-only registrations separately.
  • Add a dtype guard in _maybe_inplaceable_op (or _inplace_variant): only reinplace when the functional node's meta['val'] dtype matches the self arg's dtype. This is the robust fix — it defends against any type-promoting functional op whose in-place variant would need self to change dtype. The val dtypes are available on the FX node at reinplace time.

The second fix is the more fundamental one; the first prevents cumsum/cumprod/etc. from being considered at all and is worth having regardless.

The CI breakage is caused by _maybe_inplaceable_op reinplacing aten.cumsum (used inside cumprod_backward on a Bool tensor) into cumsum_, which is invalid because cumsum dtype-promotes bool/int inputs to int64 — the guard misses cumsum since it lives in both lowerings and fallbacks, and no dtype-match check protects against type-promoting ops.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Jul 7, 2026
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude root-cause the CI failures

@claude

claude Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Claude finished @jbschlosser's task in 5m 21s —— View job


Root-cause of the CI failures

Summary: All 7 reported failures are non-code issues. The 2 model-test failures are stale expected-accuracy CSVs on the PR branch (a trunk baseline bump for graph breaks never got merged in) — the "new graph breaks" the harness reports exactly match trunk's current expected counts, and the reinplace pass runs post-Dynamo so it cannot produce graph breaks. The other 5 are pure infra flakes (sccache, k8s pod, read-only HF cache).

Full analysis

Note: this is a different failure than my earlier cumsum analysis

My previous comment root-caused a cumsum/cumprod_backward crash. The current HEAD (3b817f5) already contains fixes for that — _maybe_inplaceable_op now has both a has_non_fallback_lowering guard and a preserves_dtype() check (torch/_inductor/fx_passes/reinplace.py). The crash is gone. The remaining failures are a completely different class: graph-break count mismatches.

The two real (non-infra) failures are stale CSVs

Both model-test failures report graph_breaks=N, expected=0:

Model Suite PR branch reports PR branch CSV expects Trunk main CSV expects
mobilenetv2_100 timm training 7 0 7
tf_efficientnet_b0 timm training 6 0 6
mnasnet1_0 torchbench training 7 0 7
mobilenet_v2 torchbench training 6 0 6
shufflenet_v2_x1_0 torchbench training 6 0 6

The observed counts match trunk's expected values exactly. Verified:

$ git show origin/main:benchmarks/dynamo/ci_expected_accuracy/inductor_timm_training.csv | grep -E "mobilenetv2_100|tf_efficientnet_b0"
mobilenetv2_100,pass,7
tf_efficientnet_b0,pass,6

$ git show origin/main:benchmarks/dynamo/ci_expected_accuracy/inductor_torchbench_training.csv | grep -E "mobilenet_v2,|mnasnet1_0|shufflenet_v2_x1_0"
mnasnet1_0,pass,7
mobilenet_v2,pass,6
shufflenet_v2_x1_0,pass,6

But this PR's base still has the old 0 baseline:

$ git show origin/gh/jbschlosser/279/base:.../inductor_torchbench_training.csv | grep -E "mobilenet_v2,|mnasnet1_0|shufflenet_v2_x1_0"
mnasnet1_0,pass,0
mobilenet_v2,pass,0
shufflenet_v2_x1_0,pass,0

So trunk bumped these graph-break baselines (for an unrelated reason — these are conv/batchnorm training models; the breaks are the standard training-mode breaks, not anything this PR introduces) after this stack was branched, and the stack never picked up that update.

Why this cannot be caused by the PR's code

The reinplacing pass (reinplace_inplaceable_ops_core) runs in Inductor's post-grad passes, after Dynamo has already traced and produced the FX graph. Dynamo graph breaks are decided during tracing, upstream of Inductor entirely. Nothing in reinplace.py, graph.py, or _ops.py in this PR can change the graph-break count. The log confirms the models compile fine (pass) — they only fail the check_graph_breaks.py count comparison against the stale CSV.

The other 5 failures are infra (matches HUD verdicts)

  • inductor ... test-osdc (inductor, 1, 2) — k8s CreateContainerError, no tests ran.
  • inductor ... test-osdc (inductor, 2, 2) — sccache: error: couldn't connect to server.
  • both torchtitan jobs — OSError: [Errno 30] Read-only file system on /mnt/hf_cache/datasets/.

None touch the reinplace path.

Recommended fix

Rebase the stack onto current main (or cherry-pick the trunk CSV bump), so the branch's inductor_timm_training.csv and inductor_torchbench_training.csv carry the updated expected counts. Alternatively, run:

python benchmarks/dynamo/ci_expected_accuracy/update_expected.py 3b817f571638870003138a4ac141017fdba7bfff

and git add the updated CSVs — though a plain rebase is cleaner since the new baselines already exist on trunk.

  • Fetch CI status & identify real (non-infra) failures
  • Download logs for the graph-break failures
  • Inspect PR changes to correlate with failures
  • Determine root cause & report
    · branch gh/jbschlosser/279/head

vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
Benchmark script (P2398638090) shows a performance issue with the new stateless RNG APIs within torch.compile. Tracked this down to the auto-generated functional variants of the new ops performing an extra clone. To address this, this PR:
* ~~Introduces explicit, non-autogenerated functional variants for the in-place ops that use `empty_like(self)` instead of `self.clone()` to indicate to functionalization that the data is completely overwritten and is not needed for correctness. This addresses the performance issue for the in-place ops, but still (briefly) results in a 2x allocation for an unused buffer alongside the output when the out-of-place APIs call the in-place ops.~~
* ~~Introduces new size-based overloads for the out-of-place APIs. Now they bypass the in-place ops entirely (preferring the size-based, out-of-place ops), avoiding the aforementioned 2x allocation.~~
* Adds `inplaceable_ops` registry entries for the philox uniform / normal ops. These will be unneeded once we land Inductor lowerings or a more general fix (e.g. pytorch#189080).

Pull Request resolved: pytorch#188495
Approved by: https://github.com/ngimel, https://github.com/zou3519
DamJanusz pushed a commit to DamJanusz/pytorch that referenced this pull request Jul 21, 2026
Benchmark script (P2398638090) shows a performance issue with the new stateless RNG APIs within torch.compile. Tracked this down to the auto-generated functional variants of the new ops performing an extra clone. To address this, this PR:
* ~~Introduces explicit, non-autogenerated functional variants for the in-place ops that use `empty_like(self)` instead of `self.clone()` to indicate to functionalization that the data is completely overwritten and is not needed for correctness. This addresses the performance issue for the in-place ops, but still (briefly) results in a 2x allocation for an unused buffer alongside the output when the out-of-place APIs call the in-place ops.~~
* ~~Introduces new size-based overloads for the out-of-place APIs. Now they bypass the in-place ops entirely (preferring the size-based, out-of-place ops), avoiding the aforementioned 2x allocation.~~
* Adds `inplaceable_ops` registry entries for the philox uniform / normal ops. These will be unneeded once we land Inductor lowerings or a more general fix (e.g. pytorch#189080).

Pull Request resolved: pytorch#188495
Approved by: https://github.com/ngimel, https://github.com/zou3519
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Benchmark script (P2398638090) shows a performance issue with the new stateless RNG APIs within torch.compile. Tracked this down to the auto-generated functional variants of the new ops performing an extra clone. To address this, this PR:
* ~~Introduces explicit, non-autogenerated functional variants for the in-place ops that use `empty_like(self)` instead of `self.clone()` to indicate to functionalization that the data is completely overwritten and is not needed for correctness. This addresses the performance issue for the in-place ops, but still (briefly) results in a 2x allocation for an unused buffer alongside the output when the out-of-place APIs call the in-place ops.~~
* ~~Introduces new size-based overloads for the out-of-place APIs. Now they bypass the in-place ops entirely (preferring the size-based, out-of-place ops), avoiding the aforementioned 2x allocation.~~
* Adds `inplaceable_ops` registry entries for the philox uniform / normal ops. These will be unneeded once we land Inductor lowerings or a more general fix (e.g. pytorch#189080).

Pull Request resolved: pytorch#188495
Approved by: https://github.com/ngimel, https://github.com/zou3519
@github-actions

github-actions Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Sep 6, 2026
@github-actions github-actions Bot closed this Oct 6, 2026
@github-actions
github-actions Bot deleted the gh/jbschlosser/279/head branch November 7, 2026 01:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: inductor module: performance Issues related to performance, either of kernel code or framework glue release notes: inductor Stale topic: performance topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant