GeezerVison is showing github.com — fix(attention): serve only the qualified flash kernel under sdpa-flash · CortexLM/hypertrain@7b23f99
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: src/hypertrain/trainer/attention.py +26-29Lines changed: 26 additions & 29 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 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 | 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. | | 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. | 22 | 23 | """ | 23 | 24 |
| 24 | 25 | from __future__ import annotations | | 44 | 45 | ((12, 0), "2.14.0+cu130"): "sdpa-flash", | 45 | 46 | } | 46 | 47 |
| 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") | 50 | 50 | _NO_KERNEL = ("No available kernel", "No viable backend") # CUDA / CPU dispatcher messages | 51 | 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 | 52 |
| 54 | 53 | _MASKS: dict[tuple[int, torch.device], Tensor] = {} | 55 | 54 |
| @@ -75,29 +74,31 @@ def select_backend(device: torch.device) -> Backend: | 75 | 74 |
| 76 | 75 |
| 77 | 76 | 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"): | 80 | 78 | g = q.shape[1] // k.shape[1] | 81 | 79 | 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]): | 83 | 81 | return F.scaled_dot_product_attention( | 84 | 82 | q, k, v, is_causal=True, enable_gqa=k.shape[1] != q.shape[1] | 85 | 83 | ) | 86 | 84 |
| 87 | 85 |
| 88 | 86 | @torch.compiler.assume_constant_result # HT_COMPILE=1 traces the cached choice, not the probe | 89 | 87 | 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 | + """ | 91 | 92 | key = (device, dtype, group, hd) | 92 | 93 | if key in _PATHS: | 93 | 94 | return _PATHS[key] | 94 | | - path = "math" | | 95 | + path = "" | 95 | 96 | # Grad enabled: training constraints apply, and no_grad replay must pick the same path. | 96 | 97 | # Identity hooks keep the probe's saved tensors out of an enclosing HT_ACT_CKPT checkpoint. | 97 | 98 | with torch.enable_grad(), torch.autograd.graph.saved_tensors_hooks(lambda x: x, lambda x: x): | 98 | 99 | q = torch.zeros(1, group, 2, hd, device=device, dtype=dtype, requires_grad=True) | 99 | 100 | 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: | 101 | 102 | if group == 1 and candidate.endswith("+expanded-kv"): | 102 | 103 | continue | 103 | 104 | try: | @@ -108,30 +109,26 @@ def _path(device: torch.device, dtype: torch.dtype, group: int, hd: int) -> str: | 108 | 109 | continue | 109 | 110 | path = candidate | 110 | 111 | break | | 112 | + if not path: | | 113 | + raise RuntimeError( | | 114 | + f"sdpa-flash: no flash path accepts {device} {dtype} group {group} head dim {hd}" | | 115 | + ) | 111 | 116 | _PATHS[key] = path | 112 | 117 | log.warning("attention backend: %s (%s %s, group %d, hd %d)", path, device, dtype, group, hd) | 113 | 118 | return path | 114 | 119 |
| 115 | 120 |
| | 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 | + | 116 | 126 | def attention(q: Tensor, k: Tensor, v: Tensor, backend: Backend = "math") -> Tensor: | 117 | 127 | """Causal attention. q [b, h, t, hd]; k, v [b, kvh, t, hd] with h % kvh == 0.""" | 118 | 128 | b, h, t, hd = q.shape | 119 | 129 | kvh = k.shape[1] | 120 | 130 | 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) | 135 | 132 | if backend == "flash-attn": | 136 | 133 | from flash_attn import flash_attn_func # type: ignore[import-not-found] | 137 | 134 |
| |
Collapse file Copy file name to clipboardExpand all lines: tests/trainer/test_attention.py +28-23Lines changed: 28 additions & 23 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -92,32 +92,40 @@ def sdpa(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, **kw: Any) -> torch. | 92 | 92 | return sdpa | 93 | 93 |
| 94 | 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 | 95 | 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 | 104 | 97 | ) -> None: | 105 | 98 | calls: list[bool] = [] | 106 | 99 | 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)) | 108 | 101 | g = torch.Generator().manual_seed(0) | 109 | 102 | q, k, v = (torch.randn(2, n, 33, 16, generator=g) for n in (8, 2, 2)) | 110 | 103 | with caplog.at_level("WARNING", logger=A.__name__): | 111 | 104 | first = attention(q, k, v, "sdpa-flash") | 112 | 105 | probed = list(calls) | 113 | 106 | 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"] | 117 | 111 | assert torch.equal(first, second) | 118 | 112 | assert (first - attention(q, k, v)).abs().max() < 1e-5 | 119 | 113 |
| 120 | 114 |
| | 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 | + | 121 | 129 | @pytest.mark.parametrize("dt", [torch.float32, torch.bfloat16]) | 122 | 130 | @pytest.mark.parametrize("h,kvh", [(8, 2), (8, 1)]) | 123 | 131 | 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 | 129 | 137 | assert (native.float() - expanded.float()).abs().max() < tol | 130 | 138 |
| 131 | 139 |
| 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", {}) | 136 | 142 | g = torch.Generator().manual_seed(0) | 137 | 143 | q, k = (torch.randn(2, n, 33, 16, generator=g) for n in (8, 2)) | 138 | 144 | 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 | + ) |
|