Skip to content

[precompile] Capture once, and apply the guard policy by re-serializing - #194302

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Most of an artifact's guards discriminate nothing: their value was identical in
every captured variant, so they select no graph. Dropping them is what makes a
large model's artifact viable at all -- 664 of 683 serializable slots on a
resnet18 -- but which slots those are is only knowable once every variant
exists, while guards are serialized per compilation, as each one is produced.

Until now that was resolved by capturing TWICE: a throwaway probe pass to learn
the policy, then a real pass applying it. That is not free, because a capture is
not free of side effects. It runs the user's region once per example per pass,
and three consequences follow that a user cannot work around:

A training capture doubles the caller's gradients. Three examples through a
region that calls .backward() leave grad norms of
[48.1, 22.8, 75.9, 72.0] where one pass leaves [24.1, 11.4, 37.9, 36.0]
-- exactly 2x. A BatchNorm in .train() mode reports
num_batches_tracked = 6 for 3 examples.

A module that mutates its own state is guarded on values the served model will
never reach. A module with self.step += 1 in its forward has been advanced
to 4 by the probe before the real pass begins, so the artifact pins steps 4..7
and a cold model serves 0 of 4 calls with "no captured variant".

And it costs a second lowering per example.

This captures once and applies the policy on the way out of the session, by
re-serializing each frame's guards from the pickle the capture already made.
Re-serializing the PICKLE rather than the live guards is the load-bearing
choice: the pickle is the value snapshot taken at compile time, whereas a
guarded attribute the model mutates has moved on by the time the session exits
-- rebuilding from live state serves 0 of 4 on that same counter module, where
this serves 4 of 4 bitwise.

The policy now runs in one place instead of being threaded through the
per-compilation filter, so keep_only and its branch in _recording_filter
are gone. _apply_guard_policy reproduces the bookkeeping that branch did --
_policy_dropped_guards, _kept_guards, and pruning _guard_sets --
because summary() and the invariants= report are built from those, and a
silent regression there is invisible: no test asserted
POLICY_DROPPED_GUARDS, and CI would have stayed green on an empty one. On
resnet18 the two designs agree field for field (19 dropped, 664 policy-dropped,
0 risky) and write_invariants() diffs to zero lines. It runs before the
report is written so that the report describes the artifact actually emitted.

Two changes in guards.py are prerequisites, not cleanup, because they are what
makes a guard pickle survive a SECOND trip:

GuardsStatePickler.reducer_override read the live tensor where it needed the
recorded snapshot. On re-serialization that tensor is the fake the first pass
wrote, so torch._C._dispatch_keys() reports Python and
PythonTLSSnapshot that the real tensor never had (latent today only because
LocalState::apply masks them), and empty_like(..., device="meta") under
the live FakeTensorMode returns another FakeTensor -- which pickles
FakeTensorMode, MetaConverter, FakeTensorConverter and
MetaTensorDescriber into the artifact along with it, and is the source of the
WeakIdKeyDictionary.remove noise at interpreter shutdown. Honouring
FakeTensor.dispatch_keys and taking the snapshot under no_dispatch()
takes a per-frame blob from 10,532 bytes to 4,164 and the resnet18 artifact from
1,531,031 to 1,005,919. The identical fix on the traceable-wrapper-subclass
branch just above is deliberately NOT made: under no_dispatch() a wrapper
subclass no longer desugars and test_tensor_subclass_metadata_match fails
with a raw AttributeError. That branch is unreachable from re-serialization, since
a wrapper subclass is not a FakeTensor.

serialize_guards indexed global_scope[builtins_dict_name] unguarded.
pickle_guards_state empties global_scope when every guard is portable but
keeps the name, so re-serializing a portable-filtered capture raised
KeyError: '__builtins_dict___0' where the two-pass design succeeded.

Net size, resnet18: the policy work itself costs about 2% (984,716 to
1,005,919), which is encoding rather than content -- the re-serialized object
graph memoizes ~22 more objects, pushing back-references past memo index 255 and
turning BINGET into LONG_BINGET. The honest speed claim is half the region
executions; wall-clock gains are smaller and warmup-dominated, since the probe's
second compile was largely served warm from the inductor caches.

Test Plan:

python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_aot_compile.py
python test/functorch/test_compile_to_python.py
python test/inductor/test_compile_to_python.py

test_aot_compile.py has 3 pre-existing failures in this environment
(test_aot_compile_with_aoti*, fatal error: cuda.h: No such file or directory),
identical with and without this change.

Three of the six new tests fail on the two-pass design: a call counter, a
training capture's gradients, and the mutating-counter module served from a cold
model. The other three exist because this design has failure modes the old one
did not, and each was written after watching it fail: reverting the reducer fix
alone puts FakeTensorMode back in the blob, reverting the builtins-dict fix
alone raises through the portable-filter case, and the
POLICY_DROPPED_GUARDS assertion is the one that would have caught an empty
bookkeeping field.

Also checked directly, against the two-pass artifact for the same model:
resnet18 serves 3 of 3 bitwise, a training step's losses and gradients match
eager on 3 of 3, and a dynamic=True capture still generalizes to shapes it
never saw.

Authored with an AI assistant.

Differential Revision: D116865483

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 23 New Failures, 1 Unrelated Failure, 1 Unclassified Failure

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

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

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 20, 2026
This was referenced Aug 20, 2026
@bobrenjc93 bobrenjc93 added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Aug 20, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

This was referenced Aug 22, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

1 similar comment
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded by the canonical precompile stack #195353-#195362; this change lives 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/1014/head branch November 12, 2026 01:45
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