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.

MoE prefill: add the shared expert in the reduce epilogue (EXL3_NC2_SHARED_FUSE)

Yaniss78c62f1cbc05
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index f8200c8..5e0accc 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -447,7 +447,7 @@ 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("act_limit") = 0.0, py::arg("mcg") = false, py::arg("addend") = py::none());
m.def("exl3_moe_prefill_gemm_test", &exl3_moe_prefill_gemm_test, "exl3_moe_prefill_gemm_test");
m.def("routing_std_gfx12_bsz1", &routing_std_gfx12_bsz1,
"routing_std_gfx12_bsz1");
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu
index d8dd3b0..6b8b083 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu
@@ -258,7 +258,9 @@ void mpw_reduce_had_kernel
float* __restrict__ output,
int rows,
int top_k,
- int width
+ int width,
+ const half* __restrict__ addend,
+ int addend_rows
)
{
const int blocks = width / 128;
@@ -285,6 +287,15 @@ void mpw_reduce_had_kernel
sum.z += h2 * r * __low2float(sc.y);
sum.w += h3 * r * __high2float(sc.y);
}
+ // 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.
+ 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);
+ }
((float4*) (output + row * width + blk * 128))[t] = sum;
}
@@ -1615,7 +1626,8 @@ void exl3_moe_prefill_wmma
at::Tensor& tiles,
at::Tensor& tile_count,
double act_limit,
- bool mcg
+ bool mcg,
+ const c10::optional<at::Tensor>& addend
)
{
const at::cuda::OptionalCUDAGuard device_guard(A.device());
@@ -1649,6 +1661,16 @@ void exl3_moe_prefill_wmma
TORCH_CHECK(down_out.dtype() == at::kFloat && down_out.numel() >= (int64_t) assignments * H, "down_out too small");
TORCH_CHECK(expert_offsets.dtype() == at::kLong && expert_offsets.numel() >= experts + 1, "expert_offsets");
TORCH_CHECK(inverse_order.dtype() == at::kLong && inverse_order.numel() >= assignments, "inverse_order");
+ const half* add_ptr = nullptr;
+ int add_rows = 0;
+ if (addend.has_value())
+ {
+ const at::Tensor& ad = addend.value();
+ TORCH_CHECK(ad.dtype() == at::kHalf && ad.is_contiguous() && ad.dim() == 2 && ad.size(1) == H &&
+ ad.size(0) <= rows && ad.device() == A.device(), "addend must be fp16 [<= rows, H] contiguous");
+ add_ptr = (const half*) ad.data_ptr();
+ add_rows = ad.size(0);
+ }
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");
@@ -1666,7 +1688,7 @@ void exl3_moe_prefill_wmma
((const int64_t*) expert_count.data_ptr(), ord, offs, inv, tl, tc, (int) experts, assignments, mpw_mt(kern));
const char* glue_env = getenv("EXL3_MPW_GLUE"); // read per launch (A/B harnesses flip it in-process)
- const bool glue2 = glue_env && glue_env[0] == '1' && top_k >= 1 && top_k <= MPW_GLUE_TK_MAX;
+ const bool glue2 = glue_env && glue_env[0] == '1' && top_k >= 1 && top_k <= MPW_GLUE_TK_MAX && !add_ptr;
if (glue2)
{
const int64_t g2jobs = (int64_t) (assignments / top_k) * (H / 128);
@@ -1706,7 +1728,7 @@ void exl3_moe_prefill_wmma
else
mpw_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);
+ (float*) output.data_ptr(), rows, top_k, H, add_ptr, add_rows);
cuda_check(hipPeekAtLastError());
}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuh
index e1ba779..90bd4c1 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuh
@@ -1,6 +1,7 @@
#pragma once
#include <ATen/Tensor.h>
+#include <c10/util/Optional.h>
// Grouped EXL3 MoE prefill for gfx11.5 (RDNA3.5 WMMA): tokens are sorted by expert and every
// projection runs as ONE launch over all experts. Trellis tiles are decoded in the GEMM (to LDS),
@@ -33,7 +34,8 @@ void exl3_moe_prefill_wmma
at::Tensor& tiles, // int32 [>= ceil(A / 64) + E]
at::Tensor& tile_count, // int32 [1]
double act_limit, // clamped SwiGLU limit, 0 = unclamped
- bool mcg // trellis codebook: true = mcg, false = mul1
+ bool 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
);
// Standalone grouped GEMM on pre-sorted rows (test / benchmark entry): C[sorted rows] =
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index 80dd081..5f92fc9 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -52,6 +52,9 @@ MAX_BSZN = 8 # must match MAX_BSZN in exllamav3_ext/libtorch/blocksparse_mlp.h
# rows); EXL3_MOE_DEDUP=0 restores the per-assignment kernel
_MOE_DEDUP = os.environ.get("EXL3_MOE_DEDUP", "1") != "0"
+def _nc2_shared_fuse() -> bool:
+ return os.environ.get("EXL3_NC2_SHARED_FUSE", "0") == "1"
+
def _moe_sync_free_count() -> bool:
# Default on: torch.bincount on a device tensor synchronizes the host once per MoE
# layer per chunk (48 layers), locking the host to the device. The scatter_add_
@@ -1734,6 +1737,23 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
gu_had = ws["gu_had"][:2 * assignments * self.hidden_size].view(2 * assignments, self.hidden_size)
# down_out aliases gu_had: the gate/up input is dead once the gate/up GEMM has run
down_out = ws["gu_had"][:2 * assignments * self.hidden_size].view(torch.float).view(assignments, self.hidden_size)
+ # EXL3_NC2_SHARED_FUSE=1 (default off, read per call): the shared expert runs first (it only
+ # reads x) and returns its down GEMM's fp16 output; the reduce widens it (exact) and adds it in
+ # fp32 in its epilogue = the arithmetic of the widen copy + `final_hidden_states += y` it
+ # replaces; both kernels disappear. Bit-exact.
+ sh_add = None
+ if (_nc2_shared_fuse() and self.shared_experts and not self.shared_gate 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):
+ sh_params = {**params, "moe_valu": True} if _MOE_VALU else dict(params)
+ sh_params["nc2_down_half"] = True
+ sh_add = self.shared_experts.forward(x, sh_params)
+ if sh_add.dtype == torch.half and sh_add.is_contiguous():
+ sh_add = sh_add.view(num_tokens, self.hidden_size)
+ bc_sh_exp = True # shared expert summed in by the reduce: skip the tail add
+ else:
+ raise RuntimeError(f"EXL3_NC2_SHARED_FUSE: shared expert output {sh_add.dtype}, contiguous "
+ f"{sh_add.is_contiguous()}: fp16 contiguous needed")
ext.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,
@@ -1744,7 +1764,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
ws["gu_out"][:2 * assignments * self.intermediate_size_padded].view(2 * assignments, self.intermediate_size_padded),
down_out,
ws["offsets"], ws["inverse"][:assignments], ws["tiles"], ws["tile_count"],
- float(self.act_limit), bool(self.wmma_mcg),
+ float(self.act_limit), bool(self.wmma_mcg), sh_add,
)
final_hidden_states = output[:num_tokens].view(eshape)
diff --git a/exllamav3/modules/mlp.py b/exllamav3/modules/mlp.py
index eb8d6d2..e04c29b 100644
--- a/exllamav3/modules/mlp.py
+++ b/exllamav3/modules/mlp.py
@@ -737,6 +737,8 @@ class GatedMLP(Module):
out_dtype: torch.dtype | None = None
) -> torch.Tensor:
bsz, q_len, dim = x.shape
+ # EXL3_NC2_SHARED_FUSE: the MoE reduce widens and adds the down GEMM's fp16 output itself
+ nc2_half = bool(params.get("nc2_down_half")) and self.num_slices == 1 and not self.tp_reduce
if self.num_slices == 0:
d = torch.zeros_like(x, dtype = self.out_dtype)
@@ -770,7 +772,7 @@ class GatedMLP(Module):
[g.view(rows, -1), u.view(rows, -1)], scratch, counters, [gi.K, ui.K], False)
a = torch.empty_like(u, dtype = torch.half) if self.interm_dtype != torch.half else u
self.activation_fn_call(g, u, a, self.act_limit)
- d_ = self.downs[s].forward(a, params)
+ d_ = self.downs[s].forward(a, params, torch.half if nc2_half else None)
if d is None: d = d_
else: d += d_
del d_
@@ -786,7 +788,7 @@ class GatedMLP(Module):
u = self.ups[s].forward(x, params)
a = torch.empty_like(u, dtype = torch.half) if self.interm_dtype != torch.half else u
self.activation_fn_call(g, u, a, self.act_limit)
- d_ = self.downs[s].forward(a, params)
+ d_ = self.downs[s].forward(a, params, torch.half if nc2_half else None)
if d is None: d = d_
else: d += d_
@@ -818,7 +820,7 @@ class GatedMLP(Module):
a = torch.empty_like(u, dtype = torch.half) if self.interm_dtype != torch.half else u
self.activation_fn_call(g, u, a, self.act_limit)
- d_ = self.downs[s].forward(a, params)
+ d_ = self.downs[s].forward(a, params, torch.half if nc2_half else None)
if d is None: d = d_
else: d += d_
@@ -827,6 +829,8 @@ class GatedMLP(Module):
if self.tp_reduce:
params["backend"].all_reduce(d)
+ if nc2_half and d.dtype == torch.half:
+ return d
return to2(d, out_dtype, self.out_dtype)