Repository navigation
Conversation
🔗 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 FailureAs of commit 1f32d24 with merge base 98059d9 ( 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. |
williamwen42
left a comment
There was a problem hiding this comment.
AI review found 2 soundness concerns that look legitimate to me, otherwise, the changes look fine.
| source=self.source, | ||
| ) | ||
| annotation = dict(args[0].as_python_constant()) | ||
| return FxTracebackAnnotateVariable(annotation, source=self.source) |
There was a problem hiding this comment.
[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.sourceto 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_kernelcontrols 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: TruePOST, after break:
break_graph: True graphs: 2 types: ['function', 'function', 'function'] fresh: FalsePOST plus suggested fix, after break:
break_graph: True graphs: 2 types: ['_GeneratorContextManager', '_GeneratorContextManager', '_GeneratorContextManager'] fresh: TruePOST 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.sourceat both annotation construction sites and use the inheritedContextWrappingVariable.reconstruct. It callsreconstruct_typewithtarget_values, following the existing convention:symbolic_convert.create_resumehandles inactive locals/stack entries, and active with-exit entries usereconstruct_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_clsEight 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 POSTca73a18f55629f655f553894f4e5a76c386e6202. Both were 188 commits behind the fetched origin/main during verification. CPU tests used the existing native binarye1994aea9ce307fb82feeb7524ab2c5d36771e4fwith 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).
c74a02a to
1f32d24
Compare
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable) Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge -i |
Merge startedYour 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 |
#198959 made Dynamo carry
fx.traceback.annotateacross graph breaks and applythe 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:
torch/_functorch/_aot_autograd/autograd_cache.py: stale AOTAutograd cachehits.
GraphModule.__reduce__stripsnode.meta, and the cache key onlyrecorded the
region_activation_memory_budgetannotation. A frame recompiledunder a different annotation produced a graph that differed only in
node.meta, so it reused the first compile's cache entry. Joint passes thatread the annotation (e.g. a
CustomGraphPass, whoseuuid()is fixed) neverran for the new value. For example, calling one compiled function under
annotate({"ac.knob": 0.3})and then0.8recompiled in Dynamo but hit theAOTAutograd cache, so the joint pass only ever saw
0.3. The key now recordsevery 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.
torch/_dynamo/variables/torch.py, theannotatehandler:self.knobvalues sharingone
forward, crashed withInternalTorchDynamoError: SymNodeVariable() is not a constantfrom the second layer on. Dynamic floats are nowspecialized. Other dynamic values (e.g.
x.shape[0]) are not, since thatwould silently recompile per size; they raise a graph break saying that
annotation values must be static.
overridden
__getitem__on a dict subclass, so dict subclasses now graphbreak.
FxTracebackAnnotateVariableconstruction sites passed thefactory'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 annotationcannot 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 functionwith
{"k": 1}or{"k": 1.0}reuses the post-break graph annotatedTrue.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. Thisbranch's
test_fx_annotate.pywas used as is; the other test files are thenightly 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.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_missandtest_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