GeezerVison is showing github.com — fix(attention): fall back when sdpa-flash rejects GQA inputs · CortexLM/hypertrain@03a3f7d
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file 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 number | Diff line number | Diff line change |
|---|
@@ -33,7 +33,7 @@ peak, tokens/s, per-step times, `rank_peak_mem_gib` (whole round), `rank_step_pe | 33 | 33 | |------|--------|--------| | 34 | 34 | | `--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). | | 35 | 35 | | `--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. | | 37 | 37 | | `--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. | | 38 | 38 | | `--micro-batch N` | Overrides the profile's per-rank micro_batch. | Part of the run; recorded as `HT_MFU_MICRO_BATCH`. | | 39 | 39 | | `--nccl-pcie` | setdefaults `NCCL_P2P_DISABLE=1`, Ring, Simple, 4-8 channels, 8 MiB buffers. | Collectives are copies: no numeric effect. | | |
Collapse file Copy file name to clipboardExpand all lines: src/hypertrain/trainer/attention.py +70-4Lines changed: 70 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 13 | 13 | The math path keeps the explicit K/V expansion: a broadcast (native-GQA) math path differs from it | 14 | 14 | by 1 ulp in dK for some shapes, so it cannot be the bitwise oracle. Native GQA lives in the fused | 15 | 15 | 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. | 16 | 22 | """ | 17 | 23 |
| 18 | 24 | from __future__ import annotations | 19 | 25 |
| | 26 | +import logging | 20 | 27 | import math | 21 | 28 | import os | 22 | 29 | from typing import Literal | 23 | 30 |
| 24 | 31 | import torch | 25 | 32 | import torch.nn.functional as F | 26 | 33 | from torch import Tensor | | 34 | +from torch.nn.attention import SDPBackend, sdpa_kernel | | 35 | + | | 36 | +log = logging.getLogger(__name__) | 27 | 37 |
| 28 | 38 | Backend = Literal["math", "sdpa-flash", "flash-attn"] | 29 | 39 | BACKENDS: tuple[Backend, ...] = ("sdpa-flash", "flash-attn", "math") | | 34 | 44 | ((12, 0), "2.14.0+cu130"): "sdpa-flash", | 35 | 45 | } | 36 | 46 |
| | 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 | + | 37 | 54 | _MASKS: dict[tuple[int, torch.device], Tensor] = {} | 38 | 55 |
| 39 | 56 |
| @@ -57,15 +74,64 @@ def select_backend(device: torch.device) -> Backend: | 57 | 74 | return QUALIFIED_BACKENDS.get((cap, torch.__version__), "math") | 58 | 75 |
| 59 | 76 |
| | 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 | + | 60 | 116 | def attention(q: Tensor, k: Tensor, v: Tensor, backend: Backend = "math") -> Tensor: | 61 | 117 | """Causal attention. q [b, h, t, hd]; k, v [b, kvh, t, hd] with h % kvh == 0.""" | 62 | 118 | b, h, t, hd = q.shape | 63 | 119 | kvh = k.shape[1] | 64 | 120 | 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) | 69 | 135 | if backend == "flash-attn": | 70 | 136 | from flash_attn import flash_attn_func # type: ignore[import-not-found] | 71 | 137 |
| |
Collapse file Copy file name to clipboardExpand all lines: tests/trainer/test_attention.py +69Lines changed: 69 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 4 | 4 |
| 5 | 5 | import math | 6 | 6 | import os | | 7 | +from collections.abc import Callable | | 8 | +from typing import Any | 7 | 9 |
| 8 | 10 | import pytest | 9 | 11 |
| | 12 | 14 | # isort: split | 13 | 15 | import torch | 14 | 16 |
| | 17 | +from hypertrain.trainer import attention as A | 15 | 18 | from hypertrain.trainer.attention import Backend, attention, select_backend | 16 | 19 |
| 17 | 20 |
| @@ -74,3 +77,69 @@ def test_backward_bitwise() -> None: | 74 | 77 | from scripts.attention_spike import spike | 75 | 78 |
| 76 | 79 | 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 |
|