Repository navigation
Conversation
🔗 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 FailuresAs of commit b01b378 with merge base 4a03eed ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Contributor
Author
|
@pytorchbot label "release notes: inductor" |
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
Contributor
Author
|
@pytorchbot label "ciflow/rocm" |
Contributor
Author
|
@pytorchbot label "ciflow/mps" |
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
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
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
This was referenced Oct 14, 2026
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
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
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
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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()) + 1on 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, andconfig.strict_flexible_layout_strides(default off), which raises onFlexibleLayout.strideand on aReinterpretViewover a flexible base. Alsoallow_layout_analysis(),freeze_storage_layout(), hint migrations forgeneric reads (layout predicates, repr,
require_stride1, ...), and aper-file opt-in list in
torch/_inductor/test_case.py. No behavior changewith 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:
Authored with Claude Code.