Skip to content

[precompile] Snapshot only tensor leaves in _trace_without_side_effects - #198530

Closed
bobrenjc93 wants to merge 5 commits into
gh/bobrenjc93/1487/basefrom
gh/bobrenjc93/1487/head
Closed

bobrenjc93 wants to merge 5 commits into
gh/bobrenjc93/1487/basefrom
gh/bobrenjc93/1487/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. _trace_without_side_effects snapshots the buffers and tensor inputs a static trace could mutate, so the serve that follows is the only execution the caller sees. It built tensors from the module buffers plus every pytree leaf of args, the modules themselves and any non-tensor leaves included, and applied isinstance(t, torch.Tensor) only inside the snapshot comprehension. The leaves are now filtered to tensors up front, so tensors holds only tensors and the snapshot needs no type check. The parameter-exclusion set loses the non-tensor ids too, which never matched anything because a live non-tensor object cannot share an id with a live parameter. What gets snapshotted is unchanged; this is review cleanup from #198243, which is approved, so it lands here at the top of the stack instead of in that commit.

# parent
leaves = pytree.tree_leaves(args)
saved = {id(t): (t, t.detach().clone()) for t in tensors if isinstance(t, torch.Tensor) and id(t) not in params}
# now
leaves = [t for t in pytree.tree_leaves(args) if isinstance(t, torch.Tensor)]
saved = {id(t): (t, t.detach().clone()) for t in tensors if id(t) not in params}

Test Plan:

test_a_capture_applies_in_place_updates_once, test_a_capture_refuses_an_in_place_parameter_update and test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were in test/test_precompile.py cover this path and pass unchanged.

python test/test_precompile.py
lintrunner -a torch/_precompile.py

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 [email protected]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 4 Unrelated Failures

As of commit f920c6b with merge base 12a7c44 (image):

🟢 GREEN LIGHT - PR approved to be merged without human review:

  • Triviality
    • Behavior-neutral tweak: leaves in _trace_without_side_effects is filtered to tensors up front, so saved drops its own isinstance check
    • saved holds the same tensors: m.buffers() yields only tensors, and the tensor filter now applies to the leaf half of tensors
  • Correctness
    • params no longer subtracts non-tensor leaf ids; args keeps those objects alive, so none can share an id with a live parameter
    • The finally restore loop and the _writes_a_parameter refusal in torch/_precompile.py are unchanged
  • Socialization
    • _trace_without_side_effects is a private method; no signature, default, or message changes

reason: clean
Reviewed commit: f920c6b

Inference job

🐛 Report a wrong verdict

NEW FAILURE - The following job has failed:

  • trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (gh)
    test/test_ops.py::TestCommonMPS::test_noncontiguous_samples_scatter_reduce_amin_mps_int64

    AI verdict: AI verdict: probably not related

    The MPS scatter_reduce_amin int64 test fails because the Metal driver refuses to compile the kernel ("Unsupported float atomic operation for given target"). The suspect PR only touches precompile/dynamo-package Python code, so the MPS code is the same as at the green merge base. The failing run used a macOS 15.7.1 runner; the passing baseline used macOS 14.8.1.

    Full reasoning on HUD →

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

  • trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (gh)
    test/test_ops.py::TestCommonMPS::test_dtypes_scatter_reduce_amax_mps

    AI verdict: AI verdict: not related

    The PR only changes how _trace_without_side_effects in torch/_precompile.py filters pytree leaves. The failure is a Metal pipeline-compile error for the int64 scatter_reduce amax kernel on an M1 runner. That error comes from main-side MPS kernel and OpInfo code, and the same test name appears on many unrelated PRs (other precompile PRs, kleidiai, ROCm, dynamo, inductor).

    Full reasoning on HUD →

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but were present on the merge base:

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

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

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 30s —— View job


No issues found. This PR is a behavior-preserving cleanup of _trace_without_side_effects, and I recommend approving it.

PR Review: #198530

Summary

The change filters pytree.tree_leaves(args) down to tensors up front (torch/_precompile.py:657), so the isinstance check in the snapshot dict comprehension (:660) is no longer needed.

I checked that nothing else changes:

  • params: it now subtracts only tensor-leaf ids, where it used to subtract the ids of every leaf. The dropped ids belong to modules and non-tensor leaves. Those objects are alive and distinct from every parameter, so none of them could ever have matched a parameter id.
  • tensors: m.buffers() already skips None buffers, so the list still holds only tensors.
  • saved: it snapshots exactly the same set of tensors as before, and the restore loop in finally is untouched.

Earlier bot reviews and replies: this thread has no earlier bot review comments or replies from you, so there were no fixes or dispositions to check. If they're on #198243, that PR is where they apply. The only thing this PR takes from it is the cleanup, and that cleanup is correct.

CI: the red jobs all fail with sits on top of >=10 ghstack entries; refusing to run CI. That comes from the depth of the stack, not from this change.

Recommendation

Approve. This is a pure refactor, and the existing tests (test_a_capture_applies_in_place_updates_once, test_a_capture_refuses_an_in_place_parameter_update, test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were) cover this path.

[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [precompile] Snapshot only tensor leaves in _trace_without_side_effects [no-ci] [precompile] Snapshot only tensor leaves in _trace_without_side_effects Sep 24, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 26s —— View job


No issues found. This PR only cleans up _trace_without_side_effects and doesn't change what it does.

PR Review: #198530

Summary

The PR filters pytree.tree_leaves(args) down to tensors before building params and tensors, so the snapshot comprehension no longer needs its own isinstance check (torch/_precompile.py:657-660).

I checked three things:

  • params: the ids no longer subtracted belong to modules and other non-tensor leaves. args holds those objects alive the whole time, so their ids can't collide with a parameter's id. The set comes out the same as before.
  • tensors: m.buffers() skips None buffers, so the list still holds only tensors.
  • saved and the restore: the same tensors get snapshotted, and the finally restore loop didn't change.

Earlier bot reviews and replies: #198530 has no inline review comments, no earlier bot review threads and no replies from you, so there are no fixes or dispositions to check here. If you meant the threads on #198243, this PR does carry out its cleanup correctly.

CI: every red job fails with sits on top of >=10 ghstack entries; refusing to run CI. That comes from how deep the stack is, not from this change.

Recommendation

Approve. This is a pure refactor. test_a_capture_applies_in_place_updates_once, test_a_capture_refuses_an_in_place_parameter_update and test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were already cover this path.

[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [no-ci] [precompile] Snapshot only tensor leaves in _trace_without_side_effects [precompile] Snapshot only tensor leaves in _trace_without_side_effects Sep 24, 2026
@bobrenjc93
bobrenjc93 requested a review from aorenste September 24, 2026 21:02
@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 24, 2026 21:02
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 27s —— View job


No issues found. This PR only cleans up _trace_without_side_effects and snapshots exactly the same tensors as before.

PR Review: #198530

Summary

The PR filters pytree.tree_leaves(args) down to tensors up front (torch/_precompile.py:659), so the snapshot comprehension at :662 no longer needs its own isinstance check. I found no issues.

  • params: the ids it no longer subtracts belong to modules and other non-tensor leaves. args keeps those objects alive, so none of them can share an id with a parameter, and the set comes out the same.
  • tensors: m.buffers() skips None buffers, so the list still holds only tensors.
  • Restore: the same tensors get snapshotted, and the finally loop that puts them back didn't change.

Earlier bot reviews and your replies: the two earlier bot reviews in this thread both recommended approving and raised no findings. There are no inline review comments and no replies from you here, so there are no fixes or dispositions to check. Both earlier reviews blamed the red CI on the ghstack depth guard, but Dr. CI now reports a different cause.

CI: all 5 red jobs now fail with CI is disabled by the [no-ci] PR title prefix. The PR title shown here has no such prefix, so it may have been removed after the last push. Pushing a new commit should re-run CI. None of these failures come from this change.

Recommendation

Approve. This is a pure refactor. test_a_capture_applies_in_place_updates_once, test_a_capture_refuses_an_in_place_parameter_update and test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were already cover this path.

@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Sep 24, 2026
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions.

@claude

claude Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 27s —— View job


No issues found. This PR is a cleanup of _trace_without_side_effects that snapshots exactly the same tensors as before, and I recommend approving it.

PR Review: #198530

Summary

The PR filters pytree.tree_leaves(args) down to tensors up front (torch/_precompile.py:659), so the snapshot comprehension at :662 no longer needs its own isinstance check. The diff is the same as at the last review, and I found no issues.

  • params (:660): the ids no longer subtracted belong to modules and other non-tensor leaves. args keeps those objects alive, so none of them can share an id with a parameter, and the set comes out the same.
  • tensors (:661): m.buffers() skips None buffers, so the list still holds only tensors.
  • Restore (:665-671): the same tensors get snapshotted, and the finally loop that puts them back didn't change.

Earlier bot reviews and your replies: the three earlier bot reviews in this thread all recommended approving and raised no findings. There are no inline review comments and no replies from you on this PR, so there are no fixes or dispositions to check. pytorchgreenlight has since approved the PR.

CI: CI is running again now. The earlier [no-ci] and ghstack-depth failures are gone. Lint, BC Lint, TSan and the ghstack mergeability check pass. trunk, pull and docs-build are still pending, and nothing has failed.

Recommendation

Approve. This is a pure refactor. test_a_capture_applies_in_place_updates_once, test_a_capture_refuses_an_in_place_parameter_update and test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were already cover this path.

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 31s —— View job


No issues found. This PR is a behavior-preserving cleanup of _trace_without_side_effects, and I recommend approving it.

PR Review: #198530

Summary

The PR filters pytree.tree_leaves(args) down to tensors up front (torch/_precompile.py:659), so the snapshot comprehension at :662 no longer needs its own isinstance check. The diff is the same as at the previous four reviews, and I found no issues.

  • params (:660): the ids it no longer subtracts belong to modules and other non-tensor leaves. args keeps those objects alive, so none of them can share an id with a parameter, and the set comes out the same.
  • tensors (:661): m.buffers() skips None buffers, so the list still holds only tensors. A buffer that is also passed as a leaf shows up twice, but saved is keyed by id, so it's still snapshotted once.
  • Restore (:665-671): the same tensors get snapshotted, and the finally loop that puts them back didn't change.

Earlier bot reviews and your replies: the four earlier bot reviews in this thread all recommended approving and raised no findings. There are no inline review comments and no replies from you on this PR, so there are no fixes or dispositions to check. pytorchgreenlight has approved the PR.

Recommendation

Approve. This is a pure refactor. test_a_capture_applies_in_place_updates_once, test_a_capture_refuses_an_in_place_parameter_update and test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were already cover this path.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 30 checks: trunk / dynamo-unittest / dynamo-test (3.11) / test (dynamo_wrapped, 4, 7, mt-l-x86iavx512-8-64) (#198138), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (#198138), trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (#198138), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (#198138), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable) (#198138), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 2, mt-l-x86iamx-8-64, unstable) (#198138), pull / linux-jammy-py3.10-clang21 / test (dynamo_wrapped, 6, 6, mt-l-x86iavx512-8-64) (#198138), trunk / dynamo-unittest / dynamo-test (3.11) / test (dynamo_wrapped, 2, 7, mt-l-x86iavx512-8-64) (#198227), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (#198227), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (#198227), trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (#198227), pull / linux-jammy-py3.10-clang21 / test (dynamo_wrapped, 5, 6, mt-l-x86iavx512-8-64) (#198227), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (#198217), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (#198217), trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (#198217), pull / linux-jammy-py3.10-clang21 / test (dynamo_wrapped, 1, 6, mt-l-x86iavx512-8-64) (#198217), pull / linux-jammy-py3.10-clang21 / test (dynamo_wrapped, 4, 6, mt-l-x86iavx512-8-64) (#198423), trunk / dynamo-unittest / dynamo-test (3.11) / test (dynamo_wrapped, 7, 7, mt-l-x86iavx512-8-64) (#198423), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (#198423), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (#198423), trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (#198423), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (#198529), trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (#198529), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (#198529), pull / linux-jammy-py3.10-clang21 / test (dynamo_wrapped, 4, 6, mt-l-x86iavx512-8-64) (#198529), pull / linux-jammy-py3.10-clang21 / test (dynamo_wrapped, 5, 6, mt-l-x86iavx512-8-64) (#198530), trunk / dynamo-unittest / dynamo-test (3.11) / test (dynamo_wrapped, 2, 7, mt-l-x86iavx512-8-64) (#198530), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (#198530), trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (#198530), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (#198530)

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

pytorchmergebot pushed a commit that referenced this pull request Oct 10, 2026
**Problem.** Each tracer's capture ran its own `with`-block lifecycle from its own flags, so a Dynamo capture misused after its block gave different errors than a make_fx one, and a spent make_fx capture kept the pair its docstring says it drops.

**Fix.** `Capture` owns the lifecycle as one state field under one lock, and the tracers implement only the hooks it calls.

**Summary.** `_MakeFxCapture` tracked its block with two booleans, `_entered` and `_exited`, which are really three states, and `_DynamoCapture` kept its own `_exited` flag and its own copies of `__enter__`, `__exit__`, `__call__` and `save()`. The two front-ends therefore drifted: a Dynamo capture called after its block said "not active" where make_fx says "already exited", and make_fx's `__exit__` never cleared the pair that `Capture`'s docstring says a spent capture does not keep. `Capture` now holds the lifecycle as one field, `new`/`active`/`spent`, owns the four methods and their not-active, already-entered and spent messages, and a tracer implements only `_start`, `_run`, `_save` and `_finish`, where `_finish` drops the pair on every exit. The Dynamo capture's `RLock`, which serializes the block's calls, saves, exit and `summary()` because every call feeds one `PrecompileSession`, moves into `Capture` with the lifecycle. The messages a make_fx capture gives do not change, and a Dynamo capture now gives the same ones.

These are review cleanups on `capture()` from #198135; that PR and #198243 are approved, so both are left as they are. The `Generic` typing of `Capture` and the tensor-only leaves snapshot that earlier revisions of this PR carried now live in #198529 and #198530.

## What a Dynamo capture says now

```python
cap = capture(fn, ...)          # a DynamoTracer capture
cap(x)                          # "before calling it" (unchanged)
with cap:
    with cap: ...               # "already been entered" (unchanged)
cap(x)                          # after the block: a call, save() or `with cap:`
# parent: "not active" / "already been entered"
# now:    "already exited", the same as make_fx
```

The `save()` checkpoint contract moves from `_DynamoCapture`'s override onto the public `Capture.save` docstring, since it holds for both tracers and `help(cap.save)` shows only the base docstring: each call rewrites both files, a refusal or failed write raises but writes nothing partial and the capture stays open, and it raises `PrecompileError` outside the `with` block. `test_calls_from_several_threads_are_serialized` pins the lock.

Test Plan:

`test_misuse_is_refused` in `TestPrecompileDynamoCapture` moves to the shared messages, and `test_save_checkpoints_mid_block` now expects "already exited" for a save after exit. The make_fx lifecycle tests pass without changes (`test_a_capture_must_be_entered_before_it_is_called`, `test_a_capture_is_over_once_its_block_exits`, `test_save_after_a_raising_block_is_refused`, `test_a_capture_is_single_use`), which pins that its messages did not move.

```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_precompile.py test/test_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: #198423
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883, #198138, #198227, #198217
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
**Problem.** Each tracer's capture ran its own `with`-block lifecycle from its own flags, so a Dynamo capture misused after its block gave different errors than a make_fx one, and a spent make_fx capture kept the pair its docstring says it drops.

**Fix.** `Capture` owns the lifecycle as one state field under one lock, and the tracers implement only the hooks it calls.

**Summary.** `_MakeFxCapture` tracked its block with two booleans, `_entered` and `_exited`, which are really three states, and `_DynamoCapture` kept its own `_exited` flag and its own copies of `__enter__`, `__exit__`, `__call__` and `save()`. The two front-ends therefore drifted: a Dynamo capture called after its block said "not active" where make_fx says "already exited", and make_fx's `__exit__` never cleared the pair that `Capture`'s docstring says a spent capture does not keep. `Capture` now holds the lifecycle as one field, `new`/`active`/`spent`, owns the four methods and their not-active, already-entered and spent messages, and a tracer implements only `_start`, `_run`, `_save` and `_finish`, where `_finish` drops the pair on every exit. The Dynamo capture's `RLock`, which serializes the block's calls, saves, exit and `summary()` because every call feeds one `PrecompileSession`, moves into `Capture` with the lifecycle. The messages a make_fx capture gives do not change, and a Dynamo capture now gives the same ones.

These are review cleanups on `capture()` from pytorch#198135; that PR and pytorch#198243 are approved, so both are left as they are. The `Generic` typing of `Capture` and the tensor-only leaves snapshot that earlier revisions of this PR carried now live in pytorch#198529 and pytorch#198530.

## What a Dynamo capture says now

```python
cap = capture(fn, ...)          # a DynamoTracer capture
cap(x)                          # "before calling it" (unchanged)
with cap:
    with cap: ...               # "already been entered" (unchanged)
cap(x)                          # after the block: a call, save() or `with cap:`
# parent: "not active" / "already been entered"
# now:    "already exited", the same as make_fx
```

The `save()` checkpoint contract moves from `_DynamoCapture`'s override onto the public `Capture.save` docstring, since it holds for both tracers and `help(cap.save)` shows only the base docstring: each call rewrites both files, a refusal or failed write raises but writes nothing partial and the capture stays open, and it raises `PrecompileError` outside the `with` block. `test_calls_from_several_threads_are_serialized` pins the lock.

Test Plan:

`test_misuse_is_refused` in `TestPrecompileDynamoCapture` moves to the shared messages, and `test_save_checkpoints_mid_block` now expects "already exited" for a save after exit. The make_fx lifecycle tests pass without changes (`test_a_capture_must_be_entered_before_it_is_called`, `test_a_capture_is_over_once_its_block_exits`, `test_save_after_a_raising_block_is_refused`, `test_a_capture_is_single_use`), which pins that its messages did not move.

```
python test/test_precompile.py
python test/dynamo/test_precompile_package.py
lintrunner -a torch/_precompile.py test/test_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: pytorch#198423
Approved by: https://github.com/MengjiaoZhou
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883, pytorch#198138, pytorch#198227, pytorch#198217
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ts (pytorch#198530)

**Summary.** `_trace_without_side_effects` snapshots the buffers and tensor inputs a static trace could mutate, so the serve that follows is the only execution the caller sees. It built `tensors` from the module buffers plus every pytree leaf of `args`, the modules themselves and any non-tensor leaves included, and applied `isinstance(t, torch.Tensor)` only inside the snapshot comprehension. The leaves are now filtered to tensors up front, so `tensors` holds only tensors and the snapshot needs no type check. The parameter-exclusion set loses the non-tensor ids too, which never matched anything because a live non-tensor object cannot share an id with a live parameter. What gets snapshotted is unchanged; this is review cleanup from pytorch#198243, which is approved, so it lands here at the top of the stack instead of in that commit.

```python
# parent
leaves = pytree.tree_leaves(args)
saved = {id(t): (t, t.detach().clone()) for t in tensors if isinstance(t, torch.Tensor) and id(t) not in params}
# now
leaves = [t for t in pytree.tree_leaves(args) if isinstance(t, torch.Tensor)]
saved = {id(t): (t, t.detach().clone()) for t in tensors if id(t) not in params}
```

Test Plan:

`test_a_capture_applies_in_place_updates_once`, `test_a_capture_refuses_an_in_place_parameter_update` and `test_a_trace_that_raises_leaves_buffers_and_inputs_as_they_were` in test/test_precompile.py cover this path and pass unchanged.

```
python test/test_precompile.py
lintrunner -a torch/_precompile.py
```

Authored with an AI assistant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Pull Request resolved: pytorch#198530
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: pytorch#198211, pytorch#198223, pytorch#198283, pytorch#198284, pytorch#197993, pytorch#198213, pytorch#198135, pytorch#198243, pytorch#198214, pytorch#198136, pytorch#198215, pytorch#198137, pytorch#198216, pytorch#198528, pytorch#199883, pytorch#198138, pytorch#198227, pytorch#198217, pytorch#198423, pytorch#198529
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants