Skip to content

[inductor] Preserve directional cudagraph decisions in AOTAutograd cache - #194632

Closed
desertfire wants to merge 5 commits into
gh/desertfire/756/basefrom
gh/desertfire/756/head
Closed

desertfire wants to merge 5 commits into
gh/desertfire/756/basefrom
gh/desertfire/756/head

Conversation

@desertfire

@desertfire desertfire commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

AOTAutograd cache loading reconstructs FX compiler state from a forward-derived
shared BoxedBool. With override_cudagraphs(bwd=False), a cold backward compile
used a separate disabled decision, but that directional choice was absent from
the AOTAutograd key and the serialized backward artifact. A warm load could
therefore reuse the forward's enabled decision for the backward.

Propagate the existing cudagraphs_bwd_override through the FX graph and
AOTAutograd cache inputs, and consult the serialized value during post_compile.
Include the override only when it is non-None so graphs without one retain their
existing cache keys. The copy in create_fx_config distinguishes AOTAutograd
entries; runtime behavior comes from the value serialized with the compiled
graph.

Test Plan:

python test/dynamo/test_aot_autograd_cache.py -k cudagraphs_bwd_override_omitted_when_unset -v
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "cudagraph_backward_override", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
lintrunner -a

This change was authored with the assistance of an AI coding agent.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 12 Pending, 1 Unrelated Failure

As of commit bc453ed with merge base d535485 (image):

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.

@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 17m 54s —— View job


Reviewed — the fix addresses a real bug, but the test only covers the cache-key half and none of the post_compile changes that are the actual point of the PR; there is also a three-way naming duplication for a single concept.

Full review

PR Review: #194632

Summary

Threads the override_cudagraphs(bwd=...) decision into the AOTAutograd cache key and into CompiledFxGraph.post_compile, and switches partition post-compile selection from ambient config.graph_partition to the artifact's partition_maps. I confirmed both bugs are real, but the test coverage does not exercise the fix, and the plumbing introduces three names for one value.

Testing

The new test does not test the bug the PR is about. test_cudagraph_backward_override_affects_aot_cache_key (test/inductor/test_cudagraph_trees.py:1148) asserts only autograd_cache_miss == 2 / autograd_cache_hit == 0, i.e. it covers the autograd_cache.py cache-key change and nothing else. The output_code.py changes — 28 of the 67 added lines, and the part the PR title calls out — are only reachable on an AOTAutograd cache hit, which this test explicitly asserts never happens.

I traced the failure mode to confirm it is real: on a hit, _load_and_post_compile (torch/_functorch/_aot_autograd/aot_autograd_result.py:484) builds bw_fx_config = {**fx_config, "is_backward": True} where fx_config["cudagraphs"] is compiler_config_extra.cudagraphs — the forward-derived shared BoxedBool, still True under bwd=False. So a same-annotation cache hit in a fresh process would cudagraph the backward that cold compilation skipped. Nothing in the diff tests that.

The existing sibling test shows the shape a real regression test should take (test_backward_gets_cached_cudagraphs, line 1107): compile, torch._dynamo.reset(), re-run to get autograd_cache_hit == 1, then assert the cudagraph decision. Please add a test that:

  1. runs under override_cudagraphs(bwd=False), then torch._dynamo.reset() and runs the same annotated code again,
  2. asserts counters["aot_autograd"]["autograd_cache_hit"] == 1,
  3. asserts the backward was not cudagraphed on the hit (e.g. counters["inductor"]["cudagraph_skips"], or the forward-only shape of self.get_root_children()).

Without step 3 the output_code.py change could be reverted and CI would stay green.

No test for the partition_maps post-compile change. The config.graph_partition → self.partition_maps is not None swap at output_code.py:857 and :935 changes routing precisely when the compile-time and load-time graph_partition settings disagree — which is untested. A test that compiles under @torch._inductor.config.patch("graph_partition", True), then loads from cache under graph_partition=False (and the reverse) is the direct regression test. Note the reverse direction was previously an outright crash: cudagraph_partition_post_compile asserts recursively_apply_fns is not None (output_code.py:369), which is None for an artifact compiled without partitions.

Test is missing the config decorators every sibling cache test carries. Lines 1102-1106 and 1173-1177 each apply:

@torch._functorch.config.patch("enable_autograd_cache", True)
@torch._inductor.config.patch("fx_graph_cache", True)
@torch._inductor.config.patch("fx_graph_remote_cache", False)
@torch._dynamo.config.patch("specialize_float", True)

The new test at line 1148 has none. enable_autograd_cache and fx_graph_cache are Config(justknob=...) (torch/_functorch/config.py:71, torch/_inductor/config.py:109), so their values are environment-dependent, and fx_graph_remote_cache is left unpinned — a remote cache hit in fbcode would change the counters. Match the sibling pattern.

Code Quality

Three names for one value. The same bwd override is now spelled three ways:

  • CompilerConfigExtra.cudagraphs_bwd_override (compile_fx.py:2701)
  • _CompileFxKwargs["backward_cudagraphs_annotation_override"] (compile_fx.py:970)
  • _CompileFxKwargs["cudagraphs_post_compile_override"] (compile_fx.py:972)

The last two hold the identical value and both live in the same TypedDict. backward_cudagraphs_annotation_override is never read anywhere — I grepped the whole tree and the only hits are its declaration and its assignment in create_fx_config. It exists purely to perturb the hash, and it also rides along unused in graph_kwargs on the cache-hit path.

Emit cudagraphs_post_compile_override from create_fx_config instead and drop backward_cudagraphs_annotation_override entirely. That gets the cache-key effect and means the same key name appears on both the cold and cache-hit paths, so a future reader doesn't have to discover that two differently-named fields are the same thing. Fix this →

Undocumented field is the one that needs the comment. At compile_fx.py:969-972, the explanatory comment sits above cudagraphs_post_compile_override, whose name is fairly self-describing, while backward_cudagraphs_annotation_override — the write-only, cache-key-only field — gets nothing. If it survives the unification above, it needs a comment saying it is a hash ingredient only.

Dead branch in the new override logic. create_compiler_config_extra only ever sets cudagraphs_bwd_override to False: compile_fx.py:2737 guards on cudagraphs.value and annotation.bwd is not None and not annotation.bwd. So BoxedBool(cudagraphs_post_compile_override) at output_code.py:892 is always BoxedBool(False), and the comment at compile_fx.py:970-971 ("True/False forces a graph-local decision") describes an unreachable case. If a True override ever became reachable it would be a latent bug: it would re-enable cudagraphs for the backward even when the shared box had been legitimately disabled during the forward (e.g. CPU-only graph, output_code.py:662). Either narrow the type/comment to the reachable case or handle True as graph_cudagraphs = graph_kwargs["cudagraphs"] and override.

Stale assertion. output_code.py:880-881 still asserts graph_kwargs["cudagraphs"] is not None unconditionally, even though the following lines may discard that value entirely in favour of the override. Not wrong today, but the assertion no longer guards what the code below actually uses.

Recommendation

Request Changes

The core diagnosis is correct and both fixes look right to me. Blocking on tests: the primary behavior this PR fixes (cache-hit backward cudagraph decision) and the secondary one (partition post-compile routing under mismatched graph_partition) are both untested — the one added test only covers the cache key. Per repo policy, new functionality without tests is Request Changes. The naming unification is a should-fix while you are in here.

| Branch: `gh/desertfire/756/head`

[ghstack-poisoned]
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review this pr again

@claude

claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 34m 14s —— View job


Re-reviewed at commit 713bbfa1 — the previous round's blocking feedback is addressed (single override name, cache-hit regression test added, config decorators present), and my remaining comments are all minor.

Full review

PR Review: #194632

Summary

Threads a backward-only cudagraph opt-out (cudagraphs_post_compile_override) into the AOTAutograd cache key and into the serialized CompiledFxGraph.fx_kwargs, so override_cudagraphs(bwd=False) survives a warm cache load. The mechanism is correct; findings below are quality/scope items, none blocking.

Status of previous review feedback

All four blocking items from the earlier round are resolved:

  • The three-way naming duplication is gone — backward_cudagraphs_annotation_override was deleted and cudagraphs_post_compile_override is now the single name across CompilerConfigExtra, _CompileFxKwargs, the cache key, and post_compile.
  • test_cudagraph_backward_override_aot_cache_hit (test/inductor/test_cudagraph_trees.py:1180) now exercises the output_code.py path, which is the actual point of the PR. I traced it: without the fix, bw_fx_config["cudagraphs"] on a hit is the forward-derived box (still True), so cudagraph_post_compile would record a second graph and new_graph_id().id would be 2 instead of 1. The test does fail without the fix.
  • Both new tests carry the four sibling config decorators (lines 1148-1151, 1176-1179).
  • The stale unconditional graph_kwargs["cudagraphs"] is not None assertion is now correctly scoped to the else branch (output_code.py:892).
  • The config.graph_partition → self.partition_maps change is no longer in the diff, so that earlier concern no longer applies.

Code Quality

Dead assertion for a state the type forbids. output_code.py:885-889:

if cudagraphs_post_compile_override is not None:
    if cudagraphs_post_compile_override:
        raise AssertionError("cudagraphs_post_compile_override only supports False")
    graph_cudagraphs = BoxedBool(False)

The field is typed Literal[False] | None in three places (compile_fx.py:972, :2700, :2714) and create_compiler_config_extra only ever assigns annotation.bwd under the guard not annotation.bwd (compile_fx.py:2736-2737), so the truthy branch is unreachable. CLAUDE.md is explicit here: don't add validation for scenarios that can't happen.

The cleaner shape is a plain bool that means what it says — e.g. disable_backward_cudagraphs: bool = False — which collapses the tri-state (False/None both meaning "not overriding" vs "overriding to off"), deletes the assertion, and removes the Literal[False] awkwardness. Fix this →

The create_fx_config copy is a cache-key ingredient only, and that is not obvious. post_compile reads the override from self.fx_kwargs (output_code.py:882) — the value serialized with the backward graph — not from the graph_kwargs/fx_config argument it is handed. So the entry added to create_fx_config (autograd_cache.py:870-876) never influences post_compile; its only effect is perturbing the AOTAutograd hash via AOTAutogradCacheDetails. A reader will reasonably assume the two are the same channel. The comment at compile_fx.py:969-971 sits on the TypedDict declaration and doesn't disambiguate; a one-line note in create_fx_config saying this entry exists to distinguish cache entries (the effective value comes from the serialized graph) would prevent someone later "simplifying" post_compile to read graph_kwargs.

post_compile applies the override regardless of is_backward. output_code.py:885 gates only on the value being non-None. Today the key is only ever set on the backward's compile_fx_inner call (compile_fx.py:2990), so this is fine, but the read is unconditional while the semantics are backward-only — and if it were ever set on a forward, cudagraphs would be silently dropped with no cudagraph_skips bump. Renaming the field to say "backward" (see above) makes the invariant self-documenting.

Testing

Unnecessary cudagraph-tree reset. test/inductor/test_cudagraph_trees.py:1203 calls torch._inductor.cudagraph_trees.reset_cudagraph_trees() immediately after torch._dynamo.reset() on line 1202, but torch._dynamo.reset() already does exactly that when CUDA is initialized (torch/_dynamo/init.py:192-195). This is the only direct call to reset_cudagraph_trees in the ~6000-line test file, so it also reads as a special requirement that doesn't exist. Drop line 1203.

test_cudagraph_backward_override_affects_aot_cache_key can't distinguish "keys differ" from "keys are unstable". The test (line 1152) runs unannotated then annotated and asserts 2 misses / 0 hits. That is satisfied both by the intended behavior and by a hypothetical world where the key is simply nondeterministic across torch._dynamo.reset(). A third run(True) asserting autograd_cache_hit == 1 would pin the key as stable and distinguishing in one test. (test_cudagraph_backward_override_aot_cache_hit covers hit-stability separately, so this is a robustness improvement rather than a gap.)

Performance

Every FX-graph and AOTAutograd cache key changes, including for graphs with no override. compile_fx_inner unconditionally does kwargs.setdefault("cudagraphs_post_compile_override", None) (compile_fx.py:1003), and create_fx_config unconditionally emits the key (autograd_cache.py:876). cudagraphs_post_compile_override is not in FxGraphHashDetails.EXCLUDED_KWARGS (codecache.py:1353), and the hash pickles the whole dict (codecache.py:1512-1520), so adding a key with value None changes the hash of every graph — a full cold-start for all existing cache entries on rollout.

That is avoidable: post_compile reads via .get(), and compile_fx_backward passes the value explicitly, so the setdefault isn't needed for correctness. Omitting the key when there is no override (both at compile_fx.py:1003 and in create_fx_config) preserves existing keys. Worth noting that for the FX-graph key specifically the new ingredient is redundant anyway — when the override applies, compile_fx_backward already passes cudagraphs=BoxedBool(False) (compile_fx.py:2951-2953), and BoxedBool is a dataclass that pickles by value, so the backward's key already differed. Fix this →

Recommendation

Approve (with the dead assertion and the redundant reset_cudagraph_trees() call worth cleaning up before merge)

The bug diagnosis and the fix are right, and the coverage gap from the previous round is closed: test_cudagraph_backward_override_aot_cache_hit genuinely fails without the output_code.py change. Remaining items are quality and cache-churn scope, not correctness.

| Branch: `gh/desertfire/756/head`

[ghstack-poisoned]
[ghstack-poisoned]
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review this pr again

@claude

claude Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 24m 48s —— View job


Re-reviewed at 3d9c3b56 — the two cleanups from last round landed and the is_backward gate closes the forward-consumption hole I was worried about; one type-widening regression is worth a second look before merge.

Full review

PR Review: #194632

Summary

Threads a backward-only cudagraph opt-out into the AOTAutograd cache key and into the serialized CompiledFxGraph.fx_kwargs, so override_cudagraphs(bwd=False) survives a warm cache load. The mechanism is correct on every load path I traced. One finding is a real regression introduced by this round's refactor; the rest are readability and test-robustness items.

Status of previous review feedback

Both items called out last round are fixed: the reset_cudagraph_trees() call is gone (it was redundant with torch._dynamo.reset(), torch/_dynamo/init.py:192-195), and test_cudagraph_backward_override_affects_aot_cache_key now has a third run(True) asserting autograd_cache_hit == 1, so it distinguishes "keys differ" from "keys are unstable" (test/inductor/test_cudagraph_trees.py:1173-1175). The dead AssertionError is also gone, and the new is_backward gate at output_code.py:883 fixes the unconditional-read concern — fw_fx_config at aot_autograd_result.py:480-483 spreads the same fx_config and therefore does carry the override, so without that gate a forward would have consumed it.

I re-verified the serialization argument the fix rests on, and it holds on all four paths: CompiledFxGraph.prepare_for_serialization (output_code.py:1005-1022) does not touch fx_kwargs, so the key survives both the FxGraphCache pickle (codecache.py:2312-2316 save, :1858 load) and the bundled AOTAutograd entry (aot_autograd_result.py:97-105). _load_and_post_compile always injects is_backward explicitly (aot_autograd_result.py:486), so the gate also works on the precompile path where the incoming dict has no is_backward key (aot_autograd_result.py:729-732).

Code Quality

The type was widened from Literal[False] to bool, so nothing now enforces the invariant the deleted assertion was checking. Last round the field was Literal[False] | None plus a runtime raise AssertionError(...) for a truthy value. Removing the assertion was right — it was dead because the type forbade True. But this round also relaxed the annotation to bool | None in all three places (compile_fx.py:970, :2697, :2711), so True is now type-legal with no check anywhere.

That matters because True is not a harmless value. At output_code.py:883-884 it becomes BoxedBool(True) and at compile_fx.py:2948-2949 it becomes a fresh BoxedBool(True), in both cases replacing compiler_config_extra.cudagraphs — so it would force-enable cudagraphs for the backward even when the shared forward box had been legitimately disabled during lowering. Only disabled_cudagraphs_reason (output_code.py:904) would still catch it, and that does not cover every disable path. create_compiler_config_extra only assigns under not annotation.bwd (compile_fx.py:2733-2734), so this is unreachable today; the point is that the invariant is now guarded by neither the type nor a runtime check, where before it was guarded by the type.

The cleanest resolution is the one from last round: a plain bool named for what it does — disable_backward_cudagraphs: bool = False. That collapses the tri-state (False and None both mean "not overriding"), makes True mean something coherent, and makes the backward-only semantics self-documenting at the read site. Restoring Literal[False] | None also works. Fix this →

Two if blocks with the same guard, 25 lines apart. compile_fx.py:2947-2949 derives the local cudagraphs box from the override, and compile_fx.py:2972-2976 builds a one-key cudagraph_kwargs dict from the same compiler_config_extra.cudagraphs_bwd_override is not None condition. Both feed the same inner_compile call. Merging them into a single block near line 2947 would make it obvious that the fresh BoxedBool and the serialized key are two halves of one decision, rather than two coincidentally-related conditionals. If the plain-bool change above lands, the cudagraph_kwargs splat can also be dropped in favour of passing the value directly.

Testing

test_cudagraphs_bwd_override_omitted_when_unset has a vacuously-passing assertion. test/dynamo/test_aot_autograd_cache.py:3634-3640 patches compile_fx.wrap_compiler_debug to intercept the kwargs. That works today (it is a module-level global imported at compile_fx.py:41 and called at :1056), but if compile_fx_inner ever stops routing through it, the mock silently stops intercepting, captured_kwargs stays empty, and assertNotIn(...) at :3639 passes for the wrong reason. The second half of the test (:3653-3654) would catch it via KeyError, so the test as a whole is not blind — but asserting captured_kwargs is non-empty before the assertNotIn would make the negative assertion trustworthy on its own.

The test also sits in the wrong class. AOTAutogradCachePicklerTests (test/dynamo/test_aot_autograd_cache.py:3514) is about cache-key pickling; this test drives compile_fx_backward and mocks inductor's compile indirection. It is the only test in that class that does so.

Backward Compatibility

Worth confirming the mark_step_begin dependency is not masking something. test_cudagraph_backward_override_aot_cache_hit calls torch.compiler.cudagraph_mark_step_begin() before every iteration (test/inductor/test_cudagraph_trees.py:1205). With fwd=True / bwd=False the backward's box is False, so cudagraph_post_compile never runs and therefore maybe_handle_backward_generation (output_code.py:181-210) never calls manager.set_to_running_backward(). That leaves running_forwards_with_pending_backwards stuck at True after the first forward (cudagraph_trees.py:2409-2410), and can_start_new_generation returns not running_forwards_with_pending_backwards unless the user invoked mark-step (cudagraph_trees.py:2824-2827). So the explicit mark_step_begin() may be the only reason the test advances generations, meaning a user with this annotation who does not call it could see the forward wedged in one generation.

This is pre-existing — the cold-path override at compile_fx.py:2947-2949 is on the base branch — so it is not something this PR introduced, and I would not block on it. Flagging it because this PR is what extends the behavior to warm loads, and because the test quietly depends on the workaround. Lower confidence than the other findings; you know this manager's generation logic better than I do.

Recommendation

Approve, with the type widening worth resolving first.

The diagnosis and the fix are correct, the serialization argument checks out on every load path, and the is_backward gate closes the last real hole. The bool | None widening is the one thing I would not merge as-is: it removes a type-level guarantee without replacing it, in exchange for deleting an assertion that the guarantee made dead.

| Branch: `gh/desertfire/756/head`

[ghstack-poisoned]
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 22m 58s —— View job


Re-reviewed at bc453edb — every item from the last round is addressed, and the cache-key churn concern is now fixed by omitting the key when unset; I have no blocking findings.

Full review

PR Review: #194632

Summary

Threads a backward-only cudagraph opt-out (cudagraphs_bwd_override) into the AOTAutograd cache key and into the serialized CompiledFxGraph.fx_kwargs, so override_cudagraphs(bwd=False) survives a warm cache load. I traced every load path and the mechanism is correct. Remaining comments are minor.

Status of previous review feedback

All items from the last round are resolved:

  • Cache-key churn is fixed. compile_fx_inner no longer does kwargs.setdefault("cudagraphs_bwd_override", None) (the setdefault list at compile_fx.py:1029-1038 no longer contains it), and create_fx_config only inserts the key when non-None (autograd_cache.py:947-949). I confirmed FxGraphHashDetails pickles the whole fx_kwargs dict minus EXCLUDED_KWARGS = ["graph_id", "compile_region_name"] (codecache.py:1355, :1514-1522), so omitting the key is what preserves existing keys for every graph without an override. test_cudagraphs_bwd_override_omitted_when_unset pins exactly this.
  • The two same-guard if blocks are merged. compile_fx.py:2975-2981 now derives the local BoxedBool and populates cudagraph_kwargs in one block, so the fresh box and the serialized key visibly come from one decision.
  • The vacuous-assertion concern is fixed. self.assertTrue(captured_kwargs) at test/dynamo/test_aot_autograd_cache.py:347 now guards the assertNotIn, so the negative assertion can no longer pass because the mock stopped intercepting.
  • The test moved to the right class. It now lives in AOTAutogradCacheTests (line 308) rather than AOTAutogradCachePicklerTests.
  • Prior rounds: the naming duplication, the dead AssertionError, the redundant reset_cudagraph_trees(), and the missing third run(True) are all gone.

I also want to correct something from my last review: I flagged the Literal[False] -> bool | None widening as a regression introduced by this PR. That was wrong. git show origin/gh/desertfire/756/base:torch/_inductor/compile_fx.py has cudagraphs_bwd_override: bool | None = None at lines 2725 and 2739 — the bool | None annotation is the base branch's, and this PR only propagates it into _CompileFxKwargs (compile_fx.py:999). Widening a field to match its existing declaration isn't a regression, and tightening a pre-existing annotation is out of scope here. Withdrawn.

Correctness

I re-verified the serialization argument on all four paths and it holds:

  • prepare_for_serialization (output_code.py:1005-1022) clears callables and the original GM but does not touch fx_kwargs; __getstate__ (:1159-1162) only nulls current_callable. So the key round-trips through both the FxGraphCache pickle and the bundled entry (BundledOutputCodeLoadable.pre_save, aot_autograd_result.py:97-101).
  • _lookup_graph (codecache.py:2196-2264) returns the deserialized graph without rebuilding fx_kwargs, so self.fx_kwargs at output_code.py:882 is the compile-time dict, not the current call's — which is precisely what makes the fix work.
  • _load_and_post_compile (aot_autograd_result.py:480-487) spreads the same fx_config into both fw_fx_config and bw_fx_config, so the is_backward gate at output_code.py:883 is load-bearing: without it a forward would consume a backward-only override.
  • The precompile and standalone paths (aot_autograd_result.py:726-733, standalone_compile.py:277-286) pass a fx_config with no is_backward key, but _load_and_post_compile always injects it explicitly, so graph_kwargs["is_backward"] is never missing at the read site.

The else branch at output_code.py:885-888 correctly scopes the graph_kwargs["cudagraphs"] is not None assertion to the case where that value is actually used.

Code Quality

Minor: the FX-graph-cache half of the key is redundant. When the override applies, compile_fx_backward already passes cudagraphs=BoxedBool(False) (compile_fx.py:2976-2980), and BoxedBool is a plain @dataclasses.dataclass holding a bool (utils.py:3451-3456), so it pickles by value and the backward's FX key already differed. Adding cudagraphs_bwd_override to inner_compile's kwargs is therefore not needed for the FX key — but it is needed to get the value serialized into CompiledFxGraph.fx_kwargs, which is the whole point. So the current shape is right; I'm noting it only because a reader might otherwise wonder whether both channels are pulling weight.

Minor: the create_fx_config comment could name the other channel. autograd_cache.py:948 says "Cache-key-only here; post_compile reads the value serialized in the graph." That's accurate and it addresses my earlier ask. One small improvement: naming CompiledFxGraph.fx_kwargs explicitly would make the pointer actionable for someone who lands here first — "post_compile reads it from the serialized CompiledFxGraph.fx_kwargs."

Testing

Both tests look right to me.

test_cudagraphs_bwd_override_omitted_when_unset (test/dynamo/test_aot_autograd_cache.py:333-366) covers both halves of the omit-when-unset behavior — the inner_compile kwargs and create_fx_config — in both the unset and False states, using assertIs(..., False) so a None/False confusion can't slip through. Note this test inherits CacheKeyEquivalenceMixin's compile_fx patcher via AOTAutogradCacheTests; since it never calls torch.compile that patcher is inert here, which is fine.

test_cudagraph_backward_override_aot_cache_hit (test/inductor/test_cudagraph_trees.py:1456-1485) is the one that actually guards the output_code.py change. Without the fix, bw_fx_config["cudagraphs"] on the hit is the forward-derived box (still True under fwd unset / bwd=False), so cudagraph_post_compile would record a second graph and new_graph_id().id would be 2 rather than 1. It also checks numerics against eager via assertEqual(result, fn(x)).

test_cudagraph_backward_override_affects_aot_cache_key now runs run(False), run(True), run(True) and asserts 2 misses / 1 hit, which pins the key as both distinguishing and stable across torch._dynamo.reset().

One pre-existing item worth a sanity check, not a blocker. test_cudagraph_backward_override_aot_cache_hit calls torch.compiler.cudagraph_mark_step_begin() before each iteration (line 1480). With bwd=False the backward's box is False, so cudagraph_post_compile never runs and maybe_handle_backward_generation never calls set_to_running_backward() — leaving running_forwards_with_pending_backwards True, which can_start_new_generation gates on unless the user marks a step. That means a user with this annotation who never calls mark_step_begin may see the forward wedged in one generation. This is inherent to the base branch's cold-path override (compile_fx.py:2976-2980), not something this PR introduced, so it shouldn't gate the merge — flagging it because this PR extends the behavior to warm loads and because the test quietly depends on the workaround. Lower confidence than the rest; you know this manager's generation logic better than I do.

Recommendation

Approve

Every blocking item from the prior rounds is resolved, the cache-key churn is now avoided, and I verified the serialization + is_backward gating on all four post-compile entry points. The two remaining notes are optional polish.

| Branch: `gh/desertfire/756/head`

@desertfire desertfire added the topic: not user facing topic category label Aug 27, 2026
@desertfire desertfire closed this Aug 27, 2026
@github-actions
github-actions Bot deleted the gh/desertfire/756/head branch November 10, 2026 01:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant