Repository navigation
[precompile] Capture once, and never drop a guard whose loss changes the answer - #195371
bobrenjc93 wants to merge 15 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195371
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 1 Unrelated FailureAs of commit 38b8639 with merge base c9fded8 ( NEW FAILURE - The following job has 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. |
This PR needs a
|
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
…the answer
The dynamo tracer below this PR learned its guard-drop policy from a throwaway
probe capture: run every example once to see which guards discriminate, reset,
run them all again keeping only those. A capture is not free of side effects,
so that design is wrong twice over -- a training step's gradients accumulate
across BOTH passes (doubling every .grad the example produced), and a region
that mutates state (BatchNorm running stats, a step counter) is guarded on
values the discarded pass had already advanced past. Capture now runs ONCE and
the policy is applied on the way out, by re-serializing each frame's guards
from the pickle the capture already made (PrecompileSession._apply_guard_policy).
The re-serialization pass unpickles the capture's guard state inside the try
that converts failures to PackageError, so an unpicklable value surfaces as the
diagnostic below rather than a raw pickle error.
The policy itself is tightened to never drop a guard whose loss changes an
answer, rather than dropping everything that held invariant across the
examples, and its classification is fail-closed. The ONLY guard types the
invariance policy may drop are the explicit _INVARIANT_DROPPABLE_GUARD_TYPES:
identity guards, which the default filter drops anyway as unserializable, and
process-wide compiler state. Everything that pins semantics is kept
unconditionally: shape-bearing guards survive a single-example capture (with
one example nothing can discriminate, so the old rule dropped even the guard
that checks the runtime tensor looks like the captured one at all); TYPE_MATCH
and HASATTR, without which a graph traced for one class was reproducibly served
to another; and every guard that pins a Python fact about a value or a
container's contents -- BOOL_MATCH, CONSTANT_SUBCLASS_MATCH, NONE_MATCH,
NOT_NONE_MATCH, DICT_CONTAINS, DICT_NOT_CONTAINS, DICT_KEYS_MATCH,
MAPPING_KEYS_CHECK, NOT_PRESENT_IN_GENERIC_DICT, SET_CONTAINS, SET_NOT_CONTAINS,
TUPLE_ITERATOR_LEN, RANGE_ITERATOR_MATCH, COUNT_ITERATOR_MATCH. Each of those
is a branch the graph specialized on, so dropping it serves the captured
branch to the other side, silently. The membership guards matter because a
module-owned dict (``self.opts = {}``) is environment-rooted, which is exactly
where the policy used to drop them: ``M({"flag": 1})`` was answered with
``M({})``'s branch, no error, at the default gates. A guard type in none of the
three sets -- i.e. anything added to GuardBuilder after this -- is KEPT until
someone classifies it, and test_guard_policy_classification_is_total pins that
the sets are a disjoint, phantom-free cover of GuardBuilder's guard-producing
methods (it caught and removed a "SYMBOL_MATCH" entry that named no method;
symbolic shapes are protected through SHAPE_ENV in the unmodelled set).
A custom guard_filter_fn composes with that default instead of replacing it,
so it can drop more guards, never fewer, and the risk accounting follows: the
identity drops the default makes anyway are judged as they always are, and
only a drop the custom filter ADDED beyond the default counts as risky by
construction, because nothing here can say what the caller gave up. Previously
every drop under a custom filter was flagged risky, which made the report
useless for the common case of a filter that only drops more.
Policy-dropped facts are re-marked enforced=False in _guard_sets instead of
deleted, so the invariants report -- whose header promises a dropped line is
"a precondition NOTHING checks" -- lists them; 738 of 1207 slots on the example
model used to vanish from the file.
``require_complete`` now also refuses a capture that compiled no graph at all.
allow_empty_graphs keeps a frame that compiled nothing as one guarded code, so
guarded_codes alone cannot tell a real capture from one whose whole body sits
behind torch._dynamo.disable; such a capture carries no compiled compute, so
``summary.complete`` says so and the artifact refuses with "compiled no graph"
unless require_complete=False.
The serialization machinery underneath gets the correctness fixes this
exposed. Value pruning applies to any guarded object rather than only
nn.Module and exempts interned values (id()-keyed pruning cannot scope a
value the interpreter shares, so registering torch.float32 as missing
poisoned every other reference to it). A Guard's export bookkeeping
(code_list/guard_types, EXTENDED per build) is no longer pickled.
_SourceGraphModule's __deepcopy__ deep-copies its parameter/buffer containers
instead of sharing their tensors between "deep" copies, and its __reduce__
snapshots the instance's own parameters/buffers/submodules (re-blobbing live
sub-GraphModules) rather than pickling the shared _src whose body aliases the
ORIGINAL's containers -- a deepcopy used to pickle the original's
since-mutated tensors. An eager backend's graph is carried through the
artifact without re-tracing at load, and a bypassed entry frame reports the
real reason, counting only the entry's own bypassed codes so an unrelated
bypassed helper no longer relabels a thin-wrapper entry as a bypass.
``pickle_guards_state`` catches ``Exception`` broadly, and that now includes
the RecursionError and AssertionError it used to let through as "our bug".
They are not ours to claim: GradScaler.__getstate__ asserts when pickled
mid-iteration, tensor subclasses assert in __tensor_flatten__, a reducer can
recurse through a user object graph, and any user assert in a __reduce__ or a
property lands here. Propagating those turns a serialization limitation into
a hard torch.compile failure for a program that has nothing wrong with it.
The caller turns the resulting PackageError into a package bypass, or
re-raises it under strict_precompile, and the message names the original
exception type plus the path to the offending value, because a type alone
("cannot pickle 'generator' object") is not actionable in a model with a
thousand-frame guard tree.
Review order: start with _apply_guard_policy and the capture-once change in
torch/_precompile.py and precompile_package.py; then the survives()/pruning
policy and the three guard-type sets in precompile_package.py; then the
GuardsStatePickler changes in guards.py; the diagnostics last. This PR
carries, squashed, the contiguous segment of the #195284 stack between the
standalone-source composition below and the hardening PR above (including the
diagnostic repairs that segment needs to be green: the whole-state search and
identity attribution), so the hardening PR above shrinks by the same content.
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
```
test_capture_runs_each_example_once pins the capture-once contract with a
region that counts its own calls; test_capture_does_not_double_the_gradients_it_accumulates
and test_a_mutating_module_is_guarded_on_what_the_capture_saw pin the two
consequences the probe design got wrong. test_shape_guards_survive_a_single_example
rejects four out-of-domain calls that the old policy served;
test_a_different_class_is_refused_not_served covers TYPE_MATCH;
test_a_dict_membership_guard_is_never_dropped and
test_a_module_owned_dict_membership_guard_is_never_dropped cover the
membership guards on a local and on a module-owned dict, the latter also
asserting DICT_NOT_CONTAINS is absent from POLICY_DROPPED_GUARDS.
test_an_empty_capture_is_not_complete covers the compiled-no-graph refusal.
The unpicklable-value tests assert the diagnostic names the actual value and
its path, including a function default
(test_unpicklable_function_default_names_the_path), and a round-trip test pins
live AND pickled isolation of _SourceGraphModule copies.
Authored with an AI assistant.
ghstack-source-id: e779d5d
Pull-Request: #195371
[ghstack-poisoned]
[ghstack-poisoned]
…the answer
The dynamo tracer below this PR learned its guard-drop policy from a throwaway
probe capture: run every example once to see which guards discriminate, reset,
run them all again keeping only those. A capture is not free of side effects,
so that design is wrong twice over -- a training step's gradients accumulate
across BOTH passes (doubling every .grad the example produced), and a region
that mutates state (BatchNorm running stats, a step counter) is guarded on
values the discarded pass had already advanced past. Capture now runs ONCE and
the policy is applied on the way out, by re-serializing each frame's guards
from the pickle the capture already made (PrecompileSession._apply_guard_policy).
The re-serialization pass unpickles the capture's guard state inside the try
that converts failures to PackageError, so an unpicklable value surfaces as the
diagnostic below rather than a raw pickle error.
The policy itself is tightened to never drop a guard whose loss changes an
answer, rather than dropping everything that held invariant across the
examples, and its classification is fail-closed. The ONLY guard types the
invariance policy may drop are the explicit _INVARIANT_DROPPABLE_GUARD_TYPES:
identity guards, which the default filter drops anyway as unserializable, and
process-wide compiler state. Everything that pins semantics is kept
unconditionally: shape-bearing guards survive a single-example capture (with
one example nothing can discriminate, so the old rule dropped even the guard
that checks the runtime tensor looks like the captured one at all); TYPE_MATCH
and HASATTR, without which a graph traced for one class was reproducibly served
to another; and every guard that pins a Python fact about a value or a
container's contents -- BOOL_MATCH, CONSTANT_SUBCLASS_MATCH, NONE_MATCH,
NOT_NONE_MATCH, DICT_CONTAINS, DICT_NOT_CONTAINS, DICT_KEYS_MATCH,
MAPPING_KEYS_CHECK, NOT_PRESENT_IN_GENERIC_DICT, SET_CONTAINS, SET_NOT_CONTAINS,
TUPLE_ITERATOR_LEN, RANGE_ITERATOR_MATCH, COUNT_ITERATOR_MATCH. Each of those
is a branch the graph specialized on, so dropping it serves the captured
branch to the other side, silently. The membership guards matter because a
module-owned dict (``self.opts = {}``) is environment-rooted, which is exactly
where the policy used to drop them: ``M({"flag": 1})`` was answered with
``M({})``'s branch, no error, at the default gates. A guard type in none of the
three sets -- i.e. anything added to GuardBuilder after this -- is KEPT until
someone classifies it, and test_guard_policy_classification_is_total pins that
the sets are a disjoint, phantom-free cover of GuardBuilder's guard-producing
methods (it caught and removed a "SYMBOL_MATCH" entry that named no method;
symbolic shapes are protected through SHAPE_ENV in the unmodelled set).
A custom guard_filter_fn composes with that default instead of replacing it,
so it can drop more guards, never fewer, and the risk accounting follows: the
identity drops the default makes anyway are judged as they always are, and
only a drop the custom filter ADDED beyond the default counts as risky by
construction, because nothing here can say what the caller gave up. Previously
every drop under a custom filter was flagged risky, which made the report
useless for the common case of a filter that only drops more.
Policy-dropped facts are re-marked enforced=False in _guard_sets instead of
deleted, so the invariants report -- whose header promises a dropped line is
"a precondition NOTHING checks" -- lists them; 738 of 1207 slots on the example
model used to vanish from the file.
``require_complete`` now also refuses a capture that compiled no graph at all.
allow_empty_graphs keeps a frame that compiled nothing as one guarded code, so
guarded_codes alone cannot tell a real capture from one whose whole body sits
behind torch._dynamo.disable; such a capture carries no compiled compute, so
``summary.complete`` says so and the artifact refuses with "compiled no graph"
unless require_complete=False.
The serialization machinery underneath gets the correctness fixes this
exposed. Value pruning applies to any guarded object rather than only
nn.Module and exempts interned values (id()-keyed pruning cannot scope a
value the interpreter shares, so registering torch.float32 as missing
poisoned every other reference to it). A Guard's export bookkeeping
(code_list/guard_types, EXTENDED per build) is no longer pickled.
_SourceGraphModule's __deepcopy__ deep-copies its parameter/buffer containers
instead of sharing their tensors between "deep" copies, and its __reduce__
snapshots the instance's own parameters/buffers/submodules (re-blobbing live
sub-GraphModules) rather than pickling the shared _src whose body aliases the
ORIGINAL's containers -- a deepcopy used to pickle the original's
since-mutated tensors. An eager backend's graph is carried through the
artifact without re-tracing at load, and a bypassed entry frame reports the
real reason, counting only the entry's own bypassed codes so an unrelated
bypassed helper no longer relabels a thin-wrapper entry as a bypass.
``pickle_guards_state`` catches ``Exception`` broadly, and that now includes
the RecursionError and AssertionError it used to let through as "our bug".
They are not ours to claim: GradScaler.__getstate__ asserts when pickled
mid-iteration, tensor subclasses assert in __tensor_flatten__, a reducer can
recurse through a user object graph, and any user assert in a __reduce__ or a
property lands here. Propagating those turns a serialization limitation into
a hard torch.compile failure for a program that has nothing wrong with it.
The caller turns the resulting PackageError into a package bypass, or
re-raises it under strict_precompile, and the message names the original
exception type plus the path to the offending value, because a type alone
("cannot pickle 'generator' object") is not actionable in a model with a
thousand-frame guard tree.
Review order: start with _apply_guard_policy and the capture-once change in
torch/_precompile.py and precompile_package.py; then the survives()/pruning
policy and the three guard-type sets in precompile_package.py; then the
GuardsStatePickler changes in guards.py; the diagnostics last. This PR
carries, squashed, the contiguous segment of the #195284 stack between the
standalone-source composition below and the hardening PR above (including the
diagnostic repairs that segment needs to be green: the whole-state search and
identity attribution), so the hardening PR above shrinks by the same content.
The policy pass rebuilds each frame's guards through CheckFunctionManager with
``explicit_capture=True``, the flag the tracer commit introduced: the
serialization filter that applies the policy runs only for an explicit
capture, so without it the pass would keep every guard and drop nothing.
Test Plan:
```
python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py
```
test_capture_runs_each_example_once pins the capture-once contract with a
region that counts its own calls; test_capture_does_not_double_the_gradients_it_accumulates
and test_a_mutating_module_is_guarded_on_what_the_capture_saw pin the two
consequences the probe design got wrong. test_shape_guards_survive_a_single_example
rejects four out-of-domain calls that the old policy served;
test_a_different_class_is_refused_not_served covers TYPE_MATCH;
test_a_dict_membership_guard_is_never_dropped and
test_a_module_owned_dict_membership_guard_is_never_dropped cover the
membership guards on a local and on a module-owned dict, the latter also
asserting DICT_NOT_CONTAINS is absent from POLICY_DROPPED_GUARDS.
test_an_empty_capture_is_not_complete covers the compiled-no-graph refusal.
The unpicklable-value tests assert the diagnostic names the actual value and
its path, including a function default
(test_unpicklable_function_default_names_the_path), and a round-trip test pins
live AND pickled isolation of _SourceGraphModule copies.
Authored with an AI assistant.
ghstack-source-id: be6a956
Pull-Request: #195371
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Stack from ghstack (oldest at bottom):
The dynamo tracer below this PR learned its guard-drop policy from a throwaway
probe capture: run every example once to see which guards discriminate, reset,
run them all again keeping only those. A capture is not free of side effects,
so that design is wrong twice over -- a training step's gradients accumulate
across BOTH passes (doubling every .grad the example produced), and a region
that mutates state (BatchNorm running stats, a step counter) is guarded on
values the discarded pass had already advanced past. Capture now runs ONCE and
the policy is applied on the way out, by re-serializing each frame's guards
from the pickle the capture already made (PrecompileSession._apply_guard_policy).
The re-serialization pass unpickles the capture's guard state inside the try
that converts failures to PackageError, so an unpicklable value surfaces as the
diagnostic below rather than a raw pickle error.
The policy itself is tightened to never drop a guard whose loss changes an
answer, rather than dropping everything that held invariant across the
examples, and its classification is fail-closed. The ONLY guard types the
invariance policy may drop are the explicit _INVARIANT_DROPPABLE_GUARD_TYPES:
identity guards, which the default filter drops anyway as unserializable, and
process-wide compiler state. Everything that pins semantics is kept
unconditionally: shape-bearing guards survive a single-example capture (with
one example nothing can discriminate, so the old rule dropped even the guard
that checks the runtime tensor looks like the captured one at all); TYPE_MATCH
and HASATTR, without which a graph traced for one class was reproducibly served
to another; and every guard that pins a Python fact about a value or a
container's contents -- BOOL_MATCH, CONSTANT_SUBCLASS_MATCH, NONE_MATCH,
NOT_NONE_MATCH, DICT_CONTAINS, DICT_NOT_CONTAINS, DICT_KEYS_MATCH,
MAPPING_KEYS_CHECK, NOT_PRESENT_IN_GENERIC_DICT, SET_CONTAINS, SET_NOT_CONTAINS,
TUPLE_ITERATOR_LEN, RANGE_ITERATOR_MATCH, COUNT_ITERATOR_MATCH. Each of those
is a branch the graph specialized on, so dropping it serves the captured
branch to the other side, silently. The membership guards matter because a
module-owned dict (
self.opts = {}) is environment-rooted, which is exactlywhere the policy used to drop them:
M({"flag": 1})was answered withM({})'s branch, no error, at the default gates. A guard type in none of thethree sets -- i.e. anything added to GuardBuilder after this -- is KEPT until
someone classifies it, and test_guard_policy_classification_is_total pins that
the sets are a disjoint, phantom-free cover of GuardBuilder's guard-producing
methods (it caught and removed a "SYMBOL_MATCH" entry that named no method;
symbolic shapes are protected through SHAPE_ENV in the unmodelled set).
A custom guard_filter_fn composes with that default instead of replacing it,
so it can drop more guards, never fewer, and the risk accounting follows: the
identity drops the default makes anyway are judged as they always are, and
only a drop the custom filter ADDED beyond the default counts as risky by
construction, because nothing here can say what the caller gave up. Previously
every drop under a custom filter was flagged risky, which made the report
useless for the common case of a filter that only drops more.
Policy-dropped facts are re-marked enforced=False in _guard_sets instead of
deleted, so the invariants report -- whose header promises a dropped line is
"a precondition NOTHING checks" -- lists them; 738 of 1207 slots on the example
model used to vanish from the file.
require_completenow also refuses a capture that compiled no graph at all.allow_empty_graphs keeps a frame that compiled nothing as one guarded code, so
guarded_codes alone cannot tell a real capture from one whose whole body sits
behind torch._dynamo.disable; such a capture carries no compiled compute, so
summary.completesays so and the artifact refuses with "compiled no graph"unless require_complete=False.
The serialization machinery underneath gets the correctness fixes this
exposed. Value pruning applies to any guarded object rather than only
nn.Module and exempts interned values (id()-keyed pruning cannot scope a
value the interpreter shares, so registering torch.float32 as missing
poisoned every other reference to it). A Guard's export bookkeeping
(code_list/guard_types, EXTENDED per build) is no longer pickled.
_SourceGraphModule's deepcopy deep-copies its parameter/buffer containers
instead of sharing their tensors between "deep" copies, and its reduce
snapshots the instance's own parameters/buffers/submodules (re-blobbing live
sub-GraphModules) rather than pickling the shared _src whose body aliases the
ORIGINAL's containers -- a deepcopy used to pickle the original's
since-mutated tensors. An eager backend's graph is carried through the
artifact without re-tracing at load, and a bypassed entry frame reports the
real reason, counting only the entry's own bypassed codes so an unrelated
bypassed helper no longer relabels a thin-wrapper entry as a bypass.
pickle_guards_statecatchesExceptionbroadly, and that now includesthe RecursionError and AssertionError it used to let through as "our bug".
They are not ours to claim: GradScaler.getstate asserts when pickled
mid-iteration, tensor subclasses assert in tensor_flatten, a reducer can
recurse through a user object graph, and any user assert in a reduce or a
property lands here. Propagating those turns a serialization limitation into
a hard torch.compile failure for a program that has nothing wrong with it.
The caller turns the resulting PackageError into a package bypass, or
re-raises it under strict_precompile, and the message names the original
exception type plus the path to the offending value, because a type alone
("cannot pickle 'generator' object") is not actionable in a model with a
thousand-frame guard tree.
Review order: start with _apply_guard_policy and the capture-once change in
torch/_precompile.py and precompile_package.py; then the survives()/pruning
policy and the three guard-type sets in precompile_package.py; then the
GuardsStatePickler changes in guards.py; the diagnostics last. This PR
carries, squashed, the contiguous segment of the #195284 stack between the
standalone-source composition below and the hardening PR above (including the
diagnostic repairs that segment needs to be green: the whole-state search and
identity attribution), so the hardening PR above shrinks by the same content.
The policy pass rebuilds each frame's guards through CheckFunctionManager with
explicit_capture=True, the flag the tracer commit introduced: theserialization filter that applies the policy runs only for an explicit
capture, so without it the pass would keep every guard and drop nothing.
Test Plan:
test_capture_runs_each_example_once pins the capture-once contract with a
region that counts its own calls; test_capture_does_not_double_the_gradients_it_accumulates
and test_a_mutating_module_is_guarded_on_what_the_capture_saw pin the two
consequences the probe design got wrong. test_shape_guards_survive_a_single_example
rejects four out-of-domain calls that the old policy served;
test_a_different_class_is_refused_not_served covers TYPE_MATCH;
test_a_dict_membership_guard_is_never_dropped and
test_a_module_owned_dict_membership_guard_is_never_dropped cover the
membership guards on a local and on a module-owned dict, the latter also
asserting DICT_NOT_CONTAINS is absent from POLICY_DROPPED_GUARDS.
test_an_empty_capture_is_not_complete covers the compiled-no-graph refusal.
The unpicklable-value tests assert the diagnostic names the actual value and
its path, including a function default
(test_unpicklable_function_default_names_the_path), and a round-trip test pins
live AND pickled isolation of _SourceGraphModule copies.
Authored with an AI assistant.