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: prefill glue for GGUF MoE on gfx1151 (shared expert in combine, half foreign projections, contiguous PLE add) (#218)

Yaniss Amazouz7316d6beab6d
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index c79bb3a..937e735 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, and MoeEpilogueVec4Kernel for fq_routed_f16_combine, 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 and fq_routed_f16_combine_shared (its shared-expert term and gate), 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 b83ffd3..93b790e 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -487,6 +487,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
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"));
+ m.def("fq_routed_f16_combine_shared", &fq_routed_f16_combine_shared, "fq_routed_f16_combine_shared", py::arg("rows"), py::arg("weights"), py::arg("shared"), py::arg("x"), py::arg("gate_w"), 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 c0bc937..9df1e07 100644
--- a/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.cu
+++ b/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.cu
@@ -11,6 +11,7 @@
// 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.
+// fq_routed_f16_combine_shared adds that shared-expert term (and the shared gate's dot product) to the same pass, as Gufo's MoeEpilogueVec4Kernel does.
#if defined(USE_ROCM)
#include <ATen/cuda/CUDAContext.h>
@@ -769,6 +770,66 @@ __global__ void RoutedCombineKernel(const __half* __restrict__ rows, const float
}
*reinterpret_cast<float4*>(out + static_cast<std::size_t>(t) * dim + i) = float4{a0, a1, a2, a3};
}
+
+// RoutedCombineKernel with the gated shared expert fused in (Gufo MoeEpilogueVec4Kernel<__half> with its shared-expert term, the gate taken as in
+// Kyojin's torch path): out[t, :] = sum_s weights[t, s] * rows[t, s, :] + shared[t, :] * sigmoid(round_f16(x[t, :] . w)). One block per token:
+// the gate dot product (F32 accumulation, rounded to F16 like the linear's output the torch path widens), then the top-k sum in registers, then the
+// shared term, so the F32 widen of the shared output, the gate GEMM (N = 1), the sigmoid / multiply / add passes and one F32 round trip of
+// the output are gone.
+__global__ void RoutedCombineSharedKernel(const __half* __restrict__ rows, const float* __restrict__ weights,
+ const __half* __restrict__ shared, const __half* __restrict__ x,
+ const __half* __restrict__ w, float* __restrict__ out, std::uint32_t top_k,
+ std::uint32_t dim, std::size_t x_pitch) {
+ __shared__ float part[kThreads / 32];
+ __shared__ float s_gate;
+ const std::size_t t = blockIdx.x;
+ // gate: x[t, :] . w, four adjacent lanes per thread
+ float dot = 0.0f;
+ const __half* xr = x + t * x_pitch;
+ for (std::uint32_t i = threadIdx.x * 4; i < dim; i += kThreads * 4) {
+ const uint2 xr_raw = *reinterpret_cast<const uint2*>(xr + i);
+ const uint2 w_raw = *reinterpret_cast<const uint2*>(w + i);
+ const __half2 x0 = *reinterpret_cast<const __half2*>(&xr_raw.x), x1 = *reinterpret_cast<const __half2*>(&xr_raw.y);
+ const __half2 w0 = *reinterpret_cast<const __half2*>(&w_raw.x), w1 = *reinterpret_cast<const __half2*>(&w_raw.y);
+ dot = __fmaf_rn(__low2float(x0), __low2float(w0), dot);
+ dot = __fmaf_rn(__high2float(x0), __high2float(w0), dot);
+ dot = __fmaf_rn(__low2float(x1), __low2float(w1), dot);
+ dot = __fmaf_rn(__high2float(x1), __high2float(w1), dot);
+ }
+ for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor(dot, o);
+ if ((threadIdx.x & 31u) == 0) part[threadIdx.x >> 5] = dot;
+ __syncthreads();
+ if (threadIdx.x == 0) {
+ float sum = 0.0f;
+ for (unsigned q = 0; q < kThreads / 32; ++q) sum += part[q];
+ const float gate = __half2float(__float2half_rn(sum));
+ s_gate = 1.0f / (1.0f + expf(-gate));
+ }
+ __syncthreads();
+ const float g = s_gate;
+ for (std::uint32_t i = threadIdx.x * 4; i < dim; i += kThreads * 4) {
+ float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
+ const __half* src = rows + t * top_k * dim + i;
+ for (std::uint32_t s = 0; s < top_k; ++s) {
+ const float wt = weights[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(wt, __low2float(lo)));
+ a1 = __fadd_rn(a1, __fmul_rn(wt, __high2float(lo)));
+ a2 = __fadd_rn(a2, __fmul_rn(wt, __low2float(hi)));
+ a3 = __fadd_rn(a3, __fmul_rn(wt, __high2float(hi)));
+ }
+ const uint2 sraw = *reinterpret_cast<const uint2*>(shared + t * dim + i);
+ const __half2 slo = *reinterpret_cast<const __half2*>(&sraw.x);
+ const __half2 shi = *reinterpret_cast<const __half2*>(&sraw.y);
+ a0 = __fadd_rn(a0, __fmul_rn(__low2float(slo), g));
+ a1 = __fadd_rn(a1, __fmul_rn(__high2float(slo), g));
+ a2 = __fadd_rn(a2, __fmul_rn(__low2float(shi), g));
+ a3 = __fadd_rn(a3, __fmul_rn(__high2float(shi), g));
+ *reinterpret_cast<float4*>(out + t * dim + i) = float4{a0, a1, a2, a3};
+ }
+}
} // namespace
#endif
} // namespace kyo_routed_f16
@@ -849,4 +910,33 @@ void fq_routed_f16_combine(torch::Tensor rows, torch::Tensor weights, torch::Ten
TORCH_CHECK(hipGetLastError() == hipSuccess, "fq_routed_f16_combine: launch failed");
}
+
+// out[t, :] (F32) = sum_s weights[t, s] * rows[t * top_k + s, :] + shared[t, :] * sigmoid(f16(x[t, :] . gate_w)): fq_routed_f16_combine with the gated shared expert
+// fused (see RoutedCombineSharedKernel). rows half [T * top_k, K], weights float [T, top_k], shared half [T, K] (contiguous), x half [T, K] with
+// unit column stride and any row pitch, gate_w half, K elements.
+void fq_routed_f16_combine_shared(torch::Tensor rows, torch::Tensor weights, torch::Tensor shared, torch::Tensor x, torch::Tensor gate_w,
+ 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(shared.is_cuda() && shared.is_contiguous() && shared.dtype() == torch::kHalf && shared.dim() == 2 && shared.size(0) == T && shared.size(1) == K,
+ "shared must be half [T, K]");
+ TORCH_CHECK(x.is_cuda() && x.dim() == 2 && x.dtype() == torch::kHalf && x.size(0) == T && x.size(1) == K && x.stride(1) == 1 &&
+ x.stride(0) % 4 == 0 && ((std::uintptr_t) x.data_ptr() % 8) == 0, "x must be half [T, K], unit column stride, 8-byte aligned rows");
+ TORCH_CHECK(gate_w.is_cuda() && gate_w.is_contiguous() && gate_w.dtype() == torch::kHalf && gate_w.numel() == K, "gate_w must be half with K elements");
+ 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(RoutedCombineSharedKernel, dim3((unsigned) T), dim3(kThreads), 0, stream,
+ (const __half *) rows.data_ptr(), (const float *) weights.data_ptr(), (const __half *) shared.data_ptr(),
+ (const __half *) x.data_ptr(), (const __half *) gate_w.data_ptr(), (float *) out.data_ptr(), (std::uint32_t) top_k,
+ (std::uint32_t) K, (std::size_t) x.stride(0));
+ TORCH_CHECK(hipGetLastError() == hipSuccess, "fq_routed_f16_combine_shared: 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 f7b3af6..a3d4aac 100644
--- a/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.h
+++ b/exllamav3/exllamav3_ext/rocm/routed_f16/routed_f16.h
@@ -12,3 +12,8 @@ void fq_routed_f16_moe(torch::Tensor x, torch::Tensor ids, torch::Tensor counts,
// 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);
+
+// fq_routed_f16_combine plus the gated shared expert in the same pass: out[t, :] = sum_s weights[t, s] * rows[t * top_k + s, :] + shared[t, :] * sigmoid(f16(x[t, :] . gate_w)).
+// shared half [T, K]; x half [T, K] (unit column stride, any row pitch); gate_w half [K]. Gufo MoeEpilogueVec4Kernel<__half> with the shared-expert term.
+void fq_routed_f16_combine_shared(torch::Tensor rows, torch::Tensor weights, torch::Tensor shared, torch::Tensor x, torch::Tensor gate_w,
+ torch::Tensor out);
diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.py
index 91cb0cf..afff251 100644
--- a/exllamav3/modules/attn.py
+++ b/exllamav3/modules/attn.py
@@ -1088,6 +1088,10 @@ class Attention(Module):
and not m.lora_a_tensors and m.pre_scale == 1.0 and m.post_scale == 1.0 \
and m.softcap == 0.0 and m.out_features == m.out_features_unpadded:
o_dt = torch.half
+ if o_dt is None and params.get("pfe_y_half") and "capture" not in params and "quant_preserve" not in params:
+ from .foreign_linear import pfe_f16_ok
+ if pfe_f16_ok(self.o_proj, o):
+ o_dt = torch.half
x = self.o_proj.forward(o, params, o_dt)
return x
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index 6b04eb7..36f4b6a 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -234,6 +234,12 @@ _FQ_PF_ROUTED_F16 = os.environ.get("MCPM_FQ_PF_ROUTED_F16", "1" if torch.version
# 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"
+# MCPM_FQ_PF_ROUTED_F16_SHARED=1: the gated shared expert joins the combine kernel (rocm/routed_f16 fq_routed_f16_combine_shared, Gufo's
+# MoeEpilogueVec4Kernel shared-expert term): the shared expert's half output is not widened to float, the shared-gate GEMM (N = 1), sigmoid,
+# multiply and add passes disappear (about 3 ms of the 6 per layer at 8K rows). Needs the combine flag; gfx1151 only (the routed F16 path's
+# gate). Default on with ROCm: a drop-one ABBA against the other three prefill-glue levers (Strix Halo Qwen3.8-Flash-Next GGUF, 8K prefill)
+# showed a reproducible ~3-4 % extra gain (6.34-6.42 -> 6.12-6.20 s). 0 = the separate gate GEMM + torch tail.
+_FQ_PF_ROUTED_F16_SHARED = os.environ.get("MCPM_FQ_PF_ROUTED_F16_SHARED", "1" if torch.version.hip else "0") == "1"
_ROUTED_F16_ARCH = {}
@@ -2213,15 +2219,42 @@ 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)
- if _FQ_PF_ROUTED_F16_COMBINE and hasattr(ext, "fq_routed_f16_combine") and K % 4 == 0:
+ fused_sh = False
+ y_se = None
+ if _FQ_PF_ROUTED_F16_COMBINE and _FQ_PF_ROUTED_F16_SHARED and hasattr(ext, "fq_routed_f16_combine_shared") and K % 4 == 0 and \
+ self.shared_experts and self.shared_gate:
+ # the shared expert's down GEMM output stays half (the widen to float moves into the combine kernel), the gate GEMM (N = 1),
+ # sigmoid, multiply and add become the combine kernel's tail (fq_routed_f16_combine_shared)
+ gw = getattr(getattr(self.shared_gate, "inner", None), "weight", None)
+ if gw is not None and gw.dtype == torch.half and gw.numel() == K and gw.is_contiguous():
+ # nc2_down_half: the shared down GEMM keeps its fp16 output (the widen is in the combine kernel); out_dtype half keeps it at the end
+ y_se = self.shared_experts.forward(x, {**params, "moe_valu": True, "nc2_down_half": True} if _MOE_VALU else {**params, "nc2_down_half": True},
+ out_dtype=torch.half)
+ try:
+ x2 = x.view(R, K)
+ except RuntimeError:
+ x2 = None
+ if x2 is not None and x2.dtype == torch.half and y_se.dtype == torch.half and y_se.is_contiguous() and y_se.numel() == R * K and x2.stride(1) == 1 \
+ and x2.stride(0) % 4 == 0 and x2.data_ptr() % 8 == 0:
+ final_hidden_states = torch.empty((R, K), dtype=torch.float, device=dev)
+ ext.fq_routed_f16_combine_shared(dn, routing_weights.to(torch.float).reshape(R, top_k).contiguous(), y_se.view(R, K), x2,
+ gw.view(-1), final_hidden_states)
+ final_hidden_states = final_hidden_states.reshape(eshape)
+ fused_sh = True
+ else:
+ y_se = y_se.to(torch.float)
+ if fused_sh:
+ pass
+ elif _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_experts and not fused_sh:
+ if y_se is None:
+ y_se = self.shared_experts.forward(x, {**params, "moe_valu": True} if _MOE_VALU else params)
if self.shared_gate:
ext.add_sigmoid_gate(y_se, self.shared_gate.forward(x, params), final_hidden_states)
else:
diff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.py
index c5c09ab..3f985f9 100644
--- a/exllamav3/modules/foreign_linear.py
+++ b/exllamav3/modules/foreign_linear.py
@@ -51,8 +51,9 @@ _FUSED = os.environ.get("BOLT_FQ_FUSED", "1") != "0"
# and the mamba projections fell back to full dequant+matmul).
# BOLT_FQ_GEMV=0 restores the fq_gemm_* path for A/B.
_GEMV = os.environ.get("BOLT_FQ_GEMV", "1") != "0"
-# Row chunk of the unfused dequant+matmul path (transient fp16 bound).
-_UNFUSED_ROWS = int(os.environ.get("BOLT_FQ_UNFUSED_ROWS", "8192"))
+# Row chunk of the unfused dequant+matmul path (transient fp16 bound). Default 16384 with ROCm (gfx1151 Strix Halo: fewer, bigger GEMMs cut
+# dequant kernel-launch overhead at long prefill without moving the tolerance). CUDA keeps 8192 until measured there.
+_UNFUSED_ROWS = int(os.environ.get("BOLT_FQ_UNFUSED_ROWS", "16384" if torch.version.hip else "8192"))
# NVFP4 E2M1 pair-table dot (fq_gemv.cuh: one shared float2 load per pair
# instead of two replicated-e2m1 loads + nibble math). BOLT_FQ_PAIR=0
# restores the direct dot for A/B.
@@ -427,3 +428,28 @@ class ForeignLinear(Module):
if self.softcap != 0.0:
ext.softcap(out, out, self.softcap)
return out
+
+
+def pfe_f16_ok(m, x: torch.Tensor) -> bool:
+ """EXL3_PFE_FOREIGN=1 (default on with ROCm, gfx1151 only): a prefill projection that is a ForeignLinear (directly or as a Linear's
+ _ForeignInner, the GGUF load) with a float default output may be asked for half instead (out_dtype=torch.half): its fp16 GEMM output
+ holds the values the float path widens (`mmout.to(float)`), and the consumers that already take half from the EXL3 projections (the
+ GDN conv's in-kernel cast, the gated norm's z, the HC residual apply's y) widen in-kernel. Drops one full fp32 write + read per
+ projection (the f16 -> f32 copy kernel), and with a half output the N-chunk slice copies move half the bytes. Prefill GEMM widths only
+ (rows >= 1024); decode kernels that accumulate straight into a float output keep their dtype. 0 = the float path."""
+ if os.environ.get("EXL3_PFE_FOREIGN", "1" if torch.version.hip else "0") != "1" or not torch.version.hip or \
+ "gfx1151" not in torch.cuda.get_device_properties(x.device).gcnArchName:
+ return False
+ if isinstance(m, ForeignLinear):
+ fl, wrap = m, None
+ else:
+ inner = getattr(m, "inner", None)
+ fl, wrap = getattr(inner, "fl", None), m
+ if not isinstance(fl, ForeignLinear) or type(inner).__name__ != "_ForeignInner" or inner.bias is not None:
+ return False
+ if wrap is not None and (getattr(wrap, "lora_a_tensors", None) or wrap.pre_scale != 1.0 or wrap.post_scale != 1.0 or wrap.softcap != 0.0
+ or wrap.out_features != wrap.out_features_unpadded or wrap.trim_padded_out):
+ return False
+ rows = x.numel() // x.shape[-1]
+ return rows >= 1024 and (wrap.out_dtype if wrap is not None else None) in (None, torch.float) and \
+ (fl.out_dtype or (wrap.out_dtype if wrap is not None else None)) == torch.float and fl.post_scale == 1.0 and fl.softcap == 0.0
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index 484b4e5..b998621 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -1323,6 +1323,9 @@ class GatedDeltaNet(Module):
# buffer holds the same values and the consumer widens in-kernel: drops the widen copy, bit-exact
if os.environ.get(env, "1") != "1" or "capture" in params or "quant_preserve" in params:
return False
+ from .foreign_linear import pfe_f16_ok
+ if pfe_f16_ok(m, x):
+ return True
from .quant import exl3 as _exl3
rows = x.numel() // x.shape[-1]
if not (_exl3._f32_via_f16 and rows >= _exl3._f32_via_f16_min_rows):
diff --git a/exllamav3/modules/ple.py b/exllamav3/modules/ple.py
index f861347..a874673 100644
--- a/exllamav3/modules/ple.py
+++ b/exllamav3/modules/ple.py
@@ -35,6 +35,39 @@ def _ple_gate_torch(gate, value, gate_scale):
return torch.sigmoid(signed_sqrt).unsqueeze(-1) * value.float().unsqueeze(-2)
+try:
+ import triton
+ import triton.language as tl
+
+ @triton.jit
+ def _ple_tadd_kernel(g_ptr, y_ptr, T, C, y_sb, y_sc, BT: tl.constexpr, BC: tl.constexpr):
+ b = tl.program_id(2)
+ t = tl.program_id(0) * BT + tl.arange(0, BT)
+ c = tl.program_id(1) * BC + tl.arange(0, BC)
+ yv = tl.load(y_ptr + b.to(tl.int64) * y_sb + c[:, None] * y_sc + t[None, :], mask=(c[:, None] < C) & (t[None, :] < T), other=0.0)
+ yv = tl.trans(yv)
+ gp = g_ptr + b.to(tl.int64) * T * C + t[:, None] * C + c[None, :]
+ m = (t[:, None] < T) & (c[None, :] < C)
+ tl.store(gp, tl.load(gp, mask=m, other=0.0) + yv.to(tl.float32), mask=m)
+except Exception: # no Triton: the transpose-copy fallback below
+ _ple_tadd_kernel = None
+
+
+def _ple_tadd(gated: torch.Tensor, conv_out: torch.Tensor) -> bool:
+ """gated (bsz, seq, H, D) fp32, contiguous, += conv_out (bsz, seq, ch = H * D) fp16, the transposed view of a (bsz, ch, seq) tensor: one Triton pass,
+ tiles transposed through shared memory. False when the layout / dtype / Triton is not the expected one (the caller adds the old way)."""
+ if _ple_tadd_kernel is None or not torch.version.hip or gated.dtype != torch.float or not gated.is_contiguous() \
+ or conv_out.dtype not in (torch.half, torch.bfloat16, torch.float) or conv_out.stride(1) != 1:
+ return False
+ bsz, seq, ch = conv_out.shape
+ if gated.numel() != bsz * seq * ch:
+ return False
+ BT = BC = 64
+ _ple_tadd_kernel[((seq + BT - 1) // BT, (ch + BC - 1) // BC, bsz)](gated, conv_out, seq, ch, conv_out.stride(0), conv_out.stride(2),
+ BT=BT, BC=BC, num_warps=4)
+ return True
+
+
class PLELayerState:
"""
Per-slot recurrent state for one PLE layer, following the ShortConvLayerState conventions:
@@ -347,7 +380,23 @@ class PLELayer(Module):
if os.environ.get("EXL3_PFE_PLE", "1") != "0":
# gated is a local temp that is dead after the conv: add in place, no 84 MB fresh allocation
# (same fp32 elementwise sum, bit-identical)
- delta = gated.add_(conv_out.view(bsz, seq, H, D))
+ co = conv_out.view(bsz, seq, H, D)
+ if os.environ.get("EXL3_PLE_CONTIG", "1" if torch.version.hip else "0") == "1" and not co.is_contiguous() and \
+ (not torch.version.hip or "gfx1151" in torch.cuda.get_device_properties(gated.device).gcnArchName):
+ # EXL3_PLE_CONTIG=1 (default on with ROCm, gfx1151 only): conv_out is the transposed view of the (bsz, ch, seq) conv result, so
+ # the in-place add below reads it with a ch-sized stride (uncoalesced, a strided broadcast kernel: ~100 ms per 8K chunk). A
+ # tiled transposed add (Triton, ple_tadd) does it in one pass at bandwidth; where Triton or the layout does not fit, one
+ # transpose copy first. Same fp32 sum (fp16 widened, added), bit-identical. 0 = the strided broadcast add.
+ try:
+ done = _ple_tadd(gated, conv_out) if conv_out.dim() == 3 else False
+ except Exception:
+ done = False
+ if not done:
+ delta = gated.add_(co.contiguous())
+ else:
+ delta = gated
+ else:
+ delta = gated.add_(co)
else:
delta = gated + conv_out.view(bsz, seq, H, D)
return delta, conv_stream
diff --git a/tests/test_hip_ple_tadd.py b/tests/test_hip_ple_tadd.py
new file mode 100644
index 0000000..8ab6797
--- /dev/null
+++ b/tests/test_hip_ple_tadd.py
@@ -0,0 +1,68 @@
+"""PLE transposed add (exllamav3.modules.ple._ple_tadd, Triton): one tiled transpose-through-shared-memory pass that adds the
+(bsz, ch, seq)-transposed conv output straight onto the fp32 gated accumulator, replacing a strided broadcast add (EXL3_PLE_CONTIG's
+old fallback: one transpose-copy, then a plain vectorized add). Checked bit-identical to the torch reference (fp16 widened to fp32,
+then added) at the real Qwen3.8-Flash-Next PLE shape (H=4, D=2560) and a couple of edge shapes (short / odd seq, 2 batches, small D).
+Runs under pytest or as a plain script (needs Triton + a CUDA/HIP device; skips otherwise)."""
+import os
+import sys
+
+import torch
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+from exllamav3.modules import ple # noqa: E402
+
+CASES = [ # (bsz, seq, H, D)
+ (1, 8192, 4, 2560),
+ (1, 1109, 4, 2560),
+ (1, 37, 4, 2560),
+ (2, 300, 4, 64),
+ (1, 1, 4, 2560),
+]
+
+
+def _avail():
+ if not torch.cuda.is_available() or ple._ple_tadd_kernel is None:
+ return False
+ try:
+ import triton # noqa: F401
+ except ImportError:
+ return False
+ return True
+
+
+def run_case(bsz, seq, H, D, seed):
+ dev = torch.device("cuda")
+ ch = H * D
+ g = torch.Generator(device="cpu").manual_seed(seed)
+ y = (torch.randn(bsz, ch, seq, generator=g) * 2).half().to(dev)
+ co = torch.nn.functional.silu(y).transpose(1, 2) # (bsz, seq, ch), transposed view, stride(1) != 1
+ gated = (torch.randn(bsz, seq, H, D, generator=g)).to(dev)
+ ref = gated + co.reshape(bsz, seq, H, D).float()
+ g2 = gated.clone()
+ done = ple._ple_tadd(g2, co)
+ torch.cuda.synchronize()
+ ok = done and bool((g2 == ref).all())
+ print(f"ple_tadd bsz={bsz} seq={seq} H={H} D={D}: dispatched={done} bit_identical={bool((g2 == ref).all())} -> "
+ f"{'PASS' if ok else 'FAIL'}")
+ return ok
+
+
+def run_all():
+ if not _avail():
+ print("SKIP: needs Triton and a CUDA/HIP device")
+ return None
+ fails = sum(not run_case(*c, seed=100 + i) for i, c in enumerate(CASES))
+ print(f"{'PASS' if fails == 0 else 'FAIL'}: {len(CASES) - fails}/{len(CASES)} cases")
+ return fails == 0
+
+
+def test_hip_ple_tadd():
+ import pytest
+ res = run_all()
+ if res is None:
+ pytest.skip("Triton PLE transposed-add op not available")
+ assert res
+
+
+if __name__ == "__main__":
+ sys.exit(0 if run_all() in (True, None) else 1)
diff --git a/tests/test_hip_routed_f16.py b/tests/test_hip_routed_f16.py
index 5c28158..4f923ab 100644
--- a/tests/test_hip_routed_f16.py
+++ b/tests/test_hip_routed_f16.py
@@ -136,6 +136,8 @@ def run_all():
def test_hip_routed_f16():
import pytest
+ if ext0 is not None and hasattr(ext0, "fq_routed_f16_combine_shared"):
+ assert run_combine_shared(ext0)
res = run_all()
if res is None:
pytest.skip("ROCm gfx1151 op (fq_routed_f16_moe) not available")
@@ -169,9 +171,45 @@ def test_hip_routed_f16_combine():
assert run_combine(ext)
+def run_combine_shared(ext):
+ """ext.fq_routed_f16_combine_shared against an fp64 reference sum_s w[t, s] * rows[t, s, :] + shared[t, :] * sigmoid(f16(x[t, :] . gate_w)) and
+ against the separate torch path it replaces (combine, F32 widen, gate matmul in half, sigmoid, multiply, add). x is a row-padded view in one case."""
+ dev = torch.device("cuda")
+ ok = True
+ for T, top_k, K, pad in ((1, 10, 2560, 0), (7, 10, 2560, 0), (600, 10, 2560, 64), (4096, 10, 2560, 0), (33, 8, 640, 0)):
+ g = torch.Generator(device="cpu").manual_seed(T * 17 + 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)
+ sh = torch.randn(T, K, generator=g).half().to(dev)
+ xb = torch.randn(T, K + pad, generator=g).half().to(dev)
+ x = xb[:, :K]
+ gw = (torch.randn(K, 1, generator=g) * 0.05).half().to(dev)
+ out = torch.empty(T, K, dtype=torch.float, device=dev)
+ ext.fq_routed_f16_combine_shared(rows, w, sh, x, gw.view(-1), out)
+ torch.cuda.synchronize()
+ gate = (x.double() @ gw.double()).half().double()
+ ref = (rows.view(T, top_k, K).double() * w.double().unsqueeze(-1)).sum(1) + sh.double() * torch.sigmoid(gate)
+ old = (rows.view(T, top_k, K) * w.reshape(T, top_k, 1)).sum(1)
+ old.add_(sh.float() * torch.sigmoid((x @ gw).float()))
+ e_ref = ((out.double() - ref).abs().max() / ref.abs().max()).item()
+ e_old = ((out - old).abs().max() / ref.abs().max()).item()
+ print(f"combine_shared T={T:5d} top_k={top_k} K={K} pad={pad}: rel err vs fp64 {e_ref:.2e}, vs torch path {e_old:.2e}")
+ ok &= e_ref < 1e-4 and e_old < 1e-4 # 1e-4: the gate dot is rounded to F16, a one-ulp flip vs the GEMM's summation order moves a few rows by <= ~1e-4 of the max
+ return ok
+
+
+def test_hip_routed_f16_combine_shared():
+ ext = _ext()
+ if ext is None or not hasattr(ext, "fq_routed_f16_combine_shared"):
+ return
+ assert run_combine_shared(ext)
+
+
if __name__ == "__main__":
ext0 = _ext()
if ext0 is not None and hasattr(ext0, "fq_routed_f16_combine"):
assert run_combine(ext0)
+ if ext0 is not None and hasattr(ext0, "fq_routed_f16_combine_shared"):
+ assert run_combine_shared(ext0)
res = run_all()
sys.exit(0 if res in (True, None) else 1)