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): serve only the qualified flash kernel under sdpa-flash · CortexLM/hypertrain@7b23f99

File tree

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

‎src/hypertrain/trainer/attention.py‎

Copy file name to clipboardExpand all lines: src/hypertrain/trainer/attention.py
+26-29Lines changed: 26 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,12 @@
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.
1616
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.
17+
sdpa-flash is the flash kernel only: with enable_gqa (the qualified path) or, when that is
18+
rejected, on K/V expanded to q heads. Nothing else is served under this name (no mem-efficient
19+
kernel, no math fallback): numerics outside the qualification record must stop the run, not
20+
change silently. The path is probed once per (device, dtype, q heads per kv head, head dim),
21+
cached and logged once; it is a pure function of hardware, torch build and model geometry, so
22+
ranks and reruns on the same hardware take the same path. chosen_paths() exposes it for evidence.
2223
"""
2324

2425
from __future__ import annotations
@@ -44,12 +45,10 @@
4445
((12, 0), "2.14.0+cu130"): "sdpa-flash",
4546
}
4647

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}
48+
# sdpa-flash paths, in order; "+expanded-kv" repeats K/V heads and calls SDPA without enable_gqa.
49+
PATHS = ("flash", "flash+expanded-kv")
5050
_NO_KERNEL = ("No available kernel", "No viable backend") # CUDA / CPU dispatcher messages
5151
_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
5352

5453
_MASKS: dict[tuple[int, torch.device], Tensor] = {}
5554

@@ -75,29 +74,31 @@ def select_backend(device: torch.device) -> Backend:
7574

7675

7776
def _sdpa(path: str, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
78-
kernel, _, expanded = path.partition("+")
79-
if expanded:
77+
if path.endswith("+expanded-kv"):
8078
g = q.shape[1] // k.shape[1]
8179
k, v = k.repeat_interleave(g, 1), v.repeat_interleave(g, 1)
82-
with sdpa_kernel([_KERNELS[kernel]]):
80+
with sdpa_kernel([SDPBackend.FLASH_ATTENTION]):
8381
return F.scaled_dot_product_attention(
8482
q, k, v, is_causal=True, enable_gqa=k.shape[1] != q.shape[1]
8583
)
8684

8785

8886
@torch.compiler.assume_constant_result # HT_COMPILE=1 traces the cached choice, not the probe
8987
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."""
88+
"""First of PATHS whose kernel accepts these inputs, probed once on tiny zero tensors.
89+
90+
Raises RuntimeError when none does (e.g. fp32): force HT_ATTN_BACKEND=math for such models.
91+
"""
9192
key = (device, dtype, group, hd)
9293
if key in _PATHS:
9394
return _PATHS[key]
94-
path = "math"
95+
path = ""
9596
# Grad enabled: training constraints apply, and no_grad replay must pick the same path.
9697
# Identity hooks keep the probe's saved tensors out of an enclosing HT_ACT_CKPT checkpoint.
9798
with torch.enable_grad(), torch.autograd.graph.saved_tensors_hooks(lambda x: x, lambda x: x):
9899
q = torch.zeros(1, group, 2, hd, device=device, dtype=dtype, requires_grad=True)
99100
kv = torch.zeros(1, 1, 2, hd, device=device, dtype=dtype, requires_grad=True)
100-
for candidate in PATHS[:-1]:
101+
for candidate in PATHS:
101102
if group == 1 and candidate.endswith("+expanded-kv"):
102103
continue
103104
try:
@@ -108,30 +109,26 @@ def _path(device: torch.device, dtype: torch.dtype, group: int, hd: int) -> str:
108109
continue
109110
path = candidate
110111
break
112+
if not path:
113+
raise RuntimeError(
114+
f"sdpa-flash: no flash path accepts {device} {dtype} group {group} head dim {hd}"
115+
)
111116
_PATHS[key] = path
112117
log.warning("attention backend: %s (%s %s, group %d, hd %d)", path, device, dtype, group, hd)
113118
return path
114119

115120

121+
def chosen_paths() -> list[str]:
122+
"""Distinct sdpa-flash paths this process has used, for run evidence."""
123+
return sorted(set(_PATHS.values()))
124+
125+
116126
def attention(q: Tensor, k: Tensor, v: Tensor, backend: Backend = "math") -> Tensor:
117127
"""Causal attention. q [b, h, t, hd]; k, v [b, kvh, t, hd] with h % kvh == 0."""
118128
b, h, t, hd = q.shape
119129
kvh = k.shape[1]
120130
if backend == "sdpa-flash":
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)
131+
return _sdpa(_path(q.device, q.dtype, h // kvh, hd), q, k, v)
135132
if backend == "flash-attn":
136133
from flash_attn import flash_attn_func # type: ignore[import-not-found]
137134

Collapse file

‎tests/trainer/test_attention.py‎

Copy file name to clipboardExpand all lines: tests/trainer/test_attention.py
+28-23Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -92,32 +92,40 @@ def sdpa(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, **kw: Any) -> torch.
9292
return sdpa
9393

9494

95-
@pytest.mark.parametrize(
96-
"when,chosen",
97-
[(lambda gqa: gqa, "flash+expanded-kv"), (lambda gqa: True, "math")], # CPU: no mem-efficient
98-
)
9995
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,
96+
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
10497
) -> None:
10598
calls: list[bool] = []
10699
monkeypatch.setattr(A, "_PATHS", {})
107-
monkeypatch.setattr(A.F, "scaled_dot_product_attention", _sdpa_raising(when, calls))
100+
monkeypatch.setattr(A.F, "scaled_dot_product_attention", _sdpa_raising(lambda gqa: gqa, calls))
108101
g = torch.Generator().manual_seed(0)
109102
q, k, v = (torch.randn(2, n, 33, 16, generator=g) for n in (8, 2, 2))
110103
with caplog.at_level("WARNING", logger=A.__name__):
111104
first = attention(q, k, v, "sdpa-flash")
112105
probed = list(calls)
113106
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
107+
assert probed[0] and len(probed) > 1 # native enable_gqa tried first, then expanded K/V
108+
assert calls[len(probed) :] == [False] # no re-probe
109+
assert [r.getMessage().split()[2] for r in caplog.records] == ["flash+expanded-kv"]
110+
assert A.chosen_paths() == ["flash+expanded-kv"]
117111
assert torch.equal(first, second)
118112
assert (first - attention(q, k, v)).abs().max() < 1e-5
119113

120114

115+
def test_no_flash_path_stops_instead_of_serving_another_kernel(
116+
monkeypatch: pytest.MonkeyPatch,
117+
) -> None:
118+
"""Only flash is qualified: no mem-efficient and no math fallback under the sdpa-flash name."""
119+
calls: list[bool] = []
120+
monkeypatch.setattr(A, "_PATHS", {})
121+
monkeypatch.setattr(A.F, "scaled_dot_product_attention", _sdpa_raising(lambda gqa: True, calls))
122+
q, k, v = (torch.randn(2, n, 33, 16) for n in (8, 2, 2))
123+
with pytest.raises(RuntimeError, match="no flash path"):
124+
attention(q, k, v, "sdpa-flash")
125+
assert A.PATHS == ("flash", "flash+expanded-kv")
126+
assert A._PATHS == {} # a refusal is not cached as a choice
127+
128+
121129
@pytest.mark.parametrize("dt", [torch.float32, torch.bfloat16])
122130
@pytest.mark.parametrize("h,kvh", [(8, 2), (8, 1)])
123131
def test_expanded_kv_close_to_native_gqa(dt: torch.dtype, h: int, kvh: int) -> None:
@@ -129,17 +137,14 @@ def test_expanded_kv_close_to_native_gqa(dt: torch.dtype, h: int, kvh: int) -> N
129137
assert (native.float() - expanded.float()).abs().max() < tol
130138

131139

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())
140+
def test_layout_rejected_after_probe_stops(monkeypatch: pytest.MonkeyPatch) -> None:
141+
monkeypatch.setattr(A, "_PATHS", {})
136142
g = torch.Generator().manual_seed(0)
137143
q, k = (torch.randn(2, n, 33, 16, generator=g) for n in (8, 2))
138144
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
145+
assert A._path(q.device, q.dtype, 4, 16) == "flash" # the contiguous probe accepts flash
146+
with pytest.raises(RuntimeError, match="No available kernel"):
147+
attention(q, k, v, "sdpa-flash") # no silent math: the run stops
148+
assert torch.equal(
149+
attention(q, k, v.contiguous(), "sdpa-flash"), A._sdpa("flash", q, k, v.contiguous())
150+
)

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.