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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
MoE prefill: sum the sigmoid-gated shared expert in the grouped reduce (EXL3_SHGATE_REDUCE) (#166)
Yaniss Amazouzcdc749972b80
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cppindex ecbf80c..02ae020 100644--- a/exllamav3/exllamav3_ext/bindings.cpp+++ b/exllamav3/exllamav3_ext/bindings.cpp@@ -489,7 +489,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)py::arg("K_gu"), py::arg("K_down"), py::arg("gu_had"), py::arg("gu_out"),py::arg("down_out"), py::arg("expert_offsets"), py::arg("inverse_order"),py::arg("tiles"), py::arg("tile_count"),- py::arg("act_limit") = 0.0, py::arg("mcg") = false, py::arg("addend") = py::none());+ py::arg("act_limit") = 0.0, py::arg("mcg") = false, py::arg("addend") = py::none(),+ py::arg("addend_gate") = py::none());+ m.attr("EXL3_MPW_ADDEND_GATE") = 1; // exl3_moe_prefill_wmma takes addend_gate (sigmoid-gated shared expert summed in the reduce)m.def("exl3_moe_prefill_wmma_mixed", &exl3_moe_prefill_wmma_mixed, "exl3_moe_prefill_wmma_mixed");m.def("exl3_moe_prefill_gemm_test", &exl3_moe_prefill_gemm_test, "exl3_moe_prefill_gemm_test");m.def("exl3_dense_mpw2", &exl3_dense_mpw2, "exl3_dense_mpw2");diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuindex 2f85ea4..dd2bd6a 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu@@ -271,7 +271,8 @@ void mpw_reduce_had_kernelint top_k,int width,const half* __restrict__ addend,- int addend_rows+ int addend_rows,+ const float* __restrict__ addend_gate = nullptr){const int blocks = width / 128;@@ -301,11 +302,26 @@ void mpw_reduce_had_kernel// Shared-expert output (fp16 GEMM result) added in the epilogue (EXL3_NC2_SHARED_FUSE): the exact// fp16 -> fp32 widen and the single fp32 add of the `y.copy_(y_)` + `final += y` pair it replaces.// Rows past addend_rows (alignment dummies) skip it.+ // EXL3_SHGATE_REDUCE: a sigmoid-gated shared expert (Qwen3.8) adds float(a) * s[row], s = sigmoid(gate) in fp32:+ // one fp32 multiply then one fp32 add, unfused (__fmul_rn / __fadd_rn), the arithmetic of gr_pf.shgate_add+ // (enable_fp_fusion = False) that it replaces, applied to the same routed fp32 sum.if (addend && row < addend_rows){const half4 a = ((const half4*) (addend + row * width + blk * 128))[t];- sum.x += __low2float(a.x); sum.y += __high2float(a.x);- sum.z += __low2float(a.y); sum.w += __high2float(a.y);+ if (addend_gate)+ {+ // HIP maps __fmul_rn / __fadd_rn to plain operators and -ffp-contract=fast fuses them into an fma: the empty asm+ // makes each product an opaque value, so the add stays a separate rounding (shgate_add is unfused)+ const float g = addend_gate[row];+ float p0 = __low2float(a.x) * g, p1 = __high2float(a.x) * g, p2 = __low2float(a.y) * g, p3 = __high2float(a.y) * g;+ asm volatile("" : "+v"(p0), "+v"(p1), "+v"(p2), "+v"(p3));+ sum.x += p0; sum.y += p1; sum.z += p2; sum.w += p3;+ }+ else+ {+ sum.x += __low2float(a.x); sum.y += __high2float(a.x);+ sum.z += __low2float(a.y); sum.w += __high2float(a.y);+ }}((float4*) (output + row * width + blk * 128))[t] = sum;}@@ -1643,7 +1659,8 @@ void exl3_moe_prefill_wmmaat::Tensor& tile_count,double act_limit,bool mcg,- const c10::optional<at::Tensor>& addend+ const c10::optional<at::Tensor>& addend,+ const c10::optional<at::Tensor>& addend_gate){const at::cuda::OptionalCUDAGuard device_guard(A.device());@@ -1693,6 +1710,15 @@ void exl3_moe_prefill_wmmaadd_ptr = (const half*) ad.data_ptr();add_rows = ad.size(0);}+ const float* gate_ptr = nullptr;+ if (addend_gate.has_value())+ {+ const at::Tensor& ag = addend_gate.value();+ TORCH_CHECK(add_ptr, "exl3_moe_prefill_wmma: addend_gate needs addend");+ TORCH_CHECK(ag.dtype() == at::kFloat && ag.is_contiguous() && ag.numel() == add_rows && ag.device() == A.device(),+ "addend_gate must be fp32 [addend rows] contiguous");+ gate_ptr = (const float*) ag.data_ptr();+ }const int kern = mpw_kern(assignments, experts);const int slots = tile_slots(assignments, experts, kern);TORCH_CHECK(tiles.dtype() == at::kInt && tiles.numel() >= slots, "tiles too small");@@ -1750,7 +1776,7 @@ void exl3_moe_prefill_wmmaelsempw_reduce_had_kernel<<<CEIL_DIVIDE(rjobs, 8), 256, 0, stream>>>((const float*) down_out.data_ptr(), sel, (const float*) weights.data_ptr(), inv, P(down_svh),- (float*) output.data_ptr(), rows, top_k, H, add_ptr, add_rows);+ (float*) output.data_ptr(), rows, top_k, H, add_ptr, add_rows, gate_ptr);cuda_check(hipPeekAtLastError());}diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuhindex 28f5739..1da282c 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuh+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuh@@ -36,7 +36,8 @@ void exl3_moe_prefill_wmmaat::Tensor& tile_count, // int32 [1]double act_limit, // clamped SwiGLU limit, 0 = unclampedbool mcg, // trellis codebook: true = mcg, false = mul1- const c10::optional<at::Tensor>& addend // fp16 [<= rows, H] widened and added to output rows (shared expert), or none+ const c10::optional<at::Tensor>& addend, // fp16 [<= rows, H] widened and added to output rows (shared expert), or none+ const c10::optional<at::Tensor>& addend_gate = c10::nullopt // fp32 [addend rows]: add float(addend) * gate[row] (sigmoid-gated shared expert));// Mixed-K layer (no pruned experts) in one pipeline: E-length pointer tables, one gather/act/reduce pass, the two GEMMsdiff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex e5334cf..99f0a29 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -18,6 +18,7 @@ from .block_sparse_mlp_cpu import BlockSparseMLP_CPUfrom .moe_batch_recon import PAD_MAXfrom ..model.model_tp_alloc import TPAllocationfrom ..util import profile_opt+from ..util.knobs import knob_onfrom ..util.tensor import g_tensor_cache, buffered_interleaved_arangefrom .quant.exl3 import dec_workspacefrom ..util.row_inv import ROW_INV_MAX_ROWS, job_slices@@ -166,6 +167,10 @@ def _scatter_expert_count(flat_expert_local: torch.Tensor, num_bins: int) -> tor# inside the expert list), so the output is bit-identical to running the sub-chunks one after the other._MOE_ALIGN_CHUNK = int(os.environ.get("EXL3_MOE_ALIGN_CHUNK", "4096"))+# EXL3_SHGATE_REDUCE_LOG=1: print once when a prefill forward sums the gated shared expert in the reduce (A/B check)+_SHGATE_REDUCE_LOG = os.environ.get("EXL3_SHGATE_REDUCE_LOG", "0") == "1"+_shgate_reduce_seen = []+def _aligned_expert_layout(flat: torch.Tensor, num_tokens: int, top_k: int, num_experts: int, chunk: int):"""flat: (num_tokens * top_k) int64 expert ids, slot = token * top_k + k. Returns (order, sel_flat, dummy_tokens):@@ -2577,6 +2582,31 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):else:raise RuntimeError(f"EXL3_NC2_SHARED_FUSE: shared expert output {sh_add.dtype}, contiguous "f"{sh_add.is_contiguous()}: fp16 contiguous needed")+ # EXL3_SHGATE_REDUCE (default 1, read per call, needs the ext flag): a sigmoid-gated shared expert (Qwen3.8) is+ # summed in by the reduce epilogue as float(y) * sigmoid(z), the arithmetic of the tail EXL3_SHGATE_FUSE pass+ # (gr_pf.shgate_add: unfused fp32 multiply + add) on the same routed fp32 sum, so the fp32 output is not read+ # and rewritten by a second pass. Same inputs (the shared expert and its gate only read x), same tail+ # conditions. Bit-identical. 0 goes back to the tail pass.+ sh_gate = None+ sh_late = None+ if (sh_add is None and self.shared_experts and self.shared_gate is not None and num_tokens > 32 and+ not self.shared_experts_post_norm and not self.tp_reduce and+ self.routed_post_norm is None and self.latent_out is None and+ hasattr(ext, "EXL3_MPW_ADDEND_GATE") and knob_on("EXL3_SHGATE_REDUCE", "1") and+ os.environ.get("EXL3_SHGATE_FUSE", "1") != "0"):+ sh_params = {**params, "moe_valu": True} if _MOE_VALU else dict(params)+ sh_params["nc2_down_half"] = True+ yh = self.shared_experts.forward(x, sh_params)+ z = self.shared_gate.forward(x, params)+ if yh.dtype == torch.half and yh.is_contiguous() and z.dtype == torch.float and z.is_contiguous():+ sh_add = yh.view(num_tokens, self.hidden_size)+ sh_gate = torch.sigmoid(z).view(-1)+ if _SHGATE_REDUCE_LOG and not _shgate_reduce_seen:+ _shgate_reduce_seen.append(self.key)+ print(f" -- EXL3_SHGATE_REDUCE: gated shared expert summed in the reduce ({self.key}, {num_tokens} rows)")+ else:+ sh_late = (yh, z) # the tail fallback (add_sigmoid_gate), applied after the reduce+ bc_sh_exp = Trueext.exl3_moe_prefill_wmma(y_k, output, sel_k, rw_k, order, expert_count,self.multi_gate.ptrs_trellis, self.multi_gate.ptrs_suh, self.multi_gate.ptrs_svh,@@ -2588,7 +2618,10 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):down_out,ws["offsets"], ws["inverse"][:assignments], ws["tiles"], ws["tile_count"],float(self.act_limit), bool(self.wmma_mcg), sh_add,+ **({"addend_gate": sh_gate} if sh_gate is not None else {}),)+ if sh_late is not None:+ ext.add_sigmoid_gate(sh_late[0].float(), sh_late[1].float(), output[:num_tokens].view(eshape))final_hidden_states = output[:num_tokens].view(eshape)# Torch/C++/fused pathdiff --git a/exllamav3/util/knobs.py b/exllamav3/util/knobs.pyindex 18f45a4..8185fe7 100644--- a/exllamav3/util/knobs.py+++ b/exllamav3/util/knobs.py@@ -53,6 +53,7 @@ KNOBS = {"EXL3_QDEC_HIP_VPF": "1","EXL3_QDEC_HIP_SMM": "auto","EXL3_QDEC_HIP_FLAGS": "",+ "EXL3_SHGATE_REDUCE": "1",}_hooks: list = []diff --git a/tests/test_mpw_shgate_reduce.py b/tests/test_mpw_shgate_reduce.pynew file mode 100644index 0000000..9671129--- /dev/null+++ b/tests/test_mpw_shgate_reduce.py@@ -0,0 +1,151 @@+"""EXL3_SHGATE_REDUCE: the sigmoid-gated shared expert summed in the grouped MoE prefill reduce epilogue.++exl3_moe_prefill_wmma(..., addend = y, addend_gate = s) must be bit-identical to the unfused sequence the+Qwen3.8 MoE block ran before: exl3_moe_prefill_wmma(..., no addend) then gr_pf.shgate_add(out, y, s)+(out += float(y) * s, unfused fp32 multiply + add). Synthetic weights (packed random trellis states), no model.+Also checks the ungated addend path (GLM, EXL3_NC2_SHARED_FUSE) is unchanged, addend rows shorter than the+output (aligned-layout dummy rows), and the argument checks.++Run (ROCm, gfx115x/gfx12): PYTHONPATH=<repo> python -m pytest -q tests/test_mpw_shgate_reduce.py+"""+from __future__ import annotations++import os+import sys++import pytest+import torch++sys.path.insert(0, os.environ.get("EXL3_REPO", os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from hardware import require # noqa: E402+require("ext")+from exllamav3.ext import exllamav3_ext as ext # noqa: E402++DEV = "cuda:0"+H, I, TOPK, EXPERTS = 2560, 640, 10, 24 # Qwen3.8-Flash-Next expert shapes (N 640: the tail-block path)+++def _require():+ if not (torch.version.hip and torch.cuda.is_available()):+ pytest.skip("ROCm build / device not available")+ if not hasattr(ext, "EXL3_MPW_ADDEND_GATE"):+ pytest.skip("this build has no addend_gate")+ if not ext.exl3_gemv_supported(torch.cuda.current_device()):+ pytest.skip("exl3 kernels not supported on this device")+++def _ptrs(tensors):+ return torch.tensor([t.data_ptr() for t in tensors], dtype=torch.long, device=DEV)+++def _trellis(k, n, K, seed):+ gen = torch.Generator(device=DEV).manual_seed(seed)+ states = torch.randint(0, 1 << K, (k // 16, n // 16, 256), generator=gen, device=DEV, dtype=torch.int16)+ packed = torch.zeros((k // 16, n // 16, 16 * K), dtype=torch.int16, device=DEV)+ ext.pack_trellis(packed, states, K)+ g = torch.Generator(device=DEV).manual_seed(seed * 7 + 1)+ suh = (torch.randint(0, 2, (k,), generator=g, device=DEV) * 2 - 1).half()+ svh = (torch.randint(0, 2, (n,), generator=g, device=DEV) * 2 - 1).half()+ return packed, suh, svh+++def _weights(K, seed):+ proj = {"gate": [_trellis(H, I, K, seed + 1 + 97 * e) for e in range(EXPERTS)],+ "up": [_trellis(H, I, K, seed + 2 + 97 * e) for e in range(EXPERTS)],+ "down": [_trellis(I, H, K, seed + 3 + 97 * e) for e in range(EXPERTS)]}+ tabs = []+ for p in ("gate", "up", "down"):+ tabs += [_ptrs([t for t, _, _ in proj[p]]), _ptrs([s for _, s, _ in proj[p]]), _ptrs([v for _, _, v in proj[p]])]+ return proj, tabs+++def _run(x, sel, w, tabs, K, addend=None, gate=None):+ rows, topk = sel.shape+ A = rows * topk+ order = sel.reshape(-1).argsort(stable=True)+ count = torch.zeros(EXPERTS + 1, dtype=torch.long, device=DEV)+ count.scatter_add_(0, sel.reshape(-1), torch.ones(A, dtype=torch.long, device=DEV))+ gu_had = torch.empty((2 * A * H + 128 * H,), dtype=torch.half, device=DEV)+ gu_out = torch.empty((2 * A + 128, I), dtype=torch.half, device=DEV)+ out = torch.empty((rows, H), dtype=torch.float, device=DEV)+ kw = {}+ if addend is not None: kw["addend"] = addend+ if gate is not None: kw["addend_gate"] = gate+ ext.exl3_moe_prefill_wmma(+ x, out, sel, w, order, count, *tabs, float(K), float(K),+ gu_had[:2 * A * H].view(2 * A, H), gu_out, gu_had[:2 * A * H].view(torch.float).view(A, H),+ torch.empty(EXPERTS + 1, dtype=torch.long, device=DEV), torch.empty(A, dtype=torch.long, device=DEV),+ torch.empty(A // 64 + EXPERTS + 1, dtype=torch.int32, device=DEV), torch.empty(1, dtype=torch.int32, device=DEV),+ 0.0, False, **kw)+ torch.cuda.synchronize()+ return out+++def _inputs(rows, seed, add_rows=None):+ g = torch.Generator(device=DEV).manual_seed(seed)+ x = (torch.randn(rows, H, generator=g, device=DEV) * 0.35).half()+ sel = torch.stack([torch.randperm(EXPERTS, generator=g, device=DEV)[:TOPK] for _ in range(rows)]).to(torch.long)+ w = torch.rand(rows, TOPK, generator=g, device=DEV)+ w = (w / w.sum(dim=-1, keepdim=True)).contiguous()+ ar = rows if add_rows is None else add_rows+ y = (torch.randn(ar, H, generator=g, device=DEV) * 3.0).half()+ z = torch.randn(ar, 1, generator=g, device=DEV) * 2.0+ return x, sel, w, y, torch.sigmoid(z).view(-1).contiguous()++[email protected]("K", [2, 4])[email protected]("rows", [40, 333, 1024])+def test_gated_reduce_bit_identical(K, rows):+ _require()+ from exllamav3.modules.gated_delta_net_fn.gr_pf import shgate_add+ _, tabs = _weights(K, 500 + K)+ x, sel, w, y, s = _inputs(rows, rows * 3 + K)+ ref = _run(x, sel, w, tabs, K)+ shgate_add(ref, y, s)+ torch.cuda.synchronize()+ got = _run(x, sel, w, tabs, K, addend=y, gate=s)+ assert torch.isfinite(ref).all()+ assert torch.equal(got.view(torch.int32), ref.view(torch.int32)), \+ f"K={K} rows={rows}: max |d| {float((got - ref).abs().max()):.3e}"+ # torch form of the same arithmetic (what add_sigmoid_gate's fallback computes)+ ref2 = _run(x, sel, w, tabs, K)+ ref2.add_(y.float() * s.view(-1, 1))+ assert torch.equal(got.view(torch.int32), ref2.view(torch.int32))+++def test_gated_reduce_short_addend_rows():+ """Aligned layout: dummy rows past the addend rows get no shared term (gate not read there)."""+ _require()+ from exllamav3.modules.gated_delta_net_fn.gr_pf import shgate_add+ K, rows, real = 4, 300, 291+ _, tabs = _weights(K, 900)+ x, sel, w, y, s = _inputs(rows, 77, add_rows=real)+ ref = _run(x, sel, w, tabs, K)+ shgate_add(ref[:real], y, s)+ got = _run(x, sel, w, tabs, K, addend=y, gate=s)+ assert torch.equal(got.view(torch.int32), ref.view(torch.int32))+++def test_ungated_addend_unchanged():+ """GLM path (EXL3_NC2_SHARED_FUSE): addend without gate = out + float(y), as before."""+ _require()+ K, rows = 2, 200+ _, tabs = _weights(K, 1300)+ x, sel, w, y, _ = _inputs(rows, 5)+ ref = _run(x, sel, w, tabs, K)+ ref += y.float()+ got = _run(x, sel, w, tabs, K, addend=y)+ assert torch.equal(got.view(torch.int32), ref.view(torch.int32))+++def test_gate_argument_checks():+ _require()+ K, rows = 2, 64+ _, tabs = _weights(K, 1700)+ x, sel, w, y, s = _inputs(rows, 9)+ with pytest.raises(RuntimeError):+ _run(x, sel, w, tabs, K, gate=s) # gate without addend+ with pytest.raises(RuntimeError):+ _run(x, sel, w, tabs, K, addend=y, gate=s[:-1]) # wrong length+ with pytest.raises(RuntimeError):+ _run(x, sel, w, tabs, K, addend=y, gate=s.half()) # wrong dtype