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.

ROCm: qdec_hip on by default with a safe fallback; opt-in side stream for the unfolded shared expert

YanissAmz95c1fbbc3b5a
diff --git a/doc/env_vars.md b/doc/env_vars.md
index 88faca5..db23e92 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -1233,7 +1233,7 @@ rows of K and V with the same arithmetic and packed plane layout as the PyTorch
`tests/test_qwrite.py`). The fallback needs ~70 launches per layer (decode append 402 us, 4096-row prefill chunk 5.2 ms at
K/V 6,6 per layer; native 17 us / 89 us). `0` restores the fallback.
-#### `EXL3_QDEC_HIP` (default `0`; ROCm gfx11.5)
+#### `EXL3_QDEC_HIP` (default `1`; ROCm gfx11.5)
HIP counterpart of `EXL3_QDEC` for AMD (Strix Halo): a wave32 WMMA kernel (`attention_fn/qdec.hip`, compiled with hipcc at first
use and cached under `~/.cache/exllamav3`) that dequantizes the packed K/V pages straight into the WMMA operands, plus a small
@@ -1243,6 +1243,14 @@ Tuning knobs for A/B work: `EXL3_QDEC_HIP_NW` (waves per CTA, default 4), `EXL3_
`EXL3_QDEC_HIP_WAVES` (target resident waves for the split count), `EXL3_QDEC_HIP_SPL` (fixed split count),
`EXL3_QDEC_HIP_MAXO` (accumulator budget per lane, default 96).
+#### `EXL3_SHARED_SIDE` (default `0`; ROCm)
+
+Batch-1 MoE decode with a shared expert that is not folded into the routed launch (Flint: shared expert K=6, I=1024; the fold needs
+K=4 and the routed shape): the shared expert's GEMVs, which do not depend on the routed experts, run on a side stream with their
+own GEMV scratch/counters while the routed kernels run on the main one, and are joined at the shared add. Bit-identical results
+(same kernels, tests/gate_kv.py KL 0), Flint 4K / 32K decode +4..5 % (tests/ab_decode.py, alternating windows in one process).
+`EXL3_DEC_MIN_BLOCKS` (default 32; read per call) at 512 adds about 1.5 % on Flint (more blocks for its small GEMVs).
+
#### `EXL3_PREFILL_WIDE` (default `1`)
Models with sliding-window attention only and a fused MoE (Flint): prompts that fit are prefilled in one pass, in
diff --git a/exllamav3/modules/attention_fn/qdec_hip.py b/exllamav3/modules/attention_fn/qdec_hip.py
index b6e2a4b..c5f3d1c 100644
--- a/exllamav3/modules/attention_fn/qdec_hip.py
+++ b/exllamav3/modules/attention_fn/qdec_hip.py
@@ -4,7 +4,7 @@ at first use with hipcc to an hsaco cached on disk, launched through the HIP mod
qdec_combine reduces them, rotates the result back with h32 and writes the fp16 output, so one call replaces the Triton split +
combine pair of triton_paged._paged_attn_decode_split_kernel for QCK > 0 and QCV > 0 with full (non-windowed) attention and no softcap.
make_cfg returns None for call shapes outside what the kernel covers; the caller then keeps the Triton kernels.
-Switch: EXL3_QDEC_HIP=0/1 (see ENABLED).
+Switch: EXL3_QDEC_HIP=0/1 (see ENABLED; default on for ROCm).
"""
import ctypes
import hashlib
@@ -15,7 +15,7 @@ import torch
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qdec.hip")
_CACHE = os.path.expanduser(os.environ.get("EXL3_QDEC_CACHE", "~/.cache/exllamav3"))
-ENABLED = bool(torch.version.hip) and os.environ.get("EXL3_QDEC_HIP", "0") != "0"
+ENABLED = bool(torch.version.hip) and os.environ.get("EXL3_QDEC_HIP", "1") != "0"
_kernels = {}
_bufs = {}
_lib = None
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index 9f528a8..bd6aacc 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -1135,6 +1135,13 @@ def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, so
max_k_len = block_table.shape[1] * k_cache.shape[1] + kv_append_len
if max_kv_len is not None:
max_k_len = min(max_k_len, max_kv_len + kv_append_len)
+ try:
+ _qh.get_kernel(cfg, q.device) # first use compiles with hipcc: a missing compiler or a build error keeps the Triton kernels
+ except Exception as exc: # noqa: BLE001
+ global _QDEC_HIP
+ _QDEC_HIP = False
+ print(f"qdec_hip: disabled, the Triton decode kernels stay ({type(exc).__name__}: {str(exc)[-300:]})", flush = True)
+ return None
if out is None:
out = torch.empty_like(q)
with torch.cuda.device(q.device):
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index 8cdb480..2fbbbdc 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -190,6 +190,17 @@ class FusedBuffers:
temp_intermediate_u: torch.Tensor
+_SHARED_SIDE_HIP = bool(torch.version.hip) # EXL3_SHARED_SIDE=1 is read per call (A/B inside one process)
+_side_state: dict = {}
+
+
+def _side(device):
+ st = _side_state.get(device)
+ if st is None:
+ st = _side_state[device] = (torch.cuda.Stream(device = device), torch.cuda.Event(), torch.cuda.Event())
+ return st
+
+
@dataclass
class HIPGroupedBuffers:
gu_had: torch.Tensor
@@ -1987,6 +1998,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
if os.environ.get("BSZ_DEBUG"):
print(f"[bsz_debug] layer={self.key} bsz={bsz} union={os.environ.get('EXL3_DEC_MOE_UNION')}")
bc_sh_exp = False
+ side_y = None
# R-row union MoE with the unique-expert table built on device (no host sync),
# fed by the batched router -- independent of EXL3_DEC_MOE_UNION's bit-exact per-row loops
union_dev = os.environ.get("EXL3_DEC_MOE_UNION_DEV", "0") != "0"
@@ -2119,6 +2131,21 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
self.latent_out is None and self.routed_post_norm is None and (shf or not self.shared_experts) and
cpu_partial is None and cpu_pending is None and not self.tp_reduce and out_dtype is None
)
+ if (
+ _SHARED_SIDE_HIP and os.environ.get("EXL3_SHARED_SIDE", "0") != "0" and not shf and self.shared_experts is not None and isinstance(self.shared_experts, GatedMLP) and
+ self.shared_gate is None and self.shared_experts_post_norm is None and cpu_partial is None and cpu_pending is None and
+ not self.tp_reduce and not self.routed_post_norm
+ ):
+ # batch-1 decode: the shared expert's three small GEMVs do not depend on the routed experts, run them on a side
+ # stream (own GEMV scratch/counters) while the routed kernels occupy the main one; joined at the shared add below
+ from .quant.exl3 import dec_side_workspace
+ side, ev_in, ev_out = _side(y.device)
+ ev_in.record(torch.cuda.current_stream(y.device))
+ with torch.cuda.stream(side):
+ side.wait_event(ev_in)
+ with dec_side_workspace():
+ side_y = self.shared_experts.forward(x, {**params, "moe_valu": True} if _MOE_VALU else params)
+ ev_out.record(side)
if shf:
ext.exl3_dec_moe_shared(
y,
@@ -2840,7 +2867,13 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
else:
ext.add_sigmoid_gate(yh.float(), z.float(), final_hidden_states)
elif self.shared_experts and not bc_sh_exp:
- y = self.shared_experts.forward(x, {**params, "moe_valu": True} if _MOE_VALU else params)
+ if side_y is not None:
+ cur = torch.cuda.current_stream(final_hidden_states.device)
+ cur.wait_event(_side(final_hidden_states.device)[2])
+ side_y.record_stream(cur)
+ y = side_y
+ else:
+ y = self.shared_experts.forward(x, {**params, "moe_valu": True} if _MOE_VALU else params)
if pre_norm_reduce:
params["backend"].all_reduce(y, True)
if self.shared_experts_post_norm:
diff --git a/exllamav3/modules/quant/exl3.py b/exllamav3/modules/quant/exl3.py
index 623795a..0a3b81f 100644
--- a/exllamav3/modules/quant/exl3.py
+++ b/exllamav3/modules/quant/exl3.py
@@ -240,10 +240,22 @@ DEC_SCRATCH_FLOATS = 2 << 20
_dec_workspaces: dict = {}
+_dec_side = [False]
+
+
+class dec_side_workspace:
+ """Context: dec_workspace() hands out a second scratch/counter pair, for GEMVs that run on a side stream concurrently with
+ launches that use the main pair (the pair is shared only among stream-ordered launches)."""
+ def __enter__(self):
+ _dec_side[0] = True
+ def __exit__(self, *a):
+ _dec_side[0] = False
+
+
def dec_workspace(device: torch.device):
"""fp32 scratch (cross-block partial sums) + int32 arrival counters, one pair per device. The
kernels leave the counters zeroed; all launches share them because they are stream-ordered."""
- key = str(device)
+ key = str(device) + ("#side" if _dec_side[0] else "")
ws = _dec_workspaces.get(key)
if ws is None:
ws = (torch.zeros(DEC_SCRATCH_FLOATS, dtype = torch.float, device = device),
diff --git a/tests/gate_cmp.py b/tests/gate_cmp.py
index d59ba7c..ed96eb1 100644
--- a/tests/gate_cmp.py
+++ b/tests/gate_cmp.py
@@ -10,7 +10,8 @@ for i, (r, n) in enumerate(zip(R["res"], N["res"])):
top2 = r["lp"][div].float().topk(2); msg += f" (ref top1-top2 logprob gap {float(top2.values[0] - top2.values[1]):.3f}; ref tok {g[div]} new tok {h[div]})"
p, q = r["lp"].float(), n["lp_forced"].float()
m = min(len(p), len(q)); p, q = p[:m], q[:m]
- kl = (p.exp() * (p - q)).sum(-1)
+ pe = p.exp()
+ kl = torch.where(pe > 0, pe * (p - q), torch.zeros_like(p)).sum(-1) # masked vocabulary (-inf in both) contributes 0
agree = (p.argmax(-1) == q.argmax(-1)).float().mean().item()
msg += f" | TF top1 agree {agree * 100:.1f}% KL mean {kl.mean().item():.2e} max {kl.max().item():.2e} steps {m}"
print(msg)