Skip to content

fix for silent data corruption optimization—-Inductor: freeze layout before noncontiguous reshape view - #192575

Closed
cartazio wants to merge 1 commit into
pytorch:mainfrom
cartazio:carters_intern/inductor-reshape-layout-fix
Closed

cartazio wants to merge 1 commit into
pytorch:mainfrom
cartazio:carters_intern/inductor-reshape-layout-fix

Conversation

@cartazio

@cartazio cartazio commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

i was hitting a very strange blowup on reverse gradient calcs, after a lot of bisections i was able to pin it down to a one line fix.

roughly: bad buffer reuse in fused code plus strided slices that are not powers of two are way more likely to tickle it.

id like to emphasize this bug will silently cause quite large relative or absolute errors on programs that trigger it. im quite fortunate to have even caught the problem!

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

@pytorch-bot

pytorch-bot Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit b1b3de0 with merge base 93977bb (image):

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: cartazio / name: Carter Schonwald (b1b3de0)

@pytorch-bot pytorch-bot Bot added ciflow/torchtitan Run TorchTitan integration tests module: inductor labels Aug 8, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Aug 8, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@cartazio

cartazio commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

id like to emphasize: silent data corruption in program evaluation that will mess with gradient calcs but could happen otherwise

@cartazio cartazio changed the title inductor: freeze layout before noncontiguous reshape view /nductor: freeze layout before noncontiguous reshape view Aug 8, 2026
@cartazio cartazio changed the title /nductor: freeze layout before noncontiguous reshape view fix for silent data corruption optimization—-Inductor: freeze layout before noncontiguous reshape view Aug 8, 2026
@jansel

jansel commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Reviewing this PR

  • Load /pr-review guidelines
  • Read the diff
  • Analyze torch/_inductor/ir.py change in context
  • Analyze the added test
  • Post review

View job run | Branch: carters_intern/inductor-reshape-layout-fix

@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 10, 2026
@zou3519
zou3519 requested a review from eellison August 10, 2026 03:39
@cartazio

Copy link
Copy Markdown
Contributor Author

theres a related in spirit bug on windows when running cpu pytorch with more than one thread when large arrays arent aligned with the power of two around 32k, i can dig into that too if needed

@cartazio

Copy link
Copy Markdown
Contributor Author

@claude could you try again?

@eellison eellison added the topic: not user facing topic category label Aug 17, 2026

@eellison eellison left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the fix!

Comment thread torch/_inductor/ir.py
storage, old_layout = as_storage_and_layout(x, freeze=False)
# ReinterpretView stores an index map derived from this layout, so the
# backing storage must not remain flexible after the view is created.
storage, old_layout = as_storage_and_layout(x)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a pretty innocuous api usage that nonetheless leads to an incorrectness error. in a follow up I will try to make this less prone to error :'( not needed for this pr

cc @laithsakka who's pr #173062 introduced this

@eellison

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 17, 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

@cartazio

Copy link
Copy Markdown
Contributor Author

awesome! silent data corruption bugs in compilers are nasty :)

eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Written with Claude Code.

ghstack-source-id: 4e7646a
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Written with Claude Code.

ghstack-source-id: f842e1d
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 61b75aa
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: b5c4873
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 8535637
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 1217156
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 81df1a1
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 4f3d535
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 6a9737f
Pull-Request: #193860
eellison added a commit that referenced this pull request Aug 18, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 6dfb53a
Pull-Request: #193860
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…before noncontiguous reshape view (pytorch#192575)

i was hitting a very strange blowup on reverse gradient calcs, after a lot of bisections i was able to pin it down to a one line fix.

roughly: bad buffer reuse in fused code plus strided slices that are not powers of two are way more likely to tickle it.

id like to emphasize this bug will silently cause quite large relative or absolute errors on programs that trigger it.  im quite fortunate to have even caught the problem!

Pull Request resolved: pytorch#192575
Approved by: https://github.com/eellison
eellison added a commit that referenced this pull request Sep 9, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: c231264
Pull-Request: #193860
eellison added a commit that referenced this pull request Sep 10, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 0687cbd
Pull-Request: #193860
eellison added a commit that referenced this pull request Sep 22, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 47b0b54
Pull-Request: #193860
eellison added a commit that referenced this pull request Oct 12, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Written with Claude Code.

ghstack-source-id: 802ead2
Pull-Request: #193860
eellison added a commit that referenced this pull request Oct 12, 2026
The strides of an unfrozen FlexibleLayout are provisional: freezing can
reorder them (fill order from decide_layout) or pad them (comprehensive
padding), so a stride read whose result outlives the freeze silently
computes wrong indices. Nothing in the API distinguished a harmless peek
from a persisted read, and this has repeatedly caused silent data
corruption: #147828, and most recently #192575, which was introduced
while fixing #172693 and survived review and six months in main.

This PR makes the peek/persist distinction explicit and enforces it,
with enforcement ON by default so CI surfaces remaining violations
(set TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES=0 to opt out).
Review in this order:

1. ir.py: Layout.stride_hint() / IRNode.get_stride_hint() /
   maybe_get_stride_hint() are the explicit way to read provisional
   strides for heuristics whose answers may go stale; results must not
   be persisted. FlexibleLayout.stride raises under the new
   config.strict_flexible_layout_strides (default ON).
   ReinterpretView.__post_init__ asserts that the base layout is frozen,
   since the view's FixedLayout indexes raw storage and cannot survive a
   base stride change. ir.freeze_storage_layout() freezes the storage
   backing a node through boxes and generic views.
2. Requirement gates now follow the pattern "flexible means not settled;
   take the require_* path, which freezes a flexible layout into the
   wanted order in place (no copy)": is_aligned_realized_tensor returns
   False for flexible layouts (sdpa constraint),
   try_match_insignificant_strides freezes before its early returns, and
   graph.py's realize-to-strides calls require_stride_order
   unconditionally instead of comparing provisional strides first.
3. Freeze fixes for reads that persist strides: the slice_/select
   unbacked lowerings (DynamicSelectStorageOffset / as_strided), flex
   attention q/k/v reads that derive persisted output and grad layouts
   (triton, cpu, decoding, cutedsl flash), flex_mps capture and input
   strides baked into Metal shader source, subgraph choice generation
   (freeze reordered above the stride reads it already required),
   TMADescriptor's ownership ReinterpretView, the qlinear binary "sum"
   in-place rewrap, and a typo in CUTLASS render that froze based on
   X's layout while iterating all input nodes.
4. Hint migrations for audited peeks: layout predicates, require_stride1,
   Reduction.num_splits pre/post-freeze comparison, bucketize helpers,
   scaled_mm row/col-major gates (aten validates at runtime), grouped-mm
   K-major flags (template stride hooks register validating
   constraints), TMA compatibility gates, cpp template kernel symbol
   collection and benchmark render, autotune benchmark input generation
   and log metadata, kernel_inputs accessors, debug/provenance strings.
5. CK (ROCm) and cutedsl template reads were converted to hints on the
   theory that final render is post-finalize; this classification is
   NOT fully audited (if the autotune-time rendered source is reused,
   they need triton-style buffer_layout_constraints validation) and is
   flagged for follow-up. The hints keep strict mode scanning past them.

The known-reachable violation (sdpa alignment check reading a
realized-but-flexible attention bias, reachable with an ordinary
computed-bias-with-reuse pattern) is fixed here and has a regression
test. Remaining CI failures under the default-on strict mode are
expected to be discovered iteratively and fixed in follow-ups.

Test Plan:

```
python test/inductor/test_layout_freezing.py
python -m pytest test/inductor/test_torchinductor.py -k "view or reshape or slice or chunk or split or cat or permute or transpose or scaled_mm or mm"
python -m pytest test/inductor/test_unbacked_symints.py test/inductor/test_padding.py
python -m pytest test/inductor/test_fused_attention.py test/inductor/test_flex_attention.py
python -m pytest test/inductor/test_max_autotune.py test/inductor/test_triton_kernels.py
```

All run with the strict mode on by default. The mkldnn qlinear, ROCm CK,
MPS flex, and cutedsl paths could not be exercised locally; relying on
CI for those.

Round 3 (found by the default-on strict mode via the flex attention
suite): the flex backward scatter modification emits grad-accumulation
indexing math into the template from the scatter graph's strides, whose
MutationLayoutSHOULDREMOVE delegates to a possibly-flexible mutation
target -- the "fresh contiguous grad" assumption held only by
placeholder luck. freeze_storage_layout now sees through mutation
layouts to their target and the scatter graph is frozen before
emission (fixes 148 TestLearnableBiases/captured-grad failures from one
root cause). Also: ir.allow_layout_analysis() extends the existing
FlexibleLayout.allow_indexing pattern so analysis extents (op counting,
dep extraction, constant evaluation) may read provisional strides
without freezing or erroring -- flags kept separate so a region can be
evaluated against hypothetical strides; cpp template kernel symbol
collection and stride hooks migrated to hints; autotune_strides_hinted
log metadata migrated to hints.

Round 4 (found by CI on the strict default): the onednn conv fusion
prepare (_prepare_convolution_fusion_create) fake-ran conv on unfrozen
input strides to derive the persisted output layout -- inputs are now
frozen first, mirroring ExternKernel.process_kernel. And the strict
check no longer fires for 0-dim layouts (empty strides cannot change at
freeze), which un-breaks while_loop's scalar carried inputs on all
devices (test_control_flow, MPS).

Round 5 (found by CI on the strict default, after rebasing onto main):
the conv backward lowering fake-ran convolution_backward on provisional
strides to derive the persisted dw/dx layouts. input/grad_out (dw) and
grad_out/weight (dx) are then required into that order, so those reads
are a peek; but dw's memory format also depends on weight and dx's on
input, which were never frozen. Now the order is picked from a peek under
allow_layout_analysis, the remaining operand is frozen, and the persisted
layout is computed from the frozen inputs.

Written with Claude Code.

ghstack-source-id: 19ba65f
Pull-Request: #193860
Z-Ghostshell added a commit to Z-Ghostshell/pytorch that referenced this pull request Nov 18, 2026
Summary:
Add regression coverage for pytorch#204346. PR pytorch#192575 already fixes the implementation by freezing the backing layout before a noncontiguous reshape records its index map. This diff changes tests only.

Both tests compile the issue's graphs with comprehensive padding. `test_nested_cat_returned_expand` checks that every returned tensor fits inside its storage before any output is read; `test_nested_cat_chunk_values` compares the chunk outputs with eager using `assertEqual`. Both turn off Dynamo's `canonicalize_output_graph_node_order`, which the Dynamo test harness enables: the bug depends on the traced output order, and with canonicalization the chunk case passes even without the fix. The earlier `dynamic=True` variants are removed because dynamic shapes are not padded by default, so they did not exercise the bug.

### Agent details

Prepared with an AI assistant. The author must inspect the exact code before GitHub export. No landing or review-gate bypass is authorized.

Test Plan:
Ran on an NVIDIA PG509-210 (A100, sm80, driver 580.126.09) with the published torch 2.15.0+cu132 / Triton 3.9.0 wheels in an isolated venv, loading this test file directly rather than a source build. The runner instantiates the CUDA tests from the file; `--old-view` restores the pre-pytorch#192575 `View.create` in-process (backing layout looked up with `freeze=False`).

```sh
python run_nested_cat.py test_padding.py              # x3
python run_nested_cat.py test_padding.py --old-view   # x3
arc lint fbcode/caffe2/test/inductor/test_padding.py
```

With the fix, both tests pass in 3/3 runs. With the old `View.create`, both fail in 3/3 runs: the expand test at the storage-bounds check (`257964 not less than or equal to 254016`, stride `(0, 1344, 27, 1)`), and the chunk test with 16198/16320 mismatched elements and a max absolute difference of 4.16, matching the issue. In the previous revision the chunk test passed without the fix because of the harness's output canonicalization; turning it off makes both tests real fail-before guards.

Not run: a clean current-master native build, XPU, or the rest of `test_padding.py`. `arc lint` passes.

Differential Revision: D131637630
Z-Ghostshell added a commit to Z-Ghostshell/pytorch that referenced this pull request Nov 18, 2026
…ch#205202)

Summary:

Add regression coverage for pytorch#204346. PR pytorch#192575 already fixes the implementation by freezing the backing layout before a noncontiguous reshape records its index map. This diff changes tests only.

Both tests compile the issue's graphs with comprehensive padding. `test_nested_cat_returned_expand` checks that every returned tensor fits inside its storage before any output is read; `test_nested_cat_chunk_values` compares the chunk outputs with eager using `assertEqual`. Both turn off Dynamo's `canonicalize_output_graph_node_order`, which the Dynamo test harness enables: the bug depends on the traced output order, and with canonicalization the chunk case passes even without the fix. The earlier `dynamic=True` variants are removed because dynamic shapes are not padded by default, so they did not exercise the bug.

### Agent details

Prepared with an AI assistant. The author must inspect the exact code before GitHub export. No landing or review-gate bypass is authorized.

Test Plan:
Ran on an NVIDIA PG509-210 (A100, sm80, driver 580.126.09) with the published torch 2.15.0+cu132 / Triton 3.9.0 wheels in an isolated venv, loading this test file directly rather than a source build. The runner instantiates the CUDA tests from the file; `--old-view` restores the pre-pytorch#192575 `View.create` in-process (backing layout looked up with `freeze=False`).

```sh
python run_nested_cat.py test_padding.py              # x3
python run_nested_cat.py test_padding.py --old-view   # x3
arc lint fbcode/caffe2/test/inductor/test_padding.py
```

With the fix, both tests pass in 3/3 runs. With the old `View.create`, both fail in 3/3 runs: the expand test at the storage-bounds check (`257964 not less than or equal to 254016`, stride `(0, 1344, 27, 1)`), and the chunk test with 16198/16320 mismatched elements and a max absolute difference of 4.16, matching the issue. In the previous revision the chunk test passed without the fix because of the harness's output canonicalization; turning it off makes both tests real fail-before guards.

Not run: a clean current-master native build, XPU, or the rest of `test_padding.py`. `arc lint` passes.

Differential Revision: D131637630
pytorchmergebot pushed a commit that referenced this pull request Nov 18, 2026
…) (#205202)

Summary:

Add regression coverage for #204346. PR #192575 already fixes the implementation by freezing the backing layout before a noncontiguous reshape records its index map. This diff changes tests only.

Both tests compile the issue's graphs with comprehensive padding. `test_nested_cat_returned_expand` checks that every returned tensor fits inside its storage before any output is read; `test_nested_cat_chunk_values` compares the chunk outputs with eager using `assertEqual`. Both turn off Dynamo's `canonicalize_output_graph_node_order`, which the Dynamo test harness enables: the bug depends on the traced output order, and with canonicalization the chunk case passes even without the fix. The earlier `dynamic=True` variants are removed because dynamic shapes are not padded by default, so they did not exercise the bug.

### Agent details

Prepared with an AI assistant. The author must inspect the exact code before GitHub export. No landing or review-gate bypass is authorized.

Test Plan:
Ran on an NVIDIA PG509-210 (A100, sm80, driver 580.126.09) with the published torch 2.15.0+cu132 / Triton 3.9.0 wheels in an isolated venv, loading this test file directly rather than a source build. The runner instantiates the CUDA tests from the file; `--old-view` restores the pre-#192575 `View.create` in-process (backing layout looked up with `freeze=False`).

```sh
python run_nested_cat.py test_padding.py              # x3
python run_nested_cat.py test_padding.py --old-view   # x3
arc lint fbcode/caffe2/test/inductor/test_padding.py
```

With the fix, both tests pass in 3/3 runs. With the old `View.create`, both fail in 3/3 runs: the expand test at the storage-bounds check (`257964 not less than or equal to 254016`, stride `(0, 1344, 27, 1)`), and the chunk test with 16198/16320 mismatched elements and a max absolute difference of 4.16, matching the issue. In the previous revision the chunk test passed without the fix because of the harness's output canonicalization; turning it off makes both tests real fail-before guards.

Not run: a clean current-master native build, XPU, or the rest of `test_padding.py`. `arc lint` passes.

Differential Revision: D131637630

Pull Request resolved: #205202
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

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants