Skip to content

Size SDPA backward workspace by total tokens instead of batch * max_seqlen - #200847

Closed
liangel-02 wants to merge 1 commit into
mainfrom
cudnn-varlen-ragged-bwd-workspace
Closed

liangel-02 wants to merge 1 commit into
mainfrom
cudnn-varlen-ragged-bwd-workspace

Conversation

@liangel-02

@liangel-02 liangel-02 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The nested/varlen cuDNN SDPA backward graph never set max_total_seq_len_q/kv. Without them, cudnn-frontend sizes its fp32 dQ_accum and softmax_sum workspace buffers as dense [b, h, max_seqlen, d+1] tensors. With skewed document lengths, b * max_seqlen is much larger than the real token count, so backward memory grows by one full padded sequence per document.

This PR sets max_total_seq_len_q/kv to the packed token counts (q.size(0) / k.size(0)), so cudnn-frontend sizes those buffers by total tokens (THD), matching the data layout.

  • cudnn-frontend already drops the attribute, with a warning, where it isn't supported (cuDNN < 9.6, head dim not a multiple of 16, sm80/sm120 kernels).
  • T is already part of the graph cache key through the q/k sizes, so a cached graph can't run with a workspace that's too small.
  • Only the backward is affected. The forward SDPA node never uses this attribute for workspace sizing, and forward peak memory is flat before and after.

Test plan

Setup: B200 (sm100), CUDA 13.0, cuDNN 9.20, cudnn-frontend 1.30 (in-tree), bf16, T = 16384 packed tokens, H = 32, D = 128. "Before" is this commit with the change reverted (same build, incremental rebuild of MHA.cpp only).

1. varlen_attn fwd+bwd peak memory (MiB above inputs), causal, cuDNN vs FA4

FA4 is enabled with activate_flash_attention_impl("FA4").

Decreasing doc lengths (8k, 4k, 2k, ..., floored at 8 tokens):

num_docs FA4 cuDNN before cuDNN after
1 906 902 902
2 908 902 902
4 912 1160 902
8 920 1676 902
16 937 2708 902
32 969 4772 902
128 1164 17156 902
512 1944 66692 902
1024 2984 OOM 903

Equal doc lengths (T / num_docs each). This PR doesn't change these numbers, because num_docs * max_seqlen == T:

num_docs FA4 cuDNN before cuDNN after
1 906 902 902
2 908 902 902
4 912 902 902
8 920 902 902
16 937 902 902
32 969 902 902
128 1164 error* error*
512 1944 error* error*
1024 2984 error* error*

* max_seqlen <= 128 requires cuDNN >= 9.24. This is an existing constraint, unrelated to this PR.

2. Forward vs backward split, decreasing doc lengths (MiB)

Forward memory is flat. All of the growth was one backward workspace allocation of exactly 4 B * num_docs * H * max_seqlen * (D + 1). The numbers are identical for causal and non-causal.

num_docs fwd peak before fwd peak after bwd peak before bwd peak after largest bwd alloc before largest bwd alloc after
1 130 130 772 772 258 258
4 130 130 1030 772 516 258
16 130 130 2578 772 2064 258
64 130 130 8770 772 8256 258
128 130 130 17026 772 16512 258

3. cudnn-frontend called directly

This uses the Python API to build the same ragged backward graph as MHA.cpp, and compares get_workspace_size() with and without max_total_seq_len_q/kv:

num_docs workspace without (MiB) workspace with (MiB)
4 516 258
16 2064 258
128 16512 258
512 66048 258

dK/dV are bitwise identical between the two. dQ differs only by the existing run-to-run nondeterminism of the default (atomic) dQ accumulation.

4. Correctness vs an fp32 reference

cuDNN varlen dQ/dK/dV compared with an fp32 per-document SDPA reference, causal and non-causal:

doc lengths max relative error
[777, 64, 3, 1201, 9] 2.9e-3 to 4.4e-3
[4096] 2.4e-3 to 3.8e-3
[1000, 1000, 1000] 2.5e-3 to 4.5e-3
[2048, 8 x 7] 2.8e-3 to 5.1e-3

5. Memory safety

compute-sanitizer --tool memcheck with PYTORCH_NO_CUDA_MEMORY_CACHING=1, so the smaller workspace is its own allocation and any out-of-bounds write would be caught. Lengths [777, 64, 3, 1201, 9], [2048, 8 x 7], and [129], causal and non-causal: 0 errors.

6. Existing tests

python test/test_varlen_attention.py: 399 passed, 86 skipped, 8 xfailed.

cc @csarofeen @ptrblck @eqy @nWEIdia @msaroufim @tinglvv

@pytorch-bot

pytorch-bot Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

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

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

@liangel-02
liangel-02 requested a review from drisspg October 13, 2026 21:17
@eqy eqy added module: cuda Related to torch.cuda, and CUDA support in general open source topic: not user facing topic category labels Oct 13, 2026
@eqy eqy added the module: cudnn Related to torch.backends.cudnn, and CuDNN support label Oct 13, 2026
@eqy
eqy requested a review from gderossi October 13, 2026 21:20
@eqy eqy added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 13, 2026

@eqy eqy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@claude does it make sense to also add this for other frontend calls such as the forward or are those workspaces not really affected by this option?

@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 13, 2026
…of batch * max_seqlen

The nested/varlen cuDNN SDPA backward graph never set
max_total_seq_len_q/kv, so cudnn-frontend sized its fp32 dQ accumulator
and softmax_sum workspace as dense [b, h, max_seqlen, d+1] buffers. With
skewed document lengths, b * max_seqlen is far larger than the actual
token count, and backward memory grows by one full padded sequence per
document.

Setting max_total_seq_len_q/kv to the packed token counts makes
cudnn-frontend size those buffers by total tokens (THD), matching the
data layout. cudnn-frontend already drops the attribute with a warning
where it is unsupported (cuDNN < 9.6, head dim not a multiple of 16,
sm80/sm120 kernels). T is already part of the graph cache key via the
q/k sizes.

Test plan

Setup: B200 (sm100), CUDA 13.0, cuDNN 9.20, cudnn-frontend 1.30 (in-tree),
bf16, T=16384 packed tokens, H=32, D=128. "Before" is this commit with
the change reverted (same build, incremental rebuild of MHA.cpp only).

1. varlen_attn fwd+bwd peak memory (MiB above inputs), causal, cuDNN vs
   FA4 (activate_flash_attention_impl("FA4")).

   Decreasing doc lengths (8k, 4k, 2k, ..., floored at 8 tokens):

     num_docs   FA4   cuDNN before   cuDNN after
            1   906            902           902
            2   908            902           902
            4   912           1160           902
            8   920           1676           902
           16   937           2708           902
           32   969           4772           902
          128  1164          17156           902
          512  1944          66692           902
         1024  2984            OOM           903

   Equal doc lengths (T / num_docs each); unchanged by this PR because
   num_docs * max_seqlen == T:

     num_docs   FA4   cuDNN before   cuDNN after
            1   906            902           902
            2   908            902           902
            4   912            902           902
            8   920            902           902
           16   937            902           902
           32   969            902           902
          128  1164        error*        error*
          512  1944        error*        error*
         1024  2984        error*        error*

   * max_seqlen <= 128 requires cuDNN >= 9.24 (existing constraint,
     unrelated to this PR).

2. Forward vs backward split, decreasing doc lengths (MiB). Forward is
   flat; all of the growth was a single backward workspace allocation
   of exactly 4 B * num_docs * H * max_seqlen * (D + 1). Identical for
   causal and non-causal.

                 fwd peak        bwd peak         largest bwd alloc
     num_docs   before after   before   after    before     after
            1      130   130      772     772       258       258
            4      130   130     1030     772       516       258
           16      130   130     2578     772      2064       258
           64      130   130     8770     772      8256       258
          128      130   130    17026     772     16512       258

3. cudnn-frontend directly (Python API, same ragged backward graph as
   MHA.cpp): get_workspace_size() without vs with max_total_seq_len_q/kv
   = 4 docs: 516 vs 258 MiB, 16: 2064 vs 258, 128: 16512 vs 258,
   512: 66048 vs 258. dK/dV bitwise identical between the two; dQ
   differs only by the existing run-to-run nondeterminism of the
   default (atomic) dQ accumulation.

4. Correctness: cuDNN varlen dQ/dK/dV vs an fp32 per-document SDPA
   reference, causal and non-causal, lens [777, 64, 3, 1201, 9],
   [4096], [1000, 1000, 1000], [2048, 8 x 7]: max relative error
   2.5e-3 to 5.1e-3 in all cases.

5. compute-sanitizer --tool memcheck with
   PYTORCH_NO_CUDA_MEMORY_CACHING=1 (so the smaller workspace is its
   own allocation), lens [777, 64, 3, 1201, 9], [2048, 8 x 7], [129],
   causal and non-causal: 0 errors.

6. python test/test_varlen_attention.py: 399 passed, 86 skipped,
   8 xfailed.
@liangel-02

Copy link
Copy Markdown
Contributor Author

@eqy i think the fwd doesnt need this cus max_total_seq_len_q/kv only affects the backward's workspace sizing

@liangel-02
liangel-02 force-pushed the cudnn-varlen-ragged-bwd-workspace branch from 878bfd8 to e007609 Compare October 13, 2026 21:24
@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merger

@pytorch-bot

pytorch-bot Bot commented Oct 13, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

@pytorchbot: error: argument command: invalid choice: 'merger' (choose from 'merge', 'revert', 'rebase', 'label', 'drci', 'review', 'pre-review', 'lint', 'fix-lint', 'apply-lint', 'cherry-pick')

usage: @pytorchbot [-h]
                   
                   {merge,revert,rebase,label,drci,review,pre-review,lint,fix-lint,apply-lint,cherry-pick}
                   ...

Try @pytorchbot --help for more info.

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@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

liangel-02 added a commit that referenced this pull request Nov 18, 2026
## Linked issue or supporting maintainer

Fixes #205493

## BC-breaking?

No.

## Summary (human written only)

<!-- Please add your own brief summary of why you want this change before submission. -->

## Agent details (AI-generated)

### Change and root cause

When Q is a view into fused QKV storage, cuDNN varlen attention backward can return incorrect dQ after the first document. #200847 exposed this by enabling compact backward workspace with `max_total_seq_len_q/kv`. The frontend describes the fp32 dQ accumulator using dQ's strides and ragged offsets, but the affected backend uses Q's ragged offsets for its TMA base addresses.

This change copies Q into `empty_like(dQ)` only when their strides differ, before constructing the backward cache key, graph, offsets, and variant pack. Matching dQ's layout also handles head-major Q; making Q contiguous unconditionally would not preserve that layout. It keeps compact workspace sizing and skips the copy when layouts already match. A TODO records the condition for removing the workaround once cuDNN honors the accumulator's own offsets.

Reverting #200847 also restores correctness, but gives up substantial memory and runtime improvements for skewed document lengths. The copy has a real cost for equal-length inputs; the measurements below include that tradeoff. These are isolated attention forward/backward measurements, not end-to-end training results.

### Validation

Built current main base `270998c816acb1ffab58639ee5e1a78b95b440e3` plus this patch with CUDA 13.2 and cuDNN 9.27.0.42 on B200 using `pip install -e . -v --no-build-isolation`.

```bash
CUDA_VISIBLE_DEVICES=1 python test/test_varlen_attention.py TestVarlenAttentionCuDNNCUDA -v
spin lint aten/src/ATen/native/cudnn/MHA.cpp
python -m spin lint test/test_varlen_attention.py
```

Results: **87 passed, 1 skipped**; lint passed. The 16 new numerical cases cover fused QKV and padded head-major Q, fp16/bf16, causal/noncausal, and MHA/GQA against fp32 math SDPA. Before rebuilding with the fix, the new fused-QKV bf16 causal MHA test failed with maximum absolute dQ error 4.2146. All 16 now pass. The original issue's reproduction also passes, with fused-QKV per-document dQ errors `[0.01185, 0.00753, 0.00786]`.

The direct frontend reproducer separately verifies that compact workspace with strided Q still fails in the backend, while padded workspace and copied Q both pass with the same selected engine. This patch works around that backend behavior; it does not change cuDNN's kernel.

### Benchmarks against reverting #200847

These measurements were collected on the preserved #200847 checkout to match that PR's documented environment. They evaluate the same conditional Q-copy operation as this patch; they are not measurements of current main with cuDNN 9.27. The benchmark environment switches were local instrumentation and are not included in this PR.

<details>
<summary>Setup, complete memory and latency tables, and limitations</summary>

### Setup

NVIDIA B200 (sm100), CUDA 13.0, cuDNN 9.20.0.48, in-tree cudnn-frontend 1.30.0, bf16, T=16384, H=32, D=128. PyTorch source is the preserved PR checkout `878bfd867075b6351f75b95f9b6052efa85beef4`, rebuilt as `2.16.0a0+git878bfd8`.

- **Revert:** omit both `set_max_total_seq_len_q/kv` attributes, no Q copy.
- **Copy:** retain the attributes; if Q and dQ strides differ, allocate `empty_like(dQ)` and copy Q into it. Use that tensor for the backward descriptor, cache key, offsets, and pointer.
- **Dense:** separate contiguous Q/K/V tensors. The conditional workaround skips the copy.
- **QKV:** leaf views into `[T,3,H,D]` storage. Q token stride is 12288, versus dQ stride 4096, so the workaround copies 128 MiB every backward.

The summary does not link its original benchmark script. `lengths_for` reconstructs the decreasing lengths by halving the remaining tokens, reserving at least 8 for each remaining document. T stays exactly 16384 and max sequence length is 8192 for every multi-document decreasing case, matching the PR's workspace table. The generator keeps the packed token count fixed: each non-final document takes `min(max(remaining // 2, 8), remaining - 8 * documents_left)`, and the final document takes the remainder.

Peak memory is allocated device memory above Q/K/V and cumulative-length inputs. It includes the output gradient, outputs, attention intermediates, gradients, workspace, and the Q copy. It excludes allocator-reserved-but-unused memory. The output gradient is allocated after the forward, matching the PR's forward/backward memory accounting.

Timing uses 5 groups of 20 iterations after warmup, reporting the median CUDA-event time. Tables below use CUDA-graph replay timings. Graph construction/compilation and random input/output-gradient generation are excluded. Memory is measured separately, outside CUDA graph capture. GPU 1 is used for all variants.

### Forward + backward peak memory (MiB), causal

#### Decreasing document lengths

| Documents | Revert, dense | Copy, dense | Revert, QKV | Copy, QKV | FA4, dense |
|---:|---:|---:|---:|---:|---:|
| 1 | 902 | 902 | 902 | 1,030 | 906 |
| 2 | 902 | 902 | 902 | 1,030 | 908 |
| 4 | 1,160 | 902 | 1,160 | 1,030 | 912 |
| 8 | 1,676 | 902 | 1,676 | 1,030 | 920 |
| 16 | 2,708 | 902 | 2,708 | 1,030 | 937 |
| 32 | 4,772 | 902 | 4,772 | 1,030 | 969 |
| 128 | 17,156 | 902 | 17,156 | 1,030 | 1,164 |
| 512 | 66,692 | 902 | 66,692 | 1,030 | 1,944 |
| 1024 | 132,740 | 902 | 132,740 | 1,030 | 2,984 |

#### Equal document lengths

| Documents | Revert, dense | Copy, dense | Revert, QKV | Copy, QKV | FA4, dense |
|---:|---:|---:|---:|---:|---:|
| 1 | 902 | 902 | 902 | 1,030 | 906 |
| 2 | 902 | 902 | 902 | 1,030 | 908 |
| 4 | 902 | 902 | 902 | 1,030 | 912 |
| 8 | 902 | 902 | 902 | 1,030 | 920 |
| 16 | 902 | 902 | 902 | 1,030 | 937 |
| 32 | 902 | 902 | 902 | 1,030 | 969 |
| 128 | error | error | error | error | 1,164 |
| 512 | error | error | error | error | 1,944 |
| 1024 | error | error | error | error | 2,984 |

### Latency when the copy is required (QKV), causal

Percent change is `(copy / revert - 1) * 100`; a negative number means faster.

#### Decreasing document lengths

| Documents | Revert bwd (ms) | Copy bwd (ms) | Revert fwd+bwd (ms) | Copy fwd+bwd (ms) | Fwd+bwd change |
|---:|---:|---:|---:|---:|---:|
| 1 | 6.959 | 7.069 | 9.381 | 9.473 | +1.0% |
| 2 | 3.736 | 3.753 | 5.002 | 5.112 | +2.2% |
| 4 | 2.582 | 2.792 | 3.542 | 3.678 | +3.9% |
| 8 | 2.672 | 2.714 | 3.534 | 3.585 | +1.4% |
| 16 | 2.779 | 2.714 | 3.632 | 3.595 | -1.0% |
| 32 | 3.242 | 2.744 | 4.092 | 3.634 | -11.2% |
| 128 | 6.003 | 2.839 | 7.011 | 3.832 | -45.3% |
| 512 | 16.732 | 3.611 | 18.355 | 5.216 | -71.6% |
| 1024 | 30.825 | 4.398 | 33.176 | 6.741 | -79.7% |

#### Equal document lengths

| Documents | Revert bwd (ms) | Copy bwd (ms) | Revert fwd+bwd (ms) | Copy fwd+bwd (ms) | Fwd+bwd change |
|---:|---:|---:|---:|---:|---:|
| 1 | 6.858 | 7.090 | 9.358 | 9.501 | +1.5% |
| 2 | 3.620 | 3.836 | 4.998 | 5.112 | +2.3% |
| 4 | 2.037 | 2.183 | 2.769 | 2.882 | +4.1% |
| 8 | 1.221 | 1.395 | 1.661 | 1.836 | +10.5% |
| 16 | 0.832 | 1.003 | 1.154 | 1.322 | +14.6% |
| 32 | 0.641 | 0.814 | 0.905 | 1.074 | +18.7% |
| 128 | error | error | error | error | - |
| 512 | error | error | error | error | - |
| 1024 | error | error | error | error | - |

### Dense control: conditional workaround skips the copy

| Equal-length documents | Revert fwd+bwd (ms) | Compact, no Q copy (ms) |
|---:|---:|---:|
| 1 | 9.328 | 9.468 |
| 2 | 4.992 | 5.067 |
| 4 | 2.750 | 2.871 |
| 8 | 1.655 | 1.772 |
| 16 | 1.143 | 1.263 |
| 32 | 0.890 | 1.015 |

### Forward/backward memory split, decreasing lengths, QKV (MiB)

| Causal | Documents | Revert fwd | Copy fwd | Revert bwd | Copy bwd | Revert workspace | Copy workspace |
|---|---:|---:|---:|---:|---:|---:|---:|
| True | 1 | 130 | 130 | 772 | 900 | 258 | 258 |
| True | 4 | 130 | 130 | 1,030 | 900 | 516 | 258 |
| True | 16 | 130 | 130 | 2,578 | 900 | 2,064 | 258 |
| True | 64 | 130 | 130 | 8,770 | 900 | 8,256 | 258 |
| True | 128 | 130 | 130 | 17,026 | 900 | 16,512 | 258 |
| False | 1 | 130 | 130 | 772 | 900 | 258 | 258 |
| False | 4 | 130 | 130 | 1,030 | 900 | 516 | 258 |
| False | 16 | 130 | 130 | 2,578 | 900 | 2,064 | 258 |
| False | 64 | 130 | 130 | 8,770 | 900 | 8,256 | 258 |
| False | 128 | 130 | 130 | 17,026 | 900 | 16,512 | 258 |

### Correctness and limits

Both variants passed 16 tests each: all four PR correctness length lists, causal/non-causal, dense/fused-QKV. Forward and dQ/dK/dV were compared against per-document fp32 math SDPA with `TestCase.assertEqual(atol=0.03, rtol=0.03)`. Gradient relative L2 errors were approximately 0.22-0.27%.

Equal-length cases with 128/512/1024 documents fail the existing cuDNN 9.20 constraint on max sequence length <=128, as in the original PR.

The 1024-document decreasing case fits on this otherwise idle GPU at approximately 132740 MiB above inputs with the revert. The original PR reported OOM for that row. The other memory rows reproduce the PR's results within rounding.

The standalone Q copy costs about 51 microseconds. The entire workaround's latency change also includes the difference between compact and padded cuDNN backward execution. Even dense Q, where no copy is performed, is slower on the compact path for the shorter equal-length cases; the full slowdown versus reverting must not be attributed only to `copy_`.

FA4 is enabled with `activate_flash_attention_impl("FA4")`; the installed package is `flash-attn-4==4.0.0b19` (the PR did not specify its FA4 package version). Its memory rows also reproduce the PR's table.

This benchmarks a workaround, not a fix to cuDNN's internal accumulator indexing. The benchmark switches are local instrumentation, not a proposed production API.

</details>
ghstack-source-id: ab28029
Pull-Request: #205562
pytorchmergebot pushed a commit that referenced this pull request Nov 19, 2026
## Linked issue or supporting maintainer

Fixes #205493

## BC-breaking?

No.

## Summary (human written only)

<!-- Please add your own brief summary of why you want this change before submission. -->

## Agent details (AI-generated)

### Change and root cause

When Q is a view into fused QKV storage, cuDNN varlen attention backward can return incorrect dQ after the first document. #200847 exposed this by enabling compact backward workspace with `max_total_seq_len_q/kv`. The frontend describes the fp32 dQ accumulator using dQ's strides and ragged offsets, but the affected backend uses Q's ragged offsets for its TMA base addresses.

This change copies Q into `empty_like(dQ)` only when their strides differ, before constructing the backward cache key, graph, offsets, and variant pack. Matching dQ's layout also handles head-major Q; making Q contiguous unconditionally would not preserve that layout. It keeps compact workspace sizing and skips the copy when layouts already match. A TODO records the condition for removing the workaround once cuDNN honors the accumulator's own offsets.

Reverting #200847 also restores correctness, but gives up substantial memory and runtime improvements for skewed document lengths. The copy has a real cost for equal-length inputs; the measurements below include that tradeoff. These are isolated attention forward/backward measurements, not end-to-end training results.

### Validation

Built current main base `270998c816acb1ffab58639ee5e1a78b95b440e3` plus this patch with CUDA 13.2 and cuDNN 9.27.0.42 on B200 using `pip install -e . -v --no-build-isolation`.

```bash
CUDA_VISIBLE_DEVICES=1 python test/test_varlen_attention.py TestVarlenAttentionCuDNNCUDA -v
spin lint aten/src/ATen/native/cudnn/MHA.cpp
python -m spin lint test/test_varlen_attention.py
```

Results: **87 passed, 1 skipped**; lint passed. The 16 new numerical cases cover fused QKV and padded head-major Q, fp16/bf16, causal/noncausal, and MHA/GQA against fp32 math SDPA. Before rebuilding with the fix, the new fused-QKV bf16 causal MHA test failed with maximum absolute dQ error 4.2146. All 16 now pass. The original issue's reproduction also passes, with fused-QKV per-document dQ errors `[0.01185, 0.00753, 0.00786]`.

The direct frontend reproducer separately verifies that compact workspace with strided Q still fails in the backend, while padded workspace and copied Q both pass with the same selected engine. This patch works around that backend behavior; it does not change cuDNN's kernel.

### Benchmarks against reverting #200847

These measurements were collected on the preserved #200847 checkout to match that PR's documented environment. They evaluate the same conditional Q-copy operation as this patch; they are not measurements of current main with cuDNN 9.27. The benchmark environment switches were local instrumentation and are not included in this PR.

<details>
<summary>Setup, complete memory and latency tables, and limitations</summary>

### Setup

NVIDIA B200 (sm100), CUDA 13.0, cuDNN 9.20.0.48, in-tree cudnn-frontend 1.30.0, bf16, T=16384, H=32, D=128. PyTorch source is the preserved PR checkout `878bfd867075b6351f75b95f9b6052efa85beef4`, rebuilt as `2.16.0a0+git878bfd8`.

- **Revert:** omit both `set_max_total_seq_len_q/kv` attributes, no Q copy.
- **Copy:** retain the attributes; if Q and dQ strides differ, allocate `empty_like(dQ)` and copy Q into it. Use that tensor for the backward descriptor, cache key, offsets, and pointer.
- **Dense:** separate contiguous Q/K/V tensors. The conditional workaround skips the copy.
- **QKV:** leaf views into `[T,3,H,D]` storage. Q token stride is 12288, versus dQ stride 4096, so the workaround copies 128 MiB every backward.

The summary does not link its original benchmark script. `lengths_for` reconstructs the decreasing lengths by halving the remaining tokens, reserving at least 8 for each remaining document. T stays exactly 16384 and max sequence length is 8192 for every multi-document decreasing case, matching the PR's workspace table. The generator keeps the packed token count fixed: each non-final document takes `min(max(remaining // 2, 8), remaining - 8 * documents_left)`, and the final document takes the remainder.

Peak memory is allocated device memory above Q/K/V and cumulative-length inputs. It includes the output gradient, outputs, attention intermediates, gradients, workspace, and the Q copy. It excludes allocator-reserved-but-unused memory. The output gradient is allocated after the forward, matching the PR's forward/backward memory accounting.

Timing uses 5 groups of 20 iterations after warmup, reporting the median CUDA-event time. Tables below use CUDA-graph replay timings. Graph construction/compilation and random input/output-gradient generation are excluded. Memory is measured separately, outside CUDA graph capture. GPU 1 is used for all variants.

### Forward + backward peak memory (MiB), causal

#### Decreasing document lengths

| Documents | Revert, dense | Copy, dense | Revert, QKV | Copy, QKV | FA4, dense |
|---:|---:|---:|---:|---:|---:|
| 1 | 902 | 902 | 902 | 1,030 | 906 |
| 2 | 902 | 902 | 902 | 1,030 | 908 |
| 4 | 1,160 | 902 | 1,160 | 1,030 | 912 |
| 8 | 1,676 | 902 | 1,676 | 1,030 | 920 |
| 16 | 2,708 | 902 | 2,708 | 1,030 | 937 |
| 32 | 4,772 | 902 | 4,772 | 1,030 | 969 |
| 128 | 17,156 | 902 | 17,156 | 1,030 | 1,164 |
| 512 | 66,692 | 902 | 66,692 | 1,030 | 1,944 |
| 1024 | 132,740 | 902 | 132,740 | 1,030 | 2,984 |

#### Equal document lengths

| Documents | Revert, dense | Copy, dense | Revert, QKV | Copy, QKV | FA4, dense |
|---:|---:|---:|---:|---:|---:|
| 1 | 902 | 902 | 902 | 1,030 | 906 |
| 2 | 902 | 902 | 902 | 1,030 | 908 |
| 4 | 902 | 902 | 902 | 1,030 | 912 |
| 8 | 902 | 902 | 902 | 1,030 | 920 |
| 16 | 902 | 902 | 902 | 1,030 | 937 |
| 32 | 902 | 902 | 902 | 1,030 | 969 |
| 128 | error | error | error | error | 1,164 |
| 512 | error | error | error | error | 1,944 |
| 1024 | error | error | error | error | 2,984 |

### Latency when the copy is required (QKV), causal

Percent change is `(copy / revert - 1) * 100`; a negative number means faster.

#### Decreasing document lengths

| Documents | Revert bwd (ms) | Copy bwd (ms) | Revert fwd+bwd (ms) | Copy fwd+bwd (ms) | Fwd+bwd change |
|---:|---:|---:|---:|---:|---:|
| 1 | 6.959 | 7.069 | 9.381 | 9.473 | +1.0% |
| 2 | 3.736 | 3.753 | 5.002 | 5.112 | +2.2% |
| 4 | 2.582 | 2.792 | 3.542 | 3.678 | +3.9% |
| 8 | 2.672 | 2.714 | 3.534 | 3.585 | +1.4% |
| 16 | 2.779 | 2.714 | 3.632 | 3.595 | -1.0% |
| 32 | 3.242 | 2.744 | 4.092 | 3.634 | -11.2% |
| 128 | 6.003 | 2.839 | 7.011 | 3.832 | -45.3% |
| 512 | 16.732 | 3.611 | 18.355 | 5.216 | -71.6% |
| 1024 | 30.825 | 4.398 | 33.176 | 6.741 | -79.7% |

#### Equal document lengths

| Documents | Revert bwd (ms) | Copy bwd (ms) | Revert fwd+bwd (ms) | Copy fwd+bwd (ms) | Fwd+bwd change |
|---:|---:|---:|---:|---:|---:|
| 1 | 6.858 | 7.090 | 9.358 | 9.501 | +1.5% |
| 2 | 3.620 | 3.836 | 4.998 | 5.112 | +2.3% |
| 4 | 2.037 | 2.183 | 2.769 | 2.882 | +4.1% |
| 8 | 1.221 | 1.395 | 1.661 | 1.836 | +10.5% |
| 16 | 0.832 | 1.003 | 1.154 | 1.322 | +14.6% |
| 32 | 0.641 | 0.814 | 0.905 | 1.074 | +18.7% |
| 128 | error | error | error | error | - |
| 512 | error | error | error | error | - |
| 1024 | error | error | error | error | - |

### Dense control: conditional workaround skips the copy

| Equal-length documents | Revert fwd+bwd (ms) | Compact, no Q copy (ms) |
|---:|---:|---:|
| 1 | 9.328 | 9.468 |
| 2 | 4.992 | 5.067 |
| 4 | 2.750 | 2.871 |
| 8 | 1.655 | 1.772 |
| 16 | 1.143 | 1.263 |
| 32 | 0.890 | 1.015 |

### Forward/backward memory split, decreasing lengths, QKV (MiB)

| Causal | Documents | Revert fwd | Copy fwd | Revert bwd | Copy bwd | Revert workspace | Copy workspace |
|---|---:|---:|---:|---:|---:|---:|---:|
| True | 1 | 130 | 130 | 772 | 900 | 258 | 258 |
| True | 4 | 130 | 130 | 1,030 | 900 | 516 | 258 |
| True | 16 | 130 | 130 | 2,578 | 900 | 2,064 | 258 |
| True | 64 | 130 | 130 | 8,770 | 900 | 8,256 | 258 |
| True | 128 | 130 | 130 | 17,026 | 900 | 16,512 | 258 |
| False | 1 | 130 | 130 | 772 | 900 | 258 | 258 |
| False | 4 | 130 | 130 | 1,030 | 900 | 516 | 258 |
| False | 16 | 130 | 130 | 2,578 | 900 | 2,064 | 258 |
| False | 64 | 130 | 130 | 8,770 | 900 | 8,256 | 258 |
| False | 128 | 130 | 130 | 17,026 | 900 | 16,512 | 258 |

### Correctness and limits

Both variants passed 16 tests each: all four PR correctness length lists, causal/non-causal, dense/fused-QKV. Forward and dQ/dK/dV were compared against per-document fp32 math SDPA with `TestCase.assertEqual(atol=0.03, rtol=0.03)`. Gradient relative L2 errors were approximately 0.22-0.27%.

Equal-length cases with 128/512/1024 documents fail the existing cuDNN 9.20 constraint on max sequence length <=128, as in the original PR.

The 1024-document decreasing case fits on this otherwise idle GPU at approximately 132740 MiB above inputs with the revert. The original PR reported OOM for that row. The other memory rows reproduce the PR's results within rounding.

The standalone Q copy costs about 51 microseconds. The entire workaround's latency change also includes the difference between compact and padded cuDNN backward execution. Even dense Q, where no copy is performed, is slower on the compact path for the shorter equal-length cases; the full slowdown versus reverting must not be attributed only to `copy_`.

FA4 is enabled with `activate_flash_attention_impl("FA4")`; the installed package is `flash-attn-4==4.0.0b19` (the PR did not specify its FA4 package version). Its memory rows also reproduce the PR's table.

This benchmarks a workaround, not a fix to cuDNN's internal accumulator indexing. The benchmark switches are local instrumentation, not a proposed production API.

</details>
Pull Request resolved: #205562
Approved by: https://github.com/pytorchgreenlight, https://github.com/eqy, https://github.com/drisspg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/trunk Trigger trunk jobs on your pull request Merged module: cuda Related to torch.cuda, and CUDA support in general module: cudnn Related to torch.backends.cudnn, and CuDNN support open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants