Skip to content

[dynamo] Key AOTAutograd cache on annotation values; fix fx.traceback.annotate edge cases - #199954

Closed
soulitzer wants to merge 1 commit into
mainfrom
fx-annotate-float-resume
Closed

soulitzer wants to merge 1 commit into
mainfrom
fx-annotate-float-resume

Conversation

@soulitzer

@soulitzer soulitzer commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

#198959 made Dynamo carry fx.traceback.annotate across graph breaks and apply
the annotation active when a frame starts, with a guard so the frame recompiles
for each annotation value. This PR originally added float-only resumption;
#198959 landed a more general version, so it is now a follow-up that fixes the
remaining gaps.

Suggested review order:

  1. torch/_functorch/_aot_autograd/autograd_cache.py: stale AOTAutograd cache
    hits. GraphModule.__reduce__ strips node.meta, and the cache key only
    recorded the region_activation_memory_budget annotation. A frame recompiled
    under a different annotation produced a graph that differed only in
    node.meta, so it reused the first compile's cache entry. Joint passes that
    read the annotation (e.g. a CustomGraphPass, whose uuid() is fixed) never
    ran for the new value. For example, calling one compiled function under
    annotate({"ac.knob": 0.3}) and then 0.8 recompiled in Dynamo but hit the
    AOTAutograd cache, so the joint pass only ever saw 0.3. The key now records
    every annotation whose value is a constant Dynamo can embed in bytecode (the
    values [dynamo] Preserve fx.traceback.annotate across graph breaks (#198959) #198959 carries across graph breaks), which includes the budget.
    Values that are not such constants (e.g. tensors or dicts) are still not
    keyed. Keying them needs a hashing or cache-bypass policy, which is left for a
    follow-up.
  2. torch/_dynamo/variables/torch.py, the annotate handler:
    • An automatically dynamic float, e.g. per-layer self.knob values sharing
      one forward, crashed with InternalTorchDynamoError: SymNodeVariable() is not a constant from the second layer on. Dynamic floats are now
      specialized. Other dynamic values (e.g. x.shape[0]) are not, since that
      would silently recompile per size; they raise a graph break saying that
      annotation values must be static.
    • Reading entries one by one (needed for the specialization) would bypass an
      overridden __getitem__ on a dict subclass, so dict subclasses now graph
      break.
    • All three FxTracebackAnnotateVariable construction sites passed the
      factory's source. When an annotation context had to be reconstructed
      (returned without being entered, or an unentered local carried across a
      graph break), codegen loaded that source and produced the factory function
      instead of a context manager. Dropping the source makes reconstruction go
      through ContextWrappingVariable.reconstruct, which builds a fresh
      _dynamo_annotate(items) context, or graph breaks when the annotation
      cannot be embedded.

The last two items address @williamwen42's review comments.

Not addressed here: resume functions are cached by comparing annotation values
with ==, so after compiling with {"k": True}, compiling the same function
with {"k": 1} or {"k": 1.0} reuses the post-break graph annotated True.

Test Plan:

The local build predates main and the newest CPU nightly is 2026-09-23
(54b9926), so the tests ran against that nightly with #198959's torch/
changes and this PR's torch/ diff applied to the installed package. This
branch's test_fx_annotate.py was used as is; the other test files are the
nightly commit's copies, since main's copies import symbols the nightly lacks.
The new cache tests were applied to that copy of test_aot_autograd_cache.py.

python test/dynamo/test_fx_annotate.py
python test/dynamo/test_aot_autograd_cache.py
python test/dynamo/test_activation_checkpointing.py
python test/dynamo/test_regional_inductor.py

All pass: 17; 237 with 82 skipped; 27 with 5 skipped (CPU only); 48 with 8 skipped.

The new tests (test_annotate_specializes_dynamic_float,
test_annotate_dynamic_int_is_unsupported,
test_annotate_dict_subclass_is_unsupported,
test_annotation_context_across_graph_break,
test_annotation_value_causes_cache_miss and
test_constant_annotation_cache_key) all fail without this change.

This PR was authored with the assistance of an AI coding assistant (Claude).

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

@pytorch-bot

pytorch-bot Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 1 Unrelated Failure

As of commit 1f32d24 with merge base 98059d9 (image):

NEW FAILURE - The following job has failed:

  • trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) (gh)
    higher_order_ops/test_inline_asm_elementwise

    AI verdict: AI verdict: probably not related

    The test process for higher_order_ops/test_inline_asm_elementwise was killed by SIGBUS about 0.15 s after it started, before pytest ran anything (no stepcurrent file). The suspect commit changes only Python and JSON in Dynamo and the AOTAutograd cache key. That cannot cause a native bus error at interpreter or import startup, so this looks like a one-off native or runner fault on the macOS host.

    Full reasoning on HUD →

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 release notes: fx release notes category labels Oct 6, 2026
@soulitzer
soulitzer requested review from williamwen42 and removed request for williamwen42 October 6, 2026 19:25
@soulitzer
soulitzer marked this pull request as draft October 6, 2026 19:40
@soulitzer
soulitzer marked this pull request as ready for review October 7, 2026 23:23
@soulitzer
soulitzer requested a review from williamwen42 October 7, 2026 23:23

@williamwen42 williamwen42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review found 2 soundness concerns that look legitimate to me, otherwise, the changes look fine.

Comment thread torch/_dynamo/variables/torch.py Resolved
Comment thread torch/_dynamo/variables/torch.py Outdated
source=self.source,
)
annotation = dict(args[0].as_python_constant())
return FxTracebackAnnotateVariable(annotation, source=self.source)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] [dynamo] Finding 3: Return the annotation context object instead of its factory

AI-assisted analysis prepared with Codex.

Both annotation construction sites attach source=self.source to the result, although that Source identifies the called factory. Output codegen prefers the Source and returns the factory function instead of the context manager object. With the new float annotation resumption path, returning an unused annotation context after a graph break now exposes this error.

This is verified newly reachable behavior: PRE executes the suffix eagerly and returns a usable context; POST returns a function. The no-break variant already exists in PRE. Independent sdpa_kernel controls return real context objects on both revisions, and its constructor omits the factory Source.

Runnable repro:

import contextlib
import copy

import torch
import torch.fx.traceback as fx_traceback
from torch._dynamo.testing import EagerAndRecordGraphs
from torch.testing._internal.common_device_type import instantiate_device_type_tests
from torch.testing._internal.common_utils import TestCase, parametrize, run_tests


class TestAnnotationReconstruction(TestCase):
    @torch.compiler.config.patch(compile_on_one_rank=False)
    @parametrize("break_graph", (False, True))
    def test_returned_context(self, device, break_graph):
        torch._dynamo.reset()
        self.addCleanup(torch._dynamo.reset)

        def fn(x):
            ctx = fx_traceback.annotate({"knob": 0.5})
            x = x.sin()
            if break_graph:
                torch._dynamo.graph_break()
            return x.cos(), ctx

        x = torch.ones(2, device=device)
        before = copy.deepcopy(fx_traceback.current_meta)
        backend = EagerAndRecordGraphs()
        compiled = torch.compile(fn, backend=backend)
        retained = [compiled(x) for _ in range(3)]
        print(
            "break_graph:", break_graph,
            "graphs:", len(backend.graphs),
            "types:", [type(ctx).__name__ for _, ctx in retained],
            "fresh:", len({id(ctx) for _, ctx in retained}) == 3,
            flush=True,
        )
        self.assertGreaterEqual(len(backend.graphs), 1)
        self.assertEqual(len({id(ctx) for _, ctx in retained}), 3)
        for result, ctx in retained:
            self.assertEqual(result, x.sin().cos())
            self.assertIsInstance(ctx, contextlib._GeneratorContextManager)
            with ctx:
                self.assertEqual(fx_traceback.current_meta["custom"], {"knob": 0.5})
            self.assertEqual(fx_traceback.current_meta, before)
            with self.assertRaises(AttributeError):
                with ctx:
                    pass


instantiate_device_type_tests(TestAnnotationReconstruction, globals(), only_for="cpu")


if __name__ == "__main__":
    run_tests()

Run the after-break witness with python repro.py -k break_graph_True; the full script also includes the pre-existing no-break variant as a control.

PRE, after break:

break_graph: True graphs: 1 types: ['_GeneratorContextManager', '_GeneratorContextManager', '_GeneratorContextManager'] fresh: True

POST, after break:

break_graph: True graphs: 2 types: ['function', 'function', 'function'] fresh: False

POST plus suggested fix, after break:

break_graph: True graphs: 2 types: ['_GeneratorContextManager', '_GeneratorContextManager', '_GeneratorContextManager'] fresh: True

POST decisive traceback frames, paths trimmed:

  File "repros/context_source_regression.py", line 38, in test_returned_context
    self.assertEqual(len({id(ctx) for _, ctx in retained}), 3)
AssertionError: Scalars are not equal!

Expected 3 but got 1.

PRE passes the after-break assertions with one recorded graph and an eager suffix. Original POST fails the fresh-object assertion and returns functions. The suggested fix passes both cases, including actual entry, metadata restoration, and consumption after the caller enters each previously unused context.

Suggested fix:

Remove source=self.source at both annotation construction sites and use the inherited ContextWrappingVariable.reconstruct. It calls reconstruct_type with target_values, following the existing convention: symbolic_convert.create_resume handles inactive locals/stack entries, and active with-exit entries use reconstruct_type/ReenterWith.

--- a/torch/_dynamo/variables/torch.py
+++ b/torch/_dynamo/variables/torch.py
@@ -829,13 +829,13 @@
                 }
             else:
                 annotation_dict = annotation.as_python_constant()
-            return FxTracebackAnnotateVariable(annotation_dict, source=self.source)
+            return FxTracebackAnnotateVariable(annotation_dict)
         elif self.value in (
             torch.fx.traceback._dynamo_resume_annotate,
             torch.fx.traceback._dynamo_resume_annotate.__wrapped__,  # type: ignore[attr-defined]
         ):
             annotation = dict(args[0].as_python_constant())
-            return FxTracebackAnnotateVariable(annotation, source=self.source)
+            return FxTracebackAnnotateVariable(annotation)
         elif inspect.isclass(self.value) and issubclass(self.value, torch.Stream):
             from torch._dynamo.variables.builder import wrap_fx_proxy_cls

Eight targeted tests passed with this patch: the two returned-context cases, three active expression/local/local-alias cases, and the PR's three added annotation tests. The ordinary inactive local constructed before the break and entered after it also retains two correct graphs with the Source correction.

Verification used PRE 4eab5fba69c3c9a2518560eaab3f3df716af0cd1 (merge base) and POST ca73a18f55629f655f553894f4e5a76c386e6202. Both were 188 commits behind the fetched origin/main during verification. CPU tests used the existing native binary e1994aea9ce307fb82feeb7524ab2c5d36771e4f with identical compatibility adjustments outside the diff.

….annotate edge cases

#198959 made Dynamo carry `fx.traceback.annotate` across graph breaks and apply
the annotation active when a frame starts, with a guard so the frame recompiles
for each annotation value. This PR originally added float-only resumption;
#198959 landed a more general version, so it is now a follow-up that fixes the
remaining gaps.

Suggested review order:

1. `torch/_functorch/_aot_autograd/autograd_cache.py`: stale AOTAutograd cache
   hits. `GraphModule.__reduce__` strips `node.meta`, and the cache key only
   recorded the `region_activation_memory_budget` annotation. A frame recompiled
   under a different annotation produced a graph that differed only in
   `node.meta`, so it reused the first compile's cache entry. Joint passes that
   read the annotation (e.g. a `CustomGraphPass`, whose `uuid()` is fixed) never
   ran for the new value. For example, calling one compiled function under
   `annotate({"ac.knob": 0.3})` and then `0.8` recompiled in Dynamo but hit the
   AOTAutograd cache, so the joint pass only ever saw `0.3`. The key now records
   every annotation whose value is a constant Dynamo can embed in bytecode (the
   values #198959 carries across graph breaks), which includes the budget.
   Values that are not such constants (e.g. tensors or dicts) are still not
   keyed. Keying them needs a hashing or cache-bypass policy, which is left for a
   follow-up.
2. `torch/_dynamo/variables/torch.py`, the `annotate` handler:
   - An automatically dynamic float, e.g. per-layer `self.knob` values sharing
     one `forward`, crashed with `InternalTorchDynamoError: SymNodeVariable() is
     not a constant` from the second layer on. Dynamic floats are now
     specialized. Other dynamic values (e.g. `x.shape[0]`) are not, since that
     would silently recompile per size; they raise a graph break saying that
     annotation values must be static.
   - Reading entries one by one (needed for the specialization) would bypass an
     overridden `__getitem__` on a dict subclass, so dict subclasses now graph
     break.
   - All three `FxTracebackAnnotateVariable` construction sites passed the
     factory's `source`. When an annotation context had to be reconstructed
     (returned without being entered, or an unentered local carried across a
     graph break), codegen loaded that source and produced the factory function
     instead of a context manager. Dropping the source makes reconstruction go
     through `ContextWrappingVariable.reconstruct`, which builds a fresh
     `_dynamo_annotate(items)` context, or graph breaks when the annotation
     cannot be embedded.

The last two items address @williamwen42's review comments.

Not addressed here: resume functions are cached by comparing annotation values
with `==`, so after compiling with `{"k": True}`, compiling the same function
with `{"k": 1}` or `{"k": 1.0}` reuses the post-break graph annotated `True`.

Test Plan:

The local build predates main and the newest CPU nightly is 2026-09-23
(54b9926), so the tests ran against that nightly with #198959's `torch/`
changes and this PR's `torch/` diff applied to the installed package. This
branch's `test_fx_annotate.py` was used as is; the other test files are the
nightly commit's copies, since main's copies import symbols the nightly lacks.
The new cache tests were applied to that copy of `test_aot_autograd_cache.py`.

```
python test/dynamo/test_fx_annotate.py
python test/dynamo/test_aot_autograd_cache.py
python test/dynamo/test_activation_checkpointing.py
python test/dynamo/test_regional_inductor.py
```

All pass: 17; 237 with 82 skipped; 27 with 5 skipped (CPU only); 48 with 8 skipped.

The new tests (`test_annotate_specializes_dynamic_float`,
`test_annotate_dynamic_int_is_unsupported`,
`test_annotate_dict_subclass_is_unsupported`,
`test_annotation_context_across_graph_break`,
`test_annotation_value_causes_cache_miss` and
`test_constant_annotation_cache_key`) all fail without this change.

This PR was authored with the assistance of an AI coding assistant (Claude).
@soulitzer soulitzer changed the title [dynamo] Resume float-only fx.traceback.annotate across graph breaks [dynamo] Key AOTAutograd cache on annotation values; fix fx.traceback.annotate edge cases Oct 12, 2026
@soulitzer
soulitzer force-pushed the fx-annotate-float-resume branch from c74a02a to 1f32d24 Compare October 12, 2026 21:33
@soulitzer

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 13, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable)

Details for Dev Infra team Raised by workflow job

@soulitzer

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8), trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

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 Merged module: dynamo release notes: fx release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants