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: fused routing-weighted top-k sum for the routed F16 prefill MoE (Gufo MoeEpilogueVec4Kernel), default on with ROCm on gfx1151 (#217)

Yaniss Amazouzbe2f2836dc83
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index bd049ed..c79bb3a 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -9,7 +9,7 @@ authors). Each file keeps its licence header and lists its changes. Gufo's MIT l
exllamav3/exllamav3_ext/rocm/routed_f16/ (routed F16-WMMA prefill MoE for HIP gfx1151) is adapted from Gufo (https://github.com/gufo-org/gufo,
commit 07e1191, src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp: RoutedPairF16Kernel, RoutedDownF16Kernel, RoutedPadBoundsKernel,
-RoutedScatterKernel and their device helpers, MIT License, Copyright (c) 2026 gufo contributors). The file keeps its licence header and lists
+RoutedScatterKernel and their device helpers, and MoeEpilogueVec4Kernel for fq_routed_f16_combine, MIT License, Copyright (c) 2026 gufo contributors). The file keeps its licence header and lists
its changes.
Parts of exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ and foreign_quant/fq_mmvq.cu are derived from
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 53dcf0c..b83ffd3 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -486,6 +486,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("fq_routed_f16_moe", &fq_routed_f16_moe, "fq_routed_f16_moe",
py::arg("x"), py::arg("ids"), py::arg("counts"), py::arg("tiles"), py::arg("gate_ptrs"), py::arg("up_ptrs"),
py::arg("down_ptrs"), py::arg("gate_fmt"), py::arg("down_fmt"), py::arg("I"), py::arg("out"));
+ m.def("fq_routed_f16_combine", &fq_routed_f16_combine, "fq_routed_f16_combine", py::arg("rows"), py::arg("weights"), py::arg("out"));
#endif
m.def("kda_gb_norm", &kda_gb_norm, "kda_gb_norm");
m.def("kda_inter_off", &kda_inter_off, "kda_inter_off");
diff --git a/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.cu b/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.cu
index 2f29571..c0bc937 100644
--- a/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.cu
+++ b/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.cu
@@ -9,6 +9,8 @@
// one contiguous [E, M, K] tensor; only the 128-token-tile kernels are kept; the host side is a torch op
// (fq_routed_f16_moe) that takes the tile list built by the caller. The kernel bodies are otherwise unchanged and depend
// on the gfx1151 (RDNA3.5, wave32) WMMA lane layout.
+// fq_routed_f16_combine is the routing-weighted top-k reduction of the down rows, after Gufo's MoeEpilogueVec4Kernel<__half> (same
+// kernels.hip.cpp; the shared-expert term is left to the caller): one pass in registers instead of torch's F32 broadcast multiply + sum.
#if defined(USE_ROCM)
#include <ATen/cuda/CUDAContext.h>
@@ -743,6 +745,30 @@ __global__ void RoutedScatterKernel(const std::int32_t* __restrict__ ids,
rows_token[c] = static_cast<std::int32_t>(slot / k);
rows_slot[c] = static_cast<std::int32_t>(slot);
}
+
+// out[t, i] (F32) = sum over s of weights[t, s] * float(rows[t, s, i]), s in order (Gufo MoeEpilogueVec4Kernel<__half>, without the shared
+// expert). Four adjacent lanes per thread, grid (T, ceil(K / (4 * kThreads))).
+__global__ void RoutedCombineKernel(const __half* __restrict__ rows, const float* __restrict__ weights, float* __restrict__ out,
+ std::uint32_t top_k, std::uint32_t dim) {
+ const std::uint32_t t = blockIdx.x;
+ const std::uint32_t i = (blockIdx.y * blockDim.x + threadIdx.x) * 4;
+ if (i >= dim) {
+ return;
+ }
+ float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
+ const __half* src = rows + static_cast<std::size_t>(t) * top_k * dim + i;
+ for (std::uint32_t s = 0; s < top_k; ++s) {
+ const float w = weights[static_cast<std::size_t>(t) * top_k + s];
+ const uint2 raw = *reinterpret_cast<const uint2*>(src + static_cast<std::size_t>(s) * dim);
+ const __half2 lo = *reinterpret_cast<const __half2*>(&raw.x);
+ const __half2 hi = *reinterpret_cast<const __half2*>(&raw.y);
+ a0 = __fadd_rn(a0, __fmul_rn(w, __low2float(lo)));
+ a1 = __fadd_rn(a1, __fmul_rn(w, __high2float(lo)));
+ a2 = __fadd_rn(a2, __fmul_rn(w, __low2float(hi)));
+ a3 = __fadd_rn(a3, __fmul_rn(w, __high2float(hi)));
+ }
+ *reinterpret_cast<float4*>(out + static_cast<std::size_t>(t) * dim + i) = float4{a0, a1, a2, a3};
+}
} // namespace
#endif
} // namespace kyo_routed_f16
@@ -804,4 +830,23 @@ void fq_routed_f16_moe(torch::Tensor x, torch::Tensor ids, torch::Tensor counts,
TORCH_CHECK(hipGetLastError() == hipSuccess, "fq_routed_f16_moe: launch failed");
}
+// out[t, :] (F32) = sum_s weights[t, s] * rows[t * top_k + s, :]; rows: half [T * top_k, K] (the fq_routed_f16_moe output), weights: float [T, top_k].
+void fq_routed_f16_combine(torch::Tensor rows, torch::Tensor weights, torch::Tensor out)
+{
+ using namespace kyo_routed_f16;
+ const at::cuda::OptionalCUDAGuard device_guard(rows.device());
+ TORCH_CHECK(rows.is_cuda() && rows.dim() == 2 && rows.is_contiguous() && rows.dtype() == torch::kHalf, "rows must be half [T * top_k, K]");
+ TORCH_CHECK(weights.is_cuda() && weights.dim() == 2 && weights.is_contiguous() && weights.dtype() == torch::kFloat, "weights must be float [T, top_k]");
+ const int64_t T = weights.size(0), top_k = weights.size(1), K = rows.size(1);
+ TORCH_CHECK(rows.size(0) == T * top_k && K % 4 == 0, "rows must be [T * top_k, K] with K % 4 == 0");
+ TORCH_CHECK(out.is_cuda() && out.is_contiguous() && out.dtype() == torch::kFloat && out.dim() == 2 && out.size(0) == T && out.size(1) == K,
+ "out must be float [T, K]");
+ if (T == 0) return;
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ hipLaunchKernelGGL(RoutedCombineKernel, dim3((unsigned) T, (unsigned) ((K / 4 + kThreads - 1) / kThreads)), dim3(kThreads), 0, stream,
+ (const __half *) rows.data_ptr(), (const float *) weights.data_ptr(), (float *) out.data_ptr(), (std::uint32_t) top_k,
+ (std::uint32_t) K);
+ TORCH_CHECK(hipGetLastError() == hipSuccess, "fq_routed_f16_combine: launch failed");
+}
+
#endif
diff --git a/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.h b/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.h
index 8b4c61a..f7b3af6 100644
--- a/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.h
+++ b/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.h
@@ -8,3 +8,7 @@
void fq_routed_f16_moe(torch::Tensor x, torch::Tensor ids, torch::Tensor counts, torch::Tensor tiles,
torch::Tensor gate_ptrs, torch::Tensor up_ptrs, torch::Tensor down_ptrs, int64_t gate_fmt,
int64_t down_fmt, int64_t I, torch::Tensor out);
+
+// out[t, :] (float) = sum_s weights[t, s] * rows[t * top_k + s, :], s in order (rows half [T * top_k, K], weights float [T, top_k]); the weighted
+// top-k reduction after fq_routed_f16_moe (Gufo MoeEpilogueVec4Kernel<__half> without the shared expert).
+void fq_routed_f16_combine(torch::Tensor rows, torch::Tensor weights, torch::Tensor out);
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index c3bb904..6b04eb7 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -230,6 +230,10 @@ _FQ_PF_GMMQ = os.environ.get("MCPM_FQ_PF_GMMQ", "1" if torch.version.hip else "0
# 10.6 -> 7.8 s, decode flat, greedy md5 identical, perplexity 3.5401 -> 3.5404. Rows >= MCPM_FQ_PF_ROUTED_F16_MIN (default 1024);
# fewer rows and other GPUs keep gmmq. 0 = gmmq.
_FQ_PF_ROUTED_F16 = os.environ.get("MCPM_FQ_PF_ROUTED_F16", "1" if torch.version.hip else "0") == "1"
+# MCPM_FQ_PF_ROUTED_F16_COMBINE=1: the routing-weighted top-k sum of the routed F16 down rows in one HIP kernel (Gufo's MoeEpilogueVec4Kernel,
+# rocm/routed_f16) instead of torch's F32 broadcast multiply (R x top_k x K floats) + sum. Default on with ROCm; gfx1151 only (the routed F16
+# path's gate). Strix Halo Flash-Next GGUF: 8K prefill 7.50 -> 7.10 s, 157K-token prompt first token 117-120 -> 107-108 s. 0 = torch sum.
+_FQ_PF_ROUTED_F16_COMBINE = os.environ.get("MCPM_FQ_PF_ROUTED_F16_COMBINE", "1" if torch.version.hip else "0") == "1"
_ROUTED_F16_ARCH = {}
@@ -2209,8 +2213,13 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
dn = torch.empty((R * top_k, K), dtype=torch.half, device=dev)
ext.fq_routed_f16_moe(y.to(torch.half).contiguous(), ids, counts.to(torch.int32), tiles, g_p, u_p, d_p,
G[fmts[0]], G[fmts[1]], I, dn)
- w = routing_weights.to(torch.float).reshape(R, top_k, 1)
- final_hidden_states = (dn.view(R, top_k, K) * w).sum(1).reshape(eshape)
+ if _FQ_PF_ROUTED_F16_COMBINE and hasattr(ext, "fq_routed_f16_combine") and K % 4 == 0:
+ final_hidden_states = torch.empty((R, K), dtype=torch.float, device=dev)
+ ext.fq_routed_f16_combine(dn, routing_weights.to(torch.float).reshape(R, top_k).contiguous(), final_hidden_states)
+ final_hidden_states = final_hidden_states.reshape(eshape)
+ else:
+ w = routing_weights.to(torch.float).reshape(R, top_k, 1)
+ final_hidden_states = (dn.view(R, top_k, K) * w).sum(1).reshape(eshape)
if self.shared_experts:
y_se = self.shared_experts.forward(x, {**params, "moe_valu": True} if _MOE_VALU else params)
if self.shared_gate:
diff --git a/tests/test_hip_routed_f16.py b/tests/test_hip_routed_f16.py
index 9747f6b..5c28158 100644
--- a/tests/test_hip_routed_f16.py
+++ b/tests/test_hip_routed_f16.py
@@ -142,6 +142,36 @@ def test_hip_routed_f16():
assert res
+def run_combine(ext):
+ """ext.fq_routed_f16_combine against an fp64 reference sum_s w[t, s] * rows[t, s, :] and against torch's F32 multiply + sum (the path it replaces)."""
+ dev = torch.device("cuda")
+ ok = True
+ for T, top_k, K in ((1, 10, 2560), (7, 10, 2560), (600, 10, 2560), (4096, 10, 2560), (33, 8, 640)):
+ g = torch.Generator(device="cpu").manual_seed(T * 31 + K)
+ rows = (torch.randn(T * top_k, K, generator=g) * 3).half().to(dev)
+ w = torch.rand(T, top_k, generator=g).float().to(dev)
+ out = torch.empty(T, K, dtype=torch.float, device=dev)
+ ext.fq_routed_f16_combine(rows, w, out)
+ torch.cuda.synchronize()
+ ref = (rows.view(T, top_k, K).double() * w.double().unsqueeze(-1)).sum(1)
+ old = (rows.view(T, top_k, K) * w.reshape(T, top_k, 1)).sum(1)
+ e_ref = ((out.double() - ref).abs().max() / ref.abs().max()).item()
+ e_old = ((out - old).abs().max() / ref.abs().max()).item()
+ print(f"combine T={T:5d} top_k={top_k} K={K}: rel err vs fp64 {e_ref:.2e}, vs torch path {e_old:.2e}")
+ ok &= e_ref < 1e-6 and e_old < 1e-6
+ return ok
+
+
+def test_hip_routed_f16_combine():
+ ext = _ext()
+ if ext is None or not hasattr(ext, "fq_routed_f16_combine"):
+ return
+ assert run_combine(ext)
+
+
if __name__ == "__main__":
+ ext0 = _ext()
+ if ext0 is not None and hasattr(ext0, "fq_routed_f16_combine"):
+ assert run_combine(ext0)
res = run_all()
sys.exit(0 if res in (True, None) else 1)