Skip to content

[inductor] Fix "Input tensor must have contiguous last dimension" crash in SDPA (#202297) - #202297

Closed
echen4096 wants to merge 1 commit into
pytorch:mainfrom
echen4096:export-D127902772
Closed

echen4096 wants to merge 1 commit into
pytorch:mainfrom
echen4096:export-D127902772

Conversation

@echen4096

@echen4096 echen4096 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Problem

Training jobs that use torch.compile with flash attention can crash with:

RuntimeError: Input tensor must have contiguous last dimension

The flash attention kernel requires the values along the last dimension of query/key/value (the head dimension) to be stored next to each other in memory (stride(-1) == 1). Before calling the kernel, Inductor is supposed to make sure its inputs meet this requirement (in sdpa_constraint). In some graphs it does not: it passes a key/value tensor whose last dimension has stride(-1) == 200, and the kernel rejects it.

This is what crashes APS IG CTR training on MI350X (T290541015, T290943677). The CUDA flash kernel has the same check, so the bug is not specific to AMD.

Why it happens

  1. sdpa_constraint first asks is_aligned_realized_tensor whether the input is already stored the way SDPA needs. If the answer is yes, the input is used as-is.
  2. Inductor can create a buffer before it has decided the buffer's memory layout (a FlexibleLayout). Until then, the buffer reports placeholder strides that look correct. is_aligned_realized_tensor reads those placeholders and answers yes, so the layout is never set to what SDPA needs.
  3. Right after, when the SDPA call is created, Inductor decides the layout (decide_layout() in ExternKernel.process_kernel). It picks the memory order that best matches how the buffer's inputs are stored. If those inputs have the sequence dimension innermost, so does the buffer, and SDPA receives a tensor whose last dimension is not contiguous.

In the IG CTR model, key and value are the same tensor. In the backward pass it is recomputed and used by two SDPA calls (the recomputed forward and the backward). Because it has two users, Inductor creates its buffer early, before deciding its layout, which is exactly the case above. The tensor is computed from a convolution output: MIOpen (AMD) stores that output with the sequence dimension innermost, while cuDNN (NVIDIA) does not. This is why the same job passes on GB200.

Fix

is_aligned_realized_tensor now answers "no" when the buffer's layout has not been decided yet. sdpa_constraint then takes its existing path that sets the layout to the one SDPA needs. Nothing is copied; the buffer is written in the right order from the start.

sdpa_constraint is the only caller of is_aligned_realized_tensor, so no other code is affected.

Alternative not taken

D125780486 makes the ROCm attention kernel copy any input whose last dimension is not contiguous. That does not fix every case: when the SDPA backward receives the bad tensor, its gradients come back in a different memory layout than Inductor expects, and Inductor's stride check fails instead. It also leaves this bug in place for other GPUs.

This change was written with an AI assistant (Claude Code).

Test Plan:
New test test_sdpa_constraint_flexible_kv_layout_gpu (in test/inductor/test_fused_attention.py) recreates the failing pattern in a few lines: key and value are the same tensor, built from transposed inputs, and used by two SDPA calls. It compiles the function with run_and_get_code and checks two things:

  1. The result matches eager.
  2. The generated code allocates key/value once, with stride(-1) == 1, and both SDPA calls use that buffer (no copies).

Check 2 is what this diff fixes: the memory layout Inductor picks for key/value. Inductor picks it while compiling, before any kernel runs, with the same code for every GPU type. So the test fails without the fix even on a GPU whose attention kernel would accept the wrong layout.

Without the fix, Inductor allocates key/value with strides (2048, 8192, 1, 32) (last dimension not contiguous) and adds two contiguous copies for the second SDPA call, so check 2 gets:

expected: ['2048, 2048, 64, 1']
actual:   ['2048, 8192, 1, 32', '2048, 2048, 64, 1', '2048, 2048, 64, 1']

Results on MI350X:

Test Without this fix With this fix
test_sdpa_constraint_flexible_kv_layout_gpu (new) Fails: Input tensor must have contiguous last dimension Passes
test_cache_sdpa_constraint_shared_kv (GPU and CPU) Passes Passes
test_insignificant_strides Fails (see note) Fails (see note)

On MI350X, the run without the fix fails at the kernel's own stride check (the crash this diff fixes) before it reaches check 2.

Note: test_insignificant_strides fails on ROCm with or without this change. It sends fp32 inputs to the CK attention kernel, which only supports fp16 and bf16, so it is unrelated to this fix.

Commands. buck2 test does not find the GPU tests on this devserver, so the test binary is run directly:

buck2 build fbcode//mode/opt-amd-gpu -c fbcode.rocm_arch=mi350 //caffe2/test/inductor:fused_attention --show-full-output
HIP_VISIBLE_DEVICES=7 <fused_attention.par from the build output> -v -k "test_sdpa_constraint_flexible_kv_layout or test_insignificant_strides or test_cache_sdpa_constraint_shared_kv"

A larger local repro of the model's pattern (not part of this diff) also crashes without the fix and passes with it, including a training step where the backward pass recomputes key/value. The gradients match eager.

Reviewed By: joebos, haoyuz

Differential Revision: D127902772

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

@pytorch-bot

pytorch-bot Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR makes `is_aligned_realized_tensor` return False for buffers that still
have a FlexibleLayout, so `sdpa_constraint` freezes them in the stride order
SDPA needs through `require_stride_order`, without adding a copy, and
`decide_layout()` can no longer pick a layout where `stride(-1) != 1` later. The
review found no issues. Recommendation: Approve, since the fix is small and
targeted and its regression test fails without it.

Reviewed commit: be75840 (NOT the current head 2a8de6a)

Review run

🔗 Helpful Links

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

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

✅ No Failures

As of commit 2a8de6a with merge base 09e2d08 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@meta-codesync

meta-codesync Bot commented Oct 27, 2026

Copy link
Copy Markdown

@echen4096 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D127902772.

@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 27, 2026
github-actions[bot]

This comment was marked as outdated.

@meta-codesync meta-codesync Bot changed the title [inductor] Fix "Input tensor must have contiguous last dimension" crash in SDPA [inductor] Fix "Input tensor must have contiguous last dimension" crash in SDPA (#202297) Oct 29, 2026
echen4096 added a commit to echen4096/pytorch that referenced this pull request Oct 29, 2026
…sh in SDPA (pytorch#202297)

Summary:

**Problem**

Training jobs that use `torch.compile` with flash attention can crash with:

```
RuntimeError: Input tensor must have contiguous last dimension
```

The flash attention kernel requires the values along the last dimension of query/key/value (the head dimension) to be stored next to each other in memory (`stride(-1) == 1`). Before calling the kernel, Inductor is supposed to make sure its inputs meet this requirement (in `sdpa_constraint`). In some graphs it does not: it passes a key/value tensor whose last dimension has `stride(-1) == 200`, and the kernel rejects it.

This is what crashes APS IG CTR training on MI350X (T290541015, T290943677). The CUDA flash kernel has the same check, so the bug is not specific to AMD.

**Why it happens**

1. `sdpa_constraint` first asks `is_aligned_realized_tensor` whether the input is already stored the way SDPA needs. If the answer is yes, the input is used as-is.
2. Inductor can create a buffer before it has decided the buffer's memory layout (a `FlexibleLayout`). Until then, the buffer reports placeholder strides that look correct. `is_aligned_realized_tensor` reads those placeholders and answers yes, so the layout is never set to what SDPA needs.
3. Right after, when the SDPA call is created, Inductor decides the layout (`decide_layout()` in `ExternKernel.process_kernel`). It picks the memory order that best matches how the buffer's inputs are stored. If those inputs have the sequence dimension innermost, so does the buffer, and SDPA receives a tensor whose last dimension is not contiguous.

In the IG CTR model, key and value are the same tensor. In the backward pass it is recomputed and used by two SDPA calls (the recomputed forward and the backward). Because it has two users, Inductor creates its buffer early, before deciding its layout, which is exactly the case above. The tensor is computed from a convolution output: MIOpen (AMD) stores that output with the sequence dimension innermost, while cuDNN (NVIDIA) does not. This is why the same job passes on GB200.

**Fix**

`is_aligned_realized_tensor` now answers "no" when the buffer's layout has not been decided yet. `sdpa_constraint` then takes its existing path that sets the layout to the one SDPA needs. Nothing is copied; the buffer is written in the right order from the start.

`sdpa_constraint` is the only caller of `is_aligned_realized_tensor`, so no other code is affected.

**Alternative not taken**

D125780486 makes the ROCm attention kernel copy any input whose last dimension is not contiguous. That does not fix every case: when the SDPA backward receives the bad tensor, its gradients come back in a different memory layout than Inductor expects, and Inductor's stride check fails instead. It also leaves this bug in place for other GPUs.

This change was written with an AI assistant (Claude Code).

Test Plan:
New test `test_sdpa_constraint_flexible_kv_layout_gpu` (in `test/inductor/test_fused_attention.py`) recreates the failing pattern in a few lines: key and value are the same tensor, built from transposed inputs, and used by two SDPA calls. It compiles the function with `run_and_get_code` and checks two things:

1. The result matches eager.
2. The generated code allocates key/value once, with `stride(-1) == 1`, and both SDPA calls use that buffer (no copies).

Check 2 is what this diff fixes: the memory layout Inductor picks for key/value. Inductor picks it while compiling, before any kernel runs, with the same code for every GPU type. So the test fails without the fix even on a GPU whose attention kernel would accept the wrong layout.

Without the fix, Inductor allocates key/value with strides `(2048, 8192, 1, 32)` (last dimension not contiguous) and adds two contiguous copies for the second SDPA call, so check 2 gets:

```
expected: ['2048, 2048, 64, 1']
actual:   ['2048, 8192, 1, 32', '2048, 2048, 64, 1', '2048, 2048, 64, 1']
```

Results on MI350X:

| Test | Without this fix | With this fix |
| --- | --- | --- |
| `test_sdpa_constraint_flexible_kv_layout_gpu` (new) | Fails: `Input tensor must have contiguous last dimension` | Passes |
| `test_cache_sdpa_constraint_shared_kv` (GPU and CPU) | Passes | Passes |
| `test_insignificant_strides` | Fails (see note) | Fails (see note) |

On MI350X, the run without the fix fails at the kernel's own stride check (the crash this diff fixes) before it reaches check 2.

Note: `test_insignificant_strides` fails on ROCm with or without this change. It sends fp32 inputs to the CK attention kernel, which only supports fp16 and bf16, so it is unrelated to this fix.

Commands. `buck2 test` does not find the GPU tests on this devserver, so the test binary is run directly:

```
buck2 build fbcode//mode/opt-amd-gpu -c fbcode.rocm_arch=mi350 //caffe2/test/inductor:fused_attention --show-full-output
HIP_VISIBLE_DEVICES=7 <fused_attention.par from the build output> -v -k "test_sdpa_constraint_flexible_kv_layout or test_insignificant_strides or test_cache_sdpa_constraint_shared_kv"
```

A larger local repro of the model's pattern (not part of this diff) also crashes without the fix and passes with it, including a training step where the backward pass recomputes key/value. The gradients match eager.

Reviewed By: joebos, haoyuz

Differential Revision: D127902772
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed their stale review October 29, 2026 01:48

Withdrawn: the automated review of 465a64e found nothing blocking.

echen4096 added a commit to echen4096/pytorch that referenced this pull request Oct 29, 2026
…sh in SDPA (pytorch#202297)

Summary:

**Problem**

Training jobs that use `torch.compile` with flash attention can crash with:

```
RuntimeError: Input tensor must have contiguous last dimension
```

The flash attention kernel requires the values along the last dimension of query/key/value (the head dimension) to be stored next to each other in memory (`stride(-1) == 1`). Before calling the kernel, Inductor is supposed to make sure its inputs meet this requirement (in `sdpa_constraint`). In some graphs it does not: it passes a key/value tensor whose last dimension has `stride(-1) == 200`, and the kernel rejects it.

This is what crashes APS IG CTR training on MI350X (T290541015, T290943677). The CUDA flash kernel has the same check, so the bug is not specific to AMD.

**Why it happens**

1. `sdpa_constraint` first asks `is_aligned_realized_tensor` whether the input is already stored the way SDPA needs. If the answer is yes, the input is used as-is.
2. Inductor can create a buffer before it has decided the buffer's memory layout (a `FlexibleLayout`). Until then, the buffer reports placeholder strides that look correct. `is_aligned_realized_tensor` reads those placeholders and answers yes, so the layout is never set to what SDPA needs.
3. Right after, when the SDPA call is created, Inductor decides the layout (`decide_layout()` in `ExternKernel.process_kernel`). It picks the memory order that best matches how the buffer's inputs are stored. If those inputs have the sequence dimension innermost, so does the buffer, and SDPA receives a tensor whose last dimension is not contiguous.

In the IG CTR model, key and value are the same tensor. In the backward pass it is recomputed and used by two SDPA calls (the recomputed forward and the backward). Because it has two users, Inductor creates its buffer early, before deciding its layout, which is exactly the case above. The tensor is computed from a convolution output: MIOpen (AMD) stores that output with the sequence dimension innermost, while cuDNN (NVIDIA) does not. This is why the same job passes on GB200.

**Fix**

`is_aligned_realized_tensor` now answers "no" when the buffer's layout has not been decided yet. `sdpa_constraint` then takes its existing path that sets the layout to the one SDPA needs. Nothing is copied; the buffer is written in the right order from the start.

`sdpa_constraint` is the only caller of `is_aligned_realized_tensor`, so no other code is affected.

**Alternative not taken**

D125780486 makes the ROCm attention kernel copy any input whose last dimension is not contiguous. That does not fix every case: when the SDPA backward receives the bad tensor, its gradients come back in a different memory layout than Inductor expects, and Inductor's stride check fails instead. It also leaves this bug in place for other GPUs.

This change was written with an AI assistant (Claude Code).

Test Plan:
New test `test_sdpa_constraint_flexible_kv_layout_gpu` (in `test/inductor/test_fused_attention.py`) recreates the failing pattern in a few lines: key and value are the same tensor, built from transposed inputs, and used by two SDPA calls. It compiles the function with `run_and_get_code` and checks two things:

1. The result matches eager.
2. The generated code allocates key/value once, with `stride(-1) == 1`, and both SDPA calls use that buffer (no copies).

Check 2 is what this diff fixes: the memory layout Inductor picks for key/value. Inductor picks it while compiling, before any kernel runs, with the same code for every GPU type. So the test fails without the fix even on a GPU whose attention kernel would accept the wrong layout.

Without the fix, Inductor allocates key/value with strides `(2048, 8192, 1, 32)` (last dimension not contiguous) and adds two contiguous copies for the second SDPA call, so check 2 gets:

```
expected: ['2048, 2048, 64, 1']
actual:   ['2048, 8192, 1, 32', '2048, 2048, 64, 1', '2048, 2048, 64, 1']
```

Results on MI350X:

| Test | Without this fix | With this fix |
| --- | --- | --- |
| `test_sdpa_constraint_flexible_kv_layout_gpu` (new) | Fails: `Input tensor must have contiguous last dimension` | Passes |
| `test_cache_sdpa_constraint_shared_kv` (GPU and CPU) | Passes | Passes |
| `test_insignificant_strides` | Fails (see note) | Fails (see note) |

On MI350X, the run without the fix fails at the kernel's own stride check (the crash this diff fixes) before it reaches check 2.

Note: `test_insignificant_strides` fails on ROCm with or without this change. It sends fp32 inputs to the CK attention kernel, which only supports fp16 and bf16, so it is unrelated to this fix.

Commands. `buck2 test` does not find the GPU tests on this devserver, so the test binary is run directly:

```
buck2 build fbcode//mode/opt-amd-gpu -c fbcode.rocm_arch=mi350 //caffe2/test/inductor:fused_attention --show-full-output
HIP_VISIBLE_DEVICES=7 <fused_attention.par from the build output> -v -k "test_sdpa_constraint_flexible_kv_layout or test_insignificant_strides or test_cache_sdpa_constraint_shared_kv"
```

A larger local repro of the model's pattern (not part of this diff) also crashes without the fix and passes with it, including a training step where the backward pass recomputes key/value. The gradients match eager.

Reviewed By: joebos, haoyuz

Differential Revision: D127902772

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review of be75840: nothing blocking; ready for human review.

The PR makes is_aligned_realized_tensor return False for buffers that still have a FlexibleLayout, so sdpa_constraint freezes them in the stride order SDPA needs through require_stride_order, without adding a copy, and decide_layout() can no longer pick a layout where stride(-1) != 1 later. The review found no issues. Recommendation: Approve, since the fix is small and targeted and its regression test fails without it.

This review is AI-generated and advisory. Each new automated review replaces the previous one.

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 29, 2026
@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Oct 29, 2026
@weikhor

weikhor commented Nov 1, 2026

Copy link
Copy Markdown

Testing it on RTX 5080 (SM120)

  1. Without this PR: Test failed - Crashes on
    a) FLASH (Input tensor must have contiguous last dimension)
    b) EFFICIENT (key: last dimension must be contiguous)
    c) default backend.

  2. With this PR: All pass

echen4096 added a commit to echen4096/pytorch that referenced this pull request Nov 2, 2026
…sh in SDPA (pytorch#202297)

Summary:

**Problem**

Training jobs that use `torch.compile` with flash attention can crash with:

```
RuntimeError: Input tensor must have contiguous last dimension
```

The flash attention kernel requires the values along the last dimension of query/key/value (the head dimension) to be stored next to each other in memory (`stride(-1) == 1`). Before calling the kernel, Inductor is supposed to make sure its inputs meet this requirement (in `sdpa_constraint`). In some graphs it does not: it passes a key/value tensor whose last dimension has `stride(-1) == 200`, and the kernel rejects it.

This is what crashes APS IG CTR training on MI350X (T290541015, T290943677). The CUDA flash kernel has the same check, so the bug is not specific to AMD.

**Why it happens**

1. `sdpa_constraint` first asks `is_aligned_realized_tensor` whether the input is already stored the way SDPA needs. If the answer is yes, the input is used as-is.
2. Inductor can create a buffer before it has decided the buffer's memory layout (a `FlexibleLayout`). Until then, the buffer reports placeholder strides that look correct. `is_aligned_realized_tensor` reads those placeholders and answers yes, so the layout is never set to what SDPA needs.
3. Right after, when the SDPA call is created, Inductor decides the layout (`decide_layout()` in `ExternKernel.process_kernel`). It picks the memory order that best matches how the buffer's inputs are stored. If those inputs have the sequence dimension innermost, so does the buffer, and SDPA receives a tensor whose last dimension is not contiguous.

In the IG CTR model, key and value are the same tensor. In the backward pass it is recomputed and used by two SDPA calls (the recomputed forward and the backward). Because it has two users, Inductor creates its buffer early, before deciding its layout, which is exactly the case above. The tensor is computed from a convolution output: MIOpen (AMD) stores that output with the sequence dimension innermost, while cuDNN (NVIDIA) does not. This is why the same job passes on GB200.

**Fix**

`is_aligned_realized_tensor` now answers "no" when the buffer's layout has not been decided yet. `sdpa_constraint` then takes its existing path that sets the layout to the one SDPA needs. Nothing is copied; the buffer is written in the right order from the start.

`sdpa_constraint` is the only caller of `is_aligned_realized_tensor`, so no other code is affected.

**Alternative not taken**

D125780486 makes the ROCm attention kernel copy any input whose last dimension is not contiguous. That does not fix every case: when the SDPA backward receives the bad tensor, its gradients come back in a different memory layout than Inductor expects, and Inductor's stride check fails instead. It also leaves this bug in place for other GPUs.

This change was written with an AI assistant (Claude Code).

Test Plan:
New test `test_sdpa_constraint_flexible_kv_layout_gpu` (in `test/inductor/test_fused_attention.py`) recreates the failing pattern in a few lines: key and value are the same tensor, built from transposed inputs, and used by two SDPA calls. It compiles the function with `run_and_get_code` and checks two things:

1. The result matches eager.
2. The generated code allocates key/value once, with `stride(-1) == 1`, and both SDPA calls use that buffer (no copies).

Check 2 is what this diff fixes: the memory layout Inductor picks for key/value. Inductor picks it while compiling, before any kernel runs, with the same code for every GPU type. So the test fails without the fix even on a GPU whose attention kernel would accept the wrong layout.

Without the fix, Inductor allocates key/value with strides `(2048, 8192, 1, 32)` (last dimension not contiguous) and adds two contiguous copies for the second SDPA call, so check 2 gets:

```
expected: ['2048, 2048, 64, 1']
actual:   ['2048, 8192, 1, 32', '2048, 2048, 64, 1', '2048, 2048, 64, 1']
```

Results on MI350X:

| Test | Without this fix | With this fix |
| --- | --- | --- |
| `test_sdpa_constraint_flexible_kv_layout_gpu` (new) | Fails: `Input tensor must have contiguous last dimension` | Passes |
| `test_cache_sdpa_constraint_shared_kv` (GPU and CPU) | Passes | Passes |
| `test_insignificant_strides` | Fails (see note) | Fails (see note) |

On MI350X, the run without the fix fails at the kernel's own stride check (the crash this diff fixes) before it reaches check 2.

Note: `test_insignificant_strides` fails on ROCm with or without this change. It sends fp32 inputs to the CK attention kernel, which only supports fp16 and bf16, so it is unrelated to this fix.

Commands. `buck2 test` does not find the GPU tests on this devserver, so the test binary is run directly:

```
buck2 build fbcode//mode/opt-amd-gpu -c fbcode.rocm_arch=mi350 //caffe2/test/inductor:fused_attention --show-full-output
HIP_VISIBLE_DEVICES=7 <fused_attention.par from the build output> -v -k "test_sdpa_constraint_flexible_kv_layout or test_insignificant_strides or test_cache_sdpa_constraint_shared_kv"
```

A larger local repro of the model's pattern (not part of this diff) also crashes without the fix and passes with it, including a training step where the backward pass recomputes key/value. The gradients match eager.

Reviewed By: joebos, haoyuz

Differential Revision: D127902772

@eellison eellison left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

looks good ! i am working on a stack that should avoid this set of issues.. #193860 anyway lets land this first

…sh in SDPA (pytorch#202297)

Summary:

**Problem**

Training jobs that use `torch.compile` with flash attention can crash with:

```
RuntimeError: Input tensor must have contiguous last dimension
```

The flash attention kernel requires the values along the last dimension of query/key/value (the head dimension) to be stored next to each other in memory (`stride(-1) == 1`). Before calling the kernel, Inductor is supposed to make sure its inputs meet this requirement (in `sdpa_constraint`). In some graphs it does not: it passes a key/value tensor whose last dimension has `stride(-1) == 200`, and the kernel rejects it.

This is what crashes APS IG CTR training on MI350X (T290541015, T290943677). The CUDA flash kernel has the same check, so the bug is not specific to AMD.

**Why it happens**

1. `sdpa_constraint` first asks `is_aligned_realized_tensor` whether the input is already stored the way SDPA needs. If the answer is yes, the input is used as-is.
2. Inductor can create a buffer before it has decided the buffer's memory layout (a `FlexibleLayout`). Until then, the buffer reports placeholder strides that look correct. `is_aligned_realized_tensor` reads those placeholders and answers yes, so the layout is never set to what SDPA needs.
3. Right after, when the SDPA call is created, Inductor decides the layout (`decide_layout()` in `ExternKernel.process_kernel`). It picks the memory order that best matches how the buffer's inputs are stored. If those inputs have the sequence dimension innermost, so does the buffer, and SDPA receives a tensor whose last dimension is not contiguous.

In the IG CTR model, key and value are the same tensor. In the backward pass it is recomputed and used by two SDPA calls (the recomputed forward and the backward). Because it has two users, Inductor creates its buffer early, before deciding its layout, which is exactly the case above. The tensor is computed from a convolution output: MIOpen (AMD) stores that output with the sequence dimension innermost, while cuDNN (NVIDIA) does not. This is why the same job passes on GB200.

**Fix**

`is_aligned_realized_tensor` now answers "no" when the buffer's layout has not been decided yet. `sdpa_constraint` then takes its existing path that sets the layout to the one SDPA needs. Nothing is copied; the buffer is written in the right order from the start.

`sdpa_constraint` is the only caller of `is_aligned_realized_tensor`, so no other code is affected.

**Alternative not taken**

D125780486 makes the ROCm attention kernel copy any input whose last dimension is not contiguous. That does not fix every case: when the SDPA backward receives the bad tensor, its gradients come back in a different memory layout than Inductor expects, and Inductor's stride check fails instead. It also leaves this bug in place for other GPUs.

This change was written with an AI assistant (Claude Code).

Test Plan:
New test `test_sdpa_constraint_flexible_kv_layout_gpu` (in `test/inductor/test_fused_attention.py`) recreates the failing pattern in a few lines: key and value are the same tensor, built from transposed inputs, and used by two SDPA calls. It compiles the function with `run_and_get_code` and checks two things:

1. The result matches eager.
2. The generated code allocates key/value once, with `stride(-1) == 1`, and both SDPA calls use that buffer (no copies).

Check 2 is what this diff fixes: the memory layout Inductor picks for key/value. Inductor picks it while compiling, before any kernel runs, with the same code for every GPU type. So the test fails without the fix even on a GPU whose attention kernel would accept the wrong layout.

Without the fix, Inductor allocates key/value with strides `(2048, 8192, 1, 32)` (last dimension not contiguous) and adds two contiguous copies for the second SDPA call, so check 2 gets:

```
expected: ['2048, 2048, 64, 1']
actual:   ['2048, 8192, 1, 32', '2048, 2048, 64, 1', '2048, 2048, 64, 1']
```

Results on MI350X:

| Test | Without this fix | With this fix |
| --- | --- | --- |
| `test_sdpa_constraint_flexible_kv_layout_gpu` (new) | Fails: `Input tensor must have contiguous last dimension` | Passes |
| `test_cache_sdpa_constraint_shared_kv` (GPU and CPU) | Passes | Passes |
| `test_insignificant_strides` | Fails (see note) | Fails (see note) |

On MI350X, the run without the fix fails at the kernel's own stride check (the crash this diff fixes) before it reaches check 2.

Note: `test_insignificant_strides` fails on ROCm with or without this change. It sends fp32 inputs to the CK attention kernel, which only supports fp16 and bf16, so it is unrelated to this fix.

Commands. `buck2 test` does not find the GPU tests on this devserver, so the test binary is run directly:

```
buck2 build fbcode//mode/opt-amd-gpu -c fbcode.rocm_arch=mi350 //caffe2/test/inductor:fused_attention --show-full-output
HIP_VISIBLE_DEVICES=7 <fused_attention.par from the build output> -v -k "test_sdpa_constraint_flexible_kv_layout or test_insignificant_strides or test_cache_sdpa_constraint_shared_kv"
```

A larger local repro of the model's pattern (not part of this diff) also crashes without the fix and passes with it, including a training step where the backward pass recomputes key/value. The gradients match eager.

Reviewed By: joebos, haoyuz

Differential Revision: D127902772
@meta-codesync

meta-codesync Bot commented Nov 3, 2026

Copy link
Copy Markdown

@pytorchbot merge

(Initiating merge automatically since Phabricator Diff has merged)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Adding the topic: not user facing label automatically: this co-dev PR is being merged after its internal diff landed, without a release-notes label. If this change is user facing, please replace the label with the appropriate release notes: ... one.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…sh in SDPA (pytorch#202297) (pytorch#202297)

Summary:

**Problem**

Training jobs that use `torch.compile` with flash attention can crash with:

```
RuntimeError: Input tensor must have contiguous last dimension
```

The flash attention kernel requires the values along the last dimension of query/key/value (the head dimension) to be stored next to each other in memory (`stride(-1) == 1`). Before calling the kernel, Inductor is supposed to make sure its inputs meet this requirement (in `sdpa_constraint`). In some graphs it does not: it passes a key/value tensor whose last dimension has `stride(-1) == 200`, and the kernel rejects it.

This is what crashes APS IG CTR training on MI350X (T290541015, T290943677). The CUDA flash kernel has the same check, so the bug is not specific to AMD.

**Why it happens**

1. `sdpa_constraint` first asks `is_aligned_realized_tensor` whether the input is already stored the way SDPA needs. If the answer is yes, the input is used as-is.
2. Inductor can create a buffer before it has decided the buffer's memory layout (a `FlexibleLayout`). Until then, the buffer reports placeholder strides that look correct. `is_aligned_realized_tensor` reads those placeholders and answers yes, so the layout is never set to what SDPA needs.
3. Right after, when the SDPA call is created, Inductor decides the layout (`decide_layout()` in `ExternKernel.process_kernel`). It picks the memory order that best matches how the buffer's inputs are stored. If those inputs have the sequence dimension innermost, so does the buffer, and SDPA receives a tensor whose last dimension is not contiguous.

In the IG CTR model, key and value are the same tensor. In the backward pass it is recomputed and used by two SDPA calls (the recomputed forward and the backward). Because it has two users, Inductor creates its buffer early, before deciding its layout, which is exactly the case above. The tensor is computed from a convolution output: MIOpen (AMD) stores that output with the sequence dimension innermost, while cuDNN (NVIDIA) does not. This is why the same job passes on GB200.

**Fix**

`is_aligned_realized_tensor` now answers "no" when the buffer's layout has not been decided yet. `sdpa_constraint` then takes its existing path that sets the layout to the one SDPA needs. Nothing is copied; the buffer is written in the right order from the start.

`sdpa_constraint` is the only caller of `is_aligned_realized_tensor`, so no other code is affected.

**Alternative not taken**

D125780486 makes the ROCm attention kernel copy any input whose last dimension is not contiguous. That does not fix every case: when the SDPA backward receives the bad tensor, its gradients come back in a different memory layout than Inductor expects, and Inductor's stride check fails instead. It also leaves this bug in place for other GPUs.

This change was written with an AI assistant (Claude Code).

Test Plan:
New test `test_sdpa_constraint_flexible_kv_layout_gpu` (in `test/inductor/test_fused_attention.py`) recreates the failing pattern in a few lines: key and value are the same tensor, built from transposed inputs, and used by two SDPA calls. It compiles the function with `run_and_get_code` and checks two things:

1. The result matches eager.
2. The generated code allocates key/value once, with `stride(-1) == 1`, and both SDPA calls use that buffer (no copies).

Check 2 is what this diff fixes: the memory layout Inductor picks for key/value. Inductor picks it while compiling, before any kernel runs, with the same code for every GPU type. So the test fails without the fix even on a GPU whose attention kernel would accept the wrong layout.

Without the fix, Inductor allocates key/value with strides `(2048, 8192, 1, 32)` (last dimension not contiguous) and adds two contiguous copies for the second SDPA call, so check 2 gets:

```
expected: ['2048, 2048, 64, 1']
actual:   ['2048, 8192, 1, 32', '2048, 2048, 64, 1', '2048, 2048, 64, 1']
```

Results on MI350X:

| Test | Without this fix | With this fix |
| --- | --- | --- |
| `test_sdpa_constraint_flexible_kv_layout_gpu` (new) | Fails: `Input tensor must have contiguous last dimension` | Passes |
| `test_cache_sdpa_constraint_shared_kv` (GPU and CPU) | Passes | Passes |
| `test_insignificant_strides` | Fails (see note) | Fails (see note) |

On MI350X, the run without the fix fails at the kernel's own stride check (the crash this diff fixes) before it reaches check 2.

Note: `test_insignificant_strides` fails on ROCm with or without this change. It sends fp32 inputs to the CK attention kernel, which only supports fp16 and bf16, so it is unrelated to this fix.

Commands. `buck2 test` does not find the GPU tests on this devserver, so the test binary is run directly:

```
buck2 build fbcode//mode/opt-amd-gpu -c fbcode.rocm_arch=mi350 //caffe2/test/inductor:fused_attention --show-full-output
HIP_VISIBLE_DEVICES=7 <fused_attention.par from the build output> -v -k "test_sdpa_constraint_flexible_kv_layout or test_insignificant_strides or test_cache_sdpa_constraint_shared_kv"
```

A larger local repro of the model's pattern (not part of this diff) also crashes without the fix and passes with it, including a training step where the backward pass recomputes key/value. The gradients match eager.

Reviewed By: joebos, haoyuz

Differential Revision: D127902772

Pull Request resolved: pytorch#202297
Approved by: https://github.com/haoyuz, https://github.com/eellison
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…sh in SDPA (pytorch#202297) (pytorch#202297)

Summary:

**Problem**

Training jobs that use `torch.compile` with flash attention can crash with:

```
RuntimeError: Input tensor must have contiguous last dimension
```

The flash attention kernel requires the values along the last dimension of query/key/value (the head dimension) to be stored next to each other in memory (`stride(-1) == 1`). Before calling the kernel, Inductor is supposed to make sure its inputs meet this requirement (in `sdpa_constraint`). In some graphs it does not: it passes a key/value tensor whose last dimension has `stride(-1) == 200`, and the kernel rejects it.

This is what crashes APS IG CTR training on MI350X (T290541015, T290943677). The CUDA flash kernel has the same check, so the bug is not specific to AMD.

**Why it happens**

1. `sdpa_constraint` first asks `is_aligned_realized_tensor` whether the input is already stored the way SDPA needs. If the answer is yes, the input is used as-is.
2. Inductor can create a buffer before it has decided the buffer's memory layout (a `FlexibleLayout`). Until then, the buffer reports placeholder strides that look correct. `is_aligned_realized_tensor` reads those placeholders and answers yes, so the layout is never set to what SDPA needs.
3. Right after, when the SDPA call is created, Inductor decides the layout (`decide_layout()` in `ExternKernel.process_kernel`). It picks the memory order that best matches how the buffer's inputs are stored. If those inputs have the sequence dimension innermost, so does the buffer, and SDPA receives a tensor whose last dimension is not contiguous.

In the IG CTR model, key and value are the same tensor. In the backward pass it is recomputed and used by two SDPA calls (the recomputed forward and the backward). Because it has two users, Inductor creates its buffer early, before deciding its layout, which is exactly the case above. The tensor is computed from a convolution output: MIOpen (AMD) stores that output with the sequence dimension innermost, while cuDNN (NVIDIA) does not. This is why the same job passes on GB200.

**Fix**

`is_aligned_realized_tensor` now answers "no" when the buffer's layout has not been decided yet. `sdpa_constraint` then takes its existing path that sets the layout to the one SDPA needs. Nothing is copied; the buffer is written in the right order from the start.

`sdpa_constraint` is the only caller of `is_aligned_realized_tensor`, so no other code is affected.

**Alternative not taken**

D125780486 makes the ROCm attention kernel copy any input whose last dimension is not contiguous. That does not fix every case: when the SDPA backward receives the bad tensor, its gradients come back in a different memory layout than Inductor expects, and Inductor's stride check fails instead. It also leaves this bug in place for other GPUs.

This change was written with an AI assistant (Claude Code).

Test Plan:
New test `test_sdpa_constraint_flexible_kv_layout_gpu` (in `test/inductor/test_fused_attention.py`) recreates the failing pattern in a few lines: key and value are the same tensor, built from transposed inputs, and used by two SDPA calls. It compiles the function with `run_and_get_code` and checks two things:

1. The result matches eager.
2. The generated code allocates key/value once, with `stride(-1) == 1`, and both SDPA calls use that buffer (no copies).

Check 2 is what this diff fixes: the memory layout Inductor picks for key/value. Inductor picks it while compiling, before any kernel runs, with the same code for every GPU type. So the test fails without the fix even on a GPU whose attention kernel would accept the wrong layout.

Without the fix, Inductor allocates key/value with strides `(2048, 8192, 1, 32)` (last dimension not contiguous) and adds two contiguous copies for the second SDPA call, so check 2 gets:

```
expected: ['2048, 2048, 64, 1']
actual:   ['2048, 8192, 1, 32', '2048, 2048, 64, 1', '2048, 2048, 64, 1']
```

Results on MI350X:

| Test | Without this fix | With this fix |
| --- | --- | --- |
| `test_sdpa_constraint_flexible_kv_layout_gpu` (new) | Fails: `Input tensor must have contiguous last dimension` | Passes |
| `test_cache_sdpa_constraint_shared_kv` (GPU and CPU) | Passes | Passes |
| `test_insignificant_strides` | Fails (see note) | Fails (see note) |

On MI350X, the run without the fix fails at the kernel's own stride check (the crash this diff fixes) before it reaches check 2.

Note: `test_insignificant_strides` fails on ROCm with or without this change. It sends fp32 inputs to the CK attention kernel, which only supports fp16 and bf16, so it is unrelated to this fix.

Commands. `buck2 test` does not find the GPU tests on this devserver, so the test binary is run directly:

```
buck2 build fbcode//mode/opt-amd-gpu -c fbcode.rocm_arch=mi350 //caffe2/test/inductor:fused_attention --show-full-output
HIP_VISIBLE_DEVICES=7 <fused_attention.par from the build output> -v -k "test_sdpa_constraint_flexible_kv_layout or test_insignificant_strides or test_cache_sdpa_constraint_shared_kv"
```

A larger local repro of the model's pattern (not part of this diff) also crashes without the fix and passes with it, including a training step where the backward pass recomputes key/value. The gradients match eager.

Reviewed By: joebos, haoyuz

Differential Revision: D127902772

Pull Request resolved: pytorch#202297
Approved by: https://github.com/haoyuz, https://github.com/eellison
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged meta-exported module: inductor ready for review Automated review passed, ready for a final review by a maintainer. topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants