Repository navigation
Description
Describe the bug
On H800 (sm90), DotProductAttention with qkv_format="thd" and head_dim=256 runs the cuDNN FusedAttention
backend for training and returns wrong gradients when the cuDNN that TE loads is 9.14.0: dQ/dK/dV are about 20%
off an fp32 reference with MHA (16 / 16 heads), and dK is about 6x off with GQA (16 query / 4 KV heads). The forward
output is correct, nothing is raised and no NaN appears in the minimal case, so training continues with silently
corrupted attention gradients.
The same calls are correct with FlashAttention 3, with qkv_format="bshd", with head_dim=128, and with the same
TE 2.18 when TE loads cuDNN 9.28.1.
TE 2.18 allows FusedAttention for training at head_dim <= 256 on sm90 for any cuDNN >= 9.5 ("9.5: <= 256 + Hopper +
bprop" in transformer_engine/common/fused_attn/fused_attn.cpp) and prefers it over FlashAttention on Hopper
("Disabling FlashAttention to give FusedAttention preference on Hopper+ for performance reasons" in
dot_product_attention/utils.py), so this is the default path. The head_dim=256 backward tests in
tests/pytorch/attention/test_attention.py run on SM100/SM103 only, so the Hopper path does not seem to be covered.
Possibly related: #2448 (THD + GQA + head_dim 256, wrong dK/dV on H100 with TE 2.13 / cuDNN 9.11, attributed in that
thread to the caching allocator reusing the fused-attention workspace). Differences here: MHA is affected as well
(including dQ), and the result changes with the cuDNN version alone (same TE, same script, same allocation order:
wrong with 9.14.0, correct with 9.28.1). We have not tried the torch.cuda.empty_cache() workaround from that thread.
Steps/Code to reproduce bug
te_attn_bwd_repro.py (below; TE + PyTorch only, random inputs) builds b=2 equal-length causal sequences of 2048
tokens, runs DotProductAttention forward and backward in bf16, and compares the output and dQ/dK/dV with plain
PyTorch attention in fp32 (||x - ref|| / ||ref||). One process per backend (TE caches its choice):
NVTE_FUSED_ATTN=1 NVTE_FLASH_ATTN=0 NVTE_UNFUSED_ATTN=0 python3 te_attn_bwd_repro.py # cuDNN FusedAttention
NVTE_FUSED_ATTN=0 NVTE_FLASH_ATTN=1 NVTE_UNFUSED_ATTN=0 python3 te_attn_bwd_repro.py # FlashAttentionTHD uses attn_mask_type="padding_causal" with cu_seqlens_q == cu_seqlens_kv = [0, 2048, 4096]; BSHD uses
attn_mask_type="causal". With NVTE_DEBUG=1 NVTE_DEBUG_LEVEL=1 TE logs
Running with FusedAttention backend (sub-backend 1) for the fused runs. The first output line shows the cuDNN TE
actually loaded. Excerpt of the fused run with cuDNN 9.14.0:
{"gpu": "NVIDIA H800", "te": "2.18.0", "torch": "2.13.0+cu130", "cudnn": "9.14.0", "env": {"NVTE_FUSED_ATTN": "1", "NVTE_FLASH_ATTN": "0"}}
{"format": "thd", "head_dim": 128, "heads": 16, "kv_heads": 4, "batch": 2, "seqlen": 2048, "out": 0.002043, "dq": 0.002481, "dk": 0.002982, "dv": 0.002867, "nan_inf": 0}
{"format": "thd", "head_dim": 256, "heads": 16, "kv_heads": 16, "batch": 2, "seqlen": 2048, "out": 0.002034, "dq": 0.1975, "dk": 0.1965, "dv": 0.1733, "nan_inf": 0}
{"format": "thd", "head_dim": 256, "heads": 16, "kv_heads": 4, "batch": 2, "seqlen": 2048, "out": 0.00204, "dq": 0.1997, "dk": 6.213, "dv": 0.256, "nan_inf": 0}
{"format": "bshd", "head_dim": 256, "heads": 16, "kv_heads": 4, "batch": 2, "seqlen": 2048, "out": 0.00204, "dq": 0.002456, "dk": 0.002969, "dv": 0.002877, "nan_inf": 0}
Relative error vs fp32 (bf16 level is about 2.5e-3; "ok" = at that level):
| format | head_dim | heads / KV heads | FusedAttention, cuDNN 9.14.0: out / dQ / dK / dV | FusedAttention, cuDNN 9.28.1 | FlashAttention 3 |
|---|---|---|---|---|---|
| thd | 128 | 16 / 16 | 0.0020 / 0.0025 / 0.0025 / 0.0023 | – | ok |
| thd | 128 | 16 / 4 | 0.0020 / 0.0025 / 0.0030 / 0.0029 | – | ok |
| thd | 256 | 16 / 16 | 0.0020 / 0.198 / 0.197 / 0.173 | 0.0020 / 0.0025 / 0.0025 / 0.0023 | ok |
| thd | 256 | 16 / 4 | 0.0020 / 0.200 / 6.21 / 0.256 | 0.0020 / 0.0025 / 0.0030 / 0.0029 | ok |
| bshd | 128 | 16 / 16 and 16 / 4 | ok | – | ok |
| bshd | 256 | 16 / 16 and 16 / 4 | ok | ok | ok |
No NaN/inf in any of these runs.
To run the same check with cuDNN 9.28.1 in the same container, TE has to be pointed at it (installing the pip
package alone is not enough, see Environment details):
pip install --no-deps nvidia-cudnn-cu13==9.28.1.4
SP=$(python3 -c "import site; print(site.getsitepackages()[0])")
export CUDNN_HOME=$SP/nvidia/cudnn CUDNN_PATH=$SP/nvidia/cudnn LD_LIBRARY_PATH=$SP/nvidia/cudnn/lib:$LD_LIBRARY_PATH
NVTE_FUSED_ATTN=1 NVTE_FLASH_ATTN=0 NVTE_UNFUSED_ATTN=0 python3 te_attn_bwd_repro.py # first line now shows "cudnn": "9.28.1"te_attn_bwd_repro.py (TE + PyTorch only, random inputs)
#!/usr/bin/env python3
"""Minimal check of TransformerEngine DotProductAttention gradients against an fp32 reference.
Random bf16 inputs, b equal-length causal sequences, no project code. For each config it prints the relative
error (||x - ref|| / ||ref||) of the output and of dQ / dK / dV against plain PyTorch attention in fp32, the
NaN/inf count, and which backend TE picked (NVTE_DEBUG=1 logs it). Pick the backend with the environment, one
process per backend (TE caches its choice):
NVTE_FUSED_ATTN=1 NVTE_FLASH_ATTN=0 NVTE_UNFUSED_ATTN=0 python te_attn_bwd_repro.py # cuDNN fused attention
NVTE_FUSED_ATTN=0 NVTE_FLASH_ATTN=1 NVTE_UNFUSED_ATTN=0 python te_attn_bwd_repro.py # FlashAttention
Expected for bf16: output and gradients within about 1e-2 of the reference, no NaN.
"""
from __future__ import annotations
import itertools
import json
import os
import torch
DEV, DT = "cuda", torch.bfloat16
def reference(q, k, v):
"""fp32 causal attention; q [b, s, h, d], k/v [b, s, g, d] -> [b, s, h*d]."""
h, g = q.shape[2], k.shape[2]
k, v = k.repeat_interleave(h // g, 2), v.repeat_interleave(h // g, 2)
s = torch.einsum("bqhd,bkhd->bhqk", q, k) / q.shape[-1] ** 0.5
mask = torch.ones(q.shape[1], k.shape[1], dtype=torch.bool, device=q.device).tril()
p = s.masked_fill(~mask, float("-inf")).softmax(-1)
return torch.einsum("bhqk,bkhd->bqhd", p, v).reshape(q.shape[0], q.shape[1], -1)
def rel(a, b):
return ((a.float() - b.float()).norm() / b.float().norm().clamp_min(1e-30)).item()
def bad(t):
return int((~torch.isfinite(t.float())).sum().item())
def run(fmt, d, h, g, b, s):
import transformer_engine.pytorch as te
torch.manual_seed(0)
q = torch.randn(b, s, h, d, device=DEV, dtype=DT, requires_grad=True)
k = torch.randn(b, s, g, d, device=DEV, dtype=DT, requires_grad=True)
v = torch.randn(b, s, g, d, device=DEV, dtype=DT, requires_grad=True)
do = torch.randn(b, s, h * d, device=DEV, dtype=DT)
attn = te.DotProductAttention(num_attention_heads=h, kv_channels=d, num_gqa_groups=g, attention_dropout=0.0,
qkv_format=fmt)
if fmt == "thd":
cu = torch.arange(0, (b + 1) * s, s, dtype=torch.int32, device=DEV)
o = attn(q.reshape(b * s, h, d), k.reshape(b * s, g, d), v.reshape(b * s, g, d), attn_mask_type="padding_causal",
cu_seqlens_q=cu, cu_seqlens_kv=cu, max_seqlen_q=s, max_seqlen_kv=s).reshape(b, s, h * d)
else: # bshd
o = attn(q, k, v, attn_mask_type="causal").reshape(b, s, h * d)
o.backward(do)
got = {"out": o.detach(), "dq": q.grad, "dk": k.grad, "dv": v.grad}
qf, kf, vf = (t.detach().float().requires_grad_(True) for t in (q, k, v))
of = reference(qf, kf, vf)
of.backward(do.float())
ref = {"out": of.detach(), "dq": qf.grad, "dk": kf.grad, "dv": vf.grad}
return {n: float(f"{rel(got[n], ref[n]):.3e}") for n in got} | {"nan_inf": sum(bad(t) for t in got.values())}
def main():
import transformer_engine as te_pkg
try:
from transformer_engine.pytorch.utils import get_cudnn_version
cudnn = ".".join(map(str, get_cudnn_version()))
except Exception:
cudnn = str(torch.backends.cudnn.version())
print(json.dumps({"gpu": torch.cuda.get_device_name(0), "te": te_pkg.__version__, "torch": torch.__version__,
"cudnn": cudnn, "env": {k: os.environ.get(k) for k in ("NVTE_FUSED_ATTN", "NVTE_FLASH_ATTN")}}),
flush=True)
b, s = int(os.environ.get("REPRO_B", 2)), int(os.environ.get("REPRO_S", 2048))
dims = tuple(int(x) for x in os.environ.get("REPRO_HEAD_DIMS", "128,256").split(","))
for fmt, d, (h, g) in itertools.product(("thd", "bshd"), dims, ((16, 16), (16, 4))):
cfg = {"format": fmt, "head_dim": d, "heads": h, "kv_heads": g, "batch": b, "seqlen": s}
try:
print(json.dumps(cfg | run(fmt, d, h, g, b, s)), flush=True)
except Exception as e: # e.g. no backend for this config with the forced backend
print(json.dumps(cfg | {"error": repr(e)[:200]}), flush=True)
if __name__ == "__main__":
main()Expected behavior
Correct gradients, or TE not selecting FusedAttention for training with THD + head_dim 256 on sm90 when the loaded
cuDNN has this problem (for example a minimum-version check like the existing "Known cuDNN < 9.26 issue" guards),
plus a Hopper head_dim 256 THD backward test.
Environment overview (please complete the following information)
- Environment location: Docker image, run with Enroot/Pyxis (
srun --container-image) on a Slurm cluster; one H800 for the repro. - Method of Transformer Engine install: preinstalled in the public image
slimerl/slime:nightly-dev-20261027a-cu130(sha256:2a7437aa771ddcd5928054d4a143a5ac1a10776ead3cf7d641b93dbec51371f4); we did not install TE ourselves. - Docker equivalent:
docker pull slimerl/slime:nightly-dev-20261027a-cu130, thendocker run --gpus all -v $PWD:/w -w /w slimerl/slime:nightly-dev-20261027a-cu130 bash -c "NVTE_FUSED_ATTN=1 NVTE_FLASH_ATTN=0 NVTE_UNFUSED_ATTN=0 python3 te_attn_bwd_repro.py".
Environment details
- OS version: the image's (tag and digest above)
- PyTorch version: 2.13.0+cu130
- Python version: 3.12
- Transformer Engine version: 2.18.0
- CUDA version: 13 (PyTorch cu130 build)
- CUDNN version: TE loads 9.14.0, the image's system package
libcudnn9-cuda-13 9.14.0.64-1(apt-held) in
/usr/lib/x86_64-linux-gnu. PyTorch in the same process uses the pip packagenvidia-cudnn-cu13 9.20.0.48
(torch.backends.cudnn.version()= 92000).CUDNN_HOME/CUDNN_PATHare unset andCUDA_HOME=/usr/local/cuda
has no cuDNN, so TE's loader (system first, pip only as a fallback) takes the older system copy, without a warning.
Device details
- GPU model: NVIDIA H800 (sm90), driver 580.178.04
Additional context
- In a larger THD test with sequences of 4096-8192 + 512-1024 tokens, the error concentrated at the end of each
sequence (dK/dV of the last tokens about 100% off), and a layout where a short query segment attends a longer key
segment (padding_causal_bottom_right,cu_seqlens_q != cu_seqlens_kv) additionally produced thousands of NaN in
dK. Both were correct with FlashAttention 3. - TE picks its cuDNN independently of PyTorch (
CUDNN_HOME,CUDNN_PATH,CUDA_HOME,CUDA_PATH,/usr/local/cuda,
then the dynamic linker, and the pip package only if none of these has one), so a process can silently run TE on an
older cuDNN than PyTorch. A warning when the two differ, or when the loaded cuDNN is below a known-good version for
the selected path, would have exposed this. - We have not bisected the first fixed cuDNN between 9.15 and 9.27 (9.20, the pip copy in the same image, is
untested); happy to run that if it helps place a gate. - Workarounds that gave correct gradients:
NVTE_FUSED_ATTN=0(FlashAttention 3), or pointing TE at cuDNN 9.28.1
(CUDNN_PATH/LD_LIBRARY_PATH). - Models with head_dim 256 full-attention layers (e.g. the Qwen3.5 family) trained with packed (THD) sequences on
Hopper with default settings (e.g. Megatron-Core--attention-backend auto) go through this path. We observed the
wrong gradients in direct TE calls with FusedAttention forced, not in a full training run. - Reported downstream to slime, whose image ships this combination: [Bug]
nightly-dev-20261027a-cu130: TE loads cuDNN 9.14, which gives wrong attention gradients for head_dim 256 with packed sequences on H800 THUDM/slime#2568.
Activity
dragonxia-ctrl commentedon Nov 28, 2026
Hi, I'd like to take this issue if nobody is working on it yet.
I traced the path on the current
main(37be77c). For F16/BF16,nvte_get_fused_attn_backend_v2()intransformer_engine/common/fused_attn/fused_attn.cppapplies only two explicit "known issue" gates (lines ~318-331) and then delegates the rest of the support query to cuDNN throughsupport_verdict_f16()->support_verdict<Backend::F16, Pass::Bwd, create_graph_f16_bwd>()ingraph_cache.h. There is no head-dimension gate left on this branch, so whether THD + head_dim=256 backward is allowed on sm90 is whatever the cuDNN graph build accepts. cuDNN 9.14 accepts the config and then computes wrong dQ/dK/dV with no error.The second half of the problem is coverage:
tests/pytorch/attention/test_attention.py:757-776documents the opposite matrix ("cuDNN FusedAttention D=256 bprop is supported on sm10x ...", THD support starting at cuDNN 9.25) and skips the whole D=256 backward family unless compute capability is (10, 0) or (10, 3). That is why the Hopper THD + 256 backward path has never been exercised.Plan, following the two existing gates in
fused_attn.cpp(thecudnn_runtime_version <= 91500CUDA-graph gate and the< 92600THD learnable-softmax gate):uses_ragged_stats),head_dim_qk == head_dim_v == 256on sm90 below the cuDNN version where the backward is correct, so the caller falls back to FlashAttention/unfused instead of getting silently wrong gradients.One question decides the shape of the fix: is the intended matrix "Hopper + THD + D=256 backward is supported from cuDNN 9.28", or "never supported on sm90"? That decides whether the gate is a version check or an architecture check.
I cannot reproduce on Hopper locally. I would land the gate plus the test and ask you to run the report's script on sm90 with both cuDNN versions in CI, or ask the reporter to confirm the boundary. I will open a draft PR early so the direction is visible. Could you assign this to me?