GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(attention): fall back when sdpa-flash rejects GQA inputs · CortexLM/hypertrain@03a3f7d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs
    • mfu-multigpu.md
  • src/hypertrain/trainer
    • attention.py
  • tests/trainer
    • test_attention.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/mfu-multigpu.md‎

Copy file name to clipboardExpand all lines: docs/mfu-multigpu.md
+1-1Lines changed: 1 addition & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ peak, tokens/s, per-step times, `rank_peak_mem_gib` (whole round), `rank_step_pe
3333
|------|--------|--------|
3434
| `--reduction zero2o` | Gradients reduced to their ZeRO-2 owner in buckets issued from post-accumulate grad hooks, so communication overlaps the rest of backward. | Bitwise equal to `zero2` (same adds, same order). |
3535
| `--act-ckpt` (`HT_ACT_CKPT=1`) | Per-layer activation checkpointing. | Same kernels on recompute: bitwise equal. |
36-
| sdpa-flash | Selected on (sm_120, torch 2.14.0+cu130) from the qualification record in `tests/trainer/data/attn_qualify_sm120.json`. | Qualified by cross-process equality. |
36+
| sdpa-flash | Selected on (sm_120, torch 2.14.0+cu130) from the qualification record in `tests/trainer/data/attn_qualify_sm120.json`. When the flash kernel rejects the inputs (dtype, head dim, `enable_gqa`), the first accepting path of `attention.PATHS` is probed once per (device, dtype, group, head dim) and logged as `attention backend: <path>`; inputs whose layout the chosen kernel still rejects use math. | Qualified by cross-process equality (flash path only). A fallback path is a function of hardware, torch and geometry, so ranks agree, but it is not qualified. |
3737
| `--compile` (`HT_COMPILE=1`) | One Inductor graph per layer. | Leaves differ from eager (fusion changes rounding), so a compiled run replays only under the same flag. Both modes replay bitwise. |
3838
| `--micro-batch N` | Overrides the profile's per-rank micro_batch. | Part of the run; recorded as `HT_MFU_MICRO_BATCH`. |
3939
| `--nccl-pcie` | setdefaults `NCCL_P2P_DISABLE=1`, Ring, Simple, 4-8 channels, 8 MiB buffers. | Collectives are copies: no numeric effect. |
Collapse file

‎src/hypertrain/trainer/attention.py‎

Copy file name to clipboardExpand all lines: src/hypertrain/trainer/attention.py
+70-4Lines changed: 70 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,27 @@
1313
The math path keeps the explicit K/V expansion: a broadcast (native-GQA) math path differs from it
1414
by 1 ulp in dK for some shapes, so it cannot be the bitwise oracle. Native GQA lives in the fused
1515
backends (enable_gqa / flash-attn MQA), which never materialise expanded K/V.
16+
17+
sdpa-flash is a chain, not one kernel: the flash kernel rejects fp32 and some head dims (and
18+
enable_gqa narrows it further), so the first of PATHS whose kernel accepts the inputs is used. The
19+
choice is probed once per (device, dtype, q heads per kv head, head dim), cached, and logged once;
20+
it is a pure function of hardware, torch build and model geometry, so ranks and reruns on the
21+
same hardware take the same path and stay bitwise equal.
1622
"""
1723

1824
from __future__ import annotations
1925

26+
import logging
2027
import math
2128
import os
2229
from typing import Literal
2330

2431
import torch
2532
import torch.nn.functional as F
2633
from torch import Tensor
34+
from torch.nn.attention import SDPBackend, sdpa_kernel
35+
36+
log = logging.getLogger(__name__)
2737

2838
Backend = Literal["math", "sdpa-flash", "flash-attn"]
2939
BACKENDS: tuple[Backend, ...] = ("sdpa-flash", "flash-attn", "math")
@@ -34,6 +44,13 @@
3444
((12, 0), "2.14.0+cu130"): "sdpa-flash",
3545
}
3646

47+
# sdpa-flash fallback order; "+expanded-kv" repeats K/V heads and calls SDPA without enable_gqa.
48+
PATHS = ("flash", "mem-efficient", "flash+expanded-kv", "mem-efficient+expanded-kv", "math")
49+
_KERNELS = {"flash": SDPBackend.FLASH_ATTENTION, "mem-efficient": SDPBackend.EFFICIENT_ATTENTION}
50+
_NO_KERNEL = ("No available kernel", "No viable backend") # CUDA / CPU dispatcher messages
51+
_PATHS: dict[tuple[torch.device, torch.dtype, int, int], str] = {}
52+
_REJECTED: set[tuple[str, torch.device, torch.dtype]] = set() # real-call rejections, logged once
53+
3754
_MASKS: dict[tuple[int, torch.device], Tensor] = {}
3855

3956

@@ -57,15 +74,64 @@ def select_backend(device: torch.device) -> Backend:
5774
return QUALIFIED_BACKENDS.get((cap, torch.__version__), "math")
5875

5976

77+
def _sdpa(path: str, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
78+
kernel, _, expanded = path.partition("+")
79+
if expanded:
80+
g = q.shape[1] // k.shape[1]
81+
k, v = k.repeat_interleave(g, 1), v.repeat_interleave(g, 1)
82+
with sdpa_kernel([_KERNELS[kernel]]):
83+
return F.scaled_dot_product_attention(
84+
q, k, v, is_causal=True, enable_gqa=k.shape[1] != q.shape[1]
85+
)
86+
87+
88+
@torch.compiler.assume_constant_result # HT_COMPILE=1 traces the cached choice, not the probe
89+
def _path(device: torch.device, dtype: torch.dtype, group: int, hd: int) -> str:
90+
"""First of PATHS whose kernel accepts these inputs, probed once on tiny zero tensors."""
91+
key = (device, dtype, group, hd)
92+
if key in _PATHS:
93+
return _PATHS[key]
94+
path = "math"
95+
# Grad enabled: training constraints apply, and no_grad replay must pick the same path.
96+
# Identity hooks keep the probe's saved tensors out of an enclosing HT_ACT_CKPT checkpoint.
97+
with torch.enable_grad(), torch.autograd.graph.saved_tensors_hooks(lambda x: x, lambda x: x):
98+
q = torch.zeros(1, group, 2, hd, device=device, dtype=dtype, requires_grad=True)
99+
kv = torch.zeros(1, 1, 2, hd, device=device, dtype=dtype, requires_grad=True)
100+
for candidate in PATHS[:-1]:
101+
if group == 1 and candidate.endswith("+expanded-kv"):
102+
continue
103+
try:
104+
_sdpa(candidate, q, kv, kv)
105+
except RuntimeError as e:
106+
if not str(e).startswith(_NO_KERNEL):
107+
raise
108+
continue
109+
path = candidate
110+
break
111+
_PATHS[key] = path
112+
log.warning("attention backend: %s (%s %s, group %d, hd %d)", path, device, dtype, group, hd)
113+
return path
114+
115+
60116
def attention(q: Tensor, k: Tensor, v: Tensor, backend: Backend = "math") -> Tensor:
61117
"""Causal attention. q [b, h, t, hd]; k, v [b, kvh, t, hd] with h % kvh == 0."""
62118
b, h, t, hd = q.shape
63119
kvh = k.shape[1]
64120
if backend == "sdpa-flash":
65-
from torch.nn.attention import SDPBackend, sdpa_kernel
66-
67-
with sdpa_kernel([SDPBackend.FLASH_ATTENTION]):
68-
return F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=kvh != h)
121+
path = _path(q.device, q.dtype, h // kvh, hd)
122+
if path != "math":
123+
try:
124+
return _sdpa(path, q, k, v)
125+
except RuntimeError as e:
126+
# The probe sees contiguous tiny tensors; this call's layout (e.g. a last-dim
127+
# stride != 1) can still be rejected. Not cached: the path stays a function of
128+
# the inputs, not of call order. ponytail: straight to math, not the next of
129+
# PATHS; walk PATHS if a production shape ever lands here.
130+
if not str(e).startswith(_NO_KERNEL):
131+
raise
132+
if (path, q.device, q.dtype) not in _REJECTED:
133+
_REJECTED.add((path, q.device, q.dtype))
134+
log.warning("attention backend: %s rejected %s, using math", path, e)
69135
if backend == "flash-attn":
70136
from flash_attn import flash_attn_func # type: ignore[import-not-found]
71137

Collapse file

‎tests/trainer/test_attention.py‎

Copy file name to clipboardExpand all lines: tests/trainer/test_attention.py
+69Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
import math
66
import os
7+
from collections.abc import Callable
8+
from typing import Any
79

810
import pytest
911

@@ -12,6 +14,7 @@
1214
# isort: split
1315
import torch
1416

17+
from hypertrain.trainer import attention as A
1518
from hypertrain.trainer.attention import Backend, attention, select_backend
1619

1720

@@ -74,3 +77,69 @@ def test_backward_bitwise() -> None:
7477
from scripts.attention_spike import spike
7578

7679
assert spike(torch.device("cuda", int(os.environ["HT_GENUINE_CUDA_INDEX"])))["chosen"]
80+
81+
82+
def _sdpa_raising(when: Callable[[bool], bool], calls: list[bool]) -> Callable[..., torch.Tensor]:
83+
"""F.scaled_dot_product_attention raising the RTX 5090 error when when(enable_gqa)."""
84+
real = A.F.scaled_dot_product_attention
85+
86+
def sdpa(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, **kw: Any) -> torch.Tensor:
87+
calls.append(kw["enable_gqa"])
88+
if when(kw["enable_gqa"]):
89+
raise RuntimeError("No available kernel. Aborting execution.")
90+
return real(q, k, v, **kw)
91+
92+
return sdpa
93+
94+
95+
@pytest.mark.parametrize(
96+
"when,chosen",
97+
[(lambda gqa: gqa, "flash+expanded-kv"), (lambda gqa: True, "math")], # CPU: no mem-efficient
98+
)
99+
def test_fallback_probed_once_when_native_kernel_missing(
100+
monkeypatch: pytest.MonkeyPatch,
101+
caplog: pytest.LogCaptureFixture,
102+
when: Callable[[bool], bool],
103+
chosen: str,
104+
) -> None:
105+
calls: list[bool] = []
106+
monkeypatch.setattr(A, "_PATHS", {})
107+
monkeypatch.setattr(A.F, "scaled_dot_product_attention", _sdpa_raising(when, calls))
108+
g = torch.Generator().manual_seed(0)
109+
q, k, v = (torch.randn(2, n, 33, 16, generator=g) for n in (8, 2, 2))
110+
with caplog.at_level("WARNING", logger=A.__name__):
111+
first = attention(q, k, v, "sdpa-flash")
112+
probed = list(calls)
113+
second = attention(q, k, v, "sdpa-flash")
114+
assert probed[0] and len(probed) > 1 # native enable_gqa tried first, then fell back
115+
assert calls[len(probed) :] == ([] if chosen == "math" else [False]) # no re-probe
116+
assert [r.getMessage().split()[2] for r in caplog.records] == [chosen] # logged once
117+
assert torch.equal(first, second)
118+
assert (first - attention(q, k, v)).abs().max() < 1e-5
119+
120+
121+
@pytest.mark.parametrize("dt", [torch.float32, torch.bfloat16])
122+
@pytest.mark.parametrize("h,kvh", [(8, 2), (8, 1)])
123+
def test_expanded_kv_close_to_native_gqa(dt: torch.dtype, h: int, kvh: int) -> None:
124+
g = torch.Generator().manual_seed(h * 7 + kvh)
125+
q, k, v = (torch.randn(2, n, 33, 16, generator=g).to(dt) for n in (h, kvh, kvh))
126+
native = A._sdpa("flash", q, k, v)
127+
expanded = A._sdpa("flash+expanded-kv", q, k, v)
128+
tol = 2e-2 if dt == torch.bfloat16 else 1e-5
129+
assert (native.float() - expanded.float()).abs().max() < tol
130+
131+
132+
def test_layout_rejected_after_probe_falls_back_to_math(
133+
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
134+
) -> None:
135+
monkeypatch.setattr(A, "_REJECTED", set())
136+
g = torch.Generator().manual_seed(0)
137+
q, k = (torch.randn(2, n, 33, 16, generator=g) for n in (8, 2))
138+
v = torch.randn(2, 2, 16, 33, generator=g).transpose(-1, -2) # stride(-1) != 1: no fused kernel
139+
with caplog.at_level("WARNING", logger=A.__name__):
140+
assert A._path(q.device, q.dtype, 4, 16) == "flash" # the contiguous probe accepts flash
141+
for _ in range(2):
142+
assert torch.equal(attention(q, k, v, "sdpa-flash"), attention(q, k, v))
143+
contiguous = attention(q, k, v.contiguous(), "sdpa-flash")
144+
assert torch.equal(contiguous, A._sdpa("flash", q, k, v.contiguous())) # rejection not cached
145+
assert sum("rejected" in r.getMessage() for r in caplog.records) == 1

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.