Repository navigation
[precompile] Type Capture over fn's signature - #198529
bobrenjc93 wants to merge 5 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198529
Note: Links to docs will display an error until the docs builds have been completed. ❌ 2 New Failures, 2 Unrelated FailuresAs of commit d37b949 with merge base 12a7c44 ( 🟡 GREEN LIGHT - PR requires human review:
reason: NEW FAILURES - The following jobs have failed:
FLAKY - The following job failed but was likely due to flakiness present on trunk:
BROKEN TRUNK - The following job failed but was 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. |
|
@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions. |
|
Claude finished @bobrenjc93's task in 1m 10s —— View job I found no issues in this PR: making PR Review: #198529SummaryThe PR makes About the earlier reviews you mentioned: the thread I was given only has the two What I checked:
RecommendationApprove. It changes typing only, and the pyrefly scratch check in the test plan is appropriate. The PR still needs a |
[ghstack-poisoned]
|
@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions. |
|
Claude finished @bobrenjc93's task in 33s —— View job I found no issues: the diff is the same one the earlier review saw, and making PR Review: #198529SummaryThe PR makes Checking the earlier review and your replies: this thread has one earlier Claude review (19:26). It reported no findings, so there were no fixes to check. The thread has no replies from you and no inline review comments, so there were no dispositions to check either. If your replies are on another PR in the stack (for example #198135), link it and I'll check them there. I re-checked the current diff in
RecommendationApprove. It still needs a |
[ghstack-poisoned]
|
@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions. |
|
Claude finished @bobrenjc93's task in 22s —— View job I found no issues: the diff hasn't changed since the two earlier reviews, and making PR Review: #198529SummaryThe PR makes Checking the earlier reviews and your replies: this thread has two earlier Claude reviews (19:26 and 20:30). Neither reported any findings, so there are no fixes to check. The thread has no replies from you and no inline review comments, so there are no dispositions to check either. The diff in RecommendationApprove. It changes typing only. The PR still needs the |
[ghstack-poisoned]
|
@claude review this PR. Earlier bot reviews and my replies are in this thread; please verify the fixes and dispositions. |
|
Claude finished @bobrenjc93's task in 19s —— View job I found no issues. The diff is the same one the three earlier reviews saw, and the one open item from those reviews (the missing PR Review: #198529SummaryThe PR makes Checking the earlier reviews and your replies:
RecommendationApprove. CI still has checks pending. |
[ghstack-poisoned]
|
@claude review |
|
Claude finished @bobrenjc93's task in 37s —— View job I found no issues. The PR's own changes are the same as in the four earlier reviews; the new HEAD PR Review: #198529SummaryThe PR makes The four earlier Claude reviews (19:26, 20:30, 20:54, 22:23) reported no code findings, so there were no fixes to check. The one open item they raised, the missing The current diff in RecommendationApprove. |
|
Starting merge as part of PR stack under #198530 |
**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
…ts (#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 #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: #198530 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883, #198138, #198227, #198217, #198423, #198529
**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
**Summary.** `capture()` took `fn: Callable[..., object]` and `Capture.__call__` returned `object`, so calling a capture threw away `fn`'s types. The documented `y = cap(model, x); y.sum()` therefore failed type-checking, and every typed caller had to cast. `Capture` is now `Generic[_P, _R]` over `fn`'s signature, the same way `torch.compile` types its result with `_InputT`/`_RetT`, and `capture(fn: Callable[_P, _R], ...)` returns `Capture[_P, _R]`. Returning a `Callable[_P, _R]` would not work, because that type has no `__enter__` or `save()`. Nothing changes at runtime, and `load()` stays untyped, since it rebuilds the callable from disk. Review cleanup on `capture()` from pytorch#198135, stacked at the top like the lifecycle change below it. ```python def step(model: torch.nn.Module, x: torch.Tensor) -> torch.Tensor: return model(x) with capture(step, artifact_path="m.py", cache_path="m.cache") as cap: y = cap(model, x) # parent: y: object; now: y: Tensor y.sum() ``` Test Plan: No runtime behaviour changes. To check the typing, I ran pyrefly on a scratch caller: `y = cap(torch.nn.Linear(2, 2), torch.randn(2))` infers `y: Tensor`, and `cap("not a module", 3)` is reported as two `bad-argument-type` errors. No CI check pins this inference. ``` 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#198529 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, pytorch#198423
…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
Stack from ghstack (oldest at bottom):
Summary.
capture()tookfn: Callable[..., object]andCapture.__call__returnedobject, so calling a capture threw awayfn's types. The documentedy = cap(model, x); y.sum()therefore failed type-checking, and every typed caller had to cast.Captureis nowGeneric[_P, _R]overfn's signature, the same waytorch.compiletypes its result with_InputT/_RetT, andcapture(fn: Callable[_P, _R], ...)returnsCapture[_P, _R]. Returning aCallable[_P, _R]would not work, because that type has no__enter__orsave(). Nothing changes at runtime, andload()stays untyped, since it rebuilds the callable from disk.Review cleanup on
capture()from #198135, stacked at the top like the lifecycle change below it.Test Plan:
No runtime behaviour changes. To check the typing, I ran pyrefly on a scratch caller:
y = cap(torch.nn.Linear(2, 2), torch.randn(2))infersy: Tensor, andcap("not a module", 3)is reported as twobad-argument-typeerrors. No CI check pins this inference.Authored with an AI assistant.
Co-Authored-By: Claude Opus 5.5 [email protected]