Skip to content

Avoid symbolic size-one metadata guards - #186032

Closed
jansel wants to merge 11 commits into
gh/jansel/1292/basefrom
gh/jansel/1292/head
Closed

jansel wants to merge 11 commits into
gh/jansel/1292/basefrom
gh/jansel/1292/head

Conversation

@jansel

@jansel jansel commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Root cause: export recorded guards from metadata-only layout, broadcast, and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten, reshape, and group_norm; those checks excluded valid values from the declared Dim range.

Use static proofs for optional metadata fast paths that can safely fall back, while preserving guard-based behavior for normal torch.compile broadcasting. Preserve the original requested fake-view shape across retries, avoid specializing unknown source dimensions when reshaping to a size-one target, and directly flatten the statically size-one leading-dimension case needed by the repro. Symbolic group_norm inputs clone into a statically known-safe memory format instead of invoking guard-producing contiguity checks.

After rebasing over #186414, native_group_norm owns concrete input and affine contiguity. Keep only the high-level symbolic input clone here and pass weight and bias through unchanged, avoiding duplicate validation and conversions while retaining the guard-free symbolic path.

Accuracy runs also reapply the existing determinism setup after benchmark model construction. Some model constructors reset global determinism flags, which otherwise makes the eager-vs-eager check fail before the compiler path runs.

Fixes #143463

Generated by my agent

Test Plan:

.venv/bin/python -m pip install -e . -v --no-build-isolation
.venv/bin/python test/export/test_export.py TestDynamismExpression.test_reshape_view_static_size_one_before_dynamic_dim TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim TestDynamismExpression.test_reshape_view_backed_size_oblivious TestDynamismExpression.test_view_unify_cross_symbols -q
.venv/bin/python test/export/test_export.py TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim_cuda -q
.venv/bin/python test/export/test_export.py TestExport.test_dim_dynamic -q
.venv/bin/python test/test_dynamic_shapes.py TestUbackedOps.test_unbacked_reshape1 TestUbackedOps.test_backed_size_oblivious_broadcast -q
.venv/bin/python -m py_compile torch/_refs/__init__.py test/export/test_export.py
CPATH=/usr/lib/gcc/x86_64-redhat-linux/11/include lintrunner -a
git diff --check
git diff --cached --check

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit be2c047 with merge base bbcda55 (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 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

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


Code Review: PR #186032 — Avoid reshape metadata guards on symbolic size-one checks

  • Read the full diff and understand the changes
  • Review C++ changes (TensorUtils.cpp, TensorShape.cpp, Contiguity.h, SymbolicShapeMeta.cpp)
  • Review Python changes (torch/_prims, torch/_prims_common, torch/_refs, torch/_subclasses)
  • Review test additions
  • Post review feedback

Summary

This PR correctly addresses the problem: metadata-only decisions (view strides, contiguity, channels-last, broadcast) were using guard_or_true/guard_or_false helpers that emit guards on symbolic dimensions being 0/1. These guards then reject valid values from user-provided Dim ranges during export. The fix converts these to statically_known_true, which only takes the fast path when the fact can be proven without guarding — otherwise falling back to a clone/slow path/returning None.

The approach is sound and well-scoped. A few observations below:


Issues

1. Stale comments in TensorUtils.cpp (lines 380-389)

The comments at lines 383 and 385 still reference TORCH_GUARD_OR_TRUE and TORCH_GUARD_OR_FALSE, but the code now uses TORCH_STATICALLY_KNOWN_TRUE. This is misleading for future readers since the semantics are meaningfully different (one guards, the other doesn't).

// That's why we use TORCH_GUARD_OR_TRUE below.   // <-- stale

// we use TORCH_GUARD_OR_FALSE and not TORCH_GUARD_OR_TRUE ...  // <-- stale

Fix this →

2. Potential infinite loop in _reshape_view_helper_core_alg (torch/_refs/__init__.py, line 3982)

while not statically_known_true(accum % length == 0):
    end += 1
    accum *= a_.shape[end]

Previously this used eager bool() evaluation (which would always resolve), but now it uses statically_known_true. If accum % length == 0 can never be statically proven (e.g., both are symbolic with no relationship), this loop will run off the end of the dimensions and raise an IndexError on a_.shape[end]. This is probably acceptable because the reshape itself would be invalid in that case, but an explicit bounds check or error message might be clearer than a raw IndexError.

3. Mixed semantics in _compute_stride (fake_impls.py, lines 800-813)

When size_oblivious=True, the boundary detection uses statically_known_true (correct), but the inner while-loop at line 801-803 still uses maybe_guard_or_true/maybe_guard_or_false which now resolve to statically_known_true via the wrappers. This means the inner loop condition (view_numel < tensor_numel) can fail to be statically known, potentially terminating the while loop prematurely and returning None more often than strictly necessary. This is safe (falls back to clone) but could cause unnecessary copies in cases where the old code would have produced a valid view. Is that intentional, or should this inner loop get the same size_oblivious branch treatment as the boundary detection?


Observations (non-blocking)

  • SymbolicShapeMeta.cpp any_symbolic guard: The new any_symbolic check ensures backed symbolic values don't go through the size-oblivious fast path. The !numel().is_symbolic() check on compute_contiguous (but not the channels-last variants) is correct since _compute_contiguous takes numel but the channels-last templates don't.

  • check_contiguous_sizes_strides dual-path structure (_prims_common/__init__.py, lines 289-300): The if false_if_dde / if not false_if_dde pattern is slightly awkward — the two branches are mutually exclusive, but a reader seeing both conditions might wonder if both can fire. An elif would be clearer, or alternatively extract to separate functions. Not a correctness issue.

  • Test coverage: The test exercises the full pipeline (GroupNorm → permute → flatten → reshape with temporal slicing) with various temporal sizes including 1, which is exactly the edge case that was breaking. Good coverage.

  • _broadcast_in_dim_meta change (lines 1342-1343): Both inner checks use statically_known_true(a.shape[original_idx] == 1) and statically_known_true(a.shape[original_idx] == shape[idx]). This means when the shape is symbolic, we fall through to the else branch which emits a torch._check(a.shape[original_idx] == shape[idx]) runtime assertion. This is correct — if we can't prove it's a broadcast, we conservatively assume non-broadcast semantics with a runtime check.


Verdict

The changes are correct and well-targeted. The main actionable item is the stale comments in TensorUtils.cpp. The potential loop issue in _refs/__init__.py and the inner-loop semantics question in fake_impls.py are worth confirming but not blocking.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 3, 2026
Root cause: export was recording runtime guards from metadata-only layout and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten/reshape and group_norm; guard-producing checks such as channels-last contiguity and view stride collapse excluded valid values from the declared Dim range.

Fix the reshape metadata path by preserving the original requested shape across symbol-unification retries, allowing statically-known equal chunk sizes to advance view stride inference, and refusing to fold undecidable size-one dimensions into collapse-view strides. For group_norm with symbolic sizes/strides, choose a channels-last copy only when that contiguity is statically proven; otherwise make an unconditional contiguous clone so export does not emit a data-dependent contiguous guard. Exact global TensorImpl symbolic metadata behavior is unchanged.

Fixes #143463

Generated by my agent

Benchmark Results:

- Not run. The change affects compile/export metadata fast paths rather than eager tensor runtime kernels; validation focused on the dynamic export regression and lint.

Test Plan:

- ninja -C build torch_cpu

- python test/export/test_export.py -k test_group_norm_spatial_dynamic_temporal_dim

- python test/export/test_export.py TestDynamismExpression.test_view_unify_cross_symbols

- python - <<'PY' collapse-view symbolic possibly-size-one stride regression check

- git diff --check

- lintrunner -a (fails only on unrelated existing torch/nn/modules/loss.py pyrefly unexpected-keyword linear_bias)

- python test/inductor/test_cpu_repro.py CPUReproTests.test_inductor_dynamic_shapes_broadcasting (blocked by local PyTorch CUDA 12.8 / torchvision CUDA 13.0 mismatch)

- Fresh agent review: no findings after narrowing the diff

ghstack-source-id: f4e84e9

Pull-Request: #186032
@jansel

jansel commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

My agent says @claude review these changes

Updated the PR to address the dynamic-shape CI regressions without the earlier broad symbolic metadata changes. The new diff keeps TensorImpl symbolic layout predicates unchanged, narrows group_norm to make an unconditional contiguous clone only when symbolic layout contiguity is not statically proven, and fixes reshape/collapse metadata to avoid guard-producing size-one decisions while preserving correct strides.

Validation:

  • ninja -C build torch_cpu
  • python test/export/test_export.py -k test_group_norm_spatial_dynamic_temporal_dim
  • python test/export/test_export.py TestDynamismExpression.test_view_unify_cross_symbols
  • collapse-view symbolic possibly-size-one stride regression check
  • git diff --check
  • fresh agent review found no issues

Known local blockers:

  • lintrunner -a still fails only on unrelated torch/nn/modules/loss.py pyrefly unexpected-keyword linear_bias
  • inductor test invocation is blocked locally by PyTorch CUDA 12.8 / torchvision CUDA 13.0 mismatch

@claude

claude Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

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


Code Review: PR #186032 (Updated) — Avoid reshape metadata guards on symbolic size-one checks

  • Read the full diff against base branch
  • Review C++ changes (TensorUtils.cpp, TensorShape.cpp, group_norm.cpp, Contiguity.h, SymbolicShapeMeta.cpp)
  • Review Python changes (torch/_prims, torch/_prims_common, torch/_refs, torch/_subclasses)
  • Review test additions
  • Post review feedback

Summary

The updated PR is well-scoped and correctly addresses the core issue: metadata-only decisions (view strides, contiguity, channels-last, broadcast) were guarding on symbolic dimensions being 0/1 via guard_or_true/guard_or_false, which emitted guards that excluded valid values from user-provided Dim ranges during export. The fix converts these to statically_known_true, which only takes the fast path when the fact is provable without a guard — otherwise falling through to a clone/slow path/returning None.

The new approach to group_norm.cpp (explicitly handling symbolic contiguity detection and falling back to clone instead of contiguous) is much more surgical than the earlier version.


Issues

1. Stale comments in TensorUtils.cpp (lines 380-389)

The inline comments at lines 383 and 385-389 still describe TORCH_GUARD_OR_TRUE / TORCH_GUARD_OR_FALSE semantics, but the code now uses TORCH_STATICALLY_KNOWN_TRUE which has meaningfully different behavior. The logic explanation is still partially valid (it explains the iteration strategy), but the macro name references are wrong and could mislead future readers.

// That's why we use TORCH_GUARD_OR_TRUE below.   // <-- stale

// we use TORCH_GUARD_OR_FALSE and not TORCH_GUARD_OR_TRUE ...  // <-- stale

Fix this →

2. Inner while-loop in _compute_stride (fake_impls.py, lines 801-803)

When size_oblivious=True, the boundary detection (lines 785-791) now uses statically_known_true correctly, but the inner while-loop condition still uses maybe_guard_or_true(view_numel < tensor_numel) and maybe_guard_or_false(new_shape[view_d] == 1). Since maybe_guard_or_true and maybe_guard_or_false now both map to statically_known_true when size_oblivious=True, this is functionally correct — but the names maybe_guard_or_true/maybe_guard_or_false are misleading since they no longer guard. The third condition (view_numel * new_shape[view_d] == tensor_numel) provides a good escape hatch to avoid premature termination.

This is non-blocking — the behavior is correct, and the wrappers are dual-purpose for the not size_oblivious path. Just worth noting that a rename or comment would help future readers understand that in the size_oblivious branch, these wrappers now mean "statically provable" rather than "guard then assume true/false".

3. Potential IndexError in _reshape_view_helper_core_alg (torch/_refs/__init__.py, line 3982)

while not statically_known_true(accum % length == 0):
    end += 1
    accum *= a_.shape[end]

If accum % length == 0 is never statically provable (both symbolic with no known relationship), this loop will run past the end of a_.shape and raise a raw IndexError. Previously bool() evaluation would always resolve. The fallback is acceptable since the reshape would be invalid in that case, but an explicit bounds check with a clearer error ("cannot statically prove reshape viewability") would be more informative than a bare index error. Non-blocking, but worth considering.


Observations (non-blocking)

  • SymbolicShapeMeta.cpp any_symbolic gate: The new any_symbolic check correctly ensures backed symbolic values don't go through the hint-based fast path that would silently hide the symbolic SymBool result. The !numel().is_symbolic() addition on compute_contiguous (but not channels-last variants) is correct since _compute_contiguous takes numel as a parameter while the channels-last templates don't.

  • group_norm.cpp symbolic handling: The explicit has_symbolic_sizes_strides check followed by progressive probing of ChannelsLast → ChannelsLast3d → Contiguous clone is clean. The needs_symbolic_copy logic correctly resets to Contiguous format and uses clone instead of contiguous (since contiguous would attempt the same symbolic contiguity check and potentially guard).

  • _collapse_view_helper stride computation (lines 1486-1499): The three-way branching (must_be_valid → always take min stride, statically_known_true(shape[idx] != 1) → take min stride, otherwise → bail to None) is correct and well-structured. The duplicate TODO comment on lines 1489 and 1494 could be deduplicated.

  • _broadcast_shapes and should_expand: Converting from guard_or_false to statically_known_true here is sound. When the broadcast direction can't be statically determined, the code falls through to torch._check(common_shape[idx] == shape[idx]) which emits a runtime assertion instead of specializing.

  • infer_size in fake_impls.py: The change correctly uses statically_known_true(sizeA == 1) for the broadcast check inside torch._check. This means if sizeA's relationship to 1 is unknown, the check won't short-circuit on broadcasting, and the full expression sizeA == sizeB flows to the runtime check — correct behavior.

  • original_shape retention in _view_unbacked_meta (line 1008): Good fix — after try_duck_specialization_first adds equalities, retrying with the post-inference shape would miss re-running -1 inference with the new symbol relationships.

  • Test coverage: The test exercises the full pipeline (GroupNorm → permute → flatten → reshape with temporal slicing) across multiple temporal sizes including 1, 2, 3, 4 — exactly the edge cases that break when guards are emitted. Good coverage.


Verdict

The updated changes are correct, well-targeted, and significantly narrower than the earlier version. The only actionable item is the stale comments in TensorUtils.cpp (issue #1). Issues #2 and #3 are non-blocking observations. LGTM with that minor fix.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 7, 2026
Root cause: export was recording runtime guards from metadata-only layout, broadcast, and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten/reshape and group_norm; guard-producing checks such as channels-last contiguity, broadcast shape checks, and reshape viewability excluded valid values from the declared Dim range.

Fix the reshape metadata path by preserving the original requested shape across symbol-unification retries, making native flatten handle ranges with only one non-size-one dimension as direct views, and using static proofs for optional Python metadata fast paths that otherwise can fall back. For group_norm with symbolic sizes/strides, choose a channels-last copy only when that contiguity is statically proven; otherwise make an unconditional contiguous clone so export does not emit a data-dependent contiguous guard.

The Python broadcast changes are intentionally narrow: they avoid guards for statically equal/no-broadcast cases and otherwise keep existing runtime assertion or slow-path behavior. A new reshape regression covers symbolic divisibility so the refs reshape helper keeps accumulating available source dims instead of guarding on the example value or walking past rank.

Fixes #143463

Generated by my agent

Test Plan:

- ninja -C build torch_cpu
- cp build/lib/libtorch_cpu.so build/lib/libc10.so torch/lib/
- python test/export/test_export.py TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim
- python test/export/test_export.py TestDynamismExpression.test_reshape_symbolic_divisibility_no_guard
- python test/export/test_export.py TestExport.test_derived_dim_1_2
- python test/test_dynamic_shapes.py TestUbackedOps.test_inductor_view_issue_172693
- python test/export/test_export.py TestDynamismExpression.test_view_unify_cross_symbols
- git diff --check
- lintrunner -a
- python test/inductor/test_cpu_repro.py CPUReproTests.test_inductor_dynamic_shapes_broadcasting (blocked locally by PyTorch CUDA 12.8 / torchvision CUDA 13.0 mismatch)
- Fresh review subagent: first found the generic symbolic reshape divisibility issue; after the fix and added regression, no findings

ghstack-source-id: f5ddfdb

Pull-Request: #186032
@jansel

jansel commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@jansel

jansel commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I updated the PR to address the failing dynamic-shape CI regressions. The fix keeps the GroupNorm symbolic-size guard removal, narrows Python metadata changes to static-proof fast paths, adds a generic symbolic reshape divisibility regression, and validates the earlier derived-dim and ubacked reshape failures locally.

@claude

claude Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 3m 17s —— View job


Code Review: PR #186032 (Latest) — Avoid reshape metadata guards on symbolic size-one checks

  • Read the full diff against base branch
  • Review C++ changes (TensorUtils.cpp, TensorShape.cpp, group_norm.cpp, Contiguity.h, SymbolicShapeMeta.cpp)
  • Review Python changes (torch/_prims, torch/_prims_common, torch/_refs, torch/_subclasses)
  • Review test additions
  • Post review feedback

Summary

The changes correctly convert metadata-only decisions (view strides, contiguity, channels-last, broadcast) from guard_or_true/guard_or_false (which emit guards specializing on whether symbolic dimensions are 0/1) to statically_known_true (which only takes fast paths when provable without a guard). The fallback behavior in each case is safe: returning None/clone for reshape, returning false for contiguity checks, and emitting runtime assertions for broadcast direction.


Issues

1. Stale comments in TensorUtils.cpp (lines 380–389)

This was flagged in both prior reviews and remains unfixed. Lines 383 and 385–389 still reference TORCH_GUARD_OR_TRUE and TORCH_GUARD_OR_FALSE, but the code now uses TORCH_STATICALLY_KNOWN_TRUE:

// That's why we use TORCH_GUARD_OR_TRUE below.   // <-- stale

// we use TORCH_GUARD_OR_FALSE and not TORCH_GUARD_OR_TRUE ...  // <-- stale

The algorithmic explanation in these comments (why we accumulate, when to stop) is still valid, but the macro name references are wrong and the semantics are meaningfully different (static proof vs. guarding assumption). Should be updated to reference TORCH_STATICALLY_KNOWN_TRUE and explain that the conditions now serve as provability checks rather than guard-producing assumptions.

Fix this →


Observations (non-blocking)

Flatten direct-view optimization (TensorShape.cpp:4141–4169)

The new fast path for flattening a range with at most one non-size-one dimension is correct and well-designed. It correctly handles: (a) all-ones ranges (stride = 1), (b) single symbolic non-one dim (uses that dim's stride), (c) multiple non-provably-one dims (falls through to reshape). The as_strided_symint avoids reshape's viewability logic entirely.

_reshape_view_helper_core_alg bounds fix (torch/_refs/__init__.py:3973–3975)

The prior review flagged a potential IndexError. This is now addressed with:

if end + 1 >= a_.ndim:
    break

Good fix.

should_expand simplification (torch/_refs/__init__.py:488–499)

The old code had complex sym_and/sym_or/torch._check logic. The new code simply returns True (expand needed) whenever equality isn't statically provable. This is conservative but correct — expand on an already-correct shape is a no-op view, and the expand call's internals handle the runtime broadcasting logic. The old torch._check for shape unification is no longer needed here since expand itself will propagate shape information.

C++ while-loop third condition (TensorUtils.cpp:393–394)

The new sym_eq(view_numel * newshape[view_d], tensor_numel) condition is a nice addition — it provides an "exact fit" escape that prevents the loop from over-consuming view dimensions when neither view_numel < tensor_numel nor newshape[view_d] == 1 are individually provable, but their product is.

_compute_stride Python path NOT changed

The Python mirror in fake_impls.py (lines 745–800) still uses guard_or_true/guard_or_false when size_oblivious=True. This is intentional — it's in the _view_unbacked_meta FakeTensor fallback path where these wrappers call size-oblivious variants that handle symbols correctly without creating the problematic guards. The C++ computeStride_impl was the path producing the invalid guards during export.

group_norm.cpp progressive probe pattern (lines 197–227)

Clean approach: detect symbolic sizes first, progressively probe ChannelsLast → ChannelsLast3d → Contiguous via statically_known_true, and use clone (not contiguous) when contiguity can't be proven — correctly avoiding re-entry into the same symbolic contiguity check that contiguous() would trigger.

check_contiguous_sizes_strides dual-path structure (_prims_common/__init__.py:289–300)

The if false_if_dde / if not false_if_dde pattern uses separate conditions rather than if/else. The branches are mutually exclusive so this is functionally correct but slightly harder to read at a glance. Non-blocking.

_broadcast_in_dim_meta reordering (torch/_prims/__init__.py:1342–1351)

The new order (check equality first → preserve stride, then check size-1 → broadcast stride 0, else → runtime assertion) is more robust than the old nested structure. When the relationship is undecidable, the runtime assertion ensures correctness without specializing.

SymbolicShapeMeta.cpp any_symbolic gate

Correctly prevents backed symbolic values (which have hints) from entering the hint-based fast path that would silently evaluate SymBools without going through the _compute_contiguous_sym slow path. The !numel().is_symbolic() addition for compute_contiguous (but not channels-last) matches the parameter lists of the underlying template functions.


Test Coverage

The test exercises the full end-to-end pipeline (GroupNorm → permute → flatten → reshape with temporal slicing) across temporal sizes 1, 2, 3, 4, 28 — covering the exact edge cases that triggered the original failure. The test_reshape_symbolic_divisibility_no_guard test verifies that reshape with symbolic divisibility doesn't over-guard.


Verdict

LGTM with one minor fix (stale comments in TensorUtils.cpp). The approach is correct, well-scoped, and narrowly targeted. The only actionable item has been flagged in two prior reviews — everything else is sound.

@jansel jansel added the agentic Created by an AI agent label Jun 9, 2026
[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 10, 2026
Root cause: export was recording runtime guards from metadata-only layout, broadcast, and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten/reshape and group_norm; those metadata checks excluded valid values from the declared Dim range.

Use static proofs for optional symbolic metadata branches that can safely fall back instead of guarding, preserve the original requested fake view shape across retry, and make symbolic CPU group_norm clone using a memory format that is statically known safe. Native flatten now handles a range with at most one provably non-size-one dimension as a direct view, avoiding reshape viewability guards for that case.

Fixes #143463

Generated by my agent

Test Plan:

- ninja -C build torch_cpu

- cp build/lib/libtorch_cpu.so build/lib/libc10.so torch/lib/

- python test/export/test_export.py TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim -q

- python test/export/test_export.py TestExport.test_dim_dynamic -q

- python test/test_dynamic_shapes.py TestUbackedOps.test_unbacked_reshape1 -q

- git diff --check main

- python -m py_compile torch/_refs/__init__.py

- lintrunner -a

- Review subagent found and I removed a transient torch.nn.functional.py regression from the diff

ghstack-source-id: 35fcc9e

Pull-Request: #186032
@jansel

jansel commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I updated the PR to avoid symbolic size-one metadata guards in the GroupNormSpatial export repro. Targeted tests now pass locally: TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim, TestExport.test_dim_dynamic, TestUbackedOps.test_unbacked_reshape1, plus lintrunner -a.

@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 5m 24s —— View job


Code Review: PR #186032 — Avoid reshape metadata guards on symbolic size-one checks

  • Read full diff against base
  • Review C++ changes (TensorShape.cpp, group_norm.cpp, Contiguity.h, SymbolicShapeMeta.cpp)
  • Review Python changes (_prims, _prims_common, _refs, fake_impls)
  • Review test additions
  • Post review feedback

Summary

The diff has tightened since prior reviews. The core idea is unchanged and correct: metadata-only fast paths (view strides, contiguity, channels-last, broadcast) used guard_or_true/guard_or_false, which emit guards specializing on whether a symbolic extent is 0/1 and thereby reject valid values from a user Dim range during export. Converting these to static-proof checks (or, in export, deferred-assert-aware variants) means the fast path is taken only when provable, otherwise falling back to a clone / slow path / None / runtime assertion.

Two notable improvements relative to the earlier rounds:

  • The TensorUtils.cpp change is gone. The stale-comment concern flagged in all three prior reviews is now moot — that file is no longer in the diff.
  • _reshape_view_helper_core_alg no longer risks an IndexError. The divisibility loop reverted to eager bool() (while accum % length != 0), and the size-one specialization is handled up front by the new IntWithoutSymInt and length == 1 fast path (torch/_refs/__init__.py:3977), which splits an outer-1 dim before any equality check. This is cleaner than the earlier statically_known_true loop and resolves the prior concern.

Issues / Questions

1. Asymmetric maybe_size_one semantics in _prims_common/__init__.py

check_contiguous_sizes_strides (lines ~277-289) gets a nuanced maybe_size_one that consults prefer_deferred_runtime_asserts_over_guards and uses guard_or_false in that mode, falling back to statically_known_true otherwise:

def maybe_size_one(x):
    if not false_if_dde:
        return bool(x)
    if isinstance(x, torch.SymBool):
        shape_env = getattr(x.node, "shape_env", None)
        if shape_env is not None and shape_env.prefer_deferred_runtime_asserts_over_guards:
            return guard_or_false(x)
    return statically_known_true(x)

But is_channels_last_contiguous_2d/3d (lines ~352, ~383) use the plain form:

maybe_size_one = statically_known_true if false_if_dde else eval_eager

So in export (deferred-asserts) mode, the contiguous check can still take its size-one shortcut via guard_or_false, while the channels-last checks cannot. Is that intentional (e.g. a missed channels-last fast path is cheaper / less common than a missed contiguous one), or should the three share the same maybe_size_one helper? If intentional, a one-line comment on why the contiguous path is special would prevent this from drifting. Discuss →

2. should_expand now delegates runtime checks to expand (torch/_refs/__init__.py:496-505)

The old body called torch._check(x == y, ...) to unify undecidable symbolic dims. The new body simply returns True (expand needed) whenever statically_known_true(x == y) is false:

for x, y in zip(a, b):
    if statically_known_true(x == y):
        continue
    return True
return False

This is conservative and avoids the size-one guard, but it shifts the burden onto expand to emit the correctness check for the u0 vs u1 (neither statically 1 nor statically equal) case. That should be fine since expand's own meta validates dim compatibility, but it's a real semantic shift from "unify here" to "let expand assert later." Worth a quick confirmation that the export repro and an unbacked-vs-unbacked expand still get a runtime assertion rather than silently broadcasting.


Observations (non-blocking)

  • flatten direct-view fast path (TensorShape.cpp:4144-4172) is correct and applies to both eager and symbolic tensors. A flatten range with at most one non-size-one dim is always a view: stride is 1 for an all-ones range (numel 1) or the lone non-one dim's stride otherwise; size-one dims never affect iteration, so as_strided_symint is valid. For eager tensors this is equivalent to the prior reshape_symint result (single-non-one-dim flatten was never a copy), so no behavior change — just bypasses reshape viewability logic.

  • SymbolicShapeMeta.cpp any_symbolic gate correctly implements the old TODO exclude backed_size_oblivious from this path. Backed symbolics have hints, so all_hinted alone would route them into the concrete _compute_*<SymInt> hint path and collapse the SymBool; the new !any_symbolic(...) forces them through _compute_contiguous_sym. The extra !numel().is_symbolic() on compute_contiguous (absent on the channels-last variants) matches the template signatures — only _compute_contiguous takes numel. The added O(ndim) scan is negligible next to the existing all_hinted loop.

  • group_norm.cpp (lines 197-219) cleanly probes ChannelsLast → ChannelsLast3d → Contiguous via statically_known_true and uses clone(memory_format) instead of contiguous(memory_format) for the symbolic case, avoiding re-entry into the same symbolic contiguity predicate that contiguous() would trigger. Default-to-Contiguous for the unprovable case is the safe choice.

  • Contiguity.h: TORCH_GUARD_OR_FALSE(numel==0) / GUARD_OR_TRUE(stride != ...) → TORCH_STATICALLY_KNOWN_TRUE(...) with the negated stride equality is logically consistent — !known(eq) is the correct conservative replacement for guard_or_true(ne) (treat undecidable as "not contiguous").

  • infer_size (fake_impls.py:1954-1961): the three statically_known_true fast paths are inserted before the original broadcasting-first logic. The comment about testing broadcasting before equality is preserved for the undecidable case (it still flows to the original code). The static sizeA == sizeB short-circuit is safe (equal dims need no broadcast).

  • _view_unbacked_meta original_shape retention (fake_impls.py:1028-1103): good fix — retrying duck-specialization with the post--1-inference shape would skip re-running inference under the newly added equalities.

  • _broadcast_in_dim_meta reordering (_prims/__init__.py:1340-1348): equality-first → preserve stride, then size-1 → stride 0, else runtime assert. More robust than the old nested guard_or_false and avoids specializing when undecidable.


Test Coverage

test_group_norm_spatial_dynamic_temporal_dim exercises the full reported pipeline (GroupNorm → permute → flatten → reshape with ::2 temporal slicing) and re-runs the exported module across temporal sizes 1, 2, 3, 4, 28 — directly covering the size-one edge case that produced the ceil(ceil(dim_2/2)/2) != 1 guard. Note: the test_reshape_symbolic_divisibility_no_guard test mentioned in the previous review comment is not present in this diff; if it was intended to stay, it appears to have been dropped — otherwise the group-norm test is the sole new coverage.


Verdict

LGTM. The diff is correct and narrower than prior rounds, and the two long-standing review items (stale TensorUtils.cpp comments, potential reshape IndexError) are both resolved. The only things worth a reply before merge are the maybe_size_one asymmetry (#1) and confirming the should_expand delegation still asserts on unbacked-vs-unbacked (#2) — both non-blocking.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 14, 2026
Root cause: export was recording runtime guards from metadata-only layout, broadcast, and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten/reshape and group_norm; those metadata checks excluded valid values from the declared Dim range.

Use static proofs for optional symbolic metadata branches that can safely fall back instead of guarding, preserve the original requested fake view shape across retry, and make symbolic CPU group_norm clone using a memory format that is statically known safe. Native flatten now only bypasses reshape for the specific statically size-one leading-dimension case needed by the repro, avoiding the broader one-non-size-one fast path that broke channels-last cat.

Fixes #143463

Generated by my agent

Test Plan:

- ninja -C build torch_cpu

- cp build/lib/libtorch_cpu.so build/lib/libc10.so torch/lib/

- python test/export/test_export.py TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim -q

- python test/export/test_export.py TestExport.test_export_max_onnx_reported -q

- python test/export/test_export.py TestExport.test_dim_dynamic -q (review subagent)

- python test/export/test_export.py TestDynamismExpression.test_view_unify_cross_symbols -q (review subagent)

- python test/test_dynamic_shapes.py TestUbackedOps.test_unbacked_reshape1 -q

- python - <<'PY' ... run test/inductor/test_torchinductor.py CpuTests.test_cat_cpu with torchvision shim ... PY

- python - <<'PY' ... run test/inductor/test_compiled_autograd.py TestCompiledAutograd.test_compiled_autograd_does_not_specialize_on_bw_symints with torchvision shim ... PY

- git diff --check main

- lintrunner aten/src/ATen/native/TensorShape.cpp test/export/test_export.py

- lintrunner -a (fails only on unrelated existing pyrefly errors in effects.py, functional_tensor.py, and proxy_tensor.py)

ghstack-source-id: 2218ea7

Pull-Request: #186032
@jansel

jansel commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@jansel

jansel commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I updated the PR to fix the CI regression from the prior broad flatten fast path. The flatten special case is now limited to the statically size-one leading-dimension pattern needed by the GroupNormSpatial export repro, and the reproduced CpuTests.test_cat_cpu failure passes locally with the torchvision import shim.

@claude

claude Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 6m 36s —— View job


Code Review: PR #186032 — Avoid reshape metadata guards on symbolic size-one checks

  • Read full diff against base
  • Review C++ changes (TensorShape.cpp, group_norm.cpp, Contiguity.h, SymbolicShapeMeta.cpp)
  • Review Python changes (_prims, _prims_common, _refs, fake_impls)
  • Review test additions
  • Post review feedback

Summary

The diff is unchanged in intent from prior rounds: metadata-only fast paths (view strides, contiguity, channels-last, broadcast) that used guard_or_true/guard_or_false — emitting guards that specialize a symbolic extent on == 0/1 and exclude valid Dim values during export — are converted to static-proof checks, falling back to clone / slow path / None / runtime assert when unprovable. The two long-standing items from earlier reviews are resolved: the TensorUtils.cpp stale comments are gone (that file is no longer touched), and the _reshape_view_helper_core_alg IndexError risk is replaced by an up-front size-one split (_refs/__init__.py:4007). The approach is sound.

One new concern is worth verifying before merge, plus the carried-over asymmetry note.


Concern worth verifying

_broadcast_shapes now uses static-proof on the non-export path too (torch/_refs/__init__.py:419-484)

guard_or_false_unless_static_metadata returns guard_or_false only when shape_env.prefer_deferred_runtime_asserts_over_guards is set (export). In every other case — including regular torch.compile with dynamic shapes — it returns statically_known_true. That is a behavior change to the standard compile path, not just export.

Tracing a backed-symbolic broadcast where the first operand's dim hints to 1 and the second hints to >1 (e.g. a.shape == (s0,) hint 1, b.shape == (s1,) hint 4):

  • Old (guard_or_false): processing a, guard_or_false(s0 == 1) is True at the hint → continue, common stays 1; processing b, common == 1 → common = s1. Result [s1]. Correct.
  • New (statically_known_true): processing a, statically_known_true(s0 == 1) is False → common == 1 → common = s0; processing b, statically_known_true(common == 1) i.e. s0 == 1 is False → common stays s0 → falls to else: torch._check(s0 == s1). That asserts the two dims equal instead of broadcasting, and the hints (1 vs 4) make it a contradiction at trace time.

In practice this is gated by specialize_zero_one (default on): a dim whose example value is 1 becomes the constant 1, never a backed symbol, so the case is normally unreachable. It can surface only when a size-one dim is forced dynamic (mark_dynamic + specialize_zero_one disabled), and the backed_size_oblivious branch above handles its own case separately. So likely benign — but since _broadcast_shapes is core to every decomposition, please confirm with a quick backed-symbolic broadcast trace (size-1 dim marked dynamic) that this doesn't regress, or restrict the static-proof behavior to the deferred-asserts mode the way check_contiguous_sizes_strides does. Look into this →

should_expand (lines 495-506), by contrast, is safe in all modes: returning True only ever triggers an expand (a no-op view when shapes already match, with expand's own meta validating), and it returns False only when all dims are statically equal.


Carried-over note (non-blocking)

maybe_size_one asymmetry in _prims_common/__init__.py

check_contiguous_sizes_strides (lines 279-289) uses the deferred-aware maybe_size_one (guard_or_false under prefer_deferred_runtime_asserts_over_guards, else statically_known_true), but is_channels_last_contiguous_2d/3d (lines 357, 388) use the plain statically_known_true if false_if_dde else eval_eager. So in export mode the contiguous check can still take its size-one shortcut via a deferred assert while the channels-last checks cannot. This was flagged last round and is unchanged — it's safe either way (both fall back conservatively), but a one-line comment on why the contiguous path is special, or sharing one helper, would keep the two from drifting.


Observations (confirmed correct)

  • flatten fast path (TensorShape.cpp:4144-4157): narrowly scoped to start_dim==0, end_dim==1 with a statically size-one dim 0 and a not-statically-one dim 1 — exactly the repro (permute(...).flatten(0,1) over (1, t, c, h, w)). A size-one leading dim has only one element, so its stride is irrelevant and [1, n, ...] -> [n, ...] with stride[1] is always a valid view. Shape/stride vector lengths line up. Correct, and general cases still fall through to reshape_symint.
  • group_norm.cpp:200-219: progressively probes ChannelsLast → ChannelsLast3d → Contiguous via statically_known_true for symbolic inputs and uses clone(memory_format) rather than contiguous(memory_format) to avoid re-entering the symbolic contiguity predicate. The clone only runs under has_symbolic_sizes_strides (tracing/fake), so no extra eager copy. Default-to-Contiguous for the unprovable case is the safe choice.
  • Contiguity.h: !TORCH_STATICALLY_KNOWN_TRUE(sym_eq(stride, expected)) is the correct conservative replacement for TORCH_GUARD_OR_TRUE(sym_ne(...)) — undecidable is treated as "not contiguous".
  • SymbolicShapeMeta.cpp any_symbolic gate: correctly forces backed symbolics (which are hinted) through _compute_*_sym instead of collapsing the SymBool via the hinted _compute_*<SymInt> path, implementing the old TODO exclude backed_size_oblivious. The extra !numel().is_symbolic() only on compute_contiguous matches the template signatures (only _compute_contiguous takes numel). The added O(ndim) scan is negligible next to all_hinted.
  • _broadcast_in_dim_meta (_prims/__init__.py:1337-1348): equality-first → preserve stride, then size-1 → stride 0, else runtime assert. More robust than the old nested guard_or_false; avoids specializing when undecidable.
  • infer_size (fake_impls.py:2240-2247): the three statically_known_true short-circuits are inserted before the original broadcast-first logic; each is safe (equal dims or a provable size-1), and undecidable cases still flow to the original code, so the "test broadcasting before equality" invariant is preserved.
  • _view_unbacked_meta original_shape retention (fake_impls.py:1082-1160): correct — retrying duck-specialization with the post--1-inference shape would skip re-running inference under the newly added equalities.
  • make_fast_binary_impl (fake_impls.py:2316): statically_known_true(sym_eq(op.shape, final_shape)) correctly takes the slow path when the output stride match is undecidable.

Test coverage

test_group_norm_spatial_dynamic_temporal_dim exercises the full reported pipeline (GroupNorm → permute → flatten → reshape with ::2 temporal slicing, two stacked blocks) and re-runs the exported module across temporal sizes 1, 2, 3, 4, 28 — directly covering the size-one edge case that produced the ceil(ceil(dim_2/2)/2) != 1 guard. The test_view_unify_cross_symbols guard-message regex is broadened to optionally accept the x.size()[0] == 1 or disjunction, consistent with the broadcast changes. The test_reshape_symbolic_divisibility_no_guard test mentioned in an earlier review comment is not in this diff; if it was meant to stay, it appears dropped.


Verdict

LGTM modulo one verification: confirm the _broadcast_shapes switch to static-proof on the non-export path doesn't regress backed-symbolic size-one broadcasting in torch.compile (likely moot under default specialize_zero_one, but _broadcast_shapes is hot enough across decomps to warrant a check). The maybe_size_one asymmetry is a non-blocking clarity note. Everything else is correct and well-targeted.
· branch gh/jansel/1292/head

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 17, 2026
Root cause: export was recording runtime guards from metadata-only layout, broadcast, and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten/reshape and group_norm; those metadata checks excluded valid values from the declared Dim range.

Use static proofs for optional symbolic metadata branches that can safely fall back instead of guarding, preserve the original requested fake view shape across retry, and make symbolic CPU group_norm clone using a memory format that is statically known safe. Native flatten only bypasses reshape for symbolic tensors in the specific statically size-one leading-dimension case needed by the repro, preserving concrete and subclass flatten behavior.

After CI exposed normal-compile broadcast regressions, keep the static-proof `_broadcast_shapes` behavior limited to export and preserve the original `guard_or_false` behavior for normal torch.compile so hinted size-one broadcasting still works.

Fixes #143463

Generated by my agent

Test Plan:
- ninja -C build torch_cpu
- cp build/lib/libtorch_cpu.so torch/lib/libtorch_cpu.so && cp build/lib/libc10.so torch/lib/libc10.so
- python test/export/test_export.py TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim -q
- python test/export/test_export.py TestExport.test_export_max_onnx_reported -q
- python test/test_dynamic_shapes.py TestUbackedOps.test_unbacked_reshape1 -q
- python test/test_dynamic_shapes.py TestUbackedOps.test_backed_size_oblivious_broadcast -q
- python test/test_torch.py TestTorchDeviceTypeCPU.test_memory_format_operators_cpu -q
- python - <<'PY' ... run test/test_linalg.py TestLinalgCPU.test_cholesky_solve_batched_broadcasting_cpu_complex128 with torchvision shim ... PY
- python test/distributed/tensor/test_dtensor_ops.py TestMultiThreadedDTensorOpsCPU.test_dtensor_op_db_cartesian_prod_cpu_float32 -q
- python test/export/test_export.py -k test_dim_dynamic (review subagent)
- python test/export/test_export.py -k test_view_unify_cross_symbols (review subagent)
- python test/test_dynamic_shapes.py -k test_backed_size_oblivious_expand (review subagent)
- git diff --check
- lintrunner -a

Attempted but locally timed out after 120s:
- python - <<'PY' ... run test/functorch/test_aotdispatch.py TestEagerFusionOpInfoCPU.test_aot_autograd_symbolic_exhaustive_linalg_tensorinv_cpu_float32 with torchvision shim ... PY
- python - <<'PY' ... run test/test_proxy_tensor.py TestProxyTensorOpInfoCPU.test_make_fx_symbolic_exhaustive_nn_functional_conv_transpose3d_cpu_float32 with torchvision shim ... PY

ghstack-source-id: b82dfa9

Pull-Request: #186032
@jansel

jansel commented Jun 17, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@jansel

jansel commented Jun 17, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I updated the PR to address the latest CI fallout. The broadcast metadata change is now export-only so normal torch.compile keeps hinted guard_or_false broadcasting behavior, and the flatten as_strided fast path is limited to symbolic-size tensors so concrete/subclass paths such as DTensor cartesian_prod keep the old reshape behavior. Local targeted checks now pass for the original GroupNormSpatial export repro, export max, unbacked reshape, backed-size-oblivious broadcast, memory_format_operators, cholesky_solve_batched_broadcasting, and DTensor cartesian_prod.

@jansel

jansel commented Jun 24, 2026

Copy link
Copy Markdown
Contributor Author

My agent says the TorchBench CSV changes are from reapplying the existing determinism setup after model construction, not from the symbolic-shape metadata fix. The affected torchvision constructors reset cuDNN determinism flags, so reapplying determinism makes the eager-vs-eager accuracy check exercise the intended deterministic compiled path; the higher graph-break counts for mnasnet1_0 and mobilenet_v2 are the real compiled baselines once that masking is removed. I added this context to the PR description, and the latest Dr. CI classifies remaining inductor failures as flaky or broken trunk rather than new regressions.

@jansel
jansel marked this pull request as ready for review June 24, 2026 22:00
@jansel
jansel requested review from ezyang and ydwu4 June 24, 2026 22:00
@jansel
jansel requested review from angelayi and zou3519 June 30, 2026 18:34
@jansel
jansel requested review from bobrenjc93, eellison and oulgen July 8, 2026 00:58
Comment thread torch/_refs/__init__.py Resolved
[ghstack-poisoned]
jansel added a commit that referenced this pull request Jul 14, 2026
Root cause: export was recording runtime guards from metadata-only layout, broadcast, and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten/reshape and group_norm; those metadata checks excluded valid values from the declared Dim range.

Use static proofs for optional symbolic metadata branches that can safely fall back instead of guarding, preserve the original requested fake view shape across retry, and make symbolic group_norm clone using a memory format that is statically known safe instead of calling guard-producing contiguous checks. Native flatten only bypasses reshape for symbolic tensors in the specific statically size-one leading-dimension case needed by the repro, preserving concrete and subclass flatten behavior.

After CI exposed normal-compile broadcast regressions, keep the static-proof broadcast behavior limited to export while preserving guard_or_false behavior for normal torch.compile. Restore the hinted SymbolicShapeMeta layout fast path as well, because sending backed symbolic layouts through the full symbolic expression path caused proxy tensor and AOT OpInfo tests to time out on complex SymPy expressions.

The previous CI failure was an inductor TorchBench eager determinism check, not a compiled accuracy failure: TorchBench torchvision model constructors reset cuDNN determinism flags after the harness configures accuracy-run determinism, so eager-vs-eager could return eager_two_runs_differ before Inductor ran. Reapply the existing determinism setup after model construction for accuracy runs, and restore the real compiled graph-break baselines for mnasnet1_0 and mobilenet_v2 that were incorrectly moved to zero by an early-return run.

Reviewer feedback found one overly broad reshape split: producing a target dimension of 1 by unconditionally splitting the current source dimension misaligned reshapes with a leading concrete size-one source dimension followed by a dynamic dimension. Keep symbolic unknown source dimensions on the split path to avoid size-one guards, but skip the split when the source dimension is statically known to be 1. This uses static proof rather than guard_or_false so it does not reinstall the same symbolic size-one guard this PR removes.

Fixes #143463

Generated by my agent

Test Plan:
- ninja -C build torch_cpu
- ninja -C build torch_python
- cp build/lib/*.so torch/lib/
- python test/export/test_export.py TestDynamismExpression.test_reshape_view_static_size_one_before_dynamic_dim TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim TestDynamismExpression.test_reshape_view_backed_size_oblivious TestDynamismExpression.test_view_unify_cross_symbols -q
- python test/export/test_export.py TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim_cuda -q
- python -m py_compile torch/_refs/__init__.py test/export/test_export.py
- git diff --check
- git diff --cached --check
- lintrunner -a
- fresh review subagent found no blocking issues
- Prior validation for the benchmark determinism update: TorchBench training AMP mobilenet_v2 and mnasnet1_0 accuracy plus graph-break checks with local torchvision extension shim

ghstack-source-id: 4604b46

Pull-Request: #186032
@jansel
jansel requested review from BoyuanFeng and laithsakka July 27, 2026 07:20
[ghstack-poisoned]
@jansel jansel changed the title Avoid reshape metadata guards on symbolic size-one checks Avoid symbolic size-one metadata guards Aug 9, 2026
@jansel

jansel commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I rebased this PR onto current main and adapted the GroupNorm path to #186414: concrete inputs and affine contiguity remain owned by native_group_norm, while the high-level path keeps only the symbolic input clone required to avoid size-one guards. The supported editable CPU/CUDA build, focused CPU/CUDA export regressions, adjacent dynamic-shape tests, py_compile, and lintrunner -a all pass. CI has restarted on be2c047.

@jansel

jansel commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

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


Reviewed the rebased diff — the export-gated broadcast work looks right, but three changes (the flatten as_strided fast path, the ungated contiguity/channels-last and fake-binary changes, and the unconditional symbolic group_norm clone) affect normal torch.compile rather than just export and I think warrant another look before merge.

Full review: PR #186032 — Avoid symbolic size-one metadata guards

PR Review: #186032

Summary

Converts metadata-only fast paths (view strides, contiguity, channels-last, broadcast) from guard-emitting guard_or_* checks to static proofs so export stops recording size-one guards that exclude valid Dim values. The broadcast changes are correctly export-gated, and bobrenjc93's split_dim misalignment (torch/_refs/__init__.py:4152) is fixed. Problems below: the flatten fast path bypasses two protections reshape_symint deliberately has, several changes leak into non-export torch.compile despite the PR description saying otherwise, three different "are we exporting" gates are now in play (one of them effectively dead), and the tests don't follow the repo's device-generic pattern.


Code Quality

1. aten/src/ATen/native/TensorShape.cpp:4153-4163 — the flatten fast path bypasses both protections reshape_symint exists to provide.

reshape_symint deliberately does not use as_strided, for two documented reasons (TensorShape.cpp:1998-2019):

  • "the backward for as_strided is not as efficient as that of view" — confirmed: as_strided → as_strided_backward(grad, TensorGeometry(self), ...) (tools/autograd/derivatives.yaml:340) vs view/_reshape_alias → grad.reshape_symint(self.sym_sizes()) (derivatives.yaml:1950, 1505). Since flatten.using_ints is CompositeImplicitAutograd (native_functions.yaml:2638), as_strided is what gets recorded. The path is gated on has_symbolic_sizes_strides(), i.e. it fires only during dynamic-shape tracing — precisely where the graph quality matters.
  • The explicit !self.is_xla() && !self.is_lazy() && !self.is_ipu() && !at::isTensorSubclassLike(self) bail-out. The new path skips this entirely. isTensorSubclassLike returns true whenever dispatch_mode_enabled() (aten/src/ATen/TensorSubclassLikeUtils.h:50-54), and a DTensor being traced has symbolic outer sizes, so it reaches this branch. DTensor's as_strided handler only supports same-rank permutations and otherwise raises RuntimeError("as_strided not supported with DTensor") (torch/distributed/tensor/_dispatch.py:114-129, _as_strided_permutation returns None on len(size) != tensor.dim() at line 97-98 — and flatten always reduces rank). A DTensor with a statically size-one dim 0 and dynamic dim 1 hitting flatten(0, 1) would hard-error. This is the same class of failure as the cartesian_prod regression from an earlier round; restricting to symbolic tensors narrowed it but did not remove it.

_reshape_alias_symint(shape, strides) is the primitive reshape_symint itself uses for exactly this "viewable geometry with known strides" case (TensorShape.cpp:2016) and carries the cheap view-style backward. Using it, plus mirroring the XLA/lazy/IPU/subclass bail-out, would keep the guard-free behavior without either downside.

2. torch/_refs/__init__.py:423-429 — hoist the export check out of the loop.

guard_or_false_unless_exporting re-reads torch.compiler.is_exporting() on all three call sites (lines 462, 465, 472) for every dimension of every shape, and _broadcast_shapes runs for every elementwise ref via _maybe_broadcast. Bind once before the loop, matching the existing idiom two files over (torch/_prims_common/__init__.py:277, maybe_guard_or_true = guard_or_true if false_if_dde else eval_eager):

guard_or_false_maybe = (
    statically_known_true if torch.compiler.is_exporting() else guard_or_false
)

3. torch/_prims/__init__.py:1290-1293 — duplicated helper with no comment.

guard_or_false_unless_exporting is defined a second time here, verbatim, minus the explanatory comment that the _refs copy has. Either share one helper or copy the comment; a bare is_exporting() branch with no rationale invites someone to "simplify" it away later.

4. aten/src/ATen/native/group_norm.cpp:226-242 — repeated condition and a device-predicate inconsistency.

preserve_cpu_memory_format && has_symbolic_sizes_strides is spelled out twice in the if/else if; nesting the two sym_is_contiguous probes under one guard reads better. Also input.is_privateuseone() here vs input.device().is_privateuseone() used everywhere else in this file (lines 98, 276) — match the file.

5. aten/src/ATen/native/group_norm.cpp:203-204 — unrelated NOLINTNEXTLINE. The misc-use-internal-linkage suppression and its comment have nothing to do with symbolic size-one guards. Separate PR.


Infrastructure

6. Three different gating strategies, and one of them is effectively dead.

The PR now uses three distinct policies for the same "don't guard on size-one during export" intent:

Location Gate Effect in default torch.export Effect in plain torch.compile
_refs/__init__.py:423, _prims/__init__.py:1290 torch.compiler.is_exporting() static proof unchanged (guard_or_false)
_prims_common/__init__.py:279-289 shape_env.prefer_deferred_runtime_asserts_over_guards static proof (see below) static proof
_prims_common/__init__.py:357, :388 (channels-last 2d/3d) none static proof static proof
fake_impls.py:2403 (make_fast_binary_impl) none static proof static proof

prefer_deferred_runtime_asserts_over_guards defaults to False for torch.export.export (torch/export/__init__.py:68, torch/export/_trace.py:161,980) and for Dynamo (torch/_dynamo/config.py:387). It is only True for the ONNX exporter (torch/onnx/_internal/exporter/_capture_strategies.py:190) or explicit opt-in. So the guard_or_false branch inside maybe_size_one never fires on the path this PR is fixing — the nuance buys nothing, and the net effect is that check_contiguous_sizes_strides uses statically_known_true for all false_if_dde=True callers, i.e. every is_contiguous_or_false call in normal dynamic-shape torch.compile, not just export. The channels-last helpers aren't gated at all.

The PR description says "preserving guard-based behavior for normal torch.compile broadcasting" — that holds for the broadcast helpers but not for contiguity, channels-last, or the fake-binary fast path. Either gate those on is_exporting() too, or state explicitly in the description that the contiguity/channels-last/layout fast paths intentionally become conservative everywhere and explain why that's safe. The three-way divergence should collapse to one signal regardless.

7. torch/_subclasses/fake_impls.py:2403 — ungated change on a hot fake-tensor path; please verify no tracing-time regression.

statically_known_true(sym_eq(op.shape, final_shape)) replaces guard_or_false, and failing it means return slow("both tensors nontrivially broadcast") — a full slow_ref decomposition under FakeTensorMode (line 2363-2366, 2408) instead of O(1) metadata construction. make_fast_binary_impl backs add/sub/mul/div, so this is one of the hottest paths in fake-tensor tracing.

The identical-symbol case is fine: the new infer_size short-circuit returns sizeA unchanged when statically_known_true(sizeA == sizeB) (line 2327-2329), so Eq(s0, s0) simplifies statically. The case I could not rule out is two distinct backed symbols with equal hints and no recorded equality — old code returned True via hint+guard, new code returns False and falls to the slow path (guard_or_false → _guard_or → evaluate_sym_node, symbolic_shapes.py:1580-1584, vs statically_known_true → _static_eval_sym_bool, :1655-1676). Duck-shaping normally unifies equal example sizes, which is why this may be rare in practice — but "may be rare" is not a compile-time budget argument. Since this change is not needed for the export fix, the lowest-risk option is to gate it on is_exporting() like the broadcast ones; otherwise please post a pr_time_benchmarks / tracing-time comparison.

8. aten/src/ATen/native/group_norm.cpp:241-242 — the clone is unconditional for any symbolic input.

has_symbolic_sizes_strides ? input.clone(memory_format) : input clones whenever sizes are symbolic, not only when contiguity is unprovable. That covers all dynamic-shape torch.compile, not just export. Two consequences:

  • For an already-contiguous input the clone should be removed by remove_noop_ops (torch/_inductor/fx_passes/post_grad.py:1288, 1360 — aten.clone is in noop_registry and same_meta(node, src) holds), so Inductor is likely fine. Anything consuming the pre-Inductor graph (AOTAutograd metadata, export graphs, non-Inductor backends) keeps the copy. Worth confirming the export graph for the repro doesn't carry a stray clone.
  • The decomp already handles this: native_group_norm in torch/_refs/__init__.py:3459-3465 does input.contiguous(memory_format=suggest_memory_format(input)). Since the PR description says native_group_norm now owns concrete input contiguity after native_group_norm: Handle non-contiguous tensors, rather than throwing #186414, having the wrapper also clone means two layers decide layout. A comment stating which layer owns what would prevent the next rebase from re-diverging.

9. Eager vs. compile output memory-format divergence in group_norm.

CPU channels-last input, contiguity not statically provable symbolically → memory_format stays Contiguous → clone(Contiguous), and native_group_norm allocates Y with empty_like(X, {}, memory_format) (group_norm.cpp:105), so the output is contiguous. The same tensor in eager gets suggest_memory_format() → channels-last output. So group_norm output layout differs between eager and dynamic-shape compile for that input. Defaulting to Contiguous when unprovable is the safe correctness choice, but the layout change is observable and untested (see below), and layout changes propagate into downstream conv/norm kernel selection.


Testing

10. New tests don't use the repo's device-generic pattern. CLAUDE.md requires instantiate_device_type_tests for any test checking on-device numerics, and @parametrize for multi-input tests. test/export/test_export.py:447-493 instead hand-rolls a _test_group_norm_spatial_dynamic_temporal_dim(self, device) helper plus a _cuda entry point behind @unittest.skipIf(not torch.cuda.is_available()), and loops for t in (1, 2, 3, 4, 28) inline so the first failure hides the rest. Note test_export.py already imports requires_cuda_and_triton/requires_gpu (line 99) if the file genuinely can't host device-generic tests — at minimum use the existing decorator rather than a bespoke skipIf.

11. No test for the flatten fast path itself. The only coverage is end-to-end through the GroupNorm repro. Nothing asserts the [1, s, ...] -> [s, ...] flatten produces a view with the expected strides and storage offset, and nothing exercises it for a tensor subclass or a sliced/offset input independent of group_norm. Given finding #1, a direct test (including a DTensor or TorchDispatchMode case) is what would have caught the subclass bypass.

12. No coverage for findings #8/#9. No test asserts group_norm's output memory format under dynamic shapes, and there is no existing group_norm + channels_last layout test to fall back on (searched test/test_nn.py, test/test_torch.py, test/inductor/). A layout change with zero assertions will only surface as an unexplained perf or accuracy delta later.

13. test/export/test_export.py:7528-7533 — broadened regex weakens the assertion.

rf"Guard failed: (?:x\.size\(\)\[0\] == 1 or )?{expected_guard}"

The optional group means the test passes with or without the new x.size()[0] == 1 or disjunct, so it no longer pins down which guard export records for max(). The disjunct's appearance is a real change in recorded constraints. Assert the exact new string — if it legitimately varies by mode, split into two cases. As written, a future regression that drops or re-adds the disjunct is invisible.


API Design

14. benchmarks/dynamo/common.py:4861-4865 is unrelated to this PR and its justification no longer appears in the diff.

Re-invoking setup_determinism(args) after model construction is a global change to every --accuracy run in every suite (it flips use_deterministic_algorithms, cuDNN determinism/benchmark, TF32, and re-patches torch.manual_seed — common.py:4203-4243). It has nothing to do with symbolic size-one guards.

The graph-break CSV bumps that motivated it are no longer in this diff — inductor_torchbench_training.csv already has mnasnet1_0,pass,7 / mobilenet_v2,pass,6 on both base and HEAD, and #187651 (c7a18daa, an ancestor of HEAD) had moved them the other way, to 0. So the evidence tying this hunk to a needed baseline no longer travels with it. Two questions: (a) is this still required for CI to pass, and (b) if so, shouldn't it land as its own PR with its own baseline updates, so a revert of the symbolic-shape fix doesn't silently revert a harness determinism fix? Only inductor_torchbench_training.csv was ever touched — the timm/huggingface accuracy CSVs were never checked.


Backward Compatibility

15. c10/core/Contiguity.h:45 — numel == 0 early-out narrowed.

TORCH_GUARD_OR_FALSE(sym_eq(numel, 0)) → TORCH_STATICALLY_KNOWN_TRUE(sym_eq(numel, 0)) inside is_contiguous_or_false. For an unbacked numel this is unchanged (guard_or_false also yields False on DDE), but for a backed symbolic numel with hint 0 the old code returned "contiguous" and the new code falls through to the stride loop and can return False. _compute_contiguous_sym is reached from SymbolicShapeMeta::compute_contiguous (c10/core/SymbolicShapeMeta.cpp:107) for every symbolic tensor, so this affects normal compile as well as export. A zero-sized tensor is contiguous by definition, so returning False is a lost fast path, not a correctness bug — but it means empty-tensor dynamic-shape paths can now take a copy. Worth confirming against the empty-tensor dynamic-shape tests.


Recommendation

Request Changes

Blocking: finding #1 (the flatten fast path bypasses reshape_symint's subclass/backend bail-out and the view-vs-as_strided backward choice — use _reshape_alias_symint and replicate the bail-out), plus findings #11/#12 (no direct test for the new flatten path or the group_norm layout change). Findings #6/#7/#8 need a decision before merge: either gate the contiguity, channels-last, and make_fast_binary_impl changes on is_exporting() like the broadcast ones, or justify in the PR description why making them conservative for all of torch.compile is acceptable — the description currently claims normal compile behavior is preserved, and for those three it isn't. Finding #14 (the benchmarks/dynamo/common.py determinism hunk) should be split out. The rest are quality items.

· branch `gh/jansel/1292/head`

jansel added a commit that referenced this pull request Aug 9, 2026
Root cause: export recorded guards from metadata-only layout, broadcast, and view decisions that used example-shape truth for symbolic size-one checks. In the issue repro, temporal slicing feeds GroupNormSpatial through flatten, reshape, and group_norm; those checks excluded valid values from the declared Dim range.

Use static proofs for optional metadata fast paths that can safely fall back, while preserving guard-based behavior for normal torch.compile broadcasting. Preserve the original requested fake-view shape across retries, avoid specializing unknown source dimensions when reshaping to a size-one target, and directly flatten the statically size-one leading-dimension case needed by the repro. Symbolic group_norm inputs clone into a statically known-safe memory format instead of invoking guard-producing contiguity checks.

After rebasing over #186414, native_group_norm owns concrete input and affine contiguity. Keep only the high-level symbolic input clone here and pass weight and bias through unchanged, avoiding duplicate validation and conversions while retaining the guard-free symbolic path.

Accuracy runs also reapply the existing determinism setup after benchmark model construction. Some model constructors reset global determinism flags, which otherwise makes the eager-vs-eager check fail before the compiler path runs.

Fixes #143463

Generated by my agent

Test Plan:

```bash
.venv/bin/python -m pip install -e . -v --no-build-isolation
.venv/bin/python test/export/test_export.py TestDynamismExpression.test_reshape_view_static_size_one_before_dynamic_dim TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim TestDynamismExpression.test_reshape_view_backed_size_oblivious TestDynamismExpression.test_view_unify_cross_symbols -q
.venv/bin/python test/export/test_export.py TestDynamismExpression.test_group_norm_spatial_dynamic_temporal_dim_cuda -q
.venv/bin/python test/export/test_export.py TestExport.test_dim_dynamic -q
.venv/bin/python test/test_dynamic_shapes.py TestUbackedOps.test_unbacked_reshape1 TestUbackedOps.test_backed_size_oblivious_broadcast -q
.venv/bin/python -m py_compile torch/_refs/__init__.py test/export/test_export.py
CPATH=/usr/lib/gcc/x86_64-redhat-linux/11/include lintrunner -a
git diff --check
git diff --cached --check
```

ghstack-source-id: e954362

Pull-Request: #186032
@jansel

jansel commented Aug 18, 2026

Copy link
Copy Markdown
Contributor Author

My agent says this PR is being closed as part of a cleanup of open agentic PRs to focus review bandwidth on a smaller set; the linked issue remains open.

@jansel jansel closed this Aug 18, 2026
@github-actions
github-actions Bot deleted the gh/jansel/1292/head branch November 2, 2026 01:42
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.

2 participants