Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

HIP GDN prefill: blocked-GQA pairing in the HF chunk kernel, no q / k duplication copy (EXL3_GDN_BLOCKED_KERNEL) (#220)

Yaniss Amazouz28fe094ca376
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index b998621..d5ee872 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -1916,7 +1916,13 @@ class GatedDeltaNet(Module):
# Delta rule
_nk, _kd, _mq = self.num_k_heads, self.k_dim, mixed_qkv
- if self.blocked_gqa and not self.kda:
+ # EXL3_GDN_BLOCKED_KERNEL (default 1 with ROCm): chunk prefill of blocked-GQA files without the q / k duplication copy
+ # (302 MB per GDN layer per 8K chunk on the 35B-A3B GGUF): the HIP HF kernel pairs v head h with q / k head h % H; any
+ # other chunk path duplicates inside vendor/fla (bit-equal)
+ _blk = (self.blocked_gqa and not self.kda and seqlen >= self.num_v_heads and not save_history
+ and os.environ.get("EXL3_GDN_BLOCKED_KERNEL", "1" if torch.version.hip else "0") == "1"
+ and os.environ.get("EXL3_GDN_PF", "1") == "1" and _mq.dim() == 3)
+ if self.blocked_gqa and not self.kda and not _blk:
# Blocked pairing for grouped-v files: duplicate q/k heads
# blocked ([q,q] not interleaved) AFTER the depthwise conv and
# run the rule plain (nk == nv, no repeat). Bitwise vs repeat
@@ -1946,6 +1952,7 @@ class GatedDeltaNet(Module):
params = params,
channelwise_g = self.kda,
g_cumsum = g_cumsum,
+ blocked_gqa = _blk,
)
if ck is not None:
params.pop("kda_ckpt")
diff --git a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py
index 6ddfa4d..8324664 100644
--- a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py
+++ b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py
@@ -104,7 +104,9 @@ def gated_delta_rule_fn(
channelwise_g: bool = False,
g_cumsum: bool = False,
recurrent_base: torch.Tensor = None,
+ blocked_gqa: bool = False,
):
+ # blocked_gqa: q / k hold num_k_heads < num_v_heads heads paired blocked with v (chunk prefill path only, see vendor/fla)
# g_cumsum: g already holds fla's chunk-local cumsum (EXL3_KDA_G_FUSED); only valid on the chunk path
if params is None:
params = {}
@@ -208,8 +210,9 @@ def gated_delta_rule_fn(
core_attn, new_state = chunk_gated_delta_rule_pf(
q[i:i + 1], k[i:i + 1], v[i:i + 1], g = g[i:i + 1], beta = beta[i:i + 1],
initial_state = state, output_final_state = save_state,
- ckpt = params.get("kda_ckpt") if bsz == 1 else None)
+ ckpt = params.get("kda_ckpt") if bsz == 1 else None, blocked = blocked_gqa)
else:
+ assert not blocked_gqa, "blocked_gqa needs the EXL3_GDN_PF chunk path"
core_attn, new_state = chunk_gated_delta_rule(
q[i:i + 1], k[i:i + 1], v[i:i + 1],
g = g[i:i + 1],
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index d1fefc9..8d99c74 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -116,10 +116,28 @@ def chunk_gated_delta_rule(
return o.to(q.dtype), final_state
-def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None, output_final_state=False, ckpt=None):
+def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None, output_final_state=False, ckpt=None, blocked=False):
"""chunk_gated_delta_rule(use_qk_l2norm_in_kernel=True, chunk_size=64) for q, k, v given as (possibly strided) views of the conv
output; g (fp32) and beta (bf16) contiguous. Bitwise equal to the guarded entry; no copies of q, k, v when the views are plain
token-pitch slices."""
+ # blocked=True (EXL3_GDN_BLOCKED_KERNEL): q / k carry H < HV heads paired BLOCKED with v (v head h <-> q / k head h % H, the
+ # GGUF grouped-v layout). The HIP HF kernel reads them that way directly; every other path gets the same blocked
+ # duplication the caller used to make (bit-equal: same per-head data)
+ if blocked and q.shape[2] != v.shape[2]:
+ _r = v.shape[2] // q.shape[2]
+ if _gdn_pf.strided_ok(q) and _gdn_pf.strided_ok(k) and q.shape[-1] == 128 and q.dtype == torch.bfloat16:
+ from .hip.gdn_hf_hip import gdn_hf_ok, chunk_gdn_hf
+ with torch.cuda.device(q.device.index):
+ qn = _gdn_pf.l2norm_strided(q)
+ kn = _gdn_pf.l2norm_strided(k)
+ if gdn_hf_ok(q, v, qn, kn, g.contiguous(), beta.contiguous(), None if initial_state is None else initial_state.contiguous()):
+ sc = scale if scale is not None else q.shape[-1] ** -0.5
+ try:
+ return chunk_gdn_hf(q, v, qn, kn, g.contiguous(), beta.contiguous(), sc, initial_state, output_final_state, ckpt=ckpt, blocked=True)
+ except Exception as e:
+ print(f" -- EXL3_GDN_HF blocked failed, duplicated q / k for the rest of the process: {e}", flush=True)
+ q = torch.cat([q] * _r, dim = 2)
+ k = torch.cat([k] * _r, dim = 2)
if not (_gdn_pf.strided_ok(q) and _gdn_pf.strided_ok(k) and q.shape[-1] == 128 and q.dtype == torch.bfloat16):
return chunk_gated_delta_rule(q, k, v, g=g, beta=beta, scale=scale, initial_state=initial_state,
output_final_state=output_final_state, use_qk_l2norm_in_kernel=True)
diff --git a/exllamav3/vendor/fla/hip/gdn_hf.hip b/exllamav3/vendor/fla/hip/gdn_hf.hip
index 5221f96..e0883ef 100644
--- a/exllamav3/vendor/fla/hip/gdn_hf.hip
+++ b/exllamav3/vendor/fla/hip/gdn_hf.hip
@@ -74,7 +74,11 @@ extern "C" __global__ void gated_delta_chunk_gate_wmma(
) {
const int vh = blockIdx.x;
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4;
+#ifdef KYO_BLOCKED
+ const int kh = vh % key_heads; // blocked GQA pairing (GGUF grouped-v files): v head vh reads k head vh mod H
+#else
const int kh = vh / (value_heads / key_heads);
+#endif
const int v_offset = 2 * key_heads * 128 + vh * 128;
const int value_width = value_heads * 128;
const size_t state_base = (size_t)vh * 128 * 128;
diff --git a/exllamav3/vendor/fla/hip/gdn_hf_hip.py b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
index 12527d0..7e80c13 100644
--- a/exllamav3/vendor/fla/hip/gdn_hf_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
@@ -45,14 +45,14 @@ def _compile_tail(lines, n=12):
return out
-def _load(device=None):
+def _load(device=None, blocked=False):
dev = select_device(device)
- key = (dev, "")
+ key = (dev, "blocked" if blocked else "")
if key in _state:
return _state[key]
arch = device_arch(dev)
src = open(_SRC, "rb").read()
- flags = ["--genco", f"--offload-arch={arch}", "-O3", "-DKYO_RAW=1", *_gcc_flag()]
+ flags = ["--genco", f"--offload-arch={arch}", "-O3", "-DKYO_RAW=1", *(["-DKYO_BLOCKED=1"] if blocked else []), *_gcc_flag()]
tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"gdn_hf_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
@@ -107,11 +107,12 @@ def gdn_hf_ok(q_raw, v, qn, kn, g, beta, initial_state):
return ok
-def chunk_gdn_hf(q_raw, v, qn, kn, g, beta, scale, initial_state, output_final_state, ckpt=None):
+def chunk_gdn_hf(q_raw, v, qn, kn, g, beta, scale, initial_state, output_final_state, ckpt=None, blocked=False):
"""Returns (o [1, T, HV, 128] bf16, final_state or None). ckpt: None, a dict or a list of <= 8 dicts {"s": fp32 [1, HV, K, V]
- contiguous, "chunk": n} (gdn_fused_h_hip contract): the state after row 64 n is written to ck["s"] and ck["ok"] set."""
+ contiguous, "chunk": n} (gdn_fused_h_hip contract): the state after row 64 n is written to ck["s"] and ck["ok"] set.
+ blocked: v head vh pairs with q / k head vh % H (blocked GQA, GGUF grouped-v files) instead of vh // (HV / H)."""
try:
- fn = _load(v.device)
+ fn = _load(v.device, blocked)
except Exception:
_state["fail"] = True # no hipcc / no module: the Triton chain for the rest of the process
raise
diff --git a/tests/test_gdn_blocked.py b/tests/test_gdn_blocked.py
new file mode 100644
index 0000000..feebb3d
--- /dev/null
+++ b/tests/test_gdn_blocked.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""test_gdn_blocked.py (ROCm gfx11.5, needs the HIP HF kernel): chunk_gated_delta_rule_pf(blocked=True) on the conv-output row (q / k with H heads, blocked pairing)
+vs the old caller-side duplication cat([q]*r + [k]*r + [v]) then blocked=False. Output and final state must be torch.equal."""
+import os, sys, torch
+sys.path.insert(0, os.getcwd())
+from exllamav3.vendor.fla import chunk_gated_delta_rule_pf
+from exllamav3.vendor.fla.hip import gdn_hf_hip
+torch.manual_seed(0)
+dev = "cuda"
+ok_all = True
+for (H, HV, T) in ((8, 16, 4096), (16, 32, 8192), (16, 48, 2048), (8, 16, 777)):
+ K = V = 128; r = HV // H
+ C = 2 * H * K + HV * V
+ row = (torch.randn(1, T, C, device=dev) * 0.5).to(torch.bfloat16)
+ g = (-torch.rand(1, T, HV, device=dev) * 0.2).float()
+ beta = torch.sigmoid(torch.randn(1, T, HV, device=dev)).to(torch.bfloat16)
+ s0 = (torch.randn(1, HV, K, V, device=dev) * 0.05).float()
+ q = row[..., :H * K].view(1, T, H, K); k = row[..., H * K:2 * H * K].view(1, T, H, K); v = row[..., 2 * H * K:].view(1, T, HV, V)
+ o1, f1 = chunk_gated_delta_rule_pf(q, k, v, g, beta, initial_state=s0.clone(), output_final_state=True, blocked=True)
+ dup = torch.cat([row[..., :H * K]] * r + [row[..., H * K:2 * H * K]] * r + [row[..., 2 * H * K:]], dim=-1).contiguous()
+ q2 = dup[..., :HV * K].view(1, T, HV, K); k2 = dup[..., HV * K:2 * HV * K].view(1, T, HV, K); v2 = dup[..., 2 * HV * K:].view(1, T, HV, V)
+ o2, f2 = chunk_gated_delta_rule_pf(q2, k2, v2, g, beta, initial_state=s0.clone(), output_final_state=True, blocked=False)
+ torch.cuda.synchronize()
+ eo, es = torch.equal(o1, o2), torch.equal(f1, f2)
+ ok_all &= eo and es
+ print(f"H {H} HV {HV} T {T}: out equal {eo} state equal {es} max|do| {(o1.float() - o2.float()).abs().max().item():.3g} "
+ f"hf calls {gdn_hf_hip._state.get('calls')}", flush=True)
+ # timing: blocked vs dup incl. the cat copy
+ for name, fn in (("blocked", lambda: chunk_gated_delta_rule_pf(q, k, v, g, beta, initial_state=s0.clone(), output_final_state=True, blocked=True)),
+ ("dup+cat", lambda: chunk_gated_delta_rule_pf(*(lambda d: (d[..., :HV * K].view(1, T, HV, K), d[..., HV * K:2 * HV * K].view(1, T, HV, K), d[..., 2 * HV * K:].view(1, T, HV, V)))(
+ torch.cat([row[..., :H * K]] * r + [row[..., H * K:2 * H * K]] * r + [row[..., 2 * H * K:]], dim=-1)), g, beta, initial_state=s0.clone(), output_final_state=True))):
+ for _ in range(2): fn()
+ torch.cuda.synchronize(); e0 = torch.cuda.Event(enable_timing=True); e1 = torch.cuda.Event(enable_timing=True); e0.record()
+ for _ in range(5): fn()
+ e1.record(); torch.cuda.synchronize(); print(f" {name}: {e0.elapsed_time(e1) / 5:.2f} ms", flush=True)
+print("PASS" if ok_all else "FAIL")