Skip to content

[precompile] Carry an eager backend's graph without re-tracing it at load - #194300

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

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

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

An eager-backend subgraph ships as a pickled GraphModule, and
GraphModule.__reduce__ deliberately serializes only the generated source,
recovering the Graph at load by symbolically re-tracing that source. For an fx
graph that round trip is the documented BC guarantee. For a DYNAMO graph it is
lossy, and the interesting half of the loss is silent.

Three failure classes, all measured on backend="eager", tracer="dynamo":

A HOP explodes. torch.cond, torch._higher_order_ops.while_loop,
torch.vmap and nested_compile_region all reject a Proxy operand, so
precompile.load raises AssertionError/TraceError from
_deserialize_graph_module.

An in-graph context manager is silently deleted. _enter_autocast /
_exit_autocast and torch._C._set_grad_enabled take no Proxy at all, so
the retrace EXECUTES them and records nothing: the graph goes 9 nodes to 7 and
the artifact serves fp32 where capture chose bf16, or returns a tensor carrying
a SinBackward0 from a region the user wrote under no_grad.

The retrace's side effects escape onto the loader. Because
_set_grad_enabled(True) actually runs, precompile.load() called inside
torch.no_grad() returns with grad enabled.

Only eager is affected: an inductor capture renders its subgraphs to source and
never goes through this pickle. Nor is it precompile-specific -- the same graph
through plain CompilePackage + DiskDynamoStore + record_eager_backend
fails the same way. And backend="inductor" is not a workaround for such a
model: AOTAutogradCache's check_node_safe refuses it at capture. The eager
path has no equivalent gate, so it accepts a graph it cannot reload.

The fix is to stop re-deriving the Graph. Nothing reads .graph on a
top-level Dynamo graph -- _install_codes installs the value as a module
global and calls it -- so _SourceGraphModule rebuilds the module by exec'ing
the same generated source and simply has no Graph. Nested HOP bodies DO need
one, because some eager HOP implementations run their body through
fx.Interpreter; those go through torch.fx._graph_pickler.GraphPickler,
which serializes a graph node by node with no retrace.

Serializing everything with GraphPickler was the obvious alternative and is
worse: it fails 8 tests in test_precompile.py (the no_dispatch() deepcopy in
record_artifact), grows the artifact 16-28%, and raises
RuntimeError: Cannot access data pointer at capture on a stock
nn.MultiheadAttention, whose node.meta["example_value"] reaches a meta
storage through a weakref. The hybrid is size-neutral -- 90,589 chars against
the baseline's 90,645 on a 6-block net -- because the top-level graph is carried
as exactly the source the old reduction carried.

Two of the three methods added to EagerCacheArtifact and
_SourceGraphModule look optional and are not. Without
_SourceGraphModule.__reduce__, an artifact that is re-serialized after being
loaded once raises PicklingError on the exec'd forward (4 errors in
test_package.py). Without __deepcopy__, deepcopy falls through to
__reduce__ and rebuilds fake tensors under the no_dispatch() that
PrecompileContext.record_artifact copies inside, which asserts in
meta_utils -- so the INSTALLED serving mode fails for every HOP graph, and only
installed-mode tests catch it.

Read-BC is automatic: bytes pickled by the old code carry the old recipe.
torch._dynamo.aot_compile's force_autograd_cache path hands over a
GraphModuleSerializableCallable rather than a bound forward and keeps the
old lossy reduction; precompile never reaches it, and the pass-through branch
says so.

Test Plan:

python test/test_precompile.py
python test/dynamo/test_package.py
python test/dynamo/test_precompile_context.py
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_aot_compile.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.

The new tests are a matrix over cond / while_loop / vmap / autocast /
checkpoint, each in both serving modes, asserting equality with
torch.compile(backend="eager") -- which for autocast is a dtype assertion,
since assertEqual compares dtype. 10 of the 12 fail without this change;
checkpoint is the exception and is there for the other half of the fix, since it
is the construct whose body is run through fx.Interpreter and so the one that
proves a nested body must keep a real Graph. The grad-mode pair is separate
because it fails in two directions: the served output's requires_grad, and
torch.is_grad_enabled() in the caller after load().

Also checked by hand, all serving with matching numerics: MultiheadAttention,
TransformerEncoderLayer, SDPA, flex_attention, a module with a buffer, a
closed-over global tensor, unbacked .item(), a custom autograd.Function,
dynamic shapes (including a shape never captured), and a training capture.

Authored with an AI assistant.

Differential Revision: D116865484

[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/194300

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

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

As of commit 96918ae 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:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but was 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 #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/1012/head branch November 12, 2026 01:44
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