Skip to content

[precompile] Capture across calls the caller makes, not calls precompile makes - #195070

Closed
bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1080/basefrom
gh/bobrenjc93/1080/head
Closed

bobrenjc93 wants to merge 3 commits into
gh/bobrenjc93/1080/basefrom
gh/bobrenjc93/1080/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

precompile() runs every entry of example_inputs itself, back to back, with
nothing in between. That is only correct when the calls are independent, and a
pipelined training step is not: its inputs come off a queue that the enclosing
loop advances, so the second call finds the state the first one consumed. On a
real sharded recommendation model that surfaces as "Invalid PipelinedForward
usage, input_dist ... probably consumed by others" -- and no shape where
precompile drives the iteration fixes it, generator or callback included,
because advancing the queue is caller code outside the region.

accumulate() inverts the control: the caller keeps their loop.

with torch.compiler.precompile.accumulate(
    train_step, artifact_path="m.py", cache_path="m.cache", training=True,
) as capture:
    for batch in loader:
        losses = capture(model, batch)
        optimizer.step()

Each call runs for real, folds in whatever it newly exercised, rewrites both
files, and returns what the region returned. A call that exercises nothing new
adds nothing. No finalize step: the files are a loadable artifact for everything
captured so far from the first call onwards, so a job that dies partway leaves a
working artifact for the batches it reached.

A handle rather than a state value threaded through precompile(). Not a style
preference -- the state cannot be a value. Compiled variants are filed under an
isolate_recompiles_id, lookup matches it with no fallback, and nothing can hand
an existing id to torch._dynamo.optimize: it mints its own from a private
counter. So a later call can only see an earlier call's variants if the compiled
region is still alive, which means the state IS a live object. Spelling it as a
keyword argument would have hidden that. Carrying the configuration on the
handle also makes a mid-capture disagreement about backend or training
unrepresentable rather than an error to raise.

The correctness problem this had to solve first: the invariant-guard policy
CANNOT be re-applied per call. _apply_guard_policy rewrites each variant's
serialized guards and then prunes the facts it derived them from, so a second
pass reads bytes the first already filtered against facts the first already
edited, and filtering only ever removes. That is not a slow leak. A single
variant is invariant by construction -- one variant cannot disagree with itself,
so varying_guard_slots over it is empty -- and the pass after call 1 therefore
strips every at-risk slot of every frame, permanently. When a later call adds
the variant that makes one of them discriminate, the earlier variant no longer
carries it and goes on matching calls that belong to the new graph. Measured end
to end on a HASATTR branch: the artifact serves the first call's numbers for the
second call's input.

So the policy is split. _apply_guard_policy still consumes the session, which is
right for the one-shot path where the capture is over. _policy_filtered_codes
runs the same core over deep copies and leaves the session pristine, and that is
what the accumulating render uses. deepcopy treats bytes as atomic, so it
duplicates the record structure and not the serialized payloads.

Resuming a session turned up two more things it could not have done before.
_closing is set by every exit and, on the one-shot path, never read again; a
second entry refused every call with "PrecompileSession is not active", and the
error was swallowed into _capture_errors where it failed require_complete
instead of being raised. And record_live_guard_leaves rebinds a fresh set on
each entry, so keeping only the newest cycle's leaves made _report_guard_drift
call every frame the cycle had not recompiled drifted; the leaves are unioned
across cycles now.

Cost is linear in what has been captured, not in the call: ~2.7 ms per
accumulated guarded code and ~10 KB of rendered source per variant, measured
over twelve calls. A long loop over a large model pays that every call, which is
the price of the files always being valid.

Three things a review pass caught in the first version of this, each verified
before and after:

The rewrite was not atomic. _write_artifact truncated both files where they lay,
code first then cache, and the pair only loads together -- the cache carries a
sha256 of exactly the python_code it was emitted with. So a process that died
mid-write left a new artifact beside the previous cache, which refuses to load
with "cache does not match python_code". At hundreds of megabytes that window is
seconds long on every call, which is exactly the crash the always-valid promise
is selling protection against. Both halves are written beside their targets,
fsynced, and renamed into place; a failed write leaves the previous pair intact
and no temp files behind.

A call that raised poisoned every later one. require_complete gates on
summary().capture_errors, which accumulates for the life of the session, so
after one bad call every subsequent render refused -- and refused AFTER the
region had run, so a training step's gradients moved and its result was never
returned. The gate now sees only the errors of the cycle it is rendering; a call
that failed has already raised to the caller.

The artifact under-reported its own drops. _policy_filtered_codes discarded what
the pass dropped, and _apply_guard_policy never runs while resumable, so
POLICY_DROPPED_GUARDS in the written file was empty where the one-shot path
listed AUTOGRAD_SAVED_TENSORS_HOOKS, DEFAULT_DEVICE, GRAD_MODE and the rest. The
drops are read back off the pass that made them, and REPLACED rather than
unioned, because keep_only grows as calls add variants and a slot dropped by an
earlier render can survive a later one. kept_guards is derived by subtraction
for the same reason instead of being decremented in place.

Test Plan:

python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/functorch/test_compile_to_python.py

Nine new tests. The one that matters is
test_precompile_accumulate_serves_a_slot_only_a_later_call_makes_vary: it builds
the HASATTR shape above, captures the two branches on two separate calls, and
asserts the reloaded artifact serves BOTH -- it returns the first branch twice
if the policy is applied to the capture rather than to a copy. The others cover
accumulation and result pass-through, gradients matching eager, the artifact
being loadable mid-loop, the session's facts surviving a render, close()
semantics, and the make_fx and lone-path rejections. Three more cover the fixes
above: a write that fails partway leaves the previous pair loadable, a call
after a raising one renders and returns, and the accumulating artifact reports
the same policy drops the one-shot one does.

Authored with the assistance of an AI coding agent.

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

pytorch-bot Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 12 New Failures, 1 Unrelated Failure

As of commit 93d89ed with merge base 1b4e490 (image):

NEW FAILURES - The following jobs have failed:

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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Aug 27, 2026
This was referenced Aug 27, 2026
This was referenced Aug 27, 2026
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 27, 2026
…ile makes

precompile() runs every entry of example_inputs itself, back to back, with
nothing in between. That is only correct when the calls are independent, and a
pipelined training step is not: its inputs come off a queue that the enclosing
loop advances, so the second call finds the state the first one consumed. On a
real sharded recommendation model that surfaces as "Invalid PipelinedForward
usage, input_dist ... probably consumed by others" -- and no shape where
precompile drives the iteration fixes it, generator or callback included,
because advancing the queue is caller code outside the region.

accumulate() inverts the control: the caller keeps their loop.

    with torch.compiler.precompile.accumulate(
        train_step, artifact_path="m.py", cache_path="m.cache", training=True,
    ) as capture:
        for batch in loader:
            losses = capture(model, batch)
            optimizer.step()

Each call runs for real, folds in whatever it newly exercised, rewrites both
files, and returns what the region returned. A call that exercises nothing new
adds nothing. No finalize step: the files are a loadable artifact for everything
captured so far from the first call onwards, so a job that dies partway leaves a
working artifact for the batches it reached.

A handle rather than a state value threaded through precompile(). Not a style
preference -- the state cannot be a value. Compiled variants are filed under an
isolate_recompiles_id, lookup matches it with no fallback, and nothing can hand
an existing id to torch._dynamo.optimize: it mints its own from a private
counter. So a later call can only see an earlier call's variants if the compiled
region is still alive, which means the state IS a live object. Spelling it as a
keyword argument would have hidden that. Carrying the configuration on the
handle also makes a mid-capture disagreement about backend or training
unrepresentable rather than an error to raise.

The correctness problem this had to solve first: the invariant-guard policy
CANNOT be re-applied per call. _apply_guard_policy rewrites each variant's
serialized guards and then prunes the facts it derived them from, so a second
pass reads bytes the first already filtered against facts the first already
edited, and filtering only ever removes. That is not a slow leak. A single
variant is invariant by construction -- one variant cannot disagree with itself,
so varying_guard_slots over it is empty -- and the pass after call 1 therefore
strips every at-risk slot of every frame, permanently. When a later call adds
the variant that makes one of them discriminate, the earlier variant no longer
carries it and goes on matching calls that belong to the new graph. Measured end
to end on a HASATTR branch: the artifact serves the first call's numbers for the
second call's input.

So the policy is split. _apply_guard_policy still consumes the session, which is
right for the one-shot path where the capture is over. _policy_filtered_codes
runs the same core over deep copies and leaves the session pristine, and that is
what the accumulating render uses. deepcopy treats bytes as atomic, so it
duplicates the record structure and not the serialized payloads.

Resuming a session turned up two more things it could not have done before.
_closing is set by every exit and, on the one-shot path, never read again; a
second entry refused every call with "PrecompileSession is not active", and the
error was swallowed into _capture_errors where it failed require_complete
instead of being raised. And record_live_guard_leaves rebinds a fresh set on
each entry, so keeping only the newest cycle's leaves made _report_guard_drift
call every frame the cycle had not recompiled drifted; the leaves are unioned
across cycles now.

Cost is linear in what has been captured, not in the call: ~2.7 ms per
accumulated guarded code and ~10 KB of rendered source per variant, measured
over twelve calls. A long loop over a large model pays that every call, which is
the price of the files always being valid.

Three things a review pass caught in the first version of this, each verified
before and after:

The rewrite was not atomic. _write_artifact truncated both files where they lay,
code first then cache, and the pair only loads together -- the cache carries a
sha256 of exactly the python_code it was emitted with. So a process that died
mid-write left a new artifact beside the previous cache, which refuses to load
with "cache does not match python_code". At hundreds of megabytes that window is
seconds long on every call, which is exactly the crash the always-valid promise
is selling protection against. Both halves are written beside their targets,
fsynced, and renamed into place; a failed write leaves the previous pair intact
and no temp files behind.

A call that raised poisoned every later one. require_complete gates on
summary().capture_errors, which accumulates for the life of the session, so
after one bad call every subsequent render refused -- and refused AFTER the
region had run, so a training step's gradients moved and its result was never
returned. The gate now sees only the errors of the cycle it is rendering; a call
that failed has already raised to the caller.

The artifact under-reported its own drops. _policy_filtered_codes discarded what
the pass dropped, and _apply_guard_policy never runs while resumable, so
POLICY_DROPPED_GUARDS in the written file was empty where the one-shot path
listed AUTOGRAD_SAVED_TENSORS_HOOKS, DEFAULT_DEVICE, GRAD_MODE and the rest. The
drops are read back off the pass that made them, and REPLACED rather than
unioned, because keep_only grows as calls add variants and a slot dropped by an
earlier render can survive a later one. kept_guards is derived by subtraction
for the same reason instead of being decremented in place.

Test Plan:

```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/functorch/test_compile_to_python.py
```

Nine new tests. The one that matters is
test_precompile_accumulate_serves_a_slot_only_a_later_call_makes_vary: it builds
the HASATTR shape above, captures the two branches on two separate calls, and
asserts the reloaded artifact serves BOTH -- it returns the first branch twice
if the policy is applied to the capture rather than to a copy. The others cover
accumulation and result pass-through, gradients matching eager, the artifact
being loadable mid-loop, the session's facts surviving a render, close()
semantics, and the make_fx and lone-path rejections. Three more cover the fixes
above: a write that fails partway leaves the previous pair loadable, a call
after a raising one renders and returns, and the accumulating artifact reports
the same policy drops the one-shot one does.

Authored with the assistance of an AI coding agent.

ghstack-source-id: aafe328
Pull-Request: #195070
bobrenjc93 added a commit that referenced this pull request Aug 28, 2026
#195070)

A comparison against the ghstack implementation ending at #195070 (the
accumulate() session shape of the same caller-owned-loop feature) surfaced
several ideas worth having regardless of API shape. This ports the ones
that fit this stack's foundation:

- _write_dynamo_artifact_files now creates parent directories, fsyncs both
  temp files before the back-to-back renames, and unlinks its temp files
  when a write fails, so a failed rewrite leaves the previous pair and no
  litter (their _write_artifact's exact discipline, with their flaky-open
  crash test ported alongside).
- Guard-drop observability: _filter_dynamo_guards reports the (guard type,
  source) pairs it minimized away; they are embedded in the artifact as a
  _DROPPED_GUARDS section and surfaced through the new
  state.summary() -> PrecompileStateSummary (calls, examples, variants,
  graphs, dynamic graphs, dropped guards), the counterpart of their
  summary()/POLICY_DROPPED_GUARDS reporting.
- dynamic= is now a real kwarg (forwarded to torch._dynamo.optimize, None
  keeps the automatic policy) and rides in the stateful consistency check
  alongside backend/training/recompile_limit, closing the one field of the
  original ask's requirement 4 that had nothing to check.
- precompile.load(artifact_path=..., cache_path=...) reads the pair a
  stateful capture wrote, mirroring their path-based load.
- The stateful default recompile_limit is now
  max(torch._dynamo.config.recompile_limit, 256): accumulating captures
  outgrow the example-count default immediately (their accumulate defaults
  to 256 outright).
- A raised call no longer being able to freeze the loop is now pinned by a
  test (a graph-breaking call fails loudly; the next good call captures and
  rewrites), matching their survives-a-call-that-raised semantics, which
  this implementation already had but never proved.

Deliberately NOT ported, called out for reviewers: nn.Module arguments,
graph breaks/multi-frame artifacts, kwargs/ExampleInput, and serve-time
compilation are foundation-level features of that stack's 63-PR base, not
ideas this diff can absorb; and serving-compiles-on-miss is a contract
decision (this stack's artifacts deliberately raise instead).

This PR was authored with an AI assistant (Claude Code); every change was
verified on a from-source build.

Test Plan:

```
.venv/bin/python test/test_precompile.py
# Ran 230 tests ... OK  (new: summary()/dropped-guards reporting, dynamic=
# kwarg incl. resume mismatch, path-based load validation, writer crash
# cleanup, survives-a-raised-call)

lintrunner torch/_precompile.py test/test_precompile.py \
  docs/source/torch.compiler_api.md
# ok No lint issues.
```

The dropped-guards test pins the exact minimized pairs
(EQUALS_MATCH/CONSTANT_MATCH on a module-global constant) in both the
summary and the artifact text; the writer test ports #195070's flaky-open
scenario and asserts the previous pair survives with no .tmp litter.

Co-Authored-By: Claude Fable 5 <[email protected]>
bobrenjc93 added a commit that referenced this pull request Aug 28, 2026
#195070)

A comparison against the ghstack implementation ending at #195070 (the
accumulate() session shape of the same caller-owned-loop feature) surfaced
several ideas worth having regardless of API shape. This ports the ones
that fit this stack's foundation:

- _write_dynamo_artifact_files now creates parent directories, fsyncs both
  temp files before the back-to-back renames, and unlinks its temp files
  when a write fails, so a failed rewrite leaves the previous pair and no
  litter (their _write_artifact's exact discipline, with their flaky-open
  crash test ported alongside).
- Guard-drop observability: _filter_dynamo_guards reports the (guard type,
  source) pairs it minimized away, aggregated and deduplicated across
  variants (a listed pair was dropped from at least one variant's dispatch
  and may remain checked in others -- the artifact comment, docstrings, and
  a two-variant test pin that reading); they are embedded in the artifact
  as a _DROPPED_GUARDS section and surfaced through the new
  state.summary() -> PrecompileStateSummary (calls, examples, variants,
  graphs, dynamic graphs, dropped guards), the counterpart of their
  summary()/POLICY_DROPPED_GUARDS reporting.
- dynamic= is now a real kwarg (forwarded to torch._dynamo.optimize, None
  keeps the automatic policy) and rides in the stateful consistency check
  alongside backend/training/recompile_limit, closing the one field of the
  original ask's requirement 4 that had nothing to check.
- precompile.load(artifact_path=..., cache_path=...) reads the pair a
  stateful capture wrote, mirroring their path-based load.
- The stateful default recompile_limit is now
  max(torch._dynamo.config.recompile_limit, 256): accumulating captures
  outgrow the example-count default immediately (their accumulate defaults
  to 256 outright).
- A raised call no longer being able to freeze the loop is now pinned by a
  test (a graph-breaking call fails loudly; the next good call captures and
  rewrites), matching their survives-a-call-that-raised semantics, which
  this implementation already had but never proved.

Deliberately NOT ported, called out for reviewers: nn.Module arguments,
graph breaks/multi-frame artifacts, kwargs/ExampleInput, and serve-time
compilation are foundation-level features of that stack's 63-PR base, not
ideas this diff can absorb; and serving-compiles-on-miss is a contract
decision (this stack's artifacts deliberately raise instead).

This PR was authored with an AI assistant (Claude Code); every change was
verified on a from-source build.

Test Plan:

```
.venv/bin/python test/test_precompile.py
# Ran 230 tests ... OK  (new: summary()/dropped-guards reporting, dynamic=
# kwarg incl. resume mismatch, path-based load validation, writer crash
# cleanup, survives-a-raised-call)

lintrunner torch/_precompile.py test/test_precompile.py \
  docs/source/torch.compiler_api.md
# ok No lint issues.
```

The dropped-guards test pins the exact minimized pairs
(EQUALS_MATCH/CONSTANT_MATCH on a module-global constant) in both the
summary and the artifact text; the writer test ports #195070's flaky-open
scenario and asserts the previous pair survives with no .tmp litter.

Co-Authored-By: Claude Fable 5 <[email protected]>
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded by the canonical precompile stack #195353-#195362; this change lives in #195362 (with the guard-drop policy half in #195360). Closing to consolidate review there. The branch is kept on GitHub.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1080/head branch November 11, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant