Skip to content

Fix AOTAutograd wrapper subclass metadata mutation - #186515

Closed
jansel wants to merge 4 commits into
gh/jansel/1435/basefrom
gh/jansel/1435/head
Closed

jansel wants to merge 4 commits into
gh/jansel/1435/basefrom
gh/jansel/1435/head

Conversation

@jansel

@jansel jansel commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

AOTAutograd was still rejecting metadata mutations on traceable wrapper
subclass inputs with a blanket guard. Removing that guard alone was not
enough: metadata collection could record fake wrapper output strides and
subclass output wrapping would bake those stale outer strides into
tensor_unflatten at runtime. In the issue repro this produced a
TwoTensor whose inner tensors had stride (8, 4, 1) while the wrapper outer
stride stayed at (4, 4, 1).

Teach SubclassCreationMeta to record when a wrapper subclass's outer size
or stride tracks its tensor attrs. Runtime reconstruction and generated
subclass wrapping code now use the runtime attr size/stride in those cases,
while subclasses whose outer metadata differs from their attrs continue to
use the recorded explicit outer metadata. With correct runtime wrapper
metadata in place, remove the obsolete blanket metadata-mutation guard.

The alternative was to keep a narrower ban for metadata-mutated subclass
inputs, but the runtime mutation epilogue and subclass dispatch path already
handle the metadata-only case once output wrappers are rebuilt from runtime
metadata.

Fixes #114975
Generated by my agent

Test Plan:

  • Direct original repro with eager-vs-compiled recursive outer/inner metadata assertions: passed
  • python test/functorch/test_subclass_codegen.py -v
  • python test/functorch/test_aotdispatch.py -k subclass_metadata_mutation -v, with local torchvision import bypass due environment failure importing torchvision::nms
  • Targeted test_aotdispatch.py tests with the same torchvision import bypass: TestAOTDispatch.test_aot_dispatch_input_metadata_mutation, TestAOTAutograd.test_input_mutation_aliases_bases_out_of_order, TestAOTDispatch.test_aot_dispatch_input_data_and_metadata_mutation, TestAOTAutogradWithDynamo.test_compute_outer_size_and_stride_bug, TestAOTAutogradWithDynamo.test_subclass_dynamic_stride
  • Extra dynamic torch.compile(backend="aot_eager", dynamic=True) TwoTensor output metadata smoke script
  • git diff --check && lintrunner -a

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

⏳ No Failures, 3 Pending

As of commit ff5ae12 with merge base fca7466 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@jansel

jansel commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 20s —— View job


Code Review: Fix AOTAutograd wrapper subclass metadata mutation

  • Read the full diff and understand the change
  • Review test changes
  • Review implementation changes
  • Post review feedback

Overall: This is a well-structured fix for a real problem (issue #114975). The approach of teaching SubclassCreationMeta to derive outer size/stride from inner tensor attrs at runtime — rather than baking in stale trace-time metadata — is sound. The blanket guard removal is justified given the runtime infrastructure now handles this correctly.

Design Feedback

_find_attr_matching_outer_metadata logic (subclass_utils.py:93-109):

The function returns the first tensor attr name only when all tensor attrs match the outer metadata. This is conservative and correct for TwoTensor (where a and b always share metadata). However, there's an implicit assumption worth noting: if even one attr has different metadata (e.g., a subclass where inner tensors intentionally have different shapes), the function returns None and falls back to the static path. This is safe but could be documented with a brief comment about why the "all must match" invariant is required (if one attr can diverge from outer, there's no single attr to trust as the source of truth).

_consume_placeholders in codegen (subclass_codegen.py:176-177):

def _consume_placeholders(placeholders: list[bool]) -> None:
    out_idx_ref[0] += sum(placeholders)

This correctly advances the output index past any symbolic symint slots that would otherwise be consumed by _build_tuple. This ensures the codegen output index stays consistent regardless of which path is taken. Good.

Runtime path redundancy (schemas.py:355-369):

The runtime creation_fn calls compute_outer_size_and_stride first, then immediately overwrites with attr-derived values if outer_size_from_attr/outer_stride_from_attr are set. This is intentional — compute_outer_size_and_stride still advances curr_start_idx internally to keep index arithmetic correct. However, note that compute_outer_size_and_stride doesn't actually advance curr_start_idx here since it's a local variable inside that method; the outer curr_start_idx in creation_fn is already past the inner tensors. The symint args in all_args at positions after curr_start_idx are consumed by the method but the returned outer_size/outer_stride is discarded when overridden. This is fine for correctness but could be slightly confusing to future readers.

Potential Issue

getattr(meta, "outer_size_from_attr", None) in codegen (subclass_codegen.py:179-180):

outer_size_from_attr = getattr(meta, "outer_size_from_attr", None)
outer_stride_from_attr = getattr(meta, "outer_stride_from_attr", None)

Since outer_size_from_attr and outer_stride_from_attr are defined as fields on SubclassCreationMeta with default None, you could access them directly as meta.outer_size_from_attr. Using getattr with a default suggests backward-compatibility concern with older pickled objects, but these are runtime-only (not serialized). Consider simplifying to direct attribute access for consistency with the rest of the function. This is minor/stylistic.

Test Coverage

The tests are thorough:

  • test_subclass_metadata_mutation_aot_function_metadata: Direct repro of the original issue (transpose_ on TwoTensor)
  • test_subclass_metadata_mutation_noncontiguous_input: Non-contiguous edge case with strided slicing
  • assertTensorMetadataEqual: Recursive metadata validation helper — good addition to catch stride mismatches that assertEqual alone would miss
  • Removal of @expectedFailure from test_aot_dispatch_input_metadata_mutation confirms the fix
  • Updated expected codegen strings in test_subclass_codegen.py reflect the new .size()/.stride() expressions

The comment update on test_aot_dispatch_input_data_and_metadata_mutation (still @expectedFailure) correctly notes this is a separate tangent metadata issue, not the metadata-mutation ban.

Minor Nit

In test_aotdispatch.py:228-241, the assertTensorMetadataEqual helper doesn't check dtype or device — which is fine since that's not what this PR is about, but the method name could be slightly misleading to future readers. Consider assertTensorShapeMetadataEqual or a brief docstring. Very minor.

Verdict

Looks good. The approach correctly separates subclasses where outer metadata tracks inner attrs (use runtime values) from subclasses with independent outer metadata (use recorded values). The fallback is conservative — if any ambiguity exists, it falls back to the existing static path.


@jansel jansel added the topic: not user facing topic category label Jun 8, 2026
[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 8, 2026
AOTAutograd was still rejecting metadata mutations on traceable wrapper subclass inputs with a blanket guard. Removing that guard alone was not enough: metadata collection could record fake wrapper output strides and subclass output wrapping would bake those stale outer strides into __tensor_unflatten__ at runtime. In the issue repro this produced a TwoTensor whose inner tensors had stride (8, 4, 1) while the wrapper outer stride stayed at (4, 4, 1).

Teach SubclassCreationMeta to record when a wrapper subclass's outer size or stride tracks its tensor attrs. Runtime reconstruction and generated subclass wrapping code now use the runtime attr size/stride in those cases, while subclasses whose outer metadata differs from their attrs continue to use the recorded explicit outer metadata. With correct runtime wrapper metadata in place, remove the obsolete blanket metadata-mutation guard.

The first generated-code path for attr-derived metadata over-advanced the flat output cursor in dynamic nested subclass cases, causing CI to read past the returned tensor leaves. The codegen now reconstructs attr-derived metadata without consuming nonexistent output slots and slices saved activations from the tail of the compiled outputs, so it also handles training graphs that still return dynamic SymInt metadata before activations.

The alternative was to keep a narrower ban for metadata-mutated subclass inputs, but the runtime mutation epilogue and subclass dispatch path already handle the metadata-only case once output wrappers are rebuilt from runtime metadata.

Fixes #114975

Generated by my agent

Test Plan:
- Direct original repro with eager-vs-compiled recursive outer/inner metadata assertions: passed
- python test/functorch/test_subclass_codegen.py -v
- python test/dynamo/test_subclasses.py -k test_subclass_TwoTensor_TwoTensor_TwoTensor -v
- python test/functorch/test_aotdispatch.py -k subclass_metadata_mutation -v, with local torchvision import bypass due local CUDA-version mismatch in torchvision
- Simple dynamic aot_function training smoke with TwoTensor and backward: passed
- git diff --check && lintrunner -a

ghstack-source-id: 2cfa5ad

Pull-Request: #186515
@jansel

jansel commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I fixed the Dr. CI failure in test/dynamo/test_subclasses.py::TestTwoTensorSubclass::test_subclass_TwoTensor_TwoTensor_TwoTensor. The generated subclass wrapper no longer skips flat output slots when size/stride come from runtime attrs, and saved activations are sliced from the output tail so dynamic SymInt metadata cannot leak into activations.

@jansel

jansel commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@jansel
jansel marked this pull request as ready for review June 8, 2026 19:37
@claude

claude Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 2m 27s —— View job


Code Review: Fix AOTAutograd wrapper subclass metadata mutation

  • Read the full diff and understand the change
  • Review implementation changes in detail
  • Review test changes
  • Post review feedback

Overall: This is a solid fix for #114975. The approach — teaching SubclassCreationMeta to derive outer size/stride from inner tensor attrs at runtime rather than baking stale trace-time metadata — is the right one. The _activation_start = len(unwrapped_outs) - num_fw_outs_saved_for_bw change is a necessary companion fix that cleanly handles the case where symint output slots are skipped by the attr-derived path.

Key Observations

1. _activation_start logic (subclass_codegen.py:301-304)

The old unwrapped_outs[num_args_tallied:] approach was fragile: when outer_size_from_attr is set, _build_tuple is skipped so out_idx_ref never advances past the symint slots, making num_args_tallied undercount. The new len(unwrapped_outs) - num_fw_outs_saved_for_bw approach is robust — it indexes from the end regardless of how many symints were or weren't consumed during wrapping. The test test_attr_derived_metadata_does_not_skip_outputs exercises exactly this edge case. Good.

2. _find_attr_matching_outer_metadata (subclass_utils.py:90-108)

The "all tensor attrs must agree" invariant is conservative and correct. For TwoTensor (where a and b always share metadata) this always picks tensor_attrs[0]. For asymmetric subclasses (where inner tensors have different shapes), it falls back to the static path. The use of guard_or_false(sym_eq(...)) ensures that if the comparison is data-dependent and can't be resolved statically, it safely returns None (fall back to static metadata).

3. Runtime path in schemas.py:355-369

compute_outer_size_and_stride is still called even when outer_size_from_attr is set, and its return value is discarded. This is acceptable: the method doesn't advance any external state (it takes curr_start_idx by value), and the symint args it reads from all_args are still present in the flat args list. It's a no-op in terms of side effects. A future cleanup could skip the call entirely when both outer_size_from_attr and outer_stride_from_attr are set, but it's not a correctness issue.

4. num_args_tallied is now dead (subclass_codegen.py:213-223)

Both callers of _emit_output_wrapping now discard the second return value. The function could be simplified to return only result_exprs, but this is a minor cleanup opportunity, not a problem.

One Potential Concern

Interaction with the backward epilogue path (_codegen_subclass_wrap_source)

The backward wrapping path at subclass_codegen.py:312-326 also calls _emit_output_wrapping. In this path, there are no "activations" to worry about, so the unconsumed symint slots between tensor outputs and the end of unwrapped_outs are harmless — the caller expects wrap_fn to simply return the wrapped subclass outputs. However, if a backward output has included_subclass_symints=True AND outer_size_from_attr is set, the generated wrapper will index only the tensor outputs and ignore the symints at the end. This is correct because the backward already knows the output count.

Test Coverage

Thorough and well-targeted:

  • test_subclass_metadata_mutation_aot_function_metadata: Direct repro of Subclass metadata mutation is broken in AOTAutograd #114975 (transpose_ on TwoTensor with recursive metadata assertions)
  • test_subclass_metadata_mutation_noncontiguous_input: Non-contiguous edge case with strided slicing — exercises the case where outer stride diverges from what a naive reshape would produce
  • test_attr_derived_metadata_does_not_skip_outputs: Unit test for the symint-skipping edge case with num_fw_outs_saved_for_bw
  • assertTensorMetadataEqual: Good helper that recursively validates shape/stride/offset on inner tensors, catching the exact class of bugs this PR fixes
  • Removal of @expectedFailure from test_aot_dispatch_input_metadata_mutation and removal from xfail_inherited_tests confirm the fix works end-to-end

Verdict

Looks good to land. The implementation is clean, the fallback to static metadata is conservative (safely handles subclasses where inner tensor metadata diverges from outer), and the _activation_start change eliminates a latent fragility in the codegen output indexing.


@jansel jansel added the agentic Created by an AI agent label Jun 9, 2026
@mlazos

mlazos commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

torch/_functorch/_aot_autograd/subclass_codegen.py:308

Will this work with dynamic shapes?

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 10, 2026
AOTAutograd was still rejecting metadata mutations on traceable wrapper subclass inputs with a blanket guard. Removing that guard alone was not enough: metadata collection could record fake wrapper output strides and subclass output wrapping would bake those stale outer strides into __tensor_unflatten__ at runtime. In the issue repro this produced a TwoTensor whose inner tensors had stride (8, 4, 1) while the wrapper outer stride stayed at (4, 4, 1).

Teach SubclassCreationMeta to record when a wrapper subclass's outer size or stride tracks its tensor attrs. Runtime reconstruction and generated subclass wrapping code now use the runtime attr size/stride in those cases, while subclasses whose outer metadata differs from their attrs continue to use the recorded explicit outer metadata. With correct runtime wrapper metadata in place, remove the obsolete blanket metadata-mutation guard.

The generated attr-derived metadata path still needs to keep the flat output cursor aligned with the compiled output layout. Dynamic graphs can return symbolic size and stride slots between subclass tensor leaves even when reconstruction reads size/stride from a runtime tensor attr. The wrapper now advances past those slots without using their stale values, so later subclass outputs are reconstructed from the correct flat tensor and opaque slots.

The alternative was to keep a narrower ban for metadata-mutated subclass inputs, but the runtime mutation epilogue and subclass dispatch path already handle the metadata-only case once output wrappers are rebuilt from runtime metadata.

Fixes #114975

Generated by my agent

Test Plan:
- Direct original repro with eager-vs-compiled recursive outer/inner metadata assertions: passed
- python test/functorch/test_subclass_codegen.py -v
- python test/distributed/tensor/test_dtensor_compile.py -k test_split_with_symint_split_size -v
- python test/dynamo/test_subclasses.py -k test_subclass_TwoTensor_TwoTensor_TwoTensor -v
- python test/functorch/test_aotdispatch.py -k subclass_metadata_mutation -v, with local torchvision import bypass due local CUDA-version mismatch in torchvision
- Simple dynamic aot_function training smoke with TwoTensor and backward: passed
- git diff --check && lintrunner -a

ghstack-source-id: 5fc775f

Pull-Request: #186515
@jansel

jansel commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

My agent says yes, this now works with dynamic shapes. I reproduced the Dr. CI failure in test/distributed/tensor/test_dtensor_compile.py::TestDTensorCompileE2E::test_split_with_symint_split_size: generated wrapping reconstructed size/stride from a runtime tensor attr but did not advance past the SymInt metadata slots still returned by the compiled graph, so the next DTensor output read an int as its tensor attr. The update advances the flat output cursor past those dynamic SymInt slots without using their values, and adds a focused codegen regression test for multiple attr-derived subclass outputs separated by SymInt metadata slots. I verified test_split_with_symint_split_size, test_subclass_codegen.py, subclass_metadata_mutation coverage, and lintrunner.

@jansel

jansel commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 7m 15s —— View job


Code Review: Fix AOTAutograd wrapper subclass metadata mutation

  • Read the full diff
  • Review implementation
  • Review tests
  • Post review

Overall: The fix is sound and the latest changes are correct. The core idea — recording outer_size_from_attr/outer_stride_from_attr so runtime reconstruction reads outer metadata from the inner tensor attrs instead of baking stale trace-time strides — cleanly addresses #114975. I focused this pass on @mlazos's dynamic-shapes question on subclass_codegen.py:308.

Answer to @mlazos: does this work with dynamic shapes?

Yes, and it's specifically the dynamic case the _activation_start change makes robust. Walking through subclass_codegen.py:300-309:

  • With dynamic shapes the compiled fn returns output symints (the subclass outer size/stride) interleaved between the flat tensor outputs and the saved activations. When outer_size_from_attr is set, _codegen_wrap_subclass builds size_expr = a.size() / a.stride() (reading the runtime inner attr, which already carries the mutated dynamic metadata) and skips the _build_tuple path. _consume_placeholders (subclass_codegen.py:176-177) still advances out_idx_ref past those symint slots, so any following output indexes correctly — test_attr_derived_metadata_consumes_symints_between_outputs exercises exactly this two-output case.
  • The old unwrapped_outs[{num_args_tallied}:] slice was the fragile part: when symint slots are skipped, num_args_tallied undercounts and the activation slice would start too early. The new _activation_start = len(unwrapped_outs) - num_fw_outs_saved_for_bw indexes from the end, so it lands on the correct activation boundary regardless of how many symint slots the wrapping consumed. Since num_fw_outs_saved_for_bw = len(fw_outs) - num_inner_fwd_outputs (graph_compile.py:1993-1994), the tail length is independent of subclass symint accounting — this is the right invariant to key off.
  • test_subclass_dynamic_stride (dynamic=True) and the compute_outer_size_and_stride unit test confirm the end-to-end and the index-arithmetic paths.

The non-codegen runtime path (wrap_tensor_subclasses, subclass_utils.py:553-560) slices activations from the front via num_args_tallied + num_fw_outs_saved_for_bw, and there arg_count does include the symint slots — so both paths agree on the activation boundary, just computed from opposite ends. The assertion at subclass_utils.py:554 guards that they're consistent.

One concern worth a note (not blocking)

_find_attr_matching_outer_metadata (subclass_utils.py:90-108) decides at trace time whether outer metadata tracks an inner attr, then bakes that decision into creation_fn/codegen for all runtime invocations. For TwoTensor the outer-tracks-inner relationship is a structural invariant, so this is always safe. The latent risk is a subclass whose outer-vs-inner metadata relationship is input-dependent: if outer happens to equal inner at trace time but legitimately diverges at runtime, the attr-derived path would produce wrong outer metadata. guard_or_false(sym_eq(...)) correctly handles the data-dependent/unbacked case (falls back to the static path), but not the "statically equal at trace, structurally divergent at runtime" case. This is narrow and no in-tree subclass hits it, but a one-line comment on the function noting the assumption (outer metadata is assumed to track the attr across all runtime inputs, not just this trace) would help a future reader who adds an asymmetric subclass.

Minor

  • schemas.py:355-369: when both outer_size_from_attr and outer_stride_from_attr are set, the compute_outer_size_and_stride return value is fully discarded. It's a side-effect-free no-op (takes curr_start_idx by value), so correct — just slightly wasteful. Could early-out, but not worth churn.
  • subclass_codegen.py:207-230: _emit_output_wrapping now returns num_args_tallied but both callers discard it (_). The second return value and the num_args_tallied bookkeeping inside the function are dead and could be dropped to simplify the signature.

Tests

Good coverage: the assertTensorMetadataEqual recursive helper catches exactly the stride-mismatch class of bug, the direct transpose_ repro plus the non-contiguous strided-slice case cover the original issue and its trickier variant, and removing @expectedFailure from test_aot_dispatch_input_metadata_mutation + the xfail confirms the fix end-to-end. The remaining @expectedFailure on test_aot_dispatch_input_data_and_metadata_mutation is correctly re-scoped to the separate tangent-metadata issue.

Verdict

Looks good to land — the dynamic-shapes path is handled correctly. Consider the one-line comment on _find_attr_matching_outer_metadata documenting the trace-time-tracks-runtime assumption.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 11, 2026
AOTAutograd was still rejecting metadata mutations on traceable wrapper subclass inputs with a blanket guard. Removing that guard alone was not enough: metadata collection could record fake wrapper output strides and subclass output wrapping would bake those stale outer strides into __tensor_unflatten__ at runtime. In the issue repro this produced a TwoTensor whose inner tensors had stride (8, 4, 1) while the wrapper outer stride stayed at (4, 4, 1).

Teach SubclassCreationMeta to record when a wrapper subclass's outer size or stride tracks its tensor attrs. Runtime reconstruction and generated subclass wrapping code now use the runtime attr size/stride in those cases, while subclasses whose outer metadata differs from their attrs continue to use the recorded explicit outer metadata. With correct runtime wrapper metadata in place, remove the obsolete blanket metadata-mutation guard.

The generated attr-derived metadata path also has to tolerate both compiled output layouts used by dynamic subclass graphs. Some graphs return symbolic size and stride slots between subclass tensor leaves, while nested attr-derived cases can return only the tensor leaves. The generated wrapper now uses a runtime flat-output cursor and only advances past recorded SymInt placeholder slots when the compiled graph actually returned subclass SymInt outputs, keeping later nested outputs aligned without relying on stale metadata values.

The alternative was to keep a narrower ban for metadata-mutated subclass inputs, but the runtime mutation epilogue and subclass dispatch path already handle the metadata-only case once output wrappers are rebuilt from runtime metadata.

Fixes #114975

Generated by my agent

Test Plan:
- Direct original repro with eager-vs-compiled recursive outer/inner metadata assertions: passed
- python test/functorch/test_subclass_codegen.py -v
- python test/dynamo/test_subclasses.py -k test_subclass_TwoTensor_TwoTensor_TwoTensor -v
- python test/distributed/tensor/test_dtensor_compile.py -k test_split_with_symint_split_size -v
- python test/functorch/test_aotdispatch.py -k subclass_metadata_mutation -v, with local torchvision import bypass due local CUDA-version mismatch in torchvision
- git diff --check
- lintrunner -a

ghstack-source-id: e49e917

Pull-Request: #186515
@jansel

jansel commented Jun 11, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@jansel

jansel commented Jun 11, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I fixed the remaining Dr. CI failure in test/dynamo/test_subclasses.py::TestTwoTensorSubclass::test_subclass_TwoTensor_TwoTensor_TwoTensor. The generated subclass wrapper now uses a runtime flat-output cursor and only skips recorded SymInt size/stride placeholders when the compiled graph actually returned subclass SymInt outputs, so nested attr-derived TwoTensor outputs that return only tensor leaves stay aligned while DTensor dynamic-shape outputs with SymInt slots still work. I verified the failing test, test_subclass_codegen.py, test_split_with_symint_split_size, subclass_metadata_mutation coverage with the local torchvision bypass, git diff --check, and lintrunner.

@claude

claude Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 4m 31s —— View job


Code Review: Fix AOTAutograd wrapper subclass metadata mutation

  • Read the latest diff vs base
  • Review implementation changes
  • Review test changes
  • Post review feedback

Overall: The PR is in good shape and already has @mlazos's approval. This pass focuses on what's new since my last review — the latest commit (ff5ae123) reworked the codegen output indexing from a compile-time out_idx_ref counter to a runtime _out_idx cursor gated by _has_subclass_symint_outputs. That change is the right call and is what makes the dynamic-shape DTensor case correct. A couple of observations below; none are blocking.

What changed since the last review

The previous design advanced a compile-time out_idx_ref[0] and baked literal indices (unwrapped_outs[3]) into the generated source. The _consume_placeholders helper did out_idx_ref[0] += sum(placeholders) unconditionally. The new design:

  • Emits a runtime _out_idx cursor and _out_idx += 1 increments (subclass_codegen.py:147-148, 167-168).
  • Computes _has_subclass_symint_outputs = len(unwrapped_outs) == {expected_with_symints} once per call (subclass_codegen.py:254-256), where expected_with_symints is derived from the new _count_output_args(..., include_subclass_symints=True) (subclass_codegen.py:210-230).
  • Only advances past symint slots when that flag is true (_consume_placeholders, subclass_codegen.py:176-180).

This correctly handles the case the third commit was chasing: a wrapper generated with symbolic placeholders, but a compiled graph specialization that doesn't actually emit the symint outputs. Walking test_attr_derived_metadata_does_not_skip_outputs and ..._consumes_symints_between_outputs by hand confirms the cursor lands exactly on the activation boundary in both the single- and two-output cases. Good, well-targeted tests.

One real asymmetry worth a look (non-blocking)

_has_subclass_symint_outputs gates the attr-derived path (_consume_placeholders), but the _build_tuple path is not gated — it unconditionally emits _out_idx += 1 for every symbolic placeholder (subclass_codegen.py:165-169):

def _build_tuple(outer, placeholders):
    for val, is_sym in zip(outer, placeholders):
        if is_sym:
            ...
            state.emit("_out_idx += 1")   # <-- always consumes, regardless of the flag

So the two paths disagree about when symint slots are present:

  • attr-derived (outer_size_from_attr set): consume iff _has_subclass_symint_outputs.
  • _build_tuple (attr is None): always consume.

For the subclasses this PR targets (TwoTensor and friends, where outer tracks inner) the attr path is always taken, so this is latent today. But if _has_subclass_symint_outputs can ever be false for an output that takes the _build_tuple path (i.e. an asymmetric subclass whose outer metadata diverges from its attrs, compiled in the same "graph elides symints" specialization that motivated the flag), _build_tuple would read symint slots that aren't there and mis-index every subsequent output. Since the flag was introduced precisely to fix that class of mis-indexing, it seems worth either gating both paths consistently or asserting/log()-ing that the _build_tuple path only runs when the flag is true. At minimum a one-line comment on _build_tuple noting it assumes symint slots are always present would flag the assumption for the next person who adds an asymmetric subclass. Fix this →

Minor

  • _emit_output_wrapping still returns num_args_tallied, but both callers discard it (result_exprs, _ = ... at subclass_codegen.py:341, 365-367). The internal num_args_tallied += meta.arg_count bookkeeping is now dead — the activation slice keys off _activation_start = len(unwrapped_outs) - num_fw_outs_saved_for_bw instead. The function could drop the second return value and the tally for a cleaner signature.
  • schemas.py:357-369: when both outer_size_from_attr and outer_stride_from_attr are set, the compute_outer_size_and_stride return value is fully discarded. It's side-effect-free (takes curr_start_idx by value), so correct, just slightly wasteful — could early-out. Not worth churn.
  • _find_attr_matching_outer_metadata (subclass_utils.py:90-108): the trace-time "outer-tracks-attr" decision is baked in for all runtime invocations. guard_or_false(sym_eq(...)) correctly handles the data-dependent/unbacked case, but not "statically equal at trace, structurally divergent at runtime." No in-tree subclass hits this; a one-line comment on the assumption would help a future reader (carried over from the prior review).

Tests

Coverage is thorough. The two new unit tests (test_attr_derived_metadata_does_not_skip_outputs, test_attr_derived_metadata_consumes_symints_between_outputs) exercise exactly the runtime-cursor edge cases the new flag introduces, including symint slots interleaved between two attr-derived subclass outputs. The expected-source updates in test_subclass_codegen.py correctly reflect the new _out_idx/_has_subclass_symint_outputs codegen. The assertTensorMetadataEqual recursive helper catches the stride-mismatch class of bug at the heart of #114975, and dropping @expectedFailure from test_aot_dispatch_input_metadata_mutation plus the two xfail_inherited_tests entries confirms the fix end-to-end. The remaining @expectedFailure on test_aot_dispatch_input_data_and_metadata_mutation is correctly re-scoped to the separate tangent-metadata issue.

Verdict

Looks good to land. The runtime-cursor rework is the correct way to handle graphs that conditionally emit symint outputs, and it answers @mlazos's dynamic-shapes question directly. The only thing I'd consider before/after landing is making the _build_tuple path agree with the attr-derived path on symint-slot gating (or documenting why it doesn't need to) so a future asymmetric subclass doesn't silently mis-index.

@jansel

jansel commented Jun 12, 2026

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 Jun 12, 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

@github-actions
github-actions Bot deleted the gh/jansel/1435/head branch July 13, 2026 02:25
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
AOTAutograd was still rejecting metadata mutations on traceable wrapper
subclass inputs with a blanket guard. Removing that guard alone was not
enough: metadata collection could record fake wrapper output strides and
subclass output wrapping would bake those stale outer strides into
__tensor_unflatten__ at runtime. In the issue repro this produced a
TwoTensor whose inner tensors had stride (8, 4, 1) while the wrapper outer
stride stayed at (4, 4, 1).

Teach SubclassCreationMeta to record when a wrapper subclass's outer size
or stride tracks its tensor attrs. Runtime reconstruction and generated
subclass wrapping code now use the runtime attr size/stride in those cases,
while subclasses whose outer metadata differs from their attrs continue to
use the recorded explicit outer metadata. With correct runtime wrapper
metadata in place, remove the obsolete blanket metadata-mutation guard.

The alternative was to keep a narrower ban for metadata-mutated subclass
inputs, but the runtime mutation epilogue and subclass dispatch path already
handle the metadata-only case once output wrappers are rebuilt from runtime
metadata.

Fixes pytorch#114975
Generated by my agent

Test Plan:
- Direct original repro with eager-vs-compiled recursive outer/inner metadata assertions: passed
- python test/functorch/test_subclass_codegen.py -v
- python test/functorch/test_aotdispatch.py -k subclass_metadata_mutation -v, with local torchvision import bypass due environment failure importing torchvision::nms
- Targeted test_aotdispatch.py tests with the same torchvision import bypass: TestAOTDispatch.test_aot_dispatch_input_metadata_mutation, TestAOTAutograd.test_input_mutation_aliases_bases_out_of_order, TestAOTDispatch.test_aot_dispatch_input_data_and_metadata_mutation, TestAOTAutogradWithDynamo.test_compute_outer_size_and_stride_bug, TestAOTAutogradWithDynamo.test_subclass_dynamic_stride
- Extra dynamic torch.compile(backend="aot_eager", dynamic=True) TwoTensor output metadata smoke script
- git diff --check && lintrunner -a
Pull Request resolved: pytorch#186515
Approved by: https://github.com/mlazos
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
AOTAutograd was still rejecting metadata mutations on traceable wrapper
subclass inputs with a blanket guard. Removing that guard alone was not
enough: metadata collection could record fake wrapper output strides and
subclass output wrapping would bake those stale outer strides into
__tensor_unflatten__ at runtime. In the issue repro this produced a
TwoTensor whose inner tensors had stride (8, 4, 1) while the wrapper outer
stride stayed at (4, 4, 1).

Teach SubclassCreationMeta to record when a wrapper subclass's outer size
or stride tracks its tensor attrs. Runtime reconstruction and generated
subclass wrapping code now use the runtime attr size/stride in those cases,
while subclasses whose outer metadata differs from their attrs continue to
use the recorded explicit outer metadata. With correct runtime wrapper
metadata in place, remove the obsolete blanket metadata-mutation guard.

The alternative was to keep a narrower ban for metadata-mutated subclass
inputs, but the runtime mutation epilogue and subclass dispatch path already
handle the metadata-only case once output wrappers are rebuilt from runtime
metadata.

Fixes pytorch#114975
Generated by my agent

Test Plan:
- Direct original repro with eager-vs-compiled recursive outer/inner metadata assertions: passed
- python test/functorch/test_subclass_codegen.py -v
- python test/functorch/test_aotdispatch.py -k subclass_metadata_mutation -v, with local torchvision import bypass due environment failure importing torchvision::nms
- Targeted test_aotdispatch.py tests with the same torchvision import bypass: TestAOTDispatch.test_aot_dispatch_input_metadata_mutation, TestAOTAutograd.test_input_mutation_aliases_bases_out_of_order, TestAOTDispatch.test_aot_dispatch_input_data_and_metadata_mutation, TestAOTAutogradWithDynamo.test_compute_outer_size_and_stride_bug, TestAOTAutogradWithDynamo.test_subclass_dynamic_stride
- Extra dynamic torch.compile(backend="aot_eager", dynamic=True) TwoTensor output metadata smoke script
- git diff --check && lintrunner -a
Pull Request resolved: pytorch#186515
Approved by: https://github.com/mlazos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentic Created by an AI agent ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants