Repository navigation
[precompile] Keep one lifecycle state in Capture - #198423
bobrenjc93 wants to merge 7 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198423
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 4 Unrelated FailuresAs of commit 7e0a61e with merge base 12a7c44 ( 🟡 GREEN LIGHT - PR requires human review:
reason: NEW FAILURE - The following job has failed:
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:
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. |
|
New PR carrying aorenste's four cleanups on #198135 and one on #198243 (both approved, so left as they are): the Capture lifecycle is now one state field, Capture is typed over fn's signature, the pair is dropped at exit, and the one-call docstrings are reworded. @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 7s —— View job The refactor matches its description, with one question: the new PR Review: #198423SummaryThe lifecycle state now lives in one field on
I couldn't check earlier dispositions: the context I was given has no earlier bot reviews or replies, only the Dr. CI comment. If they are on #198135 or #198243, point me at them and I'll check those replies. Thread Safety
Testing
RecommendationNeeds Discussion: justify or drop the lock. The rest of the refactor looks correct and does not change behavior. |
[ghstack-poisoned]
…s signature Review cleanups on `capture()` from #198135. That PR and #198243 above it are approved, so both are left as they are, and this commit sits at the top of the stack so no other PR has to be rebased onto it. `Capture.__call__` returned `object`, so the documented `y = cap(model, x); y.sum()` 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()`. `load()` stays untyped, since it rebuilds the callable from disk. `_MakeFxCapture` tracked its block with two booleans, `_entered` and `_exited`, which are really three states. The lifecycle now lives in `Capture` as one field, `new`/`active`/`spent`. `Capture` owns `__enter__`, `__exit__`, `__call__` and `save()`, including the not-active, already-entered and spent messages. A tracer implements only `_start`, `_run`, `_save` and `_finish`. `_DynamoCapture` moves onto the same hooks and drops its own `_exited` flag, so the two front-ends cannot drift: a Dynamo capture now answers a call before its block with the "before calling it" message, a nested `with` with "already been entered", and a call, `save()` or `with` after exit with "already exited". Its `RLock`, which serializes the block's calls, saves, exit and `summary()` because every call feeds one `PrecompileSession`, moves into `Capture` with the lifecycle; `test_calls_from_several_threads_are_serialized` pins it. `Capture`'s docstring says the spent capture does not keep its pair, but `__exit__` never cleared it. `_finish` now drops the pair on every exit. The `capture()` docstring is left as it is: `DynamoTracer` is the default by this point in the stack, so its multi-call wording is right. From #198243's review, `_trace_without_side_effects` now filters `args`' leaves to tensors up front. `tensors` therefore holds only tensors, not also the module arguments and non-tensor leaves, and the snapshot no longer needs an `isinstance` check. Test Plan: `test_misuse_is_refused` in `TestPrecompileDynamoCapture` is updated to the shared messages, and `test_save_checkpoints_mid_block` to "already exited" for a save after exit. The existing make_fx lifecycle tests (`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`) pass unchanged, which pins that the messages did not move. 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 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]> ghstack-source-id: d0b722c Pull-Request: #198423
|
Replies to the bot review above (5803299052). This PR has also moved to the top of the stack, so no other PR has to be rebased onto it. RLock: justify or drop. Justified, and it now sits where it is needed. The lock was never new: Typing not pinned in CI. Agreed; no repo-level check covers it. The Test Plan now says "No CI check pins this inference." I have not added a typed test file, because |
|
@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 8s —— View job Both earlier findings are resolved in the code. What remains is a stale PR description and one public docstring that was lost in the move. PR Review: #198423SummaryThis PR moves the capture lifecycle into Earlier findings:
Code Quality
API Design
RecommendationApprove once the description is refreshed and the |
[ghstack-poisoned]
[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 45s —— View job The PR's diff is the same as the one approved last round (the only change since PR Review: #198423SummaryThis PR moves the capture lifecycle into Earlier findings, re-checked on
Other checks:
RecommendationApprove: neither the code nor the description needs further changes. |
[ghstack-poisoned]
|
@claude review |
|
Claude finished @bobrenjc93's task in 49s —— View job This PR's diff is the same as the one approved last round, and I found no new issues. The new commit PR Review: #198423SummaryThis PR moves the capture lifecycle into What changed since the last review (
Earlier findings, re-checked on
RecommendationApprove: neither the code nor the description needs further changes. |
|
Starting merge as part of PR stack under #198530 |
#198138) **Problem.** `torch.compiler.precompile.capture()` only took a `MakeFxTracer`: one positional call, one ATen trace, no graph breaks, no recompiled variants, no keyword arguments. The `PrecompileSession` of the previous commits can record all of those, but nothing in the public module reached it. **Fix.** Add `DynamoTracer`, the multi-graph front-end passed as `tracer=`, and `_DynamoCapture`, the `Capture` that drives a `PrecompileSession` across as many calls as the block makes and writes the standalone artifact on a clean exit, so `load()` serves it in a fresh process. **Summary.** `capture()` accepted a `MakeFxTracer` and nothing else, so a function with a graph break, a shape-dependent branch or a keyword argument could not be precompiled through `torch.compiler.precompile` even though `PrecompileSession` and `snapshot_artifact` could already record and render such captures. This commit adds `DynamoTracer(guard_filter_fn, recompile_limit, dynamic, require_complete, require_no_risky_drops)` beside `MakeFxTracer`, and `_DynamoCapture`, which runs the block under a fresh `CacheArtifactManager` cache, serializes its calls under an `RLock`, counts attempted calls, refuses a recursive re-entry, and writes the pair behind the two `require_*` gates on a clean exit only. The artifact is standalone, so `fn` must be a module-level function of an importable module, an artifact whose capture graph-broke cannot load beside the live compile that captured it (the continuation names collide, and `load` says so), and it is locked to the producing Python version and torch build. A Dynamo capture runs every call in the caller's grad mode and lowers a backward whenever grad is enabled, so a training step that calls `.backward()` is captured like any other call and the served artifact accumulates `.grad` like eager. `MakeFxTracer` stays the default for two more commits, package and recompile errors surface as `PrecompileError`, and mid-block `save()` is the next commit's, so `save()` on this tracer raises a `PrecompileError` saying its artifact is written when the block exits. ## Where this fits The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like, the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in #197993's "The new API, end to end" section. This PR is where `capture()` becomes multi-call: `DynamoTracer` takes as many calls as the caller makes and folds every graph break and recompile they exercise into one artifact. It becomes the default tracer in #198217. The Python 3.10 `-bb` fix to the code-constant walk in `_find_code_source`, which the recursive-capture test here first exercises, lives in #198528 directly below. ## The golden path The new tests write a module with a graph-breaking step, capture it over two shapes and a keyword default, and serve it in a fresh process: ```python # precompile_golden_<uuid>.py, importable from sys.path def step(model, x, *, scale=1.0): y = model(x) * scale * SCALE torch._dynamo.graph_break() if y.shape[0] > 2: y = y + 1 return y.sum(dim=0) ``` ```python from torch.compiler.precompile import capture, DynamoTracer, load with capture(step, artifact_path="m.py", cache_path="m.cache", tracer=DynamoTracer(), backend="inductor") as cap: y2 = cap(model, x2) # step and its graph-break continuation y3 = cap(model, x3, scale=0.5) # the branch recompiles the continuation; the keyword is a second entry variant # exit: TRACER = "dynamo", SERVING_MODE = "standalone", FN_NAME = 'step' in m.py load("m.py", "m.cache") # in this process: PrecompileError, the message says to use a fresh process ``` ```python # a fresh process f = torch.compiler.precompile.load("m.py", "m.cache") f(model, x2) # == y2 f(model, x3, scale=0.5) # == y3 f(model, x2.double()) # PrecompileError: no captured variant ``` The last line is the standalone contract: there is no compiler behind a source artifact, so a call no variant covers raises rather than silently serving. `test_graph_breaks_and_recompiles_round_trip_in_a_fresh_process` pins this on both backends, including the in-process collision refusal; `test_a_single_graph_serves_in_process` pins the no-graph-break case, where `load` works in the capturing process, `f.installed` is false, `with f:` and `f.unload()` are no-ops, a second `Model()` swaps weights in, and `f(model, x3)` after a shape-2 capture raises `no captured variant`. ## `DynamoTracer` carries the multi-graph knobs ```python @dataclasses.dataclass(frozen=True) class DynamoTracer: guard_filter_fn: Callable[[Sequence[Any]], Sequence[bool]] | None = None recompile_limit: int = 256 dynamic: bool | None = None require_complete: bool = True require_no_risky_drops: bool = True ``` `guard_filter_fn` takes the `GuardFilterEntry` records (`guard_type`, `name`, ...) and returns one keep flag per entry, filtering the guards kept in the serialized artifact (runtime capture guards are always retained; the default drops only what cannot be serialized). `recompile_limit` caps recompilations per frame: a call past it runs eager and is absent from the artifact without any gate refusing it, which the docstring states. `dynamic` forces dynamic shapes as `torch.compile(dynamic=)` does. The `require_*` gates refuse, at write time, an artifact with a coverage gap (`require_complete`: a bypassed or uncovered frame, a call that raised) or one whose dropped guards told captured variants apart or hang off a configuration-chosen slot (`require_no_risky_drops`). Other dropped guards, such as the identity guards every model drops because they cannot be serialized, are listed in the artifact rather than refused; there is deliberately no gate that refuses every drop, since every capture would trip it. The annotation stays `Sequence[Any]` rather than naming `GuardFilterEntry`, because torch/compiler/precompile.py resolves the re-homed classes' annotations with `typing.get_type_hints` at import. ```python DynamoTracer(dynamic=True) # capture single on x2 -> the artifact serves x3 too DynamoTracer(guard_filter_fn=drop_x) # exit: PrecompileError "can affect dispatch" DynamoTracer(guard_filter_fn=drop_x, require_no_risky_drops=False) # writes an artifact that loads DynamoTracer(dynamic=False, recompile_limit=1) # cap(x2); cap(x3) -> served x3 raises "no captured variant" ``` `test_the_tracer_knobs_reach_the_session` pins all four lines, where `drop_x` drops the guard on `x` on top of `default_guard_filter_fn` (dropping what tells the shapes apart). `test_dropped_guards_are_listed_in_the_artifact` shows the default capture of `single` listing `['MODULE_MATCH', ...` in the artifact's dropped guards and writing the artifact regardless. ## `capture()` dispatches on the tracer ```python tracer: MakeFxTracer | DynamoTracer = MakeFxTracer() ... if isinstance(tracer, MakeFxTracer): return _MakeFxCapture(fn, artifact_path, cache_path, backend=backend, decompositions=tracer.decompositions) if not isinstance(tracer, DynamoTracer): raise TypeError("precompile.capture tracer must be a MakeFxTracer or DynamoTracer, got ...") if backend not in ("inductor", "eager"): raise ValueError(f"precompile backend must be 'inductor' or 'eager', got {backend!r}.") try: session = precompile_capture(fn, backend=backend, guard_filter_fn=tracer.guard_filter_fn, recompile_limit=tracer.recompile_limit, dynamic=tracer.dynamic) except PackageError as e: raise PrecompileError(str(e)) from e return _DynamoCapture(session, artifact_path, cache_path, require_complete=..., require_no_risky_drops=...) ``` The make_fx front-end validates `backend` when it builds its `PrecompiledModule`; the Dynamo front-end builds none, so `capture()` checks it before creating the session. `precompile_capture`'s up-front refusals now surface as `PrecompileError`. `test_entries_a_standalone_artifact_cannot_rebuild_are_refused` pins the entries a standalone artifact cannot rebuild: a bare `nn.Module` is refused by `capture()` itself (`CALLS the model`: Dynamo compiles its wrapper frame, whose graphs close over the module), and a closure entry is refused once the block calls it (`closes over`), since a code object cannot rebuild what the closure captured. A `functools.partial` never reaches the tracer: `capture()` refuses it with a `TypeError` (`takes the function itself, not a functools.partial`) before dispatching. `_MakeFxCapture`'s two refusals (a keyword argument, a second call) now point at `tracer=DynamoTracer()` instead of just explaining themselves. ## `_DynamoCapture` drives the session Entering the block opens a fresh cache before the session, and undoes it if the session refuses to enter: ```python def __enter__(self): with self._lock: if self._call is not None or self._exited: raise PrecompileError("this capture has already been entered; capture() returns a fresh capture per call.") self._fresh_cache = CacheArtifactManager.with_fresh_cache() self._fresh_cache.__enter__() try: self._call = self._map(self._session.__enter__) except BaseException: self._fresh_cache.__exit__(None, None, None) self._fresh_cache = None raise return self ``` The capture's compiles record into the process-global cache-artifact list, which the cache half of the artifact bundles to prime the kernel caches on load; a fresh one means the bundle holds only this capture's compiles. The swap spans the whole `with` block, not just the calls, so the `capture()` docstring now says a `DynamoTracer` capture records the kernel-cache artifacts of everything compiled inside the block: compile nothing else there, and do not overlap two such captures. `_map` is the one place `PackageError` and `RecompileError` become `PrecompileError`. Each call is serialized under an `RLock`, refuses a call before `__enter__` or after `__exit__` (`capture is not active`), refuses `fn` calling the capture it is being captured through (`re-entered recursively`), and counts the call before it runs: ```python def __call__(self, *args, **kwargs): with self._lock: ... self._in_call = True # Counted before the call: a call that raised is for the session's # require_complete gate to report, not "nothing was captured". self._calls += 1 try: return self._map(self._call, *args, **kwargs) finally: self._in_call = False ``` The lock is what makes concurrent callers safe: every call feeds the one session, and without it a call that finds another thread's call in flight would trip the `_in_call` check and be refused as a recursive re-entry. `test_calls_from_several_threads_are_serialized` starts eight threads (four on `x2`, four on `x3`) inside one block, checks each result against eager `step`, and asserts no errors and a written artifact. Counting attempts rather than successes matters for a block whose only calls raised: it made calls, so exit goes on to `snapshot_artifact`, and the session's `require_complete` report lists the capture errors instead of the misleading `nothing was captured`. Exit writes on a clean block only, and holds a gate refusal until the session and cache are torn down: ```python def __exit__(self, *exc): with self._lock: error = None try: if exc[0] is None: try: if self._calls == 0: raise PrecompileError("nothing was captured: call the capture with your example arguments inside the `with` block.") self._write() # snapshot_artifact(**gates) then _write_artifact(...) except BaseException as e: error = e self._exited = True try: self._map(self._session.__exit__, *exc) except BaseException as e: if error is None: raise raise e from error finally: if self._fresh_cache is not None: self._fresh_cache.__exit__(None, None, None) self._fresh_cache = None if exc[0] is None and error is not None: raise error ``` A teardown error that follows a gate refusal is raised `from` the refusal, so the refusal is not lost, and the fresh cache is always exited with `(None, None, None)` rather than with the in-flight exception. `_write` renders through `self._session.snapshot_artifact(**self._gates)` and hands the pair to `_write_artifact`; an `OSError` there becomes a `PrecompileError` (`precompile could not write the artifact`), and since `_write_artifact` leaves the previous pair in place the last good pair is still loadable. `test_a_raised_call_is_refused_at_exit_and_writes_nothing` pins the gate: a second call with `torch.randn(2, 5)` into a `Linear(4, 4)` raises `RuntimeError` inside the block, the block itself runs to completion, exit raises `PrecompileError` (`captured call raised`) through `require_complete`, and neither `m.py` nor `m.cache` exists afterwards. The same test covers a block whose only call raised, which reaches the same `captured call raised` gate rather than `nothing was captured`, and `DynamoTracer(require_complete=False)`, which writes the partial artifact instead. `test_misuse_is_refused` pins the rest of the lifecycle: ```python capture(single, ..., tracer=DynamoTracer(), backend="aot_eager") # ValueError: backend capture(single, ..., tracer=object()) # TypeError: tracer must be cap(model, x2) # before the block: PrecompileError "not active" with cap: pass # PrecompileError "nothing was captured" with cap: pass # again: PrecompileError "already been entered" cap(model, x2) # after it: PrecompileError "not active" cap(Reentrant(), x2) # forward calls cap: PrecompileError "re-entered recursively" raise KeyError("the block's own") # inside a block: propagates unchanged, nothing written # _write_artifact mocked to raise OSError: PrecompileError "could not write" ``` ## Grad mode and the training step `capture()` has no grad-mode flag. A Dynamo capture runs every call in the caller's own grad mode and lowers a backward whenever grad is enabled: a `.backward()` in `fn` graph-breaks and re-runs at serve time through the live autograd engine, accumulating `.grad` like eager, so the artifact should be served under the grad mode it was captured in. ```python def train_step(model, x): model(x).sum().backward() with capture(train_step, ..., tracer=DynamoTracer(), backend=backend) as cap: # backend: "inductor" or "eager" cap(model, x2) # returns None; model.lin.weight.grad matches an eager step # a fresh process, model reloaded from the pre-step state dict f = torch.compiler.precompile.load("m.py", "m.cache") f(model, x2) # returns None; every parameter's .grad matches the eager step ``` `test_training_step_grads_match_eager_in_a_fresh_process`, parametrized over `inductor` and `eager`, pins this: it runs an eager step on a `Model` loaded from the same state dict, checks the capture's `lin.weight` grad against it, restores the pre-step weights, and serves the artifact in a fresh process, asserting each parameter's `.grad` against the eager one. ## The artifact does not mix with a make_fx pair `test_a_dynamo_pair_does_not_mix_with_a_make_fx_pair` captures `single` once with `DynamoTracer()` and once with `MakeFxTracer()` into two pairs; `load` of the Dynamo artifact with the make_fx cache raises `PrecompileError` mentioning `tracer`, and the reverse raises `tracer` or `does not match`. `load`'s docstring now says a Dynamo artifact takes keyword arguments, carries its compiled subgraphs inside `python_code` so it serves without JIT even with no usable cache, is a no-op to enter and unload, re-seeds the names Dynamo minted into the captured module, and must be loaded in a fresh process when its capture graph-broke. ## Exports, docs and scope `DynamoTracer` joins `torch.compiler.precompile.__all__`, the `__module__` re-homing loop, the public-members test, and the API reference (`.. autoclass:: torch.compiler.precompile.DynamoTracer` in docs/source/torch.compiler_api.md). The tests pass `tracer=DynamoTracer()` explicitly through `_capture`. Mid-block `save()` checkpoints and the `summary()` report are the next commit's (#198227), so `_DynamoCapture.save()` raises `PrecompileError` (`save() is not supported on a DynamoTracer capture yet: its artifact is written when the block exits.`) rather than the base class's bare `NotImplementedError`, and the `capture()` and `Capture` docstrings' `save()` sentences say it applies to a `MakeFxTracer` capture only, for now. The module Note's `tracer:` paragraph now describes both tracers (`MakeFxTracer` the default; `DynamoTracer` standalone and version-locked, with invariants 1, 2, 3 and 6 left as the make_fx contract, refusing uncovered calls through its guards and listing the guards it could not serialize as `DROPPED_GUARDS`) instead of saying `dynamo` raises `NotImplementedError`. Deliberately absent, as follow-ups: the installed serving mode (`load(fn=)`), the rendered-as-source subgraphs, the invariants report and the per-frame drift probe. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks. ## What this leaves for later PRs - Mid-block `save()` comes in #198227. Here, `save()` on a Dynamo capture raises `PrecompileError`. - Making `DynamoTracer` the default tracer comes in #198217. Here `MakeFxTracer` is still the default. - The lifecycle refactor is #198423. The `__enter__`/`__call__`/`__exit__` bodies quoted above become `_start`/`_run`/`_finish` on the shared `Capture` base class there. The behaviour is the same, but the code at the top of the stack looks different from what this description shows. - Installed serving. This PR is standalone only, and lists installed mode above as a follow-up (`load(fn=)`). #198523 is that follow-up, except that the mode is picked automatically when the artifact is written rather than through a `load(fn=)` argument. So the `capture()` docstring paragraph this PR adds ("A Dynamo artifact is STANDALONE ... is refused at write time") is one of the stale docstrings on #198523's cleanup list, together with `PrecompileSession`'s, which comes from a lower PR. Test Plan: `TestPrecompileDynamoCapture` in test/test_precompile.py, passing `tracer=DynamoTracer()` explicitly: the graph-break/recompile round trip through a fresh process on both backends (with the in-process collision refusal), a single-graph capture served in process (weight swap, no-op enter/unload, uncovered call), a training step on both backends served in a fresh process whose `.grad` matches eager, the raised-call gate at exit (including a block whose only call raised, and `require_complete=False` writing the partial artifact), the misuse refusals (bad backend or tracer, a call outside the block, a re-entered or recursive capture, an empty block, a block raising its own exception, a write failure), calls from eight threads at once (which, unserialized, are refused as recursive re-entries), the `dynamic`, `guard_filter_fn`, `require_no_risky_drops` and `recompile_limit` knobs, the dropped guards listed in the artifact, the module/closure/partial refusals, and the make_fx/dynamo pair mismatch. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks. ``` python test/test_precompile.py PYTORCH_TEST_WITH_CROSSREF=1 python test/test_precompile.py -k TestPrecompileDynamoCapture lintrunner -a torch/_precompile.py torch/compiler/precompile.py test/test_precompile.py docs/source/torch.compiler_api.md ``` Authored with an AI assistant. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #198138 Approved by: https://github.com/MengjiaoZhou ghstack dependencies: #198211, #198223, #198283, #198284, #197993, #198213, #198135, #198243, #198214, #198136, #198215, #198137, #198216, #198528, #199883
**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 #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: #198529 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, #198423
…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
pytorch#198138) **Problem.** `torch.compiler.precompile.capture()` only took a `MakeFxTracer`: one positional call, one ATen trace, no graph breaks, no recompiled variants, no keyword arguments. The `PrecompileSession` of the previous commits can record all of those, but nothing in the public module reached it. **Fix.** Add `DynamoTracer`, the multi-graph front-end passed as `tracer=`, and `_DynamoCapture`, the `Capture` that drives a `PrecompileSession` across as many calls as the block makes and writes the standalone artifact on a clean exit, so `load()` serves it in a fresh process. **Summary.** `capture()` accepted a `MakeFxTracer` and nothing else, so a function with a graph break, a shape-dependent branch or a keyword argument could not be precompiled through `torch.compiler.precompile` even though `PrecompileSession` and `snapshot_artifact` could already record and render such captures. This commit adds `DynamoTracer(guard_filter_fn, recompile_limit, dynamic, require_complete, require_no_risky_drops)` beside `MakeFxTracer`, and `_DynamoCapture`, which runs the block under a fresh `CacheArtifactManager` cache, serializes its calls under an `RLock`, counts attempted calls, refuses a recursive re-entry, and writes the pair behind the two `require_*` gates on a clean exit only. The artifact is standalone, so `fn` must be a module-level function of an importable module, an artifact whose capture graph-broke cannot load beside the live compile that captured it (the continuation names collide, and `load` says so), and it is locked to the producing Python version and torch build. A Dynamo capture runs every call in the caller's grad mode and lowers a backward whenever grad is enabled, so a training step that calls `.backward()` is captured like any other call and the served artifact accumulates `.grad` like eager. `MakeFxTracer` stays the default for two more commits, package and recompile errors surface as `PrecompileError`, and mid-block `save()` is the next commit's, so `save()` on this tracer raises a `PrecompileError` saying its artifact is written when the block exits. ## Where this fits The stack replaces the callable `torch.compiler.precompile(fn, *example_inputs)` (trace once on inputs passed up front, pair returned in memory) with a caller-driven context manager: `capture(fn, artifact_path=, cache_path=)` is entered with a `with` block, the caller calls it on as many example inputs as they like, the `(python_code, cache)` pair is written to the two files on exit, and `load(artifact_path, cache_path)` serves it in a fresh process. The end-to-end example and the PR-by-PR map live in pytorch#197993's "The new API, end to end" section. This PR is where `capture()` becomes multi-call: `DynamoTracer` takes as many calls as the caller makes and folds every graph break and recompile they exercise into one artifact. It becomes the default tracer in pytorch#198217. The Python 3.10 `-bb` fix to the code-constant walk in `_find_code_source`, which the recursive-capture test here first exercises, lives in pytorch#198528 directly below. ## The golden path The new tests write a module with a graph-breaking step, capture it over two shapes and a keyword default, and serve it in a fresh process: ```python # precompile_golden_<uuid>.py, importable from sys.path def step(model, x, *, scale=1.0): y = model(x) * scale * SCALE torch._dynamo.graph_break() if y.shape[0] > 2: y = y + 1 return y.sum(dim=0) ``` ```python from torch.compiler.precompile import capture, DynamoTracer, load with capture(step, artifact_path="m.py", cache_path="m.cache", tracer=DynamoTracer(), backend="inductor") as cap: y2 = cap(model, x2) # step and its graph-break continuation y3 = cap(model, x3, scale=0.5) # the branch recompiles the continuation; the keyword is a second entry variant # exit: TRACER = "dynamo", SERVING_MODE = "standalone", FN_NAME = 'step' in m.py load("m.py", "m.cache") # in this process: PrecompileError, the message says to use a fresh process ``` ```python # a fresh process f = torch.compiler.precompile.load("m.py", "m.cache") f(model, x2) # == y2 f(model, x3, scale=0.5) # == y3 f(model, x2.double()) # PrecompileError: no captured variant ``` The last line is the standalone contract: there is no compiler behind a source artifact, so a call no variant covers raises rather than silently serving. `test_graph_breaks_and_recompiles_round_trip_in_a_fresh_process` pins this on both backends, including the in-process collision refusal; `test_a_single_graph_serves_in_process` pins the no-graph-break case, where `load` works in the capturing process, `f.installed` is false, `with f:` and `f.unload()` are no-ops, a second `Model()` swaps weights in, and `f(model, x3)` after a shape-2 capture raises `no captured variant`. ## `DynamoTracer` carries the multi-graph knobs ```python @dataclasses.dataclass(frozen=True) class DynamoTracer: guard_filter_fn: Callable[[Sequence[Any]], Sequence[bool]] | None = None recompile_limit: int = 256 dynamic: bool | None = None require_complete: bool = True require_no_risky_drops: bool = True ``` `guard_filter_fn` takes the `GuardFilterEntry` records (`guard_type`, `name`, ...) and returns one keep flag per entry, filtering the guards kept in the serialized artifact (runtime capture guards are always retained; the default drops only what cannot be serialized). `recompile_limit` caps recompilations per frame: a call past it runs eager and is absent from the artifact without any gate refusing it, which the docstring states. `dynamic` forces dynamic shapes as `torch.compile(dynamic=)` does. The `require_*` gates refuse, at write time, an artifact with a coverage gap (`require_complete`: a bypassed or uncovered frame, a call that raised) or one whose dropped guards told captured variants apart or hang off a configuration-chosen slot (`require_no_risky_drops`). Other dropped guards, such as the identity guards every model drops because they cannot be serialized, are listed in the artifact rather than refused; there is deliberately no gate that refuses every drop, since every capture would trip it. The annotation stays `Sequence[Any]` rather than naming `GuardFilterEntry`, because torch/compiler/precompile.py resolves the re-homed classes' annotations with `typing.get_type_hints` at import. ```python DynamoTracer(dynamic=True) # capture single on x2 -> the artifact serves x3 too DynamoTracer(guard_filter_fn=drop_x) # exit: PrecompileError "can affect dispatch" DynamoTracer(guard_filter_fn=drop_x, require_no_risky_drops=False) # writes an artifact that loads DynamoTracer(dynamic=False, recompile_limit=1) # cap(x2); cap(x3) -> served x3 raises "no captured variant" ``` `test_the_tracer_knobs_reach_the_session` pins all four lines, where `drop_x` drops the guard on `x` on top of `default_guard_filter_fn` (dropping what tells the shapes apart). `test_dropped_guards_are_listed_in_the_artifact` shows the default capture of `single` listing `['MODULE_MATCH', ...` in the artifact's dropped guards and writing the artifact regardless. ## `capture()` dispatches on the tracer ```python tracer: MakeFxTracer | DynamoTracer = MakeFxTracer() ... if isinstance(tracer, MakeFxTracer): return _MakeFxCapture(fn, artifact_path, cache_path, backend=backend, decompositions=tracer.decompositions) if not isinstance(tracer, DynamoTracer): raise TypeError("precompile.capture tracer must be a MakeFxTracer or DynamoTracer, got ...") if backend not in ("inductor", "eager"): raise ValueError(f"precompile backend must be 'inductor' or 'eager', got {backend!r}.") try: session = precompile_capture(fn, backend=backend, guard_filter_fn=tracer.guard_filter_fn, recompile_limit=tracer.recompile_limit, dynamic=tracer.dynamic) except PackageError as e: raise PrecompileError(str(e)) from e return _DynamoCapture(session, artifact_path, cache_path, require_complete=..., require_no_risky_drops=...) ``` The make_fx front-end validates `backend` when it builds its `PrecompiledModule`; the Dynamo front-end builds none, so `capture()` checks it before creating the session. `precompile_capture`'s up-front refusals now surface as `PrecompileError`. `test_entries_a_standalone_artifact_cannot_rebuild_are_refused` pins the entries a standalone artifact cannot rebuild: a bare `nn.Module` is refused by `capture()` itself (`CALLS the model`: Dynamo compiles its wrapper frame, whose graphs close over the module), and a closure entry is refused once the block calls it (`closes over`), since a code object cannot rebuild what the closure captured. A `functools.partial` never reaches the tracer: `capture()` refuses it with a `TypeError` (`takes the function itself, not a functools.partial`) before dispatching. `_MakeFxCapture`'s two refusals (a keyword argument, a second call) now point at `tracer=DynamoTracer()` instead of just explaining themselves. ## `_DynamoCapture` drives the session Entering the block opens a fresh cache before the session, and undoes it if the session refuses to enter: ```python def __enter__(self): with self._lock: if self._call is not None or self._exited: raise PrecompileError("this capture has already been entered; capture() returns a fresh capture per call.") self._fresh_cache = CacheArtifactManager.with_fresh_cache() self._fresh_cache.__enter__() try: self._call = self._map(self._session.__enter__) except BaseException: self._fresh_cache.__exit__(None, None, None) self._fresh_cache = None raise return self ``` The capture's compiles record into the process-global cache-artifact list, which the cache half of the artifact bundles to prime the kernel caches on load; a fresh one means the bundle holds only this capture's compiles. The swap spans the whole `with` block, not just the calls, so the `capture()` docstring now says a `DynamoTracer` capture records the kernel-cache artifacts of everything compiled inside the block: compile nothing else there, and do not overlap two such captures. `_map` is the one place `PackageError` and `RecompileError` become `PrecompileError`. Each call is serialized under an `RLock`, refuses a call before `__enter__` or after `__exit__` (`capture is not active`), refuses `fn` calling the capture it is being captured through (`re-entered recursively`), and counts the call before it runs: ```python def __call__(self, *args, **kwargs): with self._lock: ... self._in_call = True # Counted before the call: a call that raised is for the session's # require_complete gate to report, not "nothing was captured". self._calls += 1 try: return self._map(self._call, *args, **kwargs) finally: self._in_call = False ``` The lock is what makes concurrent callers safe: every call feeds the one session, and without it a call that finds another thread's call in flight would trip the `_in_call` check and be refused as a recursive re-entry. `test_calls_from_several_threads_are_serialized` starts eight threads (four on `x2`, four on `x3`) inside one block, checks each result against eager `step`, and asserts no errors and a written artifact. Counting attempts rather than successes matters for a block whose only calls raised: it made calls, so exit goes on to `snapshot_artifact`, and the session's `require_complete` report lists the capture errors instead of the misleading `nothing was captured`. Exit writes on a clean block only, and holds a gate refusal until the session and cache are torn down: ```python def __exit__(self, *exc): with self._lock: error = None try: if exc[0] is None: try: if self._calls == 0: raise PrecompileError("nothing was captured: call the capture with your example arguments inside the `with` block.") self._write() # snapshot_artifact(**gates) then _write_artifact(...) except BaseException as e: error = e self._exited = True try: self._map(self._session.__exit__, *exc) except BaseException as e: if error is None: raise raise e from error finally: if self._fresh_cache is not None: self._fresh_cache.__exit__(None, None, None) self._fresh_cache = None if exc[0] is None and error is not None: raise error ``` A teardown error that follows a gate refusal is raised `from` the refusal, so the refusal is not lost, and the fresh cache is always exited with `(None, None, None)` rather than with the in-flight exception. `_write` renders through `self._session.snapshot_artifact(**self._gates)` and hands the pair to `_write_artifact`; an `OSError` there becomes a `PrecompileError` (`precompile could not write the artifact`), and since `_write_artifact` leaves the previous pair in place the last good pair is still loadable. `test_a_raised_call_is_refused_at_exit_and_writes_nothing` pins the gate: a second call with `torch.randn(2, 5)` into a `Linear(4, 4)` raises `RuntimeError` inside the block, the block itself runs to completion, exit raises `PrecompileError` (`captured call raised`) through `require_complete`, and neither `m.py` nor `m.cache` exists afterwards. The same test covers a block whose only call raised, which reaches the same `captured call raised` gate rather than `nothing was captured`, and `DynamoTracer(require_complete=False)`, which writes the partial artifact instead. `test_misuse_is_refused` pins the rest of the lifecycle: ```python capture(single, ..., tracer=DynamoTracer(), backend="aot_eager") # ValueError: backend capture(single, ..., tracer=object()) # TypeError: tracer must be cap(model, x2) # before the block: PrecompileError "not active" with cap: pass # PrecompileError "nothing was captured" with cap: pass # again: PrecompileError "already been entered" cap(model, x2) # after it: PrecompileError "not active" cap(Reentrant(), x2) # forward calls cap: PrecompileError "re-entered recursively" raise KeyError("the block's own") # inside a block: propagates unchanged, nothing written # _write_artifact mocked to raise OSError: PrecompileError "could not write" ``` ## Grad mode and the training step `capture()` has no grad-mode flag. A Dynamo capture runs every call in the caller's own grad mode and lowers a backward whenever grad is enabled: a `.backward()` in `fn` graph-breaks and re-runs at serve time through the live autograd engine, accumulating `.grad` like eager, so the artifact should be served under the grad mode it was captured in. ```python def train_step(model, x): model(x).sum().backward() with capture(train_step, ..., tracer=DynamoTracer(), backend=backend) as cap: # backend: "inductor" or "eager" cap(model, x2) # returns None; model.lin.weight.grad matches an eager step # a fresh process, model reloaded from the pre-step state dict f = torch.compiler.precompile.load("m.py", "m.cache") f(model, x2) # returns None; every parameter's .grad matches the eager step ``` `test_training_step_grads_match_eager_in_a_fresh_process`, parametrized over `inductor` and `eager`, pins this: it runs an eager step on a `Model` loaded from the same state dict, checks the capture's `lin.weight` grad against it, restores the pre-step weights, and serves the artifact in a fresh process, asserting each parameter's `.grad` against the eager one. ## The artifact does not mix with a make_fx pair `test_a_dynamo_pair_does_not_mix_with_a_make_fx_pair` captures `single` once with `DynamoTracer()` and once with `MakeFxTracer()` into two pairs; `load` of the Dynamo artifact with the make_fx cache raises `PrecompileError` mentioning `tracer`, and the reverse raises `tracer` or `does not match`. `load`'s docstring now says a Dynamo artifact takes keyword arguments, carries its compiled subgraphs inside `python_code` so it serves without JIT even with no usable cache, is a no-op to enter and unload, re-seeds the names Dynamo minted into the captured module, and must be loaded in a fresh process when its capture graph-broke. ## Exports, docs and scope `DynamoTracer` joins `torch.compiler.precompile.__all__`, the `__module__` re-homing loop, the public-members test, and the API reference (`.. autoclass:: torch.compiler.precompile.DynamoTracer` in docs/source/torch.compiler_api.md). The tests pass `tracer=DynamoTracer()` explicitly through `_capture`. Mid-block `save()` checkpoints and the `summary()` report are the next commit's (pytorch#198227), so `_DynamoCapture.save()` raises `PrecompileError` (`save() is not supported on a DynamoTracer capture yet: its artifact is written when the block exits.`) rather than the base class's bare `NotImplementedError`, and the `capture()` and `Capture` docstrings' `save()` sentences say it applies to a `MakeFxTracer` capture only, for now. The module Note's `tracer:` paragraph now describes both tracers (`MakeFxTracer` the default; `DynamoTracer` standalone and version-locked, with invariants 1, 2, 3 and 6 left as the make_fx contract, refusing uncovered calls through its guards and listing the guards it could not serialize as `DROPPED_GUARDS`) instead of saying `dynamo` raises `NotImplementedError`. Deliberately absent, as follow-ups: the installed serving mode (`load(fn=)`), the rendered-as-source subgraphs, the invariants report and the per-frame drift probe. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks. ## What this leaves for later PRs - Mid-block `save()` comes in pytorch#198227. Here, `save()` on a Dynamo capture raises `PrecompileError`. - Making `DynamoTracer` the default tracer comes in pytorch#198217. Here `MakeFxTracer` is still the default. - The lifecycle refactor is pytorch#198423. The `__enter__`/`__call__`/`__exit__` bodies quoted above become `_start`/`_run`/`_finish` on the shared `Capture` base class there. The behaviour is the same, but the code at the top of the stack looks different from what this description shows. - Installed serving. This PR is standalone only, and lists installed mode above as a follow-up (`load(fn=)`). pytorch#198523 is that follow-up, except that the mode is picked automatically when the artifact is written rather than through a `load(fn=)` argument. So the `capture()` docstring paragraph this PR adds ("A Dynamo artifact is STANDALONE ... is refused at write time") is one of the stale docstrings on pytorch#198523's cleanup list, together with `PrecompileSession`'s, which comes from a lower PR. Test Plan: `TestPrecompileDynamoCapture` in test/test_precompile.py, passing `tracer=DynamoTracer()` explicitly: the graph-break/recompile round trip through a fresh process on both backends (with the in-process collision refusal), a single-graph capture served in process (weight swap, no-op enter/unload, uncovered call), a training step on both backends served in a fresh process whose `.grad` matches eager, the raised-call gate at exit (including a block whose only call raised, and `require_complete=False` writing the partial artifact), the misuse refusals (bad backend or tracer, a call outside the block, a re-entered or recursive capture, an empty block, a block raising its own exception, a write failure), calls from eight threads at once (which, unserialized, are refused as recursive re-entries), the `dynamic`, `guard_filter_fn`, `require_no_risky_drops` and `recompile_limit` knobs, the dropped guards listed in the artifact, the module/closure/partial refusals, and the make_fx/dynamo pair mismatch. The fresh-process tests are skipped under the crossref harness, whose active dispatch mode Dynamo guards on and a fresh process lacks. ``` python test/test_precompile.py PYTORCH_TEST_WITH_CROSSREF=1 python test/test_precompile.py -k TestPrecompileDynamoCapture lintrunner -a torch/_precompile.py torch/compiler/precompile.py test/test_precompile.py docs/source/torch.compiler_api.md ``` Authored with an AI assistant. Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: pytorch#198138 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
**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):
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.
Captureowns the lifecycle as one state field under one lock, and the tracers implement only the hooks it calls.Summary.
_MakeFxCapturetracked its block with two booleans,_enteredand_exited, which are really three states, and_DynamoCapturekept its own_exitedflag and its own copies of__enter__,__exit__,__call__andsave(). 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 thatCapture's docstring says a spent capture does not keep.Capturenow 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,_saveand_finish, where_finishdrops the pair on every exit. The Dynamo capture'sRLock, which serializes the block's calls, saves, exit andsummary()because every call feeds onePrecompileSession, moves intoCapturewith 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. TheGenerictyping ofCaptureand the tensor-only leaves snapshot that earlier revisions of this PR carried now live in #198529 and #198530.What a Dynamo capture says now
The
save()checkpoint contract moves from_DynamoCapture's override onto the publicCapture.savedocstring, since it holds for both tracers andhelp(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 raisesPrecompileErroroutside thewithblock.test_calls_from_several_threads_are_serializedpins the lock.Test Plan:
test_misuse_is_refusedinTestPrecompileDynamoCapturemoves to the shared messages, andtest_save_checkpoints_mid_blocknow 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.Authored with an AI assistant.
Co-Authored-By: Claude Opus 5.5 [email protected]