Skip to content

[inductor] Add stride_hint() and opt-in strict checking of FlexibleLayout stride reads - #193860

Draft
eellison wants to merge 23 commits into
gh/eellison/1089/basefrom
gh/eellison/1089/head
Draft

eellison wants to merge 23 commits into
gh/eellison/1089/basefrom
gh/eellison/1089/head

Conversation

@eellison

@eellison eellison commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

AI-generated description (unreviewed)

An unfrozen FlexibleLayout's strides are provisional: freezing can reorder or
pad them, so code that reads and persists them computes wrong indices
(#147828, #192575). On main today, with default config and
capture_scalar_outputs=True, torch.sin(x).select(0, i.item()) + 1 on a
[16, 1030] CUDA tensor is wrong in every element (fixed later in this stack).

This adds stride_hint() for reads that may go stale, and
config.strict_flexible_layout_strides (default off), which raises on
FlexibleLayout.stride and on a ReinterpretView over a flexible base. Also
allow_layout_analysis(), freeze_storage_layout(), hint migrations for
generic reads (layout predicates, repr, require_stride1, ...), and a
per-file opt-in list in torch/_inductor/test_case.py. No behavior change
with the flag off. The PRs above fix one area each and opt its tests in; the
last turns the check on for tests and CI.

Test Plan:

python test/inductor/test_layout_freezing.py

Authored with Claude Code.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

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

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

@eellison

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: inductor"

@eellison eellison changed the title [inductor] Enforce freeze discipline for FlexibleLayout strides [wip][inductor] Enforce freeze discipline for FlexibleLayout strides Aug 18, 2026
[ghstack-poisoned]
@eellison
eellison requested a review from drisspg as a code owner August 18, 2026 03:00
@pytorch-bot pytorch-bot Bot added ciflow/b200 ciflow/h100 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 labels Aug 18, 2026
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

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "ciflow/rocm"

@eellison

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "ciflow/mps"

@pytorch-bot pytorch-bot Bot added ciflow/rocm ciflow/mps Run MPS tests (subset of trunk) labels Aug 18, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 18, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/rocm.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-navi31
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

Please add the new label to .github/pytorch-probot.yml

[ghstack-poisoned]
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
[ghstack-poisoned]
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
[ghstack-poisoned]
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
[ghstack-poisoned]
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
[ghstack-poisoned]
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
[ghstack-poisoned]
[ghstack-poisoned]
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
[ghstack-poisoned]
[ghstack-poisoned]
eellison added a commit that referenced this pull request Oct 15, 2026
## AI-generated description (draft, not yet reviewed by the author)

Last PR of the FlexibleLayout freeze-discipline stack. With every area
fixed, the per-file opt-in list in `torch/_inductor/test_case.py` is
replaced by turning `strict_flexible_layout_strides` on for all inductor
tests (unless `TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES` is set
explicitly), and CI exports the env var so tests that compile through other
`TestCase` classes are checked too. Production stays off.

New violations now fail at compile time in CI, at the line that read the
provisional stride, instead of becoming silent wrong results. For example,
the conv backward lowering added weeks before the check was first run
(fixed earlier in this stack) would have been caught in its own PR.

Validated: the full CI matrix (default, inductor, dynamo_wrapped,
benchmarks, ROCm, MPS, aarch64) was green with the check on everywhere at
#193860 e77db71; the only failure, torchtitan, was failing on main.

Test Plan:

Run on B200 against main e972a0a, with strict mode on for these files:

```
python test/inductor/test_layout_freezing.py   # 31 passed
python test/inductor/test_torchinductor.py     # 2717 passed, 3 failed (also fail on main)
```

plus full CI on this PR.

Authored with Claude Code.

ghstack-source-id: b69d4d4
Pull-Request: #200996
pytorchmergebot pushed a commit that referenced this pull request Nov 2, 2026
…rs (#200461)

Author's note: Behind an off-by-default flag, a stacked computed buffer is copied by a kernel fused into its producer instead of being re-read by a pointwise cat, which saves a kernel per stack in the MXFP6 preparation graphs. It's off by default because a broad benchmark sweep found regressions when the destination is transposed; the real fix (size-1 views not freezing their base) will replace the flag.

The description below was drafted with an AI assistant (Claude):

> `torch.stack(ts, -1)` decomposes to `cat([t.unsqueeze(-1) ...], -1)`. When a
> stacked input is already realized, its unsqueeze builds a `ReinterpretView`,
> which freezes the buffer's layout, so `ConcatKernel` cannot place it in the
> output and it has to be copied. `cat` then treats that input as needing a copy
> kernel anyway; if every input does, it lowers the whole cat as one
> `pointwise_cat` kernel that re-reads the realized buffer. That kernel iterates
> over the stacked output, so it cannot fuse with the input's producer, and the
> producer's buffer is written and read back.
>
> A per-input copy through `ConcatKernel` has the same shape as the input, so the
> scheduler can fuse it into the producer, which then stores straight into the
> output slice; the intermediate buffer is removed when nothing else reads it.
> So in `should_lower_cat_input`, do not count an input as needing a copy when
> it is all of a buffer Inductor computes (and not a no-op such as
> `torch.empty`, which has nothing to fuse into).
>
> This is behind `config.cat_fuse_computed_input_copies`, off by default.
> Whether fusing the copy is profitable depends on the destination layout
> relative to the producer's iteration order, which the lowering does not know:
> on a broad benchmark sweep it removed bytes and kernels in most changed
> graphs, but a padded *transposed* output made the fused stores uncoalesced
> (1.6-1.9x slower on two cross-entropy gradients). Workloads where it is a win
> (MXFP6 preparation: one kernel instead of two) opt in. The flag is
> temporary: a size-1 view (the stack's unsqueeze) should not freeze its base,
> since it is valid under any base layout; with that, cat places the buffer in
> its output with no copy for everyone, and this flag can be removed.
>
> Alternatives considered: not freezing on size-1 views (a lazy unsqueeze view
> that `ConcatKernel` sees through) is the real fix, but lazy views currently
> claim their base's layout while having no strides, which some lowerings trip
> over; that needs fixing first (and #193860's freeze discipline). A layout
> derived from another layout would be the general form; that is a larger IR
> change.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_torchinductor.py -k "cat or stack"
> python -m pytest test/inductor/test_inline_asm_concat.py
> ```
> With the flag on, `test_stack_realized_inputs` generates 1 kernel on GPU instead of 2;
> `test_stack_realized_input_twice` copies one realized buffer into two
> slices. `test_inline_asm_concat.py` stacks the outputs of multi-output
> `inline_asm_elementwise` calls; without this change, the six-output
> `test_stack_outputs` case and the `use_asm` cases of
> `test_normal_choices_stack_reshape` get a separate stack kernel.
> `test_unrelated_asm_outputs` and `TestPointwisePackingChoices` cover stacks that
> already compile to one kernel. On the MXFP6 preparation benchmark graphs, the
> generated Triton kernels match those of the lazy-view approach (same kernel
> count, loads and stores).
>
> This change was prepared with an AI assistant.

Pull Request resolved: #200461
Approved by: https://github.com/drisspg
ghstack dependencies: #200459, #200460
[ghstack-poisoned]
eellison added a commit that referenced this pull request Nov 2, 2026
## AI-generated description (draft, not yet reviewed by the author)

Last PR of the FlexibleLayout freeze-discipline stack. With every area
fixed, the per-file opt-in list in `torch/_inductor/test_case.py` is
replaced by turning `strict_flexible_layout_strides` on for all inductor
tests (unless `TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES` is set
explicitly), and CI exports the env var so tests that compile through other
`TestCase` classes are checked too. Production stays off.

New violations now fail at compile time in CI, at the line that read the
provisional stride, instead of becoming silent wrong results. For example,
the conv backward lowering added weeks before the check was first run
(fixed earlier in this stack) would have been caught in its own PR.

Validated: the full CI matrix (default, inductor, dynamo_wrapped,
benchmarks, ROCm, MPS, aarch64) was green with the check on everywhere at
#193860 e77db71; the only failure, torchtitan, was failing on main.

Test Plan:

Run on B200 against main a67a74d, with strict mode on for these files:

```
python test/inductor/test_layout_freezing.py   # 34 passed
python test/inductor/test_torchinductor.py     # 2790 passed, 3 failed (also fail on main)
```

plus full CI on this PR.

Authored with Claude Code.

ghstack-source-id: 8a776a5
Pull-Request: #200996
eellison added a commit that referenced this pull request Nov 2, 2026
## AI-generated description (draft, not yet reviewed by the author)

Last PR of the FlexibleLayout freeze-discipline stack. With every area
fixed, the per-file opt-in list in `torch/_inductor/test_case.py` is
replaced by turning `strict_flexible_layout_strides` on for all inductor
tests (unless `TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES` is set
explicitly), and CI exports the env var so tests that compile through other
`TestCase` classes are checked too. Production stays off.

New violations now fail at compile time in CI, at the line that read the
provisional stride, instead of becoming silent wrong results. For example,
the conv backward lowering added weeks before the check was first run
(fixed earlier in this stack) would have been caught in its own PR.

Validated: the full CI matrix (default, inductor, dynamo_wrapped,
benchmarks, ROCm, MPS, aarch64) was green with the check on everywhere at
#193860 e77db71; the only failure, torchtitan, was failing on main.

Test Plan:

Run on B200 against main a67a74d, with strict mode on for these files:

```
python test/inductor/test_layout_freezing.py   # 34 passed
python test/inductor/test_torchinductor.py     # 2790 passed, 3 failed (also fail on main)
```

plus full CI on this PR.

Authored with Claude Code.

ghstack-source-id: e976c8a
Pull-Request: #200996
eellison added a commit that referenced this pull request Nov 3, 2026
## AI-generated description (draft, not yet reviewed by the author)

Last PR of the FlexibleLayout freeze-discipline stack. With every area
fixed, the per-file opt-in list in `torch/_inductor/test_case.py` is
replaced by turning `strict_flexible_layout_strides` on for all inductor
tests (unless `TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES` is set
explicitly), and CI exports the env var so tests that compile through other
`TestCase` classes are checked too. Production stays off.

New violations now fail at compile time in CI, at the line that read the
provisional stride, instead of becoming silent wrong results. For example,
the conv backward lowering added weeks before the check was first run
(fixed earlier in this stack) would have been caught in its own PR.

Validated: the full CI matrix (default, inductor, dynamo_wrapped,
benchmarks, ROCm, MPS, aarch64) was green with the check on everywhere at
#193860 e77db71; the only failure, torchtitan, was failing on main.

Test Plan:

Run on B200 against main a67a74d, with strict mode on for these files:

```
python test/inductor/test_layout_freezing.py   # 34 passed
python test/inductor/test_torchinductor.py     # 2790 passed, 3 failed (also fail on main)
```

plus full CI on this PR.

Authored with Claude Code.

ghstack-source-id: f001aad
Pull-Request: #200996
eellison added a commit that referenced this pull request Nov 3, 2026
## AI-generated description (draft, not yet reviewed by the author)

Last PR of the FlexibleLayout freeze-discipline stack. With every area
fixed, the per-file opt-in list in `torch/_inductor/test_case.py` is
replaced by turning `strict_flexible_layout_strides` on for all inductor
tests (unless `TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES` is set
explicitly), and CI exports the env var so tests that compile through other
`TestCase` classes are checked too. Production stays off.

New violations now fail at compile time in CI, at the line that read the
provisional stride, instead of becoming silent wrong results. For example,
the conv backward lowering added weeks before the check was first run
(fixed earlier in this stack) would have been caught in its own PR.

Validated: the full CI matrix (default, inductor, dynamo_wrapped,
benchmarks, ROCm, MPS, aarch64) was green with the check on everywhere at
#193860 e77db71; the only failure, torchtitan, was failing on main.

Test Plan:

Run on B200 against main a67a74d, with strict mode on for these files:

```
python test/inductor/test_layout_freezing.py   # 34 passed
python test/inductor/test_torchinductor.py     # 2790 passed, 3 failed (also fail on main)
```

plus full CI on this PR.

Authored with Claude Code.

ghstack-source-id: 86647c5
Pull-Request: #200996
[ghstack-poisoned]
eellison added a commit that referenced this pull request Nov 3, 2026
## AI-generated description (draft, not yet reviewed by the author)

Last PR of the FlexibleLayout freeze-discipline stack. With every area
fixed, the per-file opt-in list in `torch/_inductor/test_case.py` is
replaced by turning `strict_flexible_layout_strides` on for all inductor
tests (unless `TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES` is set
explicitly), and CI exports the env var so tests that compile through other
`TestCase` classes are checked too. Production stays off.

New violations now fail at compile time in CI, at the line that read the
provisional stride, instead of becoming silent wrong results. For example,
the conv backward lowering added weeks before the check was first run
(fixed earlier in this stack) would have been caught in its own PR.

Validated: the full CI matrix (default, inductor, dynamo_wrapped,
benchmarks, ROCm, MPS, aarch64) was green with the check on everywhere at
#193860 e77db71; the only failure, torchtitan, was failing on main.

Test Plan:

Run on B200 against main a67a74d, with strict mode on for these files:

```
python test/inductor/test_layout_freezing.py   # 34 passed
python test/inductor/test_torchinductor.py     # 2790 passed, 3 failed (also fail on main)
```

plus full CI on this PR.

Authored with Claude Code.

ghstack-source-id: c742cd3
Pull-Request: #200996
eellison added a commit that referenced this pull request Nov 3, 2026
## AI-generated description (draft, not yet reviewed by the author)

Last PR of the FlexibleLayout freeze-discipline stack. With every area
fixed, the per-file opt-in list in `torch/_inductor/test_case.py` is
replaced by turning `strict_flexible_layout_strides` on for all inductor
tests (unless `TORCHINDUCTOR_STRICT_FLEXIBLE_LAYOUT_STRIDES` is set
explicitly), and CI exports the env var so tests that compile through other
`TestCase` classes are checked too. Production stays off.

New violations now fail at compile time in CI, at the line that read the
provisional stride, instead of becoming silent wrong results. For example,
the conv backward lowering added weeks before the check was first run
(fixed earlier in this stack) would have been caught in its own PR.

Validated: the full CI matrix (default, inductor, dynamo_wrapped,
benchmarks, ROCm, MPS, aarch64) was green with the check on everywhere at
#193860 e77db71; the only failure, torchtitan, was failing on main.

Test Plan:

Run on B200 against main a67a74d, with strict mode on for these files:

```
python test/inductor/test_layout_freezing.py   # 34 passed
python test/inductor/test_torchinductor.py     # 2790 passed, 3 failed (also fail on main)
```

plus full CI on this PR.

Authored with Claude Code.

ghstack-source-id: 2464ec1
Pull-Request: #200996
pytorchmergebot pushed a commit that referenced this pull request Nov 3, 2026
…rs (#200461)

Author's note: Behind an off-by-default flag, a stacked computed buffer is copied by a kernel fused into its producer instead of being re-read by a pointwise cat, which saves a kernel per stack in the MXFP6 preparation graphs. It's off by default because a broad benchmark sweep found regressions when the destination is transposed; the real fix (size-1 views not freezing their base) will replace the flag.

The description below was drafted with an AI assistant (Claude):

> `torch.stack(ts, -1)` decomposes to `cat([t.unsqueeze(-1) ...], -1)`. When a
> stacked input is already realized, its unsqueeze builds a `ReinterpretView`,
> which freezes the buffer's layout, so `ConcatKernel` cannot place it in the
> output and it has to be copied. `cat` then treats that input as needing a copy
> kernel anyway; if every input does, it lowers the whole cat as one
> `pointwise_cat` kernel that re-reads the realized buffer. That kernel iterates
> over the stacked output, so it cannot fuse with the input's producer, and the
> producer's buffer is written and read back.
>
> A per-input copy through `ConcatKernel` has the same shape as the input, so the
> scheduler can fuse it into the producer, which then stores straight into the
> output slice; the intermediate buffer is removed when nothing else reads it.
> So in `should_lower_cat_input`, do not count an input as needing a copy when
> it is all of a buffer Inductor computes (and not a no-op such as
> `torch.empty`, which has nothing to fuse into).
>
> This is behind `config.cat_fuse_computed_input_copies`, off by default.
> Whether fusing the copy is profitable depends on the destination layout
> relative to the producer's iteration order, which the lowering does not know:
> on a broad benchmark sweep it removed bytes and kernels in most changed
> graphs, but a padded *transposed* output made the fused stores uncoalesced
> (1.6-1.9x slower on two cross-entropy gradients). Workloads where it is a win
> (MXFP6 preparation: one kernel instead of two) opt in. The flag is
> temporary: a size-1 view (the stack's unsqueeze) should not freeze its base,
> since it is valid under any base layout; with that, cat places the buffer in
> its output with no copy for everyone, and this flag can be removed.
>
> Alternatives considered: not freezing on size-1 views (a lazy unsqueeze view
> that `ConcatKernel` sees through) is the real fix, but lazy views currently
> claim their base's layout while having no strides, which some lowerings trip
> over; that needs fixing first (and #193860's freeze discipline). A layout
> derived from another layout would be the general form; that is a larger IR
> change.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_torchinductor.py -k "cat or stack"
> python -m pytest test/inductor/test_inline_asm_concat.py
> ```
> With the flag on, `test_stack_realized_inputs` generates 1 kernel on GPU instead of 2;
> `test_stack_realized_input_twice` copies one realized buffer into two
> slices. `test_inline_asm_concat.py` stacks the outputs of multi-output
> `inline_asm_elementwise` calls; without this change, the six-output
> `test_stack_outputs` case and the `use_asm` cases of
> `test_normal_choices_stack_reshape` get a separate stack kernel.
> `test_unrelated_asm_outputs` and `TestPointwisePackingChoices` cover stacks that
> already compile to one kernel. On the MXFP6 preparation benchmark graphs, the
> generated Triton kernels match those of the lazy-view approach (same kernel
> count, loads and stores).
>
> This change was prepared with an AI assistant.

Pull Request resolved: #200461
Approved by: https://github.com/drisspg
ghstack dependencies: #200459, #200460
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…rs (pytorch#200461)

Author's note: Behind an off-by-default flag, a stacked computed buffer is copied by a kernel fused into its producer instead of being re-read by a pointwise cat, which saves a kernel per stack in the MXFP6 preparation graphs. It's off by default because a broad benchmark sweep found regressions when the destination is transposed; the real fix (size-1 views not freezing their base) will replace the flag.

The description below was drafted with an AI assistant (Claude):

> `torch.stack(ts, -1)` decomposes to `cat([t.unsqueeze(-1) ...], -1)`. When a
> stacked input is already realized, its unsqueeze builds a `ReinterpretView`,
> which freezes the buffer's layout, so `ConcatKernel` cannot place it in the
> output and it has to be copied. `cat` then treats that input as needing a copy
> kernel anyway; if every input does, it lowers the whole cat as one
> `pointwise_cat` kernel that re-reads the realized buffer. That kernel iterates
> over the stacked output, so it cannot fuse with the input's producer, and the
> producer's buffer is written and read back.
>
> A per-input copy through `ConcatKernel` has the same shape as the input, so the
> scheduler can fuse it into the producer, which then stores straight into the
> output slice; the intermediate buffer is removed when nothing else reads it.
> So in `should_lower_cat_input`, do not count an input as needing a copy when
> it is all of a buffer Inductor computes (and not a no-op such as
> `torch.empty`, which has nothing to fuse into).
>
> This is behind `config.cat_fuse_computed_input_copies`, off by default.
> Whether fusing the copy is profitable depends on the destination layout
> relative to the producer's iteration order, which the lowering does not know:
> on a broad benchmark sweep it removed bytes and kernels in most changed
> graphs, but a padded *transposed* output made the fused stores uncoalesced
> (1.6-1.9x slower on two cross-entropy gradients). Workloads where it is a win
> (MXFP6 preparation: one kernel instead of two) opt in. The flag is
> temporary: a size-1 view (the stack's unsqueeze) should not freeze its base,
> since it is valid under any base layout; with that, cat places the buffer in
> its output with no copy for everyone, and this flag can be removed.
>
> Alternatives considered: not freezing on size-1 views (a lazy unsqueeze view
> that `ConcatKernel` sees through) is the real fix, but lazy views currently
> claim their base's layout while having no strides, which some lowerings trip
> over; that needs fixing first (and pytorch#193860's freeze discipline). A layout
> derived from another layout would be the general form; that is a larger IR
> change.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_torchinductor.py -k "cat or stack"
> python -m pytest test/inductor/test_inline_asm_concat.py
> ```
> With the flag on, `test_stack_realized_inputs` generates 1 kernel on GPU instead of 2;
> `test_stack_realized_input_twice` copies one realized buffer into two
> slices. `test_inline_asm_concat.py` stacks the outputs of multi-output
> `inline_asm_elementwise` calls; without this change, the six-output
> `test_stack_outputs` case and the `use_asm` cases of
> `test_normal_choices_stack_reshape` get a separate stack kernel.
> `test_unrelated_asm_outputs` and `TestPointwisePackingChoices` cover stacks that
> already compile to one kernel. On the MXFP6 preparation benchmark graphs, the
> generated Triton kernels match those of the lazy-view approach (same kernel
> count, loads and stores).
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200461
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…rs (pytorch#200461)

Author's note: Behind an off-by-default flag, a stacked computed buffer is copied by a kernel fused into its producer instead of being re-read by a pointwise cat, which saves a kernel per stack in the MXFP6 preparation graphs. It's off by default because a broad benchmark sweep found regressions when the destination is transposed; the real fix (size-1 views not freezing their base) will replace the flag.

The description below was drafted with an AI assistant (Claude):

> `torch.stack(ts, -1)` decomposes to `cat([t.unsqueeze(-1) ...], -1)`. When a
> stacked input is already realized, its unsqueeze builds a `ReinterpretView`,
> which freezes the buffer's layout, so `ConcatKernel` cannot place it in the
> output and it has to be copied. `cat` then treats that input as needing a copy
> kernel anyway; if every input does, it lowers the whole cat as one
> `pointwise_cat` kernel that re-reads the realized buffer. That kernel iterates
> over the stacked output, so it cannot fuse with the input's producer, and the
> producer's buffer is written and read back.
>
> A per-input copy through `ConcatKernel` has the same shape as the input, so the
> scheduler can fuse it into the producer, which then stores straight into the
> output slice; the intermediate buffer is removed when nothing else reads it.
> So in `should_lower_cat_input`, do not count an input as needing a copy when
> it is all of a buffer Inductor computes (and not a no-op such as
> `torch.empty`, which has nothing to fuse into).
>
> This is behind `config.cat_fuse_computed_input_copies`, off by default.
> Whether fusing the copy is profitable depends on the destination layout
> relative to the producer's iteration order, which the lowering does not know:
> on a broad benchmark sweep it removed bytes and kernels in most changed
> graphs, but a padded *transposed* output made the fused stores uncoalesced
> (1.6-1.9x slower on two cross-entropy gradients). Workloads where it is a win
> (MXFP6 preparation: one kernel instead of two) opt in. The flag is
> temporary: a size-1 view (the stack's unsqueeze) should not freeze its base,
> since it is valid under any base layout; with that, cat places the buffer in
> its output with no copy for everyone, and this flag can be removed.
>
> Alternatives considered: not freezing on size-1 views (a lazy unsqueeze view
> that `ConcatKernel` sees through) is the real fix, but lazy views currently
> claim their base's layout while having no strides, which some lowerings trip
> over; that needs fixing first (and pytorch#193860's freeze discipline). A layout
> derived from another layout would be the general form; that is a larger IR
> change.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_torchinductor.py -k "cat or stack"
> python -m pytest test/inductor/test_inline_asm_concat.py
> ```
> With the flag on, `test_stack_realized_inputs` generates 1 kernel on GPU instead of 2;
> `test_stack_realized_input_twice` copies one realized buffer into two
> slices. `test_inline_asm_concat.py` stacks the outputs of multi-output
> `inline_asm_elementwise` calls; without this change, the six-output
> `test_stack_outputs` case and the `use_asm` cases of
> `test_normal_choices_stack_reshape` get a separate stack kernel.
> `test_unrelated_asm_outputs` and `TestPointwisePackingChoices` cover stacks that
> already compile to one kernel. On the MXFP6 preparation benchmark graphs, the
> generated Triton kernels match those of the lazy-view approach (same kernel
> count, loads and stores).
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200461
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…rs (pytorch#200461)

Author's note: Behind an off-by-default flag, a stacked computed buffer is copied by a kernel fused into its producer instead of being re-read by a pointwise cat, which saves a kernel per stack in the MXFP6 preparation graphs. It's off by default because a broad benchmark sweep found regressions when the destination is transposed; the real fix (size-1 views not freezing their base) will replace the flag.

The description below was drafted with an AI assistant (Claude):

> `torch.stack(ts, -1)` decomposes to `cat([t.unsqueeze(-1) ...], -1)`. When a
> stacked input is already realized, its unsqueeze builds a `ReinterpretView`,
> which freezes the buffer's layout, so `ConcatKernel` cannot place it in the
> output and it has to be copied. `cat` then treats that input as needing a copy
> kernel anyway; if every input does, it lowers the whole cat as one
> `pointwise_cat` kernel that re-reads the realized buffer. That kernel iterates
> over the stacked output, so it cannot fuse with the input's producer, and the
> producer's buffer is written and read back.
>
> A per-input copy through `ConcatKernel` has the same shape as the input, so the
> scheduler can fuse it into the producer, which then stores straight into the
> output slice; the intermediate buffer is removed when nothing else reads it.
> So in `should_lower_cat_input`, do not count an input as needing a copy when
> it is all of a buffer Inductor computes (and not a no-op such as
> `torch.empty`, which has nothing to fuse into).
>
> This is behind `config.cat_fuse_computed_input_copies`, off by default.
> Whether fusing the copy is profitable depends on the destination layout
> relative to the producer's iteration order, which the lowering does not know:
> on a broad benchmark sweep it removed bytes and kernels in most changed
> graphs, but a padded *transposed* output made the fused stores uncoalesced
> (1.6-1.9x slower on two cross-entropy gradients). Workloads where it is a win
> (MXFP6 preparation: one kernel instead of two) opt in. The flag is
> temporary: a size-1 view (the stack's unsqueeze) should not freeze its base,
> since it is valid under any base layout; with that, cat places the buffer in
> its output with no copy for everyone, and this flag can be removed.
>
> Alternatives considered: not freezing on size-1 views (a lazy unsqueeze view
> that `ConcatKernel` sees through) is the real fix, but lazy views currently
> claim their base's layout while having no strides, which some lowerings trip
> over; that needs fixing first (and pytorch#193860's freeze discipline). A layout
> derived from another layout would be the general form; that is a larger IR
> change.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_torchinductor.py -k "cat or stack"
> python -m pytest test/inductor/test_inline_asm_concat.py
> ```
> With the flag on, `test_stack_realized_inputs` generates 1 kernel on GPU instead of 2;
> `test_stack_realized_input_twice` copies one realized buffer into two
> slices. `test_inline_asm_concat.py` stacks the outputs of multi-output
> `inline_asm_elementwise` calls; without this change, the six-output
> `test_stack_outputs` case and the `use_asm` cases of
> `test_normal_choices_stack_reshape` get a separate stack kernel.
> `test_unrelated_asm_outputs` and `TestPointwisePackingChoices` cover stacks that
> already compile to one kernel. On the MXFP6 preparation benchmark graphs, the
> generated Triton kernels match those of the lazy-view approach (same kernel
> count, loads and stores).
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200461
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…rs (pytorch#200461)

Author's note: Behind an off-by-default flag, a stacked computed buffer is copied by a kernel fused into its producer instead of being re-read by a pointwise cat, which saves a kernel per stack in the MXFP6 preparation graphs. It's off by default because a broad benchmark sweep found regressions when the destination is transposed; the real fix (size-1 views not freezing their base) will replace the flag.

The description below was drafted with an AI assistant (Claude):

> `torch.stack(ts, -1)` decomposes to `cat([t.unsqueeze(-1) ...], -1)`. When a
> stacked input is already realized, its unsqueeze builds a `ReinterpretView`,
> which freezes the buffer's layout, so `ConcatKernel` cannot place it in the
> output and it has to be copied. `cat` then treats that input as needing a copy
> kernel anyway; if every input does, it lowers the whole cat as one
> `pointwise_cat` kernel that re-reads the realized buffer. That kernel iterates
> over the stacked output, so it cannot fuse with the input's producer, and the
> producer's buffer is written and read back.
>
> A per-input copy through `ConcatKernel` has the same shape as the input, so the
> scheduler can fuse it into the producer, which then stores straight into the
> output slice; the intermediate buffer is removed when nothing else reads it.
> So in `should_lower_cat_input`, do not count an input as needing a copy when
> it is all of a buffer Inductor computes (and not a no-op such as
> `torch.empty`, which has nothing to fuse into).
>
> This is behind `config.cat_fuse_computed_input_copies`, off by default.
> Whether fusing the copy is profitable depends on the destination layout
> relative to the producer's iteration order, which the lowering does not know:
> on a broad benchmark sweep it removed bytes and kernels in most changed
> graphs, but a padded *transposed* output made the fused stores uncoalesced
> (1.6-1.9x slower on two cross-entropy gradients). Workloads where it is a win
> (MXFP6 preparation: one kernel instead of two) opt in. The flag is
> temporary: a size-1 view (the stack's unsqueeze) should not freeze its base,
> since it is valid under any base layout; with that, cat places the buffer in
> its output with no copy for everyone, and this flag can be removed.
>
> Alternatives considered: not freezing on size-1 views (a lazy unsqueeze view
> that `ConcatKernel` sees through) is the real fix, but lazy views currently
> claim their base's layout while having no strides, which some lowerings trip
> over; that needs fixing first (and pytorch#193860's freeze discipline). A layout
> derived from another layout would be the general form; that is a larger IR
> change.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_torchinductor.py -k "cat or stack"
> python -m pytest test/inductor/test_inline_asm_concat.py
> ```
> With the flag on, `test_stack_realized_inputs` generates 1 kernel on GPU instead of 2;
> `test_stack_realized_input_twice` copies one realized buffer into two
> slices. `test_inline_asm_concat.py` stacks the outputs of multi-output
> `inline_asm_elementwise` calls; without this change, the six-output
> `test_stack_outputs` case and the `use_asm` cases of
> `test_normal_choices_stack_reshape` get a separate stack kernel.
> `test_unrelated_asm_outputs` and `TestPointwisePackingChoices` cover stacks that
> already compile to one kernel. On the MXFP6 preparation benchmark graphs, the
> generated Triton kernels match those of the lazy-view approach (same kernel
> count, loads and stores).
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200461
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@eellison
eellison requested a review from jansel December 2, 2026 10:02

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants