Repository navigation
[dynamo] Preserve fx.traceback.annotate across graph breaks (#198959) - #198959
enlighten5 wants to merge 1 commit into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198959
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New FailureAs of commit 6166aa1 with merge base b8ef869 ( NEW FAILURE - The following job has failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@enlighten5 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D122228332. |
a2a6250 to
14812fd
Compare
14812fd to
df5f1fe
Compare
…198959) Summary: `torch.fx.traceback.annotate` / `annotate_fn` tag FX nodes with `node.meta["custom"]`, which downstream consumers (pipeline stage splitting, regional compilation, activation-checkpointing and memory-budget policies, saved-tensor hooks) use to identify where a node came from. Under `torch.compile` the tags are lost whenever the annotated region graph-breaks: - A graph break directly inside `annotate` is unsupported: `FxTracebackAnnotateVariable.reconstruct_type` raises "annotate escaped from compiled region", so Dynamo gives up on the frame and no graph is produced. - When an annotated caller graph-breaks at a call site, the callee (for example a submodule's `forward`) is compiled as a new frame while the annotation is active in eager, but its nodes are not tagged, and the cached graph is reused regardless of the annotation. This makes both cases work without new public API: 1. Resume `annotate` after a graph break. When every annotation value is a bytecode-safe constant, `FxTracebackAnnotateVariable` reconstructs as `torch.fx.traceback._dynamo_annotate(items)`, so the generated resume code re-enters the annotation around the unsupported instruction and in the resume function. This follows the existing `_dynamo_region_activation_memory_budget` path. Annotations with non-constant values keep the existing graph break, now with an accurate explanation (new GB0279 registry entry). Stream contexts, which subclass this variable, opt out because re-entering only their annotation would not restore the stream. 2. Apply the annotation active at frame start. `OutputGraph` records the ambient annotation (`fx_annotation`); `trace_frame` enables `preserve_node_meta` when it is set so every traced node carries it; and a new `FX_ANNOTATION` global-state guard (a root lambda guard, like `AUTOGRAD_SAVED_TENSORS_HOOKS`) ensures a graph compiled under one annotation is not reused under another. Frames entered with no annotation continue to reuse their graphs. `fx_annotation` is the last `OutputGraphGuardsState` field and is passed by keyword in `OutputGraphCommon`, so serialized guard state stays aligned. Test Plan: New tests in `test/dynamo/test_fx_annotate.py`: `test_graph_break_preserves_annotation`, `test_annotation_applies_to_frame_after_graph_break`, `test_frame_after_graph_break_guards_on_annotation` and `test_eager_annotation_applies_to_compiled_frame`. All four fail on the base revision and pass with this change; `test_comptime.py::test_print_guards` and `test_misc.py::test_sys_modules` (which compares exported guard code) are updated for the new guard line. `test_frame_guards_on_tensor_valued_annotation` covers switching between tensor-valued annotations: when `==` raises in the guard, `LAMBDA_GUARD` treats it as a guard failure, so the frame recompiles instead of erroring. buck2 run mode/opt fbcode//caffe2/test/dynamo:test_dynamo -- --continue-on-collection-errors -k "test_print_guards or AnnotateTests" 13 passed Regression selection (comptime, guard_serialization, precompile, package, structured_trace, recompile_ux, recompiles, guard_manager, streams, activation_checkpointing, ctx_manager, fx_annotate, aot_compile, exc, logging, error_messages, graph_deduplication, resume modules), run in mode/opt with and without this change: the only failure with the change is TestGuardSerialization::test_nested_function_preserves_a_guarded_defaults_tuple, which also fails on the base revision. Full suite with this change (x86 devvm, `fbcode//mode/opt`): ``` buck2 test fbcode//mode/opt fbcode//caffe2/test/dynamo:test_dynamo ``` Before the `test_sys_modules` update: Pass 15445, Fail 5. The failures were `test_sys_modules` and its dynamic-shapes variant (the OSS `dynamo_core` failure) and three `test_fx_graph_runnable` tests that pass when rerun on their own. After the update, the two `test_sys_modules` tests, `AnnotateTests`, and `test_print_guards` pass (15 tests). `--continue-on-collection-errors` is needed because two unrelated modules in the target fail to import on the base revision, which makes the testpilot listing fail. Reviewed By: mlazos Differential Revision: D122228332
df5f1fe to
6a51b28
Compare
…198959) Summary: `torch.fx.traceback.annotate` / `annotate_fn` tag FX nodes with `node.meta["custom"]`, which downstream consumers (pipeline stage splitting, regional compilation, activation-checkpointing and memory-budget policies, saved-tensor hooks) use to identify where a node came from. Under `torch.compile` the tags are lost whenever the annotated region graph-breaks: - A graph break directly inside `annotate` is unsupported: `FxTracebackAnnotateVariable.reconstruct_type` raises "annotate escaped from compiled region", so Dynamo gives up on the frame and no graph is produced. - When an annotated caller graph-breaks at a call site, the callee (for example a submodule's `forward`) is compiled as a new frame while the annotation is active in eager, but its nodes are not tagged, and the cached graph is reused regardless of the annotation. This makes both cases work without new public API: 1. Resume `annotate` after a graph break. When every annotation value is a bytecode-safe constant, `FxTracebackAnnotateVariable` reconstructs as `torch.fx.traceback._dynamo_annotate(items)`, so the generated resume code re-enters the annotation around the unsupported instruction and in the resume function. This follows the existing `_dynamo_region_activation_memory_budget` path. Annotations with non-constant values keep the existing graph break, now with an accurate explanation (new GB0279 registry entry). Stream contexts, which subclass this variable, opt out because re-entering only their annotation would not restore the stream. 2. Apply the annotation active at frame start. `OutputGraph` records the ambient annotation (`fx_annotation`); `trace_frame` enables `preserve_node_meta` when it is set so every traced node carries it; and a new `FX_ANNOTATION` global-state guard (a root lambda guard, like `AUTOGRAD_SAVED_TENSORS_HOOKS`) ensures a graph compiled under one annotation is not reused under another. Frames entered with no annotation continue to reuse their graphs. 3. Make `annotate` rebind `current_meta["custom"]` to a merged dict and restore the original object, instead of updating the enclosing dict in place. `trace_frame` wraps tracing in `preserve_node_meta()`, which keeps a shallow copy of `current_meta` that still points at the ambient dict; an in-place update from a nested `annotate` inlined in that frame leaked into the restored ambient annotation, so the `FX_ANNOTATION` guard failed on the frame it was just built for ("Guard failed on the same frame it was created"). Export hits this on current master because `torch._dynamo.disable` annotates its wrapped call while exporting, so frames compiled inside export (for example the `while_loop` LSTM patch) start under an ambient annotation. `fx_annotation` is the last `OutputGraphGuardsState` field and is passed by keyword in `OutputGraphCommon`, so serialized guard state stays aligned. Test Plan: New tests in `test/dynamo/test_fx_annotate.py`: `test_graph_break_preserves_annotation`, `test_annotation_applies_to_frame_after_graph_break`, `test_frame_after_graph_break_guards_on_annotation` and `test_eager_annotation_applies_to_compiled_frame`. All four fail on the base revision and pass with this change; `test_comptime.py::test_print_guards` and `test_misc.py::test_sys_modules` (which compares exported guard code) are updated for the new guard line. `test_frame_guards_on_tensor_valued_annotation` covers switching between tensor-valued annotations: when `==` raises in the guard, `LAMBDA_GUARD` treats it as a guard failure, so the frame recompiles instead of erroring. buck2 run mode/opt fbcode//caffe2/test/dynamo:test_dynamo -- --continue-on-collection-errors -k "test_print_guards or AnnotateTests" 13 passed Regression selection (comptime, guard_serialization, precompile, package, structured_trace, recompile_ux, recompiles, guard_manager, streams, activation_checkpointing, ctx_manager, fx_annotate, aot_compile, exc, logging, error_messages, graph_deduplication, resume modules), run in mode/opt with and without this change: the only failure with the change is TestGuardSerialization::test_nested_function_preserves_a_guarded_defaults_tuple, which also fails on the base revision. `test_nested_annotation_in_frame_entered_under_annotation` covers the in-place update: a function with a nested `annotate`, called under an outer annotation, keeps the outer annotation and reuses its graph. Rebased on master `f54731124de8` (2026-10-04), x86, `fbcode//mode/opt`: ``` buck2 test fbcode//mode/opt fbcode//caffe2/test:test_export fbcode//caffe2/test/dynamo:test_dynamo fbcode//caffe2/test/inductor:fxir_backend fbcode//caffe2/test/inductor:test_aot_inductor ``` Pass 23629, Fail 21. All `test_export` tests pass, including the 145 that failed in diff CI on the previous version. Of the 21 failures, rerun in isolation on this commit and on the bare master base with identical results: 13 `test_fx_graph_runnable` tests pass on both (they fail only under full-suite load), and 7 fail on both (6 `test_unspec.py` `test_random_float_draws_inductor_*` and `test_unbacked_relation_assert_lite_mode_cuda`), so they are pre-existing. `test_triton_kernel_lite_mode_cuda` is skipped in isolation on both. Earlier, on the original base: Full suite with this change (x86 devvm, `fbcode//mode/opt`): ``` buck2 test fbcode//mode/opt fbcode//caffe2/test/dynamo:test_dynamo ``` Before the `test_sys_modules` update: Pass 15445, Fail 5. The failures were `test_sys_modules` and its dynamic-shapes variant (the OSS `dynamo_core` failure) and three `test_fx_graph_runnable` tests that pass when rerun on their own. After the update, the two `test_sys_modules` tests, `AnnotateTests`, and `test_print_guards` pass (15 tests). `--continue-on-collection-errors` is needed because two unrelated modules in the target fail to import on the base revision, which makes the testpilot listing fail. Reviewed By: mlazos Differential Revision: D122228332
…198959) Summary: Pull Request resolved: pytorch#198959 `torch.fx.traceback.annotate` / `annotate_fn` tag FX nodes with `node.meta["custom"]`, which downstream consumers (pipeline stage splitting, regional compilation, activation-checkpointing and memory-budget policies, saved-tensor hooks) use to identify where a node came from. Under `torch.compile` the tags are lost whenever the annotated region graph-breaks: - A graph break directly inside `annotate` is unsupported: `FxTracebackAnnotateVariable.reconstruct_type` raises "annotate escaped from compiled region", so Dynamo gives up on the frame and no graph is produced. - When an annotated caller graph-breaks at a call site, the callee (for example a submodule's `forward`) is compiled as a new frame while the annotation is active in eager, but its nodes are not tagged, and the cached graph is reused regardless of the annotation. This makes both cases work without new public API: 1. Resume `annotate` after a graph break. When every annotation value is a bytecode-safe constant, `FxTracebackAnnotateVariable` reconstructs as `torch.fx.traceback._dynamo_annotate(items)`, so the generated resume code re-enters the annotation around the unsupported instruction and in the resume function. This follows the existing `_dynamo_region_activation_memory_budget` path. Annotations with non-constant values keep the existing graph break, now with an accurate explanation (new GB0279 registry entry). Stream contexts, which subclass this variable, opt out because re-entering only their annotation would not restore the stream. 2. Apply the annotation active at frame start. `OutputGraph` records the ambient annotation (`fx_annotation`); `trace_frame` enables `preserve_node_meta` when it is set so every traced node carries it; and a new `FX_ANNOTATION` global-state guard (a root lambda guard, like `AUTOGRAD_SAVED_TENSORS_HOOKS`) ensures a graph compiled under one annotation is not reused under another. Frames entered with no annotation continue to reuse their graphs. 3. Make `annotate` rebind `current_meta["custom"]` to a merged dict and restore the original object, instead of updating the enclosing dict in place. `trace_frame` wraps tracing in `preserve_node_meta()`, which keeps a shallow copy of `current_meta` that still points at the ambient dict; an in-place update from a nested `annotate` inlined in that frame leaked into the restored ambient annotation, so the `FX_ANNOTATION` guard failed on the frame it was just built for ("Guard failed on the same frame it was created"). Export hits this on current master because `torch._dynamo.disable` annotates its wrapped call while exporting, so frames compiled inside export (for example the `while_loop` LSTM patch) start under an ambient annotation. `fx_annotation` is the last `OutputGraphGuardsState` field and is passed by keyword in `OutputGraphCommon`, so serialized guard state stays aligned. Test Plan: New tests in `test/dynamo/test_fx_annotate.py`: `test_graph_break_preserves_annotation`, `test_annotation_applies_to_frame_after_graph_break`, `test_frame_after_graph_break_guards_on_annotation` and `test_eager_annotation_applies_to_compiled_frame`. All four fail on the base revision and pass with this change; `test_comptime.py::test_print_guards` and `test_misc.py::test_sys_modules` (which compares exported guard code) are updated for the new guard line. `test_frame_guards_on_tensor_valued_annotation` covers switching between tensor-valued annotations: when `==` raises in the guard, `LAMBDA_GUARD` treats it as a guard failure, so the frame recompiles instead of erroring. buck2 run mode/opt fbcode//caffe2/test/dynamo:test_dynamo -- --continue-on-collection-errors -k "test_print_guards or AnnotateTests" 13 passed Regression selection (comptime, guard_serialization, precompile, package, structured_trace, recompile_ux, recompiles, guard_manager, streams, activation_checkpointing, ctx_manager, fx_annotate, aot_compile, exc, logging, error_messages, graph_deduplication, resume modules), run in mode/opt with and without this change: the only failure with the change is TestGuardSerialization::test_nested_function_preserves_a_guarded_defaults_tuple, which also fails on the base revision. `test_nested_annotation_in_frame_entered_under_annotation` covers the in-place update: a function with a nested `annotate`, called under an outer annotation, keeps the outer annotation and reuses its graph. Rebased on master `f54731124de8` (2026-10-04), x86, `fbcode//mode/opt`: ``` buck2 test fbcode//mode/opt fbcode//caffe2/test:test_export fbcode//caffe2/test/dynamo:test_dynamo fbcode//caffe2/test/inductor:fxir_backend fbcode//caffe2/test/inductor:test_aot_inductor ``` Pass 23629, Fail 21. All `test_export` tests pass, including the 145 that failed in diff CI on the previous version. Of the 21 failures, rerun in isolation on this commit and on the bare master base with identical results: 13 `test_fx_graph_runnable` tests pass on both (they fail only under full-suite load), and 7 fail on both (6 `test_unspec.py` `test_random_float_draws_inductor_*` and `test_unbacked_relation_assert_lite_mode_cuda`), so they are pre-existing. `test_triton_kernel_lite_mode_cuda` is skipped in isolation on both. Earlier, on the original base: Full suite with this change (x86 devvm, `fbcode//mode/opt`): ``` buck2 test fbcode//mode/opt fbcode//caffe2/test/dynamo:test_dynamo ``` Before the `test_sys_modules` update: Pass 15445, Fail 5. The failures were `test_sys_modules` and its dynamic-shapes variant (the OSS `dynamo_core` failure) and three `test_fx_graph_runnable` tests that pass when rerun on their own. After the update, the two `test_sys_modules` tests, `AnnotateTests`, and `test_print_guards` pass (15 tests). `--continue-on-collection-errors` is needed because two unrelated modules in the target fail to import on the base revision, which makes the testpilot listing fail. Reviewed By: mlazos Differential Revision: D122228332
6a51b28 to
6166aa1
Compare
|
@pytorchbot merge (Initiating merge automatically since Phabricator Diff has merged) |
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, 2, 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 1 checks: trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…198959) (pytorch#198959) Summary: `torch.fx.traceback.annotate` / `annotate_fn` tag FX nodes with `node.meta["custom"]`, which downstream consumers (pipeline stage splitting, regional compilation, activation-checkpointing and memory-budget policies, saved-tensor hooks) use to identify where a node came from. Under `torch.compile` the tags are lost whenever the annotated region graph-breaks: - A graph break directly inside `annotate` is unsupported: `FxTracebackAnnotateVariable.reconstruct_type` raises "annotate escaped from compiled region", so Dynamo gives up on the frame and no graph is produced. - When an annotated caller graph-breaks at a call site, the callee (for example a submodule's `forward`) is compiled as a new frame while the annotation is active in eager, but its nodes are not tagged, and the cached graph is reused regardless of the annotation. This makes both cases work without new public API: 1. Resume `annotate` after a graph break. When every annotation value is a bytecode-safe constant, `FxTracebackAnnotateVariable` reconstructs as `torch.fx.traceback._dynamo_annotate(items)`, so the generated resume code re-enters the annotation around the unsupported instruction and in the resume function. This follows the existing `_dynamo_region_activation_memory_budget` path. Annotations with non-constant values keep the existing graph break, now with an accurate explanation (new GB0279 registry entry). Stream contexts, which subclass this variable, opt out because re-entering only their annotation would not restore the stream. 2. Apply the annotation active at frame start. `OutputGraph` records the ambient annotation (`fx_annotation`); `trace_frame` enables `preserve_node_meta` when it is set so every traced node carries it; and a new `FX_ANNOTATION` global-state guard (a root lambda guard, like `AUTOGRAD_SAVED_TENSORS_HOOKS`) ensures a graph compiled under one annotation is not reused under another. Frames entered with no annotation continue to reuse their graphs. 3. Make `annotate` rebind `current_meta["custom"]` to a merged dict and restore the original object, instead of updating the enclosing dict in place. `trace_frame` wraps tracing in `preserve_node_meta()`, which keeps a shallow copy of `current_meta` that still points at the ambient dict; an in-place update from a nested `annotate` inlined in that frame leaked into the restored ambient annotation, so the `FX_ANNOTATION` guard failed on the frame it was just built for ("Guard failed on the same frame it was created"). Export hits this on current master because `torch._dynamo.disable` annotates its wrapped call while exporting, so frames compiled inside export (for example the `while_loop` LSTM patch) start under an ambient annotation. `fx_annotation` is the last `OutputGraphGuardsState` field and is passed by keyword in `OutputGraphCommon`, so serialized guard state stays aligned. Test Plan: New tests in `test/dynamo/test_fx_annotate.py`: `test_graph_break_preserves_annotation`, `test_annotation_applies_to_frame_after_graph_break`, `test_frame_after_graph_break_guards_on_annotation` and `test_eager_annotation_applies_to_compiled_frame`. All four fail on the base revision and pass with this change; `test_comptime.py::test_print_guards` and `test_misc.py::test_sys_modules` (which compares exported guard code) are updated for the new guard line. `test_frame_guards_on_tensor_valued_annotation` covers switching between tensor-valued annotations: when `==` raises in the guard, `LAMBDA_GUARD` treats it as a guard failure, so the frame recompiles instead of erroring. buck2 run mode/opt fbcode//caffe2/test/dynamo:test_dynamo -- --continue-on-collection-errors -k "test_print_guards or AnnotateTests" 13 passed Regression selection (comptime, guard_serialization, precompile, package, structured_trace, recompile_ux, recompiles, guard_manager, streams, activation_checkpointing, ctx_manager, fx_annotate, aot_compile, exc, logging, error_messages, graph_deduplication, resume modules), run in mode/opt with and without this change: the only failure with the change is TestGuardSerialization::test_nested_function_preserves_a_guarded_defaults_tuple, which also fails on the base revision. `test_nested_annotation_in_frame_entered_under_annotation` covers the in-place update: a function with a nested `annotate`, called under an outer annotation, keeps the outer annotation and reuses its graph. Rebased on master `f54731124de8` (2026-10-04), x86, `fbcode//mode/opt`: ``` buck2 test fbcode//mode/opt fbcode//caffe2/test:test_export fbcode//caffe2/test/dynamo:test_dynamo fbcode//caffe2/test/inductor:fxir_backend fbcode//caffe2/test/inductor:test_aot_inductor ``` Pass 23629, Fail 21. All `test_export` tests pass, including the 145 that failed in diff CI on the previous version. Of the 21 failures, rerun in isolation on this commit and on the bare master base with identical results: 13 `test_fx_graph_runnable` tests pass on both (they fail only under full-suite load), and 7 fail on both (6 `test_unspec.py` `test_random_float_draws_inductor_*` and `test_unbacked_relation_assert_lite_mode_cuda`), so they are pre-existing. `test_triton_kernel_lite_mode_cuda` is skipped in isolation on both. Earlier, on the original base: Full suite with this change (x86 devvm, `fbcode//mode/opt`): ``` buck2 test fbcode//mode/opt fbcode//caffe2/test/dynamo:test_dynamo ``` Before the `test_sys_modules` update: Pass 15445, Fail 5. The failures were `test_sys_modules` and its dynamic-shapes variant (the OSS `dynamo_core` failure) and three `test_fx_graph_runnable` tests that pass when rerun on their own. After the update, the two `test_sys_modules` tests, `AnnotateTests`, and `test_print_guards` pass (15 tests). `--continue-on-collection-errors` is needed because two unrelated modules in the target fail to import on the base revision, which makes the testpilot listing fail. Reviewed By: mlazos Differential Revision: D122228332 Pull Request resolved: pytorch#198959 Approved by: https://github.com/mlazos
….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).
….annotate edge cases (#199954) #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). Pull Request resolved: #199954 Approved by: https://github.com/williamwen42
…x per layer (#5547) **TLDR:** Two CI fixes for the GraphTrainer and 8 GPU Integration jobs. 1. Fixes #5366. The Flex eager-vs-trace bitwise tests compiled flex once per layer in the eager reference, and after 8 graphs Dynamo silently ran unfused eager flex. The traced side was correct; the eager reference changed. With this PR the eager reference compiles flex once, like the core and RL trainers, and hitting the recompile limit raises instead of falling back. 2. Fixes PP after #3980. #3980 made PP preprocessing return 4 values, but two callers still unpacked 3, so every PP + CUDA graph integration test and the GraphTrainer PP numerics test fail on main with `ValueError: too many values to unpack (expected 3)`. ## 1. Flex bitwise tests compiled flex per layer (#5366) **Problem** 1. **The eager reference was annotated.** `_run_steps` called `annotate_graph_trainer_model` for both `Trainer` and `GraphTrainer`. It wraps every submodule's forward with `annotate_fn({"module_fqn": fqn})`. Only GraphTrainer's graph passes read these tags. The core and RL trainers never set them. 2. **Dynamo now guards on the annotation.** pytorch/pytorch#198959 (October 10 nightly, the first failing one) adds an `FX_ANNOTATION` guard. Each layer's `inner_attention` has a different `module_fqn`, so the eager compiled flex compiles once per layer: 8 graphs for Qwen3 debugmodel_moe, all identical. 3. **The graphs carry over between tests.** Dynamo caches them on `flex_attention`'s code object, which outlives the `torch.compile` wrapper rebuilt in `setUp`. Llama3 Flex leaves 6. Qwen3 MoE Flex then passes the limit of 8 at its third layer. 4. **Silent fallback.** Past the limit, Dynamo runs flex eagerly, which is the unfused implementation, so the eager loss changes: `hit config.recompile_limit (8)`, then `eager vs aot_fx_trace: loss mismatch`. **Solution** 1. **Annotate only GraphTrainer runs.** The eager reference stays unannotated, like the core and RL trainers. 2. **`fullgraph=True` and `recompile_limit=16`** on the test's flex compile, the same settings as #5442. Hitting the limit raises instead of falling back. 3. **`torch._dynamo.reset()` in `setUp`.** Tests no longer share flex graphs. 4. **Unchanged:** the GraphTrainer runs, their annotations, and every assertion. ## 2. PP callers still unpacked 3 values after #3980 **Problem** 1. #3980 made `TrainingEngine._preprocess_microbatch_group` return `(arg_mbs, kwarg_mbs, target_mbs, loss_kwarg_mbs)` under PP. 2. `prepare_for_capture` (PP + CUDA graphs, added by #5241 before #3980 landed) still unpacked 3 values. Every PP test in the 8 GPU features job fails there: 3d, pp_1f1b, pp_dp_tp, pp_looped_zero_bubble, lora, and others. On main, that job passes at #3980's parent `efdde5eda` and fails at #3980 `a4a62b349`. 3. GraphTrainer PP reuses the core preprocessing, and its forward-backward loop also unpacked 3 values, so `test_dense_llama3_hsdp_graph_pp_vs_eager` fails. The GraphTrainer job uses `set -eux`, so it stops there and never reaches `test_bitwise_deterministic.py`. 4. The CPU test for `prepare_for_capture` still fed the old 3-tuple, which hid the mismatch. **Solution** 1. **`prepare_for_capture`** unpacks 4 values and passes the first microbatch's loss arguments plus `global_loss_token_counts` to schedule initialization. Initialization calls the loss on that microbatch, as the real step does. 2. **GraphTrainer PP** drops the fourth element. GraphTrainer rejects per-microbatch loss arguments earlier, so it is always empty, and both paths now return `(arg_mbs, kwarg_mbs, target_mbs)`, as before #3980. 3. **The CPU test** feeds the PP layout with a per-microbatch loss argument and checks the loss arguments passed to initialization. It fails without the fix with the same `ValueError`. ## Results ```text torch 2.16.0.dev20261019+cu132, GB200 (2 GPUs), flash-attn-4 1. Llama3 Flex -> Qwen3 MoE Flex test_aot_fx_trace_vs_eager, in one process main: "hit config.recompile_limit (8)", then eager vs aot_fx_trace: loss mismatch: 6.995096683502197 vs 6.995151519775391 this PR: pass, 1 flex graph per test, eager == traced == 6.995151519775391 flex graphs after the Qwen3 MoE Flex eager run (test run alone) annotated eager (main): 8 (one per layer) unannotated eager: 1, same loss Full test_bitwise_deterministic.py main: recompile limit hit once; on GB200 it breaks TestDSv3FlexAttnBitwiseDeterministic::test_aot_fx_trace_vs_eager and ::test_ep_chunk_matches_eager_chunking_bitwise this PR: 16 passed (Varlen and Flex), 9 skipped, no recompile limit hit 2. PP pp_1f1b integration test (2 GPUs, PP + CUDA graphs) main: ValueError in prepare_for_capture this PR: 10 steps pass GraphTrainer PP (the HSDP+PP numerics config reduced to PP=2, 2 GPUs) main: ValueError in GraphTrainer _forward_backward_body this PR: trains ``` You may ask: does the core trainer recompile flex per layer too? No. Llama3 1B (16 layers) with flex on the core `Trainer` compiles flex once and never recompiles. Only an annotated eager model recompiles per layer. NOTE: GraphTrainer's validator runs the annotated model eagerly, so Flex validation on a model with more than 8 layers should hit the same per-layer recompiles. Not covered here. NOTE: `test_dense_llama3_hsdp_graph_pp_vs_eager` needs 8 GPUs, so I could not run it locally. On the PP=2 reduction, eager PP vs GraphPP misses its grad_norm tolerance (max 1.7e-4) both with this PR and at #3980's parent, so that gap comes from the reduced config, not this PR. The full 8 GPU test passed on main before #3980. **Test plan** - `pytest torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py`: 16 passed, 9 skipped. - The Llama3 Flex -> Qwen3 MoE Flex pair from #5366 passes in one process. - `python -m tests.integration_tests.run_tests <out> --test_suite features --test_name pp_1f1b --ngpu 2`: passes; fails on main. - `pytest tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/distributed/test_cuda_graph.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/distributed/test_pipeline_parallel.py`: 135 passed. - CI: GraphTrainer 8 GPU and 8 GPU Integration (features) jobs.
Summary:
torch.fx.traceback.annotate/annotate_fntag FX nodes withnode.meta["custom"], which downstream consumers (pipeline stage splitting, regional compilation, activation-checkpointing and memory-budget policies, saved-tensor hooks) use to identify where a node came from. Undertorch.compilethe tags are lost whenever the annotated region graph-breaks:annotateis unsupported:FxTracebackAnnotateVariable.reconstruct_typeraises "annotate escaped from compiled region", so Dynamo gives up on the frame and no graph is produced.forward) is compiled as a new frame while the annotation is active in eager, but its nodes are not tagged, and the cached graph is reused regardless of the annotation.This makes both cases work without new public API:
Resume
annotateafter a graph break. When every annotation value is a bytecode-safe constant,FxTracebackAnnotateVariablereconstructs astorch.fx.traceback._dynamo_annotate(items), so the generated resume code re-enters the annotation around the unsupported instruction and in the resume function. This follows the existing_dynamo_region_activation_memory_budgetpath. Annotations with non-constant values keep the existing graph break, now with an accurate explanation (new GB0279 registry entry). Stream contexts, which subclass this variable, opt out because re-entering only their annotation would not restore the stream.Apply the annotation active at frame start.
OutputGraphrecords the ambient annotation (fx_annotation);trace_frameenablespreserve_node_metawhen it is set so every traced node carries it; and a newFX_ANNOTATIONglobal-state guard (a root lambda guard, likeAUTOGRAD_SAVED_TENSORS_HOOKS) ensures a graph compiled under one annotation is not reused under another. Frames entered with no annotation continue to reuse their graphs.Make
annotaterebindcurrent_meta["custom"]to a merged dict and restore the original object, instead of updating the enclosing dict in place.trace_framewraps tracing inpreserve_node_meta(), which keeps a shallow copy ofcurrent_metathat still points at the ambient dict; an in-place update from a nestedannotateinlined in that frame leaked into the restored ambient annotation, so theFX_ANNOTATIONguard failed on the frame it was just built for ("Guard failed on the same frame it was created"). Export hits this on current master becausetorch._dynamo.disableannotates its wrapped call while exporting, so frames compiled inside export (for example thewhile_loopLSTM patch) start under an ambient annotation.fx_annotationis the lastOutputGraphGuardsStatefield and is passed by keyword inOutputGraphCommon, so serialized guard state stays aligned.Test Plan:
New tests in
test/dynamo/test_fx_annotate.py:test_graph_break_preserves_annotation,test_annotation_applies_to_frame_after_graph_break,test_frame_after_graph_break_guards_on_annotationandtest_eager_annotation_applies_to_compiled_frame. All four fail on the base revision and pass with this change;test_comptime.py::test_print_guardsandtest_misc.py::test_sys_modules(which compares exported guard code) are updated for the new guard line.test_frame_guards_on_tensor_valued_annotationcovers switching between tensor-valued annotations: when==raises in the guard,LAMBDA_GUARDtreats it as a guard failure, so the frame recompiles instead of erroring.buck2 run mode/opt fbcode//caffe2/test/dynamo:test_dynamo -- --continue-on-collection-errors -k "test_print_guards or AnnotateTests"
13 passed
Regression selection (comptime, guard_serialization, precompile, package, structured_trace, recompile_ux, recompiles, guard_manager, streams, activation_checkpointing, ctx_manager, fx_annotate, aot_compile, exc, logging, error_messages, graph_deduplication, resume modules), run in mode/opt with and without this change: the only failure with the change is TestGuardSerialization::test_nested_function_preserves_a_guarded_defaults_tuple, which also fails on the base revision.
test_nested_annotation_in_frame_entered_under_annotationcovers the in-place update: a function with a nestedannotate, called under an outer annotation, keeps the outer annotation and reuses its graph.Rebased on master
f54731124de8(2026-10-04), x86,fbcode//mode/opt:Pass 23629, Fail 21. All
test_exporttests pass, including the 145 that failed in diff CI on the previous version. Of the 21 failures, rerun in isolation on this commit and on the bare master base with identical results: 13test_fx_graph_runnabletests pass on both (they fail only under full-suite load), and 7 fail on both (6test_unspec.pytest_random_float_draws_inductor_*andtest_unbacked_relation_assert_lite_mode_cuda), so they are pre-existing.test_triton_kernel_lite_mode_cudais skipped in isolation on both.Earlier, on the original base:
Full suite with this change (x86 devvm,
fbcode//mode/opt):Before the
test_sys_modulesupdate: Pass 15445, Fail 5. The failures weretest_sys_modulesand its dynamic-shapes variant (the OSSdynamo_corefailure) and threetest_fx_graph_runnabletests that pass when rerun on their own. After the update, the twotest_sys_modulestests,AnnotateTests, andtest_print_guardspass (15 tests).--continue-on-collection-errorsis needed because two unrelated modules in the target fail to import on the base revision, which makes the testpilot listing fail.Reviewed By: mlazos
Differential Revision: D122228332
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98