Repository navigation
Varlen attention backend falls back to CuDNN even when FA is installed. - #5152
Conversation
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
| # varlen_attn prefers cuDNN over Flash when no sdpa_kernel priority is set. | ||
| # cuDNN's varlen backward allocates ~num_docs * max_seqlen * H * K * 8 bytes | ||
| # (e.g. 31 GiB for 64 docs with max_seqlen 8k), so pin Flash explicitly. | ||
| sdpa_backends: list[SDPBackend] = [SDPBackend.FLASH_ATTENTION] |
There was a problem hiding this comment.
I think we preferred cudnn because it's more performant.
Does it make sense if this class exposes this as a config like window_size, but in torchtitan we don't further expose it in build_model_config because you have your own config builder?
There was a problem hiding this comment.
+1 also can you provide your setup so i can try to repro this memory issue you're seeing, thanks!
There was a problem hiding this comment.
I recently upgraded PyTorch and noticed that an experiment that was already running close to the memory limit stopped working. Claude helped me identify the cause: the backend had changed from FA3 to cuDNN. Switching back to FA3 immediately resolved the issue.
Initially, I assumed the switch to cuDNN was accidental. However, since you asked about it, I looked into it further. Based on my benchmarks, cuDNN uses less memory than FA3 when document lengths are roughly uniform.
When document lengths are heavily skewed, however, FA3 performs significantly better.
For the benchmarks below, I tested two document-length policies:
1. Decreasing document lengths
- 1 document → 16k
- 2 documents → 8k, 8k
- 4 documents → 8k, 4k, 2k, 2k
- ...
2. Uniform document lengths
- 1 document → 16k
- 2 documents → 8k, 8k
- 4 documents → 4k, 4k, 4k, 4k
- ...
Under the first policy, FA3 performs significantly better. On a GH200, cuDNN cannot even complete the benchmark.
Under the second policy, cuDNN appears to have a slight memory-efficiency advantage.
Given that natural document lengths tend to be skewed, I think FA3 should be the default backend. What do you think?
The vibed benchmark
import gc
import torch
from torch.nn.attention import SDPBackend, activate_flash_attention_impl, sdpa_kernel
from torch.nn.attention.varlen import varlen_attn
activate_flash_attention_impl("FA3")
S, H, D, MIN = 16384, 32, 128, 8 # total tokens, heads, head dim, min doc length
def doc_lens_decreasing(n): # sums to S: S/2, S/4, ..., last two equal; floored at MIN
lens, rem = [], S
for i in range(n - 1):
lens.append(min(max(MIN, rem // 2), rem - MIN * (n - 1 - i)))
rem -= lens[-1]
return lens + [rem]
def doc_lens_equal(n):
return [S // n] * n
def rand(*shape):
return torch.randn(*shape, device="cuda", dtype=torch.bfloat16, requires_grad=True)
def varlen(backend): # same packed q/k/v and cu_seqlens for both backends; only the kernel differs
def setup(lens):
q, k, v = (rand(S, H, D) for _ in range(3))
cu = torch.tensor([0] + lens, device="cuda").cumsum(0, dtype=torch.int32)
def fwd():
with sdpa_kernel([backend], set_priority=True):
return varlen_attn(q, k, v, cu, cu, max(lens), max(lens), window_size=(-1, 0))
return fwd
return setup
fa3, cudnn = varlen(SDPBackend.FLASH_ATTENTION), varlen(SDPBackend.CUDNN_ATTENTION)
def peak_mb(setup, lens):
fwd = None
try:
fwd = setup(lens)
fwd().sum().backward() # warmup
torch.cuda.synchronize(); base = torch.cuda.memory_allocated(); torch.cuda.reset_peak_memory_stats()
fwd().sum().backward()
torch.cuda.synchronize()
return f"{(torch.cuda.max_memory_allocated() - base) / 2**20:.1f}"
except (torch.OutOfMemoryError, RuntimeError) as e: # cuDNN/cuda OOM can surface as a plain RuntimeError
if isinstance(e, RuntimeError) and "out of memory" not in str(e).lower():
raise
return "OOM"
finally:
fwd = None; gc.collect(); torch.cuda.empty_cache()
print("decreasing doc lens")
print(f"max_seqlen={S} heads={H}\n{'num_docs':>10} {'FA3 MiB':>10} {'cuDNN MiB':>10}")
for n in [1, 2, 4, 8, 16, 32, 128, 512, 1024]:
print(f"{n:>10} " + " ".join(f"{peak_mb(f, doc_lens_decreasing(n)):>10}" for f in (fa3, cudnn)), flush=True)
print("\n\nequal doc lens")
print(f"max_seqlen={S} heads={H}\n{'num_docs':>10} {'FA3 MiB':>10} {'cuDNN MiB':>10}")
for n in [1, 2, 4, 8, 16, 32, 128, 512, 1024]:
print(f"{n:>10} " + " ".join(f"{peak_mb(f, doc_lens_equal(n)):>10}" for f in (fa3, cudnn)), flush=True)Here's the result on a GH200:
decreasing doc lens
max_seqlen=16384 heads=32
num_docs FA3 MiB cuDNN MiB
1 906.0 902.0
2 906.1 902.0
4 908.1 1160.0
8 912.3 1676.0
16 920.5 2708.0
32 937.0 4772.0
128 1036.0 17156.1
512 1432.0 OOM
1024 1960.0 OOM
equal doc lens
max_seqlen=16384 heads=32
num_docs FA3 MiB cuDNN MiB
1 906.0 902.0
2 906.1 902.0
4 908.1 902.0
8 912.2 902.0
16 920.3 902.0
32 936.5 902.0
128 1034.0 902.1
512 1424.1 902.2
1024 1944.1 902.4
My env:
Package Version
---------------------- ------------------------
cuda-bindings 13.4.3
cuda-pathfinder 1.8.3
cuda-toolkit 13.0.3.0
einops 0.8.2
filelock 4.0.12
flash-attn-3 3.0.0
fsspec 2026.9.0
jinja2 3.1.6
markupsafe 3.0.3
mpmath 1.3.0
networkx 3.7
numpy 2.5.3
nvidia-cublas 13.1.1.3
nvidia-cuda-cccl 13.3.4.3.1
nvidia-cuda-cupti 13.0.85
nvidia-cuda-nvrtc 13.0.88
nvidia-cuda-runtime 13.0.96
nvidia-cudnn-cu13 9.26.0.51
nvidia-cufft 12.0.0.61
nvidia-cufile 1.15.1.6
nvidia-cusolver 12.0.4.66
nvidia-cusparse 12.6.3.3
nvidia-cusparselt-cu13 0.8.1
nvidia-nccl-cu13 2.30.7
nvidia-nvjitlink 13.4.92
nvidia-nvshmem-cu13 3.7.2
nvidia-nvtx 13.0.85
packaging 26.3
pillow 12.3.0
setuptools 78.1.0
sympy 1.14.0
torch 2.16.0.dev20261008+cu130
torchaudio 2.11.0.dev20261008+cu130
torchvision 0.30.0.dev20261008+cu130
triton 3.9.0+gitfc8d31a5
typing-extensions 4.16.0
There was a problem hiding this comment.
If you’d prefer to keep the cuDNN backend, I can switch to FlashAttention instead. Simply exposing the backend field is enough for me.
There was a problem hiding this comment.
thanks @francesco-bertolotti for the repro, i was able to see the same thing on gb200, turns out the reason is bc we didnt pass in the total token count so it was sizing the workspace per max seqlen. pytorch/pytorch#200847 should fix it if you want to checkout onto it and see if that fixes your problem?
either way, i am fine with exposing the backend field if you also want to make that change!
There was a problem hiding this comment.
Thanks for looking into this. I don’t think I’ll be able to check out your PR. Since the cuDNN backend should be fixed soon, it probably doesn’t make sense to make FA the default.
I would still expose the backend selection knob so that users can run varlen with different backends when needed, while keeping cuDNN as the default. Something along the lines of what was done here:
WDYT?
|
please rebase, thanks |
|
The CI errors seem to only occur on this PR @liangel-02 |
|
oh i think this needs an upstream fix, let me fix in pytorch/pytorch and then we can land this pr tmr |
|
@francesco-bertolotti this should be fixed upstream now do you mind rebasing to update pytorch nightlies |
|
Sorry to bother you again, is there something on my end blocking the merge? |
…5814) ## Summary `--print-config` crashes on main for every recipe that uses varlen attention, including `llama3_debugmodel`. #5152 put `SDPBackend` values (a pybind11 enum) into `VarlenInnerAttention.Config`, and `pprint` can't format them. This PR stores the backend names in the config instead and converts them to `SDPBackend` when the module is built, so the config stays plain data and the backend order is unchanged. I reproduced the crash on main with torch nightly, confirmed `--print-config` works with the fix, and checked that loss and grad_norm are bitwise identical over 20 steps on an L40. ## Why `--print-config` crashes on main for every recipe that uses varlen attention, which includes the default `llama3_debugmodel`. Since #5152, `VarlenInnerAttention.Config.sdpa_backends` holds `SDPBackend` values. `SDPBackend` is a pybind11 enum, and its `__repr__` is an `instancemethod`, which is unhashable. When an object does not fit on one line, `pprint` looks up `type(obj).__repr__` in a dict to pick a formatter, so formatting the backend list raises. At the config's nesting depth the list never fits on one line. **Example.** ``` $ python -m torchtitan.train --module torchtitan_recipes.tests.models.llama3 \ --config llama3_debugmodel --print-config ... File ".../pprint.py", line 181, in _format p = self._dispatch.get(type(object).__repr__, None) TypeError: unhashable type: 'instancemethod' ``` After this PR the same command prints the config and exits 0: ``` inner_attention=Config(sdpa_backends=['CUDNN_ATTENTION', 'FLASH_ATTENTION']), ``` The same field also makes `Config.to_dict()` (used by `debug.print_config` and `debug.save_config_file`) log "Config field value of type SDPBackend may not be JSON serializable" once per layer, 12 times for the debug model. ## What changed - `VarlenInnerAttention.Config.sdpa_backends` is now a list of `SDPBackend` member names (`Literal["CUDNN_ATTENTION", "FLASH_ATTENTION"]`, the two backends `varlen_attn` selects between). `VarlenInnerAttention.__init__` maps them to `SDPBackend` with `getattr`. The default order (cuDNN, then Flash) is unchanged. Sliding-window, Ulysses, and all-gather-KV varlen variants inherit the field and the conversion. - `test_varlen_attention.py`: mechanical update of the three places that set the field to `[SDPBackend.FLASH_ATTENTION]`. - New test `test_print_config_prints_and_exits` in `test_config_loader.py`. ## Alternatives considered - Print with `json.dumps(config.to_dict())` instead of `pprint`: loses the config class names, which is how implementations are selected, and still leaves a non-serializable value in the config. - Catch the `TypeError` in the loader: hides the problem for the next pybind value someone puts in a config. ## User-facing changes | Before | After | | --- | --- | | `sdpa_backends=[SDPBackend.FLASH_ATTENTION]` | `sdpa_backends=["FLASH_ATTENTION"]` | No in-repo recipe sets the field; only tests did. ## Numerics Bitwise-identical loss and grad_norm vs. base commit 0f34815 (`scripts/loss_compare.py 0f34815 c954ab5 --steps 20 --metrics loss,grad_norm --assert-equal`, `llama3_debugmodel`, seed checkpoint, deterministic). Measured at c954ab5 on 0f34815, before rebasing onto 22047b1 (#5745); the rebase only conflicted on the `typing` import line. | Config | GPUs | Result | | --- | --- | --- | | llama3_debugmodel, 20 steps | 1x L40 | loss and grad_norm bitwise identical at every step | ## Testing On 1x NVIDIA L40, torch 2.16.0.dev20261102+cu132, torchao 0.19.0.dev20261103, Python 3.12: | Check | main (0f34815) | this PR | | --- | --- | --- | | `--print-config` on `llama3_debugmodel` | TypeError, exit 1 | exit 0 | | `tests/unit_tests/gpu/models/common/test_varlen_attention.py` | 31 passed, 1 skipped | 31 passed, 1 skipped | CPU (torch 2.15.0, torchao 0.18.0, Python 3.13): `tests/unit_tests/cpu` 1843 passed, 139 skipped. 4 tests failed because they download from huggingface.co, which was unreachable from that machine; they fail the same way on main. `quantization/test_quantization.py` was excluded because it imports a module only in torchao nightly. On the L40 with the nightlies above, `test_config_loader.py` and the CPU `test_varlen_attention.py` pass (45 passed). The new test fails on main with the `TypeError` above and passes here. No existing test runs `--print-config`, which is why #5152 did not catch this. --------- Signed-off-by: Andrew Liu <[email protected]>
Pin varlen attention to Flash to avoid cuDNN backward OOM on packed batches
Problem
When no
sdpa_kernelpriority is set,torch.nn.attention.varlen.varlen_attndefaults to[CUDNN, FLASH]https://github.com/pytorch/pytorch/blob/7f758944c91946d1c7fbe69cc5cf60b1feba873c/torch/nn/attention/varlen.py#L49-L53
Is there a particular reason for moving away from flash attn? In my tests on GH200 cudnn is far more memory hungry than flash.
Regular SDPA uses a different order (
[FLASH, EFFICIENT, MATH, CUDNN, ...]).VarlenInnerAttentionnever set a priority, so every causal(-1, 0)layer ran on cuDNN. Sliding-window layers were already on Flash, because cuDNN rejects that window.Fix
VarlenInnerAttentionnow has asdpa_backends = [SDPBackend.FLASH_ATTENTION]class attribute and runsvarlen_attninsidesdpa_kernel(self.sdpa_backends, set_priority=True). This mirrorsScaledDotProductInnerAttention. The backward reuses the backend chosen in the forward, so it runs on Flash as well.