Repository navigation
[precompile] Capture once, and apply the guard policy by re-serializing - #194302
Closed
bobrenjc93 wants to merge 3 commits into
Closed
bobrenjc93 wants to merge 3 commits into
bobrenjc93 wants to merge 3 commits into
Conversation
🔗 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 FailureAs of commit f082ac5 with merge base 1b4e490 ( 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. |
This was referenced Aug 20, 2026
Closed
Closed
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 21, 2026
This was referenced Aug 22, 2026
Closed
Contributor
Author
|
@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
1 similar comment
Contributor
Author
|
@bobrenjc93 has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
Contributor
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 reportsnum_batches_tracked = 6for 3 examples.A module that mutates its own state is guarded on values the served model will
never reach. A module with
self.step += 1in its forward has been advancedto 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_onlyand its branch in_recording_filterare gone.
_apply_guard_policyreproduces the bookkeeping that branch did --_policy_dropped_guards,_kept_guards, and pruning_guard_sets--because
summary()and theinvariants=report are built from those, and asilent regression there is invisible: no test asserted
POLICY_DROPPED_GUARDS, and CI would have stayed green on an empty one. Onresnet18 the two designs agree field for field (19 dropped, 664 policy-dropped,
0 risky) and
write_invariants()diffs to zero lines. It runs before thereport 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_overrideread the live tensor where it needed therecorded snapshot. On re-serialization that tensor is the fake the first pass
wrote, so
torch._C._dispatch_keys()reportsPythonandPythonTLSSnapshotthat the real tensor never had (latent today only becauseLocalState::applymasks them), andempty_like(..., device="meta")underthe live
FakeTensorModereturns another FakeTensor -- which picklesFakeTensorMode,MetaConverter,FakeTensorConverterandMetaTensorDescriberinto the artifact along with it, and is the source of theWeakIdKeyDictionary.removenoise at interpreter shutdown. HonouringFakeTensor.dispatch_keysand taking the snapshot underno_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 wrappersubclass no longer desugars and
test_tensor_subclass_metadata_matchfailswith a raw AttributeError. That branch is unreachable from re-serialization, since
a wrapper subclass is not a FakeTensor.
serialize_guardsindexedglobal_scope[builtins_dict_name]unguarded.pickle_guards_stateemptiesglobal_scopewhen every guard is portable butkeeps 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:
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
FakeTensorModeback in the blob, reverting the builtins-dict fixalone raises through the portable-filter case, and the
POLICY_DROPPED_GUARDSassertion is the one that would have caught an emptybookkeeping 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=Truecapture still generalizes to shapes itnever saw.
Authored with an AI assistant.
Differential Revision: D116865483