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
Add Qwen3.8-Flash-Next support: server, speculative decoding, prefill and decode kernels, long-context fixes
YanissAmz4c06645c52ef
diff --git a/README.md b/README.mdindex 28abd63..761d07a 100644--- a/README.md+++ b/README.md@@ -46,6 +46,8 @@ Memory: GLM at `-c 131072` leaves about 10 GiB free on a 128 GB machine. Close bMiMo: `hf download yamz-labs/MiMo-V2.6-Flash-MOPD-EXL3-Yamz --local-dir ./mimo-pack`, then `python tools/mimo/serve.py --model ./mimo-pack --port 8000 -c 131072`. Speculative decoding (DFlash, 4 bpw drafter, confidence-truncated drafts) is on by default: the server uses the pack's `drafter/` directory (or `$MIMO_DRAFTER`, or `--drafter <dir>`). Without a drafter it logs one line and decodes plain. Set `MIMO_SPEC=0` in the lane script (`tools/lanes/serve_mimo.sh`) or pass `--no-dflash` to `serve.py` for plain decode. Greedy output under speculation is not token-identical to plain decode: near-tied logits can flip under the batched verify. A loaded drafter costs 2 to 4 % prefill. Details: `tools/mimo/SERVE.md`.+Qwen3.8-Flash-Next (125B MoE, 6B active): `hf download yamz-labs/Qwen3.8-Flash-Next-EXL3-Yamz --local-dir ./qwen-pack`, then `python tools/qwen/serve.py --model ./qwen-pack --port 8000 -c 131072`. Speculative decoding is on by default and returns the same tokens as plain decoding. The pack needs about 113 GiB of the 128 GB; start to ready takes about 90 s once the pack is in the page cache. Details: `tools/qwen/SERVE.md`.+## Measured numbersOne machine: Ryzen AI Max+ 395, Radeon 8060S (gfx1151), 128 GB LPDDR5X, ROCm. Other GPUs are untested.diff --git a/README.upstream.md b/README.upstream.mdindex d02de01..c3e4196 100644--- a/README.upstream.md+++ b/README.upstream.md@@ -1,4 +1,4 @@-> ## 🟥 AMD fork — adds RDNA 3.5 (gfx1151 / Strix Halo) support+> ## 🟥 AMD port — adds RDNA 3.5 (gfx1151 / Strix Halo) support>> **This branch adds AMD GPU functionality that is not in upstream ExLlamaV3.** Upstream targets> CUDA; the [`sdougbrown/exllamav3`](https://github.com/sdougbrown/exllamav3) base this is built ondiff --git a/exllamav3/cache/recurrent.py b/exllamav3/cache/recurrent.pyindex b09d921..4d750c7 100644--- a/exllamav3/cache/recurrent.py+++ b/exllamav3/cache/recurrent.py@@ -95,6 +95,17 @@ class RecurrentCache(OrderedDict):self.update_total_size()+ def drop(self, key) -> None:+ """Remove one checkpoint (rolling-checkpoint cleanup)."""+ popped = self.pop(key, None)+ if popped is None:+ return+ note_freed(popped["checkpoint_size"])+ if self.model.loaded_tp:+ self.model.tp_dispatch_all(mp_cache_recurrent_del, (id(self), popped["tp_handle"]))+ self.update_total_size()++def prune_stranded(self) -> int:"""Drop all checkpoints whose anchor page chain has been broken by KV eviction. A stranded checkpoint candiff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cppindex 2df6e7f..0fd2d6c 100644--- a/exllamav3/exllamav3_ext/bindings.cpp+++ b/exllamav3/exllamav3_ext/bindings.cpp@@ -31,6 +31,7 @@#include "quant/hadamard.cuh"#include "quant/exl3_gemm.cuh"#include "quant/exl3_gemv.cuh"+#include "quant/exl3_moe_fused_api.h"#include "quant/exl3_gemv_int8.cuh"#include "quant/exl3_moe_prefill.cuh"#include "cpu/moe_mul1.h"@@ -96,6 +97,7 @@#include "quant/quantize.cuh"#include "quant/hadamard.cuh"#include "quant/exl3_gemv.cuh"+#include "quant/exl3_moe_fused_api.h"#include "quant/exl3_gemv_int8.cuh"#include "quant/exl3_dec.cuh"#include "quant/exl3_moe_prefill.cuh"@@ -345,6 +347,12 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)m.def("exl3_gemv", &exl3_gemv, "exl3_gemv");m.def("exl3_gemv_supported", &exl3_gemv_supported, "exl3_gemv_supported");m.def("exl3_gemv_wmma_family", &exl3_gemv_wmma_family, "exl3_gemv_wmma_family");+ m.def("exl3_moe_fused_half", &exl3_moe_fused_half, "exl3_moe_fused_half");+ m.def("exl3_moe_valu_override", &exl3_moe_valu_override, "exl3_moe_valu_override");+ m.def("exl3_moe_fused_supported", &exl3_moe_fused_supported, "exl3_moe_fused_supported");+ m.def("exl3_moe_fused_ws_offsets", &exl3_moe_fused_ws_offsets, "exl3_moe_fused_ws_offsets");+ m.def("exl3_moe_fused_grid", &exl3_moe_fused_grid, "exl3_moe_fused_grid");+ m.def("exl3_moe_fused_tile_test", &exl3_moe_fused_tile_test, "exl3_moe_fused_tile_test");m.def("exl3_gemv_int8_max_k", &exl3_gemv_int8_max_k, "exl3_gemv_int8_max_k");m.def("exl3_moe_gfx12_k3", &exl3_moe_gfx12_k3, "exl3_moe_gfx12_k3");m.def("exl3_dec_gemv", &exl3_dec_gemv, "exl3_dec_gemv",@@ -397,6 +405,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)m.def("exl3_dec_router_rows", &exl3_dec_router_rows, "exl3_dec_router_rows");m.def("exl3_dec_rms_norm", &exl3_dec_rms_norm, "exl3_dec_rms_norm");m.def("fused_gated_rms_norm", &fused_gated_rms_norm, "fused_gated_rms_norm");+ m.def("mul_sigmoid_pad", &mul_sigmoid_pad, "mul_sigmoid_pad");+ m.def("pad_copy", &pad_copy, "pad_copy");m.def("fused_silu_mul", &fused_silu_mul, "fused_silu_mul");m.def("skinny_set_onepass", &skinny_set_onepass, "skinny_set_onepass");m.def("kda_gate", &kda_gate, "kda_gate");diff --git a/exllamav3/exllamav3_ext/fused_elt.cuh b/exllamav3/exllamav3_ext/fused_elt.cuhindex 9492b60..e746849 100644--- a/exllamav3/exllamav3_ext/fused_elt.cuh+++ b/exllamav3/exllamav3_ext/fused_elt.cuh@@ -16,7 +16,27 @@ void fused_gated_rms_normdouble constant_bias,int64_t w_groups,bool gate_first,- int64_t gate_act+ int64_t gate_act,+ int64_t y_pitch, // 0 = y contiguous; else y is [tokens, y_pitch] storage+ int64_t hpt // heads per token row when y_pitch != 0+);++// out[row, 0:k] = x[row, 0:k] for 2-byte elements, out at row pitch `pitch` (consumer-side row padding of a GEMM input)+void pad_copy+(+ const at::Tensor& x,+ at::Tensor& out,+ int64_t pitch+);++// out = x * sigmoid(g) (fp16; the ext_fallbacks.mul_sigmoid_ arithmetic: sigmoid rounded to half, then the half product)+// written to a row-padded view: x, g contiguous [..., k], out columns contiguous at row pitch `pitch`+void mul_sigmoid_pad+(+ const at::Tensor& x,+ const at::Tensor& g,+ at::Tensor& out,+ int64_t pitch);// z = silu(x) * y (ext_fallbacks._act_mul contract incl. act_limit clamps); x/y f16 or f32, z f16diff --git a/exllamav3/exllamav3_ext/fused_elt_rocm.cu b/exllamav3/exllamav3_ext/fused_elt_rocm.cuindex e1a8be3..b582bd0 100644--- a/exllamav3/exllamav3_ext/fused_elt_rocm.cu+++ b/exllamav3/exllamav3_ext/fused_elt_rocm.cu@@ -6,11 +6,13 @@#include <c10/hip/HIPGuard.h>#include <ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h>#include <cstdint>+#include <limits>#include <cstdlib>#include "fused_elt.cuh"#include "util.h"#include "util.cuh"+#include "pad_pitch.h"// Arithmetic mirrors the ATen kernels the fallback chains launch (no fast-math intrinsics):// sigmoid(x) = 1 / (1 + expf(-x)), silu(x) = x / (1 + expf(-x)), mean = sum * (1 / N)@@ -48,13 +50,17 @@ void fused_gated_rms_norm_kernelconst float constant_bias,const int w_groups,const bool gate_first,- const int gate_act+ const int gate_act,+ const size_t ypitch,+ const int hpt){const int lane = threadIdx.x & 31;const int row = blockIdx.x * (GN_THREADS / 32) + (threadIdx.x >> 5);if (row >= rows) return;const size_t off = (size_t) row * dim;+ // y token rows may sit at a padded pitch (ypitch != 0): row = token * hpt + head+ const size_t yoff = ypitch ? pad_norm_off((size_t) row, hpt, ypitch, dim) : off;float ni[GN_MAX];float gt[GN_MAX];@@ -104,8 +110,8 @@ void fused_gated_rms_norm_kernelfloat h = ni[j] * r;h = h * wf;if (!gate_first) h = h * gt[j];- if (Y_F32) ((float*) y)[off + i] = h;- else ((half*) y)[off + i] = __float2half_rn(h);+ if (Y_F32) ((float*) y)[yoff + i] = h;+ else ((half*) y)[yoff + i] = __float2half_rn(h);}}}@@ -120,7 +126,9 @@ void fused_gated_rms_normdouble constant_bias,int64_t w_groups,bool gate_first,- int64_t gate_act+ int64_t gate_act,+ int64_t y_pitch,+ int64_t hpt){const at::Device device = x.device();@@ -132,10 +140,22 @@ void fused_gated_rms_normTORCH_CHECK(w.dtype() == at::kBFloat16 || w.dtype() == at::kFloat, "fused_gated_rms_norm: w must be bf16/f32");TORCH_CHECK(g.dtype() == at::kBFloat16 || g.dtype() == at::kFloat || g.dtype() == at::kHalf,"fused_gated_rms_norm: g must be bf16/f32/f16");- TORCH_CHECK(x.is_contiguous() && y.is_contiguous() && g.is_contiguous() && w.is_contiguous(),+ TORCH_CHECK(x.is_contiguous() && g.is_contiguous() && w.is_contiguous(),"fused_gated_rms_norm: tensors must be contiguous");const int dim = x.size(-1);const int rows = x.numel() / dim;+ if (y_pitch == 0)+ {+ TORCH_CHECK(y.is_contiguous(), "fused_gated_rms_norm: tensors must be contiguous");+ }+ else+ {+ // padded y: [tokens, y_pitch] storage, hpt heads of dim per token, columns contiguous+ TORCH_CHECK(hpt >= 1 && rows % hpt == 0 && y.stride(-1) == 1 && y_pitch >= hpt * dim && y_pitch <= std::numeric_limits<int>::max(),+ "fused_gated_rms_norm: bad padded y");+ TORCH_CHECK(pad_view_fits(y.storage_offset(), rows / hpt, y_pitch, hpt * dim, (int64_t) (y.storage().nbytes() / y.element_size())),+ "fused_gated_rms_norm: padded y outside its storage");+ }TORCH_CHECK(dim <= 32 * GN_MAX && dim % 128 == 0, "fused_gated_rms_norm: dim must be <= 512 and a multiple of 128");TORCH_CHECK(y.numel() == x.numel() && g.numel() == x.numel() && w_groups >= 1 && w.numel() == w_groups * dim,"fused_gated_rms_norm: shape mismatch");@@ -147,7 +167,7 @@ void fused_gated_rms_normconst int blocks = (rows + GN_THREADS / 32 - 1) / (GN_THREADS / 32);#define GN_LAUNCH(GT, WF, YF) fused_gated_rms_norm_kernel<GT, WF, YF><<<blocks, GN_THREADS, 0, stream>>>( \(const uint16_t*) x.data_ptr(), w.data_ptr(), y.data_ptr(), g.data_ptr(), rows, dim, \- (float) eps, (float) constant_bias, (int) w_groups, gate_first, (int) gate_act)+ (float) eps, (float) constant_bias, (int) w_groups, gate_first, (int) gate_act, (size_t) y_pitch, (int) (hpt < 1 ? 1 : hpt))#define GN_W(GT) \if ( wf && yf) GN_LAUNCH(GT, true, true); \else if ( wf && !yf) GN_LAUNCH(GT, true, false); \@@ -161,6 +181,108 @@ void fused_gated_rms_normcuda_check(hipPeekAtLastError());}+// ------------------------------------------------------------------------------------------------+// out[row, col] = x * sigmoid(g) at a padded row pitch. One thread per half2 pair (k even: a pair never straddles a row).++#define MSP_THREADS 256++__global__ __launch_bounds__(MSP_THREADS)+void mul_sigmoid_pad_kernel+(+ const half* __restrict__ x,+ const half* __restrict__ g,+ half* __restrict__ out,+ const size_t numel,+ const size_t k,+ const size_t pitch+)+{+ const size_t idx = (size_t) blockIdx.x * MSP_THREADS + threadIdx.x;+ if (idx >= numel / 2) return;+ const half2 x2 = ((const half2*) x)[idx];+ const half2 g2 = ((const half2*) g)[idx];+ const half s0 = __float2half_rn(fe_sigmoid(__half2float(__low2half(g2))));+ const half s1 = __float2half_rn(fe_sigmoid(__half2float(__high2half(g2))));+ const half r0 = __float2half_rn(__half2float(__low2half(x2)) * __half2float(s0));+ const half r1 = __float2half_rn(__half2float(__high2half(x2)) * __half2float(s1));+ *((half2*) (out + pad_flat_off(2 * idx, k, pitch))) = __halves2half2(r0, r1);+}++void mul_sigmoid_pad+(+ const at::Tensor& x,+ const at::Tensor& g,+ at::Tensor& out,+ int64_t pitch+)+{+ const at::Device device = x.device();+ c10::cuda::OptionalCUDAGuard device_guard(device);+ hipStream_t stream = c10::hip::getCurrentHIPStream(device.index()).stream();++ TORCH_CHECK(x.dtype() == at::kHalf && g.dtype() == at::kHalf && out.dtype() == at::kHalf, "mul_sigmoid_pad: fp16 tensors");+ TORCH_CHECK(x.sizes() == g.sizes() && x.numel() == out.numel(), "mul_sigmoid_pad: shape mismatch");+ TORCH_CHECK(x.is_contiguous() && g.is_contiguous(), "mul_sigmoid_pad: x and g must be contiguous");+ const int64_t k = x.size(-1);+ TORCH_CHECK(k >= 2 && k % 2 == 0 && pitch % 2 == 0, "mul_sigmoid_pad: k and pitch must be even");+ TORCH_CHECK(out.stride(-1) == 1 && ((uintptr_t) out.data_ptr()) % 4 == 0, "mul_sigmoid_pad: out columns contiguous, 4-byte aligned");+ const int64_t rows = x.numel() / k;+ TORCH_CHECK(pad_view_fits(out.storage_offset(), rows, pitch, k, (int64_t) (out.storage().nbytes() / sizeof(at::Half))),+ "mul_sigmoid_pad: out outside its storage");+ if (rows == 0) return;+ const size_t numel = x.numel();+ const size_t blocks = (numel / 2 + MSP_THREADS - 1) / MSP_THREADS;+ mul_sigmoid_pad_kernel<<<blocks, MSP_THREADS, 0, stream>>>(+ (const half*) x.data_ptr(), (const half*) g.data_ptr(), (half*) out.data_ptr(), numel, (size_t) k, (size_t) pitch);+ cuda_check(hipPeekAtLastError());+}++// ------------------------------------------------------------------------------------------------+// row-padded copy, one thread per 16-byte chunk (8 two-byte elements; pad_copy_ok guarantees no row straddle).++#define PCP_THREADS 256++__global__ __launch_bounds__(PCP_THREADS)+void pad_copy_kernel+(+ const uint4* __restrict__ x,+ uint16_t* __restrict__ out,+ const size_t chunks,+ const size_t k,+ const size_t pitch+)+{+ const size_t idx = (size_t) blockIdx.x * PCP_THREADS + threadIdx.x;+ if (idx >= chunks) return;+ *((uint4*) (out + pad_flat_off(8 * idx, k, pitch))) = x[idx];+}++void pad_copy+(+ const at::Tensor& x,+ at::Tensor& out,+ int64_t pitch+)+{+ const at::Device device = x.device();+ c10::cuda::OptionalCUDAGuard device_guard(device);+ hipStream_t stream = c10::hip::getCurrentHIPStream(device.index()).stream();++ TORCH_CHECK(x.element_size() == 2 && out.dtype() == x.dtype(), "pad_copy: 2-byte elements, same dtype");+ TORCH_CHECK(x.is_contiguous() && ((uintptr_t) x.data_ptr()) % 16 == 0, "pad_copy: x must be contiguous, 16-byte aligned");+ const int64_t k = x.size(-1);+ TORCH_CHECK(out.stride(-1) == 1 && ((uintptr_t) out.data_ptr()) % 16 == 0, "pad_copy: out columns contiguous, 16-byte aligned");+ TORCH_CHECK(pad_copy_ok(k, pitch, out.storage_offset()), "pad_copy: k, pitch or offset not a multiple of 8");+ TORCH_CHECK(x.numel() == out.numel(), "pad_copy: shape mismatch");+ const int64_t rows = x.numel() / k;+ TORCH_CHECK(pad_view_fits(out.storage_offset(), rows, pitch, k, (int64_t) (out.storage().nbytes() / 2)), "pad_copy: out outside its storage");+ if (rows == 0) return;+ const size_t chunks = (size_t) x.numel() / 8;+ const size_t blocks = (chunks + PCP_THREADS - 1) / PCP_THREADS;+ pad_copy_kernel<<<blocks, PCP_THREADS, 0, stream>>>((const uint4*) x.data_ptr(), (uint16_t*) out.data_ptr(), chunks, (size_t) k, (size_t) pitch);+ cuda_check(hipPeekAtLastError());+}+// ------------------------------------------------------------------------------------------------// silu(x) * y -> z (half). Half inputs: the fallback materializes silu(x) as half first.diff --git a/exllamav3/exllamav3_ext/gdn.cu b/exllamav3/exllamav3_ext/gdn.cuindex ac649d3..6c29b6e 100644--- a/exllamav3/exllamav3_ext/gdn.cu+++ b/exllamav3/exllamav3_ext/gdn.cu@@ -18,6 +18,14 @@ using bfloat16 = __nv_bfloat16;#define MAX_V_HEADS 64#define SUBK 4+// ablation arms (timing only, results are garbage by design): bit 1 = no state stores, bit 2 = no state loads (RS_REG kernels)+#if !defined(QWG_ABL)+#define QWG_ABL 0+#endif+// QWG_ABL_RT=1: the arms are chosen at run time (env EXL3_QWG_GABL, passed in the unused D parameter); timing builds only+#if !defined(QWG_ABL_RT)+#define QWG_ABL_RT 0+#endif#define FUSED_OP_2_THREADS 512#define FUSED_OP_3_THREADS 256@@ -684,6 +692,11 @@ void cuda_recurrent_gated_delta_rule_kernel_128const float* __restrict__ D // unused, matches the generic kernel signature){+#if QWG_ABL_RT+ const int qwg_abl = (int) (intptr_t) D;+#else+ constexpr int qwg_abl = QWG_ABL;+#endifconstexpr int HEAD_DIM = 128;constexpr int V_CHUNK_DIM = HEAD_DIM / V_SPLIT;constexpr int BTS = HEAD_DIM / SUBK;@@ -719,6 +732,8 @@ void cuda_recurrent_gated_delta_rule_kernel_128__shared__ float sh_dot2[SUBK][HEAD_DIM];__shared__ float sh_g[CHANNELWISE ? HEAD_DIM : 1];+ // with RS_REG the state stays in VGPRs across the R rows of one launch (loaded at s == 0 only)+ float rs[RS_REG ? BTS : 1];for (int s = 0; s < seqlen; ++s){const bfloat16* gl_q = mixed_qkv + k_head * HEAD_DIM;@@ -746,14 +761,13 @@ void cuda_recurrent_gated_delta_rule_kernel_128// RS_REG: this thread's BTS = 32 state values (one column, one k-slice) are loaded once, before the q/k norm phase, and kept in// VGPRs for both passes (was: two strided reads). Same arithmetic on the same values: bit-identical.- float rs[RS_REG ? BTS : 1];if constexpr (RS_REG){- if (t < V_CHUNK_DIM)+ if (s == 0 && t < V_CHUNK_DIM){const float* p = gl_rs_r + v_start + t + bt * BTS * HEAD_DIM;- #pragma unroll- for (int i = 0; i < BTS; ++i) rs[i] = p[i * HEAD_DIM];+ if (qwg_abl & 2) { _Pragma("unroll") for (int i = 0; i < BTS; ++i) rs[i] = 0.01f * (float) (i + t); }+ else { _Pragma("unroll") for (int i = 0; i < BTS; ++i) rs[i] = p[i * HEAD_DIM]; }}}@@ -842,7 +856,8 @@ void cuda_recurrent_gated_delta_rule_kernel_128{float state = RS_REG ? rs[i * 8 + j] : *rs_r;state = state * (CHANNELWISE ? *sh_g_rd : g_h) + *sh_k_rd * v * beta_h;- *rs_w = state;+ if (!(qwg_abl & 1)) *rs_w = state;+ if constexpr (RS_REG) rs[i * 8 + j] = state;v_out = v_out + *sh_q_rd * state;}}@@ -960,6 +975,12 @@ void cuda_recurrent_gated_delta_rule_grfloat scale = 1.0f / sqrtf(k_head_dim);+#if QWG_ABL_RT+ const char* gabl_env = getenv("EXL3_QWG_GABL");+ #define QWG_D_ARG (const float*) (intptr_t) (gabl_env ? atoi(gabl_env) : 0)+#else+ #define QWG_D_ARG nullptr+#endif#define KERNEL_ARGS \(const bfloat16*) mixed_qkv.data_ptr(), \(const float*) g.data_ptr(), \@@ -975,7 +996,7 @@ void cuda_recurrent_gated_delta_rule_grscale, \slots_ptr, \history_stride, \- nullptr+ QWG_D_ARG// recurrent_state is kernel param 3 and slots is param 12, patched when running in a graph#define LAUNCH_RULE(...) \@@ -992,6 +1013,10 @@ void cuda_recurrent_gated_delta_rule_gr// EXL3_GDN_RS_REG (default 1): KDA state held in VGPRs across the two passes (bit-identical; 0 = r2 kernel)const char* rs_env = getenv("EXL3_GDN_RS_REG");const bool rs_reg = rs_env ? atoi(rs_env) != 0 : true;+ // EXL3_GDN_RS_REG_GDN (default 1; GDN, per-head decay): state in VGPRs across the two passes and across the R rows of a+ // history launch (the thread rewrites exactly the values it reads, so no reload of the history it just wrote)+ const char* rsg_env = getenv("EXL3_GDN_RS_REG_GDN");+ const bool rs_reg_gdn = rsg_env ? atoi(rsg_env) != 0 : true; // default ON; =0 restores the reload pathif (channelwise){if (!history)@@ -1013,8 +1038,10 @@ void cuda_recurrent_gated_delta_rule_gr{if (k_head_dim == 128 && v_head_dim == 128){- if (v_split == 4) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<false, 4>)- else LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<false, 1>)+ if (v_split == 4 && rs_reg_gdn) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<false, 4, false, true>)+ else if (v_split == 4) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<false, 4>)+ else if (rs_reg_gdn) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<false, 1, false, true>)+ else LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<false, 1>)}else if (threads.x <= 128){@@ -1029,8 +1056,10 @@ void cuda_recurrent_gated_delta_rule_gr{if (k_head_dim == 128 && v_head_dim == 128){- if (v_split == 4) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<true, 4>)- else LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<true, 1>)+ if (v_split == 4 && rs_reg_gdn) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<true, 4, false, true>)+ else if (v_split == 4) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<true, 4>)+ else if (rs_reg_gdn) LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<true, 1, false, true>)+ else LAUNCH_RULE(cuda_recurrent_gated_delta_rule_kernel_128<true, 1>)}else if (threads.x <= 128){diff --git a/exllamav3/exllamav3_ext/hc_mix.cu b/exllamav3/exllamav3_ext/hc_mix.cuindex 9bac358..c893707 100644--- a/exllamav3/exllamav3_ext/hc_mix.cu+++ b/exllamav3/exllamav3_ext/hc_mix.cu@@ -2070,6 +2070,24 @@ __device__ __forceinline__ void unpack_s8x4(uint32_t v, float& f0, float& f1, flf3 = (float) ((int) v >> 24);}+// group scales (gs != 0): fn scales per 128 consecutive k of (h, d), f32 [M][H * D / 128]; up scales per 64 ranks per column,+// f32 [H][D / 4][ceil(LR / 64)][4]. Weight = half(code * scale) as fp32 (bit-exact twin of the fp16 kernels on the dequantised half weights).+#define GS_FN_G 128+#define GS_UP_G 64+// The product must be rounded to fp32 BEFORE the half rounding (the fp16 twin sees half(fp32(q * sc))); without the barrier the compiler+// fuses mul + convert into one v_fma_mix and rounds once (differs on exact half ties).+#ifndef GS_NOFUSE+#define GS_NOFUSE(p) asm volatile("" : "+v"(p))+#endif+__device__ __forceinline__ float gs_dq(float q, float sc) { float p = q * sc; GS_NOFUSE(p); return __half2float(__float2half_rn(p)); }+__device__ __forceinline__ void gs_unpack_s8x4(uint32_t v, float sc, float& f0, float& f1, float& f2, float& f3)+{+ unpack_s8x4(v, f0, f1, f2, f3);+ f0 = gs_dq(f0, sc); f1 = gs_dq(f1, sc); f2 = gs_dq(f2, sc); f3 = gs_dq(f3, sc);+}+__device__ __forceinline__ size_t gs_fn_idx(int j, int h, int c8, int D) { return (size_t) j * (4 * D / GS_FN_G) + (size_t) h * (D / GS_FN_G) + (c8 >> 4); }+__device__ __forceinline__ size_t gs_up_idx(int h, int c, int i, int D, int LR) { return (((size_t) h * (D / 4) + c) * ((LR + GS_UP_G - 1) / GS_UP_G) + (i >> 6)) * 4; }+template <int H>__global__ __launch_bounds__(GR_THREADS_A)void gr_dots_q8_kernel@@ -2079,7 +2097,8 @@ void gr_dots_q8_kernelconst float* __restrict__ fn_scale, // (M)float* __restrict__ dots, // (R, M + 1, H): per-stream dots, row M = sum sqconst int M,- const int D+ const int D,+ const int gs = 0){const int r = blockIdx.y;@@ -2105,8 +2124,17 @@ void gr_dots_q8_kernelfloat4 s1 = s4[(size_t) h * D4 + 2 * c + 1];int2 pk = f8[c];float w0, w1, w2, w3, w4, w5, w6, w7;- unpack_s8x4((uint32_t) pk.x, w0, w1, w2, w3);- unpack_s8x4((uint32_t) pk.y, w4, w5, w6, w7);+ if (gs)+ {+ const float gsc = fn_scale[gs_fn_idx(j, h, c, D)];+ gs_unpack_s8x4((uint32_t) pk.x, gsc, w0, w1, w2, w3);+ gs_unpack_s8x4((uint32_t) pk.y, gsc, w4, w5, w6, w7);+ }+ else+ {+ unpack_s8x4((uint32_t) pk.x, w0, w1, w2, w3);+ unpack_s8x4((uint32_t) pk.y, w4, w5, w6, w7);+ }a = fmaf(s0.x, w0, a); a = fmaf(s0.y, w1, a);a = fmaf(s0.z, w2, a); a = fmaf(s0.w, w3, a);a = fmaf(s1.x, w4, a); a = fmaf(s1.y, w5, a);@@ -2132,7 +2160,7 @@ void gr_dots_q8_kernel#pragma unrollfor (int w = 0; w < GR_THREADS_A / 32; ++w)v += red[threadIdx.x][w];- if (j < M) v *= fn_scale[j];+ if (j < M && !gs) v *= fn_scale[j];dots[((size_t) r * (M + 1) + j) * H + threadIdx.x] = v;}}@@ -2151,7 +2179,8 @@ void gr_finalize_q8_kernelconst int D,const int LR,const int chunk_cols,- const float rms_eps+ const float rms_eps,+ const int gs = 0){const int r = blockIdx.y;@@ -2194,9 +2223,15 @@ void gr_finalize_q8_kernelfloat4 g[H];#pragma unrollfor (int h = 0; h < H; ++h) g[h] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ float4 gsc[H];for (int i = lane; i < LR; i += 32){float ti = t_s[i];+ if (gs && (((i - lane) & 32) == 0)) // the 32-rank step that opens a 64-rank group (warp-uniform, lane < 32)+ {+ #pragma unroll+ for (int h = 0; h < H; ++h) gsc[h] = *(const float4*) (up_scale + gs_up_idx(h, c, i, D, LR));+ }#pragma unrollfor (int h = 0; h < H; ++h){@@ -2204,6 +2239,7 @@ void gr_finalize_q8_kerneluint32_t u = *(const uint32_t*) (upt + ((((size_t) h * D4 + c) * LR + i) * 4));float u0, u1, u2, u3;unpack_s8x4(u, u0, u1, u2, u3);+ if (gs) { u0 = gs_dq(u0, gsc[h].x); u1 = gs_dq(u1, gsc[h].y); u2 = gs_dq(u2, gsc[h].z); u3 = gs_dq(u3, gsc[h].w); }g[h].x = fmaf(ti, u0, g[h].x);g[h].y = fmaf(ti, u1, g[h].y);g[h].z = fmaf(ti, u2, g[h].z);@@ -2224,7 +2260,7 @@ void gr_finalize_q8_kernel#pragma unrollfor (int h = 0; h < H; ++h){- const float4 sc = *(const float4*) (up_scale + (size_t) h * D + 4 * c);+ const float4 sc = gs ? make_float4(1.0f, 1.0f, 1.0f, 1.0f) : *(const float4*) (up_scale + (size_t) h * D + 4 * c);float4 sv = s4[(size_t) h * D4 + c];half4 wq = *(const half4*) (w + (size_t) h * D + 4 * c);float coef = rmr_s[h] * inv_h;@@ -2244,6 +2280,21 @@ void gr_finalize_q8_kernel}}+#include "hc_mix_q8r.cuh"++// One-pass-over-rows int8 mix: bit-identical to the one-row-per-block kernels, default ON,+// EXL3_GR_MIX_Q8_1PASS=0 restores the old launch (read once at first call).+static bool gr_q8_onepass()+{+ static int v = -1;+ if (v < 0)+ {+ const char* e = getenv("EXL3_GR_MIX_Q8_1PASS");+ v = (e && *e == '0') ? 0 : 1;+ }+ return v == 1;+}+void gr_mix_q8(const at::Tensor& streams, // (R, H, D) float@@ -2282,9 +2333,12 @@ void gr_mix_q8TORCH_CHECK(dots.scalar_type() == at::kFloat, "gr_mix_q8: dots must be float32");TORCH_CHECK(mixed.scalar_type() == at::kFloat || mixed.scalar_type() == at::kHalf, "gr_mix_q8: mixed must be float32 or float16");TORCH_CHECK(fn.dim() == 2 && fn.size(0) == M && fn.size(1) == H * D, "gr_mix_q8: fn must have shape (LR [+ 4], 4 * D)");- TORCH_CHECK(fn_scale.dim() == 1 && fn_scale.size(0) == M, "gr_mix_q8: fn_scale must have shape (M)");+ // group scales when fn_scale has M * H * D / 128 entries (then up_scale has H * D * ceil(LR / 64))+ const int gs = fn_scale.numel() != M ? 1 : 0;+ TORCH_CHECK(!gs || D % GS_FN_G == 0, "gr_mix_q8: group scales need D % 128 == 0");+ TORCH_CHECK(fn_scale.dim() == 1 && fn_scale.size(0) == (gs ? (int64_t) M * H * D / GS_FN_G : (int64_t) M), "gr_mix_q8: fn_scale must have shape (M) or (M * 4 * D / 128)");TORCH_CHECK(upt.size(0) == H && upt.size(1) == D / 4 && upt.size(3) == 4, "gr_mix_q8: upt must have shape (4, D / 4, LR, 4)");- TORCH_CHECK(up_scale.dim() == 1 && up_scale.size(0) == H * D, "gr_mix_q8: up_scale must have shape (4 * D)");+ TORCH_CHECK(up_scale.dim() == 1 && up_scale.size(0) == (gs ? (int64_t) H * D * ((LR + GS_UP_G - 1) / GS_UP_G) : (int64_t) H * D), "gr_mix_q8: up_scale must have shape (4 * D) or (4 * D * ceil(LR / 64))");TORCH_CHECK(w.dim() == 1 && w.size(0) == H * D, "gr_mix_q8: w must have shape (4 * D)");TORCH_CHECK(dots.dim() == 3 && dots.size(0) == R && dots.size(1) == M + 1 && dots.size(2) == H, "gr_mix_q8: dots must have shape (R, M + 1, 4)");TORCH_CHECK(mixed.dim() == 2 && mixed.size(0) == R && mixed.size(1) == D, "gr_mix_q8: mixed must have shape (R, D)");@@ -2305,11 +2359,23 @@ void gr_mix_q8const at::cuda::OptionalCUDAGuard device_guard(device);cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ if (R <= GRR_MAX_RT && gr_q8_onepass()) // measured domain: decode / MTP verify rows; larger R keeps the old launch+ {+ grr_launch+ (+ (const float*) streams.data_ptr(), (const int8_t*) fn.data_ptr(), (const float*) fn_scale.data_ptr(),+ (const int8_t*) upt.data_ptr(), (const float*) up_scale.data_ptr(), (const half*) w.data_ptr(),+ post ? (float*) post.value().data_ptr() : nullptr, mixed.data_ptr(), (float*) dots.data_ptr(),+ (int) R, (int) M, (int) D, (int) LR, (float) rms_eps, mixed.dtype() == at::kHalf, 512, stream, gs+ );+ cuda_check(cudaPeekAtLastError());+ return;+ }dim3 grid_a(M + 1, R);gr_dots_q8_kernel<4><<<grid_a, GR_THREADS_A, 0, stream>>>((const float*) streams.data_ptr(), (const int8_t*) fn.data_ptr(), (const float*) fn_scale.data_ptr(),- (float*) dots.data_ptr(), M, D+ (float*) dots.data_ptr(), M, D, gs);cuda_check(cudaPeekAtLastError());@@ -2323,7 +2389,7 @@ void gr_mix_q8#define ARGS_Q8 \(const float*) streams.data_ptr(), (const float*) dots.data_ptr(), \(const int8_t*) upt.data_ptr(), (const float*) up_scale.data_ptr(), (const half*) w.data_ptr(), \- post_p, mixed.data_ptr(), D, LR, chunk_cols, (float) rms_eps+ post_p, mixed.data_ptr(), D, LR, chunk_cols, (float) rms_eps, gsif (mixed.dtype() == at::kHalf)gr_finalize_q8_kernel<4, true><<<grid_c, NUM_THREADS, smem, stream>>>(ARGS_Q8);elsediff --git a/exllamav3/exllamav3_ext/hc_mix_q8r.cuh b/exllamav3/exllamav3_ext/hc_mix_q8r.cuhnew file mode 100644index 0000000..0d1e5a0--- /dev/null+++ b/exllamav3/exllamav3_ext/hc_mix_q8r.cuh@@ -0,0 +1,377 @@+// one-pass int8 GatedResidual mix for R = 2..4 rows (decode verify / MTP).+//+// gr_dots_q8_kernel / gr_finalize_q8_kernel use a (blocks, R) grid, so every int8 weight byte+// is fetched R times per call. These kernels give one block per fn row j (dots) and one block+// per column chunk (finalize) and loop over RT rows inside, so each weight word is loaded once+// and used for RT rows. Per (row, j) and per (row, h, column) the thread-to-element mapping,+// the fmaf order, the shuffle tree and the red[] order are the old ones, so outputs are+// bit-identical to the one-row-per-block kernels (checked by torch.equal in the parity test).+//+// Needs from the including file: NUM_THREADS (256), GR_THREADS_A (64), sigmoidf_, unpack_s8x4,+// half4, LOW_TO_FLOAT, HIGH_TO_FLOAT.+#pragma once++#define GRR_MAX_RT 4++// J fn rows per block (JT): the stream quads loaded for a column are reused by JT weight rows.+// Blocks 0 .. ceil(M / JT) - 1 do fn rows; the last block (index ceil(M / JT)) does the sum of squares+// (dots row M). Per (row, j) the c mapping, fmaf order and reduction tree are unchanged.+// Tuning knobs.+// Rows per block (JT) by group size RT = 1..4; JT * RT * H must stay <= GR_THREADS_A (64).+#ifndef GRR_J1+#define GRR_J1 2+#endif+#ifndef GRR_J2+#define GRR_J2 4+#endif+#ifndef GRR_J3+#define GRR_J3 4+#endif+#ifndef GRR_J4+#define GRR_J4 1+#endif+#ifndef GRR_R4_OLD_DOTS+#define GRR_R4_OLD_DOTS 1+#endif+#ifndef GRR_DOTS_UNROLL+#define GRR_DOTS_UNROLL 1+#endif+#ifndef GRR_FIN_UNROLL+#define GRR_FIN_UNROLL 1+#endif+template <int RT> struct GrrJ { static constexpr int v = RT == 1 ? GRR_J1 : RT == 2 ? GRR_J2 : RT == 3 ? GRR_J3 : GRR_J4; };++template <int H, int RT, int JT>+__global__ __launch_bounds__(GR_THREADS_A)+void gr_dots_q8r_kernel+(+ const float* __restrict__ streams, // (RT, H, D)+ const int8_t* __restrict__ fn, // (M, H * D) int8+ const float* __restrict__ fn_scale, // (M)+ float* __restrict__ dots, // (RT, M + 1, H)+ const int M,+ const int D,+ const int gs = 0+)+{+ static_assert(JT * RT * H <= GR_THREADS_A, "write-out phase uses one thread per (row, rowset, stream)");+ const int D4 = D / 4;+ const int ngrp = (M + JT - 1) / JT;+ const bool sq = blockIdx.x == ngrp; // sum-of-squares block+ const int j0 = blockIdx.x * JT;++ __shared__ float red[JT][RT][H][GR_THREADS_A / 32];+ const int lane = threadIdx.x % 32;+ const int warp = threadIdx.x / 32;++ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ float a[JT][RT];+ #pragma unroll+ for (int u = 0; u < JT; ++u)+ #pragma unroll+ for (int q = 0; q < RT; ++q) a[u][q] = 0.0f;+ if (!sq)+ {+ const int2* f8[JT];+ #pragma unroll+ for (int u = 0; u < JT; ++u)+ f8[u] = (const int2*) (fn + ((size_t) min(j0 + u, M - 1) * H + h) * D); // clamped: tail rows are discarded+ #pragma unroll GRR_DOTS_UNROLL+ for (int c = threadIdx.x; c < D4 / 2; c += GR_THREADS_A)+ {+ float wv[JT][8];+ #pragma unroll+ for (int u = 0; u < JT; ++u)+ {+ int2 pk = f8[u][c];+ if (gs)+ {+ const float gsc = fn_scale[gs_fn_idx(min(j0 + u, M - 1), h, c, D)];+ gs_unpack_s8x4((uint32_t) pk.x, gsc, wv[u][0], wv[u][1], wv[u][2], wv[u][3]);+ gs_unpack_s8x4((uint32_t) pk.y, gsc, wv[u][4], wv[u][5], wv[u][6], wv[u][7]);+ }+ else+ {+ unpack_s8x4((uint32_t) pk.x, wv[u][0], wv[u][1], wv[u][2], wv[u][3]);+ unpack_s8x4((uint32_t) pk.y, wv[u][4], wv[u][5], wv[u][6], wv[u][7]);+ }+ }+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ {+ const float4* s4 = (const float4*) (streams + (size_t) q * H * D);+ float4 s0 = s4[(size_t) h * D4 + 2 * c];+ float4 s1 = s4[(size_t) h * D4 + 2 * c + 1];+ #pragma unroll+ for (int u = 0; u < JT; ++u)+ {+ float x = a[u][q];+ x = fmaf(s0.x, wv[u][0], x); x = fmaf(s0.y, wv[u][1], x);+ x = fmaf(s0.z, wv[u][2], x); x = fmaf(s0.w, wv[u][3], x);+ x = fmaf(s1.x, wv[u][4], x); x = fmaf(s1.y, wv[u][5], x);+ x = fmaf(s1.z, wv[u][6], x); x = fmaf(s1.w, wv[u][7], x);+ a[u][q] = x;+ }+ }+ }+ }+ else+ {+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ {+ const float4* s4 = (const float4*) (streams + (size_t) q * H * D);+ float x = 0.0f;+ for (int c = threadIdx.x; c < D4; c += GR_THREADS_A)+ {+ float4 sv = s4[(size_t) h * D4 + c];+ x = fmaf(sv.x, sv.x, fmaf(sv.y, sv.y, fmaf(sv.z, sv.z, fmaf(sv.w, sv.w, x))));+ }+ a[0][q] = x;+ }+ }+ #pragma unroll+ for (int u = 0; u < JT; ++u)+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ {+ float x = a[u][q];+ for (int offset = 16; offset > 0; offset >>= 1)+ x += __shfl_down_sync(0xffffffffu, x, offset);+ if (lane == 0) red[u][q][h][warp] = x;+ }+ }+ __syncthreads();+ if (threadIdx.x < JT * RT * H)+ {+ const int u = threadIdx.x / (RT * H);+ const int q = (threadIdx.x / H) % RT;+ const int h = threadIdx.x % H;+ const int j = sq ? M : j0 + u;+ if (sq ? u == 0 : j < M)+ {+ float v = 0.0f;+ #pragma unroll+ for (int w = 0; w < GR_THREADS_A / 32; ++w)+ v += red[u][q][h][w];+ if (!sq && !gs) v *= fn_scale[j];+ dots[((size_t) q * (M + 1) + j) * H + h] = v;+ }+ }+}++template <int H, int RT, bool HALF_OUT>+__global__ __launch_bounds__(NUM_THREADS)+void gr_finalize_q8r_kernel+(+ const float* __restrict__ streams, // (RT, H, D)+ const float* __restrict__ dots, // (RT, M + 1, H)+ const int8_t* __restrict__ upt, // (H, D / 4, LR, 4) int8+ const float* __restrict__ up_scale, // (H * D)+ const half* __restrict__ w, // (H * D)+ float* __restrict__ post, // (RT, H) or nullptr+ void* __restrict__ mixed, // (RT, D) half or float+ const int D,+ const int LR,+ const int chunk_cols,+ const float rms_eps,+ const int gs = 0+)+{+ const int M = LR + (post ? H : 0);++ __shared__ float rmr_s[RT][H];+ extern __shared__ float t_s[]; // (RT, LR)+ if (threadIdx.x < RT * H)+ {+ const int q = threadIdx.x / H;+ const int h = threadIdx.x % H;+ const float* dr = dots + (size_t) q * (M + 1) * H;+ rmr_s[q][h] = rsqrtf(dr[(size_t) M * H + h] / (float) D + rms_eps);+ }+ __syncthreads();+ const float inv_h = 1.0f / (float) H;+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ {+ const float* dr = dots + (size_t) q * (M + 1) * H;+ for (int i = threadIdx.x; i < LR; i += NUM_THREADS)+ {+ float v = 0.0f;+ #pragma unroll+ for (int h = 0; h < H; ++h)+ v = fmaf(rmr_s[q][h], dr[(size_t) i * H + h], v);+ v *= inv_h;+ t_s[q * LR + i] = v * sigmoidf_(v);+ }+ if (post && blockIdx.x == 0 && threadIdx.x < H)+ {+ float v = 0.0f;+ #pragma unroll+ for (int h = 0; h < H; ++h)+ v = fmaf(rmr_s[q][h], dr[(size_t) (LR + threadIdx.x) * H + h], v);+ post[(size_t) q * H + threadIdx.x] = 2.0f * sigmoidf_(v * inv_h);+ }+ }+ __syncthreads();++ const int c0 = blockIdx.x * chunk_cols;+ const int c1 = min(c0 + chunk_cols, D);+ const int D4 = D / 4;+ const int lane = threadIdx.x % 32;+ const int warp = threadIdx.x / 32;+ for (int c = c0 / 4 + warp; c < c1 / 4; c += NUM_THREADS / 32)+ {+ float4 g[RT][H];+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ #pragma unroll+ for (int h = 0; h < H; ++h) g[q][h] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ float4 gsc[H];+ #pragma unroll GRR_FIN_UNROLL+ for (int i = lane; i < LR; i += 32)+ {+ float ti[RT];+ #pragma unroll+ for (int q = 0; q < RT; ++q) ti[q] = t_s[q * LR + i];+ if (gs && (((i - lane) & 32) == 0)) // the 32-rank step that opens a 64-rank group (warp-uniform, lane < 32)+ {+ #pragma unroll+ for (int h = 0; h < H; ++h) gsc[h] = *(const float4*) (up_scale + gs_up_idx(h, c, i, D, LR));+ }+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ uint32_t u = *(const uint32_t*) (upt + ((((size_t) h * D4 + c) * LR + i) * 4));+ float u0, u1, u2, u3;+ unpack_s8x4(u, u0, u1, u2, u3);+ if (gs) { u0 = gs_dq(u0, gsc[h].x); u1 = gs_dq(u1, gsc[h].y); u2 = gs_dq(u2, gsc[h].z); u3 = gs_dq(u3, gsc[h].w); }+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ {+ g[q][h].x = fmaf(ti[q], u0, g[q][h].x);+ g[q][h].y = fmaf(ti[q], u1, g[q][h].y);+ g[q][h].z = fmaf(ti[q], u2, g[q][h].z);+ g[q][h].w = fmaf(ti[q], u3, g[q][h].w);+ }+ }+ }+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ #pragma unroll+ for (int h = 0; h < H; ++h)+ for (int offset = 16; offset > 0; offset >>= 1)+ {+ g[q][h].x += __shfl_xor_sync(0xffffffffu, g[q][h].x, offset);+ g[q][h].y += __shfl_xor_sync(0xffffffffu, g[q][h].y, offset);+ g[q][h].z += __shfl_xor_sync(0xffffffffu, g[q][h].z, offset);+ g[q][h].w += __shfl_xor_sync(0xffffffffu, g[q][h].w, offset);+ }+ if (lane != 0) continue;+ #pragma unroll+ for (int q = 0; q < RT; ++q)+ {+ const float4* s4 = (const float4*) (streams + (size_t) q * H * D);+ float4 o = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ const float4 sc = gs ? make_float4(1.0f, 1.0f, 1.0f, 1.0f) : *(const float4*) (up_scale + (size_t) h * D + 4 * c);+ float4 sv = s4[(size_t) h * D4 + c];+ half4 wq = *(const half4*) (w + (size_t) h * D + 4 * c);+ float coef = rmr_s[q][h] * inv_h;+ o.x = fmaf(sigmoidf_(g[q][h].x * sc.x) * coef * LOW_TO_FLOAT(wq.x), sv.x, o.x);+ o.y = fmaf(sigmoidf_(g[q][h].y * sc.y) * coef * HIGH_TO_FLOAT(wq.x), sv.y, o.y);+ o.z = fmaf(sigmoidf_(g[q][h].z * sc.z) * coef * LOW_TO_FLOAT(wq.y), sv.z, o.z);+ o.w = fmaf(sigmoidf_(g[q][h].w * sc.w) * coef * HIGH_TO_FLOAT(wq.y), sv.w, o.w);+ }+ if (HALF_OUT)+ {+ half2* out2 = (half2*) ((half*) mixed + (size_t) q * D);+ out2[c * 2] = __floats2half2_rn(o.x, o.y);+ out2[c * 2 + 1] = __floats2half2_rn(o.z, o.w);+ }+ else+ ((float4*) ((float*) mixed + (size_t) q * D))[c] = o;+ }+ }+}++// Host side launch geometry, shared by the extension wrapper and the standalone microbench.+struct GrrGeom+{+ int n_chunks;+ int chunk_cols;+ int smem; // bytes of dynamic shared memory for finalize+};++static inline GrrGeom grr_geom(int D, int LR, int RT, int max_chunks)+{+ const int gran = 4 * (NUM_THREADS / 32);+ int chunks_c = std::max(1, std::min((D + gran - 1) / gran, max_chunks));+ int chunk_cols = ((D / chunks_c + gran - 1) / gran) * gran;+ GrrGeom g;+ g.chunk_cols = chunk_cols;+ g.n_chunks = (D + chunk_cols - 1) / chunk_cols;+ g.smem = RT * LR * (int) sizeof(float);+ return g;+}++template <int RT>+static void grr_dots_group(const float* streams, const int8_t* fn, const float* fn_scale, float* dots, int M, int D, cudaStream_t stream, int gs)+{+ constexpr int JT = GrrJ<RT>::v;+ gr_dots_q8r_kernel<4, RT, JT><<<dim3((M + JT - 1) / JT + 1), GR_THREADS_A, 0, stream>>>(streams, fn, fn_scale, dots, M, D, gs);+}++// Launch one group of RT rows (pointers already offset to the group's first row).+template <int RT>+static void grr_launch_group+(+ const float* streams, const int8_t* fn, const float* fn_scale, const int8_t* upt,+ const float* up_scale, const half* w, float* post, void* mixed, float* dots,+ int M, int D, int LR, float rms_eps, bool half_out, int max_chunks, cudaStream_t stream, int gs+)+{+ // RT = 4: a (M + 1, 4) grid (4x the blocks of the one-pass dots) measured faster on the weights-in-MALL+ // regime than JT-row blocks (latency bound), so the group of 4 keeps the one-row-per-block dots kernel+ // and only the finalize is one-pass. Same numerics either way (bit-identical).+ if (RT == 4 && GRR_R4_OLD_DOTS)+ gr_dots_q8_kernel<4><<<dim3(M + 1, RT), GR_THREADS_A, 0, stream>>>(streams, fn, fn_scale, dots, M, D, gs);+ else+ grr_dots_group<RT>(streams, fn, fn_scale, dots, M, D, stream, gs);+ GrrGeom g = grr_geom(D, LR, RT, max_chunks);+ if (half_out)+ gr_finalize_q8r_kernel<4, RT, true><<<dim3(g.n_chunks), NUM_THREADS, g.smem, stream>>>+ (streams, dots, upt, up_scale, w, post, mixed, D, LR, g.chunk_cols, rms_eps, gs);+ else+ gr_finalize_q8r_kernel<4, RT, false><<<dim3(g.n_chunks), NUM_THREADS, g.smem, stream>>>+ (streams, dots, upt, up_scale, w, post, mixed, D, LR, g.chunk_cols, rms_eps, gs);+}++// All R rows: groups of GRR_MAX_RT rows, one weight pass per group.+static void grr_launch+(+ const float* streams, const int8_t* fn, const float* fn_scale, const int8_t* upt,+ const float* up_scale, const half* w, float* post, void* mixed, float* dots,+ int R, int M, int D, int LR, float rms_eps, bool half_out, int max_chunks, cudaStream_t stream, int gs = 0+)+{+ const size_t out_el = half_out ? sizeof(half) : sizeof(float);+ for (int r0 = 0; r0 < R; r0 += GRR_MAX_RT)+ {+ const int n = std::min(GRR_MAX_RT, R - r0);+ const float* s = streams + (size_t) r0 * 4 * D;+ float* d = dots + (size_t) r0 * (M + 1) * 4;+ float* p = post ? post + (size_t) r0 * 4 : nullptr;+ void* m = (char*) mixed + (size_t) r0 * D * out_el;+ #define GRR_CALL(N) grr_launch_group<N>(s, fn, fn_scale, upt, up_scale, w, p, m, d, M, D, LR, rms_eps, half_out, max_chunks, stream, gs)+ if (n == 1) GRR_CALL(1);+ else if (n == 2) GRR_CALL(2);+ else if (n == 3) GRR_CALL(3);+ else GRR_CALL(4);+ #undef GRR_CALL+ }+}diff --git a/exllamav3/exllamav3_ext/hgemm.cu b/exllamav3/exllamav3_ext/hgemm.cuindex 2f086d8..7830756 100644--- a/exllamav3/exllamav3_ext/hgemm.cu+++ b/exllamav3/exllamav3_ext/hgemm.cu@@ -5,6 +5,7 @@#include "util.h"#include "util.cuh"#include "quant/exl3_devctx.cuh"+#include "pad_pitch.h"#include <limits>#include <cstdlib>#include <type_traits>@@ -18,6 +19,30 @@ Row-major matmul using cuBLAS, a @ b -> cusing bfloat16 = __nv_bfloat16;+// row stride (elements) of the activation operand. Contiguous -> k (unchanged behaviour).+// A row-padded view (stride > k, columns contiguous, leading dims collapsible) is accepted so a producer can leave+// a non-power-of-two row pitch: K=6144 fp16 rows are 12288 B apart and the GEMM reads them at ~half rate.+// Returns false if the view cannot be expressed as one (m, k) matrix with a single row pitch or if the+// storage cannot hold (m-1)*lda + k elements (the bound that keeps the library from reading outside the buffer).+static bool a_row_pitch(const at::Tensor& a, int64_t& lda)+{+ const int dim = a.dim();+ if (dim < 1) return false;+ const int64_t k = a.size(-1);+ if (k < 1) return false;+ if (dim == 1) { lda = k; return true; }+ if (a.stride(-1) != 1) return false;+ int64_t m = a.size(-2);+ for (int i = dim - 3; i >= 0; --i)+ {+ if (a.size(i + 1) != 1 && a.stride(i) != a.stride(i + 1) * a.size(i + 1)) return false;+ m *= a.size(i);+ }+ lda = m == 1 ? k : a.stride(-2);+ if (lda < k || lda > std::numeric_limits<int>::max()) return false;+ return pad_view_fits(a.storage_offset(), m, lda, k, (int64_t) (a.storage().nbytes() / sizeof(at::Half)));+}+static void hgemm_gemmex_impl(at::Tensor a,@@ -48,6 +73,8 @@ static void hgemm_gemmex_implint size_k = a.size(-1);int size_m = a.numel() / size_k;int size_n = b.size(-1);+ int64_t a_pitch = 0;+ TORCH_CHECK(a_row_pitch(a, a_pitch), "hgemm: a must be contiguous or a row-padded view inside its storage");int64_t c_stride_m = c.stride(-2);TORCH_CHECK(c_stride_m >= size_n, "c row stride is too small");TORCH_CHECK(c_stride_m <= std::numeric_limits<int>::max(), "c row stride is too large");@@ -70,7 +97,7 @@ static void hgemm_gemmex_implCUBLAS_OP_N, CUBLAS_OP_N,size_n, size_m, size_k,&alpha_, b_ptr, CUDA_R_16F, size_n,- a_ptr, CUDA_R_16F, size_k,+ a_ptr, CUDA_R_16F, (int) a_pitch,&beta_, c.data_ptr(), c_type, (int) c_stride_m,CUBLAS_COMPUTE_32F,CUBLAS_GEMM_DEFAULT_TENSOR_OP@@ -179,13 +206,13 @@ static rocblas_handle handle(int device)struct Call{- rocblas_handle h; int m, n, k, ldc; const void* a; const void* b; void* c; rocblas_datatype ct;+ rocblas_handle h; int m, n, k, ldc, lda; const void* a; const void* b; void* c; rocblas_datatype ct;rocblas_status run(rocblas_gemm_algo algo, int sol) const{float alpha = 1.0f, beta = 0.0f;// column-major: C^T[n, m] = B^T[n, k] @ A^T[k, m], same mapping as hgemm_gemmex_implreturn rocblas_gemm_ex(h, rocblas_operation_none, rocblas_operation_none, n, m, k,- &alpha, b, rocblas_datatype_f16_r, n, a, rocblas_datatype_f16_r, k,+ &alpha, b, rocblas_datatype_f16_r, n, a, rocblas_datatype_f16_r, lda,&beta, c, ct, ldc, c, ct, ldc, rocblas_datatype_f32_r,algo, sol, rocblas_gemm_flags_none);}@@ -276,7 +303,9 @@ static bool try_launch(const at::Tensor& a, const at::Tensor& b, at::Tensor& c,if (m < MIN_M) return false;if (a.dtype() != at::kHalf || b.dtype() != at::kHalf) return false;if (c.dtype() != at::kHalf && c.dtype() != at::kFloat) return false;- if (b.dim() != 2 || !b.is_contiguous() || !a.is_contiguous() || c.stride(-1) != 1) return false;+ if (b.dim() != 2 || !b.is_contiguous() || c.stride(-1) != 1) return false;+ int64_t lda = 0;+ if (!a_row_pitch(a, lda)) return false;const int64_t ldc = c.stride(-2);if (ldc > std::numeric_limits<int>::max()) return false;int device;@@ -286,8 +315,9 @@ static bool try_launch(const at::Tensor& a, const at::Tensor& b, at::Tensor& c,std::lock_guard<std::mutex> lock(g_mutex);load(device);const bool f32 = c.dtype() == at::kFloat;- Key key(n, k, m_class(m), ldc == n ? 1 : 0, f32 ? 1 : 0);- Call call{handle(device), m, n, k, (int) ldc, a.data_ptr(), b.data_ptr(), c.data_ptr(),+ // bit 1 of the ldc field: padded A pitch (its winner is screened on the padded layout)+ Key key(n, k, m_class(m), (ldc == n ? 1 : 0) | (lda != k ? 2 : 0), f32 ? 1 : 0);+ Call call{handle(device), m, n, k, (int) ldc, (int) lda, a.data_ptr(), b.data_ptr(), c.data_ptr(),f32 ? rocblas_datatype_f32_r : rocblas_datatype_f16_r};rocblas_set_stream(call.h, stream);auto it = g_cache.find(key);diff --git a/exllamav3/exllamav3_ext/hip/hip_mma.cuh b/exllamav3/exllamav3_ext/hip/hip_mma.cuhold mode 100755new mode 100644diff --git a/exllamav3/exllamav3_ext/pad_pitch.h b/exllamav3/exllamav3_ext/pad_pitch.hnew file mode 100644index 0000000..9ce77b8--- /dev/null+++ b/exllamav3/exllamav3_ext/pad_pitch.h@@ -0,0 +1,43 @@+#pragma once+// index arithmetic of row-padded activation buffers, shared by the kernels (device) and the+// CPU bounds proof (tests/check_pad_bounds.cpp). One definition, so the proof checks the code that ships.+//+// Why: an fp16 activation with K=6144 has a 12288 B row pitch; the dense GEMM reads such rows at about half rate+// (rocBLAS, gfx1151). A pitch of K + 64 elements runs the same product bit-exactly at 87-90 % of peak.+#include <cstddef>+#include <cstdint>++#if defined(__HIPCC__) || defined(__CUDACC__)+#define PAD_HD __host__ __device__ __forceinline__+#else+#define PAD_HD inline+#endif++// Pitch (elements) of a padded row of k elements: k + PAD_ELEMS, or k (no padding) when the row is not a pitch hazard.+constexpr int PAD_ELEMS = 64;+PAD_HD int64_t pad_pitch_for(int64_t k) { return (k * 2) % 1024 == 0 ? k + PAD_ELEMS : k; }++// Gated norm output: row = token * hpt + head (hpt heads per token, dim elements each), y token row pitch = pitch.+// Element i of that row lands at pad_norm_off(...) + i.+PAD_HD size_t pad_norm_off(size_t row, int hpt, size_t pitch, int dim)+{+ return (row / (size_t) hpt) * pitch + (row % (size_t) hpt) * (size_t) dim;+}++// Flat element e of a (rows, k) tensor lands at pad_flat_off(e, k, pitch) in a (rows, pitch) buffer.+PAD_HD size_t pad_flat_off(size_t e, size_t k, size_t pitch)+{+ return (e / k) * pitch + (e % k);+}++// pad_copy (one 16-byte chunk = 8 two-byte elements per thread): a chunk never straddles a row and every chunk start is 16-byte aligned.+PAD_HD bool pad_copy_ok(int64_t k, int64_t pitch, int64_t storage_offset)+{+ return k >= 8 && k % 8 == 0 && pitch >= k && pitch % 8 == 0 && storage_offset % 8 == 0;+}++// A view (storage_offset, m rows of k elements at row pitch lda) fits a storage of storage_elems elements.+PAD_HD bool pad_view_fits(int64_t storage_offset, int64_t m, int64_t lda, int64_t k, int64_t storage_elems)+{+ return lda >= k && storage_offset + (m - 1) * lda + k <= storage_elems;+}diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cu b/exllamav3/exllamav3_ext/quant/exl3_dec.cuindex 404325d..bf06d26 100644--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cu@@ -1,6 +1,6 @@// Batch-1 EXL3 decode kernels for RDNA3.5 (gfx1151). See exl3_dec.cuh.//-// Layout facts used here (ref/frac_reconstruct.py, validated bit-exact against the fork's HIP+// Layout facts used here (ref/frac_reconstruct.py, validated bit-exact against the port's HIP// reconstruct kernels):// - trellis[kt][nt][WORDS] u32: tile (kt, nt) covers W rows 16kt.., columns 16nt.. (y = x @ W)// - the tile bit stream is MSB-first inside each u32; ring position p has its 16-bit window at@@ -31,6 +31,12 @@#include "exl3_dec.cuh"#include "../util.cuh"+// QWG_ABLATE=1 compiles runtime ablation arms into the dense gemv (env EXL3_QWG_DABL; timing only, garbage results by design):+// bit 1 = no trellis decode (loads kept alive by an xor), bit 2 = no DRAM stream (every k-tile read is k-row 0..ktw-1), bit 4 = no epilogue+#if !defined(QWG_ABLATE)+#define QWG_ABLATE 0+#endif+namespace exl3dec {typedef _Float16 f16x2 __attribute__((ext_vector_type(2)));@@ -346,7 +352,7 @@ template <int KB2> constexpr int ring_of() { return Fmt<KB2>::WORDS <= 32 ? EXL3// Accumulate x[kt0 .. kt0 + n) . W[.., nt] for one lane (n % RING == 0), tile words streamed// through a RING-deep register ring. xs: LDS input (fp16) for this wave's k range, 16 per k-tile.-template <int KB2, int CB = 2, int RING_ = 0>+template <int KB2, int CB = 2, int RING_ = 0, bool NODEC = false>__device__ __forceinline__ void lane_gemv(const u32x4* tiles, size_t tstride, const half* xs, int n, float* acc){constexpr int VEC = Fmt<KB2>::VEC;@@ -388,20 +394,21 @@ __device__ __forceinline__ void lane_gemv(const u32x4* tiles, size_t tstride, coconst f16x2* xq = reinterpret_cast<const f16x2*>(xs + i * 16);#pragma unrollfor (int q = 0; q < 8; ++q) xp[q] = xq[q];- tile_dot<KB2, CB>(reinterpret_cast<const uint32_t*>(buf[r]), xp, acc, dc);+ if constexpr (NODEC) { uint32_t xx = 0; for (int v = 0; v < VEC; ++v) xx ^= buf[r][v].x ^ buf[r][v].y ^ buf[r][v].z ^ buf[r][v].w; acc[0] += __uint_as_float(xx & 0x3fffffff); }+ else tile_dot<KB2, CB>(reinterpret_cast<const uint32_t*>(buf[r]), xp, acc, dc);if (i + RING < n) load_tile<KB2>(tiles + (i + RING) * tstride, buf[r]);__builtin_amdgcn_sched_barrier(0); // keep the scheduler from interleaving tiles (VGPR blowup)}}}-// R-row variant: each tile is loaded once (identical RING pipeline to lane_gemv), then+// R-row variant (REPORT-16): each tile is loaded once (identical RING pipeline to lane_gemv), then// applied to `nrows` independent input rows in the exact same per-row tile_dot/pair_dot arithmetic// lane_gemv would run for a batch-1 call on that row -- so row j of acc is bit-identical to what a// batch-1 lane_gemv(..., xs_rows[j], n, acc_row_j) call would produce. xp is scoped inside the row// loop (not hoisted per-row), so only one row's 8 xp registers are live at a time; acc[MOE_R_MAX][16]// (only the first `nrows` rows used) is the only cost that scales with rows.-// RM: compile-time row bound. The row loop used to run to the runtime nrows, which+// RM (REPORT-28): compile-time row bound. The row loop used to run to the runtime nrows, which// indexes acc[j] dynamically and pushes the whole accumulator array to scratch memory; unrolled to// RM with a uniform `j < nrows` guard, acc stays in VGPRs. Arithmetic per row is unchanged.// RING_ (default ring_of<KB2>) only sets how many tiles are in flight; the per-tile arithmetic and@@ -640,6 +647,9 @@ struct Jobsint K;int kbs; // k blocksint x_gstride; // strided input (see prologue_x), 0: contiguous+#if QWG_ABLATE+ int abl;+#endif};template <int KB2, int CB = 2>@@ -680,10 +690,20 @@ void gemv_kernel(const half* __restrict__ x, Jobs jobs, float* scratch, int* couconst int nt = strip * 32 + lane;if (nt < NT){+#if QWG_ABLATE+ const int kt0 = (jobs.abl & 2) ? 0 : k0 / 16 + wave * ktw;+ const u32x4* tiles = job.trellis + ((size_t) kt0 * NT + nt) * VEC;+ if (jobs.abl & 1) lane_gemv<KB2, CB, 0, true>(tiles, (size_t) NT * VEC, xs + wave * ktw * 16, ktw, acc);+ else lane_gemv<KB2, CB>(tiles, (size_t) NT * VEC, xs + wave * ktw * 16, ktw, acc);+#elseconst int kt0 = k0 / 16 + wave * ktw;const u32x4* tiles = job.trellis + ((size_t) kt0 * NT + nt) * VEC;lane_gemv<KB2, CB>(tiles, (size_t) NT * VEC, xs + wave * ktw * 16, ktw, acc);+#endif}+#if QWG_ABLATE+ if (jobs.abl & 4) { if (acc[0] == 1.2345f) *reinterpret_cast<float*>(job.out) = acc[1]; return; }+#endifblock_reduce<CB>(acc, red, z, xsum, wave, lane, tid);const int col0 = strip * STRIP;@@ -1007,7 +1027,7 @@ void moe_down_kernel(MoeArgs a, int kbs)// -------------------------------------------------------------------------------------------------// R-row union MoE: verify-window MoE, R<=8 rows sharing one launch. Each *unique*+// R-row union MoE (REPORT-16): verify-window MoE, R<=8 rows sharing one launch. Each *unique*// expert across the R rows' top-k selections is decoded exactly once (grid.y = unique-expert// index u, not row) and its lane_gemv accumulation is run once per row assigned to it, in the// exact per-lane arithmetic order (tile_dot/pair_dot, same acc[16] sequence) a batch-1@@ -1294,7 +1314,7 @@ void moe_down_kernel_r(MoeArgsR a, int kbs, int ctr_b_off)}}-// Device-side unique-expert / assignment table for the R-row union MoE: no host sync.+// Device-side unique-expert / assignment table for the R-row union MoE (REPORT-28): no host sync.// Generic in E, topk (<= 64) and R (<= MOE_R_MAX). Slot i = row * topk + k. A slot "leads" when no// earlier slot selected the same expert; leader i gets u = number of leaders before it, and// assign[u * MOE_R_MAX + c] lists every slot with that expert in slot order (same as the host build).@@ -1368,7 +1388,8 @@ __global__ void moe_combine_kernel_r(MoeArgsR a)// arrive reduces and selects.constexpr int ROUTER_KCHUNK = 64;-constexpr int CTR_ROUTER = 4000;+constexpr int CTR_ROUTER = 4000; // one arrival counter per row: CTR_ROUTER + row+constexpr int ROUTER_NORM_MAX_ROWS = 8;// Fused pre-norm (NORM): the block also computes the MLP pre-norm of r + xa (rms_norm_res_in// semantics, the same arithmetic as rms_norm_kernel mode 2), writes its 64 normalized fp16 inputs to@@ -1407,6 +1428,21 @@ void router_kernel(const half* __restrict__ x, RouterNorm rn, const half* __restconst int tid = threadIdx.x;const int kb = blockIdx.x;const int nkb = gridDim.x;+ // Multi-row launch (gridDim.y = NR verify rows, exl3_dec_router_norm with NR > 1): block row `row`+ // runs exactly the single-row code on row `row`'s slices of xa / r / y / sel / wts, its own+ // scratch slab and its own arrival counter, so every row is bitwise a single-row launch.+ // gridDim.y == 1 (all single-row callers): row 0, no offset, nothing changes.+ if (const int row = blockIdx.y)+ {+ x += (size_t) row * H;+ rn.xa = reinterpret_cast<const char*>(rn.xa) + (size_t) row * H * (rn.xa_half ? 2 : 4);+ rn.r += (size_t) row * H;+ rn.y += (size_t) row * H;+ sel += (size_t) row * topk;+ wts += (size_t) row * topk;+ scratch += (size_t) row * nkb * E;+ counters += row;+ }__shared__ float xs[ROUTER_KCHUNK];__shared__ float red[2048];const int k0 = kb * ROUTER_KCHUNK;@@ -2113,6 +2149,9 @@ static void dec_gemv_impljobs.K = Kdim;jobs.kbs = kbs_of(Kdim / 16, ktw, env_int("EXL3_DEC_KBS", 0));jobs.x_gstride = (int) x_gstride;+#if QWG_ABLATE+ jobs.abl = env_int("EXL3_QWG_DABL", 0);+#endifint blocks = 0, part = 0, ctr = CTR_GEMV;for (int i = 0; i < n; ++i){@@ -2196,7 +2235,7 @@ void exl3_dec_gemv_strided}// -------------------------------------------------------------------------------------------------// R-row dense GEMV: each weight tile is decoded once (identical RING pipeline to+// R-row dense GEMV (REPORT-17): each weight tile is decoded once (identical RING pipeline to// batch-1's gemv_kernel) and applied to up to `rpb` rows via lane_gemv_r, in the exact per-row// arithmetic order (tile_dot/pair_dot/block_reduce/arrive) a batch-1 exl3_dec_gemv call would// use for that row -- so row j's output is bit-identical to a fresh batch-1 call, PROVIDED ktw@@ -2396,6 +2435,9 @@ static void dec_gemv_r_implint rpb = std::max(1, std::min(R, GEMV_R_ROW_BUDGET / ktw));const int rpb_cap = env_int("EXL3_GEMV_R_RPB", 0);if (rpb_cap > 0) rpb = std::min(rpb, rpb_cap);+ // mimoident2 (MiMo, R 5..8 verify, bitwise independent of rpb): the 8-row kernel variant wins at R 5-6+ // but loses at R 7-8 (131 vs 123 ms per verify forward, spills); from R 7 on run two 4-row chunks (grid.y = 2).+ else if (R >= 7 && rpb > 4 && env_int("EXL3_GEMV_R_RPB78", 4) > 0) rpb = env_int("EXL3_GEMV_R_RPB78", 4);JobsR jobs;jobs.count = n;@@ -2672,7 +2714,7 @@ void exl3_dec_moe_sharedcuda_check(cudaPeekAtLastError());}-// R-row union MoE. See the comment above MoeArgsR. Builds the unique-expert /+// R-row union MoE, REPORT-16. See the comment above MoeArgsR. Builds the unique-expert /// assignment table on the host (R * topk <= 80 entries, negligible next to the GEMVs) and runs// gu + down + combine. x: [R, H] fp16, out: [R, H] fp32, selected/weights: [R, topk].void exl3_dec_moe_union@@ -2752,7 +2794,7 @@ void exl3_dec_moe_union}else{- // table built on device, grid.y = max possible U, padded slots exit at once+ // REPORT-28: table built on device, grid.y = max possible U, padded slots exit at onceconst int64_t experts_d = experts;TORCH_CHECK(topk <= 64, "exl3_dec_moe_union: device table needs topk <= 64");U = (int) std::min<int64_t>((int64_t) R * topk, experts_d);@@ -2967,17 +3009,23 @@ void exl3_dec_router_norm{const at::cuda::OptionalCUDAGuard device_guard(xa.device());cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();- const int H = xa.numel();- TORCH_CHECK((xa.dtype() == at::kHalf || xa.dtype() == at::kFloat) && xa.is_contiguous() && xa.numel() == xa.size(-1),- "exl3_dec_router_norm: xa fp16/fp32 [1, H]");- TORCH_CHECK(r.dtype() == at::kFloat && r.is_contiguous() && r.numel() == H, "exl3_dec_router_norm: r fp32 [1, H]");- TORCH_CHECK(y.dtype() == at::kHalf && y.is_contiguous() && y.numel() == H, "exl3_dec_router_norm: y fp16 [1, H]");- TORCH_CHECK(gate.dtype() == at::kHalf && gate.is_contiguous() && gate.dim() == 2 && gate.size(0) == H, "exl3_dec_router_norm: gate fp16 [H, E]");+ // NR rows (1..ROUTER_NORM_MAX_ROWS) in one launch: xa / r / y are [NR, H], selected / weights [NR, topk]+ TORCH_CHECK(gate.dtype() == at::kHalf && gate.is_contiguous() && gate.dim() == 2, "exl3_dec_router_norm: gate fp16 [H, E]");+ const int H = gate.size(0);const int E = gate.size(1);- const int topk = selected.numel();+ TORCH_CHECK(H > 0 && xa.numel() % H == 0, "exl3_dec_router_norm: xa size");+ const int NR = xa.numel() / H;+ TORCH_CHECK(NR >= 1 && NR <= ROUTER_NORM_MAX_ROWS, "exl3_dec_router_norm: rows 1..8");+ TORCH_CHECK((xa.dtype() == at::kHalf || xa.dtype() == at::kFloat) && xa.is_contiguous() && xa.numel() == (int64_t) NR * H,+ "exl3_dec_router_norm: xa fp16/fp32 [NR, H]");+ TORCH_CHECK(r.dtype() == at::kFloat && r.is_contiguous() && r.numel() == (int64_t) NR * H, "exl3_dec_router_norm: r fp32 [NR, H]");+ TORCH_CHECK(y.dtype() == at::kHalf && y.is_contiguous() && y.numel() == (int64_t) NR * H, "exl3_dec_router_norm: y fp16 [NR, H]");+ TORCH_CHECK(selected.numel() % NR == 0, "exl3_dec_router_norm: selected size");+ const int topk = selected.numel() / NR;TORCH_CHECK(H % ROUTER_KCHUNK == 0 && E <= 1024 && E % 8 == 0 && topk <= 64 && topk <= E, "exl3_dec_router_norm: unsupported shape");- TORCH_CHECK(selected.dtype() == at::kLong && weights.dtype() == at::kHalf && weights.numel() == topk, "exl3_dec_router_norm: outputs");- TORCH_CHECK(scratch.numel() >= (int64_t) (H / ROUTER_KCHUNK) * E && counters.numel() > CTR_ROUTER, "exl3_dec_router_norm: workspace");+ TORCH_CHECK(selected.dtype() == at::kLong && selected.is_contiguous() && weights.dtype() == at::kHalf && weights.is_contiguous() &&+ weights.numel() == (int64_t) NR * topk, "exl3_dec_router_norm: outputs");+ TORCH_CHECK(scratch.numel() >= (int64_t) NR * (H / ROUTER_KCHUNK) * E && counters.numel() >= CTR_ROUTER + NR, "exl3_dec_router_norm: workspace");const float* bp = nullptr;if (bias.has_value() && bias->defined()){@@ -2999,7 +3047,7 @@ void exl3_dec_router_norm}rn.eps = (float) eps; rn.cbias = (float) constant_bias; rn.cscale = (float) constant_scale;rn.y = reinterpret_cast<half*>(y.data_ptr());- router_kernel<true><<<H / ROUTER_KCHUNK, 256, 0, stream>>>(+ router_kernel<true><<<dim3(H / ROUTER_KCHUNK, NR), 256, 0, stream>>>(nullptr, rn, reinterpret_cast<const half*>(gate.data_ptr()), bp,selected.data_ptr<int64_t>(), reinterpret_cast<half*>(weights.data_ptr()),scratch.data_ptr<float>(), counters.data_ptr<int>(), H, E, topk, (float) scale);diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cuh b/exllamav3/exllamav3_ext/quant/exl3_dec.cuhindex b7b5952..1cc3b8f 100644--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cuh+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cuh@@ -9,7 +9,7 @@// a 512-column strip, so one launch covers what the generic path does in three.//// K (bits per weight) in {2, 2.5, 3, 4, 5, 6}. `mcg` selects the codebook for all matrices of a-// launch (uniform per layer): false = mul1, true = mcg (GLM-5.3-Flash packs).+// launch (uniform per layer): false = mul1, true = mcg (GLM-5.3-Flash packs, see REPORT-22).// The two templates decode bit-identically to their codebook's reference decode; only the// summation order differs from the reconstruct+hgemm path.@@ -62,7 +62,7 @@ void exl3_dec_gemv_multibool mcg = false);-// R-row dense GEMV: y[R, N] = x[R, K] @ W, one launch, each weight tile decoded once+// R-row dense GEMV (REPORT-17): y[R, N] = x[R, K] @ W, one launch, each weight tile decoded once// and applied to every row -- bit-exact vs R independent exl3_dec_gemv calls PROVIDED the caller// doesn't touch EXL3_DEC_KTW/EXL3_DEC_MIN_BLOCKS/EXL3_DEC_KBS differently between the two (same// pick_ktw/kbs_of call as batch-1). x must be contiguous [R, K]; no strided (x_gstride) form yet.@@ -165,7 +165,7 @@ void exl3_dec_moe_sharedbool mcg);-// R-row union MoE, R<=8: x [R,H] fp16, out [R,H] fp32, selected/weights [R,topk].+// R-row union MoE (REPORT-16), R<=8: x [R,H] fp16, out [R,H] fp32, selected/weights [R,topk].// Each unique expert across the R rows' selections is decoded once and applied to every row that// picked it, in the exact batch-1 exl3_dec_moe per-lane arithmetic order (row r bit-identical to// a fresh batch-1 call). act: fp16 [R*topk, I], down_part: fp32 [R*topk, H] workspaces.diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv.cu b/exllamav3/exllamav3_ext/quant/exl3_gemv.cuindex 6fdc340..03ac583 100644--- a/exllamav3/exllamav3_ext/quant/exl3_gemv.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv.cu@@ -20,6 +20,9 @@ namespace cg = cooperative_groups;#include "../util.h"#include "../util.cuh"#include "exl3_gemv_kernel.cuh"+#if defined(USE_ROCM)+#include "exl3_moe_valu.cuh" // VALU grouped-MoE decode matvec, opt-in EXL3_MOE_VALU=1 (K2 and K4 experts)+#endif#include "exl3_devctx.cuh"#include <cstdio>#include <cstring>@@ -675,6 +678,37 @@ static void launch_moe_grouped_one// K (the experts' trellis bitrate, integer or half-integer) is a template parameter of the// grouped GEMV, so the entry point dispatches on it; MOE_CFG stays the runtime knob it always was.+// EXL3_MOE_VALU=1: VALU decode matvec (exl3_moe_valu.cuh) for K2/K4 experts instead of the WMMA body. Default off.+static int g_moe_valu_override = -1; // test hook (exl3_moe_valu_override): -1 = env, 0/1 = forced+static inline bool moe_valu_enabled()+{+ if (g_moe_valu_override >= 0) return g_moe_valu_override != 0;+ static const bool on = [] { const char* e = getenv("EXL3_MOE_VALU"); return e && atoi(e) != 0; }();+ return on;+}+void exl3_moe_valu_override(int64_t v) { g_moe_valu_override = (int) v; }++template <int K, bool FP32, bool TWO>+static void launch_moe_valu+(+ const half* A, const int64_t* selected, const MoeDedup* dd,+ const int64_t* t0, const int64_t* t1, void* C,+ int size_k, int size_n, int experts, int assignments, hipStream_t stream+)+{+ constexpr int W = EXL3_MOE_VALU_W;+ const dim3 grid(mv::grid_x(size_n / 16, W), assignments, TWO ? 2 : 1);+ const bool deep = mv::chunk(size_k / 16) >= 5; // register ring of 5 slices, else 3+ const int64_t* sel = dd ? dd->sorted_expert : selected;+ const int* gs = dd ? dd->group_start : nullptr;+ const int* ng = dd ? dd->num_groups : nullptr;+#define MV_LAUNCH(DD, VU) \+ moe_valu_kernel<K, FP32, DD, TWO, VU><<<grid, W * 32, 0, stream>>>(A, sel, gs, ng, t0, t1, C, size_k, size_n, experts, assignments)+ if (dd) { if (deep) MV_LAUNCH(true, 5); else MV_LAUNCH(true, 3); }+ else { if (deep) MV_LAUNCH(false, 5); else MV_LAUNCH(false, 3); }+#undef MV_LAUNCH+}+template <int K, bool HALF, bool FP32, bool TWO>static void launch_moe_grouped(@@ -683,6 +717,14 @@ static void launch_moe_groupedint size_k, int size_n, int experts, int assignments, hipStream_t stream){+ if constexpr (!HALF && (K == 2 || K == 4))+ {+ if (moe_valu_enabled() && size_k % 16 == 0 && size_n % 32 == 0)+ {+ launch_moe_valu<K, FP32, TWO>(A, selected, dd, t0, t1, C, size_k, size_n, experts, assignments, stream);+ return;+ }+ }dim3 grid(size_n / 32, assignments, TWO ? 2 : 1);switch (moe_decode_cfg()){diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv.cuh b/exllamav3/exllamav3_ext/quant/exl3_gemv.cuhindex 070a084..c0ff4c1 100644--- a/exllamav3/exllamav3_ext/quant/exl3_gemv.cuh+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv.cuh@@ -103,3 +103,5 @@ void exl3_gemvbool mcg,bool mul1);++void exl3_moe_valu_override(int64_t v); // test hook: force EXL3_MOE_VALU on (1) / off (0) / back to env (-1) in this processdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cunew file mode 100644index 0000000..5f39bd3--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu@@ -0,0 +1,198 @@+#if defined(USE_ROCM)+#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#else+#include <cuda_fp16.h>+#endif+#include "exl3_moe_fused_api.h"+#include "hadamard.cuh"+#include <c10/cuda/CUDAGuard.h>+#include <ATen/cuda/CUDAContext.h>+#include <ATen/ops/empty.h>+#include "../util.h"+#include "../util.cuh"+#include "exl3_gemv_kernel.cuh"+#if defined(USE_ROCM)+#include "exl3_moe_valu.cuh" // mv_dot2+#include "exl3_moe_fused.cuh" // fused MoE half-layer, opt-in EXL3_MOE_FUSED=1+#endif+#include <cstdio>+#include <cstring>+#include <algorithm>++#if defined(USE_ROCM)++// ---------------------------------------------------------------------------------------------------------------------------+// EXL3_MOE_FUSED: one persistent launch per MoE half-layer (exl3_moe_fused.cuh). Entry points: exl3_moe_fused_half (launch),+// exl3_moe_fused_supported / _ws_bytes / _ws_offsets (plan). Only shapes listed in MF_SHAPES are instantiated.+// ---------------------------------------------------------------------------------------------------------------------------+namespace {+template <class S> struct MfShapeMatch+{+ static bool eq(int D, int H, int LR, int NEXP, int TOPK, int INTER, int RB, int SB)+ { return D == S::D && H == S::H && LR == S::LR && NEXP == S::NEXP && TOPK == S::TOPK && INTER == S::INTER && RB == S::RB && SB == S::SB; }+};+// workspace layout (bytes, 256-aligned): ctl (bar, done, err u32) | dots | post | mixed | scores | sgl | gu | dn | ydbg | seldbg+template <class S> std::vector<int64_t> mf_ws_offsets()+{+ using DM = mf::Dm<S>;+ const int NARM = mf::MAXR * S::TOPK + mf::MAXR;+ const int64_t sizes[] = {+ 256, // ctl+ (int64_t) mf::MAXR * (DM::MR + 1) * S::H * 4, // dots f32+ (int64_t) mf::MAXR * S::H * 4, // post f32+ (int64_t) mf::MAXR * S::D * 2, // mixed half+ (int64_t) mf::MAXR * S::NEXP * 2, // scores half+ 256, // sgl f32 (64)+ (int64_t) 2 * NARM * S::INTER * 2, // gu half+ (int64_t) NARM * S::D * 4, // dn f32+ (int64_t) mf::MAXR * S::D * 4, // ydbg f32+ (int64_t) mf::SELDBG_INTS * 4, // seldbg i32+ };+ std::vector<int64_t> off; int64_t o = 0;+ for (int64_t s : sizes) { off.push_back(o); o += (s + 255) / 256 * 256; }+ off.push_back(o); // total+ return off;+}+template <class S> int mf_grid()+{+ static int G = [] {+ int nb = 0, dev = 0; hipGetDevice(&dev);+ hipDeviceProp_t prop; hipGetDeviceProperties(&prop, dev);+ cuda_check(hipOccupancyMaxActiveBlocksPerMultiprocessor(&nb, (const void*) mf::moe_fused_kernel<S>, mf::THREADS, 0));+ return std::max(1, nb) * prop.multiProcessorCount;+ }();+ return G;+}+template <class S> void mf_launch+(+ const at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, const at::Tensor& upt, const at::Tensor& up_scale, const at::Tensor& w_h,+ const at::Tensor& router, const at::Tensor& sgate, const at::Tensor& wt, const at::Tensor& svt,+ at::Tensor& ws, double rms_eps, int native, int R, hipStream_t stream+)+{+ using DM = mf::Dm<S>;+ TORCH_CHECK(fn.numel() == (int64_t) DM::MR * S::H * S::D, "fused: fn size");+ const bool gs = fn_scale.numel() != DM::MR;+ TORCH_CHECK(!gs || mf::gs_ok<S>(), "fused: group scales need D % 128 == 0");+ TORCH_CHECK(fn_scale.numel() == mf::fn_scale_n<S>(gs), "fused: fn_scale size");+ TORCH_CHECK(upt.numel() == (int64_t) S::H * DM::D4 * S::LR * 4, "fused: upt size");+ TORCH_CHECK(up_scale.numel() == mf::up_scale_n<S>(gs) && w_h.numel() == (int64_t) S::H * S::D, "fused: up_scale / w_h size");+ TORCH_CHECK(router.numel() == (int64_t) S::NEXP * S::D && sgate.numel() == S::D, "fused: router size");+ TORCH_CHECK(wt.dtype() == at::kLong && wt.numel() == 3 * (S::NEXP + 1) && svt.dtype() == at::kLong && svt.numel() == 6 * (S::NEXP + 1), "fused: pointer tables");+ TORCH_CHECK(native == 0 || native == 1, "fused: native flag");+ const auto off = mf_ws_offsets<S>();+ TORCH_CHECK(ws.numel() >= off.back(), "fused: workspace too small");+ char* wb = (char*) ws.data_ptr();+ mf::Params p{};+ p.R = R; p.G = mf_grid<S>();+ TORCH_CHECK(p.G >= 1 && p.G <= mf::CTL_MAXB, "exl3_moe_fused: grid exceeds the barrier arrival-marker words");+ p.xin = (float*) x.data_ptr(); p.xout = (float*) x.data_ptr();+ p.fn = (const int8_t*) fn.data_ptr(); p.fn_scale = (const float*) fn_scale.data_ptr(); p.upt = (const int8_t*) upt.data_ptr();+ p.gs = gs ? 1 : 0; p.up_scale = (const float*) up_scale.data_ptr(); p.w = (const half*) w_h.data_ptr();+ p.router = (const half*) router.data_ptr(); p.sgate_w = (const half*) sgate.data_ptr();+ p.wt = (const uint32_t* const*) wt.data_ptr(); p.svt = (const half* const*) svt.data_ptr(); p.native = native;+ unsigned* ctl = (unsigned*) (wb + off[0]);+ p.bar = ctl; p.done = ctl + 1; p.err = (int*) (ctl + 2);+ p.dots = (float*) (wb + off[1]); p.post = (float*) (wb + off[2]); p.mixed = (half*) (wb + off[3]); p.scores = (half*) (wb + off[4]);+ p.sgl = (float*) (wb + off[5]); p.gu = (half*) (wb + off[6]); p.dn = (float*) (wb + off[7]); p.ydbg = (float*) (wb + off[8]); p.seldbg = (int*) (wb + off[9]);+ p.rms_eps = (float) rms_eps;+ mf::moe_fused_kernel<S><<<p.G, mf::THREADS, 0, stream>>>(p);+ cuda_check(hipPeekAtLastError());+}+} // namespace++#define MF_SHAPES(X) X(mf::QwenShape) X(mf::SmallTestShape) X(mf::SmallK3Shape) X(mf::QwenK3S4) X(mf::QwenK3S5) X(mf::QwenK4S4) X(mf::QwenK4S5) X(mf::SmallK3S4) X(mf::SmallK3S5) X(mf::SmallK4S4) X(mf::SmallK4S5)++bool exl3_moe_fused_supported(int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB)+{+#define X(S) if (MfShapeMatch<S>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) return true;+ MF_SHAPES(X)+#undef X+ return false;+}++std::vector<int64_t> exl3_moe_fused_ws_offsets(int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB)+{+#define X(S) if (MfShapeMatch<S>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) return mf_ws_offsets<S>();+ MF_SHAPES(X)+#undef X+ TORCH_CHECK(false, "exl3_moe_fused: shape not instantiated");+ return {};+}++int64_t exl3_moe_fused_grid(int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB)+{+#define X(S) if (MfShapeMatch<S>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) return mf_grid<S>();+ MF_SHAPES(X)+#undef X+ TORCH_CHECK(false, "exl3_moe_fused: shape not instantiated");+ return 0;+}++void exl3_moe_fused_half+(+ at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, const at::Tensor& upt, const at::Tensor& up_scale, const at::Tensor& w_h,+ const at::Tensor& router, const at::Tensor& sgate, const at::Tensor& wt, const at::Tensor& svt,+ at::Tensor& ws, double rms_eps, int64_t native, int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB+)+{+ const at::cuda::OptionalCUDAGuard device_guard(x.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ TORCH_CHECK(x.dtype() == at::kFloat && x.is_contiguous() && x.dim() == 4, "fused: x must be contiguous fp32 (b, s, H, D)");+ TORCH_CHECK(x.size(2) == H && x.size(3) == D, "fused: x shape");+ const int R = (int) (x.size(0) * x.size(1));+ TORCH_CHECK(R >= 1 && R <= mf::MAXR, "fused: rows 1..4");+ TORCH_CHECK(fn.dtype() == at::kChar && upt.dtype() == at::kChar, "fused: int8 weights");+ TORCH_CHECK(fn_scale.dtype() == at::kFloat && up_scale.dtype() == at::kFloat, "fused: fp32 scales");+ TORCH_CHECK(w_h.dtype() == at::kHalf && router.dtype() == at::kHalf && sgate.dtype() == at::kHalf, "fused: fp16 tensors");+ TORCH_CHECK(ws.dtype() == at::kByte, "fused: workspace is uint8");+#define X(S) if (MfShapeMatch<S>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { mf_launch<S>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, stream); return; }+ MF_SHAPES(X)+#undef X+ TORCH_CHECK(false, "exl3_moe_fused: shape not instantiated");+}++// ---- tile test entry: (bits, K, cf32) combinations instantiated: K = 640 / 2048 (down, float out), 2560 / 4096 (gate/up, half out); bits 2, 3, 4+namespace {+template <int BITS, bool CF, int KS>+bool mf_tt_launch(const at::Tensor& A, const at::Tensor& B, at::Tensor& C, int R, int nt, int native, hipStream_t stream)+{+ mf::mf_tile_test_kernel<BITS, CF, KS><<<1, mf::THREADS, 0, stream>>>((const uint32_t*) A.data_ptr(), (const uint32_t*) B.data_ptr(), C.data_ptr(), R, nt, native);+ cuda_check(hipPeekAtLastError());+ return true;+}+template <int BITS>+bool mf_tt_dispatch(int ks, bool cf, const at::Tensor& A, const at::Tensor& B, at::Tensor& C, int R, int nt, int native, hipStream_t stream)+{+ if (!cf && ks == 160) return mf_tt_launch<BITS, false, 160>(A, B, C, R, nt, native, stream);+ if (!cf && ks == 256) return mf_tt_launch<BITS, false, 256>(A, B, C, R, nt, native, stream);+ if (cf && ks == 40) return mf_tt_launch<BITS, true, 40>(A, B, C, R, nt, native, stream);+ if (cf && ks == 128) return mf_tt_launch<BITS, true, 128>(A, B, C, R, nt, native, stream);+ return false;+}+} // namespace++void exl3_moe_fused_tile_test(const at::Tensor& A, const at::Tensor& B, at::Tensor& C, int64_t bits, int64_t native)+{+ const at::cuda::OptionalCUDAGuard device_guard(A.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ TORCH_CHECK(A.dtype() == at::kHalf && A.dim() == 2 && A.is_contiguous(), "tile test: A half [R, K]");+ TORCH_CHECK(B.dtype() == at::kShort && B.is_contiguous(), "tile test: B int16 (native [K/16, N/16, 16 bits] or repacked)");+ const bool cf = C.dtype() == at::kFloat;+ TORCH_CHECK(cf || C.dtype() == at::kHalf, "tile test: C half or float");+ TORCH_CHECK(C.is_contiguous() && C.dim() == 2, "tile test: C [R, N]");+ const int R = (int) A.size(0), K = (int) A.size(1), ks = K / 16;+ TORCH_CHECK(R >= 1 && R <= mf::MAXR && K % 16 == 0, "tile test: rows 1..4, K % 16");+ TORCH_CHECK(C.size(0) == R && C.size(1) % 16 == 0 && C.size(1) >= 16, "tile test: C shape");+ const int nt = (int) (C.size(1) / 16);+ TORCH_CHECK(B.numel() == (int64_t) ks * nt * 16 * bits, "tile test: B size vs A / C / bits");+ TORCH_CHECK(native == 1 || (native == 0 && nt % 2 == 0), "tile test: layout");+ bool ok = false;+ if (bits == 2) ok = mf_tt_dispatch<2>(ks, cf, A, B, C, R, nt, (int) native, stream);+ else if (bits == 3) ok = mf_tt_dispatch<3>(ks, cf, A, B, C, R, nt, (int) native, stream);+ else if (bits == 4) ok = mf_tt_dispatch<4>(ks, cf, A, B, C, R, nt, (int) native, stream);+ else if (bits == 5) ok = mf_tt_dispatch<5>(ks, cf, A, B, C, R, nt, (int) native, stream);+ TORCH_CHECK(ok, "tile test: (bits, K, output dtype) not instantiated");+}+#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuhnew file mode 100644index 0000000..aca8bc0--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh@@ -0,0 +1,900 @@+#pragma once+// Fused MoE half-layer decode (gfx11.5, opt-in EXL3_MOE_FUSED=1): ONE persistent launch per half-layer for R = 1..4 rows.+// hyper-connection dots -> finalize/mix -> router -> top-k + expert grouping -> gate/up (VALU trellis matvec) -> silu*up -> down+// -> Hadamard post + weighted sum + shared expert + gated residual apply (in place on the residual stack).+// Weights are repacked at load in read order (see exl3_moe_fused_idx.h). The matvec body is the core3 VALU one (same reduction order for+// every row count: chunk-ordered 16-chunk sums from 0.0f), so the result is byte-identical to the flag-off engine at R > 1 and to the same+// row of any larger batch at R = 1.+// Shapes: everything is a template parameter S (mf::QwenShape is the one instantiated); K (bits) of routed and shared experts are S::RB / S::SB.+#include "exl3_moe_fused_idx.h"+#include "exl3_moe_valu.cuh" // mv_dot2++#if defined(USE_ROCM) || defined(__HIPCC__)+namespace mf {++struct Params+{+ int R, G;+ float* xin; float* xout; // xout may alias xin (in-place apply)+ const int8_t* fn; const float* fn_scale; const int8_t* upt; const float* up_scale; const half* w;+ const half* router; const half* sgate_w;+ const uint32_t* const* wt; // [3 * (NEXP + 1)] matrix base pointers: unit u (expert id, shared = NEXP), proj 0 gate 1 up 2 down+ const half* const* svt; // [6 * (NEXP + 1)]: gsuh gsvh usuh usvh dsuh dsvh of unit u+ int native; // 1 = engine trellis layout, 0 = core4 repack layout (idx.h)+ float* dots; float* post; half* mixed; half* scores; float* sgl;+ half* gu; float* dn; float* ydbg; int* seldbg;+ unsigned* bar; unsigned* done; int* err; // all three zero between launches (the last block resets bar and done)+ float rms_eps;+ int gs; // 1 = group-scaled int8 mixer weights (fn_scale / up_scale hold group scales, see idx.h)+};++template <class S>+struct Smem+{+ union+ {+ struct { float red[RED_SIZE]; half A[MAXR * S::D]; half A2[MAXR * S::D]; } g;+ struct { float rows[(S::TOPK + 1) * 128]; } c;+ struct { float t[2][MAXR * S::LR]; float rmr[2][MAXR * 4]; float dred[4][MAXR][4][4]; } h;+ } u;+ int sel[MAXR * S::TOPK];+ half wt[MAXR * S::TOPK];+ int sorted_e[MAXR * S::TOPK], sorted_a[MAXR * S::TOPK], tok[MAXR * S::TOPK], gstart[MAXR * S::TOPK + 2], head[MAXR * S::TOPK];+ int urows[MAXR * S::TOPK + 1];+ int ngroups;+};++#define MF_DIMS using DM = Dm<S>; constexpr int D = DM::D, H = DM::H, LR = DM::LR, MR = DM::MR, NEXP = DM::NEXP, TOPK = DM::TOPK, INTER = DM::INTER; \+ (void) D; (void) H; (void) LR; (void) MR; (void) NEXP; (void) TOPK; (void) INTER;++constexpr float HAD_SCALE = 0.088388347648f;++__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); }++__device__ __forceinline__ void unpack_s8x4(uint32_t v, float& f0, float& f1, float& f2, float& f3)+{+ f0 = (float) ((int) (v << 24) >> 24);+ f1 = (float) ((int) (v << 16) >> 24);+ f2 = (float) ((int) (v << 8) >> 24);+ f3 = (float) ((int) v >> 24);+}++// group scales: weight = half(code * scale) as fp32 (bit-exact twin of the fp16 weights half(code * scale) used by the fp16 kernels)+// The product must be rounded to fp32 BEFORE the half rounding (the fp16 twin sees half(fp32(q * sc))); without the barrier the compiler+// fuses mul + convert into one v_fma_mix and rounds once (differs on exact half ties).+#ifndef GS_NOFUSE+#define GS_NOFUSE(p) asm volatile("" : "+v"(p))+#endif+__device__ __forceinline__ float gs_dq(float q, float sc) { float p = q * sc; GS_NOFUSE(p); return __half2float(__float2half_rn(p)); }+__device__ __forceinline__ void gs_unpack_s8x4(uint32_t v, float sc, float& f0, float& f1, float& f2, float& f3)+{+ unpack_s8x4(v, f0, f1, f2, f3);+ f0 = gs_dq(f0, sc); f1 = gs_dq(f1, sc); f2 = gs_dq(f2, sc); f3 = gs_dq(f3, sc);+}++// ---- optional phase time stamps (-DMF_TIMING): thread 0 of each block writes wall_clock64 (100 MHz) low 32 bits, slot k, to seldbg+#ifdef MF_TIMING+__device__ __forceinline__ void mf_stamp(const Params& p, int k)+{+ if (threadIdx.x == 0 && blockIdx.x < STAMP_MAXB && k < STAMP_SLOTS) p.seldbg[stamp_idx(blockIdx.x, k)] = (int) (unsigned) wall_clock64();+}+#else+__device__ __forceinline__ void mf_stamp(const Params&, int) {}+#endif++// ---- grid barrier (counter starts at 0 each launch)+// ctl words (u32, 256 bytes): 0 bar, 1 done, 2 err = first timed-out phase (0 = none), 3 timeout count, 4 phase / 5 block / 6 bar value seen / 7 wait ticks /+// 8 first block that had not arrived, 11 grid size, of the FIRST timeout; 9 longest wait over WAIT_LOG ticks, 10 count of such waits; [CTL_ARR, CTL_ARR + CTL_MAXB) arrival markers.+constexpr int CTL_ARR = 16, CTL_MAXB = 48;+constexpr unsigned WAIT_LOG = 5000; // 50 us at the 100 MHz wall clock+// thread 0 of the block, after ++phase: announce, wait until all p.G blocks arrived. Bounded spin; on timeout the record above is written (first one wins)+__device__ __forceinline__ void gbar_wait(const Params& p, int phase)+{+ unsigned* ctl = p.bar;+ const unsigned target = (unsigned) phase * p.G;+ __hip_atomic_store(ctl + CTL_ARR + blockIdx.x, (unsigned) phase, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ __hip_atomic_fetch_add(p.bar, 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ const long long t0 = wall_clock64();+ long long spins = 0;+ while (__hip_atomic_load(p.bar, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < target)+ {+ __builtin_amdgcn_s_sleep(1);+ if (++spins > 8000000LL)+ {+ __hip_atomic_fetch_add(ctl + 3, 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ unsigned zero = 0u;+ if (__hip_atomic_compare_exchange_strong(ctl + 2, &zero, (unsigned) phase, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT))+ {+ unsigned miss = 0xffffffffu;+ for (int b = 0; b < p.G; ++b)+ if (__hip_atomic_load(ctl + CTL_ARR + b, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < (unsigned) phase) { miss = (unsigned) b; break; }+ ctl[4] = (unsigned) phase; ctl[5] = blockIdx.x; ctl[6] = __hip_atomic_load(p.bar, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ ctl[7] = (unsigned) (wall_clock64() - t0); ctl[8] = miss; ctl[11] = (unsigned) p.G;+ }+ return;+ }+ }+ const unsigned el = (unsigned) (wall_clock64() - t0);+ if (el > WAIT_LOG)+ {+ __hip_atomic_fetch_max(ctl + 9, el, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ __hip_atomic_fetch_add(ctl + 10, 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ }+}++__device__ __forceinline__ void gbar(const Params& p, int& phase)+{+ __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");+ __syncthreads();+ mf_stamp(p, 2 * phase + 1);+ ++phase;+ if (threadIdx.x == 0) gbar_wait(p, phase);+ __syncthreads();+ __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");+ mf_stamp(p, 2 * phase);+}++// the last block to arrive here resets bar, done and the arrival markers: every block is past its last barrier, nobody spins+__device__ __forceinline__ void gfinish(const Params& p)+{+ __syncthreads();+ if (threadIdx.x == 0)+ {+ const unsigned d = __hip_atomic_fetch_add(p.done, 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ if (d == (unsigned) p.G - 1)+ {+ for (int b = 0; b < p.G; ++b) __hip_atomic_store(p.bar + CTL_ARR + b, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ __hip_atomic_store(p.bar, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ __hip_atomic_store(p.done, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ }+ }+}++// ---------------------------------------------------------------- Hadamard helpers (register form, same math as hadamard_inner.cuh)+template <bool PRE, bool POST>+__device__ __forceinline__ half4 had_regs_h(half4 v, const half* scale, const int t)+{+ if constexpr (PRE) { half4 sc = ((const half4*) scale)[t]; v.x = __hmul2(v.x, sc.x); v.y = __hmul2(v.y, sc.y); }+ float v0 = __half2float(__low2half(v.x)), v1 = __half2float(__high2half(v.x));+ float v2 = __half2float(__low2half(v.y)), v3 = __half2float(__high2half(v.y));+ float s0 = v0 + v1, d0 = v0 - v1, s1 = v2 + v3, d1 = v2 - v3;+ float h0 = s0 + s1, h1 = d0 + d1, h2 = s0 - s1, h3 = d0 - d1;+ shuffle_had_f4x32(h0, h1, h2, h3, t);+ v.x = __floats2half2_rn(h0 * HAD_SCALE, h1 * HAD_SCALE);+ v.y = __floats2half2_rn(h2 * HAD_SCALE, h3 * HAD_SCALE);+ if constexpr (POST) { half4 sc = ((const half4*) scale)[t]; v.x = __hmul2(v.x, sc.x); v.y = __hmul2(v.y, sc.y); }+ return v;+}++__device__ __forceinline__ float4 had_regs_f_post(float4 v, const half* scale, const int t)+{+ float v0 = v.x, v1 = v.y, v2 = v.z, v3 = v.w;+ float s0 = v0 + v1, d0 = v0 - v1, s1 = v2 + v3, d1 = v2 - v3;+ v.x = s0 + s1; v.y = d0 + d1; v.z = s0 - s1; v.w = d0 - d1;+ shuffle_had_f2x32(v.x, v.y, t);+ shuffle_had_f2x32(v.z, v.w, t);+ v.x *= HAD_SCALE; v.y *= HAD_SCALE; v.z *= HAD_SCALE; v.w *= HAD_SCALE;+ half4 sc = ((const half4*) scale)[t];+ v.x *= __low2float(sc.x); v.y *= __high2float(sc.x); v.z *= __low2float(sc.y); v.w *= __high2float(sc.y);+ return v;+}++__device__ __forceinline__ float wave_sum_down(float v)+{+ #pragma unroll+ for (int o = 16; o > 0; o >>= 1) v += __shfl_down(v, o, 32);+ return __shfl(v, 0, 32);+}++// K5 decode of one engine lane (t) from the lane set {wrap, own0..own4}: same arithmetic as the engine's dq4<5, cb> twice (values 0..3, 4..7)+__device__ __forceinline__ void mf_dq8_k5(const uint32_t (&w)[6], const int t, FragB& f0, FragB& f1)+{+ uint32_t v[8];+ #pragma unroll+ for (int g = 0; g < 2; ++g)+ {+ const uint32_t a = w[k5_i0(t, g)], b = w[k5_i2(t, g)];+ const int s2 = k5_s2(t, g);+ v[4 * g + 3] = fshift(b, a, s2) & 0xffff;+ v[4 * g + 2] = fshift(b, a, s2 + 5) & 0xffff;+ v[4 * g + 1] = fshift(b, a, s2 + 10) & 0xffff;+ v[4 * g + 0] = fshift(b, a, s2 + 15) & 0xffff;+ }+ exl3_gemv_ns::decode8<2>(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], f0, f1);+}++// ---------------------------------------------------------------- VALU tile on a trellis tile (native or repacked layout)+// One wave = one 16-column tile, all k. Same decode body as core3's mv_tile; Bt = base of the tile's first k-slice, ss = u32 between k-slices.+// Lane (cq, g8): g8 = column pair (g8, g8 + 8), cq = chunk lane. Words: wrap word + `BITS` own words; K3 own words are three scalar loads (3 g8 is not+// 8-byte aligned). K3 decode: lane (g8, t) is the engine's lane 4 g8 + t, whose (a, b, s2) of dq8_regs_3bits are (w[0], w[1], 8), (w[1], w[2], 16),+// (w[2], w[3], 24), (w[2], w[3], 0) in the order wrap, own0, own1, own2 (mf_k3_map in the CPU proof re-derives this from the engine's formulas).+template <int BITS, bool CF32, int RW, int KS>+__device__ __forceinline__ void mf_tile(const uint32_t* __restrict__ A32, const uint32_t* __restrict__ Bt, long ss, void* __restrict__ C,+ int size_n, int tile, float* red, int wave, int lane)+{+ static_assert(BITS >= 2 && BITS <= 5, "K1, K6.. need their own per-lane word set and decode body: not implemented");+ constexpr int NWD = BITS + 1, CH = (KS + 15) / 16, NRND = 4, K = KS * 16;+ constexpr int VU = CH > 5 ? 5 : CH;+ const int g8 = lane & 7, cq = lane >> 3;+ float rs0[RW], rs1[RW];+ #pragma unroll+ for (int r = 0; r < RW; ++r) { rs0[r] = 0.f; rs1[r] = 0.f; }+ uint32_t wa[VU][NWD], wb[VU][NWD];+ auto ld = [&](uint32_t (&w)[NWD], int s)+ {+ w[0] = Bt[wrp_i(BITS, g8, s, ss)];+ const uint32_t* q = Bt + own_i(BITS, g8, s, ss);+ if constexpr (BITS == 2) { const uint2 v = *(const uint2*) q; w[1] = v.x; w[2] = v.y; }+ else if constexpr (BITS == 3) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; }+ else if constexpr (BITS == 5) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; w[4] = q[3]; w[5] = q[4]; }+ else { const uint4 v = *(const uint4*) q; w[1] = v.x; w[2] = v.y; w[3] = v.z; w[4] = v.w; }+ };+ auto ldst = [&](uint32_t (&w)[VU][NWD], int rnd, int sg0)+ {+ const int cc = 4 * rnd + cq, s0n = cc * CH, m = myn(KS, cc);+ #pragma unroll+ for (int u = 0; u < VU; ++u) if (sg0 + u < m) ld(w[u], s0n + sg0 + u);+ };+ ldst(wa, 0, 0);+ #pragma unroll 1+ for (int round = 0; round < NRND; ++round)+ {+ const int c = 4 * round + cq;+ const int s0 = c * CH;+ const int myn_ = myn(KS, c);+ float acc0[RW], acc1[RW];+ #pragma unroll+ for (int r = 0; r < RW; ++r) { acc0[r] = 0.f; acc1[r] = 0.f; }+ #pragma unroll 1+ for (int sb = 0; sb < CH; sb += VU)+ {+ int nr = round, ns = sb + VU;+ if (ns >= CH) { nr = round + 1; ns = 0; }+ if (nr < NRND) ldst(wb, nr, ns);+ #pragma unroll+ for (int u = 0; u < VU; ++u)+ {+ if (sb + u < myn_)+ {+ FragB f0[4], f1[4];+ #pragma unroll+ for (int t = 0; t < 4; ++t)+ {+ if constexpr (BITS == 2) exl3_gemv_ns::dq8_regs_2bits<2>(wa[u][t >> 1], wa[u][1 + (t >> 1)], t << 3, f0[t], f1[t]);+ else if constexpr (BITS == 3) exl3_gemv_ns::dq8_regs_3bits<2>(wa[u][t == 0 ? 0 : (t == 1 ? 1 : 2)], wa[u][t == 0 ? 1 : (t == 1 ? 2 : 3)], t == 0 ? 8 : (t == 1 ? 16 : (t == 2 ? 24 : 0)), f0[t], f1[t]);+ else if constexpr (BITS == 5) mf_dq8_k5(wa[u], t, f0[t], f1[t]);+ else exl3_gemv_ns::dq8_regs_4bits<2>(wa[u][t], wa[u][t + 1], f0[t], f1[t]);+ }+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ const long ai = a_idx(r, K, s0 + sb + u);+ const uint4 alo = *(const uint4*) (A32 + ai);+ const uint4 ahi = *(const uint4*) (A32 + ai + 4);+ const uint32_t aq[8] = {alo.x, alo.y, alo.z, alo.w, ahi.x, ahi.y, ahi.z, ahi.w};+ #pragma unroll+ for (int q = 0; q < 8; ++q)+ {+ const int t = q & 3, h = q >> 2;+ acc0[r] = mv_dot2(__builtin_bit_cast(uint32_t, f0[t][h]), aq[q], acc0[r]);+ acc1[r] = mv_dot2(__builtin_bit_cast(uint32_t, f1[t][h]), aq[q], acc1[r]);+ }+ }+ }+ }+ #pragma unroll+ for (int u = 0; u < VU; ++u)+ #pragma unroll+ for (int w = 0; w < NWD; ++w) wa[u][w] = wb[u][w];+ }+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ red[red_idx(wave, cq, g8, r)] = acc0[r];+ red[red_idx(wave, cq, g8 + 8, r)] = acc1[r];+ }+ __syncwarp();+ if (cq == 0)+ {+ #pragma unroll+ for (int cc = 0; cc < 4; ++cc)+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ rs0[r] += red[red_idx(wave, cc, g8, r)];+ rs1[r] += red[red_idx(wave, cc, g8 + 8, r)];+ }+ }+ __syncwarp();+ }+ if (cq == 0)+ {+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ if constexpr (CF32) { ((float*) C)[c_idx(r, size_n, tile, g8)] = rs0[r]; ((float*) C)[c_idx(r, size_n, tile, g8 + 8)] = rs1[r]; }+ else { ((half*) C)[c_idx(r, size_n, tile, g8)] = __float2half_rn(rs0[r]); ((half*) C)[c_idx(r, size_n, tile, g8 + 8)] = __float2half_rn(rs1[r]); }+ }+ }+}++template <int BITS, bool CF32, int KS>+__device__ __forceinline__ void mf_tile_rows(int rows, const uint32_t* A32, const uint32_t* Bt, long ss, void* C, int size_n, int tile, float* red, int wave, int lane)+{+ if (rows == 1) mf_tile<BITS, CF32, 1, KS>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+ else if (rows == 2) mf_tile<BITS, CF32, 2, KS>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+ else if (rows == 3) mf_tile<BITS, CF32, 3, KS>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+ else mf_tile<BITS, CF32, 4, KS>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+}++// ---------------------------------------------------------------- phase 0: HC dots (128-thread teams)+template <class S>+__device__ void ph_dots(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, team = threadIdx.x >> 7, tid = threadIdx.x & 127, lane = tid & 31, warp = tid >> 5;+ const int D4 = D / 4;+ const int rounds = (MR + 1 + p.G * 4 - 1) / (p.G * 4);+ for (int k = 0; k < rounds; ++k)+ {+ const int j = blockIdx.x * 4 + team + k * p.G * 4;+ const bool valid = j < MR + 1;+ if (valid)+ {+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ float a[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) a[r] = 0.0f;+ if (j < MR)+ {+ const int2* f8 = (const int2*) (p.fn + fn_row<S>(j, h));+ for (int c = tid; c < D4 / 2; c += 128)+ {+ int2 pk = f8[c];+ float w0, w1, w2, w3, w4, w5, w6, w7;+ if (p.gs)+ {+ const float gsc = p.fn_scale[fngs_idx<S>(j, h, c)];+ gs_unpack_s8x4((uint32_t) pk.x, gsc, w0, w1, w2, w3);+ gs_unpack_s8x4((uint32_t) pk.y, gsc, w4, w5, w6, w7);+ }+ else+ {+ unpack_s8x4((uint32_t) pk.x, w0, w1, w2, w3);+ unpack_s8x4((uint32_t) pk.y, w4, w5, w6, w7);+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ if (r < R)+ {+ const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));+ float4 s0 = s4[(size_t) h * D4 + 2 * c];+ float4 s1 = s4[(size_t) h * D4 + 2 * c + 1];+ float x = a[r];+ x = fmaf(s0.x, w0, x); x = fmaf(s0.y, w1, x); x = fmaf(s0.z, w2, x); x = fmaf(s0.w, w3, x);+ x = fmaf(s1.x, w4, x); x = fmaf(s1.y, w5, x); x = fmaf(s1.z, w6, x); x = fmaf(s1.w, w7, x);+ a[r] = x;+ }+ }+ }+ }+ else+ {+ for (int c = tid; c < D4; c += 128)+ {+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));+ float4 sv = s4[(size_t) h * D4 + c];+ a[r] = fmaf(sv.x, sv.x, fmaf(sv.y, sv.y, fmaf(sv.z, sv.z, fmaf(sv.w, sv.w, a[r]))));+ }+ }+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ float v = a[r];+ for (int o = 16; o > 0; o >>= 1) v += __shfl_down(v, o, 32);+ if (lane == 0 && r < R) s.u.h.dred[team][r][h][warp] = v;+ }+ }+ }+ __syncthreads();+ if (valid && tid < H * R)+ {+ const int r = tid / H, h = tid % H;+ float v = 0.0f;+ #pragma unroll+ for (int w = 0; w < 4; ++w) v += s.u.h.dred[team][r][h][w];+ if (j < MR && !p.gs) v *= p.fn_scale[j];+ p.dots[dots_idx<S>(r, j, h)] = v;+ }+ __syncthreads();+ }+}++// ---------------------------------------------------------------- phase 1: HC finalize (256-thread teams, one 32-column chunk per item, all R rows)+// The int8 up-projection words of a chunk are loaded once and used for every row (core4 re-read them R times); per row and output the+// accumulation order is unchanged (ii ascending per lane, then the xor tree).+template <class S>+__device__ void ph_finalize(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, team = threadIdx.x >> 8, tid = threadIdx.x & 255, lane = tid & 31, warp = tid >> 5;+ const int D4 = D / 4;+ constexpr int CH = 32; // chunk_cols+ const int total = DM::FIN_CHUNKS;+ const int rounds = (total + p.G * 2 - 1) / (p.G * 2);+ float* t_s = s.u.h.t[team]; // [MAXR][LR]+ float* rmr_s = s.u.h.rmr[team]; // [MAXR][4]+ const float inv_h = 1.0f / (float) H;+ for (int k = 0; k < rounds; ++k)+ {+ const int cidx = blockIdx.x * 2 + team + k * p.G * 2;+ const bool valid = cidx < total;+ if (valid && tid < H * R)+ {+ const int r = tid / H, h = tid % H;+ rmr_s[r * 4 + h] = rsqrtf(p.dots[dots_idx<S>(r, MR, h)] / (float) D + p.rms_eps);+ }+ __syncthreads();+ if (valid)+ {+ for (int idx = tid; idx < LR * R; idx += 256)+ {+ const int r = idx / LR, ii = idx % LR;+ const float* dr = p.dots + dots_idx<S>(r, 0, 0);+ float v = 0.0f;+ #pragma unroll+ for (int h = 0; h < H; ++h) v = fmaf(rmr_s[r * 4 + h], dr[(size_t) ii * H + h], v);+ v *= inv_h;+ t_s[r * LR + ii] = v * sigmoidf_(v);+ }+ if (cidx == 0 && tid < H)+ {+ for (int r = 0; r < R; ++r)+ {+ const float* dr = p.dots + dots_idx<S>(r, 0, 0);+ float v = 0.0f;+ #pragma unroll+ for (int h = 0; h < H; ++h) v = fmaf(rmr_s[r * 4 + h], dr[(size_t) (LR + tid) * H + h], v);+ p.post[(size_t) r * H + tid] = 2.0f * sigmoidf_(v * inv_h);+ }+ }+ }+ __syncthreads();+ if (valid)+ {+ const int c0 = cidx * CH, c1 = min(c0 + CH, D);+ for (int c = c0 / 4 + warp; c < c1 / 4; c += 8)+ {+ float4 g[MAXR][H];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ #pragma unroll+ for (int h = 0; h < H; ++h) g[r][h] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ float4 gsc[H];+ for (int ii = lane; ii < LR; ii += 32)+ {+ float ti[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) ti[r] = r < R ? t_s[r * LR + ii] : 0.0f;+ if (p.gs && (((ii - lane) & 32) == 0)) // the 32-rank step that opens a 64-rank group: warp-uniform (lane < 32)+ {+ #pragma unroll+ for (int h = 0; h < H; ++h) gsc[h] = *(const float4*) (p.up_scale + upgs_idx<S>(h, c, ii));+ }+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ uint32_t u = *(const uint32_t*) (p.upt + upt_u32<S>(h, c, ii) * 4);+ float u0, u1, u2, u3;+ unpack_s8x4(u, u0, u1, u2, u3);+ if (p.gs) { u0 = gs_dq(u0, gsc[h].x); u1 = gs_dq(u1, gsc[h].y); u2 = gs_dq(u2, gsc[h].z); u3 = gs_dq(u3, gsc[h].w); }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ g[r][h].x = fmaf(ti[r], u0, g[r][h].x); g[r][h].y = fmaf(ti[r], u1, g[r][h].y);+ g[r][h].z = fmaf(ti[r], u2, g[r][h].z); g[r][h].w = fmaf(ti[r], u3, g[r][h].w);+ }+ }+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ #pragma unroll+ for (int h = 0; h < H; ++h)+ for (int o = 16; o > 0; o >>= 1)+ {+ g[r][h].x += __shfl_xor(g[r][h].x, o, 32); g[r][h].y += __shfl_xor(g[r][h].y, o, 32);+ g[r][h].z += __shfl_xor(g[r][h].z, o, 32); g[r][h].w += __shfl_xor(g[r][h].w, o, 32);+ }+ if (lane != 0) continue;+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));+ float4 o = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ const float4 sc = p.gs ? make_float4(1.0f, 1.0f, 1.0f, 1.0f) : *(const float4*) (p.up_scale + upsc_idx<S>(h, c));+ float4 sv = s4[(size_t) h * D4 + c];+ half4 wq = *(const half4*) (p.w + upsc_idx<S>(h, c));+ float coef = rmr_s[r * 4 + h] * inv_h;+ o.x = fmaf(sigmoidf_(g[r][h].x * sc.x) * coef * __low2float(wq.x), sv.x, o.x);+ o.y = fmaf(sigmoidf_(g[r][h].y * sc.y) * coef * __high2float(wq.x), sv.y, o.y);+ o.z = fmaf(sigmoidf_(g[r][h].z * sc.z) * coef * __low2float(wq.y), sv.z, o.z);+ o.w = fmaf(sigmoidf_(g[r][h].w * sc.w) * coef * __high2float(wq.y), sv.w, o.w);+ }+ half2* out2 = (half2*) (p.mixed + mixed_row<S>(r));+ out2[c * 2] = __floats2half2_rn(o.x, o.y);+ out2[c * 2 + 1] = __floats2half2_rn(o.z, o.w);+ }+ }+ }+ __syncthreads();+ }+}++// ---------------------------------------------------------------- phase 2: router logits + shared-gate logit+// The R mixed rows are staged once per block in LDS (the A region, unused until phase 3); every expert row then streams from global once.+template <class S>+__device__ void ph_router(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ half* mx = s.u.g.A; // [R][D] halves (A holds MAXR * D)+ for (int i = threadIdx.x; i < R * D / 8; i += THREADS) ((uint4*) mx)[i] = ((const uint4*) p.mixed)[i];+ __syncthreads();+ for (int e = wave * p.G + blockIdx.x; e < NEXP; e += 16 * p.G)+ {+ const half2* g2 = (const half2*) (p.router + router_row<S>(e));+ float sum[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) sum[r] = 0.0f;+ #pragma unroll 8+ for (int col = lane; col < D / 2; col += 32)+ {+ const half2 g = g2[col];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ const half2 hh = ((const half2*) (mx + (size_t) r * D))[col];+ sum[r] = fmaf(__half2float(__low2half(hh)), __half2float(__low2half(g)), sum[r]);+ sum[r] = fmaf(__half2float(__high2half(hh)), __half2float(__high2half(g)), sum[r]);+ }+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ float v = wave_sum_down(sum[r]);+ if (lane == 0 && r < R) p.scores[scores_idx<S>(r, e)] = __float2half_rn(v);+ }+ }+ if (blockIdx.x == p.G - 1 && wave == 15)+ {+ for (int r = 0; r < R; ++r)+ {+ // replay of the engine's add_sigmoid_gate_proj reduction: 1024 virtual threads t = lane + 32 j, strided fma chain,+ // shared-memory tree strides 512..32 (register folds over j), then strides 16..1 (shuffles)+ float pt[32];+ #pragma unroll+ for (int j = 0; j < 32; ++j)+ {+ float a = 0.0f;+ for (int i = lane + 32 * j; i < D; i += 1024)+ a = fmaf(__half2float(p.sgate_w[i]), __half2float(mx[(size_t) r * D + i]), a);+ pt[j] = a;+ }+ #pragma unroll+ for (int w = 16; w >= 1; w >>= 1)+ {+ #pragma unroll+ for (int j = 0; j < w; ++j) pt[j] += pt[j + w];+ }+ const float v = wave_sum_down(pt[0]);+ if (lane == 0) p.sgl[r] = v;+ }+ }+}++// ---------------------------------------------------------------- top-k (one wave per row), redundant per block+template <class S>+__device__ void ph_topk(const Params& p, Smem<S>& s)+{+ MF_DIMS+ constexpr int KEYS = DM::KEYS;+ const int R = p.R, wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ if (wave < R)+ {+ float key[KEYS];+ #pragma unroll+ for (int i = 0; i < KEYS; ++i)+ {+ // NaN and -inf scores become the lowest finite key: they stay selectable (lowest index first), so a row always picks TOPK distinct+ // experts and a group never holds more than R rows (the A staging buffers hold MAXR rows)+ const float kv = __half2float(p.scores[scores_idx<S>(wave, i * 32 + lane)]);+ key[i] = (kv > -__FLT_MAX__) ? kv : -__FLT_MAX__;+ }+ float gmax = 0.0f, ek = 0.0f;+ int myidx = 0;+ #pragma unroll+ for (int rank = 0; rank < TOPK; ++rank)+ {+ float bk = -INFINITY; int bi = 0x7fffffff;+ #pragma unroll+ for (int i = 0; i < KEYS; ++i)+ if (key[i] > bk) { bk = key[i]; bi = i * 32 + lane; }+ #pragma unroll+ for (int o = 16; o > 0; o >>= 1)+ {+ float ok = __shfl_xor(bk, o, 32); int oi = __shfl_xor(bi, o, 32);+ if (ok > bk || (ok == bk && oi < bi)) { bk = ok; bi = oi; }+ }+ if (rank == 0) gmax = bk;+ if (lane == rank) { ek = (bk == gmax) ? 1.0f : expf(bk - gmax); myidx = clamp_expert(bi, NEXP); }+ #pragma unroll+ for (int i = 0; i < KEYS; ++i)+ if (i * 32 + lane == bi) key[i] = -INFINITY;+ }+ const float e = lane < TOPK ? ek : 0.0f;+ const float sum = wave_sum_down(e) + 1.0e-20f;+ if (lane < TOPK)+ {+ s.sel[wave * TOPK + lane] = myidx;+ s.wt[wave * TOPK + lane] = __float2half_rn(e / sum);+ }+ }+ __syncthreads();+ const int NA = R * TOPK;+ if (threadIdx.x < NA)+ {+ const int a = threadIdx.x, e = s.sel[a];+ int pp = 0;+ for (int b = 0; b < NA; ++b) { const int eb = s.sel[b]; pp += (eb < e) || (eb == e && b < a); }+ s.sorted_e[pp] = e; s.sorted_a[pp] = a; s.tok[pp] = a / TOPK;+ }+ __syncthreads();+ if (threadIdx.x < NA) s.head[threadIdx.x] = (threadIdx.x == 0 || s.sorted_e[threadIdx.x - 1] != s.sorted_e[threadIdx.x]) ? 1 : 0;+ __syncthreads();+ if (threadIdx.x == 0)+ {+ int g = 0;+ for (int q = 0; q < NA; ++q) if (s.head[q]) s.gstart[g++] = q;+ s.gstart[g] = NA; s.ngroups = g;+ for (int u = 0; u < g; ++u) s.urows[u] = min(s.gstart[u + 1] - s.gstart[u], MAXR);+ s.urows[g] = R; // the shared expert: R rows+ }+ __syncthreads();+}++// ---------------------------------------------------------------- phases 3/4: one wave per 16-column tile.+// Segments (one (unit, proj) pair for gate/up, one unit for down) are processed two at a time with two A buffers, so the wave-strided+// tile list spans both and the block never idles between segments. The tile list is split between blocks by cost (idx.h split_tile).+struct Seg { int unit, proj, rows, p0, e; bool shared; const half* const* sv; };+template <class S>+__device__ __forceinline__ Seg seginfo(const Params& p, const Smem<S>& s, int seg, bool two_proj)+{+ using DM = Dm<S>;+ Seg g; g.unit = two_proj ? seg >> 1 : seg; g.proj = two_proj ? (seg & 1) : 0; g.shared = g.unit == s.ngroups; g.e = 0;+ if (g.shared) { g.rows = p.R; g.p0 = p.R * DM::TOPK; g.sv = p.svt + 6 * DM::NEXP; }+ else { g.p0 = s.gstart[g.unit]; g.rows = min(s.gstart[g.unit + 1] - g.p0, MAXR); g.e = s.sorted_e[g.p0]; g.sv = p.svt + 6 * g.e; } // min: never active (distinct experts per row)+ return g;+}++template <class S>+__device__ void ph_gateup(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK, NAR = NA + R;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int NU = s.ngroups + 1;+ constexpr int TPP = DM::TPP;+ const bool nat = p.native != 0;+ const long long W = split_total(s.urows, NU, 2, TPP);+ const int lo = split_tile(s.urows, NU, 2, TPP, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 2, TPP, (long long) (blockIdx.x + 1) * W / p.G);+ int i = lo;+ while (i < hi)+ {+ const int segA = i / TPP, endA = min(hi, (segA + 1) * TPP);+ const int iB = endA, segB = iB / TPP;+ const bool hasB = iB < hi;+ const int endB = hasB ? min(hi, (segB + 1) * TPP) : iB;+ const int nA = endA - i, nB = endB - iB;+ __syncthreads();+ for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)+ {+ const int seg = w2 ? segB : segA;+ const Seg g = seginfo<S>(p, s, seg, true);+ half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;+ const half* suh = g.sv[g.proj == 0 ? 0 : 2];+ for (int task = wave; task < g.rows * DM::CMB_BLOCKS; task += 16)+ {+ const int row = task / DM::CMB_BLOCKS, blk = task % DM::CMB_BLOCKS;+ const int token = g.shared ? row : s.tok[g.p0 + row];+ half4 v = ((const half4*) (p.mixed + mixed_row<S>(token) + blk * 128))[lane];+ v = had_regs_h<true, false>(v, suh + blk * 128, lane);+ ((half4*) (Abuf + a_row_gu<S>(row, blk)))[lane] = v;+ }+ }+ __syncthreads();+ for (int n = wave; n < nA + nB; n += 16)+ {+ const bool inB = n >= nA;+ const int seg = inB ? segB : segA;+ const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPP;+ const Seg g = seginfo<S>(p, s, seg, true);+ const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);+ half* C = p.gu + gu_out<S>(g.proj, NAR, g.p0);+ const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + g.proj];+ if (g.shared)+ mf_tile_rows<DM::SB, false, DM::KSG>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSG, TPP, tile), tile_ss(nat, DM::SB, TPP), C, INTER, tile, s.u.g.red, wave, lane);+ else+ mf_tile_rows<DM::RB, false, DM::KSG>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSG, TPP, tile), tile_ss(nat, DM::RB, TPP), C, INTER, tile, s.u.g.red, wave, lane);+ }+ i = endB;+ }+}++template <class S>+__device__ void ph_down(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK, NAR = NA + R;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int NU = s.ngroups + 1;+ constexpr int TPU = DM::TPU;+ const bool nat = p.native != 0;+ const long long W = split_total(s.urows, NU, 1, TPU);+ const int lo = split_tile(s.urows, NU, 1, TPU, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 1, TPU, (long long) (blockIdx.x + 1) * W / p.G);+ int i = lo;+ while (i < hi)+ {+ const int segA = i / TPU, endA = min(hi, (segA + 1) * TPU);+ const int iB = endA, segB = iB / TPU;+ const bool hasB = iB < hi;+ const int endB = hasB ? min(hi, (segB + 1) * TPU) : iB;+ const int nA = endA - i, nB = endB - iB;+ __syncthreads();+ for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)+ {+ const Seg g = seginfo<S>(p, s, w2 ? segB : segA, false);+ half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;+ const half* const* sv = g.sv;+ for (int task = wave; task < g.rows * DM::INT_BLOCKS; task += 16)+ {+ const int row = task / DM::INT_BLOCKS, blk = task % DM::INT_BLOCKS;+ half4 gg = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 0)))[lane];+ half4 uu = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 1)))[lane];+ gg = had_regs_h<false, true>(gg, sv[1] + blk * 128, lane);+ uu = had_regs_h<false, true>(uu, sv[3] + blk * 128, lane);+ half4 a;+ {+ float f0 = __half2float(__low2half(gg.x)), f1 = __half2float(__high2half(gg.x));+ float f2 = __half2float(__low2half(gg.y)), f3 = __half2float(__high2half(gg.y));+ half h0 = __float2half_rn(f0 / (1.0f + expf(-f0))), h1 = __float2half_rn(f1 / (1.0f + expf(-f1)));+ half h2 = __float2half_rn(f2 / (1.0f + expf(-f2))), h3 = __float2half_rn(f3 / (1.0f + expf(-f3)));+ a.x = __halves2half2(__hmul(h0, __low2half(uu.x)), __hmul(h1, __high2half(uu.x)));+ a.y = __halves2half2(__hmul(h2, __low2half(uu.y)), __hmul(h3, __high2half(uu.y)));+ }+ a = had_regs_h<true, false>(a, sv[4] + blk * 128, lane);+ ((half4*) (Abuf + a_row_dn<S>(row, blk)))[lane] = a;+ }+ }+ __syncthreads();+ for (int n = wave; n < nA + nB; n += 16)+ {+ const bool inB = n >= nA;+ const int seg = inB ? segB : segA;+ const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPU;+ const Seg g = seginfo<S>(p, s, seg, false);+ const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);+ float* C = p.dn + dn_row<S>(g.p0);+ const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + 2];+ if (g.shared)+ mf_tile_rows<DM::SB, true, DM::KSD>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSD, TPU, tile), tile_ss(nat, DM::SB, TPU), C, D, tile, s.u.g.red, wave, lane);+ else+ mf_tile_rows<DM::RB, true, DM::KSD>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSD, TPU, tile), tile_ss(nat, DM::RB, TPU), C, D, tile, s.u.g.red, wave, lane);+ }+ i = endB;+ }+}++// ---------------------------------------------------------------- phase 5: post had, weighted sum, shared add, hc apply+template <class S>+__device__ void ph_combine(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int items = DM::CMB_BLOCKS * R;+ for (int i = blockIdx.x; i < items; i += p.G)+ {+ const int cb = i / R, r = i % R;+ if (wave <= TOPK)+ {+ const int a = r * TOPK + (wave < TOPK ? wave : 0);+ int pp = 0, e = 0;+ const half* const* sv;+ if (wave < TOPK)+ {+ for (int q = 0; q < NA; ++q) if (s.sorted_a[q] == a) { pp = q; break; }+ e = s.sorted_e[pp]; sv = p.svt + 6 * e;+ }+ else { pp = NA + r; sv = p.svt + 6 * NEXP; }+ float4 v = ((const float4*) (p.dn + dn_row<S>(pp) + cb * 128))[lane];+ v = had_regs_f_post(v, sv[5] + cb * 128, lane);+ ((float4*) (s.u.c.rows + wave * 128))[lane] = v;+ }+ __syncthreads();+ if (threadIdx.x < 128)+ {+ const int col = cb * 128 + threadIdx.x, c = threadIdx.x;+ float sum = 0.0f;+ for (int q = 0; q < NA; ++q)+ {+ const int a = s.sorted_a[q];+ if (a / TOPK != r) continue;+ const int slot = a % TOPK;+ const float weighted = __fmul_rn(s.u.c.rows[slot * 128 + c], __half2float(s.wt[a]));+ sum = __fadd_rn(sum, weighted);+ }+ const float syw = 1.0f / (1.0f + __expf(-p.sgl[r]));+ if (!(syw < 1e-8f)) sum += s.u.c.rows[TOPK * 128 + c] * syw;+ p.ydbg[(size_t) r * D + col] = sum;+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ const float po = p.post[r * H + h];+ const float xv = p.xin[xout_idx<S>(r, h, col)];+ float o = po * sum;+ o += xv;+ p.xout[xout_idx<S>(r, h, col)] = o;+ }+ }+ __syncthreads();+ }+}++// Test entry (core5): all tiles of one K x N matrix (R rows of A already in the Hadamard domain, row-major R x K halves) through mf_tile, one block.+// Used to compare the tile body, native and repack addressing and K3 against the engine's exl3_gemv on synthetic data of real shapes.+template <int BITS, bool CF32, int KS>+__global__ __launch_bounds__(THREADS) void mf_tile_test_kernel(const uint32_t* A, const uint32_t* B, void* C, int R, int nt, int native)+{+ __shared__ float red[RED_SIZE];+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const bool nat = native != 0;+ for (int tile = wave; tile < nt; tile += 16)+ mf_tile_rows<BITS, CF32, KS>(R, A, B + tile_off(nat, BITS, KS, nt, tile), tile_ss(nat, BITS, nt), C, nt * 16, tile, red, wave, lane);+}++template <class S>+__global__ __launch_bounds__(THREADS) void moe_fused_kernel(Params p)+{+ __shared__ Smem<S> s;+ int phase = 0;+ mf_stamp(p, 0);+ ph_dots<S>(p, s); gbar(p, phase);+ ph_finalize<S>(p, s); gbar(p, phase);+ ph_router<S>(p, s); gbar(p, phase);+ ph_topk<S>(p, s);+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[threadIdx.x] = s.sel[threadIdx.x];+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[64 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);+ ph_gateup<S>(p, s); gbar(p, phase);+ ph_down<S>(p, s); gbar(p, phase);+ ph_combine<S>(p, s);+ mf_stamp(p, 11);+ gfinish(p);+}++} // namespace mf+#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused7.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7.cunew file mode 100644index 0000000..45f682b--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7.cu@@ -0,0 +1,96 @@+#if defined(USE_ROCM)+#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include "exl3_moe_fused_api.h"+#include "hadamard.cuh"+#include <c10/cuda/CUDAGuard.h>+#include <ATen/cuda/CUDAContext.h>+#include <torch/library.h>+#include "../util.h"+#include "../util.cuh"+#include "exl3_gemv_kernel.cuh"+#include "exl3_moe_valu.cuh"+#include "exl3_moe_fused7.cuh"+#include <algorithm>+#include <type_traits>++// core7: torch.ops.mf7.half, same arguments and workspace layout as exl3_moe_fused_half (Qwen shape only), plus `timing` (1 = phase stamps into seldbg).+namespace {+template <class S7, bool TM, int ABL> int grid7()+{+ static int G = [] {+ int nb = 0, dev = 0; hipGetDevice(&dev);+ hipDeviceProp_t prop; hipGetDeviceProperties(&prop, dev);+ cuda_check(hipOccupancyMaxActiveBlocksPerMultiprocessor(&nb, (const void*) mf7::moe_fused7_kernel<S7, TM, ABL>, mf::THREADS, 0));+ return std::max(1, nb) * prop.multiProcessorCount;+ }();+ return G;+}+template <class S> struct Match7+{+ static bool eq(int D, int H, int LR, int NEXP, int TOPK, int INTER, int RB, int SB)+ { return D == S::D && H == S::H && LR == S::LR && NEXP == S::NEXP && TOPK == S::TOPK && INTER == S::INTER && RB == S::RB && SB == S::SB; }+};+template <class S7, bool TM, int ABL> void launch7(const at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, const at::Tensor& upt, const at::Tensor& up_scale,+ const at::Tensor& w_h, const at::Tensor& router, const at::Tensor& sgate, const at::Tensor& wt, const at::Tensor& svt,+ at::Tensor& ws, double rms_eps, int native, int R, int vmask, hipStream_t stream)+{+ using DM = mf::Dm<S7>;+ const auto off = exl3_moe_fused_ws_offsets(S7::D, S7::H, S7::LR, S7::NEXP, S7::TOPK, S7::INTER, S7::RB, S7::SB);+ TORCH_CHECK(ws.numel() >= off.back(), "mf7: workspace too small");+ const bool gs = fn_scale.numel() != DM::MR;+ TORCH_CHECK(!gs || mf::gs_ok<S7>(), "mf7: group scales need D % 128 == 0");+ TORCH_CHECK(fn.numel() == (int64_t) DM::MR * S7::H * S7::D && fn_scale.numel() == mf::fn_scale_n<S7>(gs), "mf7: fn size");+ TORCH_CHECK(upt.numel() == (int64_t) S7::H * DM::D4 * S7::LR * 4, "mf7: upt size");+ TORCH_CHECK(up_scale.numel() == mf::up_scale_n<S7>(gs) && w_h.numel() == (int64_t) S7::H * S7::D, "mf7: up_scale size");+ TORCH_CHECK(router.numel() == (int64_t) S7::NEXP * S7::D && sgate.numel() == S7::D, "mf7: router size");+ TORCH_CHECK(wt.dtype() == at::kLong && wt.numel() == 3 * (S7::NEXP + 1) && svt.dtype() == at::kLong && svt.numel() == 6 * (S7::NEXP + 1), "mf7: pointer tables");+ char* wb = (char*) ws.data_ptr();+ mf::Params p{};+ p.R = R; p.G = grid7<S7, TM, ABL>();+ TORCH_CHECK(((long long) S7::H * (DM::MR + 1) + 4LL * p.G - 1) / (4LL * p.G) + 1 <= mf7::DOTS_MAXIT, "mf7: dots items per team exceed DOTS_MAXIT");+ p.xin = (float*) x.data_ptr(); p.xout = (float*) x.data_ptr();+ p.fn = (const int8_t*) fn.data_ptr(); p.fn_scale = (const float*) fn_scale.data_ptr(); p.upt = (const int8_t*) upt.data_ptr();+ p.gs = gs ? 1 : 0; p.up_scale = (const float*) up_scale.data_ptr(); p.w = (const half*) w_h.data_ptr();+ p.router = (const half*) router.data_ptr(); p.sgate_w = (const half*) sgate.data_ptr();+ p.wt = (const uint32_t* const*) wt.data_ptr(); p.svt = (const half* const*) svt.data_ptr(); p.native = native;+ unsigned* ctl = (unsigned*) (wb + off[0]);+ p.bar = ctl; p.done = ctl + 1; p.err = (int*) (ctl + 2);+ p.dots = (float*) (wb + off[1]); p.post = (float*) (wb + off[2]); p.mixed = (half*) (wb + off[3]); p.scores = (half*) (wb + off[4]);+ p.sgl = (float*) (wb + off[5]); p.gu = (half*) (wb + off[6]); p.dn = (float*) (wb + off[7]); p.ydbg = (float*) (wb + off[8]); p.seldbg = (int*) (wb + off[9]);+ p.rms_eps = (float) rms_eps;+ mf7::moe_fused7_kernel<S7, TM, ABL><<<p.G, mf::THREADS, 0, stream>>>(p, vmask);+ cuda_check(hipPeekAtLastError());+}+} // namespace++void mf7_half(at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, const at::Tensor& upt, const at::Tensor& up_scale, const at::Tensor& w_h,+ const at::Tensor& router, const at::Tensor& sgate, const at::Tensor& wt, const at::Tensor& svt, at::Tensor& ws, double rms_eps, int64_t native, int64_t timing, int64_t variant,+ int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB)+{+ const at::cuda::OptionalCUDAGuard device_guard(x.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ TORCH_CHECK(x.dtype() == at::kFloat && x.is_contiguous() && x.dim() == 4 && x.size(2) == H && x.size(3) == D, "mf7: x");+ const int R = (int) (x.size(0) * x.size(1));+ TORCH_CHECK(R >= 1 && R <= mf::MAXR, "mf7: rows 1..4");+ TORCH_CHECK(fn.dtype() == at::kChar && upt.dtype() == at::kChar && fn_scale.dtype() == at::kFloat && up_scale.dtype() == at::kFloat, "mf7: dtypes");+ TORCH_CHECK(w_h.dtype() == at::kHalf && router.dtype() == at::kHalf && sgate.dtype() == at::kHalf && ws.dtype() == at::kByte, "mf7: dtypes 2");+ TORCH_CHECK(native == 0 || native == 1, "mf7: native flag");+#define L7(SH, TMV, ABLV) launch7<SH, TMV, ABLV>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, (int) (variant & 255), stream)+#define X7(SH) if (Match7<SH>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { \+ if (timing) { L7(SH, true, 0); return; } \+ if (std::is_same<SH, mf::QwenShape>::value) { \+ switch (variant >> 8) { case 1: L7(mf::QwenShape, false, 1); return; case 2: L7(mf::QwenShape, false, 2); return; case 3: L7(mf::QwenShape, false, 3); return; \+ case 8: L7(mf::QwenShape, false, 8); return; default: break; } } \+ L7(SH, false, 0); return; }+ X7(mf::QwenShape) X7(mf::SmallTestShape)+#undef X7+ TORCH_CHECK(false, "mf7: shape not instantiated");+}++TORCH_LIBRARY_FRAGMENT(mf7, m)+{+ m.def("half(Tensor(a!) x, Tensor fn, Tensor fn_scale, Tensor upt, Tensor up_scale, Tensor w_h, Tensor router, Tensor sgate, Tensor wt, Tensor svt, Tensor(b!) ws, float rms_eps, int native, int timing, int variant, int D, int H, int LR, int NEXP, int TOPK, int INTER, int RB, int SB) -> ()");+}+TORCH_LIBRARY_IMPL(mf7, CUDA, m) { m.impl("half", &mf7_half); }+#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused7.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7.cuhnew file mode 100644index 0000000..805bed2--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7.cuh@@ -0,0 +1,450 @@+#pragma once+// core7: fused MoE half-layer, front end rewritten for memory-level parallelism (same arithmetic order as core5, byte-identical results).+// Phases dots / finalize / router issue all their global loads of a work item before the first use; the dots phase splits (h, j) items+// evenly over the 80 teams (no 5-round tail) and keeps no per-round block barrier. gate/up, down, top-k, combine are core5's.+#include "exl3_moe_fused.cuh"+#include "exl3_moe_fused7_idx.h"++#if defined(USE_ROCM) || defined(__HIPCC__)+#include "exl3_moe_fused7_mv.cuh"+namespace mf7 {+using namespace mf;++template <bool TM> __device__ __forceinline__ void st7(const Params& p, int k)+{+ if constexpr (TM) { if (threadIdx.x == 0 && blockIdx.x < STAMP_MAXB && k < STAMP_STRIDE) p.seldbg[stamp_idx(blockIdx.x, k)] = (int) (unsigned) wall_clock64(); }+}++template <bool TM> __device__ __forceinline__ void gbar7(const Params& p, int& phase)+{+ __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");+ __syncthreads();+ st7<TM>(p, 2 * phase + 1);+ ++phase;+ if (threadIdx.x == 0) gbar_wait(p, phase);+ __syncthreads();+ __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");+ st7<TM>(p, 2 * phase);+}++// ---------------------------------------------------------------- phase 0: HC dots+template <class S>+__device__ void ph_dots7(const Params& p, Smem<S>& s)+{+ MF_DIMS+ constexpr int D4 = DM::D4, NIT = (D4 / 2 + 127) / 128, NIT2 = (D4 + 127) / 128, MR1 = MR + 1;+ const int R = p.R, team = threadIdx.x >> 7, tid = threadIdx.x & 127, lane = tid & 31, warp = tid >> 5;+ const int NT = p.G * 4, tg = blockIdx.x * 4 + team;+ const int total = H * MR1;+ const int lo = dots_lo(total, NT, tg), hi = dots_lo(total, NT, tg + 1);+ float* scr = s.u.g.red;+ int cur = lo;+ while (cur < hi)+ {+ const int h = cur / MR1, j = cur % MR1;+ const int m0 = cur - lo;+ int n = 1;+ if (j < MR)+ {+ n = min(min(DOTS_GRP, hi - cur), MR - j);+ int2 pk[DOTS_GRP][NIT];+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ #pragma unroll+ for (int it = 0; it < NIT; ++it)+ {+ const int c = tid + 128 * it;+ pk[q][it] = (q < n && c < D4 / 2) ? ((const int2*) (p.fn + fn_row<S>(j + q, h)))[c] : make_int2(0, 0);+ }+ float4 xs[NIT][2][MAXR];+ #pragma unroll+ for (int it = 0; it < NIT; ++it)+ {+ const int c = tid + 128 * it;+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ xs[it][0][r] = make_float4(0.f, 0.f, 0.f, 0.f); xs[it][1][r] = xs[it][0][r];+ if (r < R && c < D4 / 2)+ {+ const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));+ xs[it][0][r] = s4[(size_t) h * D4 + 2 * c]; xs[it][1][r] = s4[(size_t) h * D4 + 2 * c + 1];+ }+ }+ }+ float a[DOTS_GRP][MAXR];+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) a[q][r] = 0.0f;+ #pragma unroll+ for (int it = 0; it < NIT; ++it)+ {+ const int c = tid + 128 * it;+ if (c < D4 / 2)+ {+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ {+ if (q < n)+ {+ float w0, w1, w2, w3, w4, w5, w6, w7;+ if (p.gs)+ {+ const float gsc = p.fn_scale[fngs_idx<S>(j + q, h, c)];+ gs_unpack_s8x4((uint32_t) pk[q][it].x, gsc, w0, w1, w2, w3);+ gs_unpack_s8x4((uint32_t) pk[q][it].y, gsc, w4, w5, w6, w7);+ }+ else+ {+ unpack_s8x4((uint32_t) pk[q][it].x, w0, w1, w2, w3);+ unpack_s8x4((uint32_t) pk[q][it].y, w4, w5, w6, w7);+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ if (r < R)+ {+ const float4 s0 = xs[it][0][r], s1 = xs[it][1][r];+ float x = a[q][r];+ x = fmaf(s0.x, w0, x); x = fmaf(s0.y, w1, x); x = fmaf(s0.z, w2, x); x = fmaf(s0.w, w3, x);+ x = fmaf(s1.x, w4, x); x = fmaf(s1.y, w5, x); x = fmaf(s1.z, w6, x); x = fmaf(s1.w, w7, x);+ a[q][r] = x;+ }+ }+ }+ }+ }+ }+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ if (q < n)+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ float v = a[q][r];+ for (int o = 16; o > 0; o >>= 1) v += __shfl_down(v, o, 32);+ if (lane == 0) scr[dots_scratch(team, m0 + q, r, warp)] = v;+ }+ }+ else+ {+ float4 sv[NIT2][MAXR];+ #pragma unroll+ for (int it = 0; it < NIT2; ++it)+ {+ const int c = tid + 128 * it;+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ sv[it][r] = make_float4(0.f, 0.f, 0.f, 0.f);+ if (r < R && c < D4) sv[it][r] = ((const float4*) (p.xin + xin_row<S>(r, 0)))[(size_t) h * D4 + c];+ }+ }+ float a[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) a[r] = 0.0f;+ #pragma unroll+ for (int it = 0; it < NIT2; ++it)+ if (tid + 128 * it < D4)+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R) a[r] = fmaf(sv[it][r].x, sv[it][r].x, fmaf(sv[it][r].y, sv[it][r].y, fmaf(sv[it][r].z, sv[it][r].z, fmaf(sv[it][r].w, sv[it][r].w, a[r]))));+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ float v = a[r];+ for (int o = 16; o > 0; o >>= 1) v += __shfl_down(v, o, 32);+ if (lane == 0) scr[dots_scratch(team, m0, r, warp)] = v;+ }+ }+ cur += n;+ }+ __syncthreads();+ for (int idx = threadIdx.x; idx < 4 * DOTS_MAXIT * R; idx += THREADS)+ {+ const int tm = idx / (DOTS_MAXIT * R), rem = idx % (DOTS_MAXIT * R), m = rem / R, r = rem % R;+ const int tgx = blockIdx.x * 4 + tm;+ const int it = dots_lo(total, NT, tgx) + m;+ if (it >= dots_lo(total, NT, tgx + 1)) continue;+ const int h = it / MR1, j = it % MR1;+ float v = 0.0f;+ #pragma unroll+ for (int w = 0; w < 4; ++w) v += scr[dots_scratch(tm, m, r, w)];+ if (j < MR && !p.gs) v *= p.fn_scale[j];+ p.dots[dots_idx<S>(r, j, h)] = v;+ }+}++// ---------------------------------------------------------------- phase 1: HC finalize (core5 arithmetic; the int8 up-projection words are loaded before the scalar prologue)+template <class S, bool TM>+__device__ void ph_finalize7(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, team = threadIdx.x >> 8, tid = threadIdx.x & 255, lane = tid & 31, warp = tid >> 5;+ const int D4 = D / 4;+ constexpr int CH = 32, NI = LR / 32, NTS = (LR * MAXR + 255) / 256;+ static_assert(LR % 32 == 0 && D % CH == 0, "finalize7 shape");+ const int total = DM::FIN_CHUNKS;+ const int rounds = (total + p.G * 2 - 1) / (p.G * 2);+ float* t_s = s.u.h.t[team];+ float* rmr_s = s.u.h.rmr[team];+ const float inv_h = 1.0f / (float) H;+ for (int k = 0; k < rounds; ++k)+ {+ const int cidx = blockIdx.x * 2 + team + k * p.G * 2;+ const bool valid = cidx < total;+ const int c = cidx * (CH / 4) + warp; // the warp's single column quad+ // loads in this order (the wait counter is in order): dots of the scalar prologue (L2), then the int8 up words (DRAM)+ static_assert(H == 4, "float4 dots rows");+ float dsum[4];+ float4 dd[NTS];+ #pragma unroll+ for (int h = 0; h < 4; ++h) dsum[h] = 0.0f;+ if (valid && tid < H * R) { const int r = tid / H, h = tid % H; dsum[0] = p.dots[dots_idx<S>(r, MR, h)]; }+ #pragma unroll+ for (int q = 0; q < NTS; ++q)+ {+ const int idx = tid + 256 * q;+ dd[q] = make_float4(0.f, 0.f, 0.f, 0.f);+ if (valid && idx < LR * R) { const int r = idx / LR, ii = idx % LR; dd[q] = *(const float4*) (p.dots + dots_idx<S>(r, 0, 0) + (size_t) ii * H); }+ }+ uint32_t up[H][NI];+ #pragma unroll+ for (int h = 0; h < H; ++h)+ #pragma unroll+ for (int i = 0; i < NI; ++i)+ up[h][i] = valid ? *(const uint32_t*) (p.upt + upt_u32<S>(h, c, lane + 32 * i) * 4) : 0u;+ if (k == 0) st7<TM>(p, 12);+ if (valid && tid < H * R)+ {+ const int r = tid / H, h = tid % H;+ rmr_s[r * 4 + h] = rsqrtf(dsum[0] / (float) D + p.rms_eps);+ }+ __syncthreads();+ if (k == 0) st7<TM>(p, 13);+ if (valid)+ {+ #pragma unroll+ for (int q = 0; q < NTS; ++q)+ {+ const int idx = tid + 256 * q;+ if (idx < LR * R)+ {+ const int r = idx / LR, ii = idx % LR;+ float v = 0.0f;+ v = fmaf(rmr_s[r * 4 + 0], dd[q].x, v); v = fmaf(rmr_s[r * 4 + 1], dd[q].y, v); v = fmaf(rmr_s[r * 4 + 2], dd[q].z, v); v = fmaf(rmr_s[r * 4 + 3], dd[q].w, v);+ v *= inv_h;+ t_s[r * LR + ii] = v * sigmoidf_(v);+ }+ }+ if (cidx == 0 && tid < H)+ {+ for (int r = 0; r < R; ++r)+ {+ const float* dr = p.dots + dots_idx<S>(r, 0, 0);+ float v = 0.0f;+ #pragma unroll+ for (int h = 0; h < H; ++h) v = fmaf(rmr_s[r * 4 + h], dr[(size_t) (LR + tid) * H + h], v);+ p.post[(size_t) r * H + tid] = 2.0f * sigmoidf_(v * inv_h);+ }+ }+ }+ __syncthreads();+ if (k == 0) st7<TM>(p, 14);+ if (valid)+ {+ float4 g[MAXR][H];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ #pragma unroll+ for (int h = 0; h < H; ++h) g[r][h] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ float4 gsc[H];+ #pragma unroll+ for (int i = 0; i < NI; ++i)+ {+ const int ii = lane + 32 * i;+ float ti[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) ti[r] = r < R ? t_s[r * LR + ii] : 0.0f;+ if (p.gs && (i & 1) == 0) // first 32-rank step of a 64-rank group+ {+ #pragma unroll+ for (int h = 0; h < H; ++h) gsc[h] = *(const float4*) (p.up_scale + upgs_idx<S>(h, c, ii));+ }+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ float u0, u1, u2, u3;+ unpack_s8x4(up[h][i], u0, u1, u2, u3);+ if (p.gs) { u0 = gs_dq(u0, gsc[h].x); u1 = gs_dq(u1, gsc[h].y); u2 = gs_dq(u2, gsc[h].z); u3 = gs_dq(u3, gsc[h].w); }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ g[r][h].x = fmaf(ti[r], u0, g[r][h].x); g[r][h].y = fmaf(ti[r], u1, g[r][h].y);+ g[r][h].z = fmaf(ti[r], u2, g[r][h].z); g[r][h].w = fmaf(ti[r], u3, g[r][h].w);+ }+ }+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ #pragma unroll+ for (int h = 0; h < H; ++h)+ for (int o = 16; o > 0; o >>= 1)+ {+ g[r][h].x += __shfl_xor(g[r][h].x, o, 32); g[r][h].y += __shfl_xor(g[r][h].y, o, 32);+ g[r][h].z += __shfl_xor(g[r][h].z, o, 32); g[r][h].w += __shfl_xor(g[r][h].w, o, 32);+ }+ if (lane == 0)+ {+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));+ float4 o = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ const float4 sc = p.gs ? make_float4(1.0f, 1.0f, 1.0f, 1.0f) : *(const float4*) (p.up_scale + upsc_idx<S>(h, c));+ float4 sv = s4[(size_t) h * D4 + c];+ half4 wq = *(const half4*) (p.w + upsc_idx<S>(h, c));+ float coef = rmr_s[r * 4 + h] * inv_h;+ o.x = fmaf(sigmoidf_(g[r][h].x * sc.x) * coef * __low2float(wq.x), sv.x, o.x);+ o.y = fmaf(sigmoidf_(g[r][h].y * sc.y) * coef * __high2float(wq.x), sv.y, o.y);+ o.z = fmaf(sigmoidf_(g[r][h].z * sc.z) * coef * __low2float(wq.y), sv.z, o.z);+ o.w = fmaf(sigmoidf_(g[r][h].w * sc.w) * coef * __high2float(wq.y), sv.w, o.w);+ }+ half2* out2 = (half2*) (p.mixed + mixed_row<S>(r));+ out2[c * 2] = __floats2half2_rn(o.x, o.y);+ out2[c * 2 + 1] = __floats2half2_rn(o.z, o.w);+ }+ }+ }+ __syncthreads();+ if (k == 0) st7<TM>(p, 15);+ }+}++// ---------------------------------------------------------------- phase 2: router logits, all row loads of two experts issued before the first fma+template <class S>+__device__ void ph_router7(const Params& p, Smem<S>& s)+{+ MF_DIMS+ constexpr int NIT = D / 64, NE = 2;+ static_assert(D % 64 == 0, "router7 shape");+ const int R = p.R, wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ half* mx = s.u.g.A;+ for (int i = threadIdx.x; i < R * D / 8; i += THREADS) ((uint4*) mx)[i] = ((const uint4*) p.mixed)[i];+ __syncthreads();+ for (int eb = wave * p.G + blockIdx.x; eb < NEXP; eb += NE * 16 * p.G)+ {+ uint32_t g[NE][NIT];+ #pragma unroll+ for (int k = 0; k < NE; ++k)+ {+ const int e = eb + k * 16 * p.G;+ const uint32_t* g2 = (const uint32_t*) (p.router + router_row<S>(e < NEXP ? e : eb));+ #pragma unroll+ for (int i = 0; i < NIT; ++i) g[k][i] = g2[lane + 32 * i];+ }+ #pragma unroll+ for (int k = 0; k < NE; ++k)+ {+ const int e = eb + k * 16 * p.G;+ if (e < NEXP)+ {+ float sum[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) sum[r] = 0.0f;+ #pragma unroll+ for (int i = 0; i < NIT; ++i)+ {+ const half2 gg = __builtin_bit_cast(half2, g[k][i]);+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ const half2 hh = ((const half2*) (mx + (size_t) r * D))[lane + 32 * i];+ sum[r] = fmaf(__half2float(__low2half(hh)), __half2float(__low2half(gg)), sum[r]);+ sum[r] = fmaf(__half2float(__high2half(hh)), __half2float(__high2half(gg)), sum[r]);+ }+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ float v = wave_sum_down(sum[r]);+ if (lane == 0 && r < R) p.scores[scores_idx<S>(r, e)] = __float2half_rn(v);+ }+ }+ }+ }+ if (blockIdx.x == p.G - 1 && wave == 15)+ {+ // replay of the engine's add_sigmoid_gate_proj reduction (virtual thread t = lane + 32 j, strided fma chain, tree strides 512..32 as register folds, then 16..1 by shuffles);+ // all sgate loads are issued first, the fma chain order per (row, j) is unchanged+ constexpr int NT3 = (D + 1023) / 1024;+ float sgf[32][NT3];+ #pragma unroll+ for (int j = 0; j < 32; ++j)+ #pragma unroll+ for (int t = 0; t < NT3; ++t)+ {+ const int i = lane + 32 * j + 1024 * t;+ sgf[j][t] = i < D ? __half2float(p.sgate_w[i]) : 0.0f;+ }+ for (int r = 0; r < R; ++r)+ {+ float pt[32];+ #pragma unroll+ for (int j = 0; j < 32; ++j)+ {+ float a = 0.0f;+ #pragma unroll+ for (int t = 0; t < NT3; ++t)+ {+ const int i = lane + 32 * j + 1024 * t;+ if (i < D) a = fmaf(sgf[j][t], __half2float(mx[(size_t) r * D + i]), a);+ }+ pt[j] = a;+ }+ #pragma unroll+ for (int w = 16; w >= 1; w >>= 1)+ {+ #pragma unroll+ for (int j = 0; j < w; ++j) pt[j] += pt[j + w];+ }+ const float v = wave_sum_down(pt[0]);+ if (lane == 0) p.sgl[r] = v;+ }+ }+}++template <class S, bool TM, int ABL>+__global__ __launch_bounds__(THREADS) void moe_fused7_kernel(Params p, int vmask)+{+ __shared__ Smem<S> s;+ int phase = 0;+ st7<TM>(p, 0);+ if (vmask & 1) ph_dots7<S>(p, s); else mf::ph_dots<S>(p, s);+ gbar7<TM>(p, phase);+ if (vmask & 2) ph_finalize7<S, TM>(p, s); else mf::ph_finalize<S>(p, s);+ gbar7<TM>(p, phase);+ if (vmask & 4) ph_router7<S>(p, s); else mf::ph_router<S>(p, s);+ gbar7<TM>(p, phase);+ ph_topk<S>(p, s);+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[threadIdx.x] = s.sel[threadIdx.x];+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[64 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);+ ph_gateup7<S, ABL>(p, s); gbar7<TM>(p, phase);+ ph_down7<S, ABL>(p, s); gbar7<TM>(p, phase);+ ph_combine<S>(p, s);+ st7<TM>(p, 11);+ gfinish(p);+}++} // namespace mf7+#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_idx.h b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_idx.hnew file mode 100644index 0000000..acba82d--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_idx.h@@ -0,0 +1,14 @@+#pragma once+// core7: index plan of the phases rewritten in exl3_moe_fused7.cuh. Pure C++, shared by the kernel and by the CPU bounds checker (bounds7.cpp).+#include "exl3_moe_fused_idx.h"+namespace mf7 {+using namespace mf;+// dots phase: (h, j) items, h-major: item i = h * (MR + 1) + j, j = MR is the sum-of-squares row. Team t (128 threads) of NT owns [dots_lo(t), dots_lo(t + 1)).+constexpr int DOTS_MAXIT = 24; // upper bound of items per team (checked at launch and in the CPU proof)+constexpr int DOTS_GRP = 4; // items of the same h processed together (loads hoisted, x rows shared)+MF_FN int dots_lo(long long total, int nt, int t) { return (int) (total * t / nt); }+// LDS scratch of one team: [item slot][row][warp] floats, inside Smem.u.g.red (RED_SIZE floats)+MF_FN int dots_scratch(int team, int m, int r, int warp) { return ((team * DOTS_MAXIT + m) * MAXR + r) * 4 + warp; }+constexpr int DOTS_SCRATCH_MAX = 4 * DOTS_MAXIT * MAXR * 4;+static_assert(DOTS_SCRATCH_MAX <= RED_SIZE, "dots scratch fits in red");+}diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_mv.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_mv.cuhnew file mode 100644index 0000000..a02347e--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_mv.cuh@@ -0,0 +1,301 @@+#pragma once+// core7: matvec phases (core5's gate/up and down) with compile-time ablation / decode variants. ABL bits: 1 = no trellis decode, 2 = every slice re-reads slice 0+// (no DRAM stream), 8 = hash multiply as two v_mul_u32_u24 + shift-add (bit-identical: all window states are 16 bit). ABL = 0 is core5's body.+// Generated from exl3_moe_fused.cuh (names mf_tile -> mf7_tile ...); ablated kernels compute garbage on purpose and are used for timing only.+namespace mf7_mv {+__device__ __forceinline__ uint32_t sad_u8_c7(uint32_t p, uint32_t addend) // same instruction as exl3_sad_u8_ (V_SAD_U8(p, 0, addend))+{+ uint32_t u;+ asm("v_sad_u8 %0, %1, %2, %3" : "=v"(u) : "v"(p), "n"(0), "n"(addend));+ return u;+}+__device__ __forceinline__ uint32_t hash_m24(uint32_t x) // == x * 0x83DCD12D (mod 2^32) for x < 2^24+{+ return __umul24(x, 0xDCD12Du) + (__umul24(x, 0x83u) << 24);+}+__device__ __forceinline__ half2 dec_pair_m24(uint32_t x0, uint32_t x1)+{+ x0 = hash_m24(x0); x1 = hash_m24(x1);+ const uint32_t sum1 = sad_u8_c7(x1, 0x6400u);+ const uint32_t sum0 = sad_u8_c7(x0, 0x6400u);+ const uint32_t packed = (sum1 << 16) + sum0;+ half2 k_inv_h2 = __half2half2(__ushort_as_half(0x1eee));+ half2 k_bias_h2 = __half2half2(__ushort_as_half(0xc931));+ half_uint16 h0((uint16_t) packed);+ half_uint16 h1((uint16_t) (packed >> 16));+ return __hfma2(__halves2half2(h0.as_half, h1.as_half), k_inv_h2, k_bias_h2);+}+__device__ __forceinline__ void decode8_m24(uint32_t w0, uint32_t w1, uint32_t w2, uint32_t w3, uint32_t w4, uint32_t w5, uint32_t w6, uint32_t w7, FragB& f0, FragB& f1)+{+ f0[0] = dec_pair_m24(w0, w1); f0[1] = dec_pair_m24(w2, w3); f1[0] = dec_pair_m24(w4, w5); f1[1] = dec_pair_m24(w6, w7);+}+__device__ __forceinline__ void dq8_regs_2bits_m24(uint32_t a, uint32_t b, int t_offset, FragB& f0, FragB& f1)+{+ uint32_t w0, w1, w2, w3, w4, w5, w6, w7;+ b = fshift(b, a, ((~t_offset) & 8) << 1);+ w7 = b & 0xffff;+ BFE16_IMM(w6, b, 2); BFE16_IMM(w5, b, 4); BFE16_IMM(w4, b, 6); BFE16_IMM(w3, b, 8); BFE16_IMM(w2, b, 10); BFE16_IMM(w1, b, 12); BFE16_IMM(w0, b, 14);+ decode8_m24(w0, w1, w2, w3, w4, w5, w6, w7, f0, f1);+}+__device__ __forceinline__ void dq8_regs_4bits_m24(uint32_t a, uint32_t b, FragB& f0, FragB& f1)+{+ uint32_t s, w0, w1, w2, w3, w4, w5, w6, w7;+ FSHF_IMM(s, b, a, 20);+ w7 = b & 0xffff;+ BFE16_IMM(w6, b, 4); BFE16_IMM(w5, b, 8); BFE16_IMM(w4, b, 12); BFE16_IMM(w3, b, 16);+ w2 = s & 0xffff;+ BFE16_IMM(w1, s, 4); BFE16_IMM(w0, s, 8);+ decode8_m24(w0, w1, w2, w3, w4, w5, w6, w7, f0, f1);+}+} // namespace mf7_mv+namespace mf7 {+using namespace mf;+using mf7_mv::dq8_regs_2bits_m24; using mf7_mv::dq8_regs_4bits_m24;+template <int BITS, bool CF32, int RW, int KS, int ABL>+__device__ __forceinline__ void mf7_tile(const uint32_t* __restrict__ A32, const uint32_t* __restrict__ Bt, long ss, void* __restrict__ C,+ int size_n, int tile, float* red, int wave, int lane)+{+ static_assert(BITS >= 2 && BITS <= 5, "K1, K6.. need their own per-lane word set and decode body: not implemented");+ constexpr int NWD = BITS + 1, CH = (KS + 15) / 16, NRND = 4, K = KS * 16;+ constexpr int VU = CH > 5 ? 5 : CH;+ const int g8 = lane & 7, cq = lane >> 3;+ float rs0[RW], rs1[RW];+ #pragma unroll+ for (int r = 0; r < RW; ++r) { rs0[r] = 0.f; rs1[r] = 0.f; }+ uint32_t wa[VU][NWD], wb[VU][NWD];+ auto ld = [&](uint32_t (&w)[NWD], int s)+ {+ if constexpr ((ABL & 2) != 0) s = 0; // ablation: every slice re-reads slice 0 (cache hits, same instruction count)+ w[0] = Bt[wrp_i(BITS, g8, s, ss)];+ const uint32_t* q = Bt + own_i(BITS, g8, s, ss);+ if constexpr (BITS == 2) { const uint2 v = *(const uint2*) q; w[1] = v.x; w[2] = v.y; }+ else if constexpr (BITS == 3) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; }+ else if constexpr (BITS == 5) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; w[4] = q[3]; w[5] = q[4]; }+ else { const uint4 v = *(const uint4*) q; w[1] = v.x; w[2] = v.y; w[3] = v.z; w[4] = v.w; }+ };+ auto ldst = [&](uint32_t (&w)[VU][NWD], int rnd, int sg0)+ {+ const int cc = 4 * rnd + cq, s0n = cc * CH, m = myn(KS, cc);+ #pragma unroll+ for (int u = 0; u < VU; ++u) if (sg0 + u < m) ld(w[u], s0n + sg0 + u);+ };+ ldst(wa, 0, 0);+ #pragma unroll 1+ for (int round = 0; round < NRND; ++round)+ {+ const int c = 4 * round + cq;+ const int s0 = c * CH;+ const int myn_ = myn(KS, c);+ float acc0[RW], acc1[RW];+ #pragma unroll+ for (int r = 0; r < RW; ++r) { acc0[r] = 0.f; acc1[r] = 0.f; }+ #pragma unroll 1+ for (int sb = 0; sb < CH; sb += VU)+ {+ int nr = round, ns = sb + VU;+ if (ns >= CH) { nr = round + 1; ns = 0; }+ if (nr < NRND) ldst(wb, nr, ns);+ #pragma unroll+ for (int u = 0; u < VU; ++u)+ {+ if (sb + u < myn_)+ {+ FragB f0[4], f1[4];+ #pragma unroll+ for (int t = 0; t < 4; ++t)+ {+ if constexpr ((ABL & 1) != 0)+ { // ablation: no trellis decode, the words themselves stand in for the decoded halves+ f0[t][0] = __builtin_bit_cast(half2, wa[u][t & 1]); f0[t][1] = __builtin_bit_cast(half2, wa[u][1 + (t & 1)] ^ (uint32_t) t);+ f1[t][0] = __builtin_bit_cast(half2, wa[u][(t + 1) & 1] + 0x1234u); f1[t][1] = __builtin_bit_cast(half2, wa[u][1 + ((t + 1) & 1)]);+ }+ else if constexpr ((ABL & 8) != 0 && BITS == 2) dq8_regs_2bits_m24(wa[u][t >> 1], wa[u][1 + (t >> 1)], t << 3, f0[t], f1[t]);+ else if constexpr ((ABL & 8) != 0 && BITS == 4) dq8_regs_4bits_m24(wa[u][t], wa[u][t + 1], f0[t], f1[t]);+ else if constexpr (BITS == 2) exl3_gemv_ns::dq8_regs_2bits<2>(wa[u][t >> 1], wa[u][1 + (t >> 1)], t << 3, f0[t], f1[t]);+ else if constexpr (BITS == 3) exl3_gemv_ns::dq8_regs_3bits<2>(wa[u][t == 0 ? 0 : (t == 1 ? 1 : 2)], wa[u][t == 0 ? 1 : (t == 1 ? 2 : 3)], t == 0 ? 8 : (t == 1 ? 16 : (t == 2 ? 24 : 0)), f0[t], f1[t]);+ else if constexpr (BITS == 5) mf_dq8_k5(wa[u], t, f0[t], f1[t]);+ else exl3_gemv_ns::dq8_regs_4bits<2>(wa[u][t], wa[u][t + 1], f0[t], f1[t]);+ }+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ const long ai = a_idx(r, K, s0 + sb + u);+ const uint4 alo = *(const uint4*) (A32 + ai);+ const uint4 ahi = *(const uint4*) (A32 + ai + 4);+ const uint32_t aq[8] = {alo.x, alo.y, alo.z, alo.w, ahi.x, ahi.y, ahi.z, ahi.w};+ #pragma unroll+ for (int q = 0; q < 8; ++q)+ {+ const int t = q & 3, h = q >> 2;+ acc0[r] = mv_dot2(__builtin_bit_cast(uint32_t, f0[t][h]), aq[q], acc0[r]);+ acc1[r] = mv_dot2(__builtin_bit_cast(uint32_t, f1[t][h]), aq[q], acc1[r]);+ }+ }+ }+ }+ #pragma unroll+ for (int u = 0; u < VU; ++u)+ #pragma unroll+ for (int w = 0; w < NWD; ++w) wa[u][w] = wb[u][w];+ }+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ red[red_idx(wave, cq, g8, r)] = acc0[r];+ red[red_idx(wave, cq, g8 + 8, r)] = acc1[r];+ }+ __syncwarp();+ if (cq == 0)+ {+ #pragma unroll+ for (int cc = 0; cc < 4; ++cc)+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ rs0[r] += red[red_idx(wave, cc, g8, r)];+ rs1[r] += red[red_idx(wave, cc, g8 + 8, r)];+ }+ }+ __syncwarp();+ }+ if (cq == 0)+ {+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ if constexpr (CF32) { ((float*) C)[c_idx(r, size_n, tile, g8)] = rs0[r]; ((float*) C)[c_idx(r, size_n, tile, g8 + 8)] = rs1[r]; }+ else { ((half*) C)[c_idx(r, size_n, tile, g8)] = __float2half_rn(rs0[r]); ((half*) C)[c_idx(r, size_n, tile, g8 + 8)] = __float2half_rn(rs1[r]); }+ }+ }+}++template <int BITS, bool CF32, int KS, int ABL>+__device__ __forceinline__ void mf7_tile_rows(int rows, const uint32_t* A32, const uint32_t* Bt, long ss, void* C, int size_n, int tile, float* red, int wave, int lane)+{+ if (rows == 1) mf7_tile<BITS, CF32, 1, KS, ABL>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+ else if (rows == 2) mf7_tile<BITS, CF32, 2, KS, ABL>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+ else if (rows == 3) mf7_tile<BITS, CF32, 3, KS, ABL>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+ else mf7_tile<BITS, CF32, 4, KS, ABL>(A32, Bt, ss, C, size_n, tile, red, wave, lane);+}+++template <class S, int ABL>+__device__ void ph_gateup7(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK, NAR = NA + R;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int NU = s.ngroups + 1;+ constexpr int TPP = DM::TPP;+ const bool nat = p.native != 0;+ const long long W = split_total(s.urows, NU, 2, TPP);+ const int lo = split_tile(s.urows, NU, 2, TPP, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 2, TPP, (long long) (blockIdx.x + 1) * W / p.G);+ int i = lo;+ while (i < hi)+ {+ const int segA = i / TPP, endA = min(hi, (segA + 1) * TPP);+ const int iB = endA, segB = iB / TPP;+ const bool hasB = iB < hi;+ const int endB = hasB ? min(hi, (segB + 1) * TPP) : iB;+ const int nA = endA - i, nB = endB - iB;+ __syncthreads();+ for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)+ {+ const int seg = w2 ? segB : segA;+ const Seg g = seginfo<S>(p, s, seg, true);+ half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;+ const half* suh = g.sv[g.proj == 0 ? 0 : 2];+ for (int task = wave; task < g.rows * DM::CMB_BLOCKS; task += 16)+ {+ const int row = task / DM::CMB_BLOCKS, blk = task % DM::CMB_BLOCKS;+ const int token = g.shared ? row : s.tok[g.p0 + row];+ half4 v = ((const half4*) (p.mixed + mixed_row<S>(token) + blk * 128))[lane];+ v = had_regs_h<true, false>(v, suh + blk * 128, lane);+ ((half4*) (Abuf + a_row_gu<S>(row, blk)))[lane] = v;+ }+ }+ __syncthreads();+ for (int n = wave; n < nA + nB; n += 16)+ {+ const bool inB = n >= nA;+ const int seg = inB ? segB : segA;+ const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPP;+ const Seg g = seginfo<S>(p, s, seg, true);+ const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);+ half* C = p.gu + gu_out<S>(g.proj, NAR, g.p0);+ const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + g.proj];+ if (g.shared)+ mf7_tile_rows<DM::SB, false, DM::KSG, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSG, TPP, tile), tile_ss(nat, DM::SB, TPP), C, INTER, tile, s.u.g.red, wave, lane);+ else+ mf7_tile_rows<DM::RB, false, DM::KSG, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSG, TPP, tile), tile_ss(nat, DM::RB, TPP), C, INTER, tile, s.u.g.red, wave, lane);+ }+ i = endB;+ }+}++template <class S, int ABL>+__device__ void ph_down7(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK, NAR = NA + R;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int NU = s.ngroups + 1;+ constexpr int TPU = DM::TPU;+ const bool nat = p.native != 0;+ const long long W = split_total(s.urows, NU, 1, TPU);+ const int lo = split_tile(s.urows, NU, 1, TPU, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 1, TPU, (long long) (blockIdx.x + 1) * W / p.G);+ int i = lo;+ while (i < hi)+ {+ const int segA = i / TPU, endA = min(hi, (segA + 1) * TPU);+ const int iB = endA, segB = iB / TPU;+ const bool hasB = iB < hi;+ const int endB = hasB ? min(hi, (segB + 1) * TPU) : iB;+ const int nA = endA - i, nB = endB - iB;+ __syncthreads();+ for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)+ {+ const Seg g = seginfo<S>(p, s, w2 ? segB : segA, false);+ half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;+ const half* const* sv = g.sv;+ for (int task = wave; task < g.rows * DM::INT_BLOCKS; task += 16)+ {+ const int row = task / DM::INT_BLOCKS, blk = task % DM::INT_BLOCKS;+ half4 gg = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 0)))[lane];+ half4 uu = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 1)))[lane];+ gg = had_regs_h<false, true>(gg, sv[1] + blk * 128, lane);+ uu = had_regs_h<false, true>(uu, sv[3] + blk * 128, lane);+ half4 a;+ {+ float f0 = __half2float(__low2half(gg.x)), f1 = __half2float(__high2half(gg.x));+ float f2 = __half2float(__low2half(gg.y)), f3 = __half2float(__high2half(gg.y));+ half h0 = __float2half_rn(f0 / (1.0f + expf(-f0))), h1 = __float2half_rn(f1 / (1.0f + expf(-f1)));+ half h2 = __float2half_rn(f2 / (1.0f + expf(-f2))), h3 = __float2half_rn(f3 / (1.0f + expf(-f3)));+ a.x = __halves2half2(__hmul(h0, __low2half(uu.x)), __hmul(h1, __high2half(uu.x)));+ a.y = __halves2half2(__hmul(h2, __low2half(uu.y)), __hmul(h3, __high2half(uu.y)));+ }+ a = had_regs_h<true, false>(a, sv[4] + blk * 128, lane);+ ((half4*) (Abuf + a_row_dn<S>(row, blk)))[lane] = a;+ }+ }+ __syncthreads();+ for (int n = wave; n < nA + nB; n += 16)+ {+ const bool inB = n >= nA;+ const int seg = inB ? segB : segA;+ const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPU;+ const Seg g = seginfo<S>(p, s, seg, false);+ const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);+ float* C = p.dn + dn_row<S>(g.p0);+ const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + 2];+ if (g.shared)+ mf7_tile_rows<DM::SB, true, DM::KSD, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSD, TPU, tile), tile_ss(nat, DM::SB, TPU), C, D, tile, s.u.g.red, wave, lane);+ else+ mf7_tile_rows<DM::RB, true, DM::KSD, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSD, TPU, tile), tile_ss(nat, DM::RB, TPU), C, D, tile, s.u.g.red, wave, lane);+ }+ i = endB;+ }+}+++} // namespace mf7diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cunew file mode 100644index 0000000..0b5534f--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu@@ -0,0 +1,110 @@+#if defined(USE_ROCM)+#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include "exl3_moe_fused_api.h"+#include "hadamard.cuh"+#include <c10/cuda/CUDAGuard.h>+#include <ATen/cuda/CUDAContext.h>+#include <torch/library.h>+#include "../util.h"+#include "../util.cuh"+#include "exl3_gemv_kernel.cuh"+#include "exl3_moe_valu.cuh"+#include "exl3_moe_fused9.cuh"+#include <algorithm>+#include <type_traits>++// core9: torch.ops.mf9.half (mf7 kernel + cache touches), same arguments and workspace layout as exl3_moe_fused_half (Qwen shape only), plus `timing` (1 = phase stamps into seldbg).+namespace {+template <class S7, bool TM, int OCC, int INL, int ABL = 0> int grid7()+{+ static int G = [] {+ int nb = 0, dev = 0; hipGetDevice(&dev);+ hipDeviceProp_t prop; hipGetDeviceProperties(&prop, dev);+ cuda_check(hipOccupancyMaxActiveBlocksPerMultiprocessor(&nb, (OCC ? (const void*) mf9::moe_fused9o_kernel<S7, TM, (bool) INL, ABL> : (const void*) mf9::moe_fused9_kernel<S7, TM, (bool) INL, ABL>), mf::THREADS, 0));+ return (OCC == 3 ? 1 : OCC == 2 ? 2 : std::max(1, nb)) * prop.multiProcessorCount; // OCC 2: forced two blocks per WGP (the occupancy API reports one); OCC 3: one block per WGP, half the VGPR / LDS free for other GPU clients+ }();+ return G;+}+template <class S> struct Match7+{+ static bool eq(int D, int H, int LR, int NEXP, int TOPK, int INTER, int RB, int SB)+ { return D == S::D && H == S::H && LR == S::LR && NEXP == S::NEXP && TOPK == S::TOPK && INTER == S::INTER && RB == S::RB && SB == S::SB; }+};+template <class S7, bool TM, int OCC, int INL, int ABL = 0> void launch7(const at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, const at::Tensor& upt, const at::Tensor& up_scale,+ const at::Tensor& w_h, const at::Tensor& router, const at::Tensor& sgate, const at::Tensor& wt, const at::Tensor& svt,+ at::Tensor& ws, double rms_eps, int native, int R, int vmask, hipStream_t stream)+{+ using DM = mf::Dm<S7>;+ const auto off = exl3_moe_fused_ws_offsets(S7::D, S7::H, S7::LR, S7::NEXP, S7::TOPK, S7::INTER, S7::RB, S7::SB);+ TORCH_CHECK(ws.numel() >= off.back(), "mf9: workspace too small");+ const bool gs = fn_scale.numel() != DM::MR;+ TORCH_CHECK(!gs || mf::gs_ok<S7>(), "mf9: group scales need D % 128 == 0");+ TORCH_CHECK(fn.numel() == (int64_t) DM::MR * S7::H * S7::D && fn_scale.numel() == mf::fn_scale_n<S7>(gs), "mf9: fn size");+ TORCH_CHECK(upt.numel() == (int64_t) S7::H * DM::D4 * S7::LR * 4, "mf9: upt size");+ TORCH_CHECK(up_scale.numel() == mf::up_scale_n<S7>(gs) && w_h.numel() == (int64_t) S7::H * S7::D, "mf9: up_scale size");+ TORCH_CHECK(router.numel() == (int64_t) S7::NEXP * S7::D && sgate.numel() == S7::D, "mf9: router size");+ TORCH_CHECK(wt.dtype() == at::kLong && wt.numel() == 3 * (S7::NEXP + 1) && svt.dtype() == at::kLong && svt.numel() == 6 * (S7::NEXP + 1), "mf9: pointer tables");+ char* wb = (char*) ws.data_ptr();+ mf::Params p{};+ p.R = R; p.G = grid7<S7, TM, OCC, INL, ABL>();+ TORCH_CHECK(p.G >= 1 && p.G <= mf::CTL_MAXB, "mf9: grid exceeds the barrier arrival-marker words");+ TORCH_CHECK(((long long) S7::H * (DM::MR + 1) + 4LL * p.G - 1) / (4LL * p.G) + 1 <= mf7::DOTS_MAXIT, "mf9: dots items per team exceed DOTS_MAXIT");+ p.xin = (float*) x.data_ptr(); p.xout = (float*) x.data_ptr();+ p.fn = (const int8_t*) fn.data_ptr(); p.fn_scale = (const float*) fn_scale.data_ptr(); p.upt = (const int8_t*) upt.data_ptr();+ p.gs = gs ? 1 : 0; p.up_scale = (const float*) up_scale.data_ptr(); p.w = (const half*) w_h.data_ptr();+ p.router = (const half*) router.data_ptr(); p.sgate_w = (const half*) sgate.data_ptr();+ p.wt = (const uint32_t* const*) wt.data_ptr(); p.svt = (const half* const*) svt.data_ptr(); p.native = native;+ unsigned* ctl = (unsigned*) (wb + off[0]);+ p.bar = ctl; p.done = ctl + 1; p.err = (int*) (ctl + 2);+ p.dots = (float*) (wb + off[1]); p.post = (float*) (wb + off[2]); p.mixed = (half*) (wb + off[3]); p.scores = (half*) (wb + off[4]);+ p.sgl = (float*) (wb + off[5]); p.gu = (half*) (wb + off[6]); p.dn = (float*) (wb + off[7]); p.ydbg = (float*) (wb + off[8]); p.seldbg = (int*) (wb + off[9]);+ p.rms_eps = (float) rms_eps;+ if (OCC) { mf9::moe_fused9o_kernel<S7, TM, (bool) INL, ABL><<<p.G, mf::THREADS, 0, stream>>>(p, vmask); }+ else { mf9::moe_fused9_kernel<S7, TM, (bool) INL, ABL><<<p.G, mf::THREADS, 0, stream>>>(p, vmask); }+ cuda_check(hipPeekAtLastError());+}+} // namespace++void mf9_half(at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, const at::Tensor& upt, const at::Tensor& up_scale, const at::Tensor& w_h,+ const at::Tensor& router, const at::Tensor& sgate, const at::Tensor& wt, const at::Tensor& svt, at::Tensor& ws, double rms_eps, int64_t native, int64_t timing, int64_t variant,+ int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB)+{+ const at::cuda::OptionalCUDAGuard device_guard(x.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ TORCH_CHECK(x.dtype() == at::kFloat && x.is_contiguous() && x.dim() == 4 && x.size(2) == H && x.size(3) == D, "mf9: x");+ const int R = (int) (x.size(0) * x.size(1));+ TORCH_CHECK(R >= 1 && R <= mf::MAXR, "mf9: rows 1..4");+ TORCH_CHECK(fn.dtype() == at::kChar && upt.dtype() == at::kChar && fn_scale.dtype() == at::kFloat && up_scale.dtype() == at::kFloat, "mf9: dtypes");+ TORCH_CHECK(w_h.dtype() == at::kHalf && router.dtype() == at::kHalf && sgate.dtype() == at::kHalf && ws.dtype() == at::kByte, "mf9: dtypes 2");+ TORCH_CHECK(native == 0 || native == 1, "mf9: native flag");+#define L7A(SH, TMV, OCCV, INLV, ABLV) launch7<SH, TMV, OCCV, INLV, ABLV>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, (int) (variant & 0xffff), stream)+#define L7(SH, TMV, OCCV, INLV) launch7<SH, TMV, OCCV, INLV>(x, fn, fn_scale, upt, up_scale, w_h, router, sgate, wt, svt, ws, rms_eps, (int) native, R, (int) (variant & 0xffff), stream)+#define X7(SH) if (Match7<SH>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { \+ if ((variant & 0x80000) && (variant & 0x70000) == 0x60000) { if (timing) L7(SH, true, 3, 1); else L7(SH, false, 3, 1); return; } /* one block per WGP */ \+ const int occ = (variant & 0x40000) ? 2 : ((variant & 0x10000) != 0), inl = (variant & 0x20000) != 0; \+ if (timing) { if (occ == 2) { if (inl) L7(SH, true, 2, 1); else L7(SH, true, 2, 0); } else if (occ) { if (inl) L7(SH, true, 1, 1); else L7(SH, true, 1, 0); } else { if (inl) L7(SH, true, 0, 1); else L7(SH, true, 0, 0); } return; } \+ if (occ == 2) { if (inl) L7(SH, false, 2, 1); else L7(SH, false, 2, 0); } else if (occ) { if (inl) L7(SH, false, 1, 1); else L7(SH, false, 1, 0); } else { if (inl) L7(SH, false, 0, 1); else L7(SH, false, 0, 0); } return; }+ X7(mf::QwenShape) X7(mf::SmallTestShape)+#undef X7+ // the shapes of K3 / K4 routed packs and K4 / K5 shared experts carry the served variant only (two blocks per WGP, forced inline, no timing build)+#define X9D(SH) if (Match7<SH>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) { \+ TORCH_CHECK((variant & 0x70000) == 0x60000, "mf9: this shape is instantiated for the default variant 0x60000 only"); \+ const bool one = (variant & 0x80000) != 0; /* one block per WGP, same kernel and arithmetic */ \+ if (timing) { if (one) L7(SH, true, 3, 1); else L7(SH, true, 2, 1); return; } \+ if (one) L7(SH, false, 3, 1); else L7(SH, false, 2, 1); return; }+ // ablation arms (timing only, garbage values by design, no index depends on them): variant bits 0x100 no decode, 0x200 every slice re-reads slice 0 (K4/S5 only)+ if (Match7<mf::QwenK4S5>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB) && (variant & 0x300) && timing) { TORCH_CHECK((variant & 0x70000) == 0x60000, "mf9: ablation needs 0x60000");+ switch ((variant >> 8) & 3) { case 1: L7A(mf::QwenK4S5, true, 2, 1, 1); break; case 2: L7A(mf::QwenK4S5, true, 2, 1, 2); break; default: L7A(mf::QwenK4S5, true, 2, 1, 3); } return; }+ X9D(mf::QwenK3S4) X9D(mf::QwenK3S5) X9D(mf::QwenK4S4) X9D(mf::QwenK4S5)+ X9D(mf::SmallK3S4) X9D(mf::SmallK3S5) X9D(mf::SmallK4S4) X9D(mf::SmallK4S5)+#undef X9D+ TORCH_CHECK(false, "mf9: shape not instantiated");+}++TORCH_LIBRARY_FRAGMENT(mf9, m)+{+ m.def("half(Tensor(a!) x, Tensor fn, Tensor fn_scale, Tensor upt, Tensor up_scale, Tensor w_h, Tensor router, Tensor sgate, Tensor wt, Tensor svt, Tensor(b!) ws, float rms_eps, int native, int timing, int variant, int D, int H, int LR, int NEXP, int TOPK, int INTER, int RB, int SB) -> ()");+}+TORCH_LIBRARY_IMPL(mf9, CUDA, m) { m.impl("half", &mf9_half); }+#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuhnew file mode 100644index 0000000..74c2945--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuh@@ -0,0 +1,255 @@+#pragma once+// core9: mf7 kernel + cache touches (read-only prefetch loads whose results are dropped).+// - static touch at kernel start / after the first dots group: finalize up-projection words, router rows, shared expert matrices (all known before the router)+// - down touch after top-k: the down matrices of the selected experts, pulled while gate/up streams+// The arithmetic is mf7's, untouched: results are byte-identical to mf7::half for every vm value.+#include "exl3_moe_fused7.cuh"+#include "exl3_moe_fused9_idx.h"+#include "exl3_moe_fused9_inl.cuh"++#if defined(USE_ROCM) || defined(__HIPCC__)+namespace mf9 {+using namespace mf;+constexpr int V_T0 = 1, V_TMID = 2, V_TDOWN = 4, V_SU = 8, V_SR = 16, V_SS = 32;++// the load is inline asm into a sink register that stays live (chained "+v") until the end of the kernel; vector memory loads return in order, nobody reads the sink.+// The compiler does not know about these loads: its own vmcnt waits count only its loads, so they can only over-wait (safe).+__device__ __forceinline__ void touch_one(uint32_t& sink, const void* base, long bytes, long chunk, int lane)+{+ const char* a = (const char*) base + touch_addr(bytes, chunk, lane);+ asm volatile("global_load_b32 %0, %1, off" : "+v"(sink) : "v"(a));+}+__device__ __forceinline__ void touch_range(uint32_t& sink, const void* base, long bytes, int gw, int nw, int lane)+{+ const long nch = touch_nch(bytes);+ for (long ch = gw; ch < nch; ch += nw)+ touch_one(sink, base, bytes, ch, lane);+}+template <class S>+__device__ __forceinline__ void touch_static(const Params& p, int vm, uint32_t& sink)+{+ using DM = Dm<S>;+ const int gw = blockIdx.x * 16 + (threadIdx.x >> 5), nw = p.G * 16, lane = threadIdx.x & 31;+ const int sel = (vm & (V_SU | V_SR | V_SS)) ? (vm & (V_SU | V_SR | V_SS)) : (V_SU | V_SR | V_SS);+ if (sel & V_SU) touch_range(sink, p.upt, upt_bytes<S>(), gw, nw, lane);+ if (sel & V_SR) touch_range(sink, p.router, router_bytes<S>(), gw, nw, lane);+ if (sel & V_SS)+ {+ touch_range(sink, p.wt[3 * DM::NEXP + 0], sh_gu_bytes<S>(), gw, nw, lane);+ touch_range(sink, p.wt[3 * DM::NEXP + 1], sh_gu_bytes<S>(), gw, nw, lane);+ touch_range(sink, p.wt[3 * DM::NEXP + 2], sh_dn_bytes<S>(), gw, nw, lane);+ }+}+template <class S>+__device__ __forceinline__ void touch_down(const Params& p, const Smem<S>& s, uint32_t& sink)+{+ using DM = Dm<S>;+ const int gw = blockIdx.x * 16 + (threadIdx.x >> 5), nw = p.G * 16, lane = threadIdx.x & 31;+ int issued = 0;+ for (int u = 0; u <= s.ngroups && issued < TOUCH_DOWN_CAP; ++u)+ {+ const bool sh = u == s.ngroups;+ const int e = sh ? DM::NEXP : s.sorted_e[s.gstart[u]];+ const void* base = p.wt[3 * e + 2];+ const long bytes = sh ? sh_dn_bytes<S>() : rt_dn_bytes<S>();+ const long nch = touch_nch(bytes);+ for (long ch = gw; ch < nch && issued < TOUCH_DOWN_CAP; ch += nw)+ {+ touch_one(sink, base, bytes, ch, lane);+ ++issued;+ }+ }+}++// ---------------------------------------------------------------- phase 0: HC dots+template <class S>+__device__ __forceinline__ void ph_dots9(const Params& p, Smem<S>& s, int vm, uint32_t& sink)+{+ MF_DIMS+ using namespace mf7;+ constexpr int D4 = DM::D4, NIT = (D4 / 2 + 127) / 128, NIT2 = (D4 + 127) / 128, MR1 = MR + 1;+ const int R = p.R, team = threadIdx.x >> 7, tid = threadIdx.x & 127, lane = tid & 31, warp = tid >> 5;+ const int NT = p.G * 4, tg = blockIdx.x * 4 + team;+ const int total = H * MR1;+ const int lo = dots_lo(total, NT, tg), hi = dots_lo(total, NT, tg + 1);+ float* scr = s.u.g.red;+ int cur = lo;+ bool touched = false;+ while (cur < hi)+ {+ const int h = cur / MR1, j = cur % MR1;+ const int m0 = cur - lo;+ int n = 1;+ if (j < MR)+ {+ n = min(min(DOTS_GRP, hi - cur), MR - j);+ int2 pk[DOTS_GRP][NIT];+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ #pragma unroll+ for (int it = 0; it < NIT; ++it)+ {+ const int c = tid + 128 * it;+ pk[q][it] = (q < n && c < D4 / 2) ? ((const int2*) (p.fn + fn_row<S>(j + q, h)))[c] : make_int2(0, 0);+ }+ float4 xs[NIT][2][MAXR];+ #pragma unroll+ for (int it = 0; it < NIT; ++it)+ {+ const int c = tid + 128 * it;+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ xs[it][0][r] = make_float4(0.f, 0.f, 0.f, 0.f); xs[it][1][r] = xs[it][0][r];+ if (r < R && c < D4 / 2)+ {+ const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));+ xs[it][0][r] = s4[(size_t) h * D4 + 2 * c]; xs[it][1][r] = s4[(size_t) h * D4 + 2 * c + 1];+ }+ }+ }+ if ((vm & V_TMID) && !touched) { touch_static<S>(p, vm, sink); touched = true; }+ float a[DOTS_GRP][MAXR];+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) a[q][r] = 0.0f;+ #pragma unroll+ for (int it = 0; it < NIT; ++it)+ {+ const int c = tid + 128 * it;+ if (c < D4 / 2)+ {+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ {+ if (q < n)+ {+ float w0, w1, w2, w3, w4, w5, w6, w7;+ if (p.gs)+ {+ const float gsc = p.fn_scale[fngs_idx<S>(j + q, h, c)];+ gs_unpack_s8x4((uint32_t) pk[q][it].x, gsc, w0, w1, w2, w3);+ gs_unpack_s8x4((uint32_t) pk[q][it].y, gsc, w4, w5, w6, w7);+ }+ else+ {+ unpack_s8x4((uint32_t) pk[q][it].x, w0, w1, w2, w3);+ unpack_s8x4((uint32_t) pk[q][it].y, w4, w5, w6, w7);+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ if (r < R)+ {+ const float4 s0 = xs[it][0][r], s1 = xs[it][1][r];+ float x = a[q][r];+ x = fmaf(s0.x, w0, x); x = fmaf(s0.y, w1, x); x = fmaf(s0.z, w2, x); x = fmaf(s0.w, w3, x);+ x = fmaf(s1.x, w4, x); x = fmaf(s1.y, w5, x); x = fmaf(s1.z, w6, x); x = fmaf(s1.w, w7, x);+ a[q][r] = x;+ }+ }+ }+ }+ }+ }+ #pragma unroll+ for (int q = 0; q < DOTS_GRP; ++q)+ if (q < n)+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ float v = a[q][r];+ for (int o = 16; o > 0; o >>= 1) v += __shfl_down(v, o, 32);+ if (lane == 0) scr[dots_scratch(team, m0 + q, r, warp)] = v;+ }+ }+ else+ {+ float4 sv[NIT2][MAXR];+ #pragma unroll+ for (int it = 0; it < NIT2; ++it)+ {+ const int c = tid + 128 * it;+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ sv[it][r] = make_float4(0.f, 0.f, 0.f, 0.f);+ if (r < R && c < D4) sv[it][r] = ((const float4*) (p.xin + xin_row<S>(r, 0)))[(size_t) h * D4 + c];+ }+ }+ float a[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) a[r] = 0.0f;+ #pragma unroll+ for (int it = 0; it < NIT2; ++it)+ if (tid + 128 * it < D4)+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R) a[r] = fmaf(sv[it][r].x, sv[it][r].x, fmaf(sv[it][r].y, sv[it][r].y, fmaf(sv[it][r].z, sv[it][r].z, fmaf(sv[it][r].w, sv[it][r].w, a[r]))));+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ float v = a[r];+ for (int o = 16; o > 0; o >>= 1) v += __shfl_down(v, o, 32);+ if (lane == 0) scr[dots_scratch(team, m0, r, warp)] = v;+ }+ }+ cur += n;+ }+ if ((vm & V_TMID) && !touched) touch_static<S>(p, vm, sink);+ __syncthreads();+ for (int idx = threadIdx.x; idx < 4 * DOTS_MAXIT * R; idx += THREADS)+ {+ const int tm = idx / (DOTS_MAXIT * R), rem = idx % (DOTS_MAXIT * R), m = rem / R, r = rem % R;+ const int tgx = blockIdx.x * 4 + tm;+ const int it = dots_lo(total, NT, tgx) + m;+ if (it >= dots_lo(total, NT, tgx + 1)) continue;+ const int h = it / MR1, j = it % MR1;+ float v = 0.0f;+ #pragma unroll+ for (int w = 0; w < 4; ++w) v += scr[dots_scratch(tm, m, r, w)];+ if (j < MR && !p.gs) v *= p.fn_scale[j];+ p.dots[dots_idx<S>(r, j, h)] = v;+ }+}++template <class S, bool TM, bool INL, int ABL = 0>+__device__ __forceinline__ void body9(const Params& p, int vm)+{+ __shared__ Smem<S> s;+ int phase = 0;+ uint32_t sink = 0;+ mf7::st7<TM>(p, 0);+ if (vm & V_T0) touch_static<S>(p, vm, sink);+ ph_dots9<S>(p, s, vm, sink);+ mf7::gbar7<TM>(p, phase);+ if constexpr (INL) ph_finalize9<S, TM>(p, s); else mf7::ph_finalize7<S, TM>(p, s);+ mf7::gbar7<TM>(p, phase);+ if constexpr (INL) ph_router9<S>(p, s); else mf7::ph_router7<S>(p, s);+ mf7::gbar7<TM>(p, phase);+ if constexpr (INL) ph_topk9<S>(p, s, vm); else ph_topk<S>(p, s);+ mf7::st7<TM>(p, 15);+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[threadIdx.x] = s.sel[threadIdx.x];+ if (blockIdx.x == 0 && threadIdx.x < p.R * S::TOPK) p.seldbg[64 + threadIdx.x] = (int) __half_as_ushort(s.wt[threadIdx.x]);+ if (vm & V_TDOWN) touch_down<S>(p, s, sink);+ if constexpr (INL) ph_gateup9<S, ABL>(p, s); else mf7::ph_gateup7<S, 0>(p, s);+ mf7::gbar7<TM>(p, phase);+ if constexpr (INL) ph_down9<S, ABL>(p, s); else mf7::ph_down7<S, 0>(p, s);+ mf7::gbar7<TM>(p, phase);+ if constexpr (INL) ph_combine9<S>(p, s); else ph_combine<S>(p, s);+ asm volatile("" :: "v"(sink));+ mf7::st7<TM>(p, 11);+ gfinish(p);+}++template <class S, bool TM, bool INL, int ABL = 0>+__global__ __launch_bounds__(THREADS) void moe_fused9_kernel(Params p, int vm) { body9<S, TM, INL, ABL>(p, vm); }+// two resident blocks per WGP (8 waves per SIMD, <= 192 VGPR): a grid of 2 * WGPs blocks, so a tile list of 880 tiles meets 640 waves (2 rounds) instead of 320 (3 rounds)+template <class S, bool TM, bool INL, int ABL = 0>+__global__ __launch_bounds__(THREADS) __attribute__((amdgpu_num_vgpr(192))) void moe_fused9o_kernel(Params p, int vm) { body9<S, TM, INL, ABL>(p, vm); }++} // namespace mf9+#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_idx.h b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_idx.hnew file mode 100644index 0000000..cc1b96b--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_idx.h@@ -0,0 +1,24 @@+#pragma once+// core9: index plan of the cache "touch" (prefetch by read-only loads) added in exl3_moe_fused9.cuh. Pure C++, shared by the kernel and by the CPU bounds checker (bounds9.cpp).+// A touch reads one dword per lane (global_load_b32 into a sink register, result never used): lane l of chunk c reads the dword at byte c * 2048 + 64 l, so a wave step covers+// 2 KB (every 64-byte granule once). Ranges are multiples of 2048 B for the real shapes (the guard handles any tail).+// The waves of the grid (gw = block * 16 + wave, NW = G * 16) share a range round-robin: wave gw reads chunks gw, gw + NW, ...+#include "exl3_moe_fused7_idx.h"+namespace mf9 {+using namespace mf;+constexpr int TOUCH_CHUNK = 2048; // bytes covered per wave per step+constexpr int TOUCH_LANE = 64; // byte stride between lanes+constexpr int TOUCH_W = 4; // bytes loaded per lane+MF_FN long touch_nch(long bytes) { return (bytes + TOUCH_CHUNK - 1) / TOUCH_CHUNK; }+MF_FN long touch_off(long chunk, int lane) { return chunk * TOUCH_CHUNK + (long) lane * TOUCH_LANE; }+MF_FN bool touch_in(long bytes, long chunk, int lane) { return touch_off(chunk, lane) + TOUCH_W <= bytes; }+// the address a lane loads: its own dword, or byte 0 of the range for a lane past the end (no divergence: every lane of the wave issues the load)+MF_FN long touch_addr(long bytes, long chunk, int lane) { return touch_in(bytes, chunk, lane) ? touch_off(chunk, lane) : 0; }+// byte sizes of the ranges the touches read (the same tensors the kernel already reads in full)+template <class S> MF_FN long upt_bytes() { return (long) Dm<S>::H * Dm<S>::D4 * Dm<S>::LR * 4; }+template <class S> MF_FN long router_bytes() { return (long) Dm<S>::NEXP * Dm<S>::D * 2; }+template <class S> MF_FN long sh_gu_bytes() { return 4L * mat_words(Dm<S>::SB, Dm<S>::KSG, Dm<S>::TPP); }+template <class S> MF_FN long sh_dn_bytes() { return 4L * mat_words(Dm<S>::SB, Dm<S>::KSD, Dm<S>::TPU); }+template <class S> MF_FN long rt_dn_bytes() { return 4L * mat_words(Dm<S>::RB, Dm<S>::KSD, Dm<S>::TPU); }+constexpr int TOUCH_DOWN_CAP = 32; // loads per wave for the down-weight touch (stays under the 63-load vmcnt window)+}diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuhnew file mode 100644index 0000000..769a3e2--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9_inl.cuh@@ -0,0 +1,569 @@+#pragma once+// core9: always-inline copies of the phases that the compiler outlines in the mf7 kernel (router, top-k, gate/up, down). Generated by gen_inl.py from the core7 sources,+// bodies unchanged (only the names and __forceinline__): in the mf7 kernel they were real calls (s_swappc_b64), which cap the caller's register budget (callees ignore it)+// and force the caller to spill across the call.+#include "exl3_moe_fused7.cuh"+#if defined(USE_ROCM) || defined(__HIPCC__)+namespace mf9 {+using namespace mf;+using namespace mf7;+template <class S>+__device__ __forceinline__ void ph_router9(const Params& p, Smem<S>& s)+{+ MF_DIMS+ constexpr int NIT = D / 64, NE = 2;+ static_assert(D % 64 == 0, "router7 shape");+ const int R = p.R, wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ half* mx = s.u.g.A;+ for (int i = threadIdx.x; i < R * D / 8; i += THREADS) ((uint4*) mx)[i] = ((const uint4*) p.mixed)[i];+ __syncthreads();+ for (int eb = wave * p.G + blockIdx.x; eb < NEXP; eb += NE * 16 * p.G)+ {+ uint32_t g[NE][NIT];+ #pragma unroll+ for (int k = 0; k < NE; ++k)+ {+ const int e = eb + k * 16 * p.G;+ const uint32_t* g2 = (const uint32_t*) (p.router + router_row<S>(e < NEXP ? e : eb));+ #pragma unroll+ for (int i = 0; i < NIT; ++i) g[k][i] = g2[lane + 32 * i];+ }+ #pragma unroll+ for (int k = 0; k < NE; ++k)+ {+ const int e = eb + k * 16 * p.G;+ if (e < NEXP)+ {+ float sum[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) sum[r] = 0.0f;+ #pragma unroll+ for (int i = 0; i < NIT; ++i)+ {+ const half2 gg = __builtin_bit_cast(half2, g[k][i]);+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ const half2 hh = ((const half2*) (mx + (size_t) r * D))[lane + 32 * i];+ sum[r] = fmaf(__half2float(__low2half(hh)), __half2float(__low2half(gg)), sum[r]);+ sum[r] = fmaf(__half2float(__high2half(hh)), __half2float(__high2half(gg)), sum[r]);+ }+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ {+ float v = wave_sum_down(sum[r]);+ if (lane == 0 && r < R) p.scores[scores_idx<S>(r, e)] = __float2half_rn(v);+ }+ }+ }+ }+ if (blockIdx.x == p.G - 1 && wave == 15)+ {+ // replay of the engine's add_sigmoid_gate_proj reduction (virtual thread t = lane + 32 j, strided fma chain, tree strides 512..32 as register folds, then 16..1 by shuffles);+ // all sgate loads are issued first, the fma chain order per (row, j) is unchanged+ constexpr int NT3 = (D + 1023) / 1024;+ float sgf[32][NT3];+ #pragma unroll+ for (int j = 0; j < 32; ++j)+ #pragma unroll+ for (int t = 0; t < NT3; ++t)+ {+ const int i = lane + 32 * j + 1024 * t;+ sgf[j][t] = i < D ? __half2float(p.sgate_w[i]) : 0.0f;+ }+ for (int r = 0; r < R; ++r)+ {+ float pt[32];+ #pragma unroll+ for (int j = 0; j < 32; ++j)+ {+ float a = 0.0f;+ #pragma unroll+ for (int t = 0; t < NT3; ++t)+ {+ const int i = lane + 32 * j + 1024 * t;+ if (i < D) a = fmaf(sgf[j][t], __half2float(mx[(size_t) r * D + i]), a);+ }+ pt[j] = a;+ }+ #pragma unroll+ for (int w = 16; w >= 1; w >>= 1)+ {+ #pragma unroll+ for (int j = 0; j < w; ++j) pt[j] += pt[j + w];+ }+ const float v = wave_sum_down(pt[0]);+ if (lane == 0) p.sgl[r] = v;+ }+ }+}++template <class S, bool TM>+__device__ __forceinline__ void ph_finalize9(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, team = threadIdx.x >> 8, tid = threadIdx.x & 255, lane = tid & 31, warp = tid >> 5;+ const int D4 = D / 4;+ constexpr int CH = 32, NI = LR / 32, NTS = (LR * MAXR + 255) / 256;+ static_assert(LR % 32 == 0 && D % CH == 0, "finalize7 shape");+ const int total = DM::FIN_CHUNKS;+ const int rounds = (total + p.G * 2 - 1) / (p.G * 2);+ float* t_s = s.u.h.t[team];+ float* rmr_s = s.u.h.rmr[team];+ const float inv_h = 1.0f / (float) H;+ for (int k = 0; k < rounds; ++k)+ {+ const int cidx = blockIdx.x * 2 + team + k * p.G * 2;+ const bool valid = cidx < total;+ const int c = cidx * (CH / 4) + warp; // the warp's single column quad+ // loads in this order (the wait counter is in order): dots of the scalar prologue (L2), then the int8 up words (DRAM)+ static_assert(H == 4, "float4 dots rows");+ float dsum[4];+ float4 dd[NTS];+ #pragma unroll+ for (int h = 0; h < 4; ++h) dsum[h] = 0.0f;+ if (valid && tid < H * R) { const int r = tid / H, h = tid % H; dsum[0] = p.dots[dots_idx<S>(r, MR, h)]; }+ #pragma unroll+ for (int q = 0; q < NTS; ++q)+ {+ const int idx = tid + 256 * q;+ dd[q] = make_float4(0.f, 0.f, 0.f, 0.f);+ if (valid && idx < LR * R) { const int r = idx / LR, ii = idx % LR; dd[q] = *(const float4*) (p.dots + dots_idx<S>(r, 0, 0) + (size_t) ii * H); }+ }+ uint32_t up[H][NI];+ #pragma unroll+ for (int h = 0; h < H; ++h)+ #pragma unroll+ for (int i = 0; i < NI; ++i)+ up[h][i] = valid ? *(const uint32_t*) (p.upt + upt_u32<S>(h, c, lane + 32 * i) * 4) : 0u;+ if (k == 0) st7<TM>(p, 12);+ if (valid && tid < H * R)+ {+ const int r = tid / H, h = tid % H;+ rmr_s[r * 4 + h] = rsqrtf(dsum[0] / (float) D + p.rms_eps);+ }+ __syncthreads();+ if (k == 0) st7<TM>(p, 13);+ if (valid)+ {+ #pragma unroll+ for (int q = 0; q < NTS; ++q)+ {+ const int idx = tid + 256 * q;+ if (idx < LR * R)+ {+ const int r = idx / LR, ii = idx % LR;+ float v = 0.0f;+ v = fmaf(rmr_s[r * 4 + 0], dd[q].x, v); v = fmaf(rmr_s[r * 4 + 1], dd[q].y, v); v = fmaf(rmr_s[r * 4 + 2], dd[q].z, v); v = fmaf(rmr_s[r * 4 + 3], dd[q].w, v);+ v *= inv_h;+ t_s[r * LR + ii] = v * sigmoidf_(v);+ }+ }+ if (cidx == 0 && tid < H)+ {+ for (int r = 0; r < R; ++r)+ {+ const float* dr = p.dots + dots_idx<S>(r, 0, 0);+ float v = 0.0f;+ #pragma unroll+ for (int h = 0; h < H; ++h) v = fmaf(rmr_s[r * 4 + h], dr[(size_t) (LR + tid) * H + h], v);+ p.post[(size_t) r * H + tid] = 2.0f * sigmoidf_(v * inv_h);+ }+ }+ }+ __syncthreads();+ if (k == 0) st7<TM>(p, 14);+ if (valid)+ {+ float4 g[MAXR][H];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ #pragma unroll+ for (int h = 0; h < H; ++h) g[r][h] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ float4 gsc[H];+ #pragma unroll+ for (int i = 0; i < NI; ++i)+ {+ const int ii = lane + 32 * i;+ float ti[MAXR];+ #pragma unroll+ for (int r = 0; r < MAXR; ++r) ti[r] = r < R ? t_s[r * LR + ii] : 0.0f;+ if (p.gs && (i & 1) == 0) // first 32-rank step of a 64-rank group+ {+ #pragma unroll+ for (int h = 0; h < H; ++h) gsc[h] = *(const float4*) (p.up_scale + upgs_idx<S>(h, c, ii));+ }+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ float u0, u1, u2, u3;+ unpack_s8x4(up[h][i], u0, u1, u2, u3);+ if (p.gs) { u0 = gs_dq(u0, gsc[h].x); u1 = gs_dq(u1, gsc[h].y); u2 = gs_dq(u2, gsc[h].z); u3 = gs_dq(u3, gsc[h].w); }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ g[r][h].x = fmaf(ti[r], u0, g[r][h].x); g[r][h].y = fmaf(ti[r], u1, g[r][h].y);+ g[r][h].z = fmaf(ti[r], u2, g[r][h].z); g[r][h].w = fmaf(ti[r], u3, g[r][h].w);+ }+ }+ }+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ #pragma unroll+ for (int h = 0; h < H; ++h)+ for (int o = 16; o > 0; o >>= 1)+ {+ g[r][h].x += __shfl_xor(g[r][h].x, o, 32); g[r][h].y += __shfl_xor(g[r][h].y, o, 32);+ g[r][h].z += __shfl_xor(g[r][h].z, o, 32); g[r][h].w += __shfl_xor(g[r][h].w, o, 32);+ }+ if (lane == 0)+ {+ #pragma unroll+ for (int r = 0; r < MAXR; ++r)+ if (r < R)+ {+ const float4* s4 = (const float4*) (p.xin + xin_row<S>(r, 0));+ float4 o = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ const float4 sc = p.gs ? make_float4(1.0f, 1.0f, 1.0f, 1.0f) : *(const float4*) (p.up_scale + upsc_idx<S>(h, c));+ float4 sv = s4[(size_t) h * D4 + c];+ half4 wq = *(const half4*) (p.w + upsc_idx<S>(h, c));+ float coef = rmr_s[r * 4 + h] * inv_h;+ o.x = fmaf(sigmoidf_(g[r][h].x * sc.x) * coef * __low2float(wq.x), sv.x, o.x);+ o.y = fmaf(sigmoidf_(g[r][h].y * sc.y) * coef * __high2float(wq.x), sv.y, o.y);+ o.z = fmaf(sigmoidf_(g[r][h].z * sc.z) * coef * __low2float(wq.y), sv.z, o.z);+ o.w = fmaf(sigmoidf_(g[r][h].w * sc.w) * coef * __high2float(wq.y), sv.w, o.w);+ }+ half2* out2 = (half2*) (p.mixed + mixed_row<S>(r));+ out2[c * 2] = __floats2half2_rn(o.x, o.y);+ out2[c * 2 + 1] = __floats2half2_rn(o.z, o.w);+ }+ }+ }+ __syncthreads();+ if (k == 0) st7<TM>(p, 15);+ }+}++template <class S>+__device__ __forceinline__ void ph_combine9(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int items = DM::CMB_BLOCKS * R;+ for (int i = blockIdx.x; i < items; i += p.G)+ {+ const int cb = i / R, r = i % R;+ if (wave <= TOPK)+ {+ const int a = r * TOPK + (wave < TOPK ? wave : 0);+ int pp = 0, e = 0;+ const half* const* sv;+ if (wave < TOPK)+ {+ for (int q = 0; q < NA; ++q) if (s.sorted_a[q] == a) { pp = q; break; }+ e = s.sorted_e[pp]; sv = p.svt + 6 * e;+ }+ else { pp = NA + r; sv = p.svt + 6 * NEXP; }+ float4 v = ((const float4*) (p.dn + dn_row<S>(pp) + cb * 128))[lane];+ v = had_regs_f_post(v, sv[5] + cb * 128, lane);+ ((float4*) (s.u.c.rows + wave * 128))[lane] = v;+ }+ __syncthreads();+ if (threadIdx.x < 128)+ {+ const int col = cb * 128 + threadIdx.x, c = threadIdx.x;+ float sum = 0.0f;+ for (int q = 0; q < NA; ++q)+ {+ const int a = s.sorted_a[q];+ if (a / TOPK != r) continue;+ const int slot = a % TOPK;+ const float weighted = __fmul_rn(s.u.c.rows[slot * 128 + c], __half2float(s.wt[a]));+ sum = __fadd_rn(sum, weighted);+ }+ const float syw = 1.0f / (1.0f + __expf(-p.sgl[r]));+ if (!(syw < 1e-8f)) sum += s.u.c.rows[TOPK * 128 + c] * syw;+ p.ydbg[(size_t) r * D + col] = sum;+ #pragma unroll+ for (int h = 0; h < H; ++h)+ {+ const float po = p.post[r * H + h];+ const float xv = p.xin[xout_idx<S>(r, h, col)];+ float o = po * sum;+ o += xv;+ p.xout[xout_idx<S>(r, h, col)] = o;+ }+ }+ __syncthreads();+ }+}++// ballot top-k (variant bit V_TK2). The 10 serial argmax ranks of the plain selection (10 x 5 cross-lane butterfly steps) become one+// bit descent over a unique 25-bit key (ordered fp16 score << 9 | 511 - expert): the 10th largest key needs 25 rounds of 16 ballot popcounts and+// no cross-lane data movement; the 10 selected keys are then ranked through the wave's own scratch. Same total order as the plain loop (score+// descending, expert ascending; NaN and -inf the lowest class, -0 == +0), same rank order, same float values for gmax / ek.+constexpr int V_TK2 = 0x1000;+__device__ __forceinline__ uint32_t tk2_key(const half h, const int idx)+{+ uint32_t u = __half_as_ushort(h);+ uint32_t k;+ if ((u & 0x7fffu) > 0x7c00u || u == 0xfc00u) k = 0u; // NaN or -inf: lowest class+ else { if ((u & 0x7fffu) == 0u) u = 0u; k = (u & 0x8000u) ? ((~u) & 0xffffu) : (u | 0x8000u); }+ return (k << 9) | (uint32_t) (511 - idx);+}+__device__ __forceinline__ float tk2_value(const uint32_t ukey)+{+ const uint32_t k = ukey >> 9;+ if (k == 0u) return -__FLT_MAX__;+ const uint32_t u = (k & 0x8000u) ? (k & 0x7fffu) : ((~k) & 0xffffu);+ return __half2float(__ushort_as_half((unsigned short) u));+}++template <class S>+__device__ __forceinline__ void ph_topk9(const Params& p, Smem<S>& s, int vm = 0)+{+ MF_DIMS+ constexpr int KEYS = DM::KEYS;+ const int R = p.R, wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ constexpr bool TK2_OK = NEXP == 512 && KEYS == 16 && TOPK <= 16; // other shapes (test shapes) keep the plain selection+ if (TK2_OK && (vm & V_TK2) && wave < R)+ {+ uint32_t uk[KEYS];+ #pragma unroll+ for (int i = 0; i < KEYS; ++i) uk[i] = tk2_key(p.scores[scores_idx<S>(wave, i * 32 + lane)], i * 32 + lane);+ uint32_t thr = 0;+ #pragma unroll 1+ for (int b = 24; b >= 0; --b)+ {+ const uint32_t cand = thr | (1u << b);+ int cnt = 0;+ #pragma unroll+ for (int i = 0; i < KEYS; ++i) cnt += __builtin_popcount(__builtin_amdgcn_ballot_w32(uk[i] >= cand));+ if (cnt >= TOPK) thr = cand;+ }+ volatile int* cmp = (volatile int*) &s.sorted_a[wave * TOPK]; // compacted selected keys (scratch, rewritten by the tail below)+ volatile int* ord = (volatile int*) &s.tok[wave * TOPK]; // keys in rank order+ int base = 0;+ #pragma unroll+ for (int i = 0; i < KEYS; ++i)+ {+ const bool sel = uk[i] >= thr;+ const unsigned m = __builtin_amdgcn_ballot_w32(sel);+ if (sel) cmp[base + __builtin_popcount(m & ((1u << lane) - 1u))] = (int) uk[i];+ base += __builtin_popcount(m);+ }+ __builtin_amdgcn_wave_barrier();+ int myk = 0, rk = 0;+ if (lane < TOPK)+ {+ myk = cmp[lane];+ #pragma unroll+ for (int j = 0; j < TOPK; ++j) rk += (cmp[j] > myk);+ ord[rk] = myk;+ }+ __builtin_amdgcn_wave_barrier();+ const uint32_t k0 = (uint32_t) ord[0];+ const uint32_t kr = lane < TOPK ? (uint32_t) ord[lane] : 0u;+ const float gmax = tk2_value(k0);+ const float bk = tk2_value(kr);+ const float ek = (bk == gmax) ? 1.0f : expf(bk - gmax);+ const int myidx = clamp_expert(511 - (int) (kr & 511u), NEXP);+ const float e = lane < TOPK ? ek : 0.0f;+ const float sum = wave_sum_down(e) + 1.0e-20f;+ if (lane < TOPK)+ {+ s.sel[wave * TOPK + lane] = myidx;+ s.wt[wave * TOPK + lane] = __float2half_rn(e / sum);+ }+ }+ else if (wave < R)+ {+ float key[KEYS];+ #pragma unroll+ for (int i = 0; i < KEYS; ++i)+ {+ // NaN and -inf scores become the lowest finite key: they stay selectable (lowest index first), so a row always picks TOPK distinct+ // experts and a group never holds more than R rows (the A staging buffers hold MAXR rows)+ const float kv = __half2float(p.scores[scores_idx<S>(wave, i * 32 + lane)]);+ key[i] = (kv > -__FLT_MAX__) ? kv : -__FLT_MAX__;+ }+ float gmax = 0.0f, ek = 0.0f;+ int myidx = 0;+ #pragma unroll+ for (int rank = 0; rank < TOPK; ++rank)+ {+ float bk = -INFINITY; int bi = 0x7fffffff;+ #pragma unroll+ for (int i = 0; i < KEYS; ++i)+ if (key[i] > bk) { bk = key[i]; bi = i * 32 + lane; }+ #pragma unroll+ for (int o = 16; o > 0; o >>= 1)+ {+ float ok = __shfl_xor(bk, o, 32); int oi = __shfl_xor(bi, o, 32);+ if (ok > bk || (ok == bk && oi < bi)) { bk = ok; bi = oi; }+ }+ if (rank == 0) gmax = bk;+ if (lane == rank) { ek = (bk == gmax) ? 1.0f : expf(bk - gmax); myidx = clamp_expert(bi, NEXP); }+ #pragma unroll+ for (int i = 0; i < KEYS; ++i)+ if (i * 32 + lane == bi) key[i] = -INFINITY;+ }+ const float e = lane < TOPK ? ek : 0.0f;+ const float sum = wave_sum_down(e) + 1.0e-20f;+ if (lane < TOPK)+ {+ s.sel[wave * TOPK + lane] = myidx;+ s.wt[wave * TOPK + lane] = __float2half_rn(e / sum);+ }+ }+ __syncthreads();+ const int NA = R * TOPK;+ if (threadIdx.x < NA)+ {+ const int a = threadIdx.x, e = s.sel[a];+ int pp = 0;+ for (int b = 0; b < NA; ++b) { const int eb = s.sel[b]; pp += (eb < e) || (eb == e && b < a); }+ s.sorted_e[pp] = e; s.sorted_a[pp] = a; s.tok[pp] = a / TOPK;+ }+ __syncthreads();+ if (threadIdx.x < NA) s.head[threadIdx.x] = (threadIdx.x == 0 || s.sorted_e[threadIdx.x - 1] != s.sorted_e[threadIdx.x]) ? 1 : 0;+ __syncthreads();+ if (threadIdx.x == 0)+ {+ int g = 0;+ for (int q = 0; q < NA; ++q) if (s.head[q]) s.gstart[g++] = q;+ s.gstart[g] = NA; s.ngroups = g;+ for (int u = 0; u < g; ++u) s.urows[u] = min(s.gstart[u + 1] - s.gstart[u], MAXR);+ s.urows[g] = R; // the shared expert: R rows+ }+ __syncthreads();+}++template <class S, int ABL>+__device__ __forceinline__ void ph_gateup9(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK, NAR = NA + R;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int NU = s.ngroups + 1;+ constexpr int TPP = DM::TPP;+ const bool nat = p.native != 0;+ const long long W = split_total(s.urows, NU, 2, TPP);+ const int lo = split_tile(s.urows, NU, 2, TPP, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 2, TPP, (long long) (blockIdx.x + 1) * W / p.G);+ int i = lo;+ while (i < hi)+ {+ const int segA = i / TPP, endA = min(hi, (segA + 1) * TPP);+ const int iB = endA, segB = iB / TPP;+ const bool hasB = iB < hi;+ const int endB = hasB ? min(hi, (segB + 1) * TPP) : iB;+ const int nA = endA - i, nB = endB - iB;+ __syncthreads();+ for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)+ {+ const int seg = w2 ? segB : segA;+ const Seg g = seginfo<S>(p, s, seg, true);+ half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;+ const half* suh = g.sv[g.proj == 0 ? 0 : 2];+ for (int task = wave; task < g.rows * DM::CMB_BLOCKS; task += 16)+ {+ const int row = task / DM::CMB_BLOCKS, blk = task % DM::CMB_BLOCKS;+ const int token = g.shared ? row : s.tok[g.p0 + row];+ half4 v = ((const half4*) (p.mixed + mixed_row<S>(token) + blk * 128))[lane];+ v = had_regs_h<true, false>(v, suh + blk * 128, lane);+ ((half4*) (Abuf + a_row_gu<S>(row, blk)))[lane] = v;+ }+ }+ __syncthreads();+ for (int n = wave; n < nA + nB; n += 16)+ {+ const bool inB = n >= nA;+ const int seg = inB ? segB : segA;+ const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPP;+ const Seg g = seginfo<S>(p, s, seg, true);+ const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);+ half* C = p.gu + gu_out<S>(g.proj, NAR, g.p0);+ const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + g.proj];+ if (g.shared)+ mf7_tile_rows<DM::SB, false, DM::KSG, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSG, TPP, tile), tile_ss(nat, DM::SB, TPP), C, INTER, tile, s.u.g.red, wave, lane);+ else+ mf7_tile_rows<DM::RB, false, DM::KSG, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSG, TPP, tile), tile_ss(nat, DM::RB, TPP), C, INTER, tile, s.u.g.red, wave, lane);+ }+ i = endB;+ }+}++template <class S, int ABL>+__device__ __forceinline__ void ph_down9(const Params& p, Smem<S>& s)+{+ MF_DIMS+ const int R = p.R, NA = R * TOPK, NAR = NA + R;+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int NU = s.ngroups + 1;+ constexpr int TPU = DM::TPU;+ const bool nat = p.native != 0;+ const long long W = split_total(s.urows, NU, 1, TPU);+ const int lo = split_tile(s.urows, NU, 1, TPU, (long long) blockIdx.x * W / p.G), hi = split_tile(s.urows, NU, 1, TPU, (long long) (blockIdx.x + 1) * W / p.G);+ int i = lo;+ while (i < hi)+ {+ const int segA = i / TPU, endA = min(hi, (segA + 1) * TPU);+ const int iB = endA, segB = iB / TPU;+ const bool hasB = iB < hi;+ const int endB = hasB ? min(hi, (segB + 1) * TPU) : iB;+ const int nA = endA - i, nB = endB - iB;+ __syncthreads();+ for (int w2 = 0; w2 < (hasB ? 2 : 1); ++w2)+ {+ const Seg g = seginfo<S>(p, s, w2 ? segB : segA, false);+ half* Abuf = w2 ? s.u.g.A2 : s.u.g.A;+ const half* const* sv = g.sv;+ for (int task = wave; task < g.rows * DM::INT_BLOCKS; task += 16)+ {+ const int row = task / DM::INT_BLOCKS, blk = task % DM::INT_BLOCKS;+ half4 gg = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 0)))[lane];+ half4 uu = ((const half4*) (p.gu + gu_read<S>(NAR, g.p0 + row, blk, 1)))[lane];+ gg = had_regs_h<false, true>(gg, sv[1] + blk * 128, lane);+ uu = had_regs_h<false, true>(uu, sv[3] + blk * 128, lane);+ half4 a;+ {+ float f0 = __half2float(__low2half(gg.x)), f1 = __half2float(__high2half(gg.x));+ float f2 = __half2float(__low2half(gg.y)), f3 = __half2float(__high2half(gg.y));+ half h0 = __float2half_rn(f0 / (1.0f + expf(-f0))), h1 = __float2half_rn(f1 / (1.0f + expf(-f1)));+ half h2 = __float2half_rn(f2 / (1.0f + expf(-f2))), h3 = __float2half_rn(f3 / (1.0f + expf(-f3)));+ a.x = __halves2half2(__hmul(h0, __low2half(uu.x)), __hmul(h1, __high2half(uu.x)));+ a.y = __halves2half2(__hmul(h2, __low2half(uu.y)), __hmul(h3, __high2half(uu.y)));+ }+ a = had_regs_h<true, false>(a, sv[4] + blk * 128, lane);+ ((half4*) (Abuf + a_row_dn<S>(row, blk)))[lane] = a;+ }+ }+ __syncthreads();+ for (int n = wave; n < nA + nB; n += 16)+ {+ const bool inB = n >= nA;+ const int seg = inB ? segB : segA;+ const int tile = (inB ? iB + (n - nA) : i + n) - seg * TPU;+ const Seg g = seginfo<S>(p, s, seg, false);+ const uint32_t* Ab = (const uint32_t*) (inB ? s.u.g.A2 : s.u.g.A);+ float* C = p.dn + dn_row<S>(g.p0);+ const uint32_t* Wm = p.wt[3 * (g.shared ? DM::NEXP : g.e) + 2];+ if (g.shared)+ mf7_tile_rows<DM::SB, true, DM::KSD, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::SB, DM::KSD, TPU, tile), tile_ss(nat, DM::SB, TPU), C, D, tile, s.u.g.red, wave, lane);+ else+ mf7_tile_rows<DM::RB, true, DM::KSD, ABL>(g.rows, Ab, Wm + tile_off(nat, DM::RB, DM::KSD, TPU, tile), tile_ss(nat, DM::RB, TPU), C, D, tile, s.u.g.red, wave, lane);+ }+ i = endB;+ }+}++} // namespace mf9+#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused_api.h b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_api.hnew file mode 100644index 0000000..6559b60--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_api.h@@ -0,0 +1,19 @@+#pragma once+// Entry points of the fused MoE half-layer (EXL3_MOE_FUSED), ROCm only. Implemented in exl3_moe_fused.cu (own translation unit since core5).+#include <ATen/ATen.h>+#include <vector>+#include <cstdint>+bool exl3_moe_fused_supported(int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB);+std::vector<int64_t> exl3_moe_fused_ws_offsets(int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB);+int64_t exl3_moe_fused_grid(int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB);+// wt: int64 [3 * (NEXP + 1)] device pointers of the gate/up/down trellis matrices (unit NEXP = shared expert); svt: int64 [6 * (NEXP + 1)] device pointers of+// gsuh gsvh usuh usvh dsuh dsvh. native = 1: engine trellis layout, 0: repacked layout (exl3_moe_fused_idx.h).+void exl3_moe_fused_half+(+ at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, const at::Tensor& upt, const at::Tensor& up_scale, const at::Tensor& w_h,+ const at::Tensor& router, const at::Tensor& sgate, const at::Tensor& wt, const at::Tensor& svt,+ at::Tensor& ws, double rms_eps, int64_t native, int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB+);+// test entry: C = matvec(A, B) with the fused kernel's tile body. A half [R, K] (Hadamard domain), B int16 trellis [K/16, N/16, 16 bits] (native) or the repacked+// layout of the same matrix, C half or float [R, N]. R 1..4; (bits, K) from a fixed table (see exl3_moe_fused.cu).+void exl3_moe_fused_tile_test(const at::Tensor& A, const at::Tensor& B, at::Tensor& C, int64_t bits, int64_t native);diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.hnew file mode 100644index 0000000..4fdd60c--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h@@ -0,0 +1,179 @@+#pragma once+// Plan constants and index arithmetic of the fused MoE half-layer (EXL3_MOE_FUSED). Pure C++: shared by the kernel+// (exl3_moe_fused.cuh) and by the CPU bounds checker (tests/moe_fused/moe_fused_bounds.cpp). Every global-memory and LDS index the kernel+// computes in a phase goes through these helpers.+//+// Pack format (repacked at load, `moe_fused.py`): one 32-column group = 2 adjacent 16-column tiles of the engine's trellis, k-slice major:+// u32 index in the group = kslice * (2 * 8 * bits) + tt * (8 * bits) + word, tt = tile & 1, bits = K of the projection (2, 3, 4).+// A group holds KS = K_dim/16 k-slices. Per expert: [gate groups INTER/32][up groups INTER/32][down groups D/32].+// Experts are indexed by expert id; the shared expert has the same layout with its own bits (SB) and its own base pointer.+// Since core5 the kernel reaches every projection matrix through a pointer table (p.wt[3 * unit + proj]) and a layout flag:+// native (the engine's own trellis tensor (K/16, N/16, 16*bits) int16, no copy): tile t, k-slice s at u32 (s * NT + t) * tw, stride between k-slices NT * tw+// repack (core4 layout above, one repacked copy): tile t at (t / 2) * KS * 2 * tw + (t & 1) * tw, stride between k-slices 2 * tw+// tw = 8 * bits u32 per tile. A lane's words are own = bits * g8 (bits words) and the wrap word.+#if defined(__HIPCC__) || defined(__CUDACC__)+#define MF_FN constexpr __host__ __device__ __forceinline__+#else+#define MF_FN constexpr inline+#endif+namespace mf {++constexpr int MAXR = 4; // rows per launch (R = 1..4)+constexpr int THREADS = 512; // 16 waves of 32++// A shape is a struct with static constexpr: D hidden, H hyper-connection streams, LR hc rank, NEXP experts, TOPK, INTER expert width,+// RB routed expert bits, SB shared expert bits.+struct QwenShape { static constexpr int D = 2560, H = 4, LR = 320, NEXP = 512, TOPK = 10, INTER = 640, RB = 2, SB = 4; };+// small synthetic shape for the first GPU run (random weights, canary-checked): same code, 2 K2 / K4 mixes, 64 experts+struct SmallTestShape { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 2, SB = 4; };++// K3 synthetic shape (routed and shared experts 3 bit) for the whole-kernel K3 run+struct SmallK3Shape { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 3, SB = 3; };++// the Qwen 3.8 Flash shape with the routed / shared bit widths of our packs (routed K3 / K4, shared K4 / K5), and small twins for the GPU parity run+struct QwenK3S4 { static constexpr int D = 2560, H = 4, LR = 320, NEXP = 512, TOPK = 10, INTER = 640, RB = 3, SB = 4; };+struct QwenK3S5 { static constexpr int D = 2560, H = 4, LR = 320, NEXP = 512, TOPK = 10, INTER = 640, RB = 3, SB = 5; };+struct QwenK4S4 { static constexpr int D = 2560, H = 4, LR = 320, NEXP = 512, TOPK = 10, INTER = 640, RB = 4, SB = 4; };+struct QwenK4S5 { static constexpr int D = 2560, H = 4, LR = 320, NEXP = 512, TOPK = 10, INTER = 640, RB = 4, SB = 5; };+struct SmallK3S4 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 3, SB = 4; };+struct SmallK3S5 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 3, SB = 5; };+struct SmallK4S4 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 4, SB = 4; };+struct SmallK4S5 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 4, SB = 5; };++template <class S>+struct Dm+{+ static constexpr int D = S::D, H = S::H, LR = S::LR, NEXP = S::NEXP, TOPK = S::TOPK, INTER = S::INTER, RB = S::RB, SB = S::SB;+ static constexpr int MR = LR + H; // hc projection rows (rank + H gates)+ static constexpr int D4 = D / 4;+ static constexpr int KSG = D / 16; // k-slices of gate/up (K dim = D)+ static constexpr int KSD = INTER / 16; // k-slices of down (K dim = INTER)+ static constexpr int NGU = INTER / 32; // 32-column groups per gate or up projection+ static constexpr int NGD = D / 32; // groups of down+ static constexpr int TPP = INTER / 16; // tiles per (unit, proj) of gate/up+ static constexpr int TPU = D / 16; // tiles per unit of down+ static constexpr int GU_GRP = KSG * 16 * RB; // u32 per gate/up group, routed+ static constexpr int DN_GRP = KSD * 16 * RB;+ static constexpr int SH_GU_GRP = KSG * 16 * SB; // shared+ static constexpr int SH_DN_GRP = KSD * 16 * SB;+ static constexpr long EXPERT_U32 = 2L * NGU * GU_GRP + (long) NGD * DN_GRP;+ static constexpr long SHARED_U32 = 2L * NGU * SH_GU_GRP + (long) NGD * SH_DN_GRP;+ static constexpr int SV_STRIDE = 3 * (D + INTER); // halves per expert: gsuh gsvh usuh usvh dsuh dsvh+ static constexpr int SV_GSUH = 0, SV_GSVH = D, SV_USUH = D + INTER, SV_USVH = 2 * D + INTER, SV_DSUH = 2 * D + 2 * INTER, SV_DSVH = 2 * D + 3 * INTER;+ static constexpr int CMB_BLOCKS = D / 128; // 128-column blocks of the combine / A prep+ static constexpr int INT_BLOCKS = INTER / 128;+ static constexpr int FIN_CHUNKS = D / 32; // finalize chunk_cols = 32+ static constexpr int KEYS = NEXP / 32; // top-k keys per lane++ static_assert(D % 128 == 0 && INTER % 128 == 0, "128-wide Hadamard blocks");+ static_assert(INTER % 32 == 0 && D % 32 == 0, "32-column groups");+ static_assert(NEXP % 32 == 0 && NEXP <= 1024, "top-k lanes");+ static_assert(TOPK >= 1 && TOPK <= 15, "combine uses wave <= TOPK, 16 waves");+ static_assert(MAXR * TOPK <= THREADS && MAXR * TOPK <= 40, "sort/group arrays");+ static_assert((RB >= 2 && RB <= 5) && (SB >= 2 && SB <= 5), "K2, K3, K4, K5");+ static_assert(H >= 1 && H <= 4, "dred/rmr scratch");+ static_assert(LR % 1 == 0 && LR <= 1024, "t scratch");+ // dynamic-free LDS: A + A2 for MAXR rows of the larger of D / INTER+ static constexpr int LDS_A_HALVES = 2 * MAXR * D;+};++// ---- load-time plan checks that do not depend on the kernel+MF_FN long expert_base(long expert_u32, int e) { return (long) e * expert_u32; }+// group base (u32 offset in an expert region) for gate/up: proj in {0,1}, group gi in [0, NGU)+template <class S> MF_FN long gu_group(int proj, int gi) { return ((long) proj * Dm<S>::NGU + gi) * Dm<S>::GU_GRP; }+template <class S> MF_FN long dn_group(int gi) { return 2L * Dm<S>::NGU * Dm<S>::GU_GRP + (long) gi * Dm<S>::DN_GRP; }+template <class S> MF_FN long sh_gu_group(int proj, int gi) { return ((long) proj * Dm<S>::NGU + gi) * Dm<S>::SH_GU_GRP; }+template <class S> MF_FN long sh_dn_group(int gi) { return 2L * Dm<S>::NGU * Dm<S>::SH_GU_GRP + (long) gi * Dm<S>::SH_DN_GRP; }++// ---- tile-level indices (same arithmetic as the engine's native layout with ntiles = 2, base at the group)+MF_FN int tw(int bits) { return 8 * bits; }+MF_FN int chunk(int ks) { return (ks + 15) / 16; }+MF_FN int myn(int ks, int c) { int ch = chunk(ks); int r = ks - c * ch; r = r < ch ? r : ch; return r > 0 ? r : 0; }+// u32 offset of tile `tile` (k-slice 0) from the matrix base, and u32 stride between two k-slices of that tile; ks = K/16, nt = N/16+MF_FN long tile_off(bool nat, int bits, int ks, int nt, int tile) { return nat ? (long) tile * tw(bits) : (long) (tile >> 1) * ks * 2 * tw(bits) + (long) (tile & 1) * tw(bits); }+MF_FN long tile_ss(bool nat, int bits, int nt) { return nat ? (long) nt * tw(bits) : 2L * tw(bits); }+MF_FN long mat_words(int bits, int ks, int nt) { return (long) ks * nt * tw(bits); }+// a lane's own words (bits of them, from g8) and its wrap word (the word before them, cyclic over the tile: any tw, K3 has tw = 24), relative to the tile base+// K5: lane (g8, t) is the engine's lane L = 4 g8 + t. Its two 4-value groups g (values 4g .. 4g + 3, engine dq4<5>) start at bit+// (8L + 4g + 257) * 5 - 16 = 160 g8 + 40 t + 20 g - 11 (mod 1280); relative to the first bit of the lane set's wrap word (global word 5 g8 - 1, cyclic) that is+// 40 t + 20 g + 21. Both words of the funnel shift are local indices 0..5 of {wrap, own0 .. own4}.+MF_FN int k5_rel(int t, int g) { return 40 * t + 20 * g + 21; }+MF_FN int k5_i0(int t, int g) { return k5_rel(t, g) / 32; }+MF_FN int k5_i2(int t, int g) { return (k5_rel(t, g) + 30) / 32; }+MF_FN int k5_s2(int t, int g) { return (k5_i2(t, g) + 1) * 32 - (k5_rel(t, g) + 31); }+MF_FN long own_i(int bits, int g8, int s, long ss) { return s * ss + (long) bits * g8; }+MF_FN long wrp_i(int bits, int g8, int s, long ss) { return s * ss + (bits * g8 > 0 ? bits * g8 - 1 : tw(bits) - 1); }+MF_FN long a_idx(int r, int k, int s) { return (long) r * (k / 2) + 8 * s; } // u32 in the A staging buffer+MF_FN int red_idx(int wave, int cq, int col, int row) { return ((wave * 4 + cq) * 16 + col) * 4 + row; }+constexpr int RED_SIZE = 16 * 4 * 16 * 4; // floats+MF_FN long c_idx(int row, int n, int tile, int col16) { return (long) row * n + (long) tile * 16 + col16; }++// ---- phase indices (elements of the stated type)+// HC dots: fn int8 [MR][H][D], xin f32 [R][H][D], dots f32 [R][MR+1][H]+template <class S> MF_FN long fn_row(int j, int h) { return ((long) j * Dm<S>::H + h) * Dm<S>::D; }+template <class S> MF_FN long xin_row(int r, int h) { return ((long) r * Dm<S>::H + h) * Dm<S>::D; }+template <class S> MF_FN long dots_idx(int r, int j, int h) { return ((long) r * (Dm<S>::MR + 1) + j) * Dm<S>::H + h; }+// finalize: upt int8 [H][D4][LR][4] read as u32 at ((h*D4 + c) * LR + ii)+template <class S> MF_FN long upt_u32(int h, int c, int ii) { return ((long) h * Dm<S>::D4 + c) * Dm<S>::LR + ii; }+template <class S> MF_FN long upsc_idx(int h, int c) { return (long) h * Dm<S>::D + 4L * c; } // up_scale f32 / w_h half, 4 wide+// group scales (EXL3_GR_GS): the int8 codes keep their layout; the per-row scale vectors are replaced by group scales, and a kernel+// is in group mode when fn_scale.numel() != MR (host sets Params::gs). Weight = half(code * scale) as fp32, accumulated in the old order.+// fn: groups of GS_FN = 128 consecutive k over the flattened (h, d) axis; fn_gs f32 [MR][H * D / 128]; c = 8-element block (int2 load index)+// up: groups of GS_UP = 64 consecutive ranks per output column; up_gs f32 [H][D4][ceil(LR / 64)][4] (4 = the column quad)+constexpr int GS_FN = 128, GS_UP = 64;+template <class S> MF_FN bool gs_ok() { return S::D % GS_FN == 0; }+template <class S> MF_FN long fn_scale_n(bool gs) { return gs ? (long) Dm<S>::MR * (S::H * S::D / GS_FN) : (long) Dm<S>::MR; }+template <class S> MF_FN long up_scale_n(bool gs) { return gs ? (long) S::H * S::D * ((S::LR + GS_UP - 1) / GS_UP) : (long) S::H * S::D; }+template <class S> MF_FN long fngs_idx(int j, int h, int c8) { return (long) j * (Dm<S>::H * Dm<S>::D / GS_FN) + (long) h * (Dm<S>::D / GS_FN) + (c8 >> 4); }+template <class S> MF_FN long upgs_idx(int h, int c, int ii) { return (((long) h * Dm<S>::D4 + c) * ((Dm<S>::LR + GS_UP - 1) / GS_UP) + (ii >> 6)) * 4; }+// router+template <class S> MF_FN long router_row(int e) { return (long) e * Dm<S>::D; }+template <class S> MF_FN long scores_idx(int r, int e) { return (long) r * Dm<S>::NEXP + e; }+template <class S> MF_FN long mixed_row(int r) { return (long) r * Dm<S>::D; }+// gate/up output (half): [proj][NAR][INTER]; down output (f32) [NAR][D]+template <class S> MF_FN long gu_out(int proj, int nar, int row0) { return ((long) proj * nar + row0) * Dm<S>::INTER; }+template <class S> MF_FN long gu_read(int nar, int row, int blk, int which) { return ((long) which * nar + row) * Dm<S>::INTER + (long) blk * 128; }+template <class S> MF_FN long dn_row(int row) { return (long) row * Dm<S>::D; }+// A staging buffers (half): row-major, K halves per row+template <class S> MF_FN long a_row_gu(int row, int blk) { return (long) row * Dm<S>::D + blk * 128; }+template <class S> MF_FN long a_row_dn(int row, int blk) { return (long) row * Dm<S>::INTER + blk * 128; }+// combine+template <class S> MF_FN long xout_idx(int r, int h, int col) { return ((long) r * Dm<S>::H + h) * Dm<S>::D + col; }++// ---- debug buffer (seldbg, int32): [0, 40) selected experts, [64, 104) weights, [STAMP_BASE, ...) per-block phase time stamps (MF_TIMING builds)+constexpr int SELDBG_INTS = 1024;+constexpr int STAMP_BASE = 256, STAMP_STRIDE = 16, STAMP_SLOTS = 12, STAMP_MAXB = 40;+MF_FN int stamp_idx(int bx, int k) { return STAMP_BASE + bx * STAMP_STRIDE + k; }++// ---- top-k expert id sanitising: an id outside [0, NEXP) (all-NaN scores leave the sentinel) becomes 0, never a wild pointer+MF_FN int clamp_expert(int e, int nexp) { return (e >= 0 && e < nexp) ? e : 0; }++// ---- task decomposition+// ---- cost-weighted split of the gate/up and down tile lists: a tile of a segment whose group has `rows` rows costs seg_weight(rows) (3.5 VALU+// instructions per weight to decode + 0.5 per row), so the shared expert (R rows) and multi-row groups get fewer tiles per block.+// urows[u] = rows of unit u (the shared expert is the last unit); nu units x pu projections (2 gate/up, 1 down), tp tiles per segment, segments unit-major.+MF_FN int seg_weight(int rows) { return 7 + rows; }+MF_FN long long split_total(const int* urows, int nu, int pu, int tp)+{+ long long w = 0;+ for (int u = 0; u < nu; ++u) w += (long long) pu * tp * seg_weight(urows[u]);+ return w;+}+// first tile index whose exclusive weight prefix is >= x, x in [0, W]; split_tile(0) = 0, split_tile(W) = nu * pu * tp. Block b owns [split(b W / G), split((b + 1) W / G)).+MF_FN int split_tile(const int* urows, int nu, int pu, int tp, long long x)+{+ long long acc = 0;+ for (int u = 0; u < nu; ++u)+ {+ const long long w = seg_weight(urows[u]), segw = w * tp;+ for (int pj = 0; pj < pu; ++pj)+ {+ if (x < acc + segw) { const long long t = (x - acc + w - 1) / w; return (u * pu + pj) * tp + (int) t; }+ acc += segw;+ }+ }+ return nu * pu * tp;+}+MF_FN int blk_lo(int bx, int total, int G) { return (int) ((long long) bx * total / G); }+MF_FN int blk_hi(int bx, int total, int G) { return (int) ((long long) (bx + 1) * total / G); }+}diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cuindex 3294e6d..d25f4d3 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu@@ -288,6 +288,123 @@ void mpw_reduce_had_kernel((float4*) (output + row * width + blk * 128))[t] = sum;}+// ---------------------------------------------------------------------------------------------+// Glue v2 (EXL3_MPW_GLUE=1, default off). Same per-element arithmetic as the kernels above, same+// output bytes. Two changes: (1) the top_k index chain (inverse_order -> selected -> table pointer+// -> data) is fetched ONCE per wave, lane k holding pick k, and broadcast with shuffles, instead of+// a serial dependent load chain per pick; (2) the picks are unrolled so loads of different picks+// are in flight together. Gather also serves gate and up from one wave (shares the A row and the+// index chain). Needs top_k <= 32 (host check) and projections == 2.+#define MPW_GLUE_TK_MAX 32++__device__ __forceinline__ int64_t mpw_bcast64(int64_t v, int k)+{+ const int lo = __shfl((int) (uint32_t) v, k, 32);+ const int hi = __shfl((int) (uint32_t) ((uint64_t) v >> 32), k, 32);+ return (int64_t) (((uint64_t) (uint32_t) hi << 32) | (uint64_t) (uint32_t) lo);+}++__global__ __launch_bounds__(256)+void mpw_gather_had2_kernel+(+ const half* __restrict__ A,+ half* __restrict__ out,+ const int64_t* __restrict__ selected,+ const int64_t* __restrict__ inverse_order,+ const int64_t* __restrict__ suh_0,+ const int64_t* __restrict__ suh_1,+ int assignments,+ int top_k,+ int width+)+{+ const int blocks = width / 128;+ const int rows = assignments / top_k;+ const int64_t job = (int64_t) blockIdx.x * 8 + (threadIdx.x >> 5);+ if (job >= (int64_t) rows * blocks) return;+ const int t = threadIdx.x & 31;+ const int blk = job % blocks;+ const int64_t r = job / blocks;+ int64_t slot_l = 0, p0_l = 0, p1_l = 0;+ if (t < top_k)+ {+ const int64_t orig = r * top_k + t;+ slot_l = inverse_order[orig];+ const int64_t e = selected[orig];+ p0_l = suh_0[e];+ p1_l = suh_1[e];+ }+ const half4 v0 = ((const half4*) (A + r * width + blk * 128))[t];+ #pragma unroll 5+ for (int k = 0; k < top_k; ++k)+ {+ const int64_t slot = mpw_bcast64(slot_l, k);+ const half* s0 = (const half*) mpw_bcast64(p0_l, k);+ const half* s1 = (const half*) mpw_bcast64(p1_l, k);+ half4 va = v0, vb = v0;+ mpw_had_h(va, s0 + blk * 128, nullptr, t);+ mpw_had_h(vb, s1 + blk * 128, nullptr, t);+ ((half4*) (out + (int64_t) slot * width + blk * 128))[t] = va;+ ((half4*) (out + ((int64_t) assignments + slot) * width + blk * 128))[t] = vb;+ }+}++template <int TK>+__global__ __launch_bounds__(256)+void mpw_reduce_had2_kernel+(+ const float* __restrict__ sorted_rows,+ const int64_t* __restrict__ selected,+ const float* __restrict__ weights,+ const int64_t* __restrict__ inverse_order,+ const int64_t* __restrict__ svh_table,+ float* __restrict__ output,+ int rows,+ int width+)+{+ const int blocks = width / 128;+ const int64_t job = (int64_t) blockIdx.x * 8 + (threadIdx.x >> 5);+ if (job >= (int64_t) rows * blocks) return;+ const int t = threadIdx.x & 31;+ const int blk = job % blocks;+ const int64_t row = job / blocks;+ int64_t slot_l = 0, p_l = 0;+ float w_l = 0.f;+ if (t < TK)+ {+ const int64_t orig = row * TK + t;+ slot_l = inverse_order[orig];+ p_l = svh_table[selected[orig]];+ w_l = weights[orig];+ }+ float4 fv[TK];+ #pragma unroll+ for (int k = 0; k < TK; ++k)+ {+ const int64_t slot = mpw_bcast64(slot_l, k);+ fv[k] = ((const float4*) (sorted_rows + slot * width + blk * 128))[t];+ }+ float4 sum = make_float4(0.f, 0.f, 0.f, 0.f);+ #pragma unroll+ for (int k = 0; k < TK; ++k)+ {+ const float w = __shfl(w_l, k, 32);+ const half* svh = (const half*) mpw_bcast64(p_l, k);+ float v0 = fv[k].x, v1 = fv[k].y, v2 = fv[k].z, v3 = fv[k].w;+ float s0 = v0 + v1, d0 = v0 - v1, s1 = v2 + v3, d1 = v2 - v3;+ float h0 = s0 + s1, h1 = d0 + d1, h2 = s0 - s1, h3 = d0 - d1;+ shuffle_had_f4x32(h0, h1, h2, h3, t);+ const half4 sc = ((const half4*) (svh + blk * 128))[t];+ const float r = mpw::HAD_SCALE * w;+ sum.x += h0 * r * __low2float(sc.x);+ sum.y += h1 * r * __high2float(sc.x);+ sum.z += h2 * r * __low2float(sc.y);+ sum.w += h3 * r * __high2float(sc.y);+ }+ ((float4*) (output + row * width + blk * 128))[t] = sum;+}+// ---------------------------------------------------------------------------------------------// Grouped GEMM: blockIdx.x = 128-column block, blockIdx.y = tile slot, blockIdx.z = projection@@ -327,7 +444,8 @@ void mpw_gemm_kernelvoid* __restrict__ C,int64_t c_proj_stride,int size_k,- int size_n+ int size_n,+ int a_ld // A row pitch in elements (>= size_k); the old mpw kernel needs a_ld == size_k){#if defined(EXL3_HIP_WMMA_GFX115)@@ -582,7 +700,7 @@ void mpw_gemm_kernel}// ----------------------------------------------------------------------------------------------// mpw2 grouped GEMM (MPW_KERN=2, default). Measured on mpw_gemm (gemm_bench): a fixed+// mpw2 grouped GEMM (MPW_KERN=2, default). Measured on mpw_gemm (gemm_bench, HANDOFF step 7): a fixed// per-tile cost of ~7.7 ms per 4096x2048 launch at 8 rows/expert and no overlap of WMMA with the rest.// On gfx1151 WMMA, trellis-decode VALU and permlanes share the SIMD, so time >= WMMA + decode: the decode// alone is ~3 ms per 4096x2048 call (no-decode ablation), paid once per m-tile. mpw2 changes the data flow:@@ -659,7 +777,8 @@ void mpw2_gemm_kernelvoid* __restrict__ C,int64_t c_proj_stride,int size_k,- int size_n+ int size_n,+ int a_ld // A row pitch in elements (>= size_k); the old mpw kernel needs a_ld == size_k){#if defined(EXL3_HIP_WMMA_GFX115)@@ -682,7 +801,7 @@ void mpw2_gemm_kernelconst int rows = (int) min((int64_t) MT, expert_offsets[expert + 1] - row0);const int proj = blockIdx.z;const uint32_t* B32 = (const uint32_t*) (proj ? B_table_1 : B_table_0)[expert];- A += proj * a_proj_stride + row0 * size_k;+ A += proj * a_proj_stride + row0 * a_ld;const int n0 = blockIdx.x * NT;const size_t slice_stride = (size_t) (size_n / 16) * TWORDS;@@ -699,8 +818,12 @@ void mpw2_gemm_kernelconst int a_r = t >> 2; // + i * (THREADS / 4)const int a_c = t & 3; // 16-byte chunk (8 k)- const half* a_src = A + (int64_t) a_r * size_k + a_c * 8;- const uint32_t* w_src = B32 + (size_t) (n0 / 16 + warp * NW) * TWORDS; // NW adjacent tiles: contiguous+ const half* a_src = A + (int64_t) a_r * a_ld + a_c * 8;+ // Tail block (size_n not a multiple of NT): waves past the last n-tile read the last valid NW tiles+ // (duplicate, never stored: the epilogue skips them), so no trellis read leaves the tensor.+ const int ntile_n = size_n / 16;+ const int first_tile = min(n0 / 16 + warp * NW, ntile_n - NW);+ const uint32_t* w_src = B32 + (size_t) first_tile * TWORDS; // NW adjacent tiles: contiguousuint4 ra[PF][ALOADS];uint32_t rw[PF][WL];@@ -712,7 +835,7 @@ void mpw2_gemm_kernel#pragma unrollfor (int i = 0; i < ALOADS; ++i)r[i] = a_r + i * (THREADS / 4) < rows- ? *((const uint4*) (a_src + (int64_t) i * (THREADS / 4) * size_k + k0))+ ? *((const uint4*) (a_src + (int64_t) i * (THREADS / 4) * a_ld + k0)): make_uint4(0, 0, 0, 0);};auto load_w = [&] (int it, uint32_t* r)@@ -805,7 +928,8 @@ void mpw2_gemm_kernelif (i >= nrg) continue;const int r = i * 16 + (lane & 15);HipFp16x16 af;- if constexpr (OPT & 2)+ if constexpr (DBG & 8) af = bf[s * NW]; // bench only: A operand from registers (no LDS read)+ else if constexpr (OPT & 2){((uint4*) &af)[0] = *((const uint4*) (sh_a[cur] + mpw2_a_off(r, s * 2 + (lane >> 4))));((uint4*) &af)[1] = *((const uint4*) (sh_a[cur] + mpw2_a_off(r, s * 2 + ((lane >> 4) ^ 1))));@@ -843,6 +967,12 @@ void mpw2_gemm_kernelload_w(it + PF, rw[ws]);if (it + 1 < iters) store_a((it + 1) & 1, ra[as]);load_a(it + 1 + PF, ra[as]);+ if constexpr (OPT & 256)+ {+ // OPT bit 8: waves whose n-tiles all lie past size_n (tail block) skip decode and WMMA: their+ // results are never stored (the epilogue skips them), so the output is unchanged. Wave-uniform.+ if (n0 + warp * NW * 16 >= size_n) return;+ }HipFp16x16 bf[KS * NW];decode(bf);mma(it & 1, bf);@@ -872,6 +1002,7 @@ void mpw2_gemm_kernel#pragma unrollfor (int j = 0; j < NW; ++j){+ if (n0 + (warp * NW + j) * 16 >= size_n) continue; // tail block: tile past size_n (wave-uniform)const int col = n0 + (warp * NW + j) * 16 + (lane & 15);#pragma unrollfor (int r = 0; r < 8; ++r)@@ -914,7 +1045,8 @@ void mpw2x_gemm_kernelvoid* __restrict__ C,int64_t c_proj_stride,int size_k,- int size_n+ int size_n,+ int a_ld // A row pitch in elements (>= size_k); the old mpw kernel needs a_ld == size_k){#if defined(EXL3_HIP_WMMA_GFX115)@@ -937,7 +1069,7 @@ void mpw2x_gemm_kernelconst int rows = (int) min((int64_t) MT, expert_offsets[expert + 1] - row0);const int proj = blockIdx.z;const uint32_t* B32 = (const uint32_t*) (proj ? B_table_1 : B_table_0)[expert];- A += proj * a_proj_stride + row0 * size_k;+ A += proj * a_proj_stride + row0 * a_ld;const int n0 = blockIdx.x * NT;const size_t slice_stride = (size_t) (size_n / 16) * TWORDS;@@ -954,8 +1086,10 @@ void mpw2x_gemm_kernelconst int a_r = t >> 2; // + i * (THREADS / 4)const int a_c = t & 3; // 16-byte chunk (8 k)- const half* a_src = A + (int64_t) a_r * size_k + a_c * 8;- const uint32_t* w_src = B32 + (size_t) (n0 / 16 + warp * NW) * TWORDS; // NW adjacent tiles: contiguous+ const half* a_src = A + (int64_t) a_r * a_ld + a_c * 8;+ const int ntile_n = size_n / 16; // tail block: clamp like mpw2_gemm_kernel (duplicate, never stored)+ const int first_tile = min(n0 / 16 + warp * NW, ntile_n - NW);+ const uint32_t* w_src = B32 + (size_t) first_tile * TWORDS; // NW adjacent tiles: contiguousuint4 ra[PF][ALOADS];uint32_t rw[PF][WL];@@ -967,7 +1101,7 @@ void mpw2x_gemm_kernel#pragma unrollfor (int i = 0; i < ALOADS; ++i)r[i] = a_r + i * (THREADS / 4) < rows- ? *((const uint4*) (a_src + (int64_t) i * (THREADS / 4) * size_k + k0))+ ? *((const uint4*) (a_src + (int64_t) i * (THREADS / 4) * a_ld + k0)): make_uint4(0, 0, 0, 0);};auto load_w = [&] (int it, uint32_t* r)@@ -1182,6 +1316,7 @@ void mpw2x_gemm_kernel#pragma unrollfor (int j = 0; j < NW; ++j){+ if (n0 + (warp * NW + j) * 16 >= size_n) continue; // tail block: tile past size_n (wave-uniform)const int col = n0 + (warp * NW + j) * 16 + (lane & 15);#pragma unrollfor (int r = 0; r < 8; ++r)@@ -1220,12 +1355,12 @@ inline int mpw_kern(int64_t assignments, int64_t experts)return e ? atoi(e) : 2;}-// MPW_NW (mpw2 only): n-tiles per wave, 2 (default, needs N % 256 == 0, else 1) or 1+// MPW_NW (mpw2 only): n-tiles per wave, 2 (default, needs N % 32 == 0, else 1) or 1inline int mpw_nw(int size_n){const char* e = getenv("MPW_NW");const int nw = e ? atoi(e) : 2;- return (nw == 2 && size_n % 256 == 0) ? 2 : 1;+ return (nw == 2 && size_n % 32 == 0) ? 2 : 1; // NW 2 pairs n-tiles; the tail block is handled in-kernel}inline int mpw_mt(int kern)@@ -1242,10 +1377,12 @@ void launch_gemm_cbfloat K, dim3 grid, hipStream_t stream,const half* A, int64_t a_proj_stride, const int64_t* offsets, const int* tiles,const int* num_tiles, const int64_t* t0, const int64_t* t1, void* C, int64_t c_proj_stride,- int size_k, int size_n, int kern+ int size_k, int size_n, int kern, int a_ld){- #define MPW_ARGS A, a_proj_stride, offsets, tiles, num_tiles, t0, t1, C, c_proj_stride, size_k, size_n+ TORCH_CHECK(a_ld >= size_k && (a_ld * 2) % 16 == 0, "exl3_moe_prefill_wmma: A pitch must be >= K and 16-byte aligned");+ TORCH_CHECK(a_ld == size_k || kern == 2, "exl3_moe_prefill_wmma: padded A pitch needs the mpw2 kernel");+ #define MPW_ARGS A, a_proj_stride, offsets, tiles, num_tiles, t0, t1, C, c_proj_stride, size_k, size_n, a_ldconst char* ldm_env = getenv("MPW_LDM"); // read per launch: A/B harnesses flip it in-processconst int ldm = ldm_env ? atoi(ldm_env) : 1; // LDM=1 default: +3.4% e2e prefill@4K (HANDOFF step 2)const int k2 = (int) (K * 2.0f + 0.5f);@@ -1254,15 +1391,21 @@ void launch_gemm_cb// grid.x arrives for NT = 128; mpw2 blocks span 128 * NW columnsconst int mt = mpw_mt(kern);const int nw = mpw_nw(size_n);- grid.x = size_n / (128 * nw);+ grid.x = CEIL_DIVIDE(size_n, 128 * nw); // last block may be a tail (mpw2_gemm_kernel clamps it)+ TORCH_CHECK(size_n % 16 == 0, "exl3_moe_prefill_wmma: size_n must be a multiple of 16");const char* pf_env = getenv("MPW_PF");const int pf = pf_env ? atoi(pf_env) : 4;const char* dbg_env = getenv("MPW_DBG");const int dbg = dbg_env ? atoi(dbg_env) : 0;+ // The kernel's NW template argument must equal nw: grid.x = size_n / (128 * nw) blocks of 128 * NW+ // columns. NW 2 with nw 1 (size_n % 256 != 0, e.g. Qwen3.8 gate/up N = 640) reads trellis tiles and+ // writes C columns past size_n.#define MPW2_L(b, h, M, P, W, D) \- { mpw2_gemm_kernel<b, h, OUT_FP32, CB, 1, M, P, W, D><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ { TORCH_CHECK((W) == nw, "exl3_moe_prefill_wmma: mpw2 NW ", W, " != grid NW ", nw); \+ mpw2_gemm_kernel<b, h, OUT_FP32, CB, 1, M, P, W, D><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }#define MPW2_V(V, M, P, W) \- { mpw2_gemm_kernel<2, false, OUT_FP32, CB, 1, M, P, W, 0, 2><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ { TORCH_CHECK((W) == nw, "exl3_moe_prefill_wmma: mpw2 NW ", W, " != grid NW ", nw); \+ mpw2_gemm_kernel<2, false, OUT_FP32, CB, 1, M, P, W, 0, 2><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }// EXL3_MPW2X=<OPT> (default 0 = off): mpw2x candidate (K 2, MT 128, NW 2 only), EXL3_MPW2X_PF=2|1.// Read per launch like MPW_LDM (A/B harnesses flip it in-process). Unknown values fall through.{@@ -1278,11 +1421,56 @@ void launch_gemm_cb#undef MPW2X}}- if (k2 == 4)+ // EXL3_PF7_OPT=<opt> (default 0 = off), EXL3_PF7_PF=1..4: production-class MT 128 NW 2 kernel for any K with+ // an explicit OPT mask (bits 0/1 direct LDS fragment reads, bit 2 2-bit mul1 decode, bit 8 tail-wave skip).+ // Bit-exact against OPT 0 / 2: same index arithmetic, same summation order.+ {+ const char* poe = getenv("EXL3_PF7_OPT");+ const int po = poe ? atoi(poe) : 0;+ if (po && nw == 2 && mt == 128)+ {+ const char* ppe = getenv("EXL3_PF7_PF");+ const int pp = ppe ? atoi(ppe) : 2;+ #define PF7O(b, h, O, P) if (po == O && pp == P) \+ { mpw2_gemm_kernel<b, h, OUT_FP32, CB, 1, 128, P, 2, 0, O><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ #define PF7K(b, h) PF7O(b, h, 3, 2) PF7O(b, h, 3, 4) PF7O(b, h, 259, 2) PF7O(b, h, 259, 4) \+ PF7O(b, h, 2, 2) PF7O(b, h, 2, 4) PF7O(b, h, 258, 2) PF7O(b, h, 258, 4) \+ PF7O(b, h, 6, 2) PF7O(b, h, 6, 4) PF7O(b, h, 262, 2) PF7O(b, h, 262, 4)+ switch (k2)+ {+ case 4: PF7K(2, false) break;+ case 5: PF7K(2, true) break;+ case 6: PF7K(3, false) break;+ case 7: PF7K(3, true) break;+ case 8: PF7K(4, false) break;+ default: break;+ }+ #undef PF7K+ #undef PF7O+ }+ }+ // EXL3_PF7_DBG=<1..7> (bench only, default 0): the production K 2 kernel with the DBG ablation bits+ // (1 no decode, 2 no WMMA, 4 no weight loads). Same index arithmetic as DBG 0 (the bits only drop work).+ {+ const char* pde = getenv("EXL3_PF7_DBG");+ const int pd = pde ? atoi(pde) : 0;+ if (pd && k2 == 4 && nw == 2 && mt == 128)+ {+ #define PF7D(D) if (pd == D) \+ { mpw2_gemm_kernel<2, false, OUT_FP32, CB, 1, 128, 2, 2, D, 2><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ PF7D(1) PF7D(2) PF7D(3) PF7D(4) PF7D(5) PF7D(6) PF7D(7) PF7D(8) PF7D(9) PF7D(12) PF7D(13)+ #undef PF7D+ }+ }+ if (k2 == 4 && nw == 2) // variants are NW 2 shapes; nw 1 takes MPW2_K below{switch (mpw_variant()){- case 1: MPW2_V(1, 128, 2, 2)+ case 1:+ // pf7: tail-wave skip (OPT bit 8) when size_n is not a multiple of 256 (Qwen gate/up N = 640)+ if (size_n % 256 && !getenv("EXL3_PF7_OFF"))+ { mpw2_gemm_kernel<2, false, OUT_FP32, CB, 1, 128, 2, 2, 0, 258><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ MPW2_V(1, 128, 2, 2)case 2: MPW2_V(2, 128, 3, 2)case 3: MPW2_V(3, 128, 1, 2)case 4: MPW2_V(4, 64, 4, 2)@@ -1310,6 +1498,22 @@ void launch_gemm_cbif (ldm == 0){ mpw2_gemm_kernel<2, false, OUT_FP32, CB, 0, 64, 4, 2, 0><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }}+ // pf7: 3-bit experts (MiMo mixed layers) get the direct-LDS fragment reads (OPT bits 0/1) that K 2 already had+ if (k2 == 6 && nw == 2 && mt == 128 && dbg == 0 && !getenv("EXL3_PF7_OFF"))+ {+ if (size_n % 256)+ { mpw2_gemm_kernel<3, false, OUT_FP32, CB, 1, 128, 2, 2, 0, 259><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ { mpw2_gemm_kernel<3, false, OUT_FP32, CB, 1, 128, 2, 2, 0, 3><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ }+ // 4-bit experts (Qwen3.8 K4 layers) take the same direct-LDS + tail-wave-skip variant as the 3-bit block+ // above (measured bit-identical to the default instance, +2 % prefill; the instance is already compiled for the+ // EXL3_PF7_OPT override)+ if (k2 == 8 && nw == 2 && mt == 128 && dbg == 0 && !getenv("EXL3_PF7_OFF"))+ {+ if (size_n % 256)+ { mpw2_gemm_kernel<4, false, OUT_FP32, CB, 1, 128, 2, 2, 0, 259><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ { mpw2_gemm_kernel<4, false, OUT_FP32, CB, 1, 128, 2, 2, 0, 3><<<grid, mpw2::THREADS, 0, stream>>>(MPW_ARGS); return; }+ }switch (k2){case 4: MPW2_K(2, false)@@ -1355,15 +1559,16 @@ void launch_gemmfloat K, dim3 grid, hipStream_t stream,const half* A, int64_t a_proj_stride, const int64_t* offsets, const int* tiles,const int* num_tiles, const int64_t* t0, const int64_t* t1, void* C, int64_t c_proj_stride,- int size_k, int size_n, bool mcg, int kern+ int size_k, int size_n, bool mcg, int kern, int a_ld = 0){+ if (a_ld == 0) a_ld = size_k;if (mcg)launch_gemm_cb<OUT_FP32, 1>(K, grid, stream, A, a_proj_stride, offsets, tiles, num_tiles,- t0, t1, C, c_proj_stride, size_k, size_n, kern);+ t0, t1, C, c_proj_stride, size_k, size_n, kern, a_ld);elselaunch_gemm_cb<OUT_FP32, 2>(K, grid, stream, A, a_proj_stride, offsets, tiles, num_tiles,- t0, t1, C, c_proj_stride, size_k, size_n, kern);+ t0, t1, C, c_proj_stride, size_k, size_n, kern, a_ld);}inline int tile_slots(int assignments, int experts, int kern)@@ -1456,10 +1661,22 @@ void exl3_moe_prefill_wmmampw_metadata_kernel<<<CEIL_DIVIDE(assignments, 256), 256, 0, stream>>>((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;+ if (glue2)+ {+ const int64_t g2jobs = (int64_t) (assignments / top_k) * (H / 128);+ mpw_gather_had2_kernel<<<CEIL_DIVIDE(g2jobs, 8), 256, 0, stream>>>+ ((const half*) A.data_ptr(), (half*) gu_had.data_ptr(), sel, inv, P(gate_suh), P(up_suh),+ assignments, top_k, H);+ }+ else+ {const int64_t gjobs = (int64_t) 2 * (assignments / top_k) * (H / 128);mpw_gather_had_kernel<<<CEIL_DIVIDE(gjobs, 8), 256, 0, stream>>>((const half*) A.data_ptr(), (half*) gu_had.data_ptr(), sel, inv, P(gate_suh), P(up_suh),assignments, top_k, H, 2);+ }launch_gemm<false>((float) K_gu, dim3(I / mpw::NT, slots, 2), stream,(const half*) gu_had.data_ptr(), (int64_t) assignments * H, offs, tl, tc,@@ -1471,12 +1688,18 @@ void exl3_moe_prefill_wmma(float) act_limit);// down_out = gu_had workspace viewed fp32 (same byte count): the down GEMM writes fp32 rows- // so the weighted reduce consumes fp32 end to end (2x output bytes vs fp16)+ // so the weighted reduce consumes fp32 end to end (2x output bytes vs fp16; cost in REPORT-10c)launch_gemm<true>((float) K_down, dim3(H / mpw::NT, slots, 1), stream,(const half*) gu_out.data_ptr(), 0, offs, tl, tc,P(down_trellis), P(down_trellis), down_out.data_ptr(), 0, I, H, mcg, kern);const int64_t rjobs = (int64_t) rows * (H / 128);+#define MPW_RED2(TKV) mpw_reduce_had2_kernel<TKV><<<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, H)+ if (glue2 && top_k == 10) { MPW_RED2(10); }+ else if (glue2 && top_k == 8) { MPW_RED2(8); }+ elsempw_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);@@ -1498,10 +1721,16 @@ void exl3_moe_prefill_gemm_test{const at::cuda::OptionalCUDAGuard device_guard(A.device());hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();- const int rows = A.size(0);+ // EXL3_GEMMTEST_Z=2 (bench only) = gate/up form: A and C hold 2 projections of rows each, grid.z = 2.+ // A may be a row-strided view (stride(1) == 1, pitch = stride(0) >= K, 16-byte aligned): the A row pitch bench.+ const char* ze = getenv("EXL3_GEMMTEST_Z");+ const int nz = (ze && atoi(ze) == 2) ? 2 : 1;+ TORCH_CHECK(A.dim() == 2 && A.stride(1) == 1 && A.size(0) % nz == 0, "A must be row-strided [nz * rows, K]");+ const int rows = A.size(0) / nz;const int size_k = A.size(1);+ const int a_ld = (int) A.stride(0);const int64_t experts = trellis_table.numel();- TORCH_CHECK(C.size(0) == rows && C.size(1) == n_size, "C shape");+ TORCH_CHECK(C.size(0) == rows * nz && C.size(1) == n_size && C.is_contiguous(), "C shape");TORCH_CHECK(size_k % (mpw::KS * 16) == 0 && n_size % mpw::NT == 0, "unsupported shape");const int kern = mpw_kern(rows, experts);const int slots = tile_slots(rows, experts, kern);@@ -1513,11 +1742,11 @@ void exl3_moe_prefill_gemm_test((const int64_t*) expert_count.data_ptr(), nullptr, offs, nullptr, tl, tc, (int) experts, rows, mpw_mt(kern));const int64_t* tt = (const int64_t*) trellis_table.data_ptr();if (C.dtype() == at::kFloat)- launch_gemm<true>((float) K, dim3(n_size / mpw::NT, slots, 1), stream,- (const half*) A.data_ptr(), 0, offs, tl, tc, tt, tt, C.data_ptr(), 0, size_k, n_size, false, kern);+ launch_gemm<true>((float) K, dim3(n_size / mpw::NT, slots, nz), stream,+ (const half*) A.data_ptr(), (int64_t) rows * a_ld, offs, tl, tc, tt, tt, C.data_ptr(), (int64_t) rows * n_size, size_k, n_size, false, kern, a_ld);else- launch_gemm<false>((float) K, dim3(n_size / mpw::NT, slots, 1), stream,- (const half*) A.data_ptr(), 0, offs, tl, tc, tt, tt, C.data_ptr(), 0, size_k, n_size, false, kern);+ launch_gemm<false>((float) K, dim3(n_size / mpw::NT, slots, nz), stream,+ (const half*) A.data_ptr(), (int64_t) rows * a_ld, offs, tl, tc, tt, tt, C.data_ptr(), (int64_t) rows * n_size, size_k, n_size, false, kern, a_ld);cuda_check(hipPeekAtLastError());}diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_valu.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_valu.cuhnew file mode 100644index 0000000..29cf7a4--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_valu.cuh@@ -0,0 +1,202 @@+#pragma once+// VALU grouped-MoE decode matvec (gfx11.5, opt-in EXL3_MOE_VALU=1). Replaces the WMMA/LDS body of the grouped and+// expert-dedup decode launches for K2 and K4 experts, one launch per projection as before.+//+// Numerics: v_wmma_f32_16x16x16_f16 equals a chain of 8 v_dot2_f32_f16 over k ascending from the running accumulator, so a lane that+// owns a whole 16-k column per k-slice reproduces the engine's WMMA body bit for bit. The 16 k-chunks (WK = 16) are reduced in chunk+// order from 0.0f exactly like the engine's `sum += red[j]`. One reduction order for every row count: a row's result does not depend+// on how many rows share the launch, so decode (R=1) and verify rounds (R>1) give identical bits.+//+// Mapping: one wave = one 16-column tile, all k. lane = cq * 8 + g8: g8 = column pair (g8, g8 + 8), cq = chunk lane; 4 rounds x 4+// chunk lanes = the 16 k-chunks. Each lane reads its own `bits` trellis words plus one wrap word per slice straight from global and+// decodes with the engine's own dq8_regs_* helpers. Rows run in passes of at most 4.+#include "exl3_moe_valu_idx.h"++#if defined(USE_ROCM) || defined(__HIPCC__)+typedef _Float16 mv_h2 __attribute__((ext_vector_type(2)));+__device__ __forceinline__ float mv_dot2(uint32_t a, uint32_t b, float c)+{+ return __builtin_amdgcn_fdot2(__builtin_bit_cast(mv_h2, a), __builtin_bit_cast(mv_h2, b), c, false);+}++#ifndef EXL3_MOE_VALU_W+#define EXL3_MOE_VALU_W 4 // waves (tiles) per block+#endif++// One tile (16 columns) of RW rows. VU = k-slices per pipeline stage (register ring of VU slices, crossing round boundaries).+template <int BITS, bool CF32, int RW, int VU>+__device__ __forceinline__ void mv_tile+(+ const uint32_t* __restrict__ A32, int size_k, const uint32_t* __restrict__ B32, int ntiles,+ void* __restrict__ C, int size_n, int tile, float* red, int wave, int lane+)+{+ constexpr int NWD = BITS + 1;+ const int ks = size_k / 16, CH = mv::chunk(ks), NRND = mv::NCH / 4;+ const int g8 = lane & 7, cq = lane >> 3;+ float rs0[RW], rs1[RW];+ #pragma unroll+ for (int r = 0; r < RW; ++r) { rs0[r] = 0.f; rs1[r] = 0.f; }+ uint32_t wa[VU][NWD], wb[VU][NWD];+ auto ld = [&](uint32_t (&w)[NWD], int s)+ {+ w[0] = B32[mv::wrap(BITS, ntiles, tile, g8, s)];+ const uint32_t* p = B32 + mv::own(BITS, ntiles, tile, g8, s);+ if constexpr (BITS == 2) { const uint2 v = *(const uint2*) p; w[1] = v.x; w[2] = v.y; }+ else { const uint4 v = *(const uint4*) p; w[1] = v.x; w[2] = v.y; w[3] = v.z; w[4] = v.w; }+ };+ auto ldst = [&](uint32_t (&w)[VU][NWD], int rnd, int sg0)+ {+ const int cc = 4 * rnd + cq, s0n = cc * CH, m = mv::myn(ks, cc);+ #pragma unroll+ for (int u = 0; u < VU; ++u) if (sg0 + u < m) ld(w[u], s0n + sg0 + u);+ };+ ldst(wa, 0, 0);+ #pragma unroll 1+ for (int round = 0; round < NRND; ++round)+ {+ const int c = 4 * round + cq;+ const int s0 = c * CH;+ const int myn = mv::myn(ks, c);+ float acc0[RW], acc1[RW];+ #pragma unroll+ for (int r = 0; r < RW; ++r) { acc0[r] = 0.f; acc1[r] = 0.f; }+ #pragma unroll 1+ for (int sb = 0; sb < CH; sb += VU)+ {+ int nr = round, ns = sb + VU;+ if (ns >= CH) { nr = round + 1; ns = 0; }+ if (nr < NRND) ldst(wb, nr, ns);+ #pragma unroll+ for (int u = 0; u < VU; ++u)+ {+ if (sb + u < myn)+ {+ FragB f0[4], f1[4];+ #pragma unroll+ for (int t = 0; t < 4; ++t)+ {+ if constexpr (BITS == 2) exl3_gemv_ns::dq8_regs_2bits<2>(wa[u][t >> 1], wa[u][1 + (t >> 1)], t << 3, f0[t], f1[t]);+ else exl3_gemv_ns::dq8_regs_4bits<2>(wa[u][t], wa[u][t + 1], f0[t], f1[t]);+ }+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ const long ai = mv::a_idx(r, size_k, s0 + sb + u);+ const uint4 alo = *(const uint4*) (A32 + ai);+ const uint4 ahi = *(const uint4*) (A32 + ai + 4);+ const uint32_t aq[8] = {alo.x, alo.y, alo.z, alo.w, ahi.x, ahi.y, ahi.z, ahi.w};+ #pragma unroll+ for (int q = 0; q < 8; ++q)+ {+ const int t = q & 3, h = q >> 2;+ acc0[r] = mv_dot2(__builtin_bit_cast(uint32_t, f0[t][h]), aq[q], acc0[r]);+ acc1[r] = mv_dot2(__builtin_bit_cast(uint32_t, f1[t][h]), aq[q], acc1[r]);+ }+ }+ }+ }+ #pragma unroll+ for (int u = 0; u < VU; ++u)+ #pragma unroll+ for (int w = 0; w < NWD; ++w) wa[u][w] = wb[u][w];+ }+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ red[mv::red_idx(wave, cq, g8, r)] = acc0[r];+ red[mv::red_idx(wave, cq, g8 + 8, r)] = acc1[r];+ }+ __syncwarp();+ if (cq == 0)+ {+ #pragma unroll+ for (int cc = 0; cc < 4; ++cc)+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ rs0[r] += red[mv::red_idx(wave, cc, g8, r)];+ rs1[r] += red[mv::red_idx(wave, cc, g8 + 8, r)];+ }+ }+ __syncwarp();+ }+ if (cq == 0)+ {+ #pragma unroll+ for (int r = 0; r < RW; ++r)+ {+ if constexpr (CF32)+ {+ ((float*) C)[mv::c_idx(r, size_n, tile, g8)] = rs0[r];+ ((float*) C)[mv::c_idx(r, size_n, tile, g8 + 8)] = rs1[r];+ }+ else+ {+ ((half*) C)[mv::c_idx(r, size_n, tile, g8)] = __float2half_rn(rs0[r]);+ ((half*) C)[mv::c_idx(r, size_n, tile, g8 + 8)] = __float2half_rn(rs1[r]);+ }+ }+ }+}++// DEDUP: blockIdx.y is a run of equal experts in the sorted assignment list (rows = run length); otherwise blockIdx.y is the+// assignment slot (one row). Same buffer layout and zero-fill of invalid experts as the WMMA grouped kernels.+template <int BITS, bool CF32, bool DEDUP, bool TWO, int VU>+__global__ __launch_bounds__(EXL3_MOE_VALU_W * 32)+void moe_valu_kernel+(+ const half* A, const int64_t* selected, const int* group_start, const int* num_groups,+ const int64_t* B_table_0, const int64_t* B_table_1, void* C,+ int size_k, int size_n, int experts, int assignments+)+{+ constexpr int W = EXL3_MOE_VALU_W;+ __shared__ float red[mv::red_size(W)];+ const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int ntiles = size_n / 16;+ const int tile = mv::tile_of(blockIdx.x, wave, W);+ int p0, rows;+ if constexpr (DEDUP)+ {+ const int g = blockIdx.y;+ if (g >= *num_groups) return;+ p0 = group_start[g];+ rows = group_start[g + 1] - p0;+ }+ else { p0 = blockIdx.y; rows = 1; }+ if (tile >= ntiles) return;+ const int projection = TWO ? blockIdx.z : 0;+ const int64_t expert = selected[p0];+ const int64_t* B_table = projection == 0 ? B_table_0 : B_table_1;+ const size_t matrix = (size_t) projection * assignments + p0;+ void* C_rows = CF32 ? static_cast<void*>(reinterpret_cast<float*>(C) + matrix * size_n)+ : static_cast<void*>(reinterpret_cast<half*>(C) + matrix * size_n);+ const bool valid_expert = expert >= 0 && expert < experts;+ const int64_t B_ptr = valid_expert ? B_table[expert] : 0;+ if (!B_ptr)+ {+ if (lane < 16)+ for (int r = 0; r < rows; ++r)+ {+ const size_t o = mv::c_idx(r, size_n, tile, lane);+ if constexpr (CF32) reinterpret_cast<float*>(C_rows)[o] = 0.0f;+ else reinterpret_cast<half*>(C_rows)[o] = __float2half_rn(0.0f);+ }+ return;+ }+ const uint32_t* B32 = reinterpret_cast<const uint32_t*>(B_ptr);+ const uint32_t* A_rows = reinterpret_cast<const uint32_t*>(A + matrix * size_k);+ for (int r0 = 0; r0 < rows; r0 += mv::MAXPASS)+ {+ const int n = mv::pass_rows(rows, r0);+ const uint32_t* Ap = A_rows + (size_t) r0 * (size_k / 2);+ void* Cp = CF32 ? static_cast<void*>(reinterpret_cast<float*>(C_rows) + (size_t) r0 * size_n)+ : static_cast<void*>(reinterpret_cast<half*>(C_rows) + (size_t) r0 * size_n);+ if (n == 1) mv_tile<BITS, CF32, 1, VU>(Ap, size_k, B32, ntiles, Cp, size_n, tile, red, wave, lane);+ else if (n == 2) mv_tile<BITS, CF32, 2, VU>(Ap, size_k, B32, ntiles, Cp, size_n, tile, red, wave, lane);+ else if (n == 3) mv_tile<BITS, CF32, 3, VU>(Ap, size_k, B32, ntiles, Cp, size_n, tile, red, wave, lane);+ else mv_tile<BITS, CF32, 4, VU>(Ap, size_k, B32, ntiles, Cp, size_n, tile, red, wave, lane);+ }+}+#endif // USE_ROCMdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_valu_idx.h b/exllamav3/exllamav3_ext/quant/exl3_moe_valu_idx.hnew file mode 100644index 0000000..368bc8f--- /dev/null+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_valu_idx.h@@ -0,0 +1,30 @@+#pragma once+// Index arithmetic of the VALU grouped-MoE decode matvec (EXL3_MOE_VALU). Pure C++: shared by the kernel+// (exl3_moe_valu.cuh) and by the CPU bounds checker (tests/moe_valu_bounds.cpp). Every global, LDS and output index the+// kernel computes goes through these helpers. Weights are in the engine's native trellis layout:+// u32 index = kslice * (ntiles * TW) + tile * TW + word, TW = 8 * bits.+#if defined(__HIPCC__) || defined(__CUDACC__)+#define MV_FN constexpr __host__ __device__ __forceinline__+#else+#define MV_FN constexpr inline+#endif+namespace mv {+constexpr int NCH = 16; // k-chunks: the engine's warp k-split (WK = 16, EXL3_MOE_CFG = 0)+constexpr int MAXPASS = 4; // rows per pass; more rows run as extra passes over the same expert+MV_FN int tw(int bits) { return 8 * bits; }+MV_FN long sst(int bits, int ntiles) { return (long) ntiles * tw(bits); } // u32 per k-slice row+MV_FN int chunk(int ks) { return (ks + NCH - 1) / NCH; } // k-slices per chunk+MV_FN int myn(int ks, int c) { int ch = chunk(ks); int r = ks - c * ch; r = r < ch ? r : ch; return r > 0 ? r : 0; }+// u32 offset in the expert region of the lane's own words (bits of them, contiguous) and of its wrap word+MV_FN long own(int bits, int ntiles, int tile, int g8, int s) { return (long) s * sst(bits, ntiles) + (long) tile * tw(bits) + bits * g8; }+MV_FN long wrap(int bits, int ntiles, int tile, int g8, int s) { return (long) s * sst(bits, ntiles) + (long) tile * tw(bits) + ((bits * g8 - 1) & (tw(bits) - 1)); }+// A (fp16, row-major, K halves per row), as u32: row r, k-slice s covers 8 u32+MV_FN long a_idx(int r, int k, int s) { return (long) r * (k / 2) + 8 * s; }+// wave-private reduction scratch [waves][4 chunk lanes][16 cols][4 rows] floats+MV_FN int red_idx(int wave, int cq, int col, int row) { return ((wave * 4 + cq) * 16 + col) * 4 + row; }+MV_FN int red_size(int waves) { return waves * 4 * 16 * 4; }+MV_FN long c_idx(int row, int n, int tile, int col16) { return (long) row * n + (long) tile * 16 + col16; }+MV_FN int tile_of(int bx, int wave, int W) { return bx * W + wave; }+MV_FN int grid_x(int ntiles, int W) { return (ntiles + W - 1) / W; }+MV_FN int pass_rows(int rows, int r0) { int n = rows - r0; return n < MAXPASS ? n : MAXPASS; }+}diff --git a/exllamav3/exllamav3_ext/quant/quantize.cu b/exllamav3/exllamav3_ext/quant/quantize.cuindex 3ebc54c..c519baa 100644--- a/exllamav3/exllamav3_ext/quant/quantize.cu+++ b/exllamav3/exllamav3_ext/quant/quantize.cu@@ -137,8 +137,8 @@ enum { QT_BASE = 0, QT_OPTIMIZED = 1, QT_RDNA = 2 };// falls back to base where it has no instance); EXL3_QT_OPTIMIZED=1/0 keeps its old meaning.// On ROCm the grouped kernel is the default for K = 2..3, the dense specialization for K = 4..5.// All are measured bit-identical to the base kernel on gfx1151. K = 4 routes to dense because the-// grouped kernel only matches base there while dense is ~2.5-3x base (K = 2..3 and-// K = 5).+// grouped kernel only matches base there while dense is ~2.5-3x base (REPORT-10; K = 2..3 and+// K = 5 measured in REPORT-09/REPORT-10).static int quantize_tiles_mode(int major, int minor, int K, int cb, int L){if (const char* env = std::getenv("EXL3_QT_KERNEL"))diff --git a/exllamav3/ext.py b/exllamav3/ext.pyindex ab516b9..b489399 100644--- a/exllamav3/ext.py+++ b/exllamav3/ext.py@@ -235,20 +235,52 @@ if torch.version.hip:if hasattr(exllamav3_ext, "fused_gated_rms_norm") and os.environ.get("EXL3_FUSE_GNORM", "1") != "0":_fb_gated_rms_norm = _fb.gated_rms_norm- def _gated_rms_norm_rocm(x, w, y, g, eps, constant_bias, w_groups, gate_first, gate_act = 0):+ def _gated_rms_norm_rocm(x, w, y, g, eps, constant_bias, w_groups, gate_first, gate_act = 0, y_pitch = 0):if (x.is_cuda and x.dtype == torch.bfloat16 and y.dtype in (torch.float16, torch.float32) andw.dtype in (torch.bfloat16, torch.float32) and(g.dtype in (torch.bfloat16, torch.float32) or(g.dtype == torch.float16 and ROCM_KNOBS["gnorm_f16g"])) and- x.is_contiguous() and y.is_contiguous() and g.is_contiguous() and w.is_contiguous() and+ x.is_contiguous() and (y.is_contiguous() or (y_pitch and y.dtype == torch.float16 and x.dim() >= 3)) and g.is_contiguous() and w.is_contiguous() andx.shape == y.shape == g.shape and x.shape[-1] <= 512 and x.shape[-1] % 128 == 0 and w_groups >= 1 andw.numel() == w_groups * x.shape[-1] and gate_act in (0, 1)):- exllamav3_ext.fused_gated_rms_norm(x, w, y, g, eps, constant_bias, w_groups, gate_first, gate_act)+ exllamav3_ext.fused_gated_rms_norm(x, w, y, g, eps, constant_bias, w_groups, gate_first, gate_act,+ y_pitch, x.shape[-2] if y_pitch else 1)return+ assert not y_pitch, "padded gated-norm output needs the fused kernel"_fb_gated_rms_norm(x, w, y, g, eps, constant_bias, w_groups, gate_first, gate_act)+ def _gn_pad_ok(x, w, y_dtype, g, w_groups, gate_act = 0):+ """True when _gated_rms_norm_rocm can write a row-padded fp16 y: the fused kernel's own conditions."""+ return (x.is_cuda and x.dtype == torch.bfloat16 and x.dim() >= 3 and y_dtype == torch.float16 and+ w.dtype in (torch.bfloat16, torch.float32) and+ (g.dtype in (torch.bfloat16, torch.float32) or+ (g.dtype == torch.float16 and ROCM_KNOBS["gnorm_f16g"])) and+ x.is_contiguous() and g.is_contiguous() and w.is_contiguous() and x.shape == g.shape and+ x.shape[-1] <= 512 and x.shape[-1] % 128 == 0 and w_groups >= 1 and+ w.numel() == w_groups * x.shape[-1] and gate_act in (0, 1))+ _gated_rms_norm_rocm.pad_ok = _gn_pad_oksetattr(exllamav3_ext, "gated_rms_norm", _gated_rms_norm_rocm)+ # deinterleave_qg: hand HIP copy kernel (modules/ple_fn/ple_hip.hip), pure copy so bitwise equal; EXL3_DQ_HIP=1+ if True: # flag read per call so one process can A/B it+ _fb_deinterleave_qg = _fb.deinterleave_qg++ def _deinterleave_qg_rocm(qg, q, g, head_dim):+ if (os.environ.get("EXL3_DQ_HIP", "0") == "1" and head_dim % 8 == 0 and qg.is_cuda and qg.dtype == torch.float16 and q.dtype == torch.float16+ and g.dtype == torch.float16 and qg.is_contiguous() and q.is_contiguous() and g.is_contiguous()+ and q.numel() == g.numel() and q.numel() * 2 == qg.numel() and q.numel() > 0+ and qg.data_ptr() % 16 == 0 and q.data_ptr() % 16 == 0 and g.data_ptr() % 16 == 0+ and qg.numel() % (2 * head_dim) == 0):+ try:+ from .modules.ple_fn import ple_hip+ ple_hip.deinterleave_qg(qg, q, g, head_dim)+ return+ except Exception:+ pass+ _fb_deinterleave_qg(qg, q, g, head_dim)++ setattr(exllamav3_ext, "deinterleave_qg", _deinterleave_qg_rocm)+# r35: runtime-mutable knobs (in-process A/B)ROCM_KNOBS = {"silu_lim": os.environ.get("EXL3_FUSE_SILU_LIM", "1") != "0",# fp16 gate (KDA z under EXL3_KDA_F16_GATES) into the fused gated norm; "0" = the torchdiff --git a/exllamav3/ext_fallbacks.py b/exllamav3/ext_fallbacks.pyindex 25f88e7..7e6f5f2 100644--- a/exllamav3/ext_fallbacks.py+++ b/exllamav3/ext_fallbacks.py@@ -225,6 +225,25 @@ def deinterleave_qg(g.copy_(chunks[..., head_dim:].reshape_as(g))+_ROWINV_ROWS = 64+++def _mean_sq(x: torch.Tensor) -> torch.Tensor:+ """mean(x^2) over the last axis of a (rows, dim) fp32 tensor, row-invariant for rows <= 64.++ torch picks the reduction tree from the (rows, dim) shape, so the same row can round+ differently at different row counts. Short inputs (decode, R <= 8 verify rows) are zero+ padded to a fixed 64 rows: every row then goes through the same reduction config.+ """+ rows, dim = x.shape+ sq = x.square()+ if rows >= _ROWINV_ROWS:+ return sq.mean(dim = -1, keepdim = True)+ pad = sq.new_zeros((_ROWINV_ROWS, dim))+ pad[:rows] = sq+ return pad.mean(dim = -1, keepdim = True)[:rows]++# -- Norm ops (norm.cu) --------------------------------------------------------def rms_norm(@@ -272,7 +291,7 @@ def rms_norm(xf = xr[r0:r0 + row_chunk].float()if x.dtype == torch.float16:xf = xf.clamp(min = -65504.0, max = 65504.0)- xf = xf * torch.rsqrt(xf.square().mean(dim = -1, keepdim = True) + eps)+ xf = xf * torch.rsqrt(_mean_sq(xf) + eps)xf = xf * constant_scaleif wf is not None:if w_groups == 1:@@ -312,7 +331,7 @@ def rms_norm_res_in(wf = w.float() + constant_bias if constant_bias != 0.0 else w.float()else:wf = None- var = rf.pow(2).mean(dim = -1, keepdim = True) + eps+ var = _mean_sq(rf.reshape(-1, rf.shape[-1])).reshape(*rf.shape[:-1], 1) + epsrf = rf * torch.rsqrt(var) * constant_scaleif wf is not None:rf = rf * wf@@ -347,7 +366,7 @@ def gated_rms_norm(gate = torch.sigmoid(gf) if gate_act == 1 else F.silu(gf)norm_input = xf * gate if gate_first else xfhidden = norm_input * torch.rsqrt(- norm_input.square().mean(dim = -1, keepdim = True) + eps+ _mean_sq(norm_input) + eps)wf = w.float().reshape(w_groups, dim)if constant_bias != 0.0:diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.pyindex 08f1bb0..05f52cd 100644--- a/exllamav3/generator/generator.py+++ b/exllamav3/generator/generator.py@@ -3,6 +3,10 @@ import loggingimport osimport timeimport torch+try:+ from ..modules.moe_fused import check_barrier as _moe_fused_check # fused MoE half-layer grid barrier: raise if it ever timed out+except Exception: # noqa: BLE001+ _moe_fused_check = Nonefrom ..model.model import Modelfrom ..cache.cache import Cachefrom ..cache.recurrent import RecurrentCache@@ -226,7 +230,7 @@ class Generator:self.ngram_match_min = ngram_match_minself.dynamic_draft = dynamic_draft_tokens and self.num_draft_tokens > 0self.record_draft_stats = record_draft_stats- # Cost-model gate: skip the drafter forward (and the R-row verify) whenever the+ # REPORT-28 cost-model gate: skip the drafter forward (and the R-row verify) whenever the# measured speculative rate would not beat plain decode. Opt-in: EXL3_SPEC_GATE=1self.spec_gate = SpecGate() if (draft_model is not None andos.environ.get("EXL3_SPEC_GATE", "0") != "0") else None@@ -240,6 +244,8 @@ class Generator:max_chunk_size = model.caps.get("prefill_chunk_size", 2048)if os.environ.get("EXL3_PREFILL_CHUNK"):max_chunk_size = int(os.environ["EXL3_PREFILL_CHUNK"])+ if max_chunk_size > 65535:+ raise ValueError(f"prefill chunk of {max_chunk_size} rows is not supported: a forward is limited to 65535 rows (mixer kernel grid.y); lower EXL3_PREFILL_CHUNK / max_chunk_size")self.max_chunk_size = max_chunk_size# Job queues@@ -507,6 +513,12 @@ class Generator:@torch.inference_modedef iterate(self) -> list[dict]:+ results = self._iterate_inner()+ if _moe_fused_check is not None:+ _moe_fused_check(self.model)+ return results++ def _iterate_inner(self) -> list[dict]:"""Performs inference on available jobs.@@ -766,8 +778,50 @@ class Generator:return self.draft_ids_pinned[:, :window]+ def _flush_mtp_defer(self, job, with_tail: bool):+ """EXL3_PF_DEFER: run the draft prefill chunks that Job.prefill stashed instead of running them before the first+ token. with_tail also writes the draft K/V row of the last prompt token (token L-1 paired with the hidden state+ of L-2): the normal first draft round writes that row itself, a deferred first round (plain target step) does not."""+ chunks = job.mtp_defer+ job.mtp_defer = None+ if not chunks:+ return+ for ids, params in chunks:+ self.draft_model.prefill(ids, params)+ if with_tail and job.mtp_defer_carry is not None:+ seq = job.sequences[0]+ pos = job.mtp_defer_end+ self.draft_model.prefill(seq.sequence_ids.torch_slice(pos, pos + 1), {+ "attn_mode": "flash_attn",+ "block_table": seq.block_index_tensor,+ "cache": self.draft_cache,+ "cache_seqlens": torch.tensor([pos], dtype = torch.int32),+ "target_hidden": job.mtp_defer_carry,+ "indexed_embeddings": job.embeddings,+ "kv_only": True,+ })+++ def _mtp_defer_gate(self) -> bool:+ """True when the coming round must be a plain target step (first token without the draft prefill).+ Otherwise flushes whatever is pending and returns False. Called at the top of the MTP draft round."""+ pend = [j for j in self.active_jobs if j.is_prefill_done() and getattr(j, "mtp_defer", None)]+ if not pend:+ return False+ rows = sum(c[0].shape[-1] for j in pend for c in j.mtp_defer)+ if len(self.active_jobs) == 1 and not pend[0].mtp_defer_plain and \+ rows >= int(os.environ.get("EXL3_PF_DEFER_MIN", "1024")):+ pend[0].mtp_defer_plain = True+ return True+ for j in pend:+ self._flush_mtp_defer(j, with_tail = j.mtp_defer_plain)+ return False++def iterate_draftmodel_mtp_gen(self, results: list):+ if self._mtp_defer_gate():+ return Noneself._draft_conf_round = None# Get shape of active batch@@ -1233,7 +1287,7 @@ class Generator:"positions": positions,"recurrent_history": draft_tokens is not None,"pinned_staging": True,- # marks a real DFlash verify forward (R rows, target model), as opposed to+ # REPORT-17: marks a real DFlash verify forward (R rows, target model), as opposed to# any other multi-row call with rows in the same 2..MAX_BSZN range -- prefill routes# 2-8 tokens to plenty of individual MoE experts, and the draft model's own forward# has draft_tokens is None too. The four R-row fast paths (block_sparse_mlp.py's MoE@@ -1923,7 +1977,7 @@ def _pt():class SpecGate:"""- Cost-model gate for speculative decoding. Keeps EMAs of the plain step time, the+ Cost-model gate for speculative decoding (REPORT-28). Keeps EMAs of the plain step time, thespeculative round time and the tokens a round yields, and speculates only whiletokens_per_round / t_round >= 1 / t_plain. In plain mode it probes one speculative round after`probe` plain steps; a failed probe doubles the interval (up to probe_max), a successful onediff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.pyindex 55ccb9c..69f0369 100644--- a/exllamav3/generator/job.py+++ b/exllamav3/generator/job.py@@ -9,6 +9,7 @@ import numpy as npfrom .pagetable import Sequence, tensor_hash_checksum, random_hashfrom .filter import Filterimport random+import loggingimport timefrom ..ext import exllamav3_ext as extfrom .loop_detect import LoopDetector@@ -308,6 +309,8 @@ class Job:# Recurrent stateself.recurrent_state = Noneself.last_recurrent_checkpoint_pos = None+ self.roll_ckpt = os.environ.get("EXL3_ROLL_CKPT", "0") == "1"+ self.roll_key = None# Loop detectorself.loop_detector = None@@ -323,6 +326,12 @@ class Job:# MTP stateself.mtp_last_hidden = None+ # EXL3_PF_DEFER: draft prefill chunks stashed by prefill() and run after the first token+ # (generator._flush_mtp_defer); end = position of the last prompt token, carry = hidden state before it+ self.mtp_defer = None+ self.mtp_defer_plain = False+ self.mtp_defer_end = 0+ self.mtp_defer_carry = Nonedef get_pinned_logit_mask(self):@@ -940,6 +949,8 @@ class Job:# An MTP draft carry refers to the pre-rewind context; drop it so drafting pauses until the next# target forward (or replay prefill) provides a fresh one. Signal the generator that any in-flight# draft verification window must be abandoned.+ if self.mtp_defer:+ self.generator._flush_mtp_defer(self, with_tail = self.mtp_defer_plain)self.mtp_last_hidden = Noneself.checkpoint_rewound = Trueoff_tokens = self.held_tokens.slice(len(self.checkpoint["held_tokens"]), None)@@ -1230,15 +1241,8 @@ class Job:# recurrent checkpoint of plain max_chunk_size chunkingchunk = self.generator.max_chunk_sizebig = int(os.environ.get("EXL3_PREFILL_BIG_CHUNK", "4096"))- # EXL3_PREFILL_BIG_CHUNK_MAXPOS (default 0 = off): from this kv position on, plain chunks again (smaller- # workspace, lower peak GPU/unified memory at very long context); the cached big-chunk workspace is- # released once per job at the switch- maxpos = int(os.environ.get("EXL3_PREFILL_BIG_CHUNK_MAXPOS", "0"))- if maxpos and big > chunk and seq.kv_position >= maxpos:- big = chunk- if not getattr(self, "_big_chunk_released", False):- self._big_chunk_released = True- torch.cuda.empty_cache()+ if big > 65535:+ raise ValueError(f"EXL3_PREFILL_BIG_CHUNK={big}: a forward is limited to 65535 rows (mixer kernel grid.y)")remaining = len(seq.sequence_ids) - 1 - seq.kv_positionbig_tail = big > chunk and big % chunk == 0 and self.big_tail_enabled()if big_tail:@@ -1499,10 +1503,22 @@ class Job:# block, so it is deliberately not touchedif self.generator.mtp_draft and os.environ.get("EXL3_PF_SKIP", "0") == "1":draft_params["kv_only"] = True- self.generator.draft_model.prefill(- input_ids = prefill_ids,- params = draft_params- )+ # EXL3_PF_DEFER=1: single sequence MTP prefill stashes the draft chunks; the generator runs them+ # after the first token (first round is a plain target step). Flushed at job end and on rewind,+ # so the draft cache stays complete for prefix reuse+ if self.generator.mtp_draft and os.environ.get("EXL3_PF_DEFER", "0") == "1" and \+ len(self.sequences) == 1 and self.generator.spec_gate is None:+ draft_params["kv_only"] = True+ if self.mtp_defer is None:+ self.mtp_defer = []+ self.mtp_defer.append((prefill_ids.clone(), draft_params))+ self.mtp_defer_end = prefill_end+ self.mtp_defer_carry = seq.mtp_carry_hidden+ else:+ self.generator.draft_model.prefill(+ input_ids = prefill_ids,+ params = draft_params+ )# Atomic MM prefill may have extended the forward pass past prefill_end, advancing any# recurrent state beyond the chunk boundary. The extension is processed again by the@@ -1603,6 +1619,12 @@ class Job:def deallocate_pages(self):+ if self.mtp_defer:+ try:+ self.generator._flush_mtp_defer(self, with_tail = self.mtp_defer_plain)+ except Exception as e: # cleanup must not raise: the draft cache only loses accept depth on reuse+ logging.warning("EXL3_PF_DEFER flush failed: %r", e)+ self.mtp_defer = Noneself.free_recurrent_state()for seq in self.sequences:if seq.allocated_pages is not None:@@ -1675,6 +1697,11 @@ class Job:seq_pos = seq.kv_position if pos is None else posif override_interval:return seq_pos % override_interval == 0+ # EXL3_ROLL_CKPT=1 (default off): while decoding, every page boundary is a checkpoint candidate; the+ # previous rolling one is dropped when the next lands (see maybe_stash_recurrent), so a follow-up turn+ # resumes at the last full page of the reply instead of the last 2048-grid checkpoint+ if self.roll_ckpt and pos is None and seq_pos >= len(seq.input_ids):+ return seq_pos % PAGE_SIZE == 0elif seq_pos >= prompt_len - self.generator.max_chunk_size * 2:return (seq_pos - self.cached_pages * PAGE_SIZE) % self.generator.recurrent_checkpoint_interval == 0else:@@ -1716,6 +1743,15 @@ class Job:page = seq.allocated_pages[last_page]assert page.kv_position == PAGE_SIZE+ if self.roll_ckpt and interval is None and seq.kv_position >= len(seq.input_ids):+ if self.roll_key is not None and self.roll_key != page.phash:+ cache.drop(self.roll_key)+ self.roll_key = None+ grid = (seq.kv_position - self.cached_pages * PAGE_SIZE) % self.generator.recurrent_checkpoint_interval == 0+ if not grid and page.phash not in cache:+ self.roll_key = page.phash+ cache.put(page.phash, self.recurrent_state)+ returncache.put(page.phash, self.recurrent_state)# Prevent setting the same checkpoint twice in a row if prefill ends on the first page of a chunkdiff --git a/exllamav3/model/config.py b/exllamav3/model/config.pyindex a6806e5..4cf0b5b 100644--- a/exllamav3/model/config.py+++ b/exllamav3/model/config.py@@ -56,7 +56,9 @@ class InferParams:# Stream an n-gram embedding table (PLE models, e.g. Qwen3.8-Flash-Next) from disk with# per-forward row gathers instead of loading the whole table into system RAM (tens of# GB). Set before loading the model- self.ngram_stream_from_disk = os.environ.get("EXL3_NGRAM_STREAM", "1") != "0"+ # None (env unset): NGramEmbedding picks RAM when the host has room for the table, else disk+ _ns = os.environ.get("EXL3_NGRAM_STREAM")+ self.ngram_stream_from_disk = None if _ns is None else _ns != "0"def use_mgemm(self, K: int, out_features: int, mul1: bool = False, device = None) -> bool:from ..ext import exllamav3_ext as extdiff --git a/exllamav3/model/dense_warmup.py b/exllamav3/model/dense_warmup.pynew file mode 100644index 0000000..7265303--- /dev/null+++ b/exllamav3/model/dense_warmup.py@@ -0,0 +1,66 @@+"""Load-time warm-up of the dense GEMM paths.++The first call of a dense product at a row count class not seen before in a process (more exactly: a key (n, k, rows rounded up to 256,+row pitch, out dtype) missing from the dense-GEMM tune cache, see hgemm.cu dtune) screens every rocBLAS solution on the live operands+and costs 0.15-4 s inside one request. This runs each dense Linear shape once per row class a request can produce, so the screening+happens at load. With a populated tune cache file the warm-up is a few seconds of ordinary GEMMs; on a cold cache it pays the screening.+Switch: EXL3_WARM_DENSE=0 turns it off. Results are unchanged: tuned winners are bit-exact with the untuned path.+"""+from __future__ import annotations+import os, time+import torch++SMALL_ROWS = (1, 2, 3, 4, 5, 6, 7, 8, 16, 64, 255) # untuned paths (decode, verify, short prompts): first-use of hipBLASLt / kernels+++def _dense_linears(model):+ from ..modules.linear import Linear+ seen = {}+ for m in model:+ if not isinstance(m, Linear) or ".experts." in m.key or m.out_features == 0 or m.out_features > 65536: # lm_head: only the last rows reach it+ continue+ inner = type(m.inner).__name__+ seen.setdefault((m.in_features, m.out_features, inner, str(m.out_dtype)), m)+ return list(seen.values())++[email protected]_mode()+def warm_dense_gemm(models, max_rows: int = 4096, log=print) -> dict:+ """models: iterable of Model (target, draft). max_rows: largest prefill chunk in tokens. Returns stats."""+ if os.environ.get("EXL3_WARM_DENSE", "1") == "0":+ return {"skipped": True}+ from ..modules.quant.exl3 import row_pad_pitch+ t0 = time.perf_counter()+ mem0 = torch.cuda.memory_allocated()+ torch.cuda.reset_peak_memory_stats()+ calls = 0+ nclass = (max_rows + 255) // 256+ for model in models:+ if model is None:+ continue+ for lin in _dense_linears(model):+ k = lin.in_features+ # The MTP input projection runs per stream: tokens x hc_count rows (4 x 4096 = class 64).+ mult = 4 if lin.key.endswith("mtp.fc_hidden") else 1+ rows_list = list(SMALL_ROWS) + [256 * c for c in range(1, nclass * mult + 1)]+ for rows in rows_list:+ # unpadded input (contiguous), and the row-padded input a producer gives (only above PAD_MIN_ROWS, and only+ # for activations of at most one prefill chunk: the per-stream MTP rows are never producer-padded)+ pitches = [0]+ if rows <= max_rows:+ p = row_pad_pitch(lin, k, rows, {})+ if p:+ pitches.append(p)+ for pitch in pitches:+ buf = torch.randn((rows, pitch or k), device=lin.device, dtype=torch.half).mul_(0.1)+ x = buf[:, :k] if pitch else buf+ lin.forward(x, {})+ calls += 1+ del buf, x+ torch.cuda.synchronize()+ torch.cuda.synchronize()+ peak = torch.cuda.max_memory_allocated() - mem0+ torch.cuda.empty_cache()+ st = {"seconds": time.perf_counter() - t0, "calls": calls, "peak_extra_mib": peak / 2**20}+ log(f"warm_dense_gemm: {calls} calls in {st['seconds']:.1f} s, transient peak {st['peak_extra_mib']:.0f} MiB")+ return stdiff --git a/exllamav3/model/model.py b/exllamav3/model/model.pyindex adb44bd..7b6e2b3 100644--- a/exllamav3/model/model.py+++ b/exllamav3/model/model.py@@ -509,6 +509,12 @@ class Model(Model_TPMixin, Model_LSMixin):kwargs["generator"] = Falsef = self.load_gen(*args, **kwargs)for _ in f: pass+ try:+ from ..modules import moe_fused+ moe_fused.report(self)+ except Exception as e: # noqa: BLE001 (diagnostics must never break a load)+ import sys+ print(f"[moe_fused] WARNING fused-status report failed: {e!r}", file = sys.stderr)# CPU-offloaded MoE experts: make sure the worker processes are up before the first# forward (spawned during module loading when the offload count is exact, so the child'sdiff --git a/exllamav3/modules/ablit_runtime.py b/exllamav3/modules/ablit_runtime.pyindex 6a4adf9..82ec6a5 100644--- a/exllamav3/modules/ablit_runtime.py+++ b/exllamav3/modules/ablit_runtime.py@@ -102,6 +102,8 @@ def prepare(block, device):m = _LAYER_RX.search(block.key or "")if not path or m is None:return+ if (block.key or "").split(".")[0] == "mtp" or ".mtp." in block.key:+ return # MTP drafter block (key mtp.layers.N reuses trunk numbers): never editedspec, r, per_dev = _load(path, source)L = int(m.group(1)) # from the key: MTP blocks reuse layer_idx 0..n but keep their checkpoint layer numberif L >= spec["n_layers"]:@@ -127,39 +129,57 @@ try:import triton.language as tl@triton.jit- def _project_kernel(y_ptr, r_ptr, w, H: tl.constexpr):+ def _project_kernel(y_ptr, r_ptr, w, H: tl.constexpr, BLOCK: tl.constexpr):+ # BLOCK = next power of two >= H (tl.arange needs one); lanes >= H are masked (hidden 2560 for Qwen)row = tl.program_id(0).to(tl.int64)- offs = tl.arange(0, H)- y = tl.load(y_ptr + row * H + offs)- r = tl.load(r_ptr + offs)+ offs = tl.arange(0, BLOCK)+ m = offs < H+ y = tl.load(y_ptr + row * H + offs, mask = m, other = 0.0)+ r = tl.load(r_ptr + offs, mask = m, other = 0.0)d = tl.sum(y.to(tl.float32) * r, axis = 0)- tl.store(y_ptr + row * H + offs, (y.to(tl.float32) - (w * d) * r).to(y.dtype))+ tl.store(y_ptr + row * H + offs, (y.to(tl.float32) - (w * d) * r).to(y.dtype), mask = m)except ImportError:triton = None+def _block(h: int) -> int:+ return 1 << (h - 1).bit_length()++_USE_TRITON = triton is not None and os.environ.get("EXL3_ABLIT_TORCH", "0") == "0"def warmup(device, hidden = None):"""Compile the fused kernel for both dtypes now, so no JIT happens inside a graph capture."""+ global _USE_TRITONhidden = hidden or HIDDEN_WARMif _USE_TRITON:- for dt in (torch.float32, torch.float16):- y = torch.zeros(1, hidden, dtype = dt, device = device)- _project_kernel[(1,)](y, torch.zeros(hidden, dtype = torch.float32, device = device), 0.0, H = hidden)+ try:+ for dt in (torch.float32, torch.float16):+ y = torch.zeros(1, hidden, dtype = dt, device = device)+ _project_kernel[(1,)](y, torch.zeros(hidden, dtype = torch.float32, device = device), 0.0, H = hidden, BLOCK = _block(hidden))+ except Exception as e: # compile failure: the torch path is equivalent (mv + addr_), just slower+ _USE_TRITON = False+ print(f" -- ablit runtime: triton projection kernel failed to compile for hidden {hidden} ({e!r}); using the torch path", file = sys.stderr, flush = True)HIDDEN_WARM = 4096+ROW_MODE = None # measurement aid, off by default: None = every row; ("from", k) = rows >= k only; "last" = in a multi-row forward only the last row++def project(y: torch.Tensor, w: float, r32: torch.Tensor, r16: torch.Tensor) -> torch.Tensor:"""In place: y -= w * r (r . y) over the last (hidden) dim. Returns y."""if w == 0.0:return yh = r32.shape[0]y2 = y.view(-1, h)+ if ROW_MODE is not None and y2.shape[0] > 1:+ y2 = y2[ROW_MODE[1]:] if isinstance(ROW_MODE, tuple) else y2[-1:]+ if y2.shape[0] == 0:+ return yif _USE_TRITON and y2.is_contiguous():- _project_kernel[(y2.shape[0],)](y2, r32, w, H = h)+ _project_kernel[(y2.shape[0],)](y2, r32, w, H = h, BLOCK = _block(h))elif y2.dtype == torch.float32:d = torch.mv(y2, r32)y2.addr_(d, r32, alpha = -w)diff --git a/exllamav3/modules/attention_fn/bc_attn.py b/exllamav3/modules/attention_fn/bc_attn.pyindex 36116e7..e1a1578 100644--- a/exllamav3/modules/attention_fn/bc_attn.py+++ b/exllamav3/modules/attention_fn/bc_attn.py@@ -504,7 +504,9 @@ class BCAttn:# Quantized K/V: the gather reads the packed pages through the shared QC# loaders (scales + H32 appended to the runtime args, same as the dense slots)ct = "*i32" if self.quant else "*fp16"- k_sp_split = _compile_kernel(dev, _qsa_sparse_split_kernel,+ from .qsa_triton import QSA_PIPE, QSA_PIPE_NW, _qsa_sparse_split_pipe_kernel+ use_pipe = QSA_PIPE and self.k_bits == 0 and self.v_bits == 0 and block_n == 32+ k_sp_split = _compile_kernel(dev, _qsa_sparse_split_pipe_kernel if use_pipe else _qsa_sparse_split_kernel,{"q": "*fp16", "k_cache": ct, "v_cache": ct, "block_table": "*i32","indices": "*i32", "partial_o": "*fp32", "partial_ml": "*fp32","k_len": "i32", "num_pages_per_seq": "i32", "num_splits": "i32",@@ -516,7 +518,7 @@ class BCAttn:page_size = PAGE_SIZE, head_dim = self.head_dim, K_pad = k_pad,scale = float(self.sm_scale), BLOCK_H = block_h, BLOCK_N = block_n,PAGED = 1, QCK = self.k_bits, QCV = self.v_bits),- 4, 2)+ QSA_PIPE_NW if use_pipe else 4, 2)k_sp_combine = _compile_kernel(dev, _paged_attn_decode_combine_kernel,{"partial_o": "*fp32", "partial_ml": "*fp32", "out": "*fp16", "h32": "*fp16",diff --git a/exllamav3/modules/attention_fn/dsa_triton.py b/exllamav3/modules/attention_fn/dsa_triton.pyindex f841f33..bd77923 100644--- a/exllamav3/modules/attention_fn/dsa_triton.py+++ b/exllamav3/modules/attention_fn/dsa_triton.py@@ -1727,7 +1727,7 @@ def _dsa_dec_fast_cfg(R = 1):if v == "0":return Noneif v == "1":- # microbench (scratch/decattn2/report.md): at R >= 2 (MTP verify, ~94 % of the+ # test box microbench (scratch/decattn2/report.md): at R >= 2 (MTP verify, ~94 % of the# served decode calls) BH 32 x DT 256 halves the redundant QK of the 64 x 128 dt tile,# 12 splits + pipelined index chain + num_stages 2: 0.091 -> 0.057 ms. R = 1: no# variant beats dt (all within +-5 %), so R = 1 keeps itdiff --git a/exllamav3/modules/attention_fn/mla_triton.py b/exllamav3/modules/attention_fn/mla_triton.pyindex e4d62a3..6585512 100644--- a/exllamav3/modules/attention_fn/mla_triton.py+++ b/exllamav3/modules/attention_fn/mla_triton.py@@ -1312,7 +1312,7 @@ def _unfold_cfg(R: int, v_head_dim: int):if _pf_fast():bm, bk, bn, st, nw = _PF_UNFOLD[_row_bucket(R)]return min(bm, block_m), bk, min(bn, v_head_dim), st, nw- # Default = one V tile, 2 stages, k tile halved until it fits. split-V restores the+ # Default = one V tile, 2 stages, k tile halved until it fits. REPORT-28: split-V restores the# full 128 k tile at D_v 256 but measured 1.6-1.9x slower; the best decode tile ("64,256,1,8",# 99 vs 116 us/call, bit-exact) moved full-model decode by -0.2% (noise), so it is not defaultreturn block_m, 128, v_head_dim, 2, 4diff --git a/exllamav3/modules/attention_fn/qsa_prefill.hip b/exllamav3/modules/attention_fn/qsa_prefill.hipnew file mode 100644index 0000000..1018dfa--- /dev/null+++ b/exllamav3/modules/attention_fn/qsa_prefill.hip@@ -0,0 +1,331 @@+// Qwen QSA sparse prefill attention, hand-written for gfx11.5 WMMA f16 (wave32). Replaces+// _qsa_sparse_split_kernel (splits == 1) + _paged_attn_decode_combine_kernel for fp16 paged caches.+// Same per-row arithmetic as the Triton pair (bit-identical per row): 32-key chunks in list order, scores = one fp32 WMMA chain+// over d = 0, 16, ... (A = K rows, B = q), scale, online softmax with Triton's exp lowering (log2e fma, +64 range trick, v_exp_f32,+// ldexp), l = fma(l, alpha, sum(p)) with the sum in Triton's register order, acc *= alpha, then two WMMA steps over the chunk's+// keys (A = V^T, B = p) accumulating onto acc, final acc / l with IEEE division, one rounding to fp16.+// One wave per (query row, kv head): QK and softmax are done once (Triton replicates them on 4 waves).+// Fragment layout (gfx1151): A: lane l, elem r -> A[l & 15][r]; B: lane l, elem r -> B[r][l & 15]; C: lane l, reg r -> C[2r + (l >> 4)][l & 15]+// MEMORY SAFETY: every global address comes from the IX_* macros with clamps (TOKC, PGC, row grid), every global store is guarded+// by the *_OK macros. check_qsa_hip_bounds.py parses these macros and replays all accesses (it must fail when a clamp or guard is mutated).+#include <hip/hip_runtime.h>+#include <stdint.h>++typedef _Float16 half_t;+typedef _Float16 v16h __attribute__((ext_vector_type(16)));+typedef float v8f __attribute__((ext_vector_type(8)));+typedef uint32_t v4u __attribute__((ext_vector_type(4)));++#define HD 256+#define NH 24+#define NKV 2+#define GRP 12 // q heads per kv head+#define PAGE 256+#define KPAD 2080 // 4 * block_topk + 3 rounded up to 32+#define BN 32 // keys per chunk+#define NCH (KPAD / BN)+#define LDV 264 // V LDS pitch in halves (512 B + 16 B)+#define LDQ 264+#ifndef WSYNC+#define WSYNC 1+#endif+#ifndef QG+#define QG 1+#endif+#ifndef PF+#define PF 0+#endif+#ifndef ABL+#define ABL 0+#endif+#ifndef SUMT0+#define SUMT0 0 // 0: p sum chain runs tile 0 then tile 1; 1: tile 1 then tile 0+#endif++#define RCL(r_, R_) min((r_), (R_) - 1)+#define IX_Q(r_, h_, d_, p_) (((int64_t) (r_)) * (p_) + (h_) * HD + (d_)) // q rows at pitch p_ (halves)+#define IX_O(r_, h_, d_, p_) (((int64_t) (r_)) * (p_) + (h_) * HD + (d_))+#define IX_IDX(r_, n_) (((int64_t) (r_)) * KPAD + (n_))+#define IX_BT(r_, pg_, p_) (((int64_t) (r_)) * (p_) + (pg_))+#define PGC(pg_, NP_) min(max((pg_), 0), (NP_) - 1)+#define TOKC(t_, NT_) min(max((t_), 0), (NT_) - 1)+#define IX_KV(t_, g_, d_, p_) (((int64_t) (t_)) * (p_) + (g_) * HD + (d_)) // K / V tokens at pitch p_ (halves)+#define Q_OK(h_) ((h_) < GRP)+#define O_OK(h_) ((h_) < GRP)++__device__ __forceinline__ v8f wmma(v16h a, v16h b, v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); }++// Triton tl.exp lowering on gfx11: t = x * log2e; adj = t < -126 ? 64 : 0; u = fma(x, log2e, adj); ldexp(exp2(u), t < -126 ? -64 : 0)+__device__ __forceinline__ float tl_exp(float x) {+ const float L2E = 1.44269502162933349609375f; // 0x3fb8aa3b+ float t = x * L2E;+ bool lo = (-126.0f > t);+ float u = __builtin_fmaf(x, L2E, lo ? 64.0f : 0.0f);+ float e = __builtin_amdgcn_exp2f(u);+ return __builtin_amdgcn_ldexpf(e, lo ? -64 : 0);+}++__device__ __forceinline__ v16h ld16h(const half_t* p) { // two 16 B loads (p is 16 B aligned)+ v4u a = *(const v4u*) p, b = *(const v4u*) (p + 8);+ union { v4u u[2]; v16h h; } x; x.u[0] = a; x.u[1] = b; return x.h;+}+__device__ __forceinline__ v16h ld16h_lds(const half_t* p) { return ld16h(p); }++#ifndef VB+#define VB 8+#endif+#if KS == 2+#define SVR 32 // K of the whole chunk (32 keys) in LDS, then both V halves in the same rows+#define V1R 16 // row offset of V half 1+#else+#define SVR 16+#define V1R 0+#endif+#ifndef KS+#define KS 0 // 2: both K halves staged at once (one q read) and both V halves staged together after QK; 1: K rows staged coalesced through LDS (half chunks, shared with the V tile); 0: K gathered from global per lane+#endif+// keys 16 hf_ .. 16 hf_ + 15 of src_ (K or V cache) -> LDS rows i at pitch LDV (invalid keys zero). A macro (a function spills 300 VGPRs). Locals carry the stg_ prefix:+// a macro argument that names an outer variable must never collide with them (the incident); check_expanded.py builds with -Werror=shadow -Werror=uninitialized.+#define STAGE(dst_, src_, hf_, mask_) do { \+ for (int stg_i0 = 0; stg_i0 < 16; stg_i0 += VB) { \+ v4u stg_vb[VB]; \+ _Pragma("unroll") for (int stg_j = 0; stg_j < VB; ++stg_j) { \+ const int stg_t = sTok[16 * (hf_) + stg_i0 + stg_j]; \+ stg_vb[stg_j] = (v4u) {0, 0, 0, 0}; \+ if (((mask_) >> (16 * (hf_) + stg_i0 + stg_j)) & 1u) stg_vb[stg_j] = *(const v4u*) ((src_) + IX_KV(stg_t, g, lane * 8, tok_stride)); \+ } \+ _Pragma("unroll") for (int stg_j = 0; stg_j < VB; ++stg_j) *(v4u*) ((dst_) + (stg_i0 + stg_j) * LDV + lane * 8) = stg_vb[stg_j]; \+ } } while (0)++#ifndef WPE+#define WPE 1+#endif+#if WSYNC+#define SYNC() asm volatile("s_waitcnt lgkmcnt(0)" ::: "memory") /* one wave per block: LDS ops complete in order */+#else+#define SYNC() __syncthreads()+#endif+extern "C" __global__ __launch_bounds__(32) __attribute__((amdgpu_waves_per_eu(WPE))) void qsa_pf(+ const half_t* __restrict__ q, const half_t* __restrict__ kc, const half_t* __restrict__ vc,+ const int* __restrict__ bt, const int* __restrict__ idx, half_t* __restrict__ o,+ int q_stride, int o_stride, int bt_stride, int tok_stride, int ntok, int npages, float scale)+{+ const int pid = blockIdx.x;+ const int row = pid / NKV, g = pid % NKV; // grid = R * NKV exactly+ const int lane = threadIdx.x, n = lane & 15, hh = lane >> 4;+#if !QG+ __shared__ half_t sQ[16 * LDQ];+#endif+ __shared__ half_t sV[SVR * LDV];+ __shared__ int sTok[BN];++#if !QG+ for (int i = 0; i < 16; ++i) { // q rows of this kv head -> LDS (rows >= GRP zero)+ const int c = i * 32 + lane, h = c >> 5, ch = c & 31;+ v4u val = {0, 0, 0, 0};+ if (Q_OK(h)) val = *(const v4u*) (q + IX_Q(row, g * GRP + h, ch * 8, q_stride));+ *(v4u*) (sQ + h * LDQ + ch * 8) = val;+ }+ SYNC();+#endif++ v8f acc[16];+#pragma unroll+ for (int i = 0; i < 16; ++i) acc[i] = (v8f) {0, 0, 0, 0, 0, 0, 0, 0};+ float m = -__builtin_inff(), l = 0.0f;+ const bool head_ok = n < GRP;++ // software pipeline of the index chain: idx (c + 1) is requested at the top of chunk c, its block table entry before the PV step+ int id = idx[IX_IDX(row, lane)];+ int ph = bt[IX_BT(row, PGC(max(id, 0) / PAGE, npages), bt_stride)];+ for (int c = 0; c < NCH; ++c) {+ const int id_n = idx[IX_IDX(row, min(c + 1, NCH - 1) * BN + lane)]; // last chunk: re-reads itself (unused)+ const bool kv_valid = id >= 0;+ const unsigned vmask = (unsigned) __ballot(kv_valid);+ const int idc = max(id, 0);+ int ph_n;+ if (vmask == 0u) { // chunk without valid keys: exact no-op in the Triton recurrence+ ph_n = bt[IX_BT(row, PGC(max(id_n, 0) / PAGE, npages), bt_stride)];+ id = id_n; ph = ph_n;+ continue;+ }+ SYNC();+ const int tok = kv_valid ? TOKC(ph * PAGE + idc % PAGE, ntok) : 0;+ sTok[lane] = tok;+ SYNC();++#if !(ABL & 1) && !KS+ STAGE(sV, vc, 0, vmask); // V half 0 -> LDS (invalid keys zero, like the masked Triton load)+#endif++ // scores+ v8f S[2] = {(v8f) {0, 0, 0, 0, 0, 0, 0, 0}, (v8f) {0, 0, 0, 0, 0, 0, 0, 0}};+#if KS == 2+ STAGE(sV, kc, 0, 0xffffffffu);+ STAGE(sV + 16 * LDV, kc, 1, 0xffffffffu);+ SYNC();+#pragma unroll+ for (int ks = 0; ks < 16; ++ks) {+ v16h B = (v16h) {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};+ if (Q_OK(n)) B = ld16h(q + IX_Q(row, g * GRP + n, 16 * ks, q_stride));+ S[0] = wmma(ld16h_lds(sV + n * LDV + 16 * ks), B, S[0]);+ S[1] = wmma(ld16h_lds(sV + (16 + n) * LDV + 16 * ks), B, S[1]);+ }+ SYNC();+#if !(ABL & 1)+ STAGE(sV, vc, 0, vmask); // both V halves -> LDS while softmax runs+ STAGE(sV + 16 * LDV, vc, 1, vmask);+#endif+#elif KS+#pragma unroll+ for (int kh = 0; kh < 2; ++kh) {+ STAGE(sV, kc, kh, 0xffffffffu); // all 16 keys of the half (masked later by ok[][])+ SYNC();+#pragma unroll+ for (int ks = 0; ks < 16; ++ks) {+ v16h B = (v16h) {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};+ if (Q_OK(n)) B = ld16h(q + IX_Q(row, g * GRP + n, 16 * ks, q_stride));+ S[kh] = wmma(ld16h_lds(sV + n * LDV + 16 * ks), B, S[kh]);+ }+ SYNC();+ }+#if !(ABL & 1)+ STAGE(sV, vc, 0, vmask); // V half 0 -> LDS while softmax runs+#endif+#else+ const int tk0 = sTok[n], tk1 = sTok[16 + n];+ const half_t* kp0 = kc + IX_KV(tk0, g, 0, tok_stride);+ const half_t* kp1 = kc + IX_KV(tk1, g, 0, tok_stride);+#if !(ABL & 4)+#pragma unroll+ for (int ks = 0; ks < 16; ++ks) {+#if QG+ v16h B = (v16h) {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};+ if (Q_OK(n)) B = ld16h(q + IX_Q(row, g * GRP + n, 16 * ks, q_stride));+#else+ v16h B = ld16h_lds(sQ + n * LDQ + 16 * ks);+#endif+ S[0] = wmma(ld16h(kp0 + 16 * ks), B, S[0]);+ S[1] = wmma(ld16h(kp1 + 16 * ks), B, S[1]);+ }+#else+ S[0][0] = (float) (tk0 & 255) * 0.01f; S[1][1] = (float) (tk1 & 255) * 0.01f;+#endif+#endif // KS++ // softmax+ float s[2][8], mx = -__builtin_inff();+ bool ok[2][8];+#pragma unroll+ for (int t = 0; t < 2; ++t)+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const int j = 16 * t + 2 * r + hh;+ ok[t][r] = head_ok && ((vmask >> j) & 1u);+ s[t][r] = ok[t][r] ? S[t][r] * scale : -__builtin_inff();+ mx = fmaxf(mx, s[t][r]);+ }+ mx = fmaxf(mx, __shfl_xor(mx, 16));+ const float m_new = fmaxf(m, mx);+ const float m_exp = (m_new == -__builtin_inff()) ? 0.0f : m_new;+ float p[2][8];+#pragma unroll+ for (int t = 0; t < 2; ++t)+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const float e = tl_exp(s[t][r] - m_exp);+ p[t][r] = ok[t][r] ? e : 0.0f;+ }+ const float alpha = (m == -__builtin_inff()) ? 0.0f : tl_exp(m - m_exp);+ float sum;+#if SUMT0 == 0+ sum = p[0][0] + p[0][1];+#pragma unroll+ for (int r = 2; r < 8; ++r) sum = sum + p[0][r];+#pragma unroll+ for (int r = 0; r < 8; ++r) sum = sum + p[1][r];+#else+ sum = p[1][0] + p[1][1];+#pragma unroll+ for (int r = 2; r < 8; ++r) sum = sum + p[1][r];+#pragma unroll+ for (int r = 0; r < 8; ++r) sum = sum + p[0][r];+#endif+ sum = sum + __shfl_xor(sum, 16);+ l = __builtin_fmaf(l, alpha, sum);+ m = m_new;++ // p fragments (B operand: lane head n, elem r = key 16 ks + r); both half-waves hold the full 16 keys+ v16h pf[2];+#pragma unroll+ for (int t = 0; t < 2; ++t)+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const half_t own = (half_t) p[t][r];+ union { half_t h; uint16_t u; } cv; cv.h = own;+ const uint16_t other = (uint16_t) __shfl_xor((int) cv.u, 16);+ union { uint16_t u; half_t h; } oc; oc.u = other;+ pf[t][2 * r] = hh == 0 ? own : oc.h;+ pf[t][2 * r + 1] = hh == 0 ? oc.h : own;+ }++#if PF+ ph_n = bt[IX_BT(row, PGC(max(id_n, 0) / PAGE, npages), bt_stride)];+#endif+ SYNC(); // V half 0 written by all lanes+#if (ABL & 2)+ acc[0][0] += pf[0][0] + pf[1][3]; acc[1][1] += alpha;+#else+#pragma unroll+ for (int nt = 0; nt < 16; ++nt) {+#pragma unroll+ for (int i = 0; i < 8; ++i) acc[nt][i] = acc[nt][i] * alpha;+ v16h A;+#pragma unroll+ for (int r = 0; r < 16; ++r) A[r] = sV[r * LDV + 16 * nt + n];+ acc[nt] = wmma(A, pf[0], acc[nt]);+ }+#endif+#if KS != 2+ SYNC();+#if !(ABL & 1)+ STAGE(sV, vc, 1, vmask);+#endif+ SYNC();+#endif+#if !(ABL & 2)+#pragma unroll+ for (int nt = 0; nt < 16; ++nt) {+ v16h A;+#pragma unroll+ for (int r = 0; r < 16; ++r) A[r] = sV[(V1R + r) * LDV + 16 * nt + n];+ acc[nt] = wmma(A, pf[1], acc[nt]);+ }+#endif+ SYNC(); // sV / sTok free for the next chunk+#if !PF+ ph_n = bt[IX_BT(row, PGC(max(id_n, 0) / PAGE, npages), bt_stride)];+#endif+ id = id_n; ph = ph_n;+ }++ // epilogue (num_splits == 1 combine, same expression order as _paged_attn_decode_combine_kernel)+ const float m_safe = (m == -__builtin_inff()) ? 0.0f : m;+ const float w = (m == -__builtin_inff()) ? 0.0f : tl_exp(m - m_safe);+ const float lw = l * w;+ const float l_sum = __builtin_fmaf(l, w, 0.0f);+ const float den = (lw != 0.0f) ? l_sum : 1.0f;+ half_t* sO = sV; // (16 heads, HD) at pitch LDV+#pragma unroll+ for (int nt = 0; nt < 16; ++nt)+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const float a = __builtin_fmaf(acc[nt][r], w, 0.0f);+ sO[n * LDV + 16 * nt + 2 * r + hh] = (half_t) (a / den);+ }+ SYNC();+ for (int i = 0; i < 12; ++i) {+ const int c = i * 32 + lane, h = c >> 5, ch = c & 31;+ if (O_OK(h)) *(v4u*) (o + IX_O(row, g * GRP + h, ch * 8, o_stride)) = *(const v4u*) (sO + h * LDV + ch * 8);+ }+}diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.pynew file mode 100644index 0000000..db80fc2--- /dev/null+++ b/exllamav3/modules/attention_fn/qsa_prefill_hip.py@@ -0,0 +1,85 @@+"""Loader for qsa_prefill.hip (one wave per (row, kv head)). Same call shape as qsa_prefill.qsa_prefill_attend (fp16, shared or per-row block table)."""+import ctypes, hashlib, os, re, shutil, subprocess+import torch+_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qsa_prefill.hip")+_state = {}++def _hipcc():+ for p in (os.environ.get("EXL3_HIPCC"), os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),+ shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):+ if p and os.path.isfile(p): return p+ raise RuntimeError("qsa_prefill_hip: hipcc not found (set EXL3_HIPCC)")++def proof_tag(src_path, defs):+ return hashlib.sha1((open(src_path).read() + "\0" + " ".join(sorted(defs.split()))).encode()).hexdigest()[:16]++def require_proof(src_path, defs):+ """no GPU build of a kernel variant without a passing CPU proof of exactly this source + defs (check_expanded.py --mark writes the marker)"""+ d = os.environ.get("QSA_PROOF_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "qsa_proof"))+ if not os.path.isfile(os.path.join(d, proof_tag(src_path, defs) + ".ok")):+ raise RuntimeError(f"qsa_prefill_hip: no CPU bounds proof for {src_path} defs={defs!r} (tag {proof_tag(src_path, defs)}); run check_expanded.py --mark first")++def compile_hsaco(defs = "", arch = "gfx1151", src_path = None, extra = ()):+ src_path = src_path or _SRC+ require_proof(src_path, defs)+ src = open(src_path, "rb").read()+ flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + list(extra) + [x if x.startswith("-") else f"-D{x}" for x in defs.split()]+ gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")+ if os.path.isdir(gcc): flags.append(f"--gcc-install-dir={gcc}")+ tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]+ cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"qsa_pf_{arch}_{tag}.hsaco")+ if not os.path.isfile(cache):+ os.makedirs(os.path.dirname(cache), exist_ok = True)+ tmp = cache + f".{os.getpid()}.tmp"+ r = subprocess.run([_hipcc(), *flags, "-o", tmp, src_path], capture_output = True, text = True)+ if r.returncode: raise RuntimeError(r.stderr[-3000:])+ os.replace(tmp, cache)+ return cache++def hsaco_stats(path):+ """vgpr / spill / lds from the code object metadata (no GPU)."""+ t = ""+ for tool in ("llvm-readelf", "llvm-readobj"):+ p = shutil.which(tool) or os.path.join(os.path.dirname(_hipcc()), "..", "lib", "llvm", "bin", tool)+ if os.path.isfile(p):+ t = subprocess.run([p, "--notes", path], capture_output = True, text = True).stdout; break+ g = lambda k: (int(re.search(k + r":\s+(\d+)", t).group(1)) if re.search(k + r":\s+(\d+)", t) else -1)+ return dict(vgpr = g(r"\.vgpr_count"), spill = g(r"\.vgpr_spill_count"), lds = g(r"\.group_segment_fixed_size"))++def _load(defs = ""):+ if defs in _state: return _state[defs]+ cache = compile_hsaco(defs, torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])+ p = os.path.join(os.path.dirname(torch.__file__), "lib", "libamdhip64.so")+ if not os.path.isfile(p): # the copy torch already loaded+ p = next(l.split()[-1] for l in open("/proc/self/maps") if "libamdhip64" in l)+ lib = ctypes.CDLL(p)+ torch.cuda.init()+ mod = ctypes.c_void_p()+ if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0: raise RuntimeError("qsa_prefill_hip: hipModuleLoad failed")+ fn = ctypes.c_void_p()+ if lib.hipModuleGetFunction(ctypes.byref(fn), mod, b"qsa_pf") != 0: raise RuntimeError("qsa_prefill_hip: no function")+ lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3+ _state["lib"] = lib; _state[defs] = fn; _state["mod", defs] = mod+ return fn++def qsa_prefill_hip(q, k, v, indices, sm_scale, block_table, page_size, out = None, defs = ""):+ R, H, hd = q.shape+ assert (H, hd, k.shape[1], page_size, indices.shape[1]) == (24, 256, 2, 256, 2080), "qsa_prefill_hip: Qwen shape only"+ assert q.dtype == k.dtype == v.dtype == torch.half and q.stride(2) == 1 and q.stride(1) == hd+ assert k.stride(1) == hd and k.stride(2) == 1 and k.stride() == v.stride() and indices.is_contiguous() and indices.dtype == torch.int32+ assert indices.shape[0] == R and R >= 1 and R <= 4096 * 4+ assert q.stride(0) % 8 == 0 and q.data_ptr() % 16 == 0 and k.data_ptr() % 16 == 0 and v.data_ptr() % 16 == 0 and k.stride(0) % 8 == 0+ if out is None: out = torch.empty((R, H, hd), dtype = torch.half, device = q.device)+ assert out.stride(2) == 1 and out.stride(1) == hd and out.stride(0) % 8 == 0 and out.data_ptr() % 16 == 0+ assert block_table.is_contiguous() and block_table.dtype == torch.int32+ bt_stride = 0 if block_table.dim() == 1 else block_table.shape[1]+ npages = block_table.shape[-1]+ ntok = k.shape[0]+ assert v.shape[0] == ntok+ fn = _load(defs)+ cargs = [ctypes.c_void_p(a.data_ptr()) for a in (q, k, v, block_table, indices, out)] + \+ [ctypes.c_int(x) for x in (q.stride(0), out.stride(0), bt_stride, k.stride(0), ntok, npages)] + [ctypes.c_float(sm_scale)]+ params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])+ r = _state["lib"].hipModuleLaunchKernel(fn, R * 2, 1, 1, 32, 1, 1, 0, torch.cuda.current_stream().cuda_stream, params, None)+ if r != 0: raise RuntimeError(f"qsa_prefill_hip: launch failed ({r})")+ return outdiff --git a/exllamav3/modules/attention_fn/qsa_triton.py b/exllamav3/modules/attention_fn/qsa_triton.pyindex 878aeaf..5411c41 100644--- a/exllamav3/modules/attention_fn/qsa_triton.py+++ b/exllamav3/modules/attention_fn/qsa_triton.py@@ -250,6 +250,97 @@ def _qsa_sparse_split_kernel(tl.store(partial_ml + ml_base + rows * 2 + 1, l)+def _qsa_pipe_load(indices, block_table, k_cache, v_cache, batch, kv_head, K_pad, num_pages_per_seq, n0, n_end,+ offs_d, n_kv_heads: tl.constexpr, page_size: tl.constexpr, head_dim: tl.constexpr,+ BLOCK_N: tl.constexpr, PAGED: tl.constexpr):+ """One BLOCK_N tile of the gather: index list, page translation, K^T and V tiles (fp16 cache). Masked+ lanes read nothing; the values are the ones the plain kernel loads."""+ offs_n = n0 + tl.arange(0, BLOCK_N)+ idx = tl.load(indices + batch * K_pad + offs_n, mask = offs_n < n_end, other = -1)+ valid_n = (idx >= 0) & (offs_n < n_end)+ idx_c = tl.where(valid_n, idx, 0)+ if PAGED:+ phys = tl.load(block_table + batch * num_pages_per_seq + idx_c // page_size, mask = valid_n, other = 0)+ tok = phys * page_size + idx_c % page_size+ else:+ tok = idx_c+ k_ptrs = k_cache + ((tok[None, :] * n_kv_heads + kv_head) * head_dim + offs_d[:, None])+ k_tile = tl.load(k_ptrs, mask = valid_n[None, :], other = 0.0)+ v_ptrs = v_cache + ((tok[:, None] * n_kv_heads + kv_head) * head_dim + offs_d[None, :])+ v_tile = tl.load(v_ptrs, mask = valid_n[:, None], other = 0.0)+ return k_tile, v_tile, valid_n++[email protected](do_not_specialize = ["k_len", "num_pages_per_seq", "num_splits", "split_len"])+def _qsa_sparse_split_pipe_kernel(+ q, k_cache, v_cache, block_table, indices, partial_o, partial_ml,+ k_len, num_pages_per_seq, num_splits, split_len,+ k_scales, v_scales, h32, # dead (fp16 cache only), kept so the launch signature matches+ n_q_heads: tl.constexpr, n_kv_heads: tl.constexpr, page_size: tl.constexpr, head_dim: tl.constexpr,+ K_pad: tl.constexpr, scale: tl.constexpr, BLOCK_H: tl.constexpr, BLOCK_N: tl.constexpr,+ PAGED: tl.constexpr = 1, QCK: tl.constexpr = 0, QCV: tl.constexpr = 0,+):+ """_qsa_sparse_split_kernel with the next tile's gather loads issued before the current tile's+ arithmetic (software pipelined, fp16 cache). The per-tile operation order (scores, online softmax, P.V,+ tile after tile) is the plain kernel's, so partial_o / partial_ml are bit-identical."""+ pid = tl.program_id(0)+ split = tl.program_id(1)+ group_size = n_q_heads // n_kv_heads+ h_blocks = tl.cdiv(group_size, BLOCK_H)+ h_block = pid % h_blocks+ bh = pid // h_blocks+ batch = bh // n_kv_heads+ kv_head = bh - batch * n_kv_heads+ rows = tl.arange(0, BLOCK_H)+ row_h_local = h_block * BLOCK_H + rows+ q_head = kv_head * group_size + row_h_local+ valid_row = row_h_local < group_size+ offs_d = tl.arange(0, head_dim)+ q_base = (batch * n_q_heads + q_head) * head_dim+ q_tile = tl.load(q + q_base[:, None] + offs_d[None, :], mask = valid_row[:, None], other = 0.0)+ n_start = split * split_len+ n_end = tl.minimum(n_start + split_len, k_len)+ m = tl.full((BLOCK_H,), -float("inf"), tl.float32)+ l = tl.full((BLOCK_H,), 0.0, tl.float32)+ acc = tl.zeros((BLOCK_H, head_dim), tl.float32)++ k_cur, v_cur, valid_cur = _qsa_pipe_load(indices, block_table, k_cache, v_cache, batch, kv_head, K_pad,+ num_pages_per_seq, n_start, n_end, offs_d, n_kv_heads, page_size, head_dim, BLOCK_N, PAGED)+ for n0 in range(n_start, n_end, BLOCK_N):+ k_nxt, v_nxt, valid_nxt = _qsa_pipe_load(indices, block_table, k_cache, v_cache, batch, kv_head, K_pad,+ num_pages_per_seq, n0 + BLOCK_N, n_end, offs_d, n_kv_heads, page_size, head_dim, BLOCK_N, PAGED)+ scores = tl.dot(q_tile, k_cur) * scale+ valid = valid_row[:, None] & valid_cur[None, :]+ scores = tl.where(valid, scores, -float("inf"))+ m_new = tl.maximum(m, tl.max(scores, axis = 1))+ m_exp = tl.where(m_new == -float("inf"), 0.0, m_new)+ p = tl.exp(scores - m_exp[:, None])+ p = tl.where(valid, p, 0.0)+ alpha = tl.where(m == -float("inf"), 0.0, tl.exp(m - m_exp))+ l = l * alpha + tl.sum(p, axis = 1)+ acc = acc * alpha[:, None] + tl.dot(p.to(v_cur.dtype), v_cur)+ m = m_new+ k_cur = k_nxt+ v_cur = v_nxt+ valid_cur = valid_nxt++ if split < num_splits:+ po_base = (pid * num_splits + split) * BLOCK_H * head_dim+ tl.store(partial_o + po_base + rows[:, None] * head_dim + offs_d[None, :], acc)+ ml_base = (pid * num_splits + split) * BLOCK_H * 2+ tl.store(partial_ml + ml_base + rows * 2, m)+ tl.store(partial_ml + ml_base + rows * 2 + 1, l)+++import os+# software-pipelined gather split kernel (fp16 cache), 8 warps; EXL3_QSA_PIPE=1 enables it (default off: no served gain measured)+QSA_PIPE = os.environ.get("EXL3_QSA_PIPE", "0") not in ("", "0")+QSA_PIPE_NW = 8+_QSA_BN = int(os.environ.get("EXL3_QSA_BN", "32"))+_QSA_NW = int(os.environ.get("EXL3_QSA_NW", "4"))+_QSA_NS = int(os.environ.get("EXL3_QSA_NS", "1"))+_sm_counts = {}def _get_sms(dev):@@ -258,6 +349,25 @@ def _get_sms(dev):return _sm_counts[dev.index]+# the split count sets the reduction tree (partials per row, then the combine). It used to depend on R+# (programs = R * kv_heads * h_blocks), so a batched verify launch (R = 2..8) reduced a different tree than the R = 1+# launch of plain decode: one fp16 step apart. For R <= ROWINV_MAX the plan is computed as if R = 1 (row-invariant:+# every row runs the same operation order as the single-row launch). EXL3_QSA_ROWINV=0 restores the old plan.+ROWINV = {"on": os.environ.get("EXL3_QSA_ROWINV", "1") not in ("", "0"), "max_rows": 8}+++def qsa_split_plan(R: int, programs_per_row: int, K_pad: int, BLOCK_N: int, sms: int, rowinv: bool | None = None):+ """(splits, split_len) of the gathered sparse launch. Pure integer arithmetic (CPU-checkable)."""+ if rowinv is None:+ rowinv = ROWINV["on"]+ eff_rows = 1 if (rowinv and R <= ROWINV["max_rows"]) else R+ programs = eff_rows * programs_per_row+ splits = max(1, min(2 * sms // programs, -(-K_pad // (4 * BLOCK_N)), 128))+ per_split = -(-K_pad // splits)+ split_len = -(-per_split // BLOCK_N) * BLOCK_N+ return splits, split_len++def qsa_sparse_attend_rows(q: torch.Tensor, # (R, n_q_heads, head_dim) fp16, normed + ropedk: torch.Tensor, # (rows, n_kv_heads, head_dim) fp16 (paged: flat cache view)@@ -290,7 +400,7 @@ def qsa_sparse_attend_rows(h32 = qgroup = H // kvhBLOCK_H = 16- BLOCK_N = 32+ BLOCK_N = _QSA_BNh_blocks = triton.cdiv(group, BLOCK_H)programs = R * kvh * h_blocksK_pad = indices.shape[1]@@ -300,9 +410,7 @@ def qsa_sparse_attend_rows(and indices.is_contiguous() and k_scales.is_contiguous() and v_scales.is_contiguous()assert not paged or (block_table.is_contiguous() and block_table.shape[0] == R)- splits = max(1, min(2 * _get_sms(dev) // programs, -(-K_pad // (4 * BLOCK_N)), 128))- per_split = -(-K_pad // splits)- split_len = -(-per_split // BLOCK_N) * BLOCK_N+ splits, split_len = qsa_split_plan(R, kvh * h_blocks, K_pad, BLOCK_N, _get_sms(dev))partial_o = torch.empty((programs * splits * BLOCK_H * hd,), dtype = torch.float, device = dev)partial_ml = torch.empty((programs * splits * BLOCK_H * 2,), dtype = torch.float, device = dev)o = torch.empty((R, H, hd), dtype = torch.half, device = dev)@@ -310,7 +418,8 @@ def qsa_sparse_attend_rows(# Triton JIT launches on the CURRENT device; with a model split across GPUs this# layer's device need not be currentwith torch.cuda.device(dev):- _qsa_sparse_split_kernel[(programs, splits)](+ use_pipe = QSA_PIPE and k_bits == 0 and v_bits == 0 and BLOCK_N == 32+ (_qsa_sparse_split_pipe_kernel if use_pipe else _qsa_sparse_split_kernel)[(programs, splits)](q, k, v, block_table if paged else indices, indices, partial_o, partial_ml,K_pad, block_table.shape[1] if paged else 0, splits, split_len,k_scales, v_scales, h32,@@ -318,7 +427,7 @@ def qsa_sparse_attend_rows(head_dim = hd, K_pad = K_pad, scale = float(sm_scale),BLOCK_H = BLOCK_H, BLOCK_N = BLOCK_N, PAGED = 1 if paged else 0,QCK = k_bits, QCV = v_bits,- num_warps = 4, num_stages = 2,+ num_warps = QSA_PIPE_NW if use_pipe else _QSA_NW, num_stages = _QSA_NS,)_paged_attn_decode_combine_kernel[(programs,)](partial_o, partial_ml, o, h32, splits, partial_ml,diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.pyindex 2504e09..d556310 100644--- a/exllamav3/modules/attention_fn/triton_paged.py+++ b/exllamav3/modules/attention_fn/triton_paged.py@@ -1090,6 +1090,7 @@ def paged_attn_triton_decode(n_kv_heads_override: int | None = None,num_warps: int = 4,num_stages: int = 2,+ split_batch: int | None = None, # batch size the split count is derived from (default: bsz)) -> torch.Tensor:"""Flash-decoding paged attention for short queries: the kv sequence is split acrossprograms (sized from the block table, so no host sync on cache_seqlens) and reduced in a@@ -1172,7 +1173,8 @@ def paged_attn_triton_decode(if dev not in _decode_sm_count:_decode_sm_count[dev] = torch.cuda.get_device_properties(q.device).multi_processor_counttarget = 2 * _decode_sm_count[dev]- num_splits = max(1, min(target // programs, triton.cdiv(max_k_len, 4 * block_n), 128))+ programs_split = programs if split_batch is None else programs // bsz * split_batch+ num_splits = max(1, min(target // programs_split, triton.cdiv(max_k_len, 4 * block_n), 128))split_len = triton.cdiv(triton.cdiv(max_k_len, num_splits), block_n) * block_nif num_splits > 1:@@ -1212,6 +1214,48 @@ def paged_attn_triton_decode(return out+_rows_arange = {}+++def paged_attn_triton_decode_rows(+ q: torch.Tensor, # [1, R, n_q_heads, head_dim]+ k: torch.Tensor, # [1, R, n_kv_heads, head_dim]+ v: torch.Tensor,+ k_cache: torch.Tensor,+ v_cache: torch.Tensor,+ block_table: torch.Tensor, # [1, pages]+ cache_seqlens: torch.Tensor, # [1]+ **kw,+) -> torch.Tensor:+ """R rows of a verify block in ONE attention launch (plus one append launch), bitwise equal to R+ batch-1 paged_attn_triton_decode calls with cache_seqlens + i. Row i becomes batch entry i of a+ q_len 1 call with its own seqlen (cache_seqlens + i), sharing the sequence's pages. The split count+ is the one a batch-1 call would pick (split_batch = 1), so every row sees the same tiling and the+ same reduction order. All rows' K/V are appended first (the batch-1 loop appends row i before+ attending, and row i never reads past cache_seqlens + i + 1, so the extra rows are masked)."""+ _, R, n_q_heads, head_dim = q.shape+ n_kv_heads = k.shape[2]+ dev = q.device+ ar = _rows_arange.get((dev, R))+ if ar is None:+ ar = _rows_arange[(dev, R)] = torch.arange(R, dtype = torch.int32, device = dev)+ seqs = cache_seqlens.to(torch.int32) + ar+ bt = block_table.expand(R, -1).contiguous()+ num_pages_per_seq = bt.shape[1]+ update_block_d = triton.next_power_of_2(head_dim)+ with torch.cuda.device(dev):+ _paged_kv_update_kernel[(R, n_kv_heads, triton.cdiv(head_dim, update_block_d))](+ k.reshape(R, 1, n_kv_heads, head_dim), v.reshape(R, 1, n_kv_heads, head_dim), k_cache, v_cache, bt, seqs,+ num_pages_per_seq, 1, n_kv_heads, k_cache.shape[1], head_dim, update_block_d,+ num_warps = 2, num_stages = 3,+ )+ o = paged_attn_triton_decode(+ q.reshape(R, 1, n_q_heads, head_dim), None, None, k_cache, v_cache, bt, seqs,+ pre_appended_len = 1, split_batch = 1, **kw,+ )+ return o.view(1, R, n_q_heads, head_dim)++def fn_triton_paged_attn_decode(args: AttnArgs) -> torch.Tensor | None:if (args.is_varlen() ordiff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.pyindex c384e70..7ea8d27 100644--- a/exllamav3/modules/attn.py+++ b/exllamav3/modules/attn.py@@ -7,7 +7,7 @@ from ..util.tensor import get_for_device, to2from . import Module, Linear, RMSNorm, LayerNormfrom ..constants import PAGE_SIZEfrom .multilinear import MultiLinear, SlicedMultiLinear-from .quant.exl3 import MAX_BSZN_GEMV_R+from .quant.exl3 import MAX_BSZN_GEMV_R, row_pad_pitchfrom ..ext import exllamav3_ext as extfrom ..model.model_tp_alloc import TPAllocationfrom ..util import profile_opt@@ -17,6 +17,7 @@ from .attention_fn.bc_attn import bc_attn_enable as _bc_attn_enable, build_bc_at# Sliced Q/K/V(/G) projection bundle at decode (one mgemm over equal-width column slices);# EXL3_QKV_SLICE=0 falls back to the pairwise K/V and Q/G bundles_qkv_slice_enable = os.environ.get("EXL3_QKV_SLICE", "1") != "0"+_QKV_IG_MULTI = os.environ.get("EXL3_ATTN_QKV_IG_MULTI", "1") != "0" # (q|gate, k, v one launch)def _sim_kvq_inplace(t: torch.Tensor, bits: int | None, compand_a: float):@@ -684,9 +685,53 @@ class Attention(Module):self._dec_qkv = linsreturn lins+ def _dec_qkv_ig_linears(self):+ """q (interleaved q|gate per head) / k / v Linears when one exl3_dec_gemv_multi launch can replace their+ three forwards, else None."""+ lins = getattr(self, "_dec_qkv_ig", False)+ if lins is False:+ from .mla_attn import dec_proj_ok, dec_proj_shapes+ lins = None+ cand = [self.q_proj, self.k_proj] + ([] if self.use_k_as_v else [self.v_proj])+ if self.interleaved_gate and self.g_proj is None and all(l is not None for l in cand) and \+ all(dec_proj_ok(l) for l in cand) and dec_proj_shapes(cand):+ lins = cand+ self._dec_qkv_ig = lins+ return lins++ def _project_qkv_ig_dec(self, x: torch.Tensor, params: dict, bsz: int, q_len: int):+ rows = bsz * q_len+ if rows > MAX_BSZN_GEMV_R or x.dtype != torch.half or x.shape[-1] != self.q_proj.in_features or \+ not x.is_contiguous() or "capture" in params or "ovr" in params:+ return None+ if rows > 1 and not (params.get("dflash_verify") and hasattr(ext, "exl3_dec_gemv_r_multi") and+ os.environ.get("EXL3_VERIFY_GEMV_R", os.environ.get("EXL3_DEC_MOE_UNION", "0")) != "0"):+ return None+ lins = self._dec_qkv_ig_linears()+ if lins is None:+ return None+ from .mla_attn import dec_proj_multi+ outs = dec_proj_multi(lins, x, rows)+ qg = outs[0].view(bsz, q_len, -1)+ k = outs[1].view(bsz, q_len, -1)+ v = outs[2].view(bsz, q_len, -1) if len(outs) > 2 else k+ if self.head_dim % 8 == 0 and qg.dtype == torch.half:+ q = torch.empty((bsz, q_len, self.num_q_heads, self.head_dim), dtype = torch.half, device = qg.device)+ g = torch.empty((bsz, q_len, self.num_q_heads * self.head_dim), dtype = torch.half, device = qg.device)+ ext.deinterleave_qg(qg, q, g, self.head_dim)+ else:+ q, g = torch.chunk(qg.view(bsz, q_len, -1, self.head_dim * 2), 2, dim = -1)+ g = g.reshape(bsz, q_len, -1)+ return self.finish_qkv(q, k, v, g, bsz, q_len, params)+def project_qkv(self, x: torch.Tensor, params: dict) -> tuple:bsz, q_len, dim = x.shape+ if _QKV_IG_MULTI and self.interleaved_gate:+ r = self._project_qkv_ig_dec(x, params, bsz, q_len)+ if r is not None:+ return r+# Batch-1 decode: q, k and v in one exl3_dec launch (both Hadamard stages fused)if bsz * q_len == 1 and x.dtype == torch.half and dim == self.q_proj.in_features and \"capture" not in params and "ovr" not in params:@@ -704,7 +749,7 @@ class Attention(Module):v = outs[2] if len(outs) > 2 else kreturn self.finish_qkv(q, k, v, None, bsz, q_len, params)- # DFlash verify (R rows): same fused launch as the bsz==1 case above,+ # DFlash verify (R rows, REPORT-17): same fused launch as the bsz==1 case above,# generalized to R rows via exl3_dec_gemv_r_multi -- see sliding_attn.py's identical# branch for why the fused multi-matrix call (not per-Linear dec_gemv_r) is required for# bit-exactness (shared strips_total -> shared ktw/kbs with the batch-1 launch). This is@@ -899,7 +944,19 @@ class Attention(Module):# Drop the zero lanes V was padded into so o_proj sees num_q_heads * v_head_dimo = o.view(bsz, seqlen, self.num_q_heads, self.head_dim)[..., : self.v_head_dim]o = o.reshape(bsz, seqlen, self.num_q_heads * self.v_head_dim).contiguous()- x = self.o_proj.forward(o, params)+ o_dt = None+ if params.get("pfe_y_half") and os.environ.get("EXL3_PFE_OPROJ", "1") == "1" and \+ "capture" not in params and "quant_preserve" not in params:+ from .quant import exl3 as _exl3+ m = self.o_proj+ rows = o.numel() // o.shape[-1]+ if _exl3._f32_via_f16 and rows > max(_exl3.AUTO_RECONSTRUCT_THRESHOLD, _exl3._f32_via_f16_min_rows - 1) \+ and type(m.inner).__name__ == "LinearEXL3" and m.inner.bias is None \+ and not self.config.infer_params.no_reconstruct and not params.get("reconstruct") \+ 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+ x = self.o_proj.forward(o, params, o_dt)return x@@ -1229,36 +1286,74 @@ class Attention(Module):if qsa_sparse:qsa_layer.update_kv_direct(cache_seqlens, block_table, k, v, seqlen)- o = self.qsa_indexer.sparse_attend(qsa_layer, self, q, qsa_q_idx, block_table, qsa_seqlens_cpu)+ o = self.qsa_indexer.sparse_attend_verify(qsa_layer, self, q, qsa_q_idx, block_table, qsa_seqlens_cpu)else:# QSA dense regime: the past is bounded by the sparse threshold, which lets the# quantized-cache prefill size its staging to the window instead of the job's pagesmax_kv_len = int(qsa_seqlens_cpu.max().item()) if qsa_seqlens_cpu is not None else None- o = attn_dispatch(- q = q,- k = k,- v = v,- cache = cache,- cache_idx = self.layer_idx,- cache_instance = params.get("layer_instance"),- block_table = block_table,- cache_seqlens = cache_seqlens,- causal = causal,- sm_scale = self.sm_scale,- window_size = self.window_arg(),- softcap = self.logit_softcapping,- non_causal_spans = non_causal_spans,- sinks = self.sinks,- dispatch_cache = self.dispatch_cache,- max_kv_len = max_kv_len,- v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,- )+ if (+ 1 < seqlen <= MAX_BSZN_GEMV_R and non_causal_spans is None and+ os.environ.get("EXL3_VERIFY_ATTN_LOOP", "0") != "0"+ ):+ # Row-invariant verify: the R-row paged decode tiles the KV span from the batch's single+ # cache_seqlens/q_len, a different float order than R batch-1 calls. Run the exact+ # batch-1 call per row (each appends its own K/V at cache_seqlens + i and attends i + 1 keys).+ o = torch.cat([attn_dispatch(+ q = q[:, i:i + 1],+ k = k[:, i:i + 1],+ v = v[:, i:i + 1],+ cache = cache,+ cache_idx = self.layer_idx,+ cache_instance = params.get("layer_instance"),+ block_table = block_table,+ cache_seqlens = cache_seqlens + i,+ causal = causal,+ sm_scale = self.sm_scale,+ window_size = self.window_arg(),+ softcap = self.logit_softcapping,+ non_causal_spans = None,+ sinks = self.sinks,+ dispatch_cache = self.dispatch_cache,+ max_kv_len = max_kv_len,+ v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,+ ) for i in range(seqlen)], dim = 1)+ else:+ o = attn_dispatch(+ q = q,+ k = k,+ v = v,+ cache = cache,+ cache_idx = self.layer_idx,+ cache_instance = params.get("layer_instance"),+ block_table = block_table,+ cache_seqlens = cache_seqlens,+ causal = causal,+ sm_scale = self.sm_scale,+ window_size = self.window_arg(),+ softcap = self.logit_softcapping,+ non_causal_spans = non_causal_spans,+ sinks = self.sinks,+ dispatch_cache = self.dispatch_cache,+ max_kv_len = max_kv_len,+ v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,+ )if self.headwise_gate:if self.gate_softplus: ext.mul_softplus_broadcast_(o, g)else: ext.mul_sigmoid_broadcast_(o, g)o = o.reshape((bsz, seqlen, self.num_q_heads * self.head_dim))- if self.full_gate or self.interleaved_gate: ext.mul_sigmoid_(o, g)+ pitch = 0+ if (self.full_gate or self.interleaved_gate) and self.v_head_dim == self.head_dim and not self.headwise_gate and \+ o.dtype == torch.half and g.dtype == torch.half and o.is_contiguous() and g.is_contiguous() and \+ getattr(ext, "mul_sigmoid_pad", None) is not None:+ pitch = row_pad_pitch(self.o_proj, o.shape[-1], o.numel() // o.shape[-1], params)+ if pitch:+ # same fp16 product as mul_sigmoid_, written at a padded row pitch (o_proj reads it at full rate)+ o2 = torch.empty((o.numel() // o.shape[-1], pitch), dtype = torch.half, device = o.device)[:, :o.shape[-1]].view(o.shape)+ ext.mul_sigmoid_pad(o, g, o2, pitch)+ o = o2+ elif self.full_gate or self.interleaved_gate:+ ext.mul_sigmoid_(o, g)o = self.project_o(o, bsz, seqlen, params)return odiff --git a/exllamav3/modules/block_graph.py b/exllamav3/modules/block_graph.pyindex 3394d28..c47e044 100644--- a/exllamav3/modules/block_graph.py+++ b/exllamav3/modules/block_graph.py@@ -139,7 +139,7 @@ class _BlockGraphSlot:def _verify_union_dev_ok(x: torch.Tensor, params: dict, draft: bool = False) -> bool:"""R-row DFlash/MTP verify through exl3_dec_moe_union with the device-built unique table- (EXL3_DEC_MOE_UNION_DEV=1): no host sync, so the block is capturable. The host+ (EXL3_DEC_MOE_UNION_DEV=1, REPORT-28): no host sync, so the block is capturable. The hosttable path (UNION_DEV=0) copies the picks to the CPU and must stay eager."""rows = x.shape[0] * x.shape[1]return ((BLOCK_GRAPH_DRAFT >= 2 if draft else BLOCK_GRAPH_VERIFY) and@@ -214,7 +214,7 @@ class BlockGraphRunner:attn = self.block.attnmlp = self.block.mlp# Batch-1 decode MoE (exl3_dec_router + exl3_dec_moe, GLM-5.3: E = 288, K 2): both launch- # sync-free on device tables, so a rows == 1 block is capturable+ # sync-free on device tables, so a rows == 1 block is capturable (REPORT-31)dec_moe_ok = BLOCK_GRAPH_DEC_MOE and getattr(mlp, "support_dec_moe", False) and \x.dim() >= 2 and (x.shape[0] * x.shape[1] == 1 or _verify_union_dev_ok(x, params, draft))if not isinstance(mlp, BlockSparseMLP) or \diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex f9b1928..2ea332f 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -23,7 +23,7 @@ from .block_sparse_mlp_routing import (routing_std, routing_std_bias, routing_ds3, routing_dots, routing_sqrtsp, routing_sqrtsp_hash,_HIP_ROUTER_HIDDEN, _HIP_ROUTER_EXPERTS, _HIP_ROUTER_TOP_K,_HIP_GROUPED_MAX_ROWS, _HIP_PREFILL_MIN_ROWS, _HIP_PREFILL_MAX_ROWS, _HIP_PREFILL_MAX_EXPERT_ROWS,- _hip_grouped_rows_eligible, _hip_prefill_rows_eligible, _prepare_hip_router_gate_t,+ _hip_grouped_rows_eligible, _hip_prefill_rows_eligible, _prepare_hip_router_gate_t, _MOE_VALU,)# Row capacity of the fused MoE kernel's per-group temp buffers (experts with more assigned@@ -78,11 +78,15 @@ def _hip_wmma_workspace(device, assignments: int, hidden: int, interm: int, expeif ws is None or any(a < b for a, b in zip(ws["cap"], need)):cap = tuple(max(a, b) for a, b in zip(ws["cap"], need)) if ws is not None else needa, h, i, e = cap+ # The grouped GEMM's last tile of an expert reads/writes up to a tile (<= 128 rows) past the+ # last assignment row: a tight tail faults when the allocator places the buffer at a segment end+ # (seen on Qwen3.8-Flash-Next once the surrounding temporaries stopped padding the pool)+ slack = 128 * max(h, i)_hip_wmma_ws[device] = Nonews = {"cap": cap,- "gu_had": torch.empty((2 * a * h,), dtype = torch.half, device = device),- "gu_out": torch.empty((2 * a * i,), dtype = torch.half, device = device),+ "gu_had": torch.empty((2 * a * h + slack,), dtype = torch.half, device = device),+ "gu_out": torch.empty((2 * a * i + slack,), dtype = torch.half, device = device),"offsets": torch.empty((e + 1,), dtype = torch.long, device = device),"inverse": torch.empty((a,), dtype = torch.long, device = device),"tiles": torch.empty((a // 64 + e + 1,), dtype = torch.int, device = device),@@ -560,6 +564,21 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return [[g + u, d]]+ def _hip_k3_prefill_selected(self, rows: int) -> bool:+ """Dispatch switch between the legacy K=3 prefill kernel (exl3_moe_gfx12_k3_prefill, 17..2048 rows) and the+ grouped WMMA GEMM (mpw2) for layers whose experts are all K=3. Read per call (one process can flip it).+ EXL3_HIP_GROUPED_MOE_PREFILL: 1 = always legacy (the earlier default), 0 = never legacy,+ unset / auto = mpw2 wherever it is eligible, legacy only below the WMMA row threshold (verify rows with+ EXL3_HIP_PREFILL_MIN_ROWS=2, rows 17..31) or when MPW_KERN=1 pins the old grouped GEMM.+ Both kernels are equally accurate against a float64 reference; mpw2 is 2.6x faster per layer."""+ v = os.environ.get("EXL3_HIP_GROUPED_MOE_PREFILL", "auto")+ if v == "0": return False+ if v == "1": return True+ return not (+ self.support_hip_wmma and rows >= _HIP_WMMA_MIN_ROWS and+ os.environ.get("EXL3_MOE_WMMA", "1") != "0" and os.environ.get("MPW_KERN", "2") != "1"+ )+def _ensure_hip_prefill_buffers(self, num_tokens):"""Allocate the gfx12 prefill workspace sized to the actual chunk so chunk512serving never reserves the full 2048-row envelope. Grows only if a larger@@ -793,7 +812,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):)# Codebook: exl3_dec_moe takes one flag for all three projections (the kernel is# templated on the codebook, not per projection), so the layer needs a uniform one.- # mul1 and mcg both decode; anything else leaves the fused path off.+ # mul1 and mcg both decode (REPORT-21); anything else leaves the fused path off.if cbs[0] == cbs[1] == cbs[2] and cbs[0] in ((True, False), (False, True)):self.dec_moe_mcg = bool(cbs[0][0])self.support_dec_moe = self.support_dec_moe and self.dec_moe_mcg is not None@@ -802,7 +821,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):self.dec_moe_act = g_tensor_cache.get(self.device, (self.num_experts_per_tok, self.intermediate_size_padded), torch.half, "dec_moe_act")self.dec_shf_setup()- # R-row union MoE (exl3_dec_moe_union): shared, per-device+ # R-row union MoE (REPORT-16/17, exl3_dec_moe_union): shared, per-device# workspace (like dec_workspace) sized for the worst case (MAX_BSZN rows, this# layer's topk/H/I) and reused across layers -- forward calls are stream-ordered# so a later layer never races an earlier one's still-in-flight kernel.@@ -827,8 +846,8 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):multi.K in (2, 2.5, 3, 4) and (multi.mul1 != multi.mcg)for multi in (self.multi_gate, self.multi_up, self.multi_down)) and self.multi_gate.K == self.multi_up.K- # Codebook: mpw_gemm is templated on it and takes one flag for all three projections,- # so the layer needs a uniform codebook. Unknown (neither mul1 nor mcg,+ # Codebook: mpw_gemm is templated on it and takes one flag for all three projections+ # (REPORT-22), so the layer needs a uniform codebook. Unknown (neither mul1 nor mcg,# or mixed) leaves the path off.wmma_cbs = {(m.mul1, m.mcg) for m in (self.multi_gate, self.multi_up, self.multi_down)}if len(wmma_cbs) == 1:@@ -1334,7 +1353,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- # R-row union MoE with the unique-expert table built on device (no host sync),+ # REPORT-28: 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 loopsunion_dev = os.environ.get("EXL3_DEC_MOE_UNION_DEV", "0") != "0"# V2 selects the device-built unique-expert table without enabling the legacy@@ -1407,7 +1426,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# gfx11.5 batch-1 fused decode (exl3_dec_moe): two launches for the whole routed sumelif (- bsz == 1 and self.support_dec_moe and self.tp_mode is None and+ bsz == 1 and self.support_dec_moe and self.tp_mode is None and not (_MOE_VALU and self.support_hip_grouped) andy.dtype == torch.half and y.is_contiguous() andselected_experts.dtype == torch.long and routing_weights.dtype == torch.half andselected_experts.numel() == self.num_experts_per_tok and@@ -1487,15 +1506,16 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return resfinal_hidden_states = self.dec_moe_out.view(eshape)- # R-row union decode (exl3_dec_moe_union), DFlash verify: bit-exact vs- # bsz independent batch-1 exl3_dec_moe calls under shared routing --+ # R-row union decode (REPORT-16/17, exl3_dec_moe_union), DFlash verify: bit-exact vs+ # bsz independent batch-1 exl3_dec_moe calls under shared routing (REPORT-16 Sec 1) --# each unique expert across the bsz rows' picks is decoded once and applied to every row# that picked it in the exact batch-1 per-row arithmetic order. Opt-in (default off):- # Measured: no clear speed win yet at R=1 or R=6-8 (host-side unique/assign+ # REPORT-16 measured no clear speed win yet at R=1 or R=6-8 (host-side unique/assign# build dominates), only R=2..5; EXL3_DEC_MOE_UNION=1 to use it anyway (e.g. to get a# bit-exact verify path even before that's fixed).elif (1 < bsz <= MAX_BSZN and self.support_dec_moe and self.tp_mode is None and+ not (_MOE_VALU and self.support_hip_grouped and bsz <= 8) andhasattr(ext, "exl3_dec_moe_union") and(union_dev or union_v2 or os.environ.get("EXL3_DEC_MOE_UNION", "0") != "0") and params.get("dflash_verify") andy.dtype == torch.half and y.is_contiguous() and@@ -1591,7 +1611,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):_hip_prefill_rows_eligible(bsz) andy.dtype == torch.half and y.is_contiguous() andselected_experts.is_contiguous() and routing_weights.is_contiguous() and- os.environ.get("EXL3_HIP_GROUPED_MOE_PREFILL", "1") != "0" and+ self._hip_k3_prefill_selected(bsz) andos.environ.get("EXL3_GEMV", "1") != "0" andnot params.get("activate_all_experts") andnot params.get("reconstruct") and not params.get("autosplit_measure")@@ -1987,7 +2007,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# Shared expertsif self.shared_experts and not bc_sh_exp:- y = self.shared_experts.forward(x, params)+ 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:@@ -2013,7 +2033,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return final_hidden_states- def dec_norm_route(self, norm, xa: torch.Tensor, r: torch.Tensor, params: dict):+ def dec_norm_route(self, norm, xa: torch.Tensor, r: torch.Tensor, params: dict, rows: int = 1):"""Batch-1 decode: MLP pre-norm (r += xa, y = norm(r)) fused with the router in oneexl3_dec_router_norm launch. Returns y (fp16), routing left in params["dec_routed"]; Nonewhen the fused path does not apply (the caller then runs the norm itself)."""@@ -2024,7 +2044,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):self.routing_fn is routing_dots and self.routing_gate is not None andself.router_pre_norm is None and self.routed_pre_norm is None and self.latent_in is None andself.routing_device is None and not self.alt_residual_channel and self.cpu_split_first is None and- xa.numel() == self.hidden_size and r.numel() == self.hidden_size and+ xa.numel() == rows * self.hidden_size and r.numel() == rows * self.hidden_size andxa.dtype in (torch.half, torch.float) and r.dtype == torch.float andxa.is_contiguous() and r.is_contiguous() andnot norm.span_heads and norm.groups == 1 and@@ -2032,11 +2052,13 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):norm.key not in params.get("export_state_norm_keys", ())):return None- y = getattr(self, "dec_norm_y", None)- if y is None or y.device != xa.device:- y = self.dec_norm_y = torch.empty((1, self.hidden_size), dtype = torch.half, device = xa.device)+ buf = "dec_norm_y" if rows == 1 else "dec_norm_y_rows"+ y = getattr(self, buf, None)+ if y is None or y.device != xa.device or y.shape[0] != rows:+ y = torch.empty((rows, self.hidden_size), dtype = torch.half, device = xa.device)+ setattr(self, buf, y)cfg = self.routing_cfg- if not _dec_router_ok(1, cfg, y, params):+ if not _dec_router_ok(1, cfg, y[:1], params):return Nonefrom .quant.exl3 import dec_workspacebias = getattr(cfg, "dec_bias", False)@@ -2046,10 +2068,19 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):cfg.dec_bias = biasscratch, counters = dec_workspace(xa.device)scale = cfg.routed_scaling_factor if cfg.routed_scaling_factor is not None else 1.0- ext.exl3_dec_router_norm(xa.view(1, -1), r.view(1, -1), norm.weight, norm.rms_norm_eps, norm.constant_bias,- norm.constant_scale, y, cfg.gate_tensor, bias, cfg.selected_experts_bsz1,- cfg.routing_weights_bsz1, scratch, counters, float(scale))- params["dec_routed"] = (cfg.selected_experts_bsz1, cfg.routing_weights_bsz1)+ if rows == 1:+ sel, wts = cfg.selected_experts_bsz1, cfg.routing_weights_bsz1+ else:+ # One launch for all rows (grid.y = row): each row is bitwise the single-row launch+ sel = getattr(self, "dec_sel_rows", None)+ if sel is None or sel.shape[0] != rows or sel.device != xa.device:+ sel = self.dec_sel_rows = torch.empty((rows, self.num_experts_per_tok), dtype = torch.long, device = xa.device)+ self.dec_wts_rows = torch.empty((rows, self.num_experts_per_tok), dtype = torch.half, device = xa.device)+ wts = self.dec_wts_rows+ ext.exl3_dec_router_norm(xa.view(rows, -1), r.view(rows, -1), norm.weight, norm.rms_norm_eps, norm.constant_bias,+ norm.constant_scale, y, cfg.gate_tensor, bias, sel,+ wts, scratch, counters, float(scale))+ params["dec_routed"] = (sel, wts)return y.view(xa.shape)@@ -2058,7 +2089,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):literal batch-1 exl3_dec_router_norm launch (same kernel, same args, just row j's data),so row j of the returned y and of dec_routed's (selected, weights) is bit-identical towhat plain batch-1 decode would produce stepping through row j alone -- this is what- A review found missing: the row-invariance probe exercised+ REPORT-16 Sec 6 found missing: that report's row-invariance probe exercisedexl3_dec_router (unfused), not the exl3_dec_router_norm/dec_norm_route path real decodeactually takes, which is why it saw a k-order mismatch and (for one cell) a 1.22e-4weight mismatch -- neither is possible here, since this never runs a second, independent@@ -2073,7 +2104,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# dec_norm_route's raw-buffer return is consumed immediately by the caller either way.return self.dec_norm_route(norm, xa[0], r[0], params)# R>1 (DFlash verify): gated by the same flag as the union MoE kernel it feeds, so- # EXL3_DEC_MOE_UNION=0 reproduces the exact pre-union behavior (generic norm+router,+ # EXL3_DEC_MOE_UNION=0 reproduces the exact pre-REPORT-17 behavior (generic norm+router,# dedup MoE) for a clean A/B against it -- R sequential kernel launches here is a real# per-layer cost even though it's bit-exact, not a free win to force on unconditionally.# Also refuse above MAX_BSZN: prefill calls this with R = chunk size (hundreds+), where@@ -2086,6 +2117,10 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):r.view(R, -1)except RuntimeError:return None+ if os.environ.get("EXL3_DEC_NORM_ROUTE_ROWS", "1") != "0":+ # One launch (grid.y = row), bitwise the R single-row launches below. None when the fused+ # path does not apply: the caller then runs the generic norm + router.+ return self.dec_norm_route(norm, xa.view(R, -1), r.view(R, -1), params, R)ys, sels, wtss = [], [], []for i in range(R):sub = dict(params)diff --git a/exllamav3/modules/block_sparse_mlp_routing.py b/exllamav3/modules/block_sparse_mlp_routing.pyindex 53af225..2f3023e 100644--- a/exllamav3/modules/block_sparse_mlp_routing.py+++ b/exllamav3/modules/block_sparse_mlp_routing.py@@ -12,6 +12,15 @@ from dataclasses import dataclassfrom ..util.device_copy import to_devicefrom ..ext import exllamav3_ext as extfrom ..util.tensor import g_tensor_cache+++def _pad_rows(y):+ """router logits GEMM input at a row pitch that is not a multiple of 2 KiB (same values; a no-op when not a hazard)."""+ if y.dim() == 2:+ from .quant.exl3 import pad_copy_in+ return pad_copy_in(y, y.shape[1])+ return y+from ..tokenizer.mm_embedding import FIRST_MM_EMBEDDING_INDEXROUTING_CACHE_ROWS = 128@@ -102,7 +111,16 @@ _HIP_PREFILL_MAX_ROWS = 2048_HIP_PREFILL_MAX_EXPERT_ROWS = _HIP_PREFILL_MAX_ROWS * _HIP_ROUTER_TOP_K+# EXL3_MOE_VALU=1: the VALU decode matvec (K2/K4 experts) serves every row count 1..8 through the grouped/dedup+# launches, one reduction order for all of them: plain decode (R=1) and verify rounds (R>1) give identical bits. It+# therefore bypasses the batch-1 fused kernel, the union path and the prefill-kernel yield below. Default off.+_MOE_VALU = os.environ.get("EXL3_MOE_VALU", "0") != "0"+_MOE_VALU_MAX_ROWS = 8++def _hip_grouped_rows_eligible(rows: int, prefill_available: bool = True) -> bool:+ if _MOE_VALU and rows <= _MOE_VALU_MAX_ROWS:+ return 1 <= rows <= min(_HIP_GROUPED_MAX_ROWS, _MOE_VALU_MAX_ROWS)# Yield to the expert-grouped prefill kernel once it claims this row count,# otherwise the per-(row,expert) decode kernel would take it first and# re-read duplicate expert weights. When no prefill kernel serves this model@@ -189,7 +207,7 @@ def _hip_router_buffers(cfg, rows):)def _routing_std_torch(cfg, y, params, include_bias = False):- router_logits = torch.matmul(y, cfg.gate_tensor)+ router_logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)router_logits_f = router_logits.float()if include_bias and cfg.router_bias is not None:router_logits_f = router_logits_f + cfg.router_bias.float()@@ -257,7 +275,7 @@ def routing_std(bsz, cfg, y, params):else:activate_all_experts = params.get("activate_all_experts")if activate_all_experts:- router_logits = torch.matmul(y, cfg.gate_tensor)+ router_logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)routing_weights = torch.softmax(router_logits, dim = -1)selected_experts = (torch.arange(start = 0, end = cfg.num_experts, dtype = torch.long, device = y.device)@@ -302,9 +320,9 @@ def routing_std_bias(bsz, cfg, y, params):)return cfg.selected_experts_bsz1, cfg.routing_weights_bsz1if cfg.router_bias is not None:- router_logits = torch.addmm(cfg.router_bias, y, cfg.gate_tensor)+ router_logits = torch.addmm(cfg.router_bias, _pad_rows(y), cfg.gate_tensor)else:- router_logits = torch.matmul(y, cfg.gate_tensor)+ router_logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)if params.get("activate_all_experts"):routing_weights = torch.softmax(router_logits.float(), dim = -1).half()selected_experts = (@@ -320,7 +338,7 @@ def routing_std_bias(bsz, cfg, y, params):# TODO: Optimize top_k groups (for DS3)def routing_ds3(bsz, cfg, y, params):activate_all_experts = params.get("activate_all_experts")- router_logits = torch.matmul(y, cfg.gate_tensor)+ router_logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)scores = router_logits.sigmoid()scores_for_choice = scores.view(-1, cfg.num_experts)@@ -435,9 +453,9 @@ def routing_dots(bsz, cfg, y, params):# cold at E=288 prefill, bit-exact (scratch/pfbig1/mb_dense.py)if cfg.gate_tensor_t is None:cfg.gate_tensor_t = cfg.gate_tensor.T.contiguous()- logits = torch.matmul(y, cfg.gate_tensor_t.T)+ logits = torch.matmul(_pad_rows(y), cfg.gate_tensor_t.T)else:- logits = torch.matmul(y, cfg.gate_tensor)+ logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)scores = torch.sigmoid(logits.float())if params.get("activate_all_experts"):routing_weights = scores@@ -471,7 +489,7 @@ def routing_dots(bsz, cfg, y, params):else:activate_all_experts = params.get("activate_all_experts")if activate_all_experts:- router_logits = torch.matmul(y, cfg.gate_tensor)+ router_logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)routing_weights = router_logits.sigmoid().float()if cfg.e_score_correction_bias is not None:routing_weights = routing_weights + cfg.e_score_correction_bias.unsqueeze(0).float()diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.pyindex 53e639e..34a0808 100644--- a/exllamav3/modules/gated_delta_net.py+++ b/exllamav3/modules/gated_delta_net.py@@ -8,6 +8,7 @@ from . import Module, Linearfrom ..ext import exllamav3_ext as extfrom ..model.model_tp_alloc import TPAllocationfrom .gated_rmsnorm import GatedRMSNorm+from .quant.exl3 import row_pad_pitch as _row_pad_pitch_MIDCKPT_STREAM = None # EXL3_MIDCHUNK_CKPT=2 side stream for the checkpoint D2Hfrom ..cache import Cache@@ -18,6 +19,13 @@ import os# Sliced qkv+z projection bundle at decode for the split-projection GDN (Qwen3.5 / Qwen3.8 style):# one mgemm over equal-width column slices, see attn.py. EXL3_QKV_SLICE=0 disables it_qkv_slice_enable = os.environ.get("EXL3_QKV_SLICE", "1") != "0"+_QKVZ_DEC_MULTI = os.environ.get("EXL3_GDN_QKVZ_MULTI", "1") != "0" # (qkv+z one launch)+# EXL3_QWD_AB (default 0 until proven) folds the fp16 b / a projections, and with a bf16 dt_bias / fp32 a_log also+# gated_delta_net_fused_op_2 (beta, g), into the qkv|z launch as extra blocks (bit-identical to the separate launches);+# EXL3_QWD_AB_FIRST=1 puts those blocks first in the grid+_QWD_AB_FLAGS = 1 if os.environ.get("EXL3_QWD_AB_FIRST", "0") != "0" else 0+def _qwd_ab_on() -> bool: # read per call so a served A/B run can flip it (serve_ab arm switch)+ return os.environ.get("EXL3_QWD_AB", "0") != "0"from ..model.model_tp_shared import TPTensorWrapperfrom .gated_delta_net_fn import causal_conv1d_update, gated_delta_rule_fnfrom ..cache.recurrent import (@@ -83,6 +91,9 @@ def mp_cache_recurrent_rewind(local_context: dict, cache_id: int, slot: int, las_dispatch_rewind_jobs(_collect_rewind_jobs(layers, slot, last_history, num_tokens))+_ABCAT = os.environ.get("EXL3_QWD4_ABCAT", "1") != "0"+QWD3 = {"skip": 0} # harness-only kill test: 1 = reuse the last b / a outputs (skip the skinny launches), 2 = also reuse beta / g. NOT bit-identical, never committed.+class GDNState:def __init__(@@ -898,6 +909,105 @@ class GatedDeltaNet(Module):core_attn_out, core_attn_out_f, qkv_xh, o_xh,)+ def _dec_qkvz_linears(self):+ """(qkv_proj, z_proj) when one exl3_dec_gemv_multi launch can replace their two forwards (same K, mcg and+ input width, no bias), else None. one launch instead of two, one grid of both matrices."""+ lins = getattr(self, "_dec_qkvz", False)+ if lins is False:+ from .mla_attn import dec_proj_ok, dec_proj_shapes+ lins = None+ if self.qkv_proj is not None and self.z_proj is not None and self.qkvz_proj is None:+ cand = (self.qkv_proj, self.z_proj)+ if all(dec_proj_ok(l) for l in cand) and dec_proj_shapes(cand):+ lins = cand+ self._dec_qkvz = lins+ return lins++ def project_qkvz_dec(self, x: torch.Tensor, params: dict, bsz: int, seqlen: int):+ """Decode qkv + z in ONE exl3_dec launch (both Hadamard stages inside): batch 1, or the R-row verify+ launch (dflash_verify). Returns (qkv, z) with the Linears' shapes and dtype, or None to fall back."""+ rows = bsz * seqlen+ if rows > 8 or x.dtype != torch.half or "capture" in params or "ovr" in params or not x.is_contiguous():+ return None+ if rows > 1 and not (params.get("dflash_verify") and os.environ.get("EXL3_VERIFY_GEMV_R", "0") != "0"+ and hasattr(ext, "exl3_dec_gemv_r_multi")):+ return None+ lins = self._dec_qkvz_linears()+ if lins is None or x.shape[-1] != lins[0].in_features:+ return None+ from .mla_attn import dec_proj_multi+ qkv, z = dec_proj_multi(lins, x, rows)+ return (qkv.view(bsz, seqlen, -1), z.view(bsz, seqlen, -1))+++ def _ab_cat(self, x: torch.Tensor, params: dict, bsz: int, seqlen: int):+ """decode b and a skinny projections in ONE launch (ext.skinny_cat_w, same per-column reduction order as the two+ separate skinny launches, bit-identical). Returns (b, a) fp32 [bsz, seqlen, heads] or None to fall back. EXL3_QWD4_ABCAT=0 = off."""+ ok = getattr(self, "_ab_cat_ok_v", None)+ if ok is None:+ mods = (self.b_proj, self.a_proj)+ ok = (hasattr(ext, "skinny_cat_w") and not self.kda and+ all(m is not None and m.quant_type == "fp16" and type(m.inner).__name__ == "LinearFP16" and m.inner.bias is None and+ m.inner._pinned_store is None 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 and m.out_features == self.num_v_heads and+ m.inner.weight.is_contiguous() and m.inner.weight.dtype == torch.half and m.inner.out_dtype == torch.float for m in mods))+ self._ab_cat_ok_v = ok+ if not ok or bsz * seqlen != 1 or x.dtype != torch.half or not x.is_contiguous() or "capture" in params or "ovr" in params:+ return None+ h = self.num_v_heads+ b = torch.empty((bsz, seqlen, h), dtype = torch.float, device = x.device)+ a = torch.empty((bsz, seqlen, h), dtype = torch.float, device = x.device)+ ext.skinny_cat_w(x.view(1, -1), [self.b_proj.inner.weight, self.a_proj.inner.weight], [b.view(1, h), a.view(1, h)])+ return b, a++ def _qwd_ab_ok(self) -> bool:+ ok = getattr(self, "_qwd_ab_ok_v", None)+ if ok is None:+ lins = self._dec_qkvz_linears()+ mods = (self.b_proj, self.a_proj)+ ok = (lins is not None and hasattr(ext, "exl3_dec_gemv_x") and not self.kda and+ all(m is not None and m.quant_type == "fp16" and type(m.inner).__name__ == "LinearFP16" and m.inner.bias is None and+ m.inner._pinned_store is None 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 and m.out_features == self.num_v_heads and+ m.inner.weight.is_contiguous() and m.inner.weight.dtype == torch.half and+ m.inner.weight.shape[0] == lins[0].in_features and m.inner.out_dtype == torch.float for m in mods) and+ int(round(lins[0].inner.K * 2)) == 10 and lins[0].inner.in_features // 128 <= 64)+ self._qwd_ab_ok_v = ok+ return ok++ def project_qkvz_ab_dec(self, x: torch.Tensor, params: dict, bsz: int, seqlen: int):+ """qkv + z + b + a (+ beta / g) in ONE launch (exl3_dec_gemv_x), batch 1 only. Returns (qkv, z, b, a, None, None) with b, a fp32+ [bsz, seqlen, num_v_heads], or (qkv, z, None, None, beta, g) when the gate math rides along, or None to fall back."""+ if bsz * seqlen != 1 or x.dtype != torch.half or "capture" in params or "ovr" in params or not x.is_contiguous():+ return None+ if not self._qwd_ab_ok():+ return None+ lins = self._dec_qkvz_linears()+ if x.shape[-1] != lins[0].in_features:+ return None+ from .quant.exl3 import dec_workspace+ scratch, counters = dec_workspace(x.device)+ outs = [torch.empty((1, l.inner.out_features), dtype = l.inner.default_out_dtype, device = x.device) for l in lins]+ h = self.num_v_heads+ gate = h % 16 == 0 and self.dt_bias.dtype == torch.bfloat16 and self.a_log.dtype == torch.float and \+ self.dt_bias.is_contiguous() and self.a_log.is_contiguous() and self.dt_bias.numel() == h and self.a_log.numel() == h+ if gate:+ o1 = torch.empty((1, h), dtype = torch.bfloat16, device = x.device)+ o2 = torch.empty((1, h), dtype = torch.float, device = x.device)+ gargs = [self.dt_bias, self.a_log]+ else:+ o1 = torch.empty((1, h), dtype = torch.float, device = x.device)+ o2 = torch.empty((1, h), dtype = torch.float, device = x.device)+ gargs = []+ ext.exl3_dec_gemv_x(+ x.reshape(1, -1), [l.inner.trellis for l in lins], [l.inner.suh for l in lins], [l.inner.svh for l in lins],+ outs, scratch, counters, [float(l.inner.K) for l in lins], bool(lins[0].inner.mcg), _QWD_AB_FLAGS,+ [self.b_proj.inner.weight, self.a_proj.inner.weight], [o1, o2], gargs, float(self.beta_scale))+ qkv, z = outs[0].view(bsz, seqlen, -1), outs[1].view(bsz, seqlen, -1)+ if gate:+ return (qkv, z, None, None, o1.view(bsz, seqlen, -1), o2.view(bsz, seqlen, -1))+ return (qkv, z, o1.view(bsz, seqlen, -1), o2.view(bsz, seqlen, -1), None, None)+def project_qkvz_sliced(self, x: torch.Tensor, bsz: int, seqlen: int) -> tuple:"""qkv and z projections as one sliced mgemm (fp32 outputs, like the Linears); m <= 32"""mq = self.multi_qkvz@@ -963,6 +1073,26 @@ class GatedDeltaNet(Module):)+ def _pfe_f16_out(self, m, x: torch.Tensor, params: dict, env: str) -> bool:+ # EXL3_PFE_QKVZ / EXL3_PFE_OPROJ (default 1): request this projection's output in fp16 instead of fp32.+ # Where the fp32 output is an fp16 GEMM plus a widen (_f32_via_f16, HIP reconstruct path) the fp16+ # 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 .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):+ return False+ if type(m.inner).__name__ != "LinearEXL3" or m.inner.bias is not None:+ return False+ if rows <= _exl3.AUTO_RECONSTRUCT_THRESHOLD or self.config.infer_params.no_reconstruct \+ or params.get("reconstruct"):+ return False+ return (+ 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+ )+def _kda_qkv_f16(self, x: torch.Tensor) -> bool:# EXL3_KDA_QKV_F16=1 (default): take qkv_proj's output in fp16 instead of fp32. On HIP the fp32 output# is an fp16 GEMM plus a widen (_f32_via_f16), so the fp16 buffer holds the same values; the@@ -1427,27 +1557,62 @@ class GatedDeltaNet(Module):else:g = -decay * torch.where(gf > 20.0, gf, torch.log1p(torch.exp(gf)))else:- if getattr(self, "multi_qkvz", None) is not None and bsz * seqlen <= 32:+ # EXL3_QWG_ABFIRST=1 runs the two skinny b / a projections before qkv / z (independent kernels, bit-exact)+ ab_first = os.environ.get("EXL3_QWG_ABFIRST", "0") == "1"+ if ab_first:+ b = self.b_proj.forward(x, params)+ a = self.a_proj.forward(x, params)+ qzab = self.project_qkvz_ab_dec(x, params, bsz, seqlen) if (_QKVZ_DEC_MULTI and not ab_first and _qwd_ab_on()) else None+ qz = None if qzab is not None else (self.project_qkvz_dec(x, params, bsz, seqlen) if _QKVZ_DEC_MULTI else None)+ if qzab is not None:+ qkv, z, b, a, beta_ab, g_ab = qzab+ elif qz is not None:+ qkv, z = qz+ elif getattr(self, "multi_qkvz", None) is not None and bsz * seqlen <= 32:qkv, z = self.project_qkvz_sliced(x, bsz, seqlen)else:- qkv = self.qkv_proj.forward(x, params)- z = self.z_proj.forward(x, params)+ qkv_dt = torch.half if self._pfe_f16_out(self.qkv_proj, x, params, "EXL3_PFE_QKVZ") else None+ z_dt = torch.half if self._pfe_f16_out(self.z_proj, x, params, "EXL3_PFE_QKVZ") else None+ qkv = self.qkv_proj.forward(x, params, qkv_dt)+ z = self.z_proj.forward(x, params, z_dt)z = z.view(bsz, seqlen, self.num_v_heads, self.v_head_dim)- b = self.b_proj.forward(x, params)- a = self.a_proj.forward(x, params)-- mixed_qkv = qkv.transpose(1, 2).to(torch.bfloat16).contiguous()-- beta = torch.empty((bsz, seqlen, self.num_v_heads), dtype = torch.bfloat16, device = self.device)- g = torch.empty((bsz, seqlen, self.num_v_heads), dtype = torch.float, device = self.device)+ if not ab_first and qzab is None:+ _c = getattr(self, "_qd3_ba", None)+ if QWD3["skip"] and _c is not None and _c[0] == x.shape:+ b, a = _c[1], _c[2]+ else:+ ba = self._ab_cat(x, params, bsz, seqlen) if QWD3.get("abcat", _ABCAT) else None+ if ba is not None:+ b, a = ba+ else:+ b = self.b_proj.forward(x, params)+ a = self.a_proj.forward(x, params)+ self._qd3_ba = (x.shape, b, a)++ # EXL3_GDN_FUSED_CAST=1 (default): the conv casts the fp16 transposed view in-kernel (bit-equal),+ # replacing two full passes (strided cast + transpose copy) over qkv+ if os.environ.get("EXL3_GDN_FUSED_CAST", "1") != "0":+ mixed_qkv = qkv.transpose(1, 2)+ else:+ mixed_qkv = qkv.transpose(1, 2).to(torch.bfloat16).contiguous()- ext.gated_delta_net_fused_op_2(- b, a,- self.dt_bias,- self.a_log,- beta, g,- self.beta_scale- )+ if qzab is not None and beta_ab is not None:+ beta, g = beta_ab, g_ab+ else:+ _c = getattr(self, "_qd3_bg", None)+ if QWD3["skip"] >= 2 and _c is not None and _c[0] == x.shape:+ beta, g = _c[1], _c[2]+ else:+ beta = torch.empty((bsz, seqlen, self.num_v_heads), dtype = torch.bfloat16, device = self.device)+ g = torch.empty((bsz, seqlen, self.num_v_heads), dtype = torch.float, device = self.device)+ ext.gated_delta_net_fused_op_2(+ b, a,+ self.dt_bias,+ self.a_log,+ beta, g,+ self.beta_scale+ )+ self._qd3_bg = (x.shape, beta, g)# Mid-chunk recurrent checkpoints (EXL3_MIDCHUNK_CKPT, set by the job via params): split conv + KDA# core at the given rows, chaining conv state and S, and save the state at each split row@@ -1502,11 +1667,20 @@ class GatedDeltaNet(Module):if lr_gaf is not None:core_attn_out = self._kda_gb_norm(core_attn_out, lr_gaf, params)else:- core_attn_out = self.norm.forward(core_attn_out, params, gate = z)+ o_pitch = 0+ _pad_ok = getattr(ext.gated_rms_norm, "pad_ok", None)+ if _pad_ok is not None and not self.kda and not self.norm.gate_first and \+ _pad_ok(core_attn_out, self.norm.weight, self.norm.out_dtype or torch.half, z, self.norm.groups,+ 1 if self.norm.gate_activation == "sigmoid" else 0):+ o_pitch = _row_pad_pitch(self.o_proj, self.num_v_heads * self.v_head_dim,+ core_attn_out.numel() // (self.num_v_heads * self.v_head_dim), params)+ core_attn_out = self.norm.forward(core_attn_out, params, gate = z, out_pitch = o_pitch)core_attn_out = core_attn_out.view(bsz, seqlen, self.num_v_heads * self.v_head_dim)- # Output projection- x = self.o_proj.forward(core_attn_out, params)+ # Output projection (fp16 when the block's residual apply reads fp16: params["pfe_y_half"])+ o_dt = torch.half if params.get("pfe_y_half") and \+ self._pfe_f16_out(self.o_proj, core_attn_out, params, "EXL3_PFE_OPROJ") else None+ x = self.o_proj.forward(core_attn_out, params, o_dt)# TP reductionif self.tp_reduce:diff --git a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.pyindex 60776e5..83476fd 100644--- a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py+++ b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py@@ -1,3 +1,4 @@+import osimport torchfrom ...ext import exllamav3_ext as extfrom ...util.tensor import get_for_device, buffered_arange@@ -181,7 +182,9 @@ def gated_delta_rule_fn(assert not g_cumsum, "g_cumsum is only valid on the KDA chunk path"# Chunked ruleif seqlen >= num_v_heads and not history:- from ...vendor.fla import chunk_gated_delta_rule+ from ...vendor.fla import chunk_gated_delta_rule, chunk_gated_delta_rule_pf+ # EXL3_GDN_PF (default 1): strided q / k / v straight from the conv output, no contiguous copies, no single-tensor cat (bit-equal)+ pf = os.environ.get("EXL3_GDN_PF", "1") == "1"q, k, v = torch.split(mixed_qkv, [k_dim, k_dim, v_dim], dim = -1)q = q.view(bsz, seqlen, -1, k_head_dim)@@ -195,19 +198,24 @@ def gated_delta_rule_fn(core_attn_out = []for i, s in enumerate(recurrent_slots_cpu.tolist()):state = recurrent_state[s, 0].unsqueeze(0) if recurrent_state is not None else None- core_attn, new_state = chunk_gated_delta_rule(- q[i:i + 1], k[i:i + 1], v[i:i + 1],- g = g[i:i + 1],- beta = beta[i:i + 1],- initial_state = state,- output_final_state = save_state,- use_qk_l2norm_in_kernel = True,- )+ if pf:+ core_attn, new_state = chunk_gated_delta_rule_pf(+ q[i:i + 1], k[i:i + 1], v[i:i + 1], g = g[i:i + 1], beta = beta[i:i + 1],+ initial_state = state, output_final_state = save_state)+ else:+ core_attn, new_state = chunk_gated_delta_rule(+ q[i:i + 1], k[i:i + 1], v[i:i + 1],+ g = g[i:i + 1],+ beta = beta[i:i + 1],+ initial_state = state,+ output_final_state = save_state,+ use_qk_l2norm_in_kernel = True,+ )if save_state and state is not None:state.copy_(new_state)core_attn_out.append(core_attn)- core_attn_out = torch.cat(core_attn_out, dim = 0)+ core_attn_out = core_attn_out[0] if pf and len(core_attn_out) == 1 else torch.cat(core_attn_out, dim = 0)# Fused recurrent ruleelse:diff --git a/exllamav3/modules/gated_delta_net_fn/gr_pf.py b/exllamav3/modules/gated_delta_net_fn/gr_pf.pynew file mode 100644index 0000000..ab15dc0--- /dev/null+++ b/exllamav3/modules/gated_delta_net_fn/gr_pf.py@@ -0,0 +1,109 @@+"""+Fused prefill pieces of GatedResidual._mix (EXL3_GR_PF_FUSE). On ROCm the grouped rms_norm+(w_groups = hc_mult) falls back to a chunked torch chain (~8 fp32 kernels over R*H*D elements),+and the gate application (sigmoid(g) * normed, mean over streams) is 5 more. Two Triton passes:++ gr_norm : normed (R*H, D) fp16 = x.float() * rsqrt(mean(x^2) + eps) * w[row % H]+ gr_gate : mixed (R, D) fp16 = mean_h(sigmoid(g[r, h*D + d]) * normed[r*H + h, d])++fp32 math, RNE fp16 rounding (Triton's fp32 -> fp16 cast is not RNE on gfx1151 ties, see kda_norm.py).+"""+import os+import torch+import triton+import triton.language as tl+from triton.language.extra import libdevice+++def _rne16(h):+ u = h.to(tl.uint32, bitcast = True)+ u = ((u + 0xFFF + ((u >> 13) & 1)) >> 13) << 13+ hn = u.to(tl.float32, bitcast = True)+ a = tl.abs(h)+ hs = (a + 0.5) - 0.5+ hs = (hs.to(tl.uint32, bitcast = True) | ((u >> 31) << 31)).to(tl.float32, bitcast = True)+ return tl.where(a < 6.103515625e-05, hs, hn)+++def _gr_norm_kernel(x_ptr, w_ptr, y_ptr, eps, YP, D: tl.constexpr, H: tl.constexpr, BD: tl.constexpr):+ r = tl.program_id(0).to(tl.int64)+ o = tl.arange(0, BD)+ m = o < D+ x = tl.load(x_ptr + r * D + o, mask = m, other = 0.0).to(tl.float32)+ ss = tl.sum(x * x, axis = 0)+ rs = (1.0 / tl.sqrt((ss / D + eps).to(tl.float64))).to(tl.float32)+ w = tl.load(w_ptr + (r % H) * D + o, mask = m, other = 0.0).to(tl.float32)+ h = _rne16(x * rs * w)+ # y row r = token * H + stream lands at token * YP + stream * D (YP = H * D: contiguous (R*H, D))+ tl.store(y_ptr + (r // H) * YP + (r % H) * D + o, h.to(tl.float16), mask = m)+++def _gr_apply_norm_kernel(x_ptr, y_ptr, post_ptr, w_ptr, n_ptr, eps, YP, D: tl.constexpr, H: tl.constexpr,+ BD: tl.constexpr, FMA: tl.constexpr):+ # EXL3_PF_GR_FUSE: x[r] += post[r] * y[r // H] (hc_apply, no comb) fused with gr_norm on the new x row.+ # Same row program, BD, num_warps and reduction as _gr_norm_kernel, so the norm is bit-identical.+ r = tl.program_id(0).to(tl.int64)+ o = tl.arange(0, BD)+ m = o < D+ x = tl.load(x_ptr + r * D + o, mask = m, other = 0.0)+ y = tl.load(y_ptr + (r // H) * D + o, mask = m, other = 0.0).to(tl.float32)+ p = tl.load(post_ptr + r)+ if FMA:+ x = tl.fma(p, y, x)+ else:+ x = x + p * y+ tl.store(x_ptr + r * D + o, x, mask = m)+ ss = tl.sum(x * x, axis = 0)+ rs = (1.0 / tl.sqrt((ss / D + eps).to(tl.float64))).to(tl.float32)+ w = tl.load(w_ptr + (r % H) * D + o, mask = m, other = 0.0).to(tl.float32)+ h = _rne16(x * rs * w)+ tl.store(n_ptr + (r // H) * YP + (r % H) * D + o, h.to(tl.float16), mask = m)+++def _gr_gate_kernel(g_ptr, n_ptr, y_ptr, D: tl.constexpr, H: tl.constexpr, BD: tl.constexpr):+ r = tl.program_id(0).to(tl.int64)+ o = tl.program_id(1) * BD + tl.arange(0, BD)+ m = o < D+ acc = tl.zeros((BD,), tl.float32)+ for h in tl.static_range(H):+ g = tl.load(g_ptr + r * (H * D) + h * D + o, mask = m, other = 0.0).to(tl.float32)+ n = tl.load(n_ptr + (r * H + h) * D + o, mask = m, other = 0.0).to(tl.float32)+ acc += (1.0 / (1.0 + libdevice.exp(-g))) * n+ tl.store(y_ptr + r * D + o, _rne16(acc / H).to(tl.float16), mask = m)+++def gr_norm(x: torch.Tensor, w_h: torch.Tensor, y: torch.Tensor, eps: float, H: int, y_pitch: int = 0):+ """x (R*H, D) fp32 contiguous, w_h (H*D,) fp16, y (R*H, D) fp16 contiguous, or y_pitch = token row pitch (>= H*D)+ of a (R, y_pitch) fp16 buffer y that receives the rows of one token side by side."""+ rows, D = x.shape+ if y_pitch:+ assert y_pitch >= H * D and y.dtype == torch.float16 and y.dim() == 2 and y.shape[0] == rows // H and y.shape[1] == y_pitch and y.is_contiguous()+ else:+ y_pitch = H * D+ _gr_norm_kernel[(rows,)](x, w_h, y, float(eps), y_pitch, D, H, triton.next_power_of_2(D),+ num_warps = 8, enable_fp_fusion = False)+++def gr_gate(g: torch.Tensor, normed: torch.Tensor, y: torch.Tensor, H: int):+ """g (R, H*D) fp16 contiguous, normed (R*H, D) fp16, y (R, D) fp16."""+ R, D = y.shape+ BD = 1024+ _gr_gate_kernel[(R, triton.cdiv(D, BD))](g, normed, y, D, H, BD, num_warps = 4, enable_fp_fusion = False)+++def gr_apply_norm(x: torch.Tensor, y: torch.Tensor, post: torch.Tensor, w_h: torch.Tensor, normed: torch.Tensor,+ eps: float, H: int, fma: bool = True, y_pitch: int = 0):+ """x (R*H, D) fp32 contiguous, updated in place (x += post * y); y (R, D) fp16/fp32, post (R*H,) fp32,+ normed (R*H, D) fp16 = gr_norm of the new x."""+ rows, D = x.shape+ if y_pitch:+ assert y_pitch >= H * D and normed.dtype == torch.float16 and normed.dim() == 2 and normed.shape[0] == rows // H and normed.shape[1] == y_pitch and normed.is_contiguous()+ else:+ y_pitch = H * D+ # fma=True is bit-identical to ext.hc_apply (hipcc contracts post * y + x; checked on GPU, R=1..2048)+ _gr_apply_norm_kernel[(rows,)](x, y, post, w_h, normed, float(eps), y_pitch, D, H, triton.next_power_of_2(D), fma,+ num_warps = 8, enable_fp_fusion = False)diff --git a/exllamav3/modules/gated_delta_net_fn/kda_norm.py b/exllamav3/modules/gated_delta_net_fn/kda_norm.pyindex 5a74513..f52c21f 100644--- a/exllamav3/modules/gated_delta_net_fn/kda_norm.py+++ b/exllamav3/modules/gated_delta_net_fn/kda_norm.py@@ -46,7 +46,7 @@ def _torch_rowsum(x_ptr, o_r, m, D: tl.constexpr, BR: tl.constexpr, NT: tl.const@triton.jit(do_not_specialize = ["R"])def kda_norm_kernel(x_ptr, g_ptr, w_ptr, y_ptr, R, eps, cbias,- D: tl.constexpr, BR: tl.constexpr, NT: tl.constexpr,+ D: tl.constexpr, BR: tl.constexpr, NT: tl.constexpr, SILU: tl.constexpr = False,):i_r = tl.program_id(0).to(tl.int64)o_r = i_r * BR + tl.arange(0, BR)@@ -68,7 +68,10 @@ def kda_norm_kernel(w = tl.load(w_ptr + o_d).to(tl.float32) + cbiash = h * w[None, :]gf = tl.load(g_ptr + p, mask = m, other = 0.0).to(tl.float32)- h = h * (1.0 / (1.0 + libdevice.exp(-gf)))+ if SILU:+ h = h * (gf / (1.0 + libdevice.exp(-gf))) # torch silu: x / (1 + exp(-x))+ else:+ h = h * (1.0 / (1.0 + libdevice.exp(-gf)))if y_ptr.dtype.element_ty == tl.float16:# Triton's fp32 -> fp16 cast on gfx1151 is not round-to-nearest-even on ties (~1e3 of 16.7M values off by# an ulp, fp_downcast_rounding = "rtne" does not change it). Round in fp32 first so the cast is exact:@@ -94,6 +97,7 @@ def kda_norm(br: int = 8,num_warps: int = 2,nt: int = 32,+ silu: bool = False,) -> None:"""x: (..., D) bf16 contiguous; g: same shape, fp16/bf16/fp32 contiguous; w: (D,) bf16/fp32;@@ -106,6 +110,6 @@ def kda_norm(grid = (triton.cdiv(R, br),)# enable_fp_fusion = False: no FMA contraction, so x*x, the sum and the scaling match torch's separate kernelskda_norm_kernel[grid](- x, g, w, y, R, float(eps), float(constant_bias), D, br, nt,+ x, g, w, y, R, float(eps), float(constant_bias), D, br, nt, silu,num_warps = num_warps, enable_fp_fusion = False,)diff --git a/exllamav3/modules/gated_rmsnorm.py b/exllamav3/modules/gated_rmsnorm.pyindex f232202..3df3fa6 100644--- a/exllamav3/modules/gated_rmsnorm.py+++ b/exllamav3/modules/gated_rmsnorm.py@@ -110,6 +110,7 @@ class GatedRMSNorm(Module):params,out_dtype: torch.dtype | None = None,gate: torch.Tensor = None,+ out_pitch: int = 0,) -> torch.Tensor:gate_act = 1 if self.gate_activation == "sigmoid" else 0if gate_act and not (x.dtype == torch.bfloat16 and x.is_contiguous() and gate.is_contiguous()):@@ -119,15 +120,24 @@ class GatedRMSNorm(Module):h = self.weight.to(torch.float32) * hh = h * torch.sigmoid(gate.to(torch.float32))return h.to(out_dtype or self.out_dtype or x.dtype)+ if out_pitch:+ # write y with a padded token-row pitch (see exl3.row_pad_pitch); the caller checked eligibility.+ # y is a (bsz, seqlen, heads, dim) view of a (tokens, out_pitch) buffer+ assert _hip and x.dim() >= 3 and (out_dtype or self.out_dtype) == torch.half+ hd = x.shape[-2] * x.shape[-1]+ y = torch.empty((x.numel() // hd, out_pitch), dtype = torch.half, device = x.device)[:, :hd].view(x.shape)+ ext.gated_rms_norm(x, self.weight, y, gate, self.rms_norm_eps, self.constant_bias, self.groups, self.gate_first, gate_act, out_pitch)+ return yy = torch.empty_like(x, dtype = out_dtype or self.out_dtype)# EXL3_KDA_NORM_FUSED: norm.cu is not built on ROCm, so ext.gated_rms_norm is a ~12-kernel torch# fallback with fp32 intermediates. One Triton pass instead (gated_delta_net_fn/kda_norm.py)if (- gate_act and _hip and self.groups == 1 and not self.gate_first+ _hip and self.groups == 1 and not self.gate_first+ and x.dtype == torch.bfloat16 and x.is_contiguous() and gate.is_contiguous()and os.environ.get("EXL3_KDA_NORM_FUSED", "0") == "1"):from .gated_delta_net_fn.kda_norm import kda_norm- kda_norm(x, self.weight, y, gate, self.rms_norm_eps, self.constant_bias)+ kda_norm(x, self.weight, y, gate, self.rms_norm_eps, self.constant_bias, silu = not gate_act)return yext.gated_rms_norm(x, self.weight, y, gate, self.rms_norm_eps, self.constant_bias, self.groups, self.gate_first, gate_act)return ydiff --git a/exllamav3/modules/hyperconnections.py b/exllamav3/modules/hyperconnections.pyindex 5a5b645..cd32fdb 100644--- a/exllamav3/modules/hyperconnections.py+++ b/exllamav3/modules/hyperconnections.py@@ -8,10 +8,105 @@ from ..model.config import Configfrom ..ext import exllamav3_ext as extfrom ..util.tensor import g_tensor_cacheimport os+from .quant.exl3 import PAD_MIN_ROWS as _PAD_MIN_ROWS, PAD_ELEMS as _PAD_ELEMS++def _pad_pitch_for(k: int) -> int:+ # keep in step with exllamav3_ext/pad_pitch.h pad_pitch_for+ return k + _PAD_ELEMS if (k * 2) % 1024 == 0 else k# gfx1151: store the GatedResidual mixer weights (the only fp16 bulk in an EXL3 model, 22% of# decode weight bytes) as per-row int8 and dequantize in the fused kernel. ROCm only; opt out# with EXL3_HIP_GR_MIX_Q8=0.+_GR_KEEP_ALL = os.environ.get("EXL3_GR_KEEP_ALL", "0") == "1" # keep fp16 fused weights next to the int8 ones+# optional sidecar with re-derived int8 codes (same format, same absmax scales, GPTQ-style rounding): EXL3_GR_Q8_SIDECAR=file.safetensors,+# keys {site}.fn_q8 (M, H*D) int8 and {site}.up_q8 (H*D, rank) int8. Off (unset) = the plain absmax rounding.+_GR_Q8_SIDECAR = os.environ.get("EXL3_GR_Q8_SIDECAR") or None+_sidecar_cache = {}++def apply_q8_sidecar(key, fn_q8, up_q8_rows, path = None):+ """Return (fn_q8, up_q8_rows) from the sidecar for this site, or the inputs unchanged when there is none."""+ path = path or _GR_Q8_SIDECAR+ if not path:+ return fn_q8, up_q8_rows+ if path not in _sidecar_cache:+ from safetensors import safe_open+ _sidecar_cache[path] = safe_open(path, "pt")+ f = _sidecar_cache[path]+ if f"{key}.fn_q8" not in f.keys():+ return fn_q8, up_q8_rows+ fq = f.get_tensor(f"{key}.fn_q8").to(fn_q8.device)+ uq = f.get_tensor(f"{key}.up_q8").to(up_q8_rows.device)+ assert fq.dtype == torch.int8 and uq.dtype == torch.int8 and fq.shape == fn_q8.shape and uq.shape == up_q8_rows.shape, key+ assert int(fq.min()) >= -127 and int(uq.min()) >= -127, key+ return fq.contiguous(), uq.contiguous()++# group scales for the int8 mixer weights, requantised at load from the stored fp16 weights (no pack change).+# fn: one fp32 scale per 128 consecutive k per row; up: one per 64 consecutive ranks per output column. The kernels read+# weight = half(code * scale) as fp32 (bit-exact twin of the fp16 kernels on dequantised half weights).+# EXL3_GR_GS: "0" off (per-row scales, the old behaviour), "1" group scales replace the per-row ones, "2" both resident+# (measurement harness: GatedResidual.GS_ON switches between them in one load).+_GR_GS = os.environ.get("EXL3_GR_GS", "0")+GS_FN, GS_UP = 128, 64+# EXL3_GR_GS_SIDECAR=file.safetensors: optional re-derived group-int8 codes (GPTQ-style rounding on the same group scales), keys {site}.fn_g8+# (M, H*D) int8 and {site}.up_g8 (H*D, rank) int8. Unset = plain absmax rounding.+_GR_GS_SIDECAR = os.environ.get("EXL3_GR_GS_SIDECAR") or None++GS_STATS = {"sidecar": 0, "plain": 0, "rejected": 0} # sites by source of the group codes (printed by the Qwen server after load)+GS_SIDECAR_MAX_MEAN_STEPS = 1.0++def apply_gs_sidecar(key, fq, upx, H, Dh, rank, path = None):+ """(fn codes (M, H*D), upx codes (H, Dh/4, rank, 4)) from the sidecar for this site, or the inputs when there is none.+ fq / upx are the plain group-rounded codes on the same scales: a sidecar made for other weights moves the codes by far more+ than GPTQ rounding does (mean |delta| well under one step), so a site whose mean delta exceeds one step is rejected (plain codes)."""+ path = path or os.environ.get("EXL3_GR_GS_SIDECAR") or _GR_GS_SIDECAR # read at load time: a wrapper may import this module before the server sets the variable+ if not path:+ GS_STATS["plain"] += 1+ return fq, upx+ # a sidecar that cannot be used (missing or unreadable file, wrong dtype or shape, codes outside +-127) never stops the load or+ # changes the weights: the site keeps its plain group rounding and is counted as rejected+ try:+ if path not in _sidecar_cache:+ from safetensors import safe_open+ _sidecar_cache[path] = safe_open(path, "pt")+ f = _sidecar_cache[path]+ if f"{key}.fn_g8" not in f.keys():+ GS_STATS["plain"] += 1+ return fq, upx+ f2 = f.get_tensor(f"{key}.fn_g8").to(fq.device); u2 = f.get_tensor(f"{key}.up_g8").to(fq.device)+ if not (f2.dtype == torch.int8 and u2.dtype == torch.int8 and f2.shape == fq.shape and tuple(u2.shape) == (H * Dh, rank)):+ raise ValueError(f"dtype or shape mismatch (fn {f2.dtype} {tuple(f2.shape)}, up {u2.dtype} {tuple(u2.shape)})")+ if int(f2.min()) < -127 or int(u2.min()) < -127:+ raise ValueError("code outside +-127")+ u2 = u2.reshape(H, Dh // 4, 4, rank).permute(0, 1, 3, 2).contiguous()+ except Exception as e: # noqa: BLE001+ print(f"hyperconnections: sidecar unusable at {key} ({type(e).__name__}: {e}), plain group rounding", flush = True)+ GS_STATS["rejected"] += 1+ return fq, upx+ mf = (f2.int() - fq.int()).abs().float().mean().item(); mu = (u2.int() - upx.int()).abs().float().mean().item()+ if mf > GS_SIDECAR_MAX_MEAN_STEPS or mu > GS_SIDECAR_MAX_MEAN_STEPS:+ print(f"hyperconnections: sidecar codes rejected at {key} (mean step delta fn {mf:.3f} up {mu:.3f}), plain group rounding", flush = True)+ GS_STATS["rejected"] += 1+ return fq, upx+ GS_STATS["sidecar"] += 1+ return f2.contiguous(), u2++def group_quant(fn32, up32, H, Dh, rank):+ """fn32 (M, H*Dh) fp32 folded fn, up32 (H*Dh, rank) fp32 up -> (fn_codes int8 (M, H*Dh), fn_gs f32 (M*H*Dh/128), upx_codes int8 (H, Dh/4, rank, 4), up_gs f32 (H*Dh*ceil(rank/64))).+ Scale = group absmax / 127 (floor 1e-12), code = round(w / scale) clamped to +-127. The last up group may be partial."""+ M = fn32.shape[0]+ g = fn32.view(M, H * Dh // GS_FN, GS_FN)+ fs = g.abs().amax(dim = 2).clamp_min_(1e-12) / 127.0+ fq = torch.round(g / fs[:, :, None]).clamp_(-127, 127).to(torch.int8).view(M, H * Dh).contiguous()+ ng = (rank + GS_UP - 1) // GS_UP+ pad = ng * GS_UP - rank+ u = torch.nn.functional.pad(up32, (0, pad)) if pad else up32+ ug = u.view(H * Dh, ng, GS_UP)+ us = ug.abs().amax(dim = 2).clamp_min_(1e-12) / 127.0+ uq = torch.round(ug / us[:, :, None]).clamp_(-127, 127).to(torch.int8).view(H * Dh, ng * GS_UP)[:, :rank]+ upx = uq.reshape(H, Dh // 4, 4, rank).permute(0, 1, 3, 2).contiguous()+ ups = us.view(H, Dh // 4, 4, ng).permute(0, 1, 3, 2).contiguous().view(-1)+ return fq, fs.contiguous().view(-1), upx, ups+_GR_MIX_Q8 = bool(torch.version.hip) and os.environ.get("EXL3_HIP_GR_MIX_Q8", "1") != "0"# hc mix fused with the consumer RMSNorm (hc_mix_norm: one finalize+norm launch instead of@@ -54,6 +149,9 @@ class ExpandStreams(Module):@overridedef forward(self, x: torch.Tensor, params: dict, out_dtype: torch.dtype | None = None):+ rows = x.shape[0] * x.shape[1]+ if rows > GatedResidual.MAX_FORWARD_ROWS:+ raise ValueError(f"hyperconnection mixer: a forward of {rows} rows exceeds the kernel grid limit of {GatedResidual.MAX_FORWARD_ROWS} rows; use a prefill chunk of at most {GatedResidual.MAX_FORWARD_ROWS} rows")return x.float().unsqueeze(2).expand(-1, -1, self.hc_mult, -1).contiguous()def tp_export(self, plan, producer):@@ -214,6 +312,8 @@ class HyperConnection(Module):return Falseif "quant_preserve" in params or "capture" in params:return False+ if post is None or comb is None: # GatedResidual-style sites (Qwen) carry no post/comb+ return Falseb, s, H, D = x.shapereturn (b * s > 256 and b * s <= 4096 and H == 4 and D % 4 == 0and x.dtype == torch.float and x.is_contiguous()@@ -229,7 +329,7 @@ class HyperConnection(Module):raise RuntimeError("EXL3_PF_HC_FUSE: deferred hc apply reached a different stream tensor")b, s, H, D = x.shapeR = b * s- ext.hc_apply(x.view(R, H, D), y.view(R, D), post.view(R, H), comb.view(R, H, H))+ ext.hc_apply(x.view(R, H, D), y.view(R, D), post.view(R, H), comb.view(R, H, H) if comb is not None else None)return xdef _pf_apply_mix_norm(self, streams: torch.Tensor, params: dict, norm, pending):@@ -366,6 +466,26 @@ class HyperConnection(Module):return module+_GR_PF_MODE = os.environ.get("EXL3_GR_PF_FUSE", "1") # 1 = norm + gate (default), 2 = norm only, 3 = gate only, 0 = torch+_GR_PF_FUSE = _GR_PF_MODE != "0"+_gr_hip_mod = []+++def _gr_hip():+ # hand-written HIP WMMA gated-residual GEMMs (gr/gr_mix_hip.py), opt-in with EXL3_GR_HIP=1; None on failure+ if not _gr_hip_mod:+ try:+ import sys+ d = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "gr")+ if d not in sys.path: sys.path.insert(0, d)+ import gr_mix_hip+ _gr_hip_mod.append(gr_mix_hip)+ except Exception as e:+ print(f" ! EXL3_GR_HIP unavailable: {e}")+ _gr_hip_mod.append(None)+ return _gr_hip_mod[0]++class GatedResidual(Module):"""Qwen4Exp-style gated residual: the low-rank, elementwise cousin of mHC. The residual is the@@ -390,7 +510,16 @@ class GatedResidual(Module):{key}.input_mix_weight_up.weight and, for the site form, {key}.block_inject_weight.weight."""- FUSED_MAX_R = 32+ # Rows at or below this take the fused small-R mixer (int8 weights on ROCm); 0 forces the precise GEMM path for every+ # row count. EXL3_HC_FUSED_MAX_R overrides at import.+ FUSED_MAX_R = int(os.environ.get("EXL3_HC_FUSED_MAX_R", "32"))+ # hc_mix kernels launch dim3(n_chunks, R): grid.y = R is limited to 65535 by HIP/CUDA, so one forward of 65536+ rows fails at its first mix launch+ MAX_FORWARD_ROWS = 65535+ # small-R fused mixer weight format. None = the load-time default (int8 when use_q8, else fp16); "fp16" runs the+ # fused fp16 kernels, "q8" the int8 ones, "q8g" the group-scaled int8 ones (needs EXL3_GR_KEEP_ALL=1 at load so that+ # every format is resident). Class attribute so a harness can flip it between passes in one load.+ MIX_MODE = os.environ.get("EXL3_GR_MIX_MODE") or None+ GS_ON = True # with EXL3_GR_GS=2 (both formats resident) False selects the per-row int8 weightsdef __init__(self,@@ -419,6 +548,7 @@ class GatedResidual(Module):self.fn_h = None # cat(down, inject) * w half, folded (fused path)self.use_q8 = False # int8 fused-path weights (ROCm), see _prepareself.fn_q8 = self.fn_scale = self.upx_q8 = self.up_scale = None+ self.fn_g8 = self.fn_gs = self.upx_g8 = self.up_gs = None # group-scaled int8 set (EXL3_GR_GS=2)self.rank = 0@override@@ -467,10 +597,24 @@ class GatedResidual(Module):up32 = self.up_h.float()usc = up32.abs().amax(dim = 1).clamp_min_(1e-12) / 127.0upq = torch.round(up32 / usc[:, None]).clamp_(-127, 127).to(torch.int8)+ self.fn_q8, upq = apply_q8_sidecar(self.key, self.fn_q8, upq)self.upx_q8 = upq.view(H, Dh // 4, 4, self.rank).permute(0, 1, 3, 2).contiguous()self.up_scale = usc.contiguous()- self.fn_h = None- self.upx_h = None+ self.fn_g8 = self.fn_gs = self.upx_g8 = self.up_gs = None+ if _GR_GS != "0" and Dh % GS_FN == 0:+ gq = group_quant(tmp, up32, H, Dh, self.rank)+ gfq, gupx = apply_gs_sidecar(self.key, gq[0], gq[2], H, Dh, self.rank)+ gq = (gfq, gq[1], gupx, gq[3])+ if _GR_GS == "2":+ self.fn_g8, self.fn_gs, self.upx_g8, self.up_gs = gq+ else:+ self.fn_q8, self.fn_scale, self.upx_q8, self.up_scale = gq+ if _GR_KEEP_ALL:+ self.fn_h = tmp.half().contiguous()+ self.upx_h = self.up_h.view(H, Dh // 4, 4, self.rank).permute(0, 1, 3, 2).contiguous()+ else:+ self.fn_h = None+ self.upx_h = Nonedel up32, upqelse:self.fn_h = tmp.half().contiguous()@@ -484,6 +628,13 @@ class GatedResidual(Module):self.norm_w_raw = self.norm_w = self.w_h = Noneself.down_h = self.up_h = self.upx_h = self.inject_h = self.proj_h = self.fn_h = Noneself.fn_q8 = self.fn_scale = self.upx_q8 = self.up_scale = None+ self.fn_g8 = self.fn_gs = self.upx_g8 = self.up_gs = None++ def q8_set(self):+ """(fn codes, fn scales, up codes, up scales) of the active int8 format. Group scales when resident (mode 2) and GS_ON."""+ if self.fn_g8 is not None and self.GS_ON:+ return self.fn_g8, self.fn_gs, self.upx_g8, self.up_gs+ return self.fn_q8, self.fn_scale, self.upx_q8, self.up_scale@overridedef get_tensors(self):@@ -518,12 +669,14 @@ class GatedResidual(Module):if self.use_combine else Nonereturn post, mixed- def _mix(self, streams: torch.Tensor, cached: bool = True):+ def _mix(self, streams: torch.Tensor, cached: bool = True, pad_ok: bool = False, pending = None):"""streams (b, s, H, D) fp32 -> (post (R, H) fp32 or None, mixed (R, D) half).cached: small-R outputs may come from the per-device static workspaces (see below);callers that hold the result across another mix on the device pass False."""H, Dh = self.hc_mult, self.hidden_sizeR = streams.shape[0] * streams.shape[1]+ if R > self.MAX_FORWARD_ROWS:+ raise ValueError(f"hyperconnection mixer: a forward of {R} rows exceeds the kernel grid limit of {self.MAX_FORWARD_ROWS} rows; use a prefill chunk of at most {self.MAX_FORWARD_ROWS} rows")s3 = streams.reshape(R, H, Dh)if s3.dtype != torch.float:s3 = s3.float() # MTP sample_from_state passes the half draft stack@@ -551,30 +704,109 @@ class GatedResidual(Module):dots = ws(R * M * H, torch.float, "gr_mix_dots").view(R, M, H)post = ws(R * H, torch.float, "gr_mix_post").view(R, H) if self.use_combine else Nonemixed = ws(R * Dh, torch.half, "gr_mix_mixed").view(R, Dh)- if self.use_q8:- ext.gr_mix_q8(s3, self.fn_q8, self.fn_scale, self.upx_q8, self.up_scale, self.w_h,- self.rms_eps, dots, post, mixed)+ mode = self.MIX_MODE+ q8 = self.use_q8 if mode is None else (mode == "q8")+ if q8:+ fq, fsc, uq, usc = self.q8_set()+ ext.gr_mix_q8(s3, fq, fsc, uq, usc, self.w_h, self.rms_eps, dots, post, mixed)else:ext.gr_mix(s3, self.fn_h, self.upx_h, self.w_h, self.rms_eps, dots, post, mixed)else:post = torch.empty((R, H), dtype = torch.float, device = dev) \if self.use_combine else None- normed = torch.empty((R * H, Dh), dtype = torch.half, device = dev)- ext.rms_norm(s3.view(R * H, Dh), self.w_h, normed,- self.rms_eps, 0.0, 1.0, False, False, H)+ fuse = _GR_PF_FUSE and dev.type == "cuda" and torch.version.hip is not None+ gr_hip_ok = (R > 32 and os.environ.get("EXL3_GR_HIP", "0") == "1" and fuse and self.use_combine and H == 4+ and tuple(self.proj_h.shape) == (324, 10240) and tuple(self.up_h.shape) == (10240, 320)+ and self.proj_h.dtype == torch.half and self.up_h.dtype == torch.half+ and self.proj_h.is_contiguous() and self.up_h.is_contiguous())+ # gr_g1 reads normed rows of H * Dh fp16 = 20480 B, a pitch the GEMM-style tile loads read at a fraction of+ # the rate; with the hand kernels (gr_g1, gr_g2s) and gr_norm all taking a token pitch, normed is a (R, H*Dh + 64) buffer.+ # Same values, bit-exact. EXL3_OPROJ_PAD=0 turns it off.+ xp = H * Dh+ if (gr_hip_ok and _GR_PF_MODE in ("1", "2") and R >= _PAD_MIN_ROWS and _gr_hip() is not None+ and os.environ.get("EXL3_OPROJ_PAD", "1") != "0"):+ xp = _pad_pitch_for(H * Dh)+ if xp != H * Dh:+ nbuf = torch.empty((R, xp), dtype = torch.half, device = dev)+ if pending is not None:+ # EXL3_PF_GR_FUSE: the previous site's residual apply, folded into this norm pass (padded pitch)+ assert pending[0] is streams and s3.data_ptr() == streams.data_ptr()+ from .gated_delta_net_fn.gr_pf import gr_apply_norm+ gr_apply_norm(s3.view(R * H, Dh), pending[1].view(R, Dh), pending[2].view(R * H), self.w_h, nbuf,+ self.rms_eps, H, y_pitch = xp)+ else:+ from .gated_delta_net_fn.gr_pf import gr_norm+ gr_norm(s3.view(R * H, Dh), self.w_h, nbuf, self.rms_eps, H, xp)+ normed = nbuf[:, : H * Dh]+ else:+ normed = torch.empty((R * H, Dh), dtype = torch.half, device = dev)+ if pending is not None:+ assert pending[0] is streams and fuse and _GR_PF_MODE in ("1", "2") and s3.data_ptr() == streams.data_ptr()+ from .gated_delta_net_fn.gr_pf import gr_apply_norm+ gr_apply_norm(s3.view(R * H, Dh), pending[1].view(R, Dh), pending[2].view(R * H), self.w_h, normed,+ self.rms_eps, H)+ elif fuse and _GR_PF_MODE in ("1", "2"):+ from .gated_delta_net_fn.gr_pf import gr_norm+ gr_norm(s3.view(R * H, Dh), self.w_h, normed, self.rms_eps, H)+ else:+ ext.rms_norm(s3.view(R * H, Dh), self.w_h, normed,+ self.rms_eps, 0.0, 1.0, False, False, H)+ if gr_hip_ok:+ gr_hip = _gr_hip()+ if gr_hip is not None:+ t = torch.empty((R, self.rank), dtype = torch.half, device = dev)+ gr_hip.gr_g1(normed.view(R, H * Dh), self.proj_h, t, post)+ # the block input feeds qkv / z / q|gate; at a 5120 B row pitch their GEMMs read it ~7 % slower+ # than at a padded pitch. gr_g2s writes mixed at row pitch Dh + 64 when the consumer accepts a padded view+ # (pad_ok, set by the transformer for the attention site only). EXL3_OPROJ_PAD=0 turns it off.+ pitch = _pad_pitch_for(Dh) if (pad_ok and R >= _PAD_MIN_ROWS and os.environ.get("EXL3_OPROJ_PAD", "1") != "0") else Dh+ if pitch != Dh:+ mixed = torch.empty((R, pitch), dtype = torch.half, device = dev)[:, :Dh]+ else:+ mixed = torch.empty((R, Dh), dtype = torch.half, device = dev)+ gr_hip.gr_g2s(t, self.up_h, normed, mixed)+ return post, mixed+ assert xp == H * Dhdm = torch.matmul(normed.view(R, H * Dh), self.proj_h.t()) # (R, rank [+ H])t = F.silu(dm[:, : self.rank] / H)if self.use_combine:post.copy_(2.0 * torch.sigmoid(dm[:, self.rank :].float() / H))g = torch.matmul(t, self.up_h.t()) # (R, H * Dh)- mixed = (torch.sigmoid(g.float()).view(R, H, Dh)- * normed.float().view(R, H, Dh)).mean(dim = -2).half()+ if fuse and _GR_PF_MODE in ("1", "3") and g.dtype == torch.half and g.is_contiguous():+ from .gated_delta_net_fn.gr_pf import gr_gate+ mixed = torch.empty((R, Dh), dtype = torch.half, device = dev)+ gr_gate(g, normed, mixed, H)+ else:+ mixed = (torch.sigmoid(g.float()).view(R, H, Dh)+ * normed.float().view(R, H, Dh)).mean(dim = -2).half()return post, mixed- def mix(self, streams: torch.Tensor, params: dict):+ def gr_can_defer(self, x: torch.Tensor, y: torch.Tensor, post: torch.Tensor, params: dict) -> bool:+ """EXL3_PF_GR_FUSE (default off, read per call): the next GatedResidual site may run this site's+ residual apply inside its norm pass (gr_pf.gr_apply_norm). Only the prefill-size Triton norm path+ takes a pending apply; anything else flushes it with HyperConnection.flush_pending."""+ if os.environ.get("EXL3_PF_GR_FUSE", "0") != "1" or not _GR_PF_FUSE or _GR_PF_MODE not in ("1", "2"):+ return False+ if "quant_preserve" in params or "capture" in params or not self.use_combine or post is None:+ return False+ if not hasattr(ext, "gr_mix") or not _hc_mix_supported(x.device) or torch.version.hip is None:+ return False+ if x.dim() != 4 or x.shape[2] != self.hc_mult or x.shape[3] != self.hidden_size:+ return False+ R = x.shape[0] * x.shape[1]+ return (R > self.FUSED_MAX_R and x.dtype == torch.float and x.is_contiguous()+ and y.dtype in (torch.half, torch.float) and y.is_contiguous() and y.numel() == R * self.hidden_size+ and post.dtype == torch.float and post.is_contiguous() and post.numel() == R * self.hc_mult)++ def mix(self, streams: torch.Tensor, params: dict, pending = None):"""(b, s, H, D) fp32 -> (inject gates (b, s, H) fp32, None, collapsed (b, s, D) half)."""b, s = streams.shape[:2]- post, mixed = self._mix(streams)+ if pending is not None and not (self.gr_can_defer(streams, pending[1], pending[2], params)+ and pending[0] is streams):+ HyperConnection.flush_pending(streams, pending)+ pending = None+ post, mixed = self._mix(streams, pending = pending, pad_ok = bool(params.get("hc_pad_ok")) and "capture" not in params+ and "quant_preserve" not in params and "ovr" not in params and "reconstruct" not in params)return post.view(b, s, self.hc_mult), None, mixed.view(b, s, self.hidden_size)def apply_(@@ -608,6 +840,9 @@ class GatedResidual(Module):def forward(self, x: torch.Tensor, params: dict, out_dtype: torch.dtype | None = None):"""Final-mixer form only: collapse the stream stack."""assert not self.use_combine, "site-form GatedResidual is consumed via mix()/apply_()"+ pending = params.pop("hc_pending", None)+ if pending is not None:+ HyperConnection.flush_pending(x, pending)# MTP trunk tap: models without a final norm export the PRE-collapse stream stack here# (flattened), the analog of the RMSNorm export hookif self.key in params.get("export_state_norm_keys", ()):diff --git a/exllamav3/modules/mla_attn.py b/exllamav3/modules/mla_attn.pyindex a43183f..00cecda 100644--- a/exllamav3/modules/mla_attn.py+++ b/exllamav3/modules/mla_attn.py@@ -33,6 +33,7 @@ MAX_DECODE_QLEN = 16# the score transient at (256 rows, tile) regardless of context length; must be a multiple# of the page size (256)_score_tile = int(os.environ.get("EXL3_DSA_SCORE_TILE", 32768))+_kpool_eager_rows = int(os.environ.get("EXL3_DSA_KPOOL_EAGER_ROWS", 1024)) # 0 = one shot (old path)assert _score_tile % 256 == 0 and _score_tile > 0# Decode/verify has few query rows. When enabled, score the whole visible slab in one@@ -966,16 +967,25 @@ class MLAttention(Module):probs = torch.softmax(gg + self.idx_kpool_ape.unsqueeze(0), dim = 1)pool_keys = (probs * gk).sum(dim = 1)- sc = torch.einsum("shd,pd->shp", q_idx[b].float(), pool_keys)- sc = F.relu(sc * (D_i ** -0.5))- sc = torch.einsum("sh,shp->sp", w[b].float() * (H_i ** -0.5), sc)-q_pos = host_seqlens[b] + torch.arange(seqlen, device = x.device)pool_end = torch.arange(n_pools, device = x.device) * P + (P - 1)- sc = sc.masked_fill(pool_end.unsqueeze(0) > q_pos.unsqueeze(1), -float("inf"))-select_k = min(self.index_topk // P, n_pools)- top_sc, top_pool = sc.topk(select_k, dim = -1)+ qf, wb = q_idx[b], w[b]+ # Query-chunked: the [rows, H_i, n_pools] fp32 score cube is 8 GiB per copy at 16K tokens.+ # Rows are independent, so every chunk computes the same per-row values.+ step = _kpool_eager_rows if _kpool_eager_rows > 0 else seqlen+ top_sc_l, top_pool_l = [], []+ for r0 in range(0, seqlen, step):+ r1 = min(r0 + step, seqlen)+ sc = torch.einsum("shd,pd->shp", qf[r0:r1].float(), pool_keys)+ sc = F.relu(sc * (D_i ** -0.5))+ sc = torch.einsum("sh,shp->sp", wb[r0:r1].float() * (H_i ** -0.5), sc)+ sc = sc.masked_fill(pool_end.unsqueeze(0) > q_pos[r0:r1].unsqueeze(1), -float("inf"))+ ts, tp = sc.topk(select_k, dim = -1)+ del sc+ top_sc_l.append(ts); top_pool_l.append(tp)+ top_sc = top_sc_l[0] if len(top_sc_l) == 1 else torch.cat(top_sc_l)+ top_pool = top_pool_l[0] if len(top_pool_l) == 1 else torch.cat(top_pool_l)exp = (top_pool.unsqueeze(-1) * P +torch.arange(P, device = x.device)).view(seqlen, -1)exp = torch.where(diff --git a/exllamav3/modules/moe_fused.py b/exllamav3/modules/moe_fused.pynew file mode 100644index 0000000..7646cd4--- /dev/null+++ b/exllamav3/modules/moe_fused.py@@ -0,0 +1,278 @@+"""Fused MoE half-layer decode (EXL3_MOE_FUSED=1, ROCm gfx11.5, default off).++One persistent launch per MoE half-layer replaces `mlp_hc.mix`, `mlp.forward` and `mlp_hc.apply_` for R = 1..4 rows (decode and short verify+rounds): HC dots + finalize, router, top-k, expert gate/up/down VALU matvecs on weights repacked in read order, Hadamard post, weighted sum,+shared expert, gated-residual apply in place on the stack. Kernel: quant/exl3_moe_fused.cuh. Byte-identical to the flag-off engine at R > 1+and row-identical at R = 1 (one reduction order for every R, same as EXL3_MOE_VALU).++Weights (core5): the kernel reads the engine's own trellis tensors through pointer tables (layout "native", zero extra memory). The+EXL3_MOE_FUSED_LAYOUT=repack option builds the older 32-column-group copy for A/B timing (extra memory, reported by `extra_bytes`).+Only the router / shared-gate weights are copied when they are not already contiguous half.+"""+from __future__ import annotations+import os+import time+import torch+from ..ext import exllamav3_ext as ext+from .hyperconnections import HyperConnection++MAX_ROWS = 4+++# EXL3_MOE_FUSED9=<variant>: 0 off, 393216 (0x60000) = forced-inline phases + two blocks per WGP (core9), 917504 = same kernel, ONE block per WGP:+# the grid barrier needs every block resident, and two 512-thread blocks fill a WGP's VGPR file exactly, so a desktop client on the same GPU can leave half the grid unscheduled. Runtime-mutable for one-load A/B.+MF9 = {"variant": int(os.environ.get("EXL3_MOE_FUSED9", "917504"), 0), "timing": 0, # timing 1 = phase stamps into seldbg (tests)+ # ballot top-k in the expert selection (variant bit 0x1000), bit-identical to the plain loop; EXL3_MOE_TK2=0 turns it off+ "tk2": os.environ.get("EXL3_MOE_TK2", "1") not in ("", "0")}+++def enabled_by_env() -> bool:+ return bool(torch.version.hip) and os.environ.get("EXL3_MOE_FUSED", "0") not in ("", "0")+++def _rep(tr: torch.Tensor) -> torch.Tensor:+ """(kt, nt, nw) int16 trellis -> (nt/2, kt, 2*nw) int16: one 32-column group per leading index, k-slice major."""+ kt, nt, nw = tr.shape+ assert nt % 2 == 0+ return tr.reshape(kt, nt // 2, 2 * nw).permute(1, 0, 2).contiguous()+++class FusedMoEHalf:+ """Static plan + workspace of one qwen4_exp-style MoE half-layer (HC sites, BlockSparseMLP + shared expert)."""++ @staticmethod+ def why_not(block) -> str | None:+ """None if the block is eligible, else the reason (kept for the verdict / debugging)."""+ from .block_sparse_mlp_routing import routing_std+ if not hasattr(ext, "exl3_moe_fused_half"):+ return "extension has no exl3_moe_fused_half"+ gr, mlp = block.mlp_hc, block.mlp+ if gr is None or mlp is None or block.mlp_norm is not None:+ return "needs mlp_hc, mlp and no mlp_norm"+ if not getattr(gr, "use_q8", False) or gr.hc_mult != 4:+ return "GatedResidual int8 mixer (use_q8) with 4 streams required"+ if getattr(mlp, "routing_fn", None) is not routing_std or mlp.routing_gate is None or mlp.shared_gate is None or mlp.shared_experts is None:+ return "needs routing_std, shared_gate and shared_experts"+ if getattr(mlp.routing_gate.inner, "bias", None) is not None or mlp.shared_experts_post_norm is not None:+ return "router bias / shared post norm"+ if len(mlp.gates) != mlp.num_experts or len(mlp.ups) != mlp.num_experts or len(mlp.downs) != mlp.num_experts:+ return "experts are not one linear each"+ return None++ def __init__(self, block):+ t0 = time.time()+ gr, mlp = block.mlp_hc, block.mlp+ why = self.why_not(block)+ assert why is None, why+ dev = gr.fn_q8.device+ self.dev = dev+ self.gr, self.mlp = gr, mlp+ self.D = mlp.hidden_size+ self.H = gr.hc_mult+ self.LR = gr.fn_q8.shape[0] - self.H+ self.NEXP = mlp.num_experts+ self.TOPK = mlp.num_experts_per_tok+ self.INTER = mlp.intermediate_size+ g0, u0, d0 = mlp.gates[0].inner, mlp.ups[0].inner, mlp.downs[0].inner+ sh = mlp.shared_experts+ sg, su, sd = sh.gates[0].inner, sh.ups[0].inner, sh.downs[0].inner+ self.RB = int(round(g0.K))+ self.SB = int(round(sg.K))+ assert g0.K == self.RB and sg.K == self.SB, "integer K only (K2.5 not supported)"+ for l in (g0, u0, d0, sg, su, sd):+ assert l.mul1 and not l.mcg, "mul1 codebook required"+ self.supported = bool(ext.exl3_moe_fused_supported(self.D, self.H, self.LR, self.NEXP, self.TOPK, self.INTER, self.RB, self.SB))+ if not self.supported:+ self.extra_bytes = 0+ return+ self.shape = (self.D, self.H, self.LR, self.NEXP, self.TOPK, self.INTER, self.RB, self.SB)+ E = self.NEXP+ self.native = os.environ.get("EXL3_MOE_FUSED_LAYOUT", "native") != "repack"+ lin = [(mlp.gates[e].inner, mlp.ups[e].inner, mlp.downs[e].inner) for e in range(E)] + [(sg, su, sd)]+ wt, svt, keep = [], [], []+ self.extra_bytes = 0+ if self.native:+ # zero copy: the tables point at the engine's own trellis and scale-vector tensors (they stay alive through the modules)+ for tri in lin:+ for l in tri:+ assert l.trellis.dtype == torch.int16 and l.trellis.is_contiguous() and l.trellis.device == dev+ wt.append(l.trellis.data_ptr())+ for l in tri:+ for v in (l.suh, l.svh):+ assert v.dtype == torch.half and v.is_contiguous() and v.device == dev+ svt += [tri[0].suh.data_ptr(), tri[0].svh.data_ptr(), tri[1].suh.data_ptr(), tri[1].svh.data_ptr(), tri[2].suh.data_ptr(), tri[2].svh.data_ptr()]+ else:+ # A/B layout: 32-column groups, k-slice major, one copy (the originals stay: prefill and the flag-off path read them)+ mats = [[_rep(l.trellis).reshape(-1) for l in tri] for tri in lin]+ tot = sum(m.numel() for tri in mats for m in tri)+ self.rep = torch.empty(tot, dtype=torch.int16, device=dev)+ o = 0+ for tri in mats:+ for m in tri:+ self.rep[o: o + m.numel()].copy_(m)+ wt.append(self.rep.data_ptr() + 2 * o)+ o += m.numel()+ self.svs = torch.stack([torch.cat([t[0].suh, t[0].svh, t[1].suh, t[1].svh, t[2].suh, t[2].svh]).half() for t in lin]).contiguous()+ sl = self.svs.shape[1]+ for i in range(E + 1):+ base = self.svs.data_ptr() + 2 * i * sl+ offs = [0, self.D, self.D + self.INTER, 2 * self.D + self.INTER, 2 * self.D + 2 * self.INTER, 2 * self.D + 3 * self.INTER]+ svt += [base + 2 * q for q in offs]+ self.extra_bytes += self.rep.numel() * 2 + self.svs.numel() * 2+ self.wt = torch.tensor(wt, dtype=torch.int64, device=dev)+ self.svt = torch.tensor(svt, dtype=torch.int64, device=dev)+ assert self.wt.numel() == 3 * (E + 1) and self.svt.numel() == 6 * (E + 1)+ self.extra_bytes += self.wt.numel() * 8 + self.svt.numel() * 8+ rw = mlp.routing_gate.inner.weight+ rr = rw.t() if tuple(rw.shape) == (self.D, self.NEXP) else rw+ self.router = rr if (rr.dtype == torch.half and rr.is_contiguous()) else rr.half().contiguous() # kernel wants [NEXP][D]; alias when already so+ sw = mlp.shared_gate.inner.weight+ self.sgate = sw.reshape(-1) if (sw.dtype == torch.half and sw.is_contiguous()) else sw.half().reshape(-1).contiguous()+ if self.router.data_ptr() != rr.data_ptr():+ self.extra_bytes += self.router.numel() * 2+ if self.sgate.data_ptr() != sw.data_ptr():+ self.extra_bytes += self.sgate.numel() * 2+ assert self.router.shape == (self.NEXP, self.D) and self.sgate.numel() == self.D+ off = ext.exl3_moe_fused_ws_offsets(*self.shape)+ self.off = off+ self.ws = torch.zeros(off[-1], dtype=torch.uint8, device=dev)+ self.grid = int(ext.exl3_moe_fused_grid(*self.shape))+ self.extra_bytes += self.ws.numel()+ torch.cuda.synchronize()+ self.build_seconds = time.time() - t0++ # ---- views of the workspace (tests / debugging)+ def ws_view(self, name: str, R: int):+ idx = {"dots": 1, "post": 2, "mixed": 3, "scores": 4, "sgl": 5, "gu": 6, "dn": 7, "ydbg": 8, "seldbg": 9}[name]+ dt = {"dots": torch.float, "post": torch.float, "mixed": torch.half, "scores": torch.half, "sgl": torch.float,+ "gu": torch.half, "dn": torch.float, "ydbg": torch.float, "seldbg": torch.int32}[name]+ nbytes = self.off[idx + 1] - self.off[idx]+ return self.ws[self.off[idx]: self.off[idx] + nbytes].view(dt)++ def ctl(self):+ return self.ws[: 12].view(torch.int32) # [bar, done, err]++ def applicable(self, x: torch.Tensor, params: dict) -> bool:+ if not self.supported or "capture" in params or "quant_preserve" in params:+ return False+ if x.dtype != torch.float or not x.is_contiguous() or x.dim() != 4 or x.shape[2] != self.H or x.shape[3] != self.D:+ return False+ return 1 <= x.shape[0] * x.shape[1] <= MAX_ROWS++ def __call__(self, x: torch.Tensor) -> torch.Tensor:+ """x (b, s, H, D) fp32 residual stack, updated in place and returned."""+ gr = self.gr+ fq, fsc, uq, usc = gr.q8_set()+ if MF9["variant"] and self.native and hasattr(torch.ops, "mf9") and hasattr(torch.ops.mf9, "half"):+ # core9 kernel (forced-inline phases, two blocks per WGP), byte-identical to the kernel below; same workspace layout+ torch.ops.mf9.half(x, fq, fsc, uq, usc, gr.w_h, self.router, self.sgate,+ self.wt, self.svt, self.ws, gr.rms_eps, 1, MF9["timing"], MF9["variant"] | (0x1000 if MF9["tk2"] else 0), *self.shape)+ return x+ ext.exl3_moe_fused_half(x, fq, fsc, uq, usc, gr.w_h, self.router, self.sgate,+ self.wt, self.svt, self.ws, gr.rms_eps, int(self.native), *self.shape)+ return x+++def block_status(block) -> str | None:+ """None if the fused half-layer will run for this block, else one short reason (no weights are touched)."""+ why = FusedMoEHalf.why_not(block)+ if why is not None:+ return why+ try:+ gr, mlp = block.mlp_hc, block.mlp+ g0, sg = mlp.gates[0].inner, mlp.shared_experts.gates[0].inner+ rb, sb = int(round(g0.K)), int(round(sg.K))+ if g0.K != rb or sg.K != sb:+ return f"fractional K (routed {g0.K}, shared {sg.K})"+ if not (g0.mul1 and not g0.mcg and sg.mul1 and not sg.mcg):+ return "codebook is not mul1"+ H = gr.hc_mult+ if not ext.exl3_moe_fused_supported(mlp.hidden_size, H, gr.fn_q8.shape[0] - H, mlp.num_experts, mlp.num_experts_per_tok,+ mlp.intermediate_size, rb, sb):+ return f"routed K{rb} / shared K{sb} at this shape is not instantiated"+ except Exception as exc: # noqa: BLE001+ return f"status check failed: {exc!r}"+ return None+++def report(model, label: str = "") -> str | None:+ """One log line per model load: which MoE layers run the fused half-layer and which fall back to the slow path, and why.+ Silent when EXL3_MOE_FUSED is off or the model has no fusable MoE layers. Returns the line (also printed to stderr)."""+ if not enabled_by_env():+ return None+ ok, bad = [], {}+ for m in getattr(model, "modules", []):+ if not hasattr(m, "_moe_fused_on") or getattr(m, "mlp", None) is None or getattr(m, "mlp_hc", None) is None:+ continue+ if not hasattr(m.mlp, "gates"):+ continue+ idx = getattr(m, "layer_idx", None)+ idx = idx if idx is not None else len(ok) + sum(len(v) for v in bad.values())+ why = block_status(m)+ if why is None:+ ok.append(idx)+ else:+ bad.setdefault(why, []).append(idx)+ if not ok and not bad:+ return None+ def rng(v):+ v = sorted(v); out, a = [], v[0]+ for i, x in enumerate(v):+ if i + 1 == len(v) or v[i + 1] != x + 1:+ out.append(f"{a}" if a == x else f"{a}-{x}"); a = v[i + 1] if i + 1 < len(v) else None+ return ",".join(out)+ nb = sum(len(v) for v in bad.values())+ if nb == 0:+ line = f"[moe_fused]{label} all {len(ok)} MoE layers run the fused half-layer"+ else:+ det = "; ".join(f"layers {rng(v)}: {k}" for k, v in sorted(bad.items(), key=lambda kv: kv[1][0]))+ line = f"[moe_fused]{label} WARNING {nb} of {nb + len(ok)} MoE layers are NOT fused (slow path): {det}"+ import sys+ print(line, file=sys.stderr, flush=True)+ return line+++def maybe_apply(block, x: torch.Tensor, params: dict, hc_pending):+ """Hook for TransformerBlock._forward_mlp. Returns the new residual, or None to fall through to the unfused path."""+ if not block._moe_fused_on:+ return None+ fh = block._moe_fused+ if fh is None:+ if block._moe_fused_tried:+ return None+ block._moe_fused_tried = True+ if FusedMoEHalf.why_not(block) is not None:+ return None+ fh = FusedMoEHalf(block)+ block._moe_fused = fh+ if not fh.applicable(x, params):+ return None+ if hc_pending is not None:+ HyperConnection.flush_pending(x, hc_pending)+ return fh(x)+++_CHK = {"n": 0, "on": True} # "on" False only in the determinism harness arms that deliberately run the two-blocks-per-WGP grid+++def check_barrier(model, every: int = 8, force: bool = False) -> None:+ """Raise if any fused half-layer grid barrier timed out (its workgroups would have read partial results). Reads the ctl record of every layer+ with one gather every `every` calls (one decode step per call), or at once with force=True."""+ if not _CHK["on"] and not force:+ return+ _CHK["n"] += 1+ if not force and _CHK["n"] % every:+ return+ fhs = [(m.key, m._moe_fused) for m in getattr(model, "modules", []) if getattr(m, "_moe_fused", None) is not None]+ if not fhs:+ return+ rec = torch.cat([f.ws[8:44].view(torch.int32) for _, f in fhs]).cpu().view(len(fhs), 9) # ctl words 2..10+ bad = (rec[:, 0] != 0) | (rec[:, 1] != 0)+ if bad.any():+ i = int(bad.nonzero()[0])+ e, cnt, ph, blk, seen, ticks, miss, _, _ = [int(v) for v in rec[i]]+ with torch.inference_mode():+ for _, f in fhs:+ f.ws[8:64].zero_()+ raise RuntimeError(f"fused MoE grid barrier timed out in {fhs[i][0]} (phase {e}, {cnt} timeouts, block {blk} saw {seen} arrivals after {ticks / 1e5:.0f} ms, "+ f"first missing block {miss}): the output of this step is invalid; the GPU is shared and not all workgroups were resident")diff --git a/exllamav3/modules/ngram_embedding.py b/exllamav3/modules/ngram_embedding.pyindex 023a916..3ca32cb 100644--- a/exllamav3/modules/ngram_embedding.py+++ b/exllamav3/modules/ngram_embedding.py@@ -9,6 +9,40 @@ from ..ext import exllamav3_ext as extfrom . import Modulefrom .quant.exl3_lib.ngram_codec import ROW_DIM, mul1_codebook, dequant_rows, words_per_row++_MADV_POPULATE_READ = 22+_MADV_PAGEOUT = 21+++def process_swap_bytes() -> int | None:+ """VmSwap of this process in bytes, None when unknown"""+ try:+ with open("/proc/self/status") as f:+ for line in f:+ if line.startswith("VmSwap:"):+ return int(line.split()[1]) * 1024+ except OSError:+ pass+ return None+++def _madvise_range(tensor: torch.Tensor, advice: int, byte_start: int = 0, byte_len: int | None = None, chunk: int = 1 << 30) -> int:+ """madvise a byte range of a CPU tensor in chunks of at most `chunk` bytes. Returns byte_len, -1 when madvise is unavailable or failed"""+ import ctypes+ libc = ctypes.CDLL(None, use_errno = True)+ page = os.sysconf("SC_PAGE_SIZE")+ total = tensor.numel() * tensor.element_size()+ byte_len = total - byte_start if byte_len is None else min(byte_len, total - byte_start)+ base = tensor.data_ptr() + byte_start+ lo = base - base % page+ hi = base + byte_len+ while lo < hi:+ n = min(chunk, hi - lo)+ if libc.madvise(ctypes.c_void_p(lo), ctypes.c_size_t(n), advice) != 0:+ return -1+ lo += n+ return byte_len+"""Hashed n-gram embedding table (Qwen3.8-Flash-Next ple_embedding and kin): maps each token positionto (ngram_size - 1) * heads_per_ngram hash-table rows and concatenates them into one feature vector.@@ -212,7 +246,14 @@ class NGramEmbedding(Module):stream_from_disk = self.stream_from_diskif stream_from_disk is None:infer_params = getattr(self.config, "infer_params", None)- stream_from_disk = infer_params.ngram_stream_from_disk if infer_params is not None else True+ stream_from_disk = infer_params.ngram_stream_from_disk if infer_params is not None else None+ if stream_from_disk is None:+ # Auto: per-token row preads cost ~0.8 ms of GPU idle per decode token (tokplan1), so hold+ # the table in RAM when it fits with a wide margin; otherwise stream from disk+ from ..util.memory import host_memory_available+ avail = host_memory_available()+ tbl = self.num_rows * (words_per_row(self.K) * 2 if quantized else ROW_DIM * 2)+ stream_from_disk = avail is None or avail < tbl + (48 << 30)if stream_from_disk:self.mode = "trellis_disk" if quantized else "fp16_disk"self.handles = [stc.get_tensor_handle(k) for k in keys]@@ -258,6 +299,33 @@ class NGramEmbedding(Module):self.rows_per_shard = self.num_rowsif not quantized:self._row_dtype = self.tables[0].dtype+ if not getattr(NGramEmbedding, "_mode_logged", False):+ NGramEmbedding._mode_logged = True+ from ..util.memory import host_memory_available+ av = host_memory_available()+ print(f"[ngram] table mode {self.mode}: {self.num_rows} rows, host MemAvailable "+ f"{'?' if av is None else f'{av / 2**30:.1f}'} GiB at load (RAM mode needs table + 48 GiB; "+ f"disk mode = every prefill chunk reads its rows from the file, a busy disk or a cold page cache stalls it)",+ flush=True)++ def ensure_resident(self, min_swap_bytes: int = 64 << 20) -> dict:+ """RAM modes only. The table is anonymous host memory that the kernel may have swapped out during the load (the weights+ take most of the RAM): every later row lookup that lands on a swapped page then waits for a disk read. If this process has+ more than min_swap_bytes in swap, read the whole table back in (MADV_POPULATE_READ). Contents are unchanged"""+ info = {"mode": self.mode, "swap_before": process_swap_bytes(), "populated": 0, "seconds": 0.0}+ if self.tables is None or info["swap_before"] is None or info["swap_before"] < min_swap_bytes:+ return info+ import time+ t0 = time.perf_counter()+ for t in self.tables:+ n = _madvise_range(t, _MADV_POPULATE_READ)+ if n < 0:+ info["error"] = "madvise(MADV_POPULATE_READ) failed"+ break+ info["populated"] += n+ info["seconds"] = round(time.perf_counter() - t0, 2)+ info["swap_after"] = process_swap_bytes()+ return info@overridedef unload(self):@@ -277,7 +345,7 @@ class NGramEmbedding(Module):@overridedef get_tensors(self):# The table is never resident as a whole in the general case; export/compile of this- # module is handled by the conversion pipeline (util/convert_ngram.py), not here+ # module is handled at conversion time, not herereturn {}@overridediff --git a/exllamav3/modules/ple.py b/exllamav3/modules/ple.pyindex f3ff065..68fc083 100644--- a/exllamav3/modules/ple.py+++ b/exllamav3/modules/ple.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom typing_extensions import overrideimport math+import osimport torchimport torch.nn.functional as Ffrom .module import Module@@ -296,13 +297,41 @@ class PLELayer(Module):return delta, conv_streamreturn self.forward_streams_reference(streams, emb, params, conv_state)+ def _streams_chain_hip(self, streams, key, value, conv_state):+ """ple_fn/ple_hip.hip chain; None when the shapes/dtypes are not the proved ones (caller keeps the torch chain)."""+ try:+ from .ple_fn import ple_hip+ if not (torch.version.hip and self.norm_key.rms_norm_eps == self.norm_query.rms_norm_eps == self.norm_conv.rms_norm_eps+ and self.norm_key.constant_bias == 1.0 and self.norm_key.constant_scale == 1.0+ and self.norm_query.constant_bias == 1.0 and self.norm_query.constant_scale == 1.0+ and self.norm_conv.constant_bias == 1.0 and self.norm_conv.constant_scale == 1.0+ and self.conv_state_len == ple_hip.ST and self.conv_dilation == 3 and self.conv_kernel_size == 4):+ return None+ bsz, seq = streams.shape[:2]+ key = key.reshape(bsz * seq, -1)+ value = value.reshape(bsz * seq, -1)+ if conv_state is not None:+ conv_state = conv_state.contiguous()+ wts = (self.norm_key.weight.data, self.norm_query.weight.data, self.norm_conv.weight.data)+ if not ple_hip.supported(key, value, streams, conv_state, wts, self.conv_w, 1.0, self.hc_mult, self.hidden_size):+ return None+ return ple_hip.ple_chain(key, value, streams, conv_state, *wts, self.conv_w,+ self.norm_key.rms_norm_eps, self.gate_scale)+ except Exception:+ return None+def forward_streams_reference(self, streams, emb, params, conv_state = None):"""Op-by-op form of forward_streams (torch + individual ext kernels)."""bsz, seq = streams.shape[:2]H, D = self.hc_mult, self.hidden_sizekey = self.key_proj.forward(emb, params).view(bsz, seq, H, D)- key = self.norm_key.forward(key, params, out_dtype = torch.float)value = self.value_proj.forward(emb, params) # (bsz, seq, hidden) fp16+ if os.environ.get("EXL3_PLE_HIP", "0") == "1":+ # hand HIP kernels for everything after the projections (bitwise equal to the torch chain below)+ out = self._streams_chain_hip(streams, key, value, conv_state)+ if out is not None:+ return out+ key = self.norm_key.forward(key, params, out_dtype = torch.float)query = self.norm_query.forward(streams, params, out_dtype = torch.float)# per-stream key/query dots as a batched (1, D) x (D, 1) matmul, then the fused gate# kernel: gated = sigmoid(signed_sqrt(dot * scale)) * value broadcast over streams@@ -315,7 +344,12 @@ class PLELayer(Module):gated = _ple_gate_torch(gate, value, self.gate_scale)normed = self.norm_conv.forward(gated, params, out_dtype = torch.half).flatten(-2)conv_out, conv_stream = self._short_conv(normed, conv_state)- delta = gated + conv_out.view(bsz, seq, H, D)+ 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))+ else:+ delta = gated + conv_out.view(bsz, seq, H, D)return delta, conv_streamdef _prepare_ids(self, ids: torch.Tensor) -> torch.Tensor:@@ -372,6 +406,10 @@ class PLELayer(Module):conventions as ShortConv: state window in [:, ..., :width], history writes right-alignedfor rewind)."""+ pending = params.pop("hc_pending", None) # EXL3_PF_GR_FUSE / EXL3_PF_HC_FUSE: apply the deferred residual first+ if pending is not None:+ from .hyperconnections import HyperConnection+ HyperConnection.flush_pending(x, pending)bsz, seq = x.shape[:2]ids = params.get("input_ids")if ids is None:@@ -399,4 +437,7 @@ class PLELayer(Module):id_state[s, :ctx].copy_(history[i, -ctx:])else:delta, _ = self.forward_streams(x, history, params)+ if os.environ.get("EXL3_PFE_PLE", "1") != "0":+ # delta is a fresh tensor owned here; x stays untouched (conversion-safe). fp32 add commutes exactly+ return delta.add_(x)return x + deltadiff --git a/exllamav3/modules/ple_fn/__init__.py b/exllamav3/modules/ple_fn/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/exllamav3/modules/ple_fn/ple_hip.hip b/exllamav3/modules/ple_fn/ple_hip.hipnew file mode 100644index 0000000..6c8f6f1--- /dev/null+++ b/exllamav3/modules/ple_fn/ple_hip.hip@@ -0,0 +1,276 @@+// Hand HIP kernels for the two torch fallbacks left in the Qwen prefill (ROCm, gfx1151, wave32):+// * PLELayer.forward_streams_reference (everything after the key/value projections)+// * deinterleave_qg+// Every kernel is bitwise identical to the torch chain it replaces. Rounding points and reduction orders+// (all found by probing torch on the target device, see VERDICT.md):+// - grouped RMS mean(x^2): torch reduce kernel for a (rows>=16, 2560) fp32 tensor = one wave32 per row,+// lane t sums vec4 groups (t + 32 j) into 4 accumulators (j = 0..19, in order), acc0+acc1, +acc2, +acc3,+// then shfl_down tree with offsets 1,2,4,8,16, then times float(1/2560). x*x is rounded before the add (no fma).+// - bmm (query . key): one sequential fp32 fma chain k = 0..2559, start 0.+// - depthwise conv k=4, dilation 3: fp32 chain over taps 0..3 (products of halves are exact), rounded to half.+// Compiled with -ffp-contract=off; every fma is explicit.+#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include <stdint.h>++#ifndef DD+#define DD 2560 // hidden size D (per stream)+#endif+#define HS 4 // hyper-connection streams+#define NV (DD / 4) // vec4 groups per row (640)+#define NJ (NV / 32) // iterations per lane (20)+#define ST 9 // conv state length (kernel 4 - 1) * dilation 3+#define DIL 3+#define TT 64 // tile edge of the transposing kernels+#define PITCH_V 66 // LDS pitch (halves) of the value tile in ple_norm_conv+#define PITCH_I 75 // LDS pitch (halves) of the conv input tile+#define PITCH_O 66 // LDS pitch (halves) of the conv output tile++// ---- index expressions: the bounds checker (check_ple_bounds.py) evaluates these macros over the real shapes ----+#define IX_K1_ROW(blk, wv) ((blk) * 8 + (wv))+#define IX_K1_SRC(rl, t, j) ((rl) * DD + ((t) + 32 * (j)) * 4)+#define IX_K2_ROW(blk, tid) ((blk) * 64 + (tid))+#define IX_K2_SRC(i, kk) ((i) * DD + (kk) * 8)+#define IX_K2_W(i, kk) (((i) % HS) * DD + (kk) * 8)+#define IX_K3_ROW(blk, sl) ((blk) * TT + (sl))+#define IX_K3_VAL(row, dc, dl) ((row) * DD + (dc) * TT + (dl))+#define IX_K3_W(h, dc, dl) ((h) * DD + (dc) * TT + (dl))+#define IX_K3_OUT(b, ch, s, S) (((size_t)(b) * HS * DD + (ch)) * (size_t)(ST + (S)) + ST + (s))+#define IX_K3B_OUT(b, ch, j, S) (((size_t)(b) * HS * DD + (ch)) * (size_t)(ST + (S)) + (j))+#define IX_K3B_SRC(b, ch, j) (((size_t)(b) * HS * DD + (ch)) * ST + (j))+#define IX_K4_IN(b, c, j, S) (((size_t)(b) * HS * DD + (c)) * (size_t)(ST + (S)) + (j))+#define IX_K4_ROW(b, s, S) ((size_t)(b) * (S) + (s))+#define IX_K4_VAL(row, d) ((row) * DD + (d))+#define IX_K4_OUT(row, c) ((size_t)(row) * HS * DD + (c))+#define IX_DQ_SRC(i, hd8, d) (((i) / (hd8)) * 2 * (hd8) + (d))++static __device__ __forceinline__ float h2f(uint16_t u) { return __half2float(__ushort_as_half(u)); }+static __device__ __forceinline__ float bf2f(uint16_t u) { return __uint_as_float(((uint32_t) u) << 16); }+// Materialize an fp32 value: without it the backend folds fptrunc(fmul/fma) into one v_fma_mix_f16 (single rounding, and+// -0 + +0 = +0), which breaks bitwise equality with torch's two separate roundings.+static __device__ __forceinline__ float rnd32(float v) { asm volatile("" : "+v"(v)); return v; }+static __device__ __forceinline__ float clamp_h(float v) {+ // torch.clamp(min=-65504, max=65504) on a float widened from fp16 (NaN passes through)+ if (v > 65504.0f) v = 65504.0f;+ if (v < -65504.0f) v = -65504.0f;+ return v;+}++// Torch's row reduction tree for mean(x^2): acc[4] per lane, combined sequentially, shfl_down 1..16, times 1/D+static __device__ __forceinline__ float tree_finish(float a0, float a1, float a2, float a3) {+ float v = a0;+ v = v + a1; v = v + a2; v = v + a3;+ for (int off = 1; off < 32; off <<= 1) v = v + __shfl_down(v, off, 32);+ return v;+}+static __device__ __forceinline__ float rs_from_sum(float tot, float eps) {+ const float mean = tot * (1.0f / (float) DD);+ // torch.rsqrt on this device is the correctly rounded 1/sqrt (hardware rsq differs in ~11 % of inputs)+ return (float) (1.0 / sqrt((double) (mean + eps)));+}++// ---- K1: 1/rms of every key row (half, clamped) and query row (float). One wave per row.+// rows [0, RH) = key rows (r, h), rows [RH, 2 RH) = query rows.+extern "C" __global__ __launch_bounds__(256)+void ple_rs(const uint16_t* __restrict__ key, const float* __restrict__ strm, float* __restrict__ rs, int RH, float eps)+{+ const int t = threadIdx.x & 31, wv = threadIdx.x >> 5;+ const int row = IX_K1_ROW(blockIdx.x, wv);+ if (row >= 2 * RH) return;+ const bool isq = row >= RH;+ const int rl = isq ? row - RH : row;+ float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f;+ if (!isq) {+ const uint2* p = (const uint2*) key;+ for (int j = 0; j < NJ; j++) {+ uint2 u = p[IX_K1_SRC(rl, t, j) / 4];+ float x0 = clamp_h(h2f(u.x & 0xffff)), x1 = clamp_h(h2f(u.x >> 16));+ float x2 = clamp_h(h2f(u.y & 0xffff)), x3 = clamp_h(h2f(u.y >> 16));+ float s0 = x0 * x0, s1 = x1 * x1, s2 = x2 * x2, s3 = x3 * x3;+ a0 = a0 + s0; a1 = a1 + s1; a2 = a2 + s2; a3 = a3 + s3;+ }+ } else {+ const float4* p = (const float4*) strm;+ for (int j = 0; j < NJ; j++) {+ float4 u = p[IX_K1_SRC(rl, t, j) / 4];+ float s0 = u.x * u.x, s1 = u.y * u.y, s2 = u.z * u.z, s3 = u.w * u.w;+ a0 = a0 + s0; a1 = a1 + s1; a2 = a2 + s2; a3 = a3 + s3;+ }+ }+ float v = tree_finish(a0, a1, a2, a3);+ if (t == 0) rs[row] = rs_from_sum(v, eps);+}++// ---- K2: gate. One lane per (row, stream): sequential fma chain over the normalized key . query, then+// s = sigmoid(sign(g) sqrt(max(|g|, 1e-6))), g = dot * gate_scale. Normalized values recomputed (same ops as torch).+extern "C" __global__ __launch_bounds__(64)+void ple_gate(const uint16_t* __restrict__ key, const float* __restrict__ strm, const float* __restrict__ rs,+ const uint16_t* __restrict__ wk, const uint16_t* __restrict__ wq, float* __restrict__ gs, int RH, float gate_scale)+{+ const int i = IX_K2_ROW(blockIdx.x, threadIdx.x);+ if (i >= RH) return;+ const float rk = rs[i], rq = rs[RH + i];+ float acc = 0.f;+ for (int kk = 0; kk < DD / 8; kk++) {+ const uint4 ku = *(const uint4*) (key + IX_K2_SRC(i, kk));+ const float4 q0 = *(const float4*) (strm + IX_K2_SRC(i, kk));+ const float4 q1 = *(const float4*) (strm + IX_K2_SRC(i, kk) + 4);+ const uint4 wku = *(const uint4*) (wk + IX_K2_W(i, kk));+ const uint4 wqu = *(const uint4*) (wq + IX_K2_W(i, kk));+ const uint32_t kv[4] = {ku.x, ku.y, ku.z, ku.w}, wkv[4] = {wku.x, wku.y, wku.z, wku.w}, wqv[4] = {wqu.x, wqu.y, wqu.z, wqu.w};+ const float qv[8] = {q0.x, q0.y, q0.z, q0.w, q1.x, q1.y, q1.z, q1.w};+#pragma unroll+ for (int u = 0; u < 8; u++) {+ const uint32_t kw = kv[u >> 1], kww = wkv[u >> 1], qww = wqv[u >> 1];+ const int sh = (u & 1) * 16;+ float kf = clamp_h(h2f((kw >> sh) & 0xffff));+ float kn = kf * rk;+ kn = kn * (bf2f((kww >> sh) & 0xffff) + 1.0f);+ float qn = qv[u] * rq;+ qn = qn * (bf2f((qww >> sh) & 0xffff) + 1.0f);+ acc = fmaf(qn, kn, acc);+ }+ }+ const float g = acc * gate_scale;+ const float a = fabsf(g);+ const float am = a < 1e-6f ? 1e-6f : a;+ const float sgn = (float) ((0.0f < g) - (g < 0.0f));+ const float ss = sgn * sqrtf(am);+ gs[i] = 1.0f / (1.0f + expf(-ss));+}++// ---- K3: gated = s * value (fp32), grouped RMS over D with the torch tree, normed = half(gated * rs * (w + 1)),+// written transposed into conv_stream[b, ch, ST + s]. One block = 64 consecutive rows x one stream h.+extern "C" __global__ __launch_bounds__(256)+void ple_norm_conv(const uint16_t* __restrict__ value, const float* __restrict__ gs, const uint16_t* __restrict__ wc,+ uint16_t* __restrict__ cstream, int RT, int S, float eps)+{+ __shared__ float s_rs[TT];+ __shared__ uint16_t s_val[TT * PITCH_V];+ const int tid = threadIdx.x, t = tid & 31, wv = tid >> 5;+ const int h = blockIdx.y;+ // pass 1: per-row 1/rms of gated (wave wv owns rows wv*8 .. wv*8+7)+ for (int r8 = 0; r8 < 8; r8++) {+ const int sl = wv * 8 + r8;+ const int row = IX_K3_ROW(blockIdx.x, sl);+ float rsv = 0.f;+ if (row < RT) {+ const float s = gs[row * HS + h];+ const uint2* p = (const uint2*) value;+ float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f;+ for (int j = 0; j < NJ; j++) {+ uint2 u = p[IX_K1_SRC(row, t, j) / 4];+ float g0 = s * h2f(u.x & 0xffff), g1 = s * h2f(u.x >> 16), g2 = s * h2f(u.y & 0xffff), g3 = s * h2f(u.y >> 16);+ float s0 = g0 * g0, s1 = g1 * g1, s2 = g2 * g2, s3 = g3 * g3;+ a0 = a0 + s0; a1 = a1 + s1; a2 = a2 + s2; a3 = a3 + s3;+ }+ rsv = rs_from_sum(tree_finish(a0, a1, a2, a3), eps);+ }+ if (t == 0) s_rs[sl] = rsv;+ }+ __syncthreads();+ // pass 2: d chunks of 64+ const int sl = tid & 63, dd = tid >> 6;+ const int row = IX_K3_ROW(blockIdx.x, sl);+ const bool ok = row < RT;+ const int b = ok ? row / S : 0, s_in = ok ? row % S : 0;+ const float s_g = ok ? gs[row * HS + h] : 0.f;+ const float rsv = s_rs[sl];+ for (int dc = 0; dc < DD / TT; dc++) {+ // coalesced load of the value tile: row-major, each row 64 halves+ for (int e = tid; e < TT * TT; e += 256) {+ const int rl = e >> 6, dl = e & 63;+ const int rrow = IX_K3_ROW(blockIdx.x, rl);+ s_val[rl * PITCH_V + dl] = rrow < RT ? value[IX_K3_VAL(rrow, dc, dl)] : (uint16_t) 0;+ }+ __syncthreads();+ if (ok) {+#pragma unroll 4+ for (int i = 0; i < TT / 4; i++) {+ const int dl = dd + 4 * i;+ float g = s_g * h2f(s_val[sl * PITCH_V + dl]);+ float x = g * rsv;+ x = rnd32(x * (bf2f(wc[IX_K3_W(h, dc, dl)]) + 1.0f));+ const int ch = h * DD + dc * TT + dl;+ cstream[IX_K3_OUT(b, ch, s_in, S)] = __half_as_ushort(__float2half_rn(x));+ }+ }+ __syncthreads();+ }+}++// ---- K3b: conv state columns of conv_stream (zeros when there is no state)+extern "C" __global__ __launch_bounds__(256)+void ple_copy_state(const uint16_t* __restrict__ cstate, uint16_t* __restrict__ cstream, int B, int S, int has_state)+{+ const size_t n = (size_t) B * HS * DD * ST;+ const size_t i = (size_t) blockIdx.x * 256 + threadIdx.x;+ if (i >= n) return;+ const int j = (int) (i % ST);+ const size_t bc = i / ST; // b * HS*DD + ch+ const int b = (int) (bc / (HS * DD)), ch = (int) (bc % (HS * DD));+ cstream[IX_K3B_OUT(b, ch, j, S)] = has_state ? cstate[IX_K3B_SRC(b, ch, j)] : (uint16_t) 0;+}++// ---- K4: depthwise dilated conv + silu over the transposed stream, delta = gated + conv (fp32), written (row, c).+// One block = 64 channels (inside one stream) x 64 consecutive positions of one batch element.+extern "C" __global__ __launch_bounds__(256)+void ple_conv_out(const uint16_t* __restrict__ cstream, const uint16_t* __restrict__ convw, const uint16_t* __restrict__ value,+ const float* __restrict__ gs, float* __restrict__ delta, int S)+{+ __shared__ uint16_t s_in[TT * PITCH_I];+ __shared__ uint16_t s_out[TT * PITCH_O];+ const int tid = threadIdx.x;+ const int ct = blockIdx.x, st = blockIdx.y, b = blockIdx.z;+ const int c0 = ct * TT, s0 = st * TT;+ const int h = c0 / DD, d0 = c0 % DD;+ // load the input window: channel cl, columns s0 .. s0 + 63 + ST (stream columns)+ for (int e = tid; e < TT * (TT + ST); e += 256) {+ const int cl = e / (TT + ST), j = e % (TT + ST);+ const int col = s0 + j;+ s_in[cl * PITCH_I + j] = col < ST + S ? cstream[IX_K4_IN(b, c0 + cl, col, S)] : (uint16_t) 0;+ }+ __syncthreads();+ // conv + silu: thread -> (channel cl, positions sl0, sl0+4, ...) with consecutive threads on consecutive positions+ {+ const int sl = tid & 63, cg = tid >> 6;+ for (int i = 0; i < TT / 4; i++) {+ const int cl = cg + 4 * i;+ const uint2 wu = *(const uint2*) (convw + (size_t) (c0 + cl) * 4);+ const float w0 = h2f(wu.x & 0xffff), w1 = h2f(wu.x >> 16), w2 = h2f(wu.y & 0xffff), w3 = h2f(wu.y >> 16);+ float acc = 0.f;+ acc = fmaf(w0, h2f(s_in[cl * PITCH_I + sl + 0 * DIL]), acc);+ acc = fmaf(w1, h2f(s_in[cl * PITCH_I + sl + 1 * DIL]), acc);+ acc = fmaf(w2, h2f(s_in[cl * PITCH_I + sl + 2 * DIL]), acc);+ acc = rnd32(fmaf(w3, h2f(s_in[cl * PITCH_I + sl + 3 * DIL]), acc));+ const float y = __half2float(__float2half_rn(acc));+ const float sv = rnd32(y / (1.0f + expf(-y)));+ s_out[sl * PITCH_O + cl] = __half_as_ushort(__float2half_rn(sv));+ }+ }+ __syncthreads();+ // write: thread -> channel cl, rows sl0 + 4 i+ {+ const int cl = tid & 63, sg = tid >> 6;+ for (int i = 0; i < TT / 4; i++) {+ const int sl = sg + 4 * i;+ const int s = s0 + sl;+ if (s >= S) continue;+ const size_t row = IX_K4_ROW(b, s, S);+ const float g = rnd32(gs[row * HS + h] * h2f(value[IX_K4_VAL(row, d0 + cl)]));+ delta[IX_K4_OUT(row, c0 + cl)] = g + h2f(s_out[sl * PITCH_O + cl]);+ }+ }+}++// ---- deinterleave_qg: [.., heads, (q: hd, g: hd)] -> contiguous q and g (pure 16-byte copy)+extern "C" __global__ __launch_bounds__(256)+void deinterleave_qg(const uint4* __restrict__ qg, uint4* __restrict__ q, uint4* __restrict__ g, int hd8, size_t n8)+{+ const size_t i = (size_t) blockIdx.x * 256 + threadIdx.x;+ if (i >= n8) return;+ const size_t d = i % hd8;+ const size_t src = IX_DQ_SRC(i, hd8, d);+ q[i] = qg[src];+ g[i] = qg[src + hd8];+}diff --git a/exllamav3/modules/ple_fn/ple_hip.py b/exllamav3/modules/ple_fn/ple_hip.pynew file mode 100644index 0000000..045f021--- /dev/null+++ b/exllamav3/modules/ple_fn/ple_hip.py@@ -0,0 +1,134 @@+# Loader + launchers for ple_hip.hip (hand HIP kernels: PLE streams chain after the projections, deinterleave_qg).+# hipcc genco (cached by source hash), launched through torch's libamdhip64 on the current stream.+import ctypes, hashlib, os, shutil, subprocess+import torch++_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ple_hip.hip")+_state = {}+HS, DD, ST = 4, 2560, 9+_FUNCS = ("ple_rs", "ple_gate", "ple_norm_conv", "ple_copy_state", "ple_conv_out", "deinterleave_qg")+++def _hipcc():+ for p in (os.environ.get("EXL3_HIPCC"), os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),+ "$EXL3_ROOT",+ "$EXL3_ROOT",+ shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):+ if p and os.path.isfile(p):+ return p+ raise RuntimeError("ple_hip: hipcc not found (set EXL3_HIPCC)")+++def compile_hsaco(arch="gfx1151", src_path=None):+ src_path = src_path or _SRC+ src = open(src_path, "rb").read()+ flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off"]+ gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")+ if os.path.isdir(gcc):+ flags.append(f"--gcc-install-dir={gcc}")+ tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]+ cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"ple_{arch}_{tag}.hsaco")+ if not os.path.isfile(cache):+ os.makedirs(os.path.dirname(cache), exist_ok=True)+ tmp = cache + f".{os.getpid()}.tmp"+ r = subprocess.run([_hipcc(), *flags, "-o", tmp, src_path], capture_output=True, text=True)+ if r.returncode:+ raise RuntimeError(r.stderr[-3000:])+ os.replace(tmp, cache)+ return cache+++def _load():+ if "fns" in _state:+ return _state["fns"]+ cache = compile_hsaco(torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])+ lib = ctypes.CDLL(os.path.join(os.path.dirname(torch.__file__), "lib", "libamdhip64.so"))+ torch.cuda.init()+ mod = ctypes.c_void_p()+ if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0:+ raise RuntimeError("ple_hip: hipModuleLoad failed")+ fns = {}+ for n in _FUNCS:+ fn = ctypes.c_void_p()+ if lib.hipModuleGetFunction(ctypes.byref(fn), mod, n.encode()) != 0:+ raise RuntimeError("ple_hip: no function " + n)+ fns[n] = fn+ lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3+ _state["lib"], _state["fns"], _state["mod"] = lib, fns, mod+ return fns+++def _launch(name, grid, block, args):+ fn = _load()[name]+ cargs = []+ for a in args:+ if isinstance(a, torch.Tensor):+ cargs.append(ctypes.c_void_p(a.data_ptr()))+ elif isinstance(a, float):+ cargs.append(ctypes.c_float(a))+ elif isinstance(a, tuple): # ("sz", value): size_t+ cargs.append(ctypes.c_size_t(a[1]))+ else:+ cargs.append(ctypes.c_int(a))+ params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])+ g = tuple(grid) + (1,) * (3 - len(grid))+ r = _state["lib"].hipModuleLaunchKernel(fn, g[0], g[1], g[2], block, 1, 1, 0,+ torch.cuda.current_stream().cuda_stream, params, None)+ if r != 0:+ raise RuntimeError(f"ple_hip: launch of {name} failed ({r})")+++def supported(key, value, streams, conv_state, norm_w, conv_w, constant_scale, hc_mult, hidden):+ """Shapes and dtypes the kernels were proved for (everything else keeps the torch reference)."""+ if hc_mult != HS or hidden != DD or constant_scale != 1.0:+ return False+ ts = (key, value, streams, conv_w) + tuple(norm_w)+ if not all(t.is_cuda and t.is_contiguous() and t.data_ptr() % 16 == 0 for t in ts):+ return False+ if key.dtype != torch.half or value.dtype != torch.half or streams.dtype != torch.float or conv_w.dtype != torch.half:+ return False+ if any(w.dtype != torch.bfloat16 or w.numel() != HS * DD for w in norm_w):+ return False+ if conv_w.numel() != HS * DD * 4:+ return False+ if conv_state is not None and (conv_state.dtype != torch.half or not conv_state.is_contiguous()):+ return False+ return True+++def ple_chain(key, value, streams, conv_state, norm_key_w, norm_query_w, norm_conv_w, conv_w, eps, gate_scale,+ delta=None, conv_stream=None, dbg=None):+ """+ key (B*S, H*D) half, value (B*S, D) half, streams (B, S, H, D) fp32, conv_state (B, H*D, 9) half or None,+ norm weights (H*D) bf16 (raw, +1 applied inside), conv_w (H*D, 1, 4) half.+ Returns delta (B, S, H, D) fp32 and conv_stream (B, H*D, 9 + S) half, bitwise equal to the torch chain.+ """+ B, S = streams.shape[:2]+ RT, RH = B * S, B * S * HS+ dev = streams.device+ if delta is None:+ delta = torch.empty_like(streams)+ if conv_stream is None:+ conv_stream = torch.empty((B, HS * DD, ST + S), dtype=torch.half, device=dev)+ rs = torch.empty(2 * RH, dtype=torch.float, device=dev)+ gs = torch.empty(RH, dtype=torch.float, device=dev)+ eps = float(eps); gate_scale = float(gate_scale)+ nrow = 2 * RH+ _launch("ple_rs", ((nrow + 7) // 8,), 256, (key, streams, rs, RH, eps))+ _launch("ple_gate", ((RH + 63) // 64,), 64, (key, streams, rs, norm_key_w, norm_query_w, gs, RH, gate_scale))+ _launch("ple_norm_conv", ((RT + 63) // 64, HS), 256, (value, gs, norm_conv_w, conv_stream, RT, S, eps))+ n = B * HS * DD * ST+ cs = conv_state if conv_state is not None else conv_stream+ _launch("ple_copy_state", ((n + 255) // 256,), 256, (cs, conv_stream, B, S, 1 if conv_state is not None else 0))+ _launch("ple_conv_out", (HS * DD // 64, (S + 63) // 64, B), 256, (conv_stream, conv_w, value, gs, delta, S))+ if dbg is not None:+ dbg.update(rs=rs, gs=gs)+ return delta, conv_stream+++def deinterleave_qg(qg, q, g, head_dim):+ assert head_dim % 8 == 0 and qg.is_contiguous() and q.is_contiguous() and g.is_contiguous()+ assert q.numel() == g.numel() and q.numel() * 2 == qg.numel()+ assert all(t.data_ptr() % 16 == 0 for t in (qg, q, g))+ n8 = q.numel() // 8+ _launch("deinterleave_qg", ((n8 + 255) // 256,), 256, (qg, q, g, head_dim // 8, ("sz", n8)))diff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.pyindex 30a0265..537a1bb 100644--- a/exllamav3/modules/qsa_indexer.py+++ b/exllamav3/modules/qsa_indexer.py@@ -9,6 +9,26 @@ from .linear import Linearfrom .rmsnorm import RMSNormfrom ..model.config import Config+# row-invariant verify in the sparse regime. In a verify forward (R = 2..8 rows) the indexer's qk+# projection, the per-row top-k selection and the gathered sparse attention are launched once for R rows, a different+# float order than the R = 1 launches plain decode makes. Both knobs run the exact R = 1 call per row.+# EXL3_VERIFY_QSA_PROJ=1 qk projection per row+# EXL3_VERIFY_QSA_ATTN=all|sel|att selection and attention per row / selection only / attention only+# EXL3_QSA_SHADOW=1 (diagnostic): also run the per-row twin and count bitwise mismatches in SHADOW.+VERIFY_QSA_PROJ = {"on": os.environ.get("EXL3_VERIFY_QSA_PROJ", "0") not in ("", "0")}+VERIFY_QSA_ATTN = {"mode": {"": "", "0": "", "1": "all", "all": "all", "sel": "sel", "att": "att"}.get(os.environ.get("EXL3_VERIFY_QSA_ATTN", ""), "")}+QSA_SHADOW = {"on": os.environ.get("EXL3_QSA_SHADOW", "0") not in ("", "0")}+SHADOW: dict = {}+++def shadow_note(key: str, a: torch.Tensor, b: torch.Tensor) -> None:+ n = SHADOW.setdefault(key, [0, 0, 0.0])+ n[0] += 1+ if not torch.equal(a, b):+ n[1] += 1+ if a.is_floating_point():+ n[2] = max(n[2], float((a.float() - b.float()).abs().max()))+"""QSA (Qwen sparse attention) indexer: selects which tokens each query may attend to, at 4-tokenblock granularity (Qwen3.8-Flash-Next full-attention layers).@@ -38,6 +58,20 @@ def _rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensorreturn torch.cat((x_rope * cos + rot * sin, x_pass), dim = -1)+_PF_HIP = {"ok": None}+def _pf_hip_ready() -> bool:+ """EXL3_QSA_PF_HIP (default 1, 0 = Triton pair): first use loads the proven HIP prefill kernel; a missing compiler or proof disables it with a warning."""+ if _PF_HIP["ok"] is None:+ try:+ from .attention_fn.qsa_prefill_hip import _load+ _load()+ _PF_HIP["ok"] = True+ except Exception as e:+ print(f" !! QSA prefill HIP kernel unavailable, using the Triton pair: {str(e)[:200]}")+ _PF_HIP["ok"] = False+ return _PF_HIP["ok"]++class QSAIndexer(Module):def __init__(@@ -486,7 +520,17 @@ class QSAIndexer(Module):npr = bt.shape[1]page_size = layer.raw_k.shape[1]- qk = self.index_qk_proj.forward(x.contiguous(), params).view(R, (H + 1) * dk)+ xc = x.contiguous()+ qk = self.index_qk_proj.forward(xc, params).view(R, (H + 1) * dk)+ if bsz == 1 and 1 < seqlen <= 8 and params.get("dflash_verify") and (VERIFY_QSA_PROJ["on"] or QSA_SHADOW["on"]):+ qk = qk.clone()+ p1 = dict(params, dflash_verify = False)+ rows1 = torch.cat([self.index_qk_proj.forward(xc[:, i:i + 1], p1).reshape(1, (H + 1) * dk).clone()+ for i in range(seqlen)], dim = 0)+ if QSA_SHADOW["on"]:+ shadow_note("proj", qk, rows1)+ if VERIFY_QSA_PROJ["on"]:+ qk = rows1q = self._workspace(R, R * H * dk, torch.half, "qsa_up_q", dev) \.view(bsz, seqlen, H, dk)kraw = self._workspace(R, R * dk, torch.half, "qsa_up_k", dev) \@@ -648,6 +692,7 @@ class QSAIndexer(Module):q_idx: torch.Tensor,block_table: torch.Tensor,cache_seqlens_cpu: torch.Tensor,+ indices: torch.Tensor | None = None,) -> torch.Tensor:"""Sparse paged attention through the gathered-GQA kernel: per-row selection over the@@ -656,12 +701,14 @@ class QSAIndexer(Module):OOMed on long prefills). Serves cached prefill chunks and every eager sparse fallback(bsz > 1, MTP verify). K/V for the current tokens must already be written to the cache.q: (bsz, seq, num_q_heads, head_dim) roped; q_idx: roped indexer queries from- update_planes. Returns (bsz, seq, num_q_heads, head_dim) fp16.+ update_planes. indices: precomputed selection (bsz * seq, K_pad), else computed here.+ Returns (bsz, seq, num_q_heads, head_dim) fp16."""from .attention_fn.qsa_triton import qsa_sparse_attend_rowsfrom ..cache.quant import CacheLayer_quantbsz, seq = q.shape[:2]- indices = self.select_indices_paged(layer, q_idx, block_table, cache_seqlens_cpu)+ if indices is None:+ indices = self.select_indices_paged(layer, q_idx, block_table, cache_seqlens_cpu)bt_rows = block_table.int().unsqueeze(1).expand(bsz, seq, -1) \.reshape(bsz * seq, -1).contiguous()if isinstance(layer, CacheLayer_quant):@@ -672,10 +719,46 @@ class QSAIndexer(Module):k_arg = layer.k.view(-1, attn.num_kv_heads, attn.head_dim)v_arg = layer.v.view(-1, attn.num_kv_heads, attn.head_dim)qc, page_size = None, layer.k.shape[1]+ q_rows = q.reshape(bsz * seq, attn.num_q_heads, attn.head_dim).contiguous()+ if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and qc is None and bsz == 1 and seq >= 64 and seq <= 4096 * 4+ and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)+ and q_rows.dtype == torch.half and k_arg.dtype == torch.half and _pf_hip_ready()):+ # one wave per (row, kv head) HIP kernel, bit-identical to the Triton pair (fp16 cache, prefill chunks only)+ from .attention_fn.qsa_prefill_hip import qsa_prefill_hip+ o = qsa_prefill_hip(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)+ return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)o = qsa_sparse_attend_rows(- q.reshape(bsz * seq, attn.num_q_heads, attn.head_dim).contiguous(),+ q_rows,k_arg, v_arg, indices, attn.sm_scale,block_table = bt_rows, page_size = page_size,qc = qc, n_kv_heads = attn.num_kv_heads,)return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)++ def sparse_attend_verify(self, layer, attn, q, q_idx, block_table, cache_seqlens_cpu) -> torch.Tensor:+ """sparse_attend for a verify forward: optionally row-invariant (the R = 1 call per row, as plain decode)."""+ bsz, seq = q.shape[:2]+ mode = VERIFY_QSA_ATTN["mode"]+ if not (bsz == 1 and 1 < seq <= 8) or not (mode or QSA_SHADOW["on"]):+ return self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu)+ def row_idx(i):+ return self.select_indices_paged(layer, q_idx[:, i:i + 1], block_table, cache_seqlens_cpu + i).clone()+ def attend_rows(idx):+ return torch.cat([self.sparse_attend(layer, attn, q[:, i:i + 1], q_idx[:, i:i + 1], block_table,+ cache_seqlens_cpu + i, indices = idx[i:i + 1]).clone()+ for i in range(seq)], dim = 1)+ idx_rows = torch.cat([row_idx(i) for i in range(seq)], dim = 0)+ idx_all = self.select_indices_paged(layer, q_idx, block_table, cache_seqlens_cpu)+ if QSA_SHADOW["on"]:+ o_all = self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_all)+ shadow_note("sel", idx_all, idx_rows)+ shadow_note("att_rowwise_vs_batched_same_idx", o_all, attend_rows(idx_all))+ shadow_note("att_rowwise_vs_batched_row_idx", self.sparse_attend(+ layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_rows), attend_rows(idx_rows))+ if mode == "all":+ return attend_rows(idx_rows)+ if mode == "sel": # per-row selection, one attention launch+ return self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_rows)+ if mode == "att": # one selection, per-row attention+ return attend_rows(idx_all)+ return self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_all)diff --git a/exllamav3/modules/quant/exl3.py b/exllamav3/modules/quant/exl3.pyindex 407036f..961cffc 100644--- a/exllamav3/modules/quant/exl3.py+++ b/exllamav3/modules/quant/exl3.py@@ -37,6 +37,167 @@ _EXL3_GEMV_HIP_MMODE2_VARIANTS = frozenset({no_fused_reconstruct = os.environ.get("EXL3_NO_FUSED_RECONSTRUCT", "0") != "0"+# row-padded activations for the prefill GEMMs. An fp16 row of K = 6144 is 12288 B; at that pitch the+# rocBLAS GEMM reads A at about half rate (out_proj 50 % of peak in place). One extra 128 B per row runs the same+# product, bit-exact, at 87-90 %. Keep PAD_ELEMS and the K rule in step with exllamav3_ext/pad_pitch.h.+_PAD_HIP = torch.version.hip is not None+PAD_ELEMS = 64+PAD_MIN_ROWS = 1024 # the fused reconstruct path (no input Hadamard launch) starts at 1024 rows++def _pad_view_ok(x: torch.Tensor) -> bool:+ """x is one (rows, k) matrix with columns contiguous and a single row pitch >= k (leading dims collapsible)."""+ if x.dim() < 2 or x.stride(-1) != 1:+ return False+ k = x.shape[-1]+ if x.stride(-2) < k:+ return False+ for i in range(x.dim() - 3, -1, -1):+ if x.shape[i + 1] != 1 and x.stride(i) != x.stride(i + 1) * x.shape[i + 1]:+ return False+ return True++# Consumer-side padding: a producer we do not own hands a contiguous x whose pitch is a hazard; copy it once into a padded+# buffer (one read + one write of x, bit-exact) before the GEMM. EXL3_PAD_COPY=0 turns it off (read per call).+def pad_copy_in(x: torch.Tensor, k: int) -> torch.Tensor:+ """x is (rows, k) fp16 contiguous with a hazard pitch: return a (rows, k) view at row pitch k + PAD_ELEMS, else x."""+ if (not _PAD_HIP or x.dtype not in (torch.half, torch.bfloat16) or x.dim() != 2 or (k * 2) % 4096 != 0 or x.shape[0] < PAD_MIN_ROWS+ or not x.is_contiguous() or x.data_ptr() % 16 != 0 or os.environ.get("EXL3_PAD_COPY", "1") == "0" or os.environ.get("EXL3_OPROJ_PAD", "1") == "0"):+ return x+ pitch = k + PAD_ELEMS+ buf = torch.empty((x.shape[0], pitch), dtype = x.dtype, device = x.device)+ y = buf[:, :k]+ ext.pad_copy(x, y, pitch)+ return y++def _pad_eligible(lin, k: int, rows: int, params: dict) -> bool:+ """One predicate for producer and consumer: this linear can take a row-padded input of k columns."""+ if not _PAD_HIP or rows < PAD_MIN_ROWS or k % 128 != 0:+ return False+ inner = getattr(lin, "inner", lin)+ if type(inner).__name__ != "LinearEXL3" or inner.in_features != k or inner.out_features % 128 != 0:+ return False+ if no_fused_reconstruct or inner.config.infer_params.no_reconstruct or inner.bias is not None:+ return False+ if any(p in params for p in ("capture", "quant_preserve", "ovr", "reconstruct")):+ return False+ if getattr(lin, "lora_a_tensors", None):+ return False+ if getattr(lin, "pre_scale", 1.0) != 1.0 or getattr(lin, "post_scale", 1.0) != 1.0 or getattr(lin, "softcap", 0.0) != 0.0:+ return False+ return True++def row_pad_pitch(lin, k: int, rows: int, params: dict) -> int:+ """Row pitch (elements) a producer should give the activation of `lin` (0 = leave it contiguous).+ EXL3_OPROJ_PAD=0 turns it off (read per call)."""+ if os.environ.get("EXL3_OPROJ_PAD", "1") == "0" or (k * 2) % 1024 != 0:+ return 0+ return k + PAD_ELEMS if _pad_eligible(lin, k, rows, params) else 0++# hadP: prefill reconstruct cache. A long prefill runs as several row-chunks, and every+# LinearEXL3 reconstructs its (rows-independent!) fp16 weight once per chunk, so the+# same weight is rebuilt once per chunk: 2x at 4K, N-chunk-times beyond. The reconstruct+# is a pure function of the trellis, so keeping the fp16 result and reusing it on the next+# chunk is bit-exact. LRU with a byte budget (EXL3_HAD_PF_FAST_MB, default 2048): the+# unique fp16 weight set of GLM-5.3-Flash is 14.4 GB and cannot all be held.+# EXL3_HAD_PF_FAST=0 (default) leaves the code path untouched.+# EXL3_HAD_PF_FAST_PRIORITY=1 (default) admits a weight only if its measured cost per+# written MB (_had_cost_per_mb, filled in by the unit benchmark) is at or above the best+# cost-per-byte the budget can still afford, so a small budget buys the shapes the kernel+# is worst at rather than an arbitrary LRU slice.+# NOTE: the knobs are read per call, not at import: the A/B harness (glm_base --ab-sets)+# flips os.environ between variants inside one process, so an import-time read would+# silently measure the base arm four times.+def had_pf_fast():+ return os.environ.get("EXL3_HAD_PF_FAST", "0") != "0"+++def _had_budget_bytes():+ return int(os.environ.get("EXL3_HAD_PF_FAST_MB", "2048")) << 20+++def _had_priority():+ return os.environ.get("EXL3_HAD_PF_FAST_PRIORITY", "1") != "0"+++_had_cache: dict = {}+_had_cache_bytes = 0+_had_cache_clock = 0+# hit/miss counters: the A/B must be able to prove the cache actually engaged. A knob read+# at import time while the harness flips os.environ at runtime produced four identical+# "cache" arms before this was added; the count is the cheap guard against that class of+# silent no-op.+_had_stats = {"hit": 0, "miss": 0, "recon": 0}+# measured reconstruct cost in us per fp16 MB written, per (k, n); from mb_had.py+_had_cost_per_mb: dict = {+ (4096, 24576): 6.96, (8192, 4096): 7.38, (4096, 12288): 6.95, (12288, 4096): 7.30,+ (4096, 2048): 6.20, (2048, 4096): 6.32, (4096, 1536): 6.51, (1536, 16384): 7.58,+ (4096, 512): 9.77, (16384, 4096): 7.18, (1536, 4096): 6.51, (4096, 4096): 7.74,+}+++def _had_cache_get(inner, n_offset, n):+ """Return the cached fp16 weight for this (trellis, n_offset, n) if it is resident."""+ global _had_cache_clock+ _had_cache_clock += 1+ key = (inner.trellis.data_ptr(), float(inner.K), bool(inner.mcg), bool(inner.mul1),+ int(n_offset), int(n))+ e = _had_cache.get(key)+ if e is None:+ _had_stats["miss"] += 1+ return None+ e[1] = _had_cache_clock+ _had_stats["hit"] += 1+ return e[0]+++def _had_cache_admit(inner, n_offset, n):+ """Decide whether to keep this weight, given the budget. Returns the LRU clock value to+ stamp on the new entry, or None.++ A plain LRU is wrong here: one 4K prefill walks all 255 weights in the same order and+ does it twice, so under a 2 GB budget an LRU filled by the first (largest) weights+ evicts everything before it is ever reused. Instead admit by *value per byte* -- once the+ budget is actually short, a shape joins only if its measured reconstruct cost per fp16+ MB is at least as good as the weakest shape already resident, so a small budget buys+ exactly the shapes the kernel is worst at. The ordering deliberately does NOT bind+ while the budget has room (see the comment below): that would cap large budgets too.++ Admission is sticky: a shape already resident stays resident, and the first call of a+ new shape does not pay anything.+ """+ global _had_cache_bytes, _had_cache_clock+ nbytes = inner.in_features * n * 2+ budget = _had_budget_bytes()+ if nbytes > budget:+ return None+ cost = _had_cost_per_mb.get((inner.in_features, n))+ # Value-ordering is a *scarcity* policy, so it must only bind once the budget is+ # actually short. Applied unconditionally it also throttles a large budget: the first+ # weak shape to be admitted becomes the floor and every worse shape is refused for the+ # rest of the session, which capped a 24 GB budget at 10.9 GB resident / 104 hits.+ if _had_priority() and cost is not None and _had_cache \+ and _had_cache_bytes + nbytes > budget * 0.95:+ costs = [_had_cost_per_mb[e[3]] for e in _had_cache.values() if e[3] in _had_cost_per_mb]+ if costs and cost < min(costs):+ return None+ while _had_cache and _had_cache_bytes + nbytes > budget:+ oldest = min(_had_cache.items(), key=lambda kv: kv[1][1])[0]+ _had_cache_bytes -= _had_cache.pop(oldest)[2]+ return _had_cache_clock+++def _had_cache_put(inner, n_offset, n, w, clock):+ global _had_cache_bytes+ nbytes = inner.in_features * n * 2+ key = (inner.trellis.data_ptr(), float(inner.K), bool(inner.mcg), bool(inner.mul1),+ int(n_offset), int(n))+ if clock is None:+ return+ # entry: [w, clock, nbytes, (in_features, n)] -- a list, not a tuple: the LRU stamp+ # (element 1) is updated in place on every hit.+ _had_cache[key] = [w, clock, nbytes, (int(inner.in_features), int(n))]+ _had_cache_bytes += nbytes+# gfx1151: hipblaslt has no good fp16-in/fp32-out kernel. For a [2048,2560]@[2560,10240] it# picks Cijk_..._HSS_MT64x32x8 and runs at 6.2 TFLOP/s, where the identical GEMM with an fp16# output runs at 34 (the card's practical peak). The gated-delta-net projections all declare@@ -68,6 +229,23 @@ def dec_workspace(device: torch.device):return ws+# specrow1: wide-N R-row GEMV (lm_head, N=248320: R*kbs*N partial sums > DEC_SCRATCH_FLOATS even at R=2) used to fall back to+# R batch-1 launches, each re-reading the whole weight (R x 1.36 ms). A dedicated scratch lets one gemv_r launch carry all rows+# (same kernel, same per-row reduction order, so bit-exact). Counters are shared (R * ceil(N/512) <= 3880 <= 4096 for R <= 8).+# Mutable at run time for one-load A/B: set WIDE_R["on"].+WIDE_R = {"on": os.environ.get("EXL3_VERIFY_WIDE_R", "1") != "0"}+WIDE_SCRATCH_FLOATS = 16 << 20+_wide_scratch: dict = {}+++def wide_scratch(device: torch.device):+ key = str(device)+ t = _wide_scratch.get(key)+ if t is None:+ t = _wide_scratch[key] = torch.zeros(WIDE_SCRATCH_FLOATS, dtype = torch.float, device = device)+ return t++def dec_supported(inner) -> bool:"""True when a LinearEXL3 can run the exl3_dec kernels (mul1 codebook, supported K, shapes)."""return (@@ -84,7 +262,7 @@ def dec_moe_supported(inner) -> bool:"""True when a LinearEXL3 can feed the fused routed-MoE decode (exl3_dec_moe / _union).Same as dec_supported() except that both codebooks qualify: the MoE kernels decode the mcg- codebook as well as mul1 in current packs (GLM-5.3-Flash's published packs are all mcg), while+ codebook as well as mul1 since REPORT-21 (GLM-5.3-Flash's published packs are all mcg), whilethe dense exl3_dec_gemv route stays mul1-only."""return (@@ -223,15 +401,20 @@ class LinearEXL3:# of a wider tensor) would be silently misread as interleaved garbage. Producers are# responsible for contiguity (a silent copy here would hide a hot-path inefficiency# and break CUDA-graph address stability)- assert x.is_contiguous(), f"LinearEXL3 {self.key}: non-contiguous input {tuple(x.shape)}"+ if not x.is_contiguous():+ # a producer's row-padded output (row_pad_pitch): same product, bit-exact, GEMM reads it at full rate.+ # Only the reconstruct + hgemm path takes a pitch (hgemm checks the view against its storage)+ assert _pad_view_ok(x) and _pad_eligible(self, x.shape[-1], x.numel() // x.shape[-1], params), \+ f"LinearEXL3 {self.key}: non-contiguous input {tuple(x.shape)}"+ return self.reconstruct_hgemm(x, out_dtype)reconstruct = params.get("reconstruct")if not reconstruct:rows = x.numel() // x.shape[-1]if rows <= AUTO_RECONSTRUCT_THRESHOLD or self.config.infer_params.no_reconstruct:- if rows == 1 and self.dec_ok:+ if rows == 1 and self.dec_ok and not params.get("moe_valu"):return self.dec_gemv(x, out_dtype)- # R-row DFlash verify: same kernel family as dec_gemv, one weight+ # R-row DFlash verify (REPORT-17): same kernel family as dec_gemv, one weight# tile decode shared across rows -- see exl3_dec_gemv_r's docstring for why this# is bit-exact vs R independent dec_gemv calls. Opt-in (EXL3_DEC_MOE_UNION, the# same flag dec_norm_route_r/the union MoE branch use, so one flag controls the@@ -243,7 +426,7 @@ class LinearEXL3:hasattr(ext, "exl3_dec_gemv_r") and(VERIFY_FUSE["on"] oros.environ.get("EXL3_VERIFY_GEMV_R", os.environ.get("EXL3_DEC_MOE_UNION", "0")) != "0") and- params.get("dflash_verify") and+ params.get("dflash_verify") and not params.get("moe_valu") andx.is_contiguous()):return self.dec_gemv_r(x, rows, out_dtype)@@ -282,7 +465,7 @@ class LinearEXL3:def dec_gemv_r(self, x: torch.Tensor, rows: int, out_dtype):- """R-row decode GEMV (exl3_dec_gemv_r): one launch, each weight tile decoded+ """R-row decode GEMV (exl3_dec_gemv_r, REPORT-17): one launch, each weight tile decodedonce and applied to every row -- bit-exact vs R independent dec_gemv calls, see thekernel's own docstring. Reuses the global dec_workspace() scratch/counters: this callnever runs concurrently (same stream) with a bsz==1 dec_gemv call reading the same@@ -293,7 +476,24 @@ class LinearEXL3:if x.dtype != torch.half:x = x.half()scratch, counters = dec_workspace(x.device)- if self.K >= DEC_GEMV_R_LOOP_MIN_K:+ loop = self.K >= DEC_GEMV_R_LOOP_MIN_K+ if not loop:+ try:+ ext.exl3_dec_gemv_r(x.view(rows, self.in_features), self.trellis, self.suh, self.svh,+ y.view(rows, self.out_features), scratch, counters, self.K)+ except RuntimeError as e:+ # The R-row partial sums of a very wide N (lm_head) can exceed the shared scratch; the+ # size check runs before any launch, so fall back to the batch-1 loop (same order)+ if "scratch too small" not in str(e): raise+ loop = True+ if WIDE_R["on"] and rows <= 8:+ try:+ ext.exl3_dec_gemv_r(x.view(rows, self.in_features), self.trellis, self.suh, self.svh,+ y.view(rows, self.out_features), wide_scratch(x.device), counters, self.K)+ loop = False+ except RuntimeError as e2:+ if "scratch too small" not in str(e2): raise+ if loop:# reference path: R batch-1 launches, bit-identical to gemv_r. gemv_r lost at K >= 5 only# while its 2-deep tile ring spilled; with ring 1 at RM > 1 it wins (GLM lm_head K 5,# N 154880: R 2 1.80 vs 3.56 ms, R 4 1.81 vs 7.12 ms, tools/glm/gemv_r_bench.py)@@ -301,9 +501,6 @@ class LinearEXL3:for r in range(rows):ext.exl3_dec_gemv(x2[r:r + 1], self.trellis, self.suh, self.svh,y2[r:r + 1], scratch, counters, self.K)- else:- ext.exl3_dec_gemv_r(x.view(rows, self.in_features), self.trellis, self.suh, self.svh,- y.view(rows, self.out_features), scratch, counters, self.K)if self.bias is not None:y += self.biasreturn y@@ -346,6 +543,31 @@ class LinearEXL3:return expanded.contiguous().to(device)+ def _had_weight(self, w, n_offset, n):+ """reconstruct_had_slice into w, or reuse the cached fp16 weight for this+ (trellis, n_offset, n). The reconstruct is a pure function of the trellis and+ does not depend on the row count, so a hit is bit-exact. Returns the tensor to+ hand to hgemm_recon (a resident cache entry, or w after a fresh reconstruct)."""+ if not had_pf_fast():+ ext.reconstruct_had_slice(w, self.trellis, self.suh, self.svh if n_offset == 0+ else self.svh[n_offset:], self.K, self.mcg, self.mul1, n_offset)+ return w+ hit = _had_cache_get(self, n_offset, n)+ if hit is not None:+ return hit+ _had_stats["recon"] += 1+ clock = _had_cache_admit(self, n_offset, n)+ if clock is None:+ ext.reconstruct_had_slice(w, self.trellis, self.suh, self.svh if n_offset == 0+ else self.svh[n_offset:], self.K, self.mcg, self.mul1, n_offset)+ return w+ # admitted: the caller allocates a fresh w per call, so w itself can be the resident+ # entry (no copy) -- nothing else holds a reference to it+ ext.reconstruct_had_slice(w, self.trellis, self.suh, self.svh if n_offset == 0+ else self.svh[n_offset:], self.K, self.mcg, self.mul1, n_offset)+ _had_cache_put(self, n_offset, n, w, clock)+ return w+def reconstruct_hgemm(self, x: torch.Tensor, out_dtype):shape = x.shape@@ -379,7 +601,7 @@ class LinearEXL3:use_fused = self._fused_reconstruct and rows >= 1024if use_fused:- xh = x+ xh = pad_copy_in(x, self.in_features)else:xh = torch.empty_like(x)ext.had_r_128(x, xh, self.suh, None, 1.0)@@ -387,7 +609,7 @@ class LinearEXL3:if self.out_features <= MAX_RECONSTRUCT_SLICE_N:w = torch.empty((self.in_features, self.out_features), dtype = torch.half, device = self.trellis.device)if use_fused:- ext.reconstruct_had_slice(w, self.trellis, self.suh, self.svh, self.K, self.mcg, self.mul1, 0)+ w = self._had_weight(w, 0, self.out_features)else:ext.reconstruct(w, self.trellis, self.K, self.mcg, self.mul1)# EXL3_PF_MSPLIT=<rows> (default 0 = off): run big prefill GEMMs as row blocks. Same kernel@@ -407,8 +629,7 @@ class LinearEXL3:numel = self.in_features * (n_end - n_start)w = w_[:numel].view(self.in_features, n_end - n_start)if use_fused:- ext.reconstruct_had_slice(- w, self.trellis, self.suh, self.svh[n_start:], self.K, self.mcg, self.mul1, n_start)+ w = self._had_weight(w, n_start, n_end - n_start)else:ext.reconstruct_slice(w, self.trellis, self.K, self.mcg, self.mul1, n_start)ext.hgemm_recon(xh, w, y_[:, n_start:n_end])diff --git a/exllamav3/modules/quant/fp16.py b/exllamav3/modules/quant/fp16.pyindex d4b14df..71f95f2 100644--- a/exllamav3/modules/quant/fp16.py+++ b/exllamav3/modules/quant/fp16.py@@ -6,7 +6,7 @@ import os as _os_f32_via_f16 = _os.environ.get("EXL3_HIP_F32OUT_VIA_F16", "1") != "0" and bool(torch.version.hip)_f32_via_f16_min_rows = int(_os.environ.get("EXL3_HIP_F32OUT_VIA_F16_MIN_ROWS", "32"))# gfx1151 decode: fp16-out torch.matmul at M <= 8 lands on a single-workgroup hipBLAS tile (GLM-5.3-# indexer wk/weights_proj: 108-154 us for 1 MB); ext.hgemm takes the multi-CU skinny+# indexer wk/weights_proj: 108-154 us for 1 MB, REPORT-31); ext.hgemm takes the multi-CU skinny# split-K GEMV first (M <= 8, N <= 128) and falls back to the same GEMM otherwise_hip = bool(torch.version.hip)_f16_small_m_hgemm = _os.environ.get("EXL3_HIP_F16_SMALL_M_HGEMM", "1") != "0" and bool(torch.version.hip)@@ -103,7 +103,10 @@ class LinearFP16:and weight.is_contiguous() and x.is_contiguous()):# prefill: ext.hgemm's tuned rocBLAS path (see hgemm.cu dtune); torch's hipBLASLt# default is 1.3-1.8x slower on these small-K / small-N shapes- ext.hgemm(x, weight, y)+ # skinny-N projections (indexer wk / weights_proj, kv_a) collapse to ~20 % of peak when the row pitch is a+ # multiple of 4 KiB (hidden 4096 = 8192 B); one padded copy of x runs the same product bit-exactly 3-4x faster+ from .exl3 import pad_copy_in+ ext.hgemm(pad_copy_in(x, x.shape[1]), weight, y)elif dtype == x.dtype and not (_f16_small_m_hgemm and x.dtype == torch.half and x.shape[0] <= 8):torch.matmul(x, weight, out = y)elif (_f32_via_f16 and dtype == torch.float and x.dtype == torch.halfdiff --git a/exllamav3/modules/qwd3_pf.py b/exllamav3/modules/qwd3_pf.pynew file mode 100644index 0000000..b32502b--- /dev/null+++ b/exllamav3/modules/qwd3_pf.py@@ -0,0 +1,98 @@+"""weight prefetch into the infinity cache (MALL, 32 MB, about 700 GB/s on re-reads against 236 GB/s from DRAM) during the+latency-bound kernels of a decode token. Read-only side-stream reads of weights that a later streaming kernel (qkv|z gemv, o gemv, fused+MoE front end) will read; no output of the model is touched, so results are bit-identical by construction. The side stream never runs while+the persistent fused MoE kernel (grid barrier, all blocks must stay resident) is on the device: its launch waits for the side stream's last event.+Switch: EXL3_QWD3_PF (0 off, default 0 until the served A/B); harness arms flip PF["on"] at run time.+Parts: w1 = MB of the qkv trellis read after the previous MoE half (dots / finalize window); o = o_proj trellis; moe = HC mixer codes, router,+shared expert of the same block, both read after the qkv|z launch (skinny / conv / recurrence window)."""+import os, torch++PF = {"on": int(os.environ.get("EXL3_QWD3_PF", "0") != "0"), "w1": 8, "o": 1, "moe": 1, "fired1": 0, "fired2": 0, "waits": 0}+_S = {"side": None, "ev0": None, "ev1": None, "evs": None, "pending": False, "sink": None, "cur": None, "inst": False}+MB = 1 << 20++def _side():+ if _S["side"] is None:+ _S["side"] = torch.cuda.Stream(); _S["ev0"] = torch.cuda.Event(); _S["ev1"] = torch.cuda.Event(); _S["evs"] = torch.cuda.Event()+ _S["sink"] = torch.zeros((), dtype = torch.float32, device = "cuda")+ return _S["side"]++def _f32(t, nbytes = None):+ """Contiguous view of t's first nbytes as fp32 (4-byte aligned prefix), no copy."""+ v = t.reshape(-1).view(torch.uint8) if t.dtype != torch.uint8 else t.reshape(-1)+ n = v.numel() if nbytes is None else min(nbytes, v.numel())+ n -= n % 4+ return v[:n].view(torch.float32) if n else None++def _touch(t, nbytes = None):+ if PF.get("noop"): return+ v = _f32(t, nbytes)+ if v is not None:+ torch.sum(v, dim = 0, out = _S["sink"])++def _is_decode(x, params):+ return x.dim() >= 2 and x.numel() // x.shape[-1] // (x.shape[2] if x.dim() == 4 else 1) == 1 and not params.get("prefill")++def _gdn_tensors(attn):+ ts = getattr(attn, "_qd3_t", None)+ if ts is None:+ ts = (attn.qkv_proj.inner.trellis, attn.z_proj.inner.trellis, attn.o_proj.inner.trellis)+ attn._qd3_t = ts+ return ts++def _moe_tensors(fh):+ ts = getattr(fh, "_qd3_t", None)+ if ts is None:+ fq, fsc, uq, usc = fh.gr.q8_set()+ ts = [fq, uq, fh.router, fh.sgate]+ ts += [t for t in (fh.svt,) if t is not None]+ mlp = fh.mlp+ sh = mlp.shared_experts+ ts += [sh.gates[0].inner.trellis, sh.ups[0].inner.trellis, sh.downs[0].inner.trellis]+ fh._qd3_t = ts+ return ts++def install():+ if _S["inst"] or not torch.cuda.is_available():+ return+ _S["inst"] = True+ from . import transformer, moe_fused, gated_delta_net+ TB = transformer.TransformerBlock+ orig_fwd = TB.forward+ def block_forward(self, x, params, *a, **kw):+ if PF["on"] and isinstance(getattr(self, "attn", None), gated_delta_net.GatedDeltaNet) and _is_decode(x, params):+ _S["cur"] = self+ side = _side(); main = torch.cuda.current_stream()+ _S["ev0"].record(main); side.wait_event(_S["ev0"])+ with torch.cuda.stream(side):+ if PF["w1"]: _touch(_gdn_tensors(self.attn)[0], int(PF["w1"] * MB))+ _S["evs"].record(side)+ _S["pending"] = True; PF["fired1"] += 1+ else:+ _S["cur"] = None+ return orig_fwd(self, x, params, *a, **kw)+ TB.forward = block_forward+ G = gated_delta_net.GatedDeltaNet+ orig_p = G.project_qkvz_dec+ def project_qkvz_dec(self, x, params, bsz, seqlen):+ r = orig_p(self, x, params, bsz, seqlen)+ blk = _S["cur"]+ if PF["on"] and r is not None and blk is not None and blk.attn is self:+ side = _side(); main = torch.cuda.current_stream()+ _S["ev1"].record(main); side.wait_event(_S["ev1"])+ with torch.cuda.stream(side):+ if PF["o"]: _touch(_gdn_tensors(self)[2])+ fh = getattr(blk, "_moe_fused", None)+ if PF["moe"] and fh is not None and fh.supported:+ for t in _moe_tensors(fh): _touch(t)+ _S["evs"].record(side)+ _S["pending"] = True; PF["fired2"] += 1+ return r+ G.project_qkvz_dec = project_qkvz_dec+ F = moe_fused.FusedMoEHalf+ orig_call = F.__call__+ def call(self, x):+ if _S["pending"]:+ torch.cuda.current_stream().wait_event(_S["evs"]); _S["pending"] = False; PF["waits"] += 1+ return orig_call(self, x)+ F.__call__ = calldiff --git a/exllamav3/modules/sliding_attn.py b/exllamav3/modules/sliding_attn.pyindex faa3dab..f71dbaa 100644--- a/exllamav3/modules/sliding_attn.py+++ b/exllamav3/modules/sliding_attn.py@@ -6,7 +6,7 @@ from ..util.rope import RopeSettings, RoPEfrom ..util.tensor import get_for_device, to2, g_tensor_cachefrom . import Module, Linear, RMSNorm, LayerNormfrom ..constants import PAGE_SIZE-from .attention_fn.triton_paged import paged_attn_triton_decode, paged_attn_triton_prefill+from .attention_fn.triton_paged import paged_attn_triton_decode, paged_attn_triton_decode_rows, paged_attn_triton_prefillfrom .attention_fn.bc_attn import bc_attn_enable as _bc_attn_enable, build_bc_swa, MAX_BSZ as _bc_max_bsz, MAX_QLEN as _bc_max_qlenfrom .multilinear import MultiLinear, SlicedMultiLinearfrom .quant.exl3 import MAX_BSZN_GEMV_R@@ -735,7 +735,7 @@ class SlidingAttention(Module):g = outs[3] if len(outs) > 3 else Nonereturn self.finish_qkv(outs[0], outs[1], outs[2], g, bsz, q_len, params)- # DFlash verify (R rows): same fused launch as the bsz==1 case above, generalized+ # DFlash verify (R rows, REPORT-17): same fused launch as the bsz==1 case above, generalized# to R rows via exl3_dec_gemv_r_multi -- same trellis/suh/svh/K list and order as# exl3_dec_gemv_multi, so pick_ktw/kbs_of see the same strips_total and pick the identical# ktw/kbs the batch-1 launch uses. That's required for the block-reduce partition (and so the@@ -1109,7 +1109,7 @@ class SlidingAttention(Module):# window run reaches the end of the buffer) and attend over the pagesbt, cache_seqlens = self._decode_state_prep(rsg, k_states, v_states, seqlen)- # DFlash verify (R rows): a single paged_attn_triton_decode call over all+ # DFlash verify (R rows, REPORT-17): a single paged_attn_triton_decode call over all# R rows at once tiles/splits the KV span from the batch's (single) cache_seqlens and# q_len, which is not necessarily the same tiling a batch-1 call would use for each# row's own (shorter) span -- unverified, and the one dimension this session's kernel@@ -1125,19 +1125,31 @@ class SlidingAttention(Module):1 < seqlen <= MAX_BSZN_GEMV_R and params.get("dflash_verify") andos.environ.get("EXL3_VERIFY_ATTN_LOOP", os.environ.get("EXL3_DEC_MOE_UNION", "0")) != "0"):- outs = []- for i in range(seqlen):- outs.append(paged_attn_triton_decode(- q[:, i:i + 1], k[:, i:i + 1], v[:, i:i + 1], k_pages, v_pages, bt,- cache_seqlens + i,+ if os.environ.get("EXL3_VERIFY_ATTN_ROWS", "1") != "0" and q.shape[0] == 1 and bt.shape[0] == 1:+ # one append + one attention launch, bitwise the R batch-1 calls below+ o = paged_attn_triton_decode_rows(+ q, k, v, k_pages, v_pages, bt, cache_seqlens,causal = causal,softmax_scale = self.sm_scale,window_size = (sw, 0),softcap = self.logit_softcapping,sinks = self.sinks,max_kv_len = S,- ))- o = torch.cat(outs, dim = 1)+ )+ else:+ outs = []+ for i in range(seqlen):+ outs.append(paged_attn_triton_decode(+ q[:, i:i + 1], k[:, i:i + 1], v[:, i:i + 1], k_pages, v_pages, bt,+ cache_seqlens + i,+ causal = causal,+ softmax_scale = self.sm_scale,+ window_size = (sw, 0),+ softcap = self.logit_softcapping,+ sinks = self.sinks,+ max_kv_len = S,+ ))+ o = torch.cat(outs, dim = 1)else:o = paged_attn_triton_decode(q, k, v, k_pages, v_pages, bt, cache_seqlens,diff --git a/exllamav3/modules/transformer.py b/exllamav3/modules/transformer.pyindex 8d43a07..634464a 100644--- a/exllamav3/modules/transformer.py+++ b/exllamav3/modules/transformer.py@@ -7,6 +7,7 @@ from . import Module, RMSNorm, LayerNorm, Attention, GatedDeltaNet, GatedMLP, MLfrom .hyperconnections import HyperConnectionfrom . import ablit_runtimefrom ..util import profile_opt+from . import moe_fusedclass TransformerBlock(Module):@@ -41,6 +42,10 @@ class TransformerBlock(Module):self.mlp_post_norm = mlp_post_normself.attn_hc = attn_hcself.mlp_hc = mlp_hc+ # EXL3_MOE_FUSED=1: fused MoE half-layer for R <= 4 rows (moe_fused.py). Attribute so a harness can toggle it per block.+ self._moe_fused_on = moe_fused.enabled_by_env()+ self._moe_fused = None+ self._moe_fused_tried = Falseself.qbits_key = qbits_keyself.out_dtype = out_dtype@@ -141,15 +146,21 @@ class TransformerBlock(Module):"""MLP half of forward (norm, MLP, residual/hc apply). `y_resid` is a pending attentionoutput whose residual add is folded into the MLP input norm. Returns the new residual."""if self.mlp:+ if self.mlp_hc and self._moe_fused_on:+ fused_x = moe_fused.maybe_apply(self, x, params, hc_pending)+ if fused_x is not None:+ return fused_xif self.mlp_hc:- if hc_pending is not None and not self.mlp_norm:+ gr_pend = hc_pending is not None and hc_pending[3] is None and not self.mlp_norm+ if hc_pending is not None and not self.mlp_norm and not gr_pend:HyperConnection.flush_pending(x, hc_pending)hc_pending = Nonefused = self.mlp_hc.mix_norm(x, params, self.mlp_norm, hc_pending) if self.mlp_norm else Noneif fused is not None:hc_post, hc_comb, y = fusedelse:- hc_post, hc_comb, y = self.mlp_hc.mix(x, params)+ hc_post, hc_comb, y = self.mlp_hc.mix(x, params, pending = hc_pending) if gr_pend \+ else self.mlp_hc.mix(x, params)y = y.half()if self.mlp_norm:y = self.mlp_norm.forward(y, params, out_dtype = torch.half)@@ -199,6 +210,8 @@ class TransformerBlock(Module):# EXL3_PF_HC_FUSE: defer into the next block's attn mix_norm (see pf_can_defer)if hc_defer and HyperConnection.pf_can_defer(x, y, hc_post, hc_comb, params):params["hc_pending"] = (x, y, hc_post, hc_comb)+ elif hc_defer and hc_comb is None and hasattr(self.mlp_hc, "gr_can_defer") and self.mlp_hc.gr_can_defer(x, y, hc_post, params):+ params["hc_pending"] = (x, y, hc_post, None)else:x = self.mlp_hc.apply_(x, y, hc_post, hc_comb, params)elif self.mlp_post_norm:@@ -230,7 +243,9 @@ class TransformerBlock(Module):export_state = params.get("export_state_layers")export_state = export_state and self.layer_idx in export_state and params.get("layer_instance", 0) == 0- if hc_pending is not None and not (self.attn and self.attn_hc and self.attn_norm):+ gr_pend = hc_pending is not None and hc_pending[3] is None and bool(self.attn and self.attn_hc) \+ and not self.attn_norm+ if hc_pending is not None and not gr_pend and not (self.attn and self.attn_hc and self.attn_norm):HyperConnection.flush_pending(x, hc_pending)hc_pending = Nonehc_defer = not export_state and self.layer_scalar_f is None@@ -244,7 +259,12 @@ class TransformerBlock(Module):if fused is not None:hc_post, hc_comb, y = fusedelse:- hc_post, hc_comb, y = self.attn_hc.mix(x, params)+ params["hc_pad_ok"] = True # the attention site accepts a row-padded block input+ try:+ hc_post, hc_comb, y = self.attn_hc.mix(x, params, pending = hc_pending) if gr_pend \+ else self.attn_hc.mix(x, params)+ finally:+ params.pop("hc_pad_ok", None)y = y.half()if self.attn_norm:y = self.attn_norm.forward(y, params, out_dtype = torch.half)@@ -252,7 +272,17 @@ class TransformerBlock(Module):y = self.attn_norm.forward(x, params, out_dtype = torch.half)else:y = x.half()- y = self.attn.forward(y, params)+ # EXL3_PFE_OPROJ: this site's residual apply (hc_apply) reads fp16 or fp32 y alike, so the+ # attention output projection may skip its fp32 widen (see GatedDeltaNet / Attention.project_o)+ pfe_half = bool(self.attn_hc) and not self.ablit and self.attn_resid_scalar is None \+ and not export_state and "pfe_y_half" not in params+ if pfe_half:+ params["pfe_y_half"] = True+ try:+ y = self.attn.forward(y, params)+ finally:+ if pfe_half:+ params.pop("pfe_y_half", None)if y is None:# EXL3_PF_SKIP: kv_only -- attention wrote its K/V (and indexer) rows and the# caller discards this block's output, so nothing below has an input to read@@ -267,6 +297,9 @@ class TransformerBlock(Module):if self.mlp and self.mlp_hc and self.mlp_norm \and HyperConnection.pf_can_defer(x, y, hc_post, hc_comb, params):mlp_pending = (x, y, hc_post, hc_comb)+ elif self.mlp and self.mlp_hc and not self.mlp_norm and hc_comb is None \+ and hasattr(self.mlp_hc, "gr_can_defer") and self.mlp_hc.gr_can_defer(x, y, hc_post, params):+ mlp_pending = (x, y, hc_post, None)else:x = self.attn_hc.apply_(x, y, hc_post, hc_comb, params)elif self.attn_post_norm:diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.pyindex 9f16c1a..6b68e9e 100644--- a/exllamav3/vendor/fla/__init__.py+++ b/exllamav3/vendor/fla/__init__.py@@ -15,6 +15,7 @@ import torchfrom .utils import input_guardfrom .l2norm import l2norm_fwd+from . import gdn_pf as _gdn_pffrom .cumsum import chunk_local_cumsumfrom .gdn_chunk_fwd import chunk_gated_delta_rule_fwd_intrafrom .chunk_delta_h import chunk_gated_delta_rule_fwd_h@@ -70,6 +71,11 @@ def chunk_gated_delta_rule(q, _ = l2norm_fwd(q)k, _ = l2norm_fwd(k)g = chunk_local_cumsum(g, chunk_size = chunk_size, scale = RCP_LN2)+ if os.environ.get("EXL3_GDN_FUSE", "0") == "1": # hand-written HIP chunk kernel (gdn_fused.py), bitwise equal, default off+ from .gdn_fused import chunk_gdn_fused+ res = chunk_gdn_fused(q, k, v, g, beta, scale, initial_state, output_final_state, chunk_size)+ if res is not None:+ return res[0].to(q.dtype), res[1]# WY representation: fused kkt + solve_tril + recompute_w_u. u is the new vw, u, _ = chunk_gated_delta_rule_fwd_intra(k = k, v = v, g = g, beta = beta, chunk_size = chunk_size)h, v_new, final_state = chunk_gated_delta_rule_fwd_h(@@ -82,6 +88,36 @@ def chunk_gated_delta_rule(return o.to(q.dtype), final_state+def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None, output_final_state=False):+ """chunk_gated_delta_rule(use_qk_l2norm_in_kernel=True, chunk_size=64) for q, k, v given as (possibly strided) views of the conv+ output; g (fp32) and beta (bf16) contiguous. Bitwise equal to the guarded entry; no copies of q, k, v when the views are plain+ token-pitch slices."""+ if not (_gdn_pf.strided_ok(q) and _gdn_pf.strided_ok(k) and q.shape[-1] == 128 and q.dtype == torch.bfloat16):+ return chunk_gated_delta_rule(q, k, v, g=g, beta=beta, scale=scale, initial_state=initial_state,+ output_final_state=output_final_state, use_qk_l2norm_in_kernel=True)+ g = g.contiguous(); beta = beta.contiguous()+ if initial_state is not None:+ initial_state = initial_state.contiguous()+ chunk_size = 64+ if scale is None:+ scale = k.shape[-1] ** -0.5+ with torch.cuda.device(q.device.index):+ qn = _gdn_pf.l2norm_strided(q)+ kn = _gdn_pf.l2norm_strided(k)+ g = chunk_local_cumsum(g, chunk_size = chunk_size, scale = RCP_LN2)+ if os.environ.get("EXL3_GDN_FUSE", "0") == "1":+ from .gdn_fused import chunk_gdn_fused+ res = chunk_gdn_fused(qn, kn, v, g, beta, scale, initial_state, output_final_state, chunk_size)+ if res is not None:+ return res[0].to(qn.dtype), res[1]+ v = v.contiguous()+ w, u, _ = chunk_gated_delta_rule_fwd_intra(k = kn, v = v, g = g, beta = beta, chunk_size = chunk_size)+ h, v_new, final_state = chunk_gated_delta_rule_fwd_h(+ k = kn, w = w, u = u, g = g, initial_state = initial_state, output_final_state = output_final_state, chunk_size = chunk_size)+ o = chunk_fwd_o(q = qn, k = kn, v = v_new, h = h, g = g, scale = scale, chunk_size = chunk_size)+ return o.to(qn.dtype), final_state++@input_guarddef chunk_kda(q: torch.Tensor,diff --git a/exllamav3/vendor/fla/chunk_o.py b/exllamav3/vendor/fla/chunk_o.pyindex b56ca94..421d79d 100644--- a/exllamav3/vendor/fla/chunk_o.py+++ b/exllamav3/vendor/fla/chunk_o.py@@ -29,6 +29,9 @@ NUM_WARPS = [2, 4] if IS_NVIDIA_HOPPER else [2, 4, 8]triton.Config({'BK': 128, 'BV': 128}, num_warps=8, num_stages=3),triton.Config({'BK': 64, 'BV': 64}, num_warps=4, num_stages=3),triton.Config({'BK': 32, 'BV': 32}, num_warps=2, num_stages=3),+ ] + [+ triton.Config({'BK': bk, 'BV': bk}, num_warps=nw, num_stages=ns)+ for bk in (64, 128) for nw in (4, 8) for ns in (1, 2)],key=['H', 'HV', 'K', 'V', 'BT', 'STATE_V_FIRST'],**autotune_cache_kwargs,diff --git a/exllamav3/vendor/fla/chunk_scaled_dot_kkt.py b/exllamav3/vendor/fla/chunk_scaled_dot_kkt.pyindex e89bc1f..b88ca5f 100644--- a/exllamav3/vendor/fla/chunk_scaled_dot_kkt.py+++ b/exllamav3/vendor/fla/chunk_scaled_dot_kkt.py@@ -23,7 +23,7 @@ from .utils import autotune_cache_kwargstriton.Config({'BK': BK}, num_warps=num_warps, num_stages=num_stages)for BK in [32, 64, 128]for num_warps in [2, 4, 8]- for num_stages in [2, 3, 4]+ for num_stages in [1, 2, 3, 4]],key=['H', 'HV', 'K', 'BT', 'IS_VARLEN'],**autotune_cache_kwargs,diff --git a/exllamav3/vendor/fla/gdn_fused.py b/exllamav3/vendor/fla/gdn_fused.pynew file mode 100644index 0000000..d6306c8--- /dev/null+++ b/exllamav3/vendor/fla/gdn_fused.py@@ -0,0 +1,50 @@+# EXL3_GDN_FUSE=1: GDN prefill chunk path with the hand-written HIP kernel (vendor/fla/hip/gdn_fused_h.hip) replacing+# recompute_w_u + chunk_h + chunk_o. kkt + solve_tril stay on the Triton kernel (it produces A). Bitwise equal to the Triton chain+# (w, u, v_new, state, o, final state), microbench Qwen shape (H 16, HV 48) on gfx1151. Default off; falls back to the Triton chain+# on unsupported shapes / dtypes and disables itself for the process if the HIP build or launch fails.+import os+import torch+import triton+from .gdn_chunk_fwd import chunk_gated_delta_rule_fwd_kkt_solve_kernel++_FAIL = []+++def gdn_fuse_ok(q, k, v, g, beta, initial_state, chunk_size):+ if _FAIL or chunk_size != 64:+ return False+ bf = torch.bfloat16+ B, T, H, K = k.shape+ HV, V = v.shape[2], v.shape[-1]+ return (K == 128 and V == 128 and HV % H == 0 and q.shape == k.shape and g.shape == (B, T, HV) and beta.shape == (B, T, HV)+ and all(t.dtype == bf and t.is_contiguous() for t in (q, k, beta)) and v.dtype == bf and v.stride(3) == 1 and v.stride(2) == V+ and v.stride(1) >= HV * V and v.stride(1) % 2 == 0 and v.storage_offset() % 2 == 0 and (B == 1 or v.stride(0) == T * v.stride(1)) and g.dtype == torch.float32 and g.is_contiguous()+ and (initial_state is None or (initial_state.dtype == torch.float32 and initial_state.is_contiguous()+ and initial_state.shape == (B, HV, K, V))))+++def gdn_kkt_solve(k, g, beta, chunk_size=64):+ B, T, H, K = k.shape+ HV = beta.shape[2]+ # EXL3_GDN_KKT_SHARED (default 1): one program per (chunk, k-head) computes the k k^T Gram once for the HV // H value heads that share it+ # (stock: once per value head); everything per value head is the stock text, A is bitwise equal. 0 = stock kernel.+ if os.environ.get("EXL3_GDN_KKT_SHARED", "1") == "1" and chunk_size == 64 and K % 32 == 0:+ from .gdn_kkt_shared import kkt_shared+ return kkt_shared(k, g, beta, chunk_size)+ A = torch.zeros(B, T, HV, chunk_size, device=k.device, dtype=k.dtype)+ chunk_gated_delta_rule_fwd_kkt_solve_kernel[(triton.cdiv(T, chunk_size), B * HV)](+ k=k, g=g, beta=beta, A=A, cu_seqlens=None, chunk_indices=None, T=T, H=H, HV=HV, K=K, BT=chunk_size, BC=16)+ return A+++def chunk_gdn_fused(q, k, v, g, beta, scale, initial_state, output_final_state, chunk_size=64):+ """Returns (o, final_state) or None when the caller must run the Triton chain."""+ if not gdn_fuse_ok(q, k, v, g, beta, initial_state, chunk_size):+ return None+ try:+ from .hip.gdn_fused_h_hip import chunk_gdn_fwd_fused_hip+ A = gdn_kkt_solve(k, g, beta, chunk_size)+ return chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=initial_state, output_final_state=output_final_state)+ except Exception:+ _FAIL.append(1)+ return Nonediff --git a/exllamav3/vendor/fla/gdn_kkt_shared.py b/exllamav3/vendor/fla/gdn_kkt_shared.pynew file mode 100644index 0000000..99af1f7--- /dev/null+++ b/exllamav3/vendor/fla/gdn_kkt_shared.py@@ -0,0 +1,272 @@+# Shared-Gram variant of the fused kkt + solve_tril kernel (gdn_chunk_fwd.chunk_gated_delta_rule_fwd_kkt_solve_kernel).+# GENERATED from that kernel's source by a kernel generator script (not published) (do not edit by hand). One program handles one (chunk, k-head) and+# loops over the HV // H value heads that share the k-head: the 10 raw k k^T blocks (fp32 tl.dot chains) are computed once instead of+# once per value head. Everything per value head (gate, beta, exp2 scaling, forward substitution, block merge, store) is the original text,+# so the stored A is bitwise equal. ABL (timing experiments only, 0 in service): 1 = skip forward substitution.+import torch+import triton+import triton.language as tl+from .op import exp2+from .utils import autotune_cache_kwargs+from .gdn_chunk_fwd import SOLVE_TRIL_DOT_PRECISION+++ configs=[+ triton.Config({'BK': BK}, num_warps=num_warps)+ for BK in [32, 64]+ for num_warps in [1, 2, 4]+ ],+ key=['H', 'HV', 'K', 'BC'],+ **autotune_cache_kwargs,+)[email protected](do_not_specialize=['T'])+def kkt_solve_shared_kernel(+ k,+ g,+ beta,+ A,+ T,+ H: tl.constexpr,+ HV: tl.constexpr,+ K: tl.constexpr,+ BT: tl.constexpr,+ BC: tl.constexpr,+ BK: tl.constexpr,+ ABL: tl.constexpr,+):+ i_t, i_bk = tl.program_id(0).to(tl.int64), tl.program_id(1)+ i_b, i_hk = i_bk // H, i_bk % H+ bos, eos = i_b * T, i_b * T + T++ if i_t * BT >= T:+ return++ i_tc0 = i_t * BT+ i_tc1 = i_t * BT + BC+ i_tc2 = i_t * BT + 2 * BC+ i_tc3 = i_t * BT + 3 * BC++ k += (bos * H + i_hk) * K++ o_i = tl.arange(0, BC)+ m_tc0 = (i_tc0 + o_i) < T+ m_tc1 = (i_tc1 + o_i) < T+ m_tc2 = (i_tc2 + o_i) < T+ m_tc3 = (i_tc3 + o_i) < T++ # Step 1 (once per k-head): the 10 raw lower-triangular [BC, BC] blocks of K @ K^T+ # 4 diagonal blocks+ r_A00 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A11 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A22 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A33 = tl.zeros([BC, BC], dtype=tl.float32)++ # 6 off-diagonal blocks+ r_A10 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A20 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A21 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A30 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A31 = tl.zeros([BC, BC], dtype=tl.float32)+ r_A32 = tl.zeros([BC, BC], dtype=tl.float32)++ for i_k in range(tl.cdiv(K, BK)):+ o_k = i_k * BK + tl.arange(0, BK)+ p_k0 = k + (i_tc0 + o_i)[:, None] * (H*K) + o_k[None, :]+ b_k0 = tl.load(p_k0, mask=m_tc0[:, None] & (o_k[None, :] < K), other=0.0)+ # diagonal block 0+ r_A00 += tl.dot(b_k0, tl.trans(b_k0))++ if i_tc1 < T:+ p_k1 = k + (i_tc1 + o_i)[:, None] * (H*K) + o_k[None, :]+ b_k1 = tl.load(p_k1, mask=m_tc1[:, None] & (o_k[None, :] < K), other=0.0)+ # diagonal block 1+ r_A11 += tl.dot(b_k1, tl.trans(b_k1))+ # off-diagonal (1,0)+ r_A10 += tl.dot(b_k1, tl.trans(b_k0))++ if i_tc2 < T:+ p_k2 = k + (i_tc2 + o_i)[:, None] * (H*K) + o_k[None, :]+ b_k2 = tl.load(p_k2, mask=m_tc2[:, None] & (o_k[None, :] < K), other=0.0)+ # diagonal block 2+ r_A22 += tl.dot(b_k2, tl.trans(b_k2))+ # off-diagonal (2,0), (2,1)+ r_A20 += tl.dot(b_k2, tl.trans(b_k0))+ r_A21 += tl.dot(b_k2, tl.trans(b_k1))++ if i_tc3 < T:+ p_k3 = k + (i_tc3 + o_i)[:, None] * (H*K) + o_k[None, :]+ b_k3 = tl.load(p_k3, mask=m_tc3[:, None] & (o_k[None, :] < K), other=0.0)+ # diagonal block 3+ r_A33 += tl.dot(b_k3, tl.trans(b_k3))+ # off-diagonal (3,0), (3,1), (3,2)+ r_A30 += tl.dot(b_k3, tl.trans(b_k0))+ r_A31 += tl.dot(b_k3, tl.trans(b_k1))+ r_A32 += tl.dot(b_k3, tl.trans(b_k2))++ for i_g in range(HV // H):+ i_h = i_hk * (HV // H) + i_g+ A_h = A + (bos * HV + i_h) * BT++ # load beta / gate for each sub-chunk+ p_b0 = beta + bos * HV + i_h + (i_tc0 + o_i) * HV+ p_b1 = beta + bos * HV + i_h + (i_tc1 + o_i) * HV+ p_b2 = beta + bos * HV + i_h + (i_tc2 + o_i) * HV+ p_b3 = beta + bos * HV + i_h + (i_tc3 + o_i) * HV+ b_b0 = tl.load(p_b0, mask=m_tc0, other=0.0).to(tl.float32)+ b_b1 = tl.load(p_b1, mask=m_tc1, other=0.0).to(tl.float32)+ b_b2 = tl.load(p_b2, mask=m_tc2, other=0.0).to(tl.float32)+ b_b3 = tl.load(p_b3, mask=m_tc3, other=0.0).to(tl.float32)++ p_g0 = g + bos * HV + i_h + (i_tc0 + o_i) * HV+ p_g1 = g + bos * HV + i_h + (i_tc1 + o_i) * HV+ p_g2 = g + bos * HV + i_h + (i_tc2 + o_i) * HV+ p_g3 = g + bos * HV + i_h + (i_tc3 + o_i) * HV++ b_g0 = tl.load(p_g0, mask=m_tc0, other=0.0).to(tl.float32)+ b_g1 = tl.load(p_g1, mask=m_tc1, other=0.0).to(tl.float32)+ b_g2 = tl.load(p_g2, mask=m_tc2, other=0.0).to(tl.float32)+ b_g3 = tl.load(p_g3, mask=m_tc3, other=0.0).to(tl.float32)++ # apply gate, beta scaling, and masking+ # m_d: strictly lower triangular mask for diagonal blocks+ # m_tc: boundary mask to prevent NaN from 0 * inf (IEEE 754) when+ # out-of-bounds g loads as 0 via boundary_check and exp2(0 - g_inbounds) overflows+ m_d = o_i[:, None] > o_i[None, :]+ m_I = o_i[:, None] == o_i[None, :]++ b_A00 = r_A00 * tl.where(m_d & m_tc0[:, None] & m_tc0[None, :], exp2(b_g0[:, None] - b_g0[None, :]), 0.)+ b_A11 = r_A11 * tl.where(m_d & m_tc1[:, None] & m_tc1[None, :], exp2(b_g1[:, None] - b_g1[None, :]), 0.)+ b_A22 = r_A22 * tl.where(m_d & m_tc2[:, None] & m_tc2[None, :], exp2(b_g2[:, None] - b_g2[None, :]), 0.)+ b_A33 = r_A33 * tl.where(m_d & m_tc3[:, None] & m_tc3[None, :], exp2(b_g3[:, None] - b_g3[None, :]), 0.)++ b_A10 = r_A10 * tl.where(m_tc1[:, None] & m_tc0[None, :], exp2(b_g1[:, None] - b_g0[None, :]), 0.)+ b_A20 = r_A20 * tl.where(m_tc2[:, None] & m_tc0[None, :], exp2(b_g2[:, None] - b_g0[None, :]), 0.)+ b_A21 = r_A21 * tl.where(m_tc2[:, None] & m_tc1[None, :], exp2(b_g2[:, None] - b_g1[None, :]), 0.)+ b_A30 = r_A30 * tl.where(m_tc3[:, None] & m_tc0[None, :], exp2(b_g3[:, None] - b_g0[None, :]), 0.)+ b_A31 = r_A31 * tl.where(m_tc3[:, None] & m_tc1[None, :], exp2(b_g3[:, None] - b_g1[None, :]), 0.)+ b_A32 = r_A32 * tl.where(m_tc3[:, None] & m_tc2[None, :], exp2(b_g3[:, None] - b_g2[None, :]), 0.)++ # diagonal blocks: scaled by beta+ b_A00 = b_A00 * b_b0[:, None]+ b_A11 = b_A11 * b_b1[:, None]+ b_A22 = b_A22 * b_b2[:, None]+ b_A33 = b_A33 * b_b3[:, None]++ # off-diagonal blocks: full block, scaled by beta+ b_A10 = b_A10 * b_b1[:, None]+ b_A20 = b_A20 * b_b2[:, None]+ b_A21 = b_A21 * b_b2[:, None]+ b_A30 = b_A30 * b_b3[:, None]+ b_A31 = b_A31 * b_b3[:, None]+ b_A32 = b_A32 * b_b3[:, None]++ b_Ai00 = -b_A00+ b_Ai11 = -b_A11+ b_Ai22 = -b_A22+ b_Ai33 = -b_A33++ for i in range(2, tl.minimum(BC, T - i_tc0) * (1 - (ABL & 1))):+ b_a00 = tl.sum(tl.where((o_i == i)[:, None], -b_A00, 0.), 0)+ b_a00 = tl.where(o_i < i, b_a00, 0.)+ b_a00 = b_a00 + tl.sum(b_a00[:, None] * b_Ai00, 0)+ b_Ai00 = tl.where((o_i == i)[:, None], b_a00, b_Ai00)+ for i in range(2, tl.minimum(BC, T - i_tc1) * (1 - (ABL & 1))):+ b_a11 = tl.sum(tl.where((o_i == i)[:, None], -b_A11, 0.), 0)+ b_a11 = tl.where(o_i < i, b_a11, 0.)+ b_a11 = b_a11 + tl.sum(b_a11[:, None] * b_Ai11, 0)+ b_Ai11 = tl.where((o_i == i)[:, None], b_a11, b_Ai11)+ for i in range(2, tl.minimum(BC, T - i_tc2) * (1 - (ABL & 1))):+ b_a22 = tl.sum(tl.where((o_i == i)[:, None], -b_A22, 0.), 0)+ b_a22 = tl.where(o_i < i, b_a22, 0.)+ b_a22 = b_a22 + tl.sum(b_a22[:, None] * b_Ai22, 0)+ b_Ai22 = tl.where((o_i == i)[:, None], b_a22, b_Ai22)+ for i in range(2, tl.minimum(BC, T - i_tc3) * (1 - (ABL & 1))):+ b_a33 = tl.sum(tl.where((o_i == i)[:, None], -b_A33, 0.), 0)+ b_a33 = tl.where(o_i < i, b_a33, 0.)+ b_a33 = b_a33 + tl.sum(b_a33[:, None] * b_Ai33, 0)+ b_Ai33 = tl.where((o_i == i)[:, None], b_a33, b_Ai33)++ b_Ai00 += m_I+ b_Ai11 += m_I+ b_Ai22 += m_I+ b_Ai33 += m_I++ b_Ai10 = -tl.dot(+ tl.dot(b_Ai11, b_A10, input_precision=SOLVE_TRIL_DOT_PRECISION),+ b_Ai00,+ input_precision=SOLVE_TRIL_DOT_PRECISION+ )+ b_Ai21 = -tl.dot(+ tl.dot(b_Ai22, b_A21, input_precision=SOLVE_TRIL_DOT_PRECISION),+ b_Ai11,+ input_precision=SOLVE_TRIL_DOT_PRECISION+ )+ b_Ai32 = -tl.dot(+ tl.dot(b_Ai33, b_A32, input_precision=SOLVE_TRIL_DOT_PRECISION),+ b_Ai22,+ input_precision=SOLVE_TRIL_DOT_PRECISION+ )++ b_Ai20 = -tl.dot(+ b_Ai22,+ tl.dot(b_A20, b_Ai00, input_precision=SOLVE_TRIL_DOT_PRECISION) ++ tl.dot(b_A21, b_Ai10, input_precision=SOLVE_TRIL_DOT_PRECISION),+ input_precision=SOLVE_TRIL_DOT_PRECISION,+ )+ b_Ai31 = -tl.dot(+ b_Ai33,+ tl.dot(b_A31, b_Ai11, input_precision=SOLVE_TRIL_DOT_PRECISION) ++ tl.dot(b_A32, b_Ai21, input_precision=SOLVE_TRIL_DOT_PRECISION),+ input_precision=SOLVE_TRIL_DOT_PRECISION,+ )+ b_Ai30 = -tl.dot(+ b_Ai33,+ tl.dot(b_A30, b_Ai00, input_precision=SOLVE_TRIL_DOT_PRECISION) ++ tl.dot(b_A31, b_Ai10, input_precision=SOLVE_TRIL_DOT_PRECISION) ++ tl.dot(b_A32, b_Ai20, input_precision=SOLVE_TRIL_DOT_PRECISION),+ input_precision=SOLVE_TRIL_DOT_PRECISION,+ )++ p_A00 = A_h + (i_tc0 + o_i)[:, None] * (HV*BT) + o_i[None, :]+ p_A10 = A_h + (i_tc1 + o_i)[:, None] * (HV*BT) + o_i[None, :]+ p_A11 = A_h + (i_tc1 + o_i)[:, None] * (HV*BT) + (BC + o_i)[None, :]+ p_A20 = A_h + (i_tc2 + o_i)[:, None] * (HV*BT) + o_i[None, :]+ p_A21 = A_h + (i_tc2 + o_i)[:, None] * (HV*BT) + (BC + o_i)[None, :]+ p_A22 = A_h + (i_tc2 + o_i)[:, None] * (HV*BT) + (2*BC + o_i)[None, :]+ p_A30 = A_h + (i_tc3 + o_i)[:, None] * (HV*BT) + o_i[None, :]+ p_A31 = A_h + (i_tc3 + o_i)[:, None] * (HV*BT) + (BC + o_i)[None, :]+ p_A32 = A_h + (i_tc3 + o_i)[:, None] * (HV*BT) + (2*BC + o_i)[None, :]+ p_A33 = A_h + (i_tc3 + o_i)[:, None] * (HV*BT) + (3*BC + o_i)[None, :]++ m_A0 = m_tc0[:, None] & (o_i[None, :] < BT)+ m_A1 = m_tc1[:, None] & (o_i[None, :] < BT)+ m_A2 = m_tc2[:, None] & (o_i[None, :] < BT)+ m_A3 = m_tc3[:, None] & (o_i[None, :] < BT)+ m_A11 = m_tc1[:, None] & ((BC + o_i)[None, :] < BT)+ m_A21 = m_tc2[:, None] & ((BC + o_i)[None, :] < BT)+ m_A22 = m_tc2[:, None] & ((2*BC + o_i)[None, :] < BT)+ m_A31 = m_tc3[:, None] & ((BC + o_i)[None, :] < BT)+ m_A32 = m_tc3[:, None] & ((2*BC + o_i)[None, :] < BT)+ m_A33 = m_tc3[:, None] & ((3*BC + o_i)[None, :] < BT)++ tl.store(p_A00, b_Ai00.to(A.dtype.element_ty), mask=m_A0)+ tl.store(p_A10, b_Ai10.to(A.dtype.element_ty), mask=m_A1)+ tl.store(p_A11, b_Ai11.to(A.dtype.element_ty), mask=m_A11)+ tl.store(p_A20, b_Ai20.to(A.dtype.element_ty), mask=m_A2)+ tl.store(p_A21, b_Ai21.to(A.dtype.element_ty), mask=m_A21)+ tl.store(p_A22, b_Ai22.to(A.dtype.element_ty), mask=m_A22)+ tl.store(p_A30, b_Ai30.to(A.dtype.element_ty), mask=m_A3)+ tl.store(p_A31, b_Ai31.to(A.dtype.element_ty), mask=m_A31)+ tl.store(p_A32, b_Ai32.to(A.dtype.element_ty), mask=m_A32)+ tl.store(p_A33, b_Ai33.to(A.dtype.element_ty), mask=m_A33)+++def kkt_shared(k, g, beta, chunk_size=64, abl=0):+ """Same result as gdn_fused.gdn_kkt_solve (bitwise): A [B, T, HV, 64] = (I + tril(beta k k^T exp2(dg)))^-1, bf16."""+ B, T, H, K = k.shape+ HV = beta.shape[2]+ assert chunk_size == 64 and K % 32 == 0 and HV % H == 0+ A = torch.zeros(B, T, HV, chunk_size, device=k.device, dtype=k.dtype)+ kkt_solve_shared_kernel[(triton.cdiv(T, chunk_size), B * H)](k=k, g=g, beta=beta, A=A, T=T, H=H, HV=HV, K=K, BT=chunk_size, BC=16, ABL=abl)+ return Adiff --git a/exllamav3/vendor/fla/gdn_pf.py b/exllamav3/vendor/fla/gdn_pf.pynew file mode 100644index 0000000..21b877e--- /dev/null+++ b/exllamav3/vendor/fla/gdn_pf.py@@ -0,0 +1,44 @@+# EXL3_GDN_PF=1 (default 1): GDN prefill entry that takes q, k, v as strided slices of the conv output (no input_guard copies of q, k, v:+# three full passes, 168 MB per layer-chunk at 4096 rows) and no single-tensor cat copy of the result. The q / k l2norm reads the strided rows+# directly (same Triton body and the same pinned (BT, num_warps) as l2norm_fwd_kernel: only the load address differs, so the bits are the same),+# and the fused HIP kernel reads v through its row pitch. Falls back to the stock chain on the same inputs made contiguous.+import torch+import triton+import triton.language as tl+from .l2norm import L2_BT, L2_WARPS++BT_LIST = [8, 16, 32, 64, 128]++[email protected](do_not_specialize=["T"])+def l2norm_strided_kernel(x, y, eps, T, S, D: tl.constexpr, H: tl.constexpr, BD: tl.constexpr, NB: tl.constexpr, BT: tl.constexpr):+ # rows o_t = token * H + head; input row address token * S + head * D (S = token pitch in elements), output contiguous+ i_t = tl.program_id(0).to(tl.int64)+ o_t = i_t * BT + tl.arange(0, BT)+ o_d = tl.arange(0, BD)+ m_t = o_t < T * H+ m_x = m_t[:, None] & (o_d[None, :] < D)+ p_x = x + (o_t // H)[:, None] * S + (o_t % H)[:, None] * D + o_d[None, :]+ p_y = y + o_t[:, None] * D + o_d[None, :]+ b_x = tl.load(p_x, mask=m_x, other=0.0).to(tl.float32)+ b_rstd = 1 / tl.sqrt(tl.sum(b_x * b_x, 1) + eps)+ b_y = b_x * b_rstd[:, None]+ tl.store(p_y, b_y.to(p_y.dtype.element_ty), mask=m_x)+++def strided_ok(x):+ B, T, H, D = x.shape+ return x.stride(3) == 1 and x.stride(2) == D and x.stride(1) >= H * D and (B == 1 or x.stride(0) == T * x.stride(1)) \+ and x.stride(1) % 8 == 0 and x.storage_offset() % 8 == 0+++def l2norm_strided(x, eps=1e-6):+ B, T, H, D = x.shape+ assert strided_ok(x) and D == 128+ y = torch.empty((B, T, H, D), dtype=x.dtype, device=x.device)+ rows = B * T * H+ # rows of batch item b start at b * T * S; for B > 1 the flat row -> (token, head) map still holds because stride(0) == T * stride(1)+ l2norm_strided_kernel[(triton.cdiv(rows, L2_BT),)](+ x=x, y=y, eps=eps, T=B * T, S=x.stride(1), D=D, H=H, BD=triton.next_power_of_2(D), NB=triton.cdiv(B * T, 2048 * 32),+ BT=L2_BT, num_warps=L2_WARPS)+ return ydiff --git a/exllamav3/vendor/fla/gdn_wy_fast.py b/exllamav3/vendor/fla/gdn_wy_fast.pyindex 746d405..53e7c5d 100644--- a/exllamav3/vendor/fla/gdn_wy_fast.py+++ b/exllamav3/vendor/fla/gdn_wy_fast.py@@ -26,7 +26,7 @@ PREPARE_WY_REPR_BWD_NUM_STAGES = [4] if IS_NVIDIA_BLACKWELL else [2, 3, 4]configs=[triton.Config({}, num_warps=num_warps, num_stages=num_stages)for num_warps in [2, 4, 8]- for num_stages in [2, 3, 4]+ for num_stages in [1, 2, 3, 4]],key=['H', 'HV', 'K', 'V', 'BT', 'BK', 'BV', 'IS_VARLEN'],**autotune_cache_kwargs,diff --git a/exllamav3/vendor/fla/hip/gdn_fused_h.hip b/exllamav3/vendor/fla/hip/gdn_fused_h.hipnew file mode 100644index 0000000..c781f65--- /dev/null+++ b/exllamav3/vendor/fla/hip/gdn_fused_h.hip@@ -0,0 +1,503 @@+// GDN (gated delta rule) fused chunk kernel, hand-written for gfx11.5 WMMA (Strix Halo, wave32).+// Fuses recompute_w_u + chunk_gated_delta_rule_fwd_h + chunk_fwd_o of the vendored fla Triton chain:+// w = A (k beta exp2 g), u = A (v beta), v_new = u - w h, o = scale (exp2(g) q h + tril(q k^T exp2(g_i - g_j)) v_new),+// h <- exp2(g_last) h + k^T (v_new exp2(g_last - g)).+// Same rounding points as the Triton kernels (bf16 products truncated, explicit casts RNE, raw v_exp_f32,+// fp32 WMMA accumulation chained in the same k order, no fma contraction: build with -ffp-contract=off).+// One workgroup (8 waves) per (batch, value head); K = V = 128, BT = 64. Wave i owns the state columns+// h[:, 16i:16i+16] in registers (8 WMMA C tiles). A (the solved kkt matrix, bf16) comes from the Triton kkt_solve kernel.+// Fragment layout (gfx1151, oracle-verified in exllamav3_ext/hip/hip_mma.cuh):+// A: lane l, elem r -> A[l & 15][r]; B: lane l, elem r -> B[r][l & 15]; C: lane l, reg r -> C[2r + (l >> 4)][l & 15]+//+// v is read through the row pitch PV (elements; HV * VD when contiguous), so the conv output slice can be used in place.+// MEMORY SAFETY: every global address comes from the IX_* macros below with the token row clamped by TCL (rows >= T+// re-read row T - 1 and are zeroed in registers), every store is guarded by t < T. check_gdn_bounds.py parses these+// macros and replays all accesses over the real shapes (it must fail when TCL or a guard is mutated).++#include <hip/hip_runtime.h>+#include <stdint.h>++typedef short v16s __attribute__((ext_vector_type(16)));+typedef float v8f __attribute__((ext_vector_type(8)));+typedef uint32_t v8u __attribute__((ext_vector_type(8)));++#define BT 64+#define KD 128+#define VD 128+#define LDR 136 // row-major [token][kdim] buffers (bf16 elements per row)+#define LDT 72 // transposed [dim][token] buffers++#ifndef OFMA+#define OFMA 1 // 1 (Triton contracts it; bit-exact): o = fma(o_inter, scale, o_intra * scale) (Triton may contract this add)+#endif+#ifndef DBG+#define DBG 0 // 1: dump w, u, v_new (bf16) and per-chunk state (bf16) for stage-by-stage checks (B = 1)+#endif+#ifndef RELOAD+#define RELOAD 0 // 1: q and k rows are re-read from global (L2) after the w/u phase instead of being held in registers across it+#endif+#ifndef SB+#define SB 0 // bit mask of sched_barrier(0) sites (stops the scheduler hoisting later LDS fragment loads: spills): 1 chain kt loop, 2 state kt loop, 4 w/u a loop, 8 o2 a loop, 16 Aqk kt loop+#endif+#ifndef ABL+#define ABL 0 // timing ablations (output is garbage when nonzero; addresses unchanged or fewer): 1 w/u chain, 2 Aqk chain, 4 o1/vn chain, 8 o2 chain, 16 state update chain, 32 phase-1 global loads, 64 barriers 3-6, 128 barriers 1-2, 256 o stores (result folded into a sink instead), 512 o stores all to row 0, 1024 / 2048 / 4096 zero the v / k+q / g+beta loads+#endif+#define SYNCA(b) do { if (!(ABL & (b))) __syncthreads(); } while (0)+#define SBAR(b) do { if (SB & (b)) __builtin_amdgcn_sched_barrier(0); } while (0)+#ifndef OST+#define OST 0 // 1: o tile staged through LDS (sW) and written as 16 B vectors, full 256 B rows (same bits; replaces 2 B stores of 32 B row pieces)+#endif+#ifndef PF1+#define PF1 0 // 1: phase 1 writes its LDS tiles directly after a barrier at the top of the chunk (no register staging across a barrier; same bits)+#endif+#if PF1 && RELOAD+#error PF1 and RELOAD are exclusive+#endif+#ifndef BRL+#define BRL 1 // branchless f2bf (same bits)+#endif++// ---- global index macros (checked on CPU). tc = absolute token row (bos + clamped t), results in elements ----+#define TCL(bos_, t_, T_) ((bos_) + min((t_), (T_) - 1))+#define IX_QK(tc, hh, c) ((((int64_t) (tc)) * H + (hh)) * KD + (c))+#define IX_V(tc, hv, c) ((((int64_t) (tc)) * HV + (hv)) * VD + (c))+#define IX_VR(tc, hv, c) ((((int64_t) (tc)) * PV) + ((int64_t) (hv)) * VD + (c)) // v read with row pitch PV (elements)+#define IX_G(tc, hv) (((int64_t) (tc)) * HV + (hv))+#define IX_A(tc, hv, c) ((((int64_t) (tc)) * HV + (hv)) * BT + (c))+#define IX_S(nh, kd, cl) (((int64_t) (nh)) * KD * VD + (kd) * VD + (cl))++__device__ __forceinline__ uint32_t f2bf(float f)+{+ uint32_t u = __float_as_uint(f);+#if BRL+ const uint32_t n = ((u >> 16) | 0x40u) & 0xffffu;+ const uint32_t r = (u + 0x7fffu + ((u >> 16) & 1u)) >> 16;+ const uint32_t m = 0u - (uint32_t) ((u & 0x7fffffffu) > 0x7f800000u);+ return (r & ~m) | (n & m);+#else+ if ((u & 0x7fffffffu) > 0x7f800000u) return ((u >> 16) | 0x40u) & 0xffffu;+ u += 0x7fffu + ((u >> 16) & 1u);+ return u >> 16;+#endif+}+__device__ __forceinline__ float bf2f(uint32_t b) { return __uint_as_float(b << 16); }+// Triton rounds explicit .to(bf16) casts to nearest even but truncates the result of bf16 x bf16 arithmetic+__device__ __forceinline__ uint32_t f2bf_rtz(float f) { return __float_as_uint(f) >> 16; }+__device__ __forceinline__ float ex2(float x) { return __builtin_amdgcn_exp2f(x); }++__device__ __forceinline__ v8f wmma(v8u a, v8u b, v8f c)+{+ return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(__builtin_bit_cast(v16s, a), __builtin_bit_cast(v16s, b), c);+}++// 16 contiguous bf16 at base[row * ld + col] (32 B, 16 B aligned) from LDS+__device__ __forceinline__ v8u ld16(const uint16_t* base, int row, int ld, int col)+{+ const uint4* p = (const uint4*) (base + row * ld + col);+ uint4 x = p[0], y = p[1];+ v8u r = {x.x, x.y, x.z, x.w, y.x, y.y, y.z, y.w};+ return r;+}++// p must be a valid address (clamped row); zeroed after the load when !ok+__device__ __forceinline__ v8u ld16g(const uint16_t* p, bool ok)+{+ uint4 x = ((const uint4*) p)[0], y = ((const uint4*) p)[1];+ v8u r = {x.x, x.y, x.z, x.w, y.x, y.y, y.z, y.w};+ if (!ok) r = (v8u) {0, 0, 0, 0, 0, 0, 0, 0};+ return r;+}++// C tile (fp32, rows 2r + half) -> B fragment of the same bf16-rounded matrix (k = row), via permlanex16.+__device__ __forceinline__ v8u c_to_b(const v8f& c, int half)+{+ uint32_t own[4], oth[4];+ #pragma unroll+ for (int m = 0; m < 4; ++m)+ {+ own[m] = f2bf(c[2 * m]) | (f2bf(c[2 * m + 1]) << 16);+ oth[m] = __builtin_amdgcn_permlanex16(own[m], own[m], 0x76543210u, 0xfedcba98u, false, false);+ }+ v8u b;+ #pragma unroll+ for (int d = 0; d < 8; ++d)+ {+ uint32_t o = (own[d >> 1] >> (16 * (d & 1))) & 0xffffu;+ uint32_t t = (oth[d >> 1] >> (16 * (d & 1))) & 0xffffu;+ b[d] = half ? (t | (o << 16)) : (o | (t << 16));+ }+ return b;+}++extern "C" __global__ __launch_bounds__(256) void gdn_fused_h_o(+ const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,+ const float* __restrict__ g, const uint16_t* __restrict__ beta, const uint16_t* __restrict__ A,+ uint16_t* __restrict__ o, const float* __restrict__ h0, float* __restrict__ ht, float scale, int T, int H, int HV, int PV,+ uint16_t* __restrict__ dw, uint16_t* __restrict__ du, uint16_t* __restrict__ dvn, uint16_t* __restrict__ dh)+{+ __shared__ __attribute__((aligned(16))) uint16_t sW[BT * LDR]; // w [token][kdim]+ __shared__ __attribute__((aligned(16))) uint16_t sX[KD * LDT]; // kb^T [kdim][token], then q [token][kdim]+ __shared__ __attribute__((aligned(16))) uint16_t sY[KD * LDT]; // vb^T [v][token], then k [token][kdim], then k^T [kdim][token]+ __shared__ __attribute__((aligned(16))) uint16_t sA[BT * LDT]; // A [token][token], then tril(Aqk) bf16+ __shared__ float sG[BT], sGE[BT], sRS[BT]; // g, exp2(g), exp2(g_last - g) (0 for rows >= T)++ const int tid = threadIdx.x, wv = tid >> 5, lane = tid & 31, ll = lane & 15, half = lane >> 4;+ const int i_nh = blockIdx.x, i_n = i_nh / HV, i_hv = i_nh % HV, i_h = i_hv / (HV / H);+ const int64_t bos = (int64_t) i_n * T;+ const int NT = (T + BT - 1) / BT;+ const int cp = tid & 63, tg = tid >> 6; // loader: column pair 2cp, tokens 16tg..16tg+15+ const int col = 16 * wv + ll; // this lane's state / value column+ const int ar = tid >> 2, ac = 16 * (tid & 3); // A-matrix staging: row, 16-column slice++ uint32_t sink = 0; // ABL 256 only+ v8f h[8];+ #pragma unroll+ for (int kt = 0; kt < 8; ++kt)+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ h[kt][r] = h0 ? h0[IX_S(i_nh, 16 * kt + 2 * r + half, col)] : 0.0f;++ for (int i_t = 0; i_t < NT; ++i_t)+ {+ const int t0 = i_t * BT;+ const int last = min(t0 + BT, T) - 1;+ const float gl = g[IX_G(bos + last, i_hv)];+ const float egl = ex2(gl);++#if PF1+ // ---- phase 1 (PF1): barrier first (previous chunk done with sX, sY, sW, sA, sG), then every per-token product goes straight+ // into LDS, so no phase-1 result is held in registers across a barrier (that held ~64 registers next to the 64-register state+ // and made the compiler spill about 50 per chunk to scratch)+ SYNCA(128);+ if (tid < BT)+ {+ const int t = t0 + tid;+ const float gv = (t < T) ? g[IX_G(TCL(bos, t, T), i_hv)] : 0.0f;+ sG[tid] = gv; sGE[tid] = ex2(gv); sRS[tid] = (t < T) ? ex2(gl - gv) : 0.0f;+ }+ {+ const v8u aa = ld16g(A + IX_A(TCL(bos, t0 + ar, T), i_hv, ac), t0 + ar < T);+ uint4* d = (uint4*) (sA + ar * LDT + ac);+ d[0] = make_uint4(aa[0], aa[1], aa[2], aa[3]); d[1] = make_uint4(aa[4], aa[5], aa[6], aa[7]);+ }+ uint32_t qraw[16], kraw[16];+ #pragma unroll+ for (int s2 = 0; s2 < 8; ++s2)+ {+ uint32_t kb[2][2], vb[2][2];+ #pragma unroll+ for (int e = 0; e < 2; ++e)+ {+ const int tt = 16 * tg + 2 * s2 + e, t = t0 + tt;+ const bool ok = t < T;+ const int64_t tc = TCL(bos, t, T);+ uint32_t kk = *(const uint32_t*) (k + IX_QK(tc, i_h, 2 * cp));+ uint32_t qq = *(const uint32_t*) (q + IX_QK(tc, i_h, 2 * cp));+ uint32_t vv = *(const uint32_t*) (v + IX_VR(tc, i_hv, 2 * cp));+ float gv = g[IX_G(tc, i_hv)];+ uint32_t bb = beta[IX_G(tc, i_hv)];+ if (!ok || (ABL & 32)) { kk = qq = vv = bb = 0; gv = 0.f; }+ if (ABL & 1024) vv = 0;+ if (ABL & 2048) { kk = 0; qq = 0; }+ if (ABL & 4096) { bb = 0; gv = 0.f; }+ const float fb = bf2f(bb), eg = ex2(gv);+ const float k0 = bf2f(kk & 0xffff), k1 = bf2f(kk >> 16);+ kb[0][e] = f2bf(bf2f(f2bf_rtz(k0 * fb)) * eg);+ kb[1][e] = f2bf(bf2f(f2bf_rtz(k1 * fb)) * eg);+ vb[0][e] = f2bf_rtz(bf2f(vv & 0xffff) * fb);+ vb[1][e] = f2bf_rtz(bf2f(vv >> 16) * fb);+ qraw[2 * s2 + e] = qq;+ kraw[2 * s2 + e] = kk;+ }+ #pragma unroll+ for (int c = 0; c < 2; ++c)+ {+ *(uint32_t*) (sX + (2 * cp + c) * LDT + 16 * tg + 2 * s2) = kb[c][0] | (kb[c][1] << 16);+ *(uint32_t*) (sY + (2 * cp + c) * LDT + 16 * tg + 2 * s2) = vb[c][0] | (vb[c][1] << 16);+ }+ }+ SYNCA(128);++#else+ // ---- phase 1: per-token products in registers (+ this thread's A slice)+ const v8u aa = ld16g(A + IX_A(TCL(bos, t0 + ar, T), i_hv, ac), t0 + ar < T);+ uint32_t kbp[2][8], vbp[2][8];+#if !RELOAD+ uint32_t qraw[16], kraw[16];+#else+ uint32_t kraw[16];+#endif+ #pragma unroll+ for (int s2 = 0; s2 < 8; ++s2)+ {+ uint32_t kb[2][2], vb[2][2];+ #pragma unroll+ for (int e = 0; e < 2; ++e)+ {+ const int tt = 16 * tg + 2 * s2 + e, t = t0 + tt;+ const bool ok = t < T;+ const int64_t tc = TCL(bos, t, T);+ uint32_t kk = *(const uint32_t*) (k + IX_QK(tc, i_h, 2 * cp));+ uint32_t qq = *(const uint32_t*) (q + IX_QK(tc, i_h, 2 * cp));+ uint32_t vv = *(const uint32_t*) (v + IX_VR(tc, i_hv, 2 * cp));+ float gv = g[IX_G(tc, i_hv)];+ uint32_t bb = beta[IX_G(tc, i_hv)];+ if (!ok || (ABL & 32)) { kk = qq = vv = bb = 0; gv = 0.f; }+ if (ABL & 1024) vv = 0;+ if (ABL & 2048) { kk = 0; qq = 0; }+ if (ABL & 4096) { bb = 0; gv = 0.f; }+ const float fb = bf2f(bb), eg = ex2(gv);+ const float k0 = bf2f(kk & 0xffff), k1 = bf2f(kk >> 16);+ kb[0][e] = f2bf(bf2f(f2bf_rtz(k0 * fb)) * eg);+ kb[1][e] = f2bf(bf2f(f2bf_rtz(k1 * fb)) * eg);+ vb[0][e] = f2bf_rtz(bf2f(vv & 0xffff) * fb);+ vb[1][e] = f2bf_rtz(bf2f(vv >> 16) * fb);+#if !RELOAD+ qraw[2 * s2 + e] = qq;+ kraw[2 * s2 + e] = kk;+#endif+ }+ #pragma unroll+ for (int c = 0; c < 2; ++c)+ {+ kbp[c][s2] = kb[c][0] | (kb[c][1] << 16);+ vbp[c][s2] = vb[c][0] | (vb[c][1] << 16);+ }+ }++ SYNCA(128); // previous chunk done with sX, sY, sW, sA, sG+ if (tid < BT)+ {+ const int t = t0 + tid;+ const float gv = (t < T) ? g[IX_G(TCL(bos, t, T), i_hv)] : 0.0f;+ sG[tid] = gv; sGE[tid] = ex2(gv); sRS[tid] = (t < T) ? ex2(gl - gv) : 0.0f;+ }+ #pragma unroll+ for (int c = 0; c < 2; ++c)+ #pragma unroll+ for (int s2 = 0; s2 < 8; ++s2)+ {+ *(uint32_t*) (sX + (2 * cp + c) * LDT + 16 * tg + 2 * s2) = kbp[c][s2];+ *(uint32_t*) (sY + (2 * cp + c) * LDT + 16 * tg + 2 * s2) = vbp[c][s2];+ }+ {+ uint4* d = (uint4*) (sA + ar * LDT + ac);+ d[0] = make_uint4(aa[0], aa[1], aa[2], aa[3]); d[1] = make_uint4(aa[4], aa[5], aa[6], aa[7]);+ }+ SYNCA(128);++#endif++ // ---- w[:, kdim block wv] and u[:, v block wv]+ uint32_t up[4][4];+ #pragma unroll+ for (int a = 0; a < 4; ++a)+ {+ v8u Af[4];+ #pragma unroll+ for (int j = 0; j < 4; ++j)+ Af[j] = ld16(sA, 16 * a + ll, LDT, 16 * j);+ v8f w = {0, 0, 0, 0, 0, 0, 0, 0}, u = {0, 0, 0, 0, 0, 0, 0, 0};+ #pragma unroll+ for (int j = 0; j < 4; ++j)+ {+ if (!(ABL & 1))+ {+ w = wmma(Af[j], ld16(sX, col, LDT, 16 * j), w);+ u = wmma(Af[j], ld16(sY, col, LDT, 16 * j), u);+ }+ }+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ sW[(16 * a + 2 * r + half) * LDR + col] = (uint16_t) f2bf(w[r]);+ #pragma unroll+ for (int m = 0; m < 4; ++m)+ up[a][m] = f2bf(u[2 * m]) | (f2bf(u[2 * m + 1]) << 16);+ SBAR(4);+#if DBG+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ {+ const int t = t0 + 16 * a + 2 * r + half;+ if (t < T)+ {+ dw[IX_V(bos + t, i_hv, col)] = (uint16_t) f2bf(w[r]);+ du[IX_V(bos + t, i_hv, col)] = (uint16_t) ((up[a][r >> 1] >> (16 * (r & 1))) & 0xffffu);+ }+ }+#endif+ }+ SYNCA(64); // sW complete; sX / sY phase-1 reads done++ // q and k row-major for the intra-chunk product+ #pragma unroll+ for (int s = 0; s < 16; ++s)+ {+#if RELOAD+ const int t = t0 + 16 * tg + s;+ const int64_t tc = TCL(bos, t, T);+ uint32_t kk = *(const uint32_t*) (k + IX_QK(tc, i_h, 2 * cp));+ uint32_t qq = *(const uint32_t*) (q + IX_QK(tc, i_h, 2 * cp));+ if (t >= T) kk = qq = 0;+ kraw[s] = kk;+ *(uint32_t*) (sX + (16 * tg + s) * LDR + 2 * cp) = qq;+ *(uint32_t*) (sY + (16 * tg + s) * LDR + 2 * cp) = kk;+#else+ *(uint32_t*) (sX + (16 * tg + s) * LDR + 2 * cp) = qraw[s];+ *(uint32_t*) (sY + (16 * tg + s) * LDR + 2 * cp) = kraw[s];+#endif+ }+ SYNCA(64);++ // ---- Aqk = tril(q k^T exp2(g_i - g_j)) -> bf16 into sA (10 lower tiles over 8 waves)+ #pragma unroll+ for (int ti = 0; ti < 2; ++ti)+ {+ const int tix = wv + 8 * ti;+ if (tix < 10)+ {+ const int a = (tix >= 6) ? 3 : (tix >= 3) ? 2 : (tix >= 1) ? 1 : 0;+ const int j = tix - (a * (a + 1)) / 2;+ v8f acc = {0, 0, 0, 0, 0, 0, 0, 0};+ #pragma unroll+ for (int kt = 0; kt < 8; ++kt)+ {+ if (!(ABL & 2)) acc = wmma(ld16(sX, 16 * a + ll, LDR, 16 * kt), ld16(sY, 16 * j + ll, LDR, 16 * kt), acc);+ SBAR(16);+ }+ const int cj = 16 * j + ll;+ const float gc = sG[cj];+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ {+ const int ri = 16 * a + 2 * r + half;+ const float x = acc[r] * ex2(sG[ri] - gc);+ const bool keep = (t0 + ri >= t0 + cj) && (t0 + ri < T) && (t0 + cj < T);+ sA[ri * LDT + cj] = (uint16_t) (keep ? f2bf(x) : 0u);+ }+ }+ }+ SYNCA(64); // tril(Aqk) complete; sY (k row-major) reads done++ // k^T [kdim][token] for the state update+ #pragma unroll+ for (int s2 = 0; s2 < 8; ++s2)+ {+ const uint32_t k0 = kraw[2 * s2], k1 = kraw[2 * s2 + 1];+ *(uint32_t*) (sY + (2 * cp) * LDT + 16 * tg + 2 * s2) = (k0 & 0xffffu) | (k1 << 16);+ *(uint32_t*) (sY + (2 * cp + 1) * LDT + 16 * tg + 2 * s2) = (k0 >> 16) | (k1 & 0xffff0000u);+ }++ // ---- o1 = q h, vn = w h (chained over kdim tiles)+ v8f oa[4], vn[4];+ #pragma unroll+ for (int a = 0; a < 4; ++a) { oa[a] = (v8f) {0, 0, 0, 0, 0, 0, 0, 0}; vn[a] = oa[a]; }+ #pragma unroll+ for (int kt = 0; kt < 8; ++kt)+ {+ const v8u hb = c_to_b(h[kt], half);+#if DBG+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ dh[((int64_t) i_t * HV + i_hv) * KD * VD + (16 * kt + 2 * r + half) * VD + col] = (uint16_t) f2bf(h[kt][r]);+#endif+ #pragma unroll+ for (int a = 0; a < 4; ++a)+ {+ if (!(ABL & 4))+ {+ oa[a] = wmma(ld16(sX, 16 * a + ll, LDR, 16 * kt), hb, oa[a]);+ vn[a] = wmma(ld16(sW, 16 * a + ll, LDR, 16 * kt), hb, vn[a]);+ }+ }+ SBAR(1);+ }++#if OST+ __syncthreads(); // every wave is done reading sW (w) before the o tile is staged into it+#endif+ // ---- v_new = u - w h; o = scale (exp2(g) o1) + scale (Aqk v_new)+ v8u vs[4], vg[4];+ #pragma unroll+ for (int a = 0; a < 4; ++a)+ {+ v8f vsc;+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ {+ vn[a][r] = bf2f((up[a][r >> 1] >> (16 * (r & 1))) & 0xffffu) - vn[a][r];+ vsc[r] = vn[a][r] * sRS[16 * a + 2 * r + half];+ }+ vs[a] = c_to_b(vn[a], half);+ vg[a] = c_to_b(vsc, half);+#if DBG+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ {+ const int t = t0 + 16 * a + 2 * r + half;+ if (t < T) dvn[IX_V(bos + t, i_hv, col)] = (uint16_t) f2bf(vn[a][r]);+ }+#endif+ }+ #pragma unroll+ for (int a = 0; a < 4; ++a)+ {+ v8f o2 = {0, 0, 0, 0, 0, 0, 0, 0};+ #pragma unroll+ for (int j = 0; j < 4; ++j)+ if (j <= a && !(ABL & 8)) o2 = wmma(ld16(sA, 16 * a + ll, LDT, 16 * j), vs[j], o2);+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ {+ const int t = t0 + 16 * a + 2 * r + half;+ const float o1 = oa[a][r] * sGE[16 * a + 2 * r + half];+#if OFMA+ const float res = __builtin_fmaf(o1, scale, o2[r] * scale);+#else+ const float res = o1 * scale + o2[r] * scale;+#endif+#if OST+ sW[(16 * a + 2 * r + half) * LDR + col] = (uint16_t) f2bf(res);+#else+ if (ABL & 256) sink ^= f2bf(res);+ else if (ABL & 512) { o[IX_V(bos, i_hv, col)] = (uint16_t) f2bf(res); } // timing only: every row lands on token row 0 of this item (same instruction count, no write traffic)+ else+ if (t < T) o[IX_V(bos + t, i_hv, col)] = (uint16_t) f2bf(res);+#endif+ }+ SBAR(8);+ }++ SYNCA(64); // k^T visible+#if OST+ // o tile (sW, written above) -> global: thread (row rr, 8 columns cc), 4 rows per thread, 16 B per store+ #pragma unroll+ for (int i = 0; i < 4; ++i)+ {+ const int rr = (tid >> 4) + 16 * i, cc = 8 * (tid & 15), t = t0 + rr;+ const uint4 x = *(const uint4*) (sW + rr * LDR + cc);+ if (t < T) *(uint4*) (o + IX_V(bos + t, i_hv, cc)) = x;+ }+#endif+ // ---- h = h exp2(g_last) + k^T (v_new exp2(g_last - g))+ #pragma unroll+ for (int kt = 0; kt < 8; ++kt)+ {+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ h[kt][r] *= egl;+ #pragma unroll+ for (int j = 0; j < 4; ++j)+ if (!(ABL & 16)) h[kt] = wmma(ld16(sY, 16 * kt + ll, LDT, 16 * j), vg[j], h[kt]);+ SBAR(2);+ }+ }++ if (ABL & 256) { if (sink == 0x9e3779b9u && tid == 0) o[0] = 0; } // keeps the ablated o path alive+ if (ht)+ #pragma unroll+ for (int kt = 0; kt < 8; ++kt)+ #pragma unroll+ for (int r = 0; r < 8; ++r)+ ht[IX_S(i_nh, 16 * kt + 2 * r + half, col)] = h[kt][r];+}diff --git a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.pynew file mode 100644index 0000000..d843a18--- /dev/null+++ b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py@@ -0,0 +1,95 @@+# Loader for the hand-written HIP fused GDN chunk kernel (gdn_fused_h.hip). Compiles a gfx code object with the+# ROCm SDK hipcc on first use (cached by source hash) and launches it through torch's own libamdhip64 via+# hipModuleLaunchKernel on the current torch stream: no extension rebuild, no second HIP runtime.++import ctypes, hashlib, os, shutil, subprocess+import torch++_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gdn_fused_h.hip")+_state = {}+++def _hipcc():+ for p in (os.environ.get("EXL3_HIPCC"),+ os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),+ "$EXL3_ROOT",+ shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):+ if p and os.path.isfile(p):+ return p+ raise RuntimeError("gdn_fused_h_hip: hipcc not found (set EXL3_HIPCC)")+++def _compile(defs, arch):+ # hsaco path for these defines (compiled once, cached by source + flags hash); needs no GPU+ src = open(_SRC, "rb").read()+ flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off"] + [x if x.startswith("-") else f"-D{x}" for x in defs.split()]+ gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")+ if os.path.isdir(gcc):+ flags.append(f"--gcc-install-dir={gcc}")+ tag = hashlib.sha1(src + " ".join(flags).encode()).hexdigest()[:16]+ cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"gdn_fused_h_{arch}_{tag}.hsaco")+ if not os.path.isfile(cache):+ os.makedirs(os.path.dirname(cache), exist_ok=True)+ tmp = cache + f".{os.getpid()}.tmp"+ subprocess.run([_hipcc(), *flags, "-o", tmp, _SRC], check=True, capture_output=True)+ os.replace(tmp, cache)+ return cache+++def _load(defs=""):+ # defs: extra -D defines (timing experiments only, e.g. "ABL=4"); one module per defines string+ if defs in _state:+ return _state[defs]+ cache = _compile(defs, torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])+ lib = ctypes.CDLL(os.path.join(os.path.dirname(torch.__file__), "lib", "libamdhip64.so"))+ torch.cuda.init()+ mod, fn = ctypes.c_void_p(), ctypes.c_void_p()+ if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0:+ raise RuntimeError("gdn_fused_h_hip: hipModuleLoad failed")+ if lib.hipModuleGetFunction(ctypes.byref(fn), mod, b"gdn_fused_h_o") != 0:+ raise RuntimeError("gdn_fused_h_hip: hipModuleGetFunction failed")+ lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3+ _state["lib"] = lib+ _state[defs] = fn+ _state["mod", defs] = mod+ return fn+++def chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=None, output_final_state=False, defs="", dbg=None, grid=None):+ """recompute_w_u + chunk_h + chunk_o in one kernel. q, k [B,T,H,128] bf16; v [B,T,HV,128] bf16; g [B,T,HV] fp32+ (chunk-local cumsum, log2 domain); beta [B,T,HV] bf16; A [B,T,HV,64] bf16 (solved kkt). Returns (o, final_state).+ dbg: optional dict of bf16 buffers w, u, vn [T,HV,128] and h [NT,HV,128,128] (build with defs containing DBG=1)."""+ B, T, H, K = k.shape+ HV, V = v.shape[2], v.shape[-1]+ assert K == 128 and V == 128 and HV % H == 0+ assert q.dtype == k.dtype == v.dtype == beta.dtype == A.dtype == torch.bfloat16 and g.dtype == torch.float32+ for t in (q, k, g, beta, A):+ assert t.is_contiguous()+ # v: row pitch (elements) may exceed HV * V (slice of the conv output); rows of one batch item are pitch apart, items T * pitch apart+ PV = v.stride(1)+ assert v.stride(3) == 1 and v.stride(2) == V and PV >= HV * V and PV % 2 == 0 and v.storage_offset() % 2 == 0+ assert B == 1 or v.stride(0) == T * PV+ assert q.shape == k.shape and g.shape == (B, T, HV) and beta.shape == (B, T, HV) and A.shape == (B, T, HV, 64)+ if not defs and os.environ.get("EXL3_GDN_OST", "1") == "1":+ defs = "OST=1" # EXL3_GDN_OST: o tile staged through LDS, 16 B row stores (same bits, see gdn_fused_h.hip)+ fn = _load(defs)+ o = torch.empty(B, T, HV, V, device=v.device, dtype=v.dtype)+ final_state = k.new_empty(B, HV, K, V, dtype=torch.float32) if output_final_state else None+ h0 = initial_state+ if h0 is not None:+ assert h0.dtype == torch.float32 and h0.is_contiguous() and h0.shape == (B, HV, K, V)+ P = ctypes.c_void_p+ d = dbg or {}+ args = [P(q.data_ptr()), P(k.data_ptr()), P(v.data_ptr()), P(g.data_ptr()), P(beta.data_ptr()), P(A.data_ptr()),+ P(o.data_ptr()), P(0 if h0 is None else h0.data_ptr()), P(final_state.data_ptr() if output_final_state else 0),+ ctypes.c_float(scale), ctypes.c_int(T), ctypes.c_int(H), ctypes.c_int(HV), ctypes.c_int(PV)]+ for n in ("w", "u", "vn", "h"):+ args.append(P(d[n].data_ptr() if n in d else 0))+ params = (ctypes.c_void_p * len(args))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in args])+ stream = torch.cuda.current_stream().cuda_stream+ nwg = B * HV if grid is None else int(grid) # grid < B * HV launches the first nwg heads only (timing experiments)+ assert 0 < nwg <= B * HV+ r = _state["lib"].hipModuleLaunchKernel(fn, nwg, 1, 1, 256, 1, 1, 0, stream, params, None)+ if r != 0:+ raise RuntimeError(f"gdn_fused_h_hip: launch failed ({r})")+ return o, final_statediff --git a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py b/exllamav3/vendor/fla/hip/kda_fused_h_hip.pyindex be3b0ac..0e5eb98 100644--- a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py+++ b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py@@ -12,7 +12,7 @@ _state = {}def _hipcc():for p in (os.environ.get("EXL3_HIPCC"),os.path.join(os.environ.get("EXL3_ROCM_SDK", ""), "bin", "hipcc"),- "~/kyojin/.venv-gfx1151/lib/python3.12/site-packages/_rocm_sdk_devel/bin/hipcc",+ "$EXL3_ROOT",shutil.which("hipcc"), "/opt/rocm/bin/hipcc"):if p and os.path.isfile(p):return pdiff --git a/exllamav3/vendor/fla/l2norm.py b/exllamav3/vendor/fla/l2norm.pyindex 7c50757..a84b34d 100644--- a/exllamav3/vendor/fla/l2norm.py+++ b/exllamav3/vendor/fla/l2norm.py@@ -45,8 +45,14 @@ def l2norm_fwd_kernel1(tl.store(rstd + i_t, b_rstd)+# One fixed launch config (8 rows per program, 8 warps = one row per warp). The sum over D = 128 rounds differently for other (BT, num_warps)+# (1 ulp bf16 on about 4 elements in a million), so a timing-picked config made the result depend on which autotune run filled the cache.+# The pinned config is the one that cache held on the test box; gdn_pf.l2norm_strided uses the same (BT, num_warps) and is bitwise equal to this kernel.+L2_BT, L2_WARPS = 8, 8++@triton.autotune(- configs=[triton.Config({"BT": BT}, num_warps=num_warps) for num_warps in [1, 2, 4, 8, 16] for BT in BT_LIST],+ configs=[triton.Config({"BT": L2_BT}, num_warps=L2_WARPS)],key=["D", "NB"],**autotune_cache_kwargs,)diff --git a/tests/test_ablit_qwen_cpu.py b/tests/test_ablit_qwen_cpu.pynew file mode 100644index 0000000..2bfb268--- /dev/null+++ b/tests/test_ablit_qwen_cpu.py@@ -0,0 +1,133 @@+"""CPU tests for the Qwen (qwen4_exp) runtime-ablation port: hidden 2560 kernel (non power of two), MTP skip,+arch table, spec export on mock directions, trunk-state capture. No model, no GPU."""+import os+os.environ["TRITON_INTERPRET"] = "1" # kernel runs in the Triton CPU interpreter (set before triton is imported)+import importlib.util+import json+import os+import subprocess+import sys+import types++import numpy as np+import pytest+import torch+from safetensors.torch import save_file++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+sys.path.insert(0, os.path.join(ROOT, "tools", "ablit"))+H = 2560+++def load_hook(triton_interpret=False):+ if triton_interpret:+ os.environ["TRITON_INTERPRET"] = "1"+ s = importlib.util.spec_from_file_location("ablit_runtime_q", os.path.join(ROOT, "exllamav3/modules/ablit_runtime.py"))+ m = importlib.util.module_from_spec(s)+ s.loader.exec_module(m)+ return m+++def dense(y, w, r):+ r = (r / r.norm()).float()+ return y.float() - w * torch.outer(y.float() @ r, r)+++def test_block_size_is_power_of_two():+ hook = load_hook()+ assert hook._block(2560) == 4096 and hook._block(4096) == 4096 and hook._block(2049) == 4096 and hook._block(1) == 1++[email protected]("dt", [torch.float32, torch.float16])+def test_triton_kernel_hidden_2560_matches_dense(dt):+ pytest.importorskip("triton")+ hook = load_hook(triton_interpret=True)+ if hook.triton is None:+ pytest.skip("no triton")+ g = torch.Generator().manual_seed(0)+ r = torch.randn(H, generator=g)+ r32 = (r / r.norm()).float()+ y = torch.randn(7, H, generator=g).to(dt)+ want = dense(y, 1.3, r)+ got = y.clone()+ hook._USE_TRITON = True+ hook.project(got, 1.3, r32, r32.half())+ assert torch.allclose(got.float(), want, atol=2e-3 if dt == torch.float16 else 1e-4, rtol=1e-3)+ # the masked lanes must not touch memory past the row: neighbouring rows of a bigger tensor stay equal+ big = torch.randn(3, H, generator=g).to(dt)+ ref = big.clone()+ hook.project(big[1:2], 0.0, r32, r32.half())+ assert torch.equal(big, ref)+++def test_torch_path_hidden_2560():+ hook = load_hook()+ hook._USE_TRITON = False+ g = torch.Generator().manual_seed(1)+ r = torch.randn(H, generator=g)+ r32 = (r / r.norm()).float()+ y = torch.randn(5, H, generator=g)+ assert torch.allclose(hook.project(y.clone(), 0.9, r32, r32.half()), dense(y, 0.9, r), atol=1e-4)+++def test_mtp_blocks_are_not_edited(tmp_path, monkeypatch):+ r = torch.randn(32, dtype=torch.float64)+ save_file({"r": r.contiguous()}, str(tmp_path / "s.safetensors"))+ (tmp_path / "s.json").write_text(json.dumps({"hidden": 32, "n_layers": 48, "attn_w": [0.5] * 48, "mlp_w": [0.5] * 48}))+ monkeypatch.setenv("EXL3_ABLIT_RUNTIME", str(tmp_path / "s.json"))+ hook = load_hook()+ hook._USE_TRITON = False+ def blk(key):+ return types.SimpleNamespace(key=key, attn=object(), mlp=object(), ablit=None, config=types.SimpleNamespace(directory=str(tmp_path)))+ for key, expect in (("model.language_model.layers.5", True), ("model.language_model.layers.47", True),+ ("mtp.layers.0", False), ("model.mtp.layers.0", False)):+ b = blk(key)+ hook.prepare(b, "cpu")+ assert (b.ablit is not None) == expect, key+++def test_arch_qwen_detect_and_chat():+ import arch+ d = os.path.expanduser("~/models/qwen38-yamz-v1")+ if os.path.isdir(d):+ assert arch.get("auto", d)["name"] == "qwen4_exp"+ a = arch.get("qwen4_exp")+ assert (a["n_layers"], a["hidden"], a["readout"]) == (48, 2560, "hc_mean")+ assert arch.chat_wrap("Hi", a).endswith("<|im_start|>assistant\n<think>\n\n</think>\n\n")+ assert a["pca_layer"] == 31+++def test_export_spec_on_mock_directions(tmp_path):+ out = subprocess.run([sys.executable, os.path.join(ROOT, "tools/ablit/collect_dirs.py"), "--mock", "--mock-layers", "48",+ "--mock-hidden", str(H), "--mock-n", "16", "--out", str(tmp_path / "dirs")],+ capture_output=True, text=True)+ assert out.returncode == 0, out.stderr[-500:]+ k = {"attn": {"max_w": 2.0, "peak": 30.0, "min_w": 1.0, "width": 20.0}, "mlp": {"max_w": 1.0, "peak": 18.0, "min_w": 0.3, "width": 28.0}}+ (tmp_path / "k.json").write_text(json.dumps(k))+ out = subprocess.run([sys.executable, os.path.join(ROOT, "tools/ablit/export_spec.py"), "--dirs", str(tmp_path / "dirs"),+ "--arch", "qwen4_exp", "--kernel", str(tmp_path / "k.json"), "--scale-kernel", "--out", str(tmp_path / "spec")],+ capture_output=True, text=True)+ assert out.returncode == 0, out.stderr[-500:]+ spec = json.load(open(tmp_path / "spec" / "edit_spec.json"))+ assert spec["hidden"] == H and spec["n_layers"] == 48 and len(spec["attn_w"]) == 48 and len(spec["mlp_w"]) == 48+ from safetensors.torch import load_file+ r = load_file(str(tmp_path / "spec" / "edit_spec.safetensors"))["r"]+ assert r.shape == (H,) and abs(float(r.norm()) - 1.0) < 1e-4+++def test_capture_states_collects_48_blocks_with_hc_mean():+ import qwen_collect_dirs as Q+ class TransformerBlock:+ def __init__(self, k): self.k = k+ def prepare_for_device(self, s, p): return s+ def forward(self, s, p): return s + 1.0+ class Embed:+ def prepare_for_device(self, s, p): return s+ def forward(self, s, p): return s+ x = torch.zeros(1, 5, 4, 8)+ x[..., 0] = torch.tensor([0.0, 2.0, 4.0, 6.0]) # streams differ -> mean 3+ out = Q.capture_states([Embed()] + [TransformerBlock(i) for i in range(48)], x, {"export_states": [1]})+ assert len(out) == 48 and out[0].shape == (5, 8)+ assert torch.allclose(out[0][:, 0], torch.full((5,), 4.0)) and torch.allclose(out[47][:, 0], torch.full((5,), 51.0))+ with pytest.raises(AssertionError):+ Q.capture_states([TransformerBlock(0)], x, {})diff --git a/tests/test_ple_stash_clone.py b/tests/test_ple_stash_clone.pynew file mode 100644index 0000000..ee0e71b--- /dev/null+++ b/tests/test_ple_stash_clone.py@@ -0,0 +1,43 @@+"""+CPU regression test for the PLE checkpoint stash: id_state lives on the CPU, so stash() must return a+copy. A stashed state must not change when the slot advances (decode, next job), and unstash must+restore the ids that were live at stash time. Fails if the .clone() in PLELayerState.stash is removed.+"""+import os, sys+from types import SimpleNamespace+import torch+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from exllamav3.modules.ple import PLELayerState+++def make_state():+ module = SimpleNamespace(+ conv_state_len = 3,+ hc_mult = 2,+ hidden_size = 4,+ ple_embedding = SimpleNamespace(context_len = 5, eos_token_id = 7),+ )+ st = PLELayerState(module, max_batch_size = 2, max_history = 4, cache_id = 0)+ st.alloc("cpu")+ return st+++def test_stash_is_a_copy():+ st = make_state()+ slot = 1+ st.id_state[slot, :st.ctx] = torch.arange(100, 100 + st.ctx)+ ids_at_stash = st.id_state[slot, :st.ctx].clone()+ stashed = st.stash(slot)++ # slot advances+ st.id_state[slot, :st.ctx] = torch.arange(900, 900 + st.ctx)++ assert torch.equal(stashed[1], ids_at_stash), "stashed id_state changed when the slot advanced"++ st.unstash(slot, stashed)+ assert torch.equal(st.id_state[slot, :st.ctx], ids_at_stash)+++if __name__ == "__main__":+ test_stash_is_a_copy()+ print("ok")diff --git a/tools/evalgate/loops.py b/tools/evalgate/loops.pynew file mode 100644index 0000000..1aa807b--- /dev/null+++ b/tools/evalgate/loops.py@@ -0,0 +1,36 @@+"""Greedy-loop detector (hard release gate: 0/100). CPU only, model-agnostic.++A generation is a loop when its last 1000 characters compress below 30 % with zlib (same rule as loop1/loop2) AND the+tail holds an explicit repeated span: some 50-character span occurs at least 3 times in the last 3000 characters.+The span check is script-agnostic. The zlib ratio alone flags short valid answers in non-Latin scripts (Thai, 3 bytes per+character in UTF-8 compress differently: ifeval-0183, ratio 0.291), because zlib runs on UTF-8 bytes.+"""+import zlib+from collections import Counter++WINDOW, RATIO, MIN_CHARS = 1000, 0.30, 200+SPAN_TAIL, SPAN_LEN, SPAN_MIN = 3000, 50, 3+# the gate arm: 100 pinned IFEval prompts, cap 1536 (the old cap 640 hid loops: loop1), greedy. sampler_kw None = engine default+# (serve.DEFAULT_SAMPLER_KW / SERVE_SAMPLER_KW); a profile sets the shipped penalties, e.g. {"rep_p": 1.10} for GLM.+DEFAULT_ARM = {"task": "ifeval", "n": 100, "cap": 1536, "temp": 0.0, "top_p": 1.0, "sampler_kw": None}+++def zlib_low(text):+ t = text[-WINDOW:]+ return len(t) >= MIN_CHARS and len(zlib.compress(t.encode())) / max(len(t.encode()), 1) < RATIO+++def max_span_repeat(text):+ """Highest occurrence count of any SPAN_LEN-character span in the last SPAN_TAIL characters."""+ t = text[-SPAN_TAIL:]+ return max(Counter(t[i:i + SPAN_LEN] for i in range(len(t) - SPAN_LEN + 1)).values(), default=0)+++def is_loop(text):+ return zlib_low(text) and max_span_repeat(text) >= SPAN_MIN+++def summarize(recs):+ """recs: run_suite jsonl records (_id, text, hit_cap) -> {n, loops, ids, capped}."""+ ids = sorted(r["_id"] for r in recs if is_loop(r["text"]))+ return {"n": len(recs), "loops": len(ids), "ids": ids, "capped": sum(bool(r.get("hit_cap")) for r in recs)}diff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex 136006a..7dac24a 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -1,7 +1,7 @@#!/usr/bin/env python3"""msrv -- OpenAI-compatible server for MiMo-V2.6 EXL3 with DFlash drafting + SpecGate.-The HTTP/streaming layer is adapted from tools/glm/serve.py (the GLM server); the engine wiring is+The HTTP/streaming layer is adapted from tools/glm/serve.py (glm-serve); the engine wiring isadapted from scripts/dflash-bench.py so the served decode path is the measured one (plain ~30 t/s,DFlash with a 4 bpw EXL3 drafter and confidence-truncated draft length).@@ -32,8 +32,8 @@ DEFAULT_MODEL = os.path.expanduser("~/models/mimo26-exl3")DEFAULT_MODEL_ID = "MiMo-2.6-EXL3"DEFAULT_CTX = 4096DEFAULT_NDT = 7-# Sampling used when a request omits temperature/top_p. Agent clients often send neither, so-# a plain-greedy default makes the lane loop; the lane launchers pass the model-card values (T1.0, top_p 0.95).+# Sampling used when a request omits temperature/top_p. The client sends neither on the main agent loop, so+# a plain-greedy default makes the lane loop; the lane launcher passes the model-card values (T1.0, top_p 0.95).SERVE_DEFAULTS: dict[str, float] = {"temperature": 0.0, "top_p": 1.0}# The template uses a zero-width space inside the tag so plain prose does not trigger tools.TOOL_OPEN = "<tool_call>"@@ -77,96 +77,56 @@ def _json_value(raw: str) -> Any:# ---------------------------------------------------------------------------- completion parsing_NAME_RE = re.compile(r"<function=([^\s>]+)\s*>")-_FUNC_RE = re.compile(r"<function=([^\s>]+)\s*>(.*?)(?:</function>|(?=<function=)|\Z)", re.S)_PARAM_RE = re.compile(r"<parameter=([^\s>]+)\s*>(.*?)</parameter>", re.S)-def _schema_types(tools: list[dict[str, Any]] | None, name: str) -> dict[str, Any]:- """Property schemas of the declared tool `name` ({} when unknown)."""- for tool in tools or []:- fn = tool.get("function", tool) if isinstance(tool, dict) else {}- if fn.get("name") == name:- params = fn.get("parameters") or fn.get("input_schema") or {}- props = params.get("properties") if isinstance(params, dict) else None- return props if isinstance(props, dict) else {}- return {}---def _coerce(value: str, schema: Any) -> Any:- """XML parameter text -> typed value. Strings stay strings unless the schema asks for another type."""- kind = schema.get("type") if isinstance(schema, dict) else None- kinds = kind if isinstance(kind, list) else [kind]- if "string" in kinds and len(kinds) == 1:- return value- parsed = _json_value(value)- if parsed is value: # not JSON- return value- if isinstance(parsed, (dict, list)):- return parsed- # scalars: only when the schema declares a non-string type, else keep the text (e.g. "007", "true" as a name)- if kinds != [None] and any(k in kinds for k in ("integer", "number", "boolean", "null")):- return parsed- return value---def _xml_params(raw: str, props: dict[str, Any] | None = None) -> dict[str, Any] | None:- """MiMo's template teaches <parameter=key>value</parameter>: map it to a dict."""+def _xml_params(raw: str) -> dict[str, Any] | None:+ """MiMo's template teaches <parameter=key>value</parameter>: map it to a dict (object/array values parsed as JSON, the rest kept as text)."""found = _PARAM_RE.findall(raw)- if not found:- return None- props = props or {}- return {k: _coerce(v.strip("\n") if props.get(k, {}).get("type") == "string" else v.strip(), props.get(k))- for k, v in found}---def _parse_call(name: str, body: str, tools: list[dict[str, Any]] | None) -> dict[str, Any]:- args_text = body.split("</function>")[0].strip()- args: Any = {}- if args_text:- args = _json_value(args_text)- if isinstance(args, str): # not JSON: try the XML parameter form- xml = _xml_params(args_text, _schema_types(tools, name))- if xml is not None:- args = xml- # A malformed body is passed through raw (never silently turned into {} and executed):- # the client fails json.loads and reports the error back to the model.- arguments = json.dumps(args, ensure_ascii=False) if isinstance(args, dict) else args_text- return {"id": f"call_{uuid.uuid4().hex[:24]}", "type": "function",- "function": {"name": name, "arguments": arguments}}---def parse_completion(text: str, tools: list[dict[str, Any]] | None = None) -> dict[str, Any]:- """Split MiMo <think> blocks and <tool_call><function=NAME>...</function></tool_call>- blocks into OpenAI message fields. A block body is JSON or <parameter=k>v</parameter> XML;- one block may hold several <function=...> elements. An unterminated trailing <tool_call>- (generation cut off) is dropped from the content and yields no call."""+ vals = {k: v.strip() for k, v in found}+ return {k: (j if isinstance(j := _json_value(v), (dict, list)) else v) for k, v in vals.items()} if vals else None+++def parse_completion(text: str) -> dict[str, Any]:+ """Split MiMo <think> blocks and <tool_call><function=NAME>{json}</function></tool_call>+ blocks into OpenAI message fields."""calls: list[dict[str, Any]] = []content_parts: list[str] = []reasoning_parts: list[str] = []-- def prose(chunk: str) -> None:- if "<think>" in chunk:- before, after = chunk.split("<think>", 1)- content_parts.append(before)- thinking, _, chunk = after.partition("</think>")- reasoning_parts.append(thinking)- content_parts.append(chunk)-# A bare "</think>" with no opener is left as literal content: MiMo's template never ends the# generation prompt inside a think block (it emits "<think></think>" for enable_thinking=false),# so the streamed and non-streamed paths classify the same text identically.cursor = 0pattern = re.compile(re.escape(TOOL_OPEN) + r"(.*?)" + re.escape(TOOL_CLOSE), re.S)for match in pattern.finditer(text):- prose(text[cursor:match.start()])- cursor = match.end() # always advance: a nameless block must not leak or duplicate text- for fn in _FUNC_RE.finditer(match.group(1)):- calls.append(_parse_call(fn.group(1), fn.group(2), tools))+ visible = text[cursor:match.start()]+ if "<think>" in visible:+ before, after = visible.split("<think>", 1)+ content_parts.append(before)+ thinking, _, visible = after.partition("</think>")+ reasoning_parts.append(thinking)+ content_parts.append(visible)+ body = match.group(1)+ name_match = _NAME_RE.search(body)+ if not name_match:+ continue+ args_text = body[name_match.end():]+ args_text = args_text.split("</function>")[0].strip()+ args = _json_value(args_text) if args_text else {}+ if isinstance(args, str) and (xml := _xml_params(args_text)) is not None:+ args = xml+ calls.append({"id": f"call_{uuid.uuid4().hex[:24]}", "type": "function",+ "function": {"name": name_match.group(1),+ "arguments": args_text if isinstance(args, str)+ else json.dumps(args, ensure_ascii=False)}})+ cursor = match.end()tail = text[cursor:]- open_at = tail.find(TOOL_OPEN)- if open_at >= 0 and tail[open_at + len(TOOL_OPEN):].lstrip().startswith("<function="):- tail = tail[:open_at] # cut-off call: do not leak raw XML; prose that merely mentions the tag stays- prose(tail)+ if "<think>" in tail:+ before, after = tail.split("<think>", 1)+ content_parts.append(before)+ thinking, _, tail = after.partition("</think>")+ reasoning_parts.append(thinking)+ content_parts.append(tail)message: dict[str, Any] = {"role": "assistant", "content": "".join(content_parts)}reasoning = "".join(reasoning_parts)if reasoning:@@ -200,6 +160,17 @@ class ResidentEngine:spec_gate: bool = False, ctx: int | None = None,reset_gate_per_request: bool = False,dynamic_draft: bool = True, draft_confidence: float = 0.6):+ # Lossless speculation (mimoident1): every verify row uses the exact R=1 arithmetic, so+ # speculative output equals plain greedy output (20/20 prompts). Costs about 5 % chat and+ # 12 % code tok/s. EXL3_MIMO_LOSSLESS=0 restores the fast, not bit-identical verify.+ # Set before the exllamav3 import. Catch-up fusion stays automatic (on with the union MoE).+ if os.environ.get("EXL3_MIMO_LOSSLESS", "1") != "0":+ for k, v in (("EXL3_VERIFY_ATTN_LOOP", "1"), ("EXL3_VERIFY_GEMV_R", "1"),+ ("EXL3_DEC_MOE_UNION", "1")):+ os.environ.setdefault(k, v)+ # v2mimochk1: the one-launch wide-N verify GEMV (specrow1, lm_head) is a Qwen win but costs MiMo+ # about 7 % tok/s (35.6/31.0/42.3 -> 33.2/28.9/39.5). Off by default here; the caller's env wins.+ os.environ.setdefault("EXL3_VERIFY_WIDE_R", "0")import torchfrom exllamav3 import Config, Generator, Job, model_init@@ -442,7 +413,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:await flush(False)text, _ = stop_text(text, body["_stop"])await flush(True)- message = parse_completion(text, body.get("tools"))+ message = parse_completion(text)if "tool_calls" in message:await response.write(sse(event({"tool_calls": [dict(call, index=n) for n, call in enumerate(message["tool_calls"])]})))@@ -454,7 +425,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:raw = "".join([d async for d in deltas()])text, _ = stop_text(raw, body["_stop"])- message = parse_completion(text, body.get("tools"))+ message = parse_completion(text)finish = message.pop("finish_reason", "stop")return web.json_response({"id": request_id, "object": "chat.completion", "created": created, "model": model_id,@@ -581,7 +552,6 @@ def main() -> None:parser.add_argument("--host", default="127.0.0.1")parser.add_argument("--port", type=int, default=8000)parser.add_argument("--model", default=DEFAULT_MODEL)- parser.add_argument("--no-uncensor", action="store_true", help="ignore a bundled uncensor_spec.json in the model directory (same as EXL3_ABLIT_RUNTIME=off)")parser.add_argument("--model-id", default=DEFAULT_MODEL_ID)parser.add_argument("--drafter", default=None,help="drafter directory (default: $MIMO_DRAFTER, <model>/drafter, then <model>-drafter)")@@ -604,8 +574,6 @@ def main() -> None:parser.add_argument("--default-temperature", type=float, default=0.0, help="used when a request omits temperature")parser.add_argument("--default-top-p", type=float, default=1.0, help="used when a request omits top_p")args = parser.parse_args()- if args.no_uncensor:- os.environ["EXL3_ABLIT_RUNTIME"] = "off"SERVE_DEFAULTS.update(temperature=args.default_temperature, top_p=args.default_top_p)torch.set_grad_enabled(False)diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdnew file mode 100644index 0000000..1f96ea7--- /dev/null+++ b/tools/qwen/SERVE.md@@ -0,0 +1,106 @@+# qserve: OpenAI-compatible server for Qwen3.8-Flash EXL3 packs++`tools/qwen/serve.py` serves a Qwen3.8-Flash EXL3 pack (for example `Qwen3.8-Flash-Yamz`) over HTTP. It loads the target+model, the MTP drafter and the vision tower once, and keeps one Generator. Speculative decoding (MTP plus n-gram lookup,+the shipped "mix" rule) is on by default and lossless: greedy output equals plain greedy output.++## Run++Verified command (lab box, scripts/env.sh sets the ROCm runtime, `EXL3_MOE_CFG=2`, `EXL3_HIP_PREFILL_MIN_ROWS=2`;+the job ran from the repo root with the tree on `PYTHONPATH`):++ source $EXL3_ROOT+ export EXL3_ROOT=$PWD EXL3_REPO=$PWD PYTHONPATH=$PWD+ python -u tools/qwen/serve.py --model ~/models/qwen38-yamz-v1 --port 8000 -c 65536++Public tree: `source tools/strix_halo/env.sh` instead, then `export EXL3_MOE_CFG=2 EXL3_HIP_PREFILL_MIN_ROWS=2` (the two+values the verified runs had; the public env.sh does not set them; this variant was not run). Run from the repo root.+The server prints its effective `EXL3_*` / `MPW*` environment at start-up.++The server prints a progress line every 15 s while it loads (target, drafter, vision, warm-up). The port opens only when+everything is ready, and the last line says so:++ qserve: READY on http://127.0.0.1:8000 model=Qwen3.8-Flash-Yamz ctx=65536 speculative=True vision=True (start-up N s)++Quick test:++ curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{+ "model": "Qwen3.8-Flash-Yamz", "messages": [{"role": "user", "content": "Hello"}],+ "enable_thinking": false, "max_tokens": 100}'++## Flags++| flag | default | meaning |+|---|---|---|+| `--model` | `~/models/qwen38-yamz-v1` | pack directory (needs `chat_template.jinja`, `generation_config.json`) |+| `--model-id` | `Qwen3.8-Flash-Yamz` | id in `/v1/models`; requests that name another model get 400 |+| `--host`, `--port` | `127.0.0.1`, 8000 | listen address |+| `-c`, `--ctx` | 65536 | KV cache size in tokens (prompt + answer must fit) |+| `--ndt` | 3 | max draft tokens per speculative round |+| `--draft-policy` | `mix` | `mix` shipped rule, `mtp` fixed MTP chain, `off` plain decode (no drafter loaded) |+| `--no-vision` | off | do not load the vision tower (less memory, image input answers 400) |+| `--default-temperature/-top-p/-top-k/-min-p` | from `generation_config.json` (1.0 / 0.95 / 20) | used when a request omits them |+| `--default-reasoning-effort` | template default (`xhigh`) | `low`, `medium` or `xhigh` |+| `--no-thinking` | off | thinking off unless a request turns it on |+| `--default-max-tokens` | 32768 | when a request omits `max_tokens` (always clipped to the free context) |+| `--slot-save-path` | `~/cache/llama-slots` | directory for slot files |++Environment: the server sets the measured Qwen configuration with `setdefault` before the engine loads (the list is+`SERVE_ENV` in `serve.py`; the start-up log prints the effective `EXL3_*` / `MPW*` environment). It covers decode and+verify (`EXL3_MOE_FUSED`, `EXL3_MOE_VALU`, `EXL3_VERIFY_*`, `EXL3_GEMV_R_DEC1`, `EXL3_MTP_FUSE_CATCHUP=0`), prefill+(`EXL3_PLE_HIP`, `EXL3_DQ_HIP`, `EXL3_GR_HIP`, `EXL3_GDN_FUSE`, `EXL3_PF_SKIP`, `EXL3_PREFILL_CHUNK=4096`,+`EXL3_PF_DEFER`, `EXL3_PF_GR_FUSE`, `EXL3_MPW_GLUE`), `EXL3_MOE_CFG=2`, `EXL3_HIP_PREFILL_MIN_ROWS=2`, `EXL3_QSA_ROWINV`, `EXL3_ROLL_CKPT` and the int8 mixer with group+scales (`EXL3_GR_GS=1`; `hc_gs_sidecar.safetensors` in the model directory is picked up when present). Your own+environment wins. The engine modules read several of these when they are imported, so the server refuses to start if+`exllamav3` was imported before they were set.++## API++- `POST /v1/chat/completions`: stream (SSE) and non-stream, `tools` and `tool_calls`, `tool` role messages, images as+ `image_url` parts (`data:` URI or http(s) URL), `stop`, `max_tokens` / `max_completion_tokens`, `temperature`,+ `top_p`, `top_k`, `min_p`, `seed`. The model's own chat template renders the prompt (identical to the HF `apply_chat_template`).+- Thinking: the template default is thinking ON at effort `xhigh`; the answer then starts inside a reasoning block.+ The server splits it into `reasoning_content` and `content`. Turn it off per request with `"enable_thinking": false`+ (or `"chat_template_kwargs": {"enable_thinking": false}` or `"reasoning_effort": "none"`). Effort: `low`, `medium`,+ `xhigh` (`high` maps to `xhigh`, `minimal` to `low`).+ Give thinking room: with a small `max_tokens` the budget can end inside the thought, so `content` is empty and+ `finish_reason` is `length`.+- `finish_reason`: `stop`, `length` (cut by `max_tokens`), `tool_calls`.+- Tool calls: the model writes `<tool_call><function=NAME><parameter=KEY>VALUE</parameter></function></tool_call>`.+ They come back as OpenAI `tool_calls`; argument types follow the tool's JSON schema. In a stream, tool calls arrive+ as one delta after the text. Text after a closed call (or between two calls) is returned as `content`.+- `usage` (with `prompt_tokens_details.cached_tokens`) and `timings` (`cache_n`, `prompt_n` = tokens prefilled this turn,+ `prompt_ms`, `predicted_n`, `predicted_ms`, `predicted_per_second`, draft accept counts) on every answer; in a stream+ they are on the last chunk.+- Errors are JSON `{"error": {"message", "type", "code"}}`: 400 for bad requests (including prompt longer than the+ context), 500 for engine errors.+- `GET /v1/models`, `GET /health` (status, speculation state, vision), `POST /apply-template` (renders the prompt,+ generates nothing), `GET /slots`, `POST /slots/0?action=save|restore|erase` (llama.cpp slot files),+ `POST /completion` (llama.cpp style) and `POST /v1/completions` (OpenAI style, stream and non-stream): raw prompt, no+ template, one prompt, one choice (`n`, `best_of`, `echo` answer 400). The slot routes are CPU-tested only.+- Debug extensions (all optional): `"speculative": false` decodes plain for that request, `"cache_prompt": false`+ forgets the prompt cache first (cold run), `"return_token_ids": true` adds the generated ids. Switching+ speculative mode or `cache_prompt: false` rebuilds the Generator and so drops the prompt cache.++## Prompt cache between turns++The Generator keeps KV pages (256 tokens) and GDN recurrent checkpoints in RAM (4 GiB, about 111 MiB each). A follow-up+turn re-prefills only the part after the last checkpoint: the tail of the previous prompt (under 256 tokens) plus the+new text. `timings.prompt_n` shows how many tokens were prefilled. Requests are served one at a time, in order.++## Tests++ python -m pytest tools/qwen/test_serve.py tools/qwen/test_guard.py # CPU, fake engine, no GPU (template test needs the pack)+ python tools/qwen/serve_check.py http://127.0.0.1:8000 out_dir # live server: chat, thinking, tools, stream, image,+ # 3-turn cache, plain vs speculative, warm vs cold++## Measured on the real pack (qwen38-yamz-v1, 3.47 bpw, box iGPU, `-c 65536`, `MPW_KERN=1`)++- Start-up 52 s to READY (target, drafter, vision, warm-up).+- Served decode, greedy, 160 tokens, thinking off, 4 prompts per class, 2 interleaved passes (tok/s, plain / speculative):+ chat 27.3 / 42.2, prose 27.3 / 38.7, code 27.3 / 52.2, multi 27.3 / 42.6, copy 27.2 / 54.7.+ Speculative output equals plain greedy on all 20 prompts, both passes (token ids).+- Prompt cache, 3-turn chat with a 1.9K-token system prompt: prefilled 1909, 215, 338 tokens; time to first token 2.9 s, 0.5 s, 0.9 s.+- A cached second turn does not always give the same greedy tokens as a cold run of the same prompt (4 of 5 prompts+ diverge, first difference at token 19 to 83); plain decode shows the same, and two cold runs are identical. It comes with the cache restore, not with speculation (cause not isolated further,+ see `convcache1`).diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pynew file mode 100644index 0000000..edebaa0--- /dev/null+++ b/tools/qwen/serve.py@@ -0,0 +1,1417 @@+#!/usr/bin/env python3+"""qserve -- OpenAI-compatible server for Qwen3.8-Flash-class EXL3 packs (Yamz).++One resident target model, its MTP drafter (lossless speculative decoding, the shipped "mix" draft rule on by+default), the vision tower (optional), one Generator. The paged KV cache and the GDN recurrent checkpoints live in+the Generator, so a follow-up turn only prefills what is new.++The HTTP helpers (template render, SSE framing, stop strings) come from tools/mimo/serve.py; the engine wiring is+the one measured by tools/qwen/spec_bench.py (same Generator arguments, same draft policy).++Start: python tools/qwen/serve.py --model <pack> --port 8000 -c 65536 (see tools/qwen/SERVE.md)+"""+from __future__ import annotations++import argparse+import asyncio+import base64+import gc+import importlib.util+import io+import json+import math+import os+import re+import sys+import threading+import time+import urllib.request+import uuid+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++import jinja2+from aiohttp import web++HERE = Path(__file__).resolve().parent+sys.path.insert(0, str(HERE))+++def _load_mimo():+ spec = importlib.util.spec_from_file_location("mimo_serve", HERE.parent / "mimo" / "serve.py")+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++_mimo = _load_mimo()+render_prompt, stop_text, sse, config_max_position = (+ _mimo.render_prompt, _mimo.stop_text, _mimo.sse, _mimo.config_max_position)++DEFAULT_MODEL = os.path.expanduser("~/models/Qwen3.8-Flash-Next-EXL3-Yamz")+DEFAULT_MODEL_ID = "Qwen3.8-Flash-Yamz"+THINK_CLOSE = "</think>"+TOOL_OPEN, TOOL_CLOSE = "<tool_call>", "</tool_call>"+IMAGE_PAD = "<|image_pad|>"+MAX_IMAGE_BYTES = 20 * 1024**2+# Used when generation_config.json is missing (values of the Qwen3.8 card).+FALLBACK_DEFAULTS: dict[str, Any] = {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0}+# OpenAI effort names -> the Qwen template names (xhigh, medium, low).+EFFORT_ALIASES = {"high": "xhigh", "minimal": "low"}+++class BadRequest(Exception):+ pass+++# ---------------------------------------------------------------------------- parsing of the model output+++def _partial_tag(buf: str, tags: list[str]) -> int:+ """Length of the longest suffix of buf that is a proper prefix of one of the tags."""+ best = 0+ for tag in tags:+ for n in range(min(len(tag) - 1, len(buf)), best, -1):+ if tag.startswith(buf[-n:]):+ best = n+ break+ return best+++class Splitter:+ """Incremental split of the model text into reasoning, content and tool-call text.++ The same object serves the streamed and the non-streamed path, so both classify text identically.+ `reasoning_first`: the generation prompt ended inside a <think> block (template default), so the text+ starts as reasoning until </think>. From <tool_call> to </tool_call> everything is held for parse_tool_calls(); text after the close is content again.+ Whitespace at the edges of a piece (the newlines around </think> and <tool_call>) is dropped.+ """++ def __init__(self, reasoning_first: bool):+ self.mode = "reasoning" if reasoning_first else "content"+ self.buf = ""+ self.ws = ""+ self.lead = reasoning_first+ self.tool_text = ""+ self.tool_from = 0+ self.said = self.after_call = False++ def _emit(self, seg: str, out: list[tuple[str, str]]) -> None:+ seg = self.ws + seg+ self.ws = ""+ if self.lead:+ seg = seg.lstrip()+ self.lead = not seg+ body = seg.rstrip()+ self.ws = seg[len(body):]+ if body:+ if self.mode == "content":+ if self.after_call and self.said:+ body = "\n" + body # text that follows a tool call starts on its own line+ self.said, self.after_call = True, False+ out.append((self.mode, body))++ def feed(self, text: str, final: bool = False) -> list[tuple[str, str]]:+ out: list[tuple[str, str]] = []+ self.buf += text+ while True:+ if self.mode == "tool":+ self.tool_text += self.buf+ self.buf = ""+ end = self.tool_text.find(TOOL_CLOSE, self.tool_from)+ if end < 0:+ return out+ # call closed: text after it (or between two calls) is content again, a later <tool_call> reopens the mode+ end += len(TOOL_CLOSE)+ self.buf, self.tool_text = self.tool_text[end:], self.tool_text[:end]+ self.mode, self.lead, self.after_call = "content", True, True+ continue+ tags = [TOOL_OPEN] + ([THINK_CLOSE] if self.mode == "reasoning" else [])+ hits = [(self.buf.find(t), t) for t in tags if t in self.buf]+ if hits:+ pos, tag = min(hits)+ self._emit(self.buf[:pos], out)+ self.ws = ""+ self.buf = self.buf[pos + len(tag):]+ if tag == TOOL_OPEN:+ self.mode, self.tool_from = "tool", len(self.tool_text)+ self.tool_text += TOOL_OPEN+ else:+ self.mode, self.lead = "content", True+ continue+ keep = 0 if final else _partial_tag(self.buf, tags)+ self._emit(self.buf[:len(self.buf) - keep], out)+ self.buf = self.buf[len(self.buf) - keep:]+ return out++ def finish(self) -> list[tuple[str, str]]:+ out = self.feed("", final=True)+ self.ws = ""+ return out+++_FUNC_RE = re.compile(r"<function=([^>\s]+)\s*>(.*?)(?:</function>|$)", re.S)+_PARAM_RE = re.compile(r"<parameter=([^>\s]+)\s*>\n?(.*?)\n?</parameter>", re.S)+++def _coerce(value: str, schema: dict[str, Any] | None) -> Any:+ """Typed value of one <parameter>. The schema type wins: "string" keeps the text, boolean accepts true/false in any case+ (the template shows Python-style True/False), integer and number accept their text form, anything else is read as JSON."""+ kind = (schema or {}).get("type")+ kinds = [k for k in (kind if isinstance(kind, list) else [kind]) if isinstance(k, str)]+ text = value.strip()+ if kinds and "string" in kinds and not (text == "null" and "null" in kinds):+ return value+ if "boolean" in kinds and text.lower() in ("true", "false"):+ return text.lower() == "true"+ if "null" in kinds and text in ("null", "None"):+ return None+ for want, conv in (("integer", int), ("number", float)):+ if want in kinds:+ try:+ got = conv(text)+ except ValueError:+ continue+ if isinstance(got, float) and not math.isfinite(got):+ continue # nan / inf are not JSON: keep the text+ return got+ try:+ parsed = json.loads(value)+ except json.JSONDecodeError:+ return value+ if schema is None and not isinstance(parsed, (dict, list)):+ return value # no schema: keep scalars as the model wrote them+ return parsed+++def parse_tool_calls(tool_text: str, tools: list[dict[str, Any]] | None) -> list[dict[str, Any]]:+ """Qwen XML tool calls (<tool_call><function=NAME><parameter=K>V</parameter></function></tool_call>) to OpenAI."""+ schemas = {}+ for t in tools or []:+ fn = t.get("function", t)+ schemas[fn.get("name")] = (fn.get("parameters") or {}).get("properties", {})+ calls = []+ for block in re.findall(re.escape(TOOL_OPEN) + r"(.*?)" + re.escape(TOOL_CLOSE), tool_text, re.S):+ fm = _FUNC_RE.search(block)+ if fm:+ name, props = fm.group(1), schemas.get(fm.group(1), {})+ args = {k: _coerce(v, props.get(k) if props else None) for k, v in _PARAM_RE.findall(fm.group(2))}+ else: # JSON body: {"name": ..., "arguments": {...}}+ try:+ obj = json.loads(block.strip())+ name, args = obj["name"], obj.get("arguments", obj.get("parameters", {}))+ except (json.JSONDecodeError, KeyError, TypeError):+ continue+ calls.append({"id": f"call_{uuid.uuid4().hex[:24]}", "type": "function",+ "function": {"name": name,+ "arguments": args if isinstance(args, str) else json.dumps(args, ensure_ascii=False)}})+ return calls+++def split_completion(text: str, reasoning_first: bool, tools: list[dict[str, Any]] | None) -> dict[str, Any]:+ """Whole-text version of Splitter: an OpenAI message dict."""+ sp = Splitter(reasoning_first)+ pieces = sp.feed(text) + sp.finish()+ msg: dict[str, Any] = {"role": "assistant",+ "content": "".join(t for k, t in pieces if k == "content")}+ reasoning = "".join(t for k, t in pieces if k == "reasoning")+ if reasoning:+ msg["reasoning_content"] = reasoning+ calls = parse_tool_calls(sp.tool_text, tools)+ if calls:+ msg["tool_calls"] = calls+ return msg+++# ---------------------------------------------------------------------------- request helpers+++def resolve_template_kwargs(body: dict[str, Any], defaults: dict[str, Any]) -> dict[str, Any]:+ """enable_thinking / reasoning_effort for the chat template: chat_template_kwargs > top level > server defaults."""+ kw: dict[str, Any] = {}+ ctk = body.get("chat_template_kwargs") or {}+ if not isinstance(ctk, dict):+ raise BadRequest("chat_template_kwargs must be an object")+ for key in ("enable_thinking", "reasoning_effort"):+ for src in (ctk, body, defaults):+ if src.get(key) is not None:+ kw[key] = src[key]+ break+ effort = kw.get("reasoning_effort")+ if effort == "none":+ kw.pop("reasoning_effort")+ kw["enable_thinking"] = False+ elif isinstance(effort, str):+ kw["reasoning_effort"] = EFFORT_ALIASES.get(effort, effort)+ if "enable_thinking" in kw and not isinstance(kw["enable_thinking"], bool):+ raise BadRequest("enable_thinking must be boolean")+ return kw+++def extract_images(messages: list[dict[str, Any]]) -> list[str]:+ """Image URLs of the messages in prompt order (OpenAI image_url parts)."""+ urls = []+ for m in messages:+ content = m.get("content")+ if isinstance(content, list):+ for part in content:+ if isinstance(part, dict) and (part.get("type") in ("image_url", "image") or "image_url" in part):+ iu = part.get("image_url", part.get("image"))+ urls.append(iu.get("url") if isinstance(iu, dict) else iu)+ return urls+++def normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ out = []+ for m in messages:+ if not isinstance(m, dict) or "role" not in m:+ raise BadRequest("each message needs a role")+ if m.get("content") is None:+ m = dict(m, content="")+ out.append(m)+ return out+++def load_image(url: str):+ """PIL image from a data: URI or an http(s) URL (size capped)."""+ from PIL import Image+ if not isinstance(url, str) or not url:+ raise BadRequest("image_url needs a url")+ if url.startswith("data:"):+ try:+ raw = base64.b64decode(url.split(",", 1)[1])+ except Exception as exc: # noqa: BLE001+ raise BadRequest(f"bad data URI: {exc}") from exc+ elif url.startswith(("http://", "https://")):+ with urllib.request.urlopen(url, timeout=20) as r: # noqa: S310+ raw = r.read(MAX_IMAGE_BYTES + 1)+ else:+ raise BadRequest("image url must be a data: URI or http(s) URL")+ if len(raw) > MAX_IMAGE_BYTES:+ raise BadRequest("image too large")+ try:+ return Image.open(io.BytesIO(raw)).convert("RGB")+ except Exception as exc: # noqa: BLE001+ raise BadRequest(f"cannot decode image: {exc}") from exc+++def sampling_from(body: dict[str, Any], defaults: dict[str, Any]) -> dict[str, Any]:+ s = {}+ for key in ("temperature", "top_p", "top_k", "min_p"):+ v = body.get(key)+ s[key] = defaults[key] if v is None else v+ if not isinstance(s[key], (int, float)) or isinstance(s[key], bool) or not math.isfinite(s[key]):+ raise BadRequest(f"{key} must be a finite number")+ if s["temperature"] < 0 or not 0 < s["top_p"] <= 1 or s["top_k"] < 0 or not 0 <= s["min_p"] < 1:+ raise BadRequest("sampling parameter out of range")+ s["top_k"] = int(s["top_k"])+ return s+++def load_defaults(model_dir: str, args: argparse.Namespace | None = None) -> dict[str, Any]:+ """Sampling defaults = the pack's generation_config.json; command-line flags override."""+ d = dict(FALLBACK_DEFAULTS)+ gc = Path(model_dir) / "generation_config.json"+ if gc.is_file():+ cfg = json.loads(gc.read_text())+ d.update({k: cfg[k] for k in ("temperature", "top_p", "top_k") if k in cfg})+ d.update({"enable_thinking": None, "reasoning_effort": None})+ if args is not None:+ for key in ("temperature", "top_p", "top_k", "min_p"):+ v = getattr(args, "default_" + key, None)+ if v is not None:+ d[key] = v+ if args.default_reasoning_effort:+ d["reasoning_effort"] = args.default_reasoning_effort+ if args.no_thinking:+ d["enable_thinking"] = False+ return d+++# ---------------------------------------------------------------------------- engine+++class Heartbeat:+ """Prints one progress line every `every` seconds while a long start-up phase runs."""++ def __init__(self, label: str, every: float = 15.0):+ self.label, self.every, self.stop = label, every, threading.Event()++ def __enter__(self):+ self.t0 = time.time()+ print(f"qserve: {self.label} ...", flush=True)+ threading.Thread(target=self._run, daemon=True).start()+ return self++ def _run(self):+ while not self.stop.wait(self.every):+ print(f"qserve: {self.label} ... {time.time() - self.t0:.0f} s", flush=True)++ def __exit__(self, *exc):+ self.stop.set()+ print(f"qserve: {self.label} done in {time.time() - self.t0:.0f} s", flush=True)+++# ---------------------------------------------------------------------------- loop guard++# Same family as the GLM guard (tools/glm/serve.py LoopGuard): an n-gram period detector, plus a text rule for loops+# that drift (no exact period): the release-gate rule of tools/evalgate/loops.py (zlib ratio of the last 1000 chars+# < 30 % AND a 50-char span seen >= 3 times in the last 3000 chars) that must hold for a sustained stretch. Greedy+# thinking on a near-tie (the Qwen3.8 trait, ifeval-0015/0114/0195) is the target: the guard closes the think block.+GUARD_MAX_N = 64+GUARD_THINK = {"k": 4, "min_span": 48, "sustain": 320} # tokens; GLM thresholds for the period rule+GUARD_ANSWER = {"k": 6, "min_span": 96, "sustain": 640} # stricter: an answer may repeat items legitimately+GUARD_CHECK_EVERY = 16 # tokens between two evaluations of the text rule+TEXT_WINDOW, TEXT_RATIO, TEXT_MIN_CHARS = 1000, 0.30, 200+SPAN_TAIL, SPAN_LEN, SPAN_MIN = 3000, 50, 3+THINK_CLOSE_TEXT = "\n</think>\n\n"+THINK_CLOSE_TAG = "</think>"+FINAL_TRIES = 2+++def loop_guard_default() -> bool:+ return os.environ.get("EXL3_LOOP_GUARD", "1") != "0"+++def text_loop(text: str) -> bool:+ """tools/evalgate/loops.is_loop (kept identical; test_serve checks both agree)."""+ import zlib+ from collections import Counter+ w = text[-TEXT_WINDOW:]+ if len(w) < TEXT_MIN_CHARS or len(zlib.compress(w.encode())) / max(len(w.encode()), 1) >= TEXT_RATIO:+ return False+ t = text[-SPAN_TAIL:]+ return max(Counter(t[i:i + SPAN_LEN] for i in range(len(t) - SPAN_LEN + 1)).values(), default=0) >= SPAN_MIN+++class LoopMonitor:+ """Watches the tokens of one generation. feed() returns None, or a dict+ {phase, kind ("period"|"text"|"budget"), cut (tokens of the current phase to keep), at, period}.+ Phases: "think" (until the </think> token) then "answer"; a request without a think block starts in "answer".+ With detect=False only the thinking budget is enforced."""++ def __init__(self, phase: str, close_id: int | None, budget: int | None = None, detect: bool = True):+ self.close_id, self.budget, self.detect = close_id, budget, detect+ self.start_phase(phase)++ def start_phase(self, phase: str) -> None:+ self.phase = phase+ self.cfg = GUARD_THINK if phase == "think" else GUARD_ANSWER+ self.ids: list[int] = []+ self.run = [0] * (GUARD_MAX_N + 1)+ self.text = ""+ self.last_check = 0+ self.flag_from: int | None = None++ def feed(self, tokens, text: str = "") -> dict[str, Any] | None:+ tokens = [int(t) for t in tokens]+ if self.phase == "think" and self.close_id is not None and self.close_id in tokens:+ k = tokens.index(self.close_id)+ hit = self._feed(tokens[:k], text)+ if hit:+ return hit+ self.start_phase("answer")+ return self._feed(tokens[k + 1:], "")+ return self._feed(tokens, text)++ def _feed(self, tokens, text: str) -> dict[str, Any] | None:+ ids, run, cfg = self.ids, self.run, self.cfg+ self.text += text+ for t in tokens:+ i = len(ids)+ ids.append(t)+ if self.phase == "think" and self.budget is not None and i + 1 >= self.budget:+ return {"phase": "think", "kind": "budget", "cut": self.budget, "at": i + 1, "period": 0}+ if not self.detect:+ continue+ for n in range(1, GUARD_MAX_N + 1):+ r = run[n] + 1 if i >= n and t == ids[i - n] else 0+ run[n] = r+ if r >= max(n * (cfg["k"] - 1), cfg["min_span"] - n):+ return {"phase": self.phase, "kind": "period", "cut": max(i - r + 1, 1), "at": i + 1, "period": n}+ if self.detect and len(ids) - self.last_check >= GUARD_CHECK_EVERY:+ prev, self.last_check = self.last_check, len(ids)+ if text_loop(self.text[-(SPAN_TAIL + 200):]):+ if self.flag_from is None:+ self.flag_from = prev+ if len(ids) - self.flag_from >= cfg["sustain"]:+ return {"phase": self.phase, "kind": "text", "cut": max(self.flag_from, 1), "at": len(ids), "period": 0}+ else:+ self.flag_from = None+ if len(self.text) > 4 * SPAN_TAIL:+ self.text = self.text[-SPAN_TAIL * 2:]+ return None+++def gate_text(vis: str) -> str:+ """The text the release gate sees: reasoning + </think> + answer, each stripped (what Splitter returns to the client)."""+ think, tag, ans = vis.partition(THINK_CLOSE_TAG)+ return think.strip() + tag + ans.strip()+++def max_span_repeat(text: str) -> int:+ t = text[-SPAN_TAIL:]+ from collections import Counter+ return max(Counter(t[i:i + SPAN_LEN] for i in range(len(t) - SPAN_LEN + 1)).values(), default=0)+++def final_cut(vis: str) -> int:+ """The gate rule holds on the visible text (thinking [+ </think> + answer]). Return the character index at which to cut+ the thinking: the longest prefix (line starts first, then 64-character steps) that (a) holds no 50-character span twice+ in its last 3000 characters, so that the answer, which repeats the last draft once more, cannot bring any span to the+ count of 3 whatever it says, and (b) with </think> and the answer already written does not trip the rule. 0 if none."""+ think, _, ans = vis.partition(THINK_CLOSE_TAG)+ think = think.rstrip()+ lines = sorted({m.end() for m in re.finditer("\n", think)}, reverse=True)+ steps = sorted(set(range(0, len(think), 64)) - set(lines), reverse=True)+ for c in lines + steps:+ pre = think[:c].rstrip()+ if max_span_repeat(pre) <= 1 and not text_loop(pre + THINK_CLOSE_TAG + ans.strip()):+ return c+ return 0+++class Retract(int):+ """Yielded by QwenEngine.generate after a loop-guard restart: drop this many trailing characters of the text+ streamed so far (the discarded part of the thinking). A streaming client has already received them."""+++# Serving defaults applied at start-up (the caller's environment wins). The first six are the decode/verify set.+# The last five are the prefill set (served A/B on the test box, outputs identical): hand HIP kernels for the PLE chain,+# deinterleave_qg, the gated-residual GEMMs and the GDN chunk path (bitwise equal to the torch/triton paths, +21 % to +24 %+# prefill at 4K/16K), and EXL3_PF_SKIP (the MTP draft prefill fills K/V only and skips the 1-row lm_head, +0.5 % to +2 %).+# Set any of them to 0 to go back.+SERVE_ENV = (("EXL3_MOE_FUSED", "1"), ("EXL3_MOE_VALU", "1"), ("EXL3_VERIFY_ATTN_LOOP", "1"),+ ("EXL3_VERIFY_GEMV_R", "1"), ("EXL3_GEMV_R_DEC1", "1"), ("EXL3_MTP_FUSE_CATCHUP", "0"),+ ("EXL3_PLE_HIP", "1"), ("EXL3_DQ_HIP", "1"), ("EXL3_GR_HIP", "1"), ("EXL3_GDN_FUSE", "1"), ("EXL3_PF_SKIP", "1"),+ # 4096-row prefill chunks (one MoE pass per 4096 rows, no 2048 + 2048 + tail split below 4097 tokens) and the+ # draft prefill deferred behind the first token (first round is a plain target step; flushed before the second round,+ # at job end and on rewind, so the draft cache stays complete). 0 for either goes back.+ ("EXL3_PREFILL_CHUNK", "4096"), ("EXL3_PF_DEFER", "1"),+ # the batched R-row sparse attention launch is row-invariant (the split plan no longer depends on R, see+ # qsa_split_plan; EXL3_QSA_ROWINV=0 goes back), so verify keeps ONE launch and speculative == plain bitwise above the+ # QSA sparse threshold (2051 tokens). The per-row fallback is EXL3_VERIFY_QSA_PROJ=1 EXL3_VERIFY_QSA_ATTN=all.+ ("EXL3_VERIFY_QSA_PROJ", "0"), ("EXL3_VERIFY_QSA_ATTN", "0"), ("EXL3_QSA_ROWINV", "1"),+ # checkpoint the decode state at the end of every answer, so the next chat turn only prefills+ # the new message (without it an answer shorter than the 2048-token grid is prefilled again). 0 = off.+ ("EXL3_ROLL_CKPT", "1"),+ # bit-identical prefill levers (hyper-connection apply folded into the next norm, MoE glue v2), served+ # +2.4 % / +1.6 % / +1.8 % (fuse) and +0.9 / -0.1 / +0.3 % (glue) at 4K / 16K / 32K on bal. 0 = off.+ ("EXL3_PF_GR_FUSE", "1"), ("EXL3_MPW_GLUE", "1"),+ # Fidelity first: int8 mixer weights with group scales (fn 128 along H*D, up 64+ # along rank) and, when <model_dir>/hc_gs_sidecar.safetensors exists, its GPTQ-rounded codes (decoded-token KLD 0.0504 ->+ # 0.0455, plain decode +0.5-0.8 ms). A missing file means group scales with plain rounding. EXL3_GR_GS=0 = per-row scales.+ ("EXL3_GR_GS", "1"),+ # The verified serving command (SERVE.md, every served A/B log): k-split width 4 for the MoE matvec kernels and the+ # grouped prefill kernel from 2 rows up, so a speculative verify batch (2..4 rows) takes the deduplicating path.+ # Without them a bare `python serve.py` ran another kernel configuration than the one measured.+ ("EXL3_MOE_CFG", "2"), ("EXL3_HIP_PREFILL_MIN_ROWS", "2"),+ # Grouped MoE prefill GEMM: mpw2 (the engine default, +3-5 % prefill over the legacy kernel, identical ids). Its CPU bounds+ # proof (tools/qwen/check_mpw2_qwen.py --bits 4, bal pack: 4-bit routed experts, gate/up N 640, down N 2560, 63748 launches,+ # 0 failures, mutants fail) passed on this tree. The K6 draft experts never reach it (k2 12 aborts in a host check).+ ("MPW_KERN", "2"))++HC_GS_SIDECAR = "hc_gs_sidecar.safetensors"+# The sidecar of the published pack. A file with another hash (wrong pack, damaged download) is not used: plain group rounding, one log line.+HC_GS_SIDECAR_SHA256 = "473e7547adaad190788634556ce6b32614bdb280ccedadbed8789d39b59dcc8f"+++def _sha256_file(path) -> str:+ import hashlib+ h = hashlib.sha256()+ with open(path, "rb") as fh:+ for blk in iter(lambda: fh.read(1 << 24), b""):+ h.update(blk)+ return h.hexdigest()+++def configure_hc_sidecar(model_path: str) -> str:+ """Point EXL3_GR_GS_SIDECAR at <model_path>/hc_gs_sidecar.safetensors when group scales are on, the variable is unset and+ the file exists. Call before importing exllamav3 (the engine reads it at import). Returns the log line."""+ if os.environ.get("EXL3_GR_GS", "0") == "0":+ return "hc mixer: per-row int8 scales (EXL3_GR_GS=0)"+ env = os.environ.get("EXL3_GR_GS_SIDECAR")+ if env:+ return f"hc mixer: group scales, codes from {env} (EXL3_GR_GS_SIDECAR)"+ f = Path(model_path) / HC_GS_SIDECAR+ if f.is_file():+ got = _sha256_file(f)+ if got != HC_GS_SIDECAR_SHA256:+ return f"hc mixer: group scales, plain rounding ({f} has sha256 {got[:12]}, expected {HC_GS_SIDECAR_SHA256[:12]}: sidecar not used)"+ os.environ["EXL3_GR_GS_SIDECAR"] = str(f)+ return f"hc mixer: group scales, codes from {f}"+ return f"hc mixer: group scales, plain rounding (no {HC_GS_SIDECAR} in the model directory)"+++def _env_flag(name: str, default: str, off: tuple = ("", "0")) -> bool:+ return os.environ.get(name, default) not in off+++# (module, latched value, what the environment says now). The engine reads these switches when its modules are imported.+LATCHED = (+ ("exllamav3.modules.hyperconnections", lambda m: m._GR_GS, lambda: os.environ.get("EXL3_GR_GS", "0")),+ ("exllamav3.modules.block_sparse_mlp_routing", lambda m: m._MOE_VALU, lambda: os.environ.get("EXL3_MOE_VALU", "0") != "0"),+ ("exllamav3.modules.block_sparse_mlp_routing", lambda m: m._HIP_PREFILL_MIN_ROWS,+ lambda: max(2, int(os.environ.get("EXL3_HIP_PREFILL_MIN_ROWS", "17")))),+ ("exllamav3.modules.attention_fn.qsa_triton", lambda m: m.ROWINV["on"], lambda: _env_flag("EXL3_QSA_ROWINV", "1")),+ ("exllamav3.modules.qsa_indexer", lambda m: m.VERIFY_QSA_PROJ["on"], lambda: _env_flag("EXL3_VERIFY_QSA_PROJ", "0")),+ ("exllamav3.modules.qsa_indexer", lambda m: m.VERIFY_QSA_ATTN["mode"],+ lambda: {"": "", "0": "", "1": "all", "all": "all", "sel": "sel", "att": "att"}.get(os.environ.get("EXL3_VERIFY_QSA_ATTN", ""), "")),+ ("exllamav3.generator.generator", lambda m: m.MTP_FUSE_CATCHUP,+ lambda: None if os.environ.get("EXL3_MTP_FUSE_CATCHUP") is None else int(os.environ["EXL3_MTP_FUSE_CATCHUP"])),+)+++def check_latched_env() -> None:+ """Import-order trap: if exllamav3 was imported before SERVE_ENV was applied (a harness, a wrapper), the modules latched the+ engine defaults (for example the per-row mixer path instead of group scales) and the server would run another code path+ without saying so. Raise instead. Modules not imported yet read the environment at their first import and are fine."""+ bad = []+ for name, got, want in LATCHED:+ mod = sys.modules.get(name)+ if mod is not None and got(mod) != want():+ bad.append(f"{name}: engine has {got(mod)!r}, environment says {want()!r}")+ if bad:+ raise RuntimeError("exllamav3 was imported before the serving environment was set; restart with the server's own entry "+ "point (or set the EXL3_* switches in the shell before importing): " + "; ".join(bad))+++class QwenEngine:+ """Target model + MTP drafter + (optional) vision tower + one Generator."""++ def __init__(self, model_path: str, ctx: int, ndt: int = 3, draft_policy: str = "mix",+ vision: bool = True, max_chunk_size: int = 2048):+ # The measured Qwen serving configuration. Read at import time by the engine:+ # set before importing exllamav3. The caller's environment wins.+ for k, v in SERVE_ENV:+ os.environ.setdefault(k, v)+ check_latched_env()+ print("qserve:", configure_hc_sidecar(model_path), flush=True)+ import torch+ from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer+ torch.set_grad_enabled(False)+ self.torch, self.Generator, self.Job = torch, Generator, Job+ self.model_path, self.ctx, self.ndt, self.draft_policy = model_path, ctx, ndt, draft_policy+ self.config = Config.from_directory(model_path)+ self.tokenizer = Tokenizer.from_config(self.config)+ self.eos = list(self.config.eos_token_id_list)+ self.model = Model.from_config(self.config)+ self.cache = Cache(self.model, max_num_tokens=ctx, max_history=3)+ with Heartbeat("loading target model"):+ self.model.load(max_chunk_size=max_chunk_size, progressbar=False)+ from exllamav3.modules.hyperconnections import GS_STATS+ print("qserve: hc mixer sites by code source", dict(GS_STATS), flush=True)+ self.draft_model = self.draft_cache = None+ if draft_policy != "off":+ self.draft_model = Model.from_config(self.config, component="mtp")+ self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx, max_history=3)+ with Heartbeat("loading MTP drafter"):+ self.draft_model.load(progressbar=False)+ self.vision = None+ if vision:+ try:+ self.vision = Model.from_config(self.config, component="vision")+ with Heartbeat("loading vision tower"):+ self.vision.load(progressbar=False)+ except Exception as exc: # noqa: BLE001+ self.vision = None+ print(f"qserve: vision tower not loaded ({exc!r}); image input disabled", flush=True)+ self.supports_vision = self.vision is not None+ self._ngram_resident()+ self.generator = self.uninstall = None+ self.spec_on = self.draft_model is not None+ self.slot_store = None+ self.last_stats: dict[str, Any] = {}+ self._build(self.spec_on)++ def _ngram_resident(self) -> None:+ """t4: the kernel can swap part of the host-RAM n-gram table out while the weights load; every lookup on a swapped page then+ stalls on disk (transient 1-30 % slower first passes). Read it back in before READY. EXL3_NGRAM_POPULATE=0 = off."""+ if os.environ.get("EXL3_NGRAM_POPULATE", "1") == "0":+ return+ from exllamav3.modules.ngram_embedding import NGramEmbedding+ for mod in self.model.modules:+ for m in mod:+ if isinstance(m, NGramEmbedding):+ info = m.ensure_resident()+ sw = info["swap_before"]+ if info["populated"]:+ print(f"qserve: n-gram table was partly swapped out (process swap {sw / 2**20:.0f} MiB): read back "+ f"{info['populated'] / 2**30:.1f} GiB in {info['seconds']} s, swap now {info.get('swap_after', 0) / 2**20:.0f} MiB", flush=True)+ elif info.get("error"):+ print(f"qserve: WARNING n-gram table is partly swapped out (process swap {sw / 2**20:.0f} MiB) and could not be read back: {info['error']}", flush=True)++ def _build(self, spec: bool) -> None:+ """(Re)create the Generator. Drops the prompt cache: used for mode switches and cache_prompt=false."""+ if self.uninstall:+ self.uninstall()+ self.uninstall = None+ self.generator = None+ gc.collect() # the old Generator sits in reference cycles (jobs, hooks); free its buffers and n-gram index now+ self.torch.cuda.empty_cache()+ spec = spec and self.draft_model is not None+ kw = dict(model=self.model, cache=self.cache, tokenizer=self.tokenizer)+ if spec:+ kw.update(draft_model=self.draft_model, draft_cache=self.draft_cache, num_draft_tokens=self.ndt)+ self.generator = self.Generator(**kw)+ if spec and self.draft_policy == "mix":+ import spec_policy # tools/qwen/spec_policy.py: dynamic length + n-gram lookup, the shipped rule+ self.uninstall = spec_policy.install(self.generator, self.draft_model, self.model,+ 0.6, 0.3, self.ndt, (2, 3, 5), {})+ self.spec_on = spec+ if self.slot_store is not None:+ self.slot_store.generator = self.generator++ def warmup(self) -> None:+ # dense GEMM warm-up at load (EXL3_WARM_DENSE=0 = off): the first request at a new row-count class+ # no longer pays the rocBLAS solution screening (0.15-4 s per shape).+ from exllamav3.model.dense_warmup import warm_dense_gemm+ warm_dense_gemm([self.model, self.draft_model], max_rows=self.generator.max_chunk_size)+ ids = self.tokenizer.encode("<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",+ add_bos=False, encode_special_tokens=True)+ job = self.Job(input_ids=ids, max_new_tokens=24, sampler=self._sampler({"temperature": 0.0}),+ stop_conditions=self.eos)+ self.generator.enqueue(job)+ while self.generator.num_remaining_jobs():+ list(self.generator.iterate())+ self.torch.cuda.synchronize()++ def count_tokens(self, text: str) -> int:+ return int(self.tokenizer.encode(text, add_bos=False, encode_special_tokens=True).numel())++ def _sampler(self, s: dict[str, Any]):+ from exllamav3.generator.sampler import ArgmaxSampler, ComboSampler+ if s["temperature"] == 0 or s.get("top_k") == 1:+ return ArgmaxSampler()+ return ComboSampler(temperature=s["temperature"], top_k=s.get("top_k", 0), top_p=s.get("top_p", 1.0),+ min_p=s.get("min_p", 0.0))++ def _encode(self, prompt: str, image_urls: list[str]):+ embs = []+ for url in image_urls:+ embs.append(self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=load_image(url)))+ for emb in embs:+ prompt = prompt.replace(IMAGE_PAD, emb.text_alias, 1)+ kw = {"embeddings": embs} if embs else {}+ ids = self.tokenizer.encode(prompt, add_bos=False, encode_special_tokens=True, **kw)+ return ids, embs++ def _close_ids(self) -> tuple[int | None, list[int]]:+ """(id of the </think> token, ids of the text that closes a think block). Cached."""+ if not hasattr(self, "_think_close"):+ one = self.tokenizer.encode(THINK_CLOSE, add_bos=False, encode_special_tokens=True).flatten().tolist()+ seq = self.tokenizer.encode(THINK_CLOSE_TEXT, add_bos=False, encode_special_tokens=True).flatten().tolist()+ self._think_close = (one[0] if len(one) == 1 else None, seq)+ return self._think_close++ async def generate(self, prompt: str, **kw: Any) -> AsyncIterator[str]:+ """See _generate. Whatever way the call ends (error in a step, client gone, cancelled task), no job of it stays in the+ Generator: a leftover job would run inside the next request and deliver its tokens there."""+ try:+ async for piece in self._generate(prompt, **kw):+ yield piece+ finally:+ if self.generator is not None and self.generator.num_remaining_jobs():+ self.generator.clear_queue()++ async def _generate(self, prompt: str, *, max_tokens: int, sampling: dict[str, Any], stop: list[str],+ images: list[str] | None = None, speculative: bool = True, cache_prompt: bool = True,+ cancel: asyncio.Event | None = None, seed: int | None = None, reasoning_first: bool = False,+ thinking_budget: int | None = None, loop_guard: bool | None = None,+ loop_final: bool | None = None) -> AsyncIterator[str]:+ """Yield decoded text pieces. The caller serializes calls. Final stats land in self.last_stats.++ Final check (on with the guard, loop_final=False turns it off): when the turn ends normally and the visible text+ (thinking + answer) trips the release-gate loop rule, the thinking is cut back (final_cut), the close is forced and+ the answer is generated again, at most FINAL_TRIES times. Discarded tokens do not count against max_tokens.++ Loop guard (default on, EXL3_LOOP_GUARD=0 or loop_guard=False turns it off): when the think block loops (or+ thinking_budget tokens are used) the job is cancelled and restarted from prompt + the thinking kept so far ++ "\n</think>\n\n", so the answer proceeds. A loop inside the answer ends the turn (finish_reason stop).+ Nothing is changed while no loop is detected."""+ loop = asyncio.get_running_loop()+ self.last_stats = {}+ if cancel is not None and cancel.is_set():+ return # the client left while the request was queued: no rebuild, no prefill+ want_spec = bool(speculative) and self.draft_model is not None+ if want_spec != self.spec_on or not cache_prompt:+ await loop.run_in_executor(None, self._build, want_spec)+ ids, embs = await loop.run_in_executor(None, self._encode, prompt, images or [])+ ctx = getattr(self, "ctx", None)+ if ctx: # the chat handler counted a picture as one token; its embeddings take many+ room = ctx - int(ids.numel()) - 1+ if room < 1:+ raise BadRequest(f"prompt is {int(ids.numel())} tokens, the server context is {ctx}")+ max_tokens = min(max_tokens, room)+ if self.slot_store is not None:+ self.slot_store.note_prompt(prompt, ids)+ guard_on = loop_guard_default() if loop_guard is None else bool(loop_guard)+ budget = thinking_budget if reasoning_first else None+ close_id, close_seq = self._close_ids()+ mon = None+ if guard_on or budget:+ mon = LoopMonitor("think" if reasoning_first else "answer", close_id, budget, detect=guard_on)+ token_ids: list[int] = [] # everything streamed to the client, all segments+ fired: dict[str, Any] | None = None+ marks: list[tuple[int, int]] = [(0, 0)] # (tokens, characters) streamed after each event of this segment+ chars = 0+ spent = 0.0 # seconds of cancelled segments+ generated = 0 # tokens the model produced, including the discarded thinking tail+ discount = 0 # discarded tokens of final-check recoveries: not charged to max_tokens+ final_tries = 0+ final_on = guard_on and reasoning_first and close_id is not None and loop_final is not False+ vis = "" # the text the client holds (Retract applied)+ gmarks: list[tuple[int, int]] = [(0, 0)] # (len(token_ids), chars) after each event, all segments+ job_ids = ids++ def step():+ return list(self.generator.iterate())++ while True:+ job = self.Job(input_ids=job_ids, max_new_tokens=max(max_tokens - generated + discount, 1),+ sampler=self._sampler(sampling), stop_conditions=self.eos + list(stop),+ embeddings=embs or None, decode_special_tokens=True, seed=seed)+ self.generator.enqueue(job)+ seg: list[int] = []+ marks = [(0, 0)]+ base_chars = chars+ seg_t0 = time.perf_counter()+ hit = None+ redo = False+ while self.generator.num_remaining_jobs():+ if cancel is not None and cancel.is_set():+ self.generator.cancel(job)+ return+ for ev in await loop.run_in_executor(None, step):+ if ev.get("error"):+ raise RuntimeError(str(ev["error"]))+ t = ev.get("token_ids")+ toks = t.flatten().tolist() if t is not None and t.numel() else []+ token_ids += toks+ seg += toks+ generated += len(toks)+ if ev.get("text"):+ chars += len(ev["text"])+ vis += ev["text"]+ yield ev["text"]+ marks.append((len(seg), chars - base_chars))+ gmarks.append((len(token_ids), chars))+ if mon is not None and toks and not ev.get("eos"):+ hit = mon.feed(toks, ev.get("text") or "")+ if hit:+ break+ if ev.get("eos") and final_on and final_tries < FINAL_TRIES and text_loop(gate_text(vis)) \+ and (THINK_CLOSE_TAG in vis or ev.get("eos_reason") == "max_new_tokens"+ or generated - discount >= max_tokens):+ redo = True+ break+ if ev.get("eos"):+ self.last_stats = {k: v for k, v in ev.items() if k not in ("job", "token_ids", "text", "held")}+ self.last_stats["token_ids"] = token_ids+ if fired:+ self.last_stats.update(prompt_tokens=int(ids.numel()), new_tokens=generated,+ cached_tokens=min(int(self.last_stats.get("cached_tokens", 0)), int(ids.numel())),+ loop_guard=fired)+ if self.last_stats.get("time_generate") is not None:+ self.last_stats["time_generate"] += spent+ return+ if hit or redo:+ break+ if redo:+ cut_chars = final_cut(vis)+ final_tries += 1+ keep_tokens, keep_chars = max(m for m in gmarks if m[1] <= cut_chars)+ fired = {"phase": "think", "kind": "final", "cut": keep_tokens, "at": len(token_ids), "period": 0,+ "tokens_streamed": len(token_ids), "kept_tokens": keep_tokens, "tries": final_tries}+ print(f"qserve: loop guard final in think: gate rule holds on the answer, thinking cut to {keep_tokens} tokens "+ f"({keep_chars} chars of {len(vis)}), try {final_tries}", file=sys.stderr, flush=True)+ spent += time.perf_counter() - seg_t0+ yield Retract(len(vis) - keep_chars)+ vis, chars = vis[:keep_chars], keep_chars+ discount += len(token_ids) - keep_tokens+ del token_ids[keep_tokens:]+ token_ids += close_seq+ generated += len(close_seq)+ chars += len(THINK_CLOSE_TEXT)+ vis += THINK_CLOSE_TEXT+ yield THINK_CLOSE_TEXT+ gmarks[:] = [m for m in gmarks if m[0] <= keep_tokens and m[1] <= keep_chars]+ gmarks.append((len(token_ids), chars))+ extra = self.torch.tensor([token_ids], dtype=ids.dtype)+ job_ids = self.torch.cat([ids, extra.to(ids.device)], dim=-1)+ mon.start_phase("answer")+ continue+ if not hit:+ return+ self.generator.cancel(job)+ fired = dict(hit, tokens_streamed=len(token_ids))+ print(f"qserve: loop guard {hit['kind']} in {hit['phase']} at {hit['at']} tokens (period {hit['period']}, "+ f"keep {hit['cut']})", file=sys.stderr, flush=True)+ n_total = int(ids.numel())+ if hit["phase"] == "answer" or close_id is None:+ self.last_stats = {"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,+ "eos_reason": "loop_guard", "token_ids": token_ids, "loop_guard": fired}+ return+ # think block: keep the thinking up to the cut (on an event boundary), force the close, restart from there+ keep_tokens, keep_chars = max(m for m in marks if m[0] <= hit["cut"])+ spent += time.perf_counter() - seg_t0+ fired["kept_tokens"] = keep_tokens+ if chars - base_chars > keep_chars:+ yield Retract(chars - base_chars - keep_chars)+ chars = base_chars + keep_chars+ vis = vis[:chars]+ del token_ids[len(token_ids) - len(seg) + keep_tokens:]+ token_ids += close_seq+ generated += len(close_seq)+ chars += len(THINK_CLOSE_TEXT)+ vis += THINK_CLOSE_TEXT+ yield THINK_CLOSE_TEXT+ gmarks[:] = [m for m in gmarks if m[0] <= len(token_ids) - len(close_seq) and m[1] <= chars - len(THINK_CLOSE_TEXT)]+ gmarks.append((len(token_ids), chars))+ if generated - discount >= max_tokens:+ self.last_stats = {"prompt_tokens": n_total, "new_tokens": generated, "cached_tokens": 0,+ "eos_reason": "max_new_tokens", "token_ids": token_ids, "loop_guard": fired}+ return+ extra = self.torch.tensor([seg[:keep_tokens] + close_seq], dtype=ids.dtype)+ job_ids = self.torch.cat([ids, extra.to(ids.device)], dim=-1)+ mon.start_phase("answer")++ def spec_stats(self) -> dict[str, Any]:+ return {"speculative": self.spec_on, "draft_policy": self.draft_policy if self.spec_on else "off", "ndt": self.ndt}+++# ---------------------------------------------------------------------------- HTTP+++def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Any] | None = None,+ default_max_tokens: int = 32768) -> web.Application:+ """HTTP layer around a resident engine (also accepts a fake engine in tests)."""+ defaults = defaults or load_defaults("/nonexistent")+ queue: asyncio.Queue = asyncio.Queue()+ lock = asyncio.Lock()+ app = web.Application(client_max_size=64 * 1024**2)+ app.update(engine=engine, model_id=model_id, template=template, defaults=defaults)++ def err(status: int, message: str) -> web.Response:+ return web.json_response({"error": {"message": message, "type": "invalid_request_error", "code": status}},+ status=status)++ async def models(_: web.Request) -> web.Response:+ return web.json_response({"object": "list", "data": [+ {"id": model_id, "object": "model", "created": 0, "owned_by": "yamz",+ "max_context": getattr(engine, "ctx", None)}]})++ async def health(_: web.Request) -> web.Response:+ return web.json_response({"status": "ok", "model": model_id, "vision": bool(engine.supports_vision),+ **(engine.spec_stats() if hasattr(engine, "spec_stats") else {})})++ async def worker() -> None:+ while True:+ job, out = await queue.get()+ store = getattr(engine, "slot_store", None)+ try:+ async with lock:+ if store is not None:+ store.busy = True+ async for delta in engine.generate(+ job["prompt"], max_tokens=job["max_tokens"], sampling=job["sampling"],+ stop=job["stop"], images=job["images"], speculative=job["speculative"],+ cache_prompt=job["cache_prompt"], cancel=job["cancel"],+ seed=job.get("seed"), reasoning_first=job.get("reasoning_first", False),+ thinking_budget=job.get("thinking_budget"), loop_guard=job.get("loop_guard"), loop_final=job.get("loop_final")):+ out.put_nowait(delta)+ out.put_nowait(("done", dict(getattr(engine, "last_stats", None) or {})))+ except Exception as exc: # noqa: BLE001+ out.put_nowait(exc)+ finally:+ if store is not None:+ store.busy = False+ queue.task_done()++ async def start(_: web.Application) -> None:+ app["worker_task"] = asyncio.create_task(worker())++ async def close(app_: web.Application) -> None:+ app_["worker_task"].cancel()++ def prepare(body: Any) -> dict[str, Any]:+ """Validate a request and build the engine job. Raises BadRequest."""+ if not isinstance(body, dict):+ raise BadRequest("body must be a JSON object")+ if body.get("model", model_id) != model_id:+ raise BadRequest(f"unknown model; expected {model_id}")+ if not isinstance(body.get("messages"), list) or not body["messages"]:+ raise BadRequest("messages must be a non-empty array")+ if "stream" in body and not isinstance(body["stream"], bool):+ raise BadRequest("stream must be boolean")+ if body.get("tools") is not None and not isinstance(body["tools"], list):+ raise BadRequest("tools must be an array")+ messages = normalize_messages(body["messages"])+ kwargs = resolve_template_kwargs(body, defaults)+ try:+ prompt = render_prompt(template, messages, body.get("tools"), **kwargs)+ except (ValueError, TypeError, KeyError, AttributeError, jinja2.TemplateError) as exc:+ raise BadRequest(f"chat template: {exc}") from exc+ images = extract_images(messages)+ if images and not engine.supports_vision:+ raise BadRequest("this server runs without the vision tower (--no-vision)")+ if len(images) != prompt.count(IMAGE_PAD):+ raise BadRequest("image parts and image placeholders do not match (images are allowed in user messages only)")+ stops = body.get("stop") or []+ stops = [stops] if isinstance(stops, str) else list(stops)+ if not all(isinstance(s, str) for s in stops):+ raise BadRequest("stop must be a string or a list of strings")+ prompt_tokens = engine.count_tokens(prompt)+ ctx = getattr(engine, "ctx", None)+ max_tokens = body.get("max_completion_tokens")+ if max_tokens is None:+ max_tokens = body.get("max_tokens")+ if max_tokens is not None and (not isinstance(max_tokens, int) or isinstance(max_tokens, bool) or max_tokens < 1):+ raise BadRequest("max_tokens must be a positive integer")+ room = (ctx - prompt_tokens - 1) if ctx else default_max_tokens+ if room < 1:+ raise BadRequest(f"prompt is {prompt_tokens} tokens, the server context is {ctx}")+ max_tokens = min(max_tokens or default_max_tokens, room)+ seed = body.get("seed")+ if seed is not None and (not isinstance(seed, int) or isinstance(seed, bool)):+ raise BadRequest("seed must be an integer")+ budget = body.get("thinking_budget")+ if budget is not None and (not isinstance(budget, int) or isinstance(budget, bool) or budget < 1):+ raise BadRequest("thinking_budget must be a positive integer")+ if body.get("loop_guard") is not None and not isinstance(body["loop_guard"], bool):+ raise BadRequest("loop_guard must be boolean")+ if body.get("loop_final") is not None and not isinstance(body["loop_final"], bool):+ raise BadRequest("loop_final must be boolean")+ return {"seed": seed, "thinking_budget": budget, "loop_guard": body.get("loop_guard"), "loop_final": body.get("loop_final"), "prompt": prompt, "prompt_tokens": prompt_tokens, "max_tokens": max_tokens,+ "sampling": sampling_from(body, defaults), "stop": stops, "images": images,+ "speculative": body.get("speculative", True) is not False,+ "cache_prompt": body.get("cache_prompt", True) is not False,+ "reasoning_first": prompt.rstrip().endswith("<think>"), "tools": body.get("tools"),+ "return_token_ids": bool(body.get("return_token_ids")), "cancel": asyncio.Event()}++ async def completions(request: web.Request) -> web.StreamResponse:+ try:+ body = await request.json()+ job = prepare(body)+ except json.JSONDecodeError as exc:+ return err(400, f"invalid JSON: {exc}")+ except BadRequest as exc:+ return err(400, str(exc))+ request_id, created = f"chatcmpl-{uuid.uuid4().hex}", int(time.time())+ base = {"id": request_id, "object": "chat.completion.chunk", "created": created, "model": model_id}++ def event(delta: dict[str, Any], finish: str | None = None) -> dict[str, Any]:+ return base | {"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}++ out: asyncio.Queue = asyncio.Queue()+ await queue.put((job, out))++ def finish_and_stats(stats: dict[str, Any], text: str, has_calls: bool):+ n_new = int(stats.get("new_tokens") or engine.count_tokens(text))+ prompt_tokens = int(stats.get("prompt_tokens") or job["prompt_tokens"])+ cache_n = int(stats.get("cached_tokens", 0))+ pre, gen = stats.get("time_prefill") or 0.0, stats.get("time_generate") or 0.0+ if has_calls:+ reason = "tool_calls"+ elif stats.get("eos_reason") in ("max_new_tokens",):+ reason = "length"+ else:+ reason = "stop"+ usage = {"prompt_tokens": prompt_tokens, "completion_tokens": n_new,+ "total_tokens": prompt_tokens + n_new, "prompt_tokens_details": {"cached_tokens": cache_n}}+ timings = {"cache_n": cache_n, "prompt_n": max(prompt_tokens - cache_n, 0), "prompt_ms": pre * 1000,+ "predicted_n": n_new, "predicted_ms": gen * 1000,+ "prompt_per_second": (prompt_tokens - cache_n) / pre if pre else 0.0,+ "predicted_per_second": n_new / gen if gen else 0.0,+ "speculative": bool(getattr(engine, "spec_on", False))}+ if stats.get("loop_guard"):+ timings["loop_guard"] = stats["loop_guard"]+ if "accepted_draft_tokens" in stats:+ timings["accepted_draft_tokens"] = int(stats["accepted_draft_tokens"])+ timings["rejected_draft_tokens"] = int(stats["rejected_draft_tokens"])+ return reason, usage, timings++ async def pieces() -> AsyncIterator[str | dict]:+ while True:+ # a non-streaming client that hung up is only noticed here (nothing is written until the end)+ tr = request.transport+ if tr is None or tr.is_closing():+ job["cancel"].set()+ raise ConnectionResetError("client left")+ try:+ item = await asyncio.wait_for(out.get(), 1.0)+ except asyncio.TimeoutError:+ continue+ if isinstance(item, Exception):+ raise item+ if isinstance(item, tuple):+ yield item[1]+ return+ yield item++ sp = Splitter(job["reasoning_first"])+ if body.get("stream", False):+ response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})+ await response.prepare(request)+ try:+ await response.write(sse(event({"role": "assistant", "content": ""})))+ stats, full = {}, ""+ async for item in pieces():+ if isinstance(item, dict):+ stats = item+ continue+ if isinstance(item, Retract): # loop guard restart: this client already received the text+ if sp.mode != "reasoning":+ # final check after the close: the discarded answer is gone for the model, and the restart text+ # begins with a new close tag. A fresh Splitter in reasoning mode swallows that tag and also drops+ # whatever the discarded answer left behind (an open or finished tool call, a held partial tag).+ sp = Splitter(True)+ continue+ full += item+ for kind, piece in sp.feed(item):+ key = "reasoning_content" if kind == "reasoning" else "content"+ await response.write(sse(event({key: piece})))+ for kind, piece in sp.finish():+ key = "reasoning_content" if kind == "reasoning" else "content"+ await response.write(sse(event({key: piece})))+ calls = parse_tool_calls(sp.tool_text, job["tools"])+ if calls:+ await response.write(sse(event({"tool_calls": [dict(c, index=i) for i, c in enumerate(calls)]})))+ reason, usage, timings = finish_and_stats(stats, full, bool(calls))+ final = event({}, reason) | {"usage": usage, "timings": timings}+ if job["return_token_ids"]:+ final["token_ids"] = stats.get("token_ids", [])+ await response.write(sse(final))+ await response.write(b"data: [DONE]\n\n")+ await response.write_eof()+ except ConnectionResetError: # client left: stop the job, no traceback+ job["cancel"].set()+ except asyncio.CancelledError:+ job["cancel"].set()+ raise+ except Exception as exc: # noqa: BLE001+ job["cancel"].set()+ try:+ await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))+ await response.write_eof()+ except ConnectionError:+ pass+ return response++ try:+ stats, full = {}, ""+ async for item in pieces():+ if isinstance(item, dict):+ stats = item+ elif isinstance(item, Retract):+ full = full[:len(full) - int(item)]+ else:+ full += item+ except ConnectionResetError:+ return web.Response(status=499) # client left; the job is cancelled+ except BadRequest as exc: # e.g. an image that does not decode (loaded by the worker)+ return err(400, str(exc))+ except Exception as exc: # noqa: BLE001+ return web.json_response({"error": {"message": f"{type(exc).__name__}: {exc}", "type": "server_error"}},+ status=500)+ text, _ = stop_text(full, job["stop"])+ message = split_completion(text, job["reasoning_first"], job["tools"])+ reason, usage, timings = finish_and_stats(stats, text, "tool_calls" in message)+ payload = {"id": request_id, "object": "chat.completion", "created": created, "model": model_id,+ "choices": [{"index": 0, "message": message, "finish_reason": reason}],+ "usage": usage, "timings": timings}+ if job["return_token_ids"]:+ payload["token_ids"] = stats.get("token_ids", [])+ return web.json_response(payload)++ async def apply_template(request: web.Request) -> web.Response:+ try:+ body = await request.json()+ if not isinstance(body, dict) or not isinstance(body.get("messages"), list) or not body["messages"]:+ raise BadRequest("messages must be a non-empty array")+ prompt = render_prompt(template, normalize_messages(body["messages"]), body.get("tools"),+ **resolve_template_kwargs(body, defaults))+ except json.JSONDecodeError as exc:+ return err(400, f"invalid JSON: {exc}")+ except (BadRequest, ValueError, TypeError, KeyError, AttributeError, jinja2.TemplateError) as exc:+ return err(400, str(exc))+ return web.json_response({"prompt": prompt})++ async def completion(request: web.Request) -> web.Response:+ """Minimal llama.cpp POST /completion: prompt used verbatim (no template), same queue and generator."""+ try:+ body = await request.json()+ if not isinstance(body, dict):+ raise BadRequest("body must be a JSON object")+ prompt = body.get("prompt")+ if not isinstance(prompt, str) or not prompt:+ raise BadRequest("prompt must be a non-empty string")+ n_predict = body.get("n_predict", 128)+ if n_predict is not None and (not isinstance(n_predict, int) or isinstance(n_predict, bool)):+ raise BadRequest("n_predict must be an integer")+ n_predict = n_predict if n_predict and n_predict > 0 else 128+ n_predict = min(n_predict, 8192)+ stops = body.get("stop") or []+ stops = [stops] if isinstance(stops, str) else stops+ if not isinstance(stops, list) or not all(isinstance(x, str) for x in stops):+ raise BadRequest("stop must be a string or a list of strings")+ ctx = getattr(engine, "ctx", None)+ if ctx:+ room = ctx - engine.count_tokens(prompt) - 1+ if room < 1:+ raise BadRequest(f"prompt is longer than the server context ({ctx})")+ n_predict = min(n_predict, room)+ job = {"prompt": prompt, "max_tokens": n_predict,+ "sampling": sampling_from({k: body.get(k) for k in ("temperature", "top_p", "top_k", "min_p")}, defaults),+ "stop": stops, "images": [], "speculative": True,+ "seed": body.get("seed") if isinstance(body.get("seed"), int) and not isinstance(body.get("seed"), bool) else None,+ "cache_prompt": body.get("cache_prompt", True) is not False, "cancel": asyncio.Event()}+ except json.JSONDecodeError as exc:+ return err(400, f"invalid JSON: {exc}")+ except (BadRequest, TypeError, ValueError) as exc:+ return err(400, str(exc))+ out: asyncio.Queue = asyncio.Queue()+ await queue.put((job, out))+ text, stats = "", {}+ while True:+ item = await out.get()+ if isinstance(item, Exception):+ return web.json_response({"error": {"message": f"{type(item).__name__}: {item}", "type": "server_error"}},+ status=500)+ if isinstance(item, tuple):+ stats = item[1]+ break+ text += item+ text, stopped = stop_text(text, job["stop"])+ return web.json_response({+ "id": f"cmpl-{uuid.uuid4().hex}", "object": "completion", "created": int(time.time()), "model": model_id,+ "content": text, "tokens_cached": int(stats.get("cached_tokens", 0)),+ "tokens_predicted": int(stats.get("new_tokens", 0)), "cache_prompt": job["cache_prompt"],+ "stop": True, "stopped_eos": stats.get("eos_reason") == "stop_token",+ "stopped_limit": stats.get("eos_reason") == "max_new_tokens", "stopped_word": stopped,+ "timings": {"prompt_n": int(stats.get("prompt_tokens", 0)) - int(stats.get("cached_tokens", 0)),+ "predicted_n": int(stats.get("new_tokens", 0))}})++ async def v1_completions(request: web.Request) -> web.StreamResponse:+ """OpenAI POST /v1/completions: the prompt is used verbatim (no chat template), one prompt, one choice."""+ try:+ body = await request.json()+ if not isinstance(body, dict):+ raise BadRequest("body must be a JSON object")+ if body.get("model", model_id) != model_id:+ raise BadRequest(f"unknown model; expected {model_id}")+ prompt = body.get("prompt")+ if isinstance(prompt, list) and len(prompt) == 1:+ prompt = prompt[0]+ if not isinstance(prompt, str) or not prompt:+ raise BadRequest("prompt must be a non-empty string (one prompt per request)")+ if body.get("n") not in (None, 1) or body.get("echo") or body.get("best_of") not in (None, 1):+ raise BadRequest("n, best_of and echo are not supported")+ if "stream" in body and not isinstance(body["stream"], bool):+ raise BadRequest("stream must be boolean")+ max_tokens = body.get("max_tokens")+ if max_tokens is None:+ max_tokens = 16+ if not isinstance(max_tokens, int) or isinstance(max_tokens, bool) or max_tokens < 1:+ raise BadRequest("max_tokens must be a positive integer")+ stops = body.get("stop") or []+ stops = [stops] if isinstance(stops, str) else stops+ if not isinstance(stops, list) or not all(isinstance(x, str) for x in stops):+ raise BadRequest("stop must be a string or a list of strings")+ seed = body.get("seed")+ if seed is not None and (not isinstance(seed, int) or isinstance(seed, bool)):+ raise BadRequest("seed must be an integer")+ if body.get("loop_guard") is not None and not isinstance(body["loop_guard"], bool):+ raise BadRequest("loop_guard must be boolean")+ prompt_tokens = engine.count_tokens(prompt)+ ctx = getattr(engine, "ctx", None)+ if ctx:+ room = ctx - prompt_tokens - 1+ if room < 1:+ raise BadRequest(f"prompt is {prompt_tokens} tokens, the server context is {ctx}")+ max_tokens = min(max_tokens, room)+ job = {"prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": True, "seed": seed,+ "sampling": sampling_from(body, defaults), "cache_prompt": body.get("cache_prompt", True) is not False,+ "loop_guard": body.get("loop_guard"), "cancel": asyncio.Event()}+ except json.JSONDecodeError as exc:+ return err(400, f"invalid JSON: {exc}")+ except BadRequest as exc:+ return err(400, str(exc))+ request_id, created = f"cmpl-{uuid.uuid4().hex}", int(time.time())++ def chunk(text: str, finish: str | None) -> dict[str, Any]:+ return {"id": request_id, "object": "text_completion", "created": created, "model": model_id,+ "choices": [{"text": text, "index": 0, "logprobs": None, "finish_reason": finish}]}++ def reason_usage(stats: dict[str, Any], text: str):+ n_new = int(stats.get("new_tokens") or engine.count_tokens(text))+ n_prompt = int(stats.get("prompt_tokens") or prompt_tokens)+ reason = "length" if stats.get("eos_reason") == "max_new_tokens" else "stop"+ return reason, {"prompt_tokens": n_prompt, "completion_tokens": n_new, "total_tokens": n_prompt + n_new}++ out: asyncio.Queue = asyncio.Queue()+ await queue.put((job, out))++ async def pieces() -> AsyncIterator[str | dict]:+ while True:+ tr = request.transport+ if tr is None or tr.is_closing():+ job["cancel"].set()+ raise ConnectionResetError("client left")+ try:+ item = await asyncio.wait_for(out.get(), 1.0)+ except asyncio.TimeoutError:+ continue+ if isinstance(item, Exception):+ raise item+ if isinstance(item, tuple):+ yield item[1]+ return+ yield item++ if body.get("stream", False):+ response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})+ await response.prepare(request)+ try:+ stats, full = {}, ""+ async for item in pieces():+ if isinstance(item, dict):+ stats = item+ elif not isinstance(item, Retract):+ full += item+ await response.write(sse(chunk(item, None)))+ reason, usage = reason_usage(stats, full)+ await response.write(sse(chunk("", reason) | {"usage": usage}))+ await response.write(b"data: [DONE]\n\n")+ await response.write_eof()+ except ConnectionResetError:+ job["cancel"].set()+ except asyncio.CancelledError:+ job["cancel"].set()+ raise+ except Exception as exc: # noqa: BLE001+ job["cancel"].set()+ try:+ await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))+ await response.write_eof()+ except ConnectionError:+ pass+ return response++ try:+ stats, full = {}, ""+ async for item in pieces():+ if isinstance(item, dict):+ stats = item+ elif isinstance(item, Retract):+ full = full[:len(full) - int(item)]+ else:+ full += item+ except ConnectionResetError:+ return web.Response(status=499)+ except BadRequest as exc:+ return err(400, str(exc))+ except Exception as exc: # noqa: BLE001+ return web.json_response({"error": {"message": f"{type(exc).__name__}: {exc}", "type": "server_error"}}, status=500)+ text, _ = stop_text(full, job["stop"])+ reason, usage = reason_usage(stats, text)+ return web.json_response(chunk(text, reason) | {"object": "text_completion", "usage": usage})++ async def slots(_: web.Request) -> web.Response:+ return web.json_response(engine.slot_store.slots())++ async def slot_action(request: web.Request) -> web.Response:+ """llama.cpp POST /slots/0?action=save|restore|erase (same SlotStore as the MiMo server)."""+ store = engine.slot_store+ if request.match_info["id"] != "0":+ return err(400, "only slot 0 exists")+ action = request.query.get("action")+ try:+ body = await request.json() if request.can_read_body else {}+ async with lock:+ if action == "erase":+ return web.json_response(store.erase())+ if action not in ("save", "restore"):+ return err(400, "action must be save, restore or erase")+ result = await asyncio.get_running_loop().run_in_executor(None, getattr(store, action), body.get("filename", ""))+ return web.json_response(result)+ except (ValueError, FileNotFoundError, RuntimeError, json.JSONDecodeError) as exc:+ return err(400, f"{type(exc).__name__}: {exc}")++ app.router.add_get("/v1/models", models)+ app.router.add_get("/health", health)+ app.router.add_post("/v1/chat/completions", completions)+ app.router.add_post("/apply-template", apply_template)+ app.router.add_post("/completion", completion)+ app.router.add_post("/v1/completions", v1_completions)+ if getattr(engine, "slot_store", None) is not None:+ app.router.add_get("/slots", slots)+ app.router.add_post("/slots/{id}", slot_action)+ app.on_startup.append(start)+ app.on_cleanup.append(close)+ return app+++# ---------------------------------------------------------------------------- main+++def main() -> None:+ parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--host", default="127.0.0.1")+ parser.add_argument("--port", type=int, default=8000)+ parser.add_argument("--model", default=DEFAULT_MODEL, help="pack directory")+ parser.add_argument("--model-id", default=DEFAULT_MODEL_ID, help="id shown by /v1/models and expected in requests")+ parser.add_argument("--ctx", "-c", type=int, default=65536, help="KV cache size in tokens (default 65536)")+ parser.add_argument("--ndt", type=int, default=3, help="max draft tokens per round (default 3)")+ parser.add_argument("--draft-policy", choices=("mix", "mtp", "off"), default="mix",+ help="mix = shipped rule (MTP + n-gram lookup, lossless), mtp = fixed MTP chain, off = plain decode")+ parser.add_argument("--no-vision", action="store_true", help="do not load the vision tower (saves memory)")+ parser.add_argument("--no-uncensor", action="store_true", help="ignore a bundled uncensor_spec.json in the model directory (same as EXL3_ABLIT_RUNTIME=off)")+ parser.add_argument("--default-temperature", type=float, default=None, help="when a request omits it (default: generation_config.json)")+ parser.add_argument("--default-top-p", type=float, default=None)+ parser.add_argument("--default-top-k", type=int, default=None)+ parser.add_argument("--default-min-p", type=float, default=None)+ parser.add_argument("--default-reasoning-effort", choices=("low", "medium", "xhigh"), default=None,+ help="thinking effort when a request omits it (template default: xhigh)")+ parser.add_argument("--no-thinking", action="store_true", help="thinking off unless a request turns it on")+ parser.add_argument("--default-max-tokens", type=int, default=32768, help="when a request omits max_tokens")+ parser.add_argument("--slot-save-path", default="~/cache/llama-slots")+ args = parser.parse_args()++ if args.no_uncensor:+ os.environ["EXL3_ABLIT_RUNTIME"] = "off"+ model_dir = str(Path(args.model).expanduser())+ template = (Path(model_dir) / "chat_template.jinja").read_text(encoding="utf-8")+ defaults = load_defaults(model_dir, args)+ t0 = time.time()+ print(f"qserve: starting, model={model_dir} ctx={args.ctx} draft_policy={args.draft_policy} "+ f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)+ engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision)+ env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}+ print(f"qserve: effective env {env}", flush=True)+ from exllamav3.generator.slot_store import SlotStore+ engine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],+ args.slot_save_path, args.model_id)+ with Heartbeat("warm-up (first decode steps)"):+ engine.warmup()+ app = create_app(engine, args.model_id, template, defaults, args.default_max_tokens)++ async def serve() -> None:+ runner = web.AppRunner(app)+ await runner.setup()+ await web.TCPSite(runner, args.host, args.port).start()+ print(f"qserve: READY on http://{args.host}:{args.port} model={args.model_id} ctx={args.ctx} "+ f"speculative={engine.spec_on} vision={engine.supports_vision} (start-up {time.time() - t0:.0f} s)",+ flush=True)+ await asyncio.Event().wait()++ try:+ asyncio.run(serve())+ except KeyboardInterrupt:+ pass+++if __name__ == "__main__":+ main()diff --git a/tools/qwen/serve_check.py b/tools/qwen/serve_check.pynew file mode 100644index 0000000..656fb14--- /dev/null+++ b/tools/qwen/serve_check.py@@ -0,0 +1,290 @@+#!/usr/bin/env python3+"""HTTP acceptance check for tools/qwen/serve.py (run against a live server; no engine import).++usage: serve_check.py URL OUT_DIR [--steps functional,speed,warmcold] [--ntok 160] [--nper 4] [--passes 2]+Writes OUT_DIR/check.json and prints one line per check. Everything is greedy (temperature 0) unless noted.+"""+from __future__ import annotations++import argparse+import base64+import glob+import io+import json+import os+import statistics+import sys+import time+import urllib.error+import urllib.request+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "tools" / "qwen")), sys.path.insert(0, str(ROOT / "tools" / "glm"))++ap = argparse.ArgumentParser()+ap.add_argument("url"), ap.add_argument("out")+ap.add_argument("--steps", default="functional,speed,warmcold")+ap.add_argument("--ntok", type=int, default=160), ap.add_argument("--nper", type=int, default=4)+ap.add_argument("--passes", type=int, default=2), ap.add_argument("--model", default="Qwen3.8-Flash-Yamz")+a = ap.parse_args()+os.makedirs(a.out, exist_ok=True)+R: dict = {}+++def post(payload: dict, stream: bool = False, timeout: int = 900):+ req = urllib.request.Request(a.url + "/v1/chat/completions", json.dumps({"model": a.model} | payload).encode(),+ {"Content-Type": "application/json"})+ t0 = time.perf_counter()+ if not stream:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return json.loads(r.read()), time.perf_counter() - t0+ chunks, ttft = [], None+ with urllib.request.urlopen(req, timeout=timeout) as r:+ for line in r:+ line = line.decode().strip()+ if not line.startswith("data: ") or line.endswith("[DONE]"):+ continue+ ev = json.loads(line[6:])+ chunks.append(ev)+ d = ev["choices"][0]["delta"] if ev.get("choices") else {}+ if ttft is None and (d.get("content") or d.get("reasoning_content") or d.get("tool_calls")):+ ttft = time.perf_counter() - t0+ return chunks, ttft+++def rec(name, ok, **kw):+ R.setdefault("checks", []).append({"name": name, "ok": bool(ok), **kw})+ print(("OK " if ok else "BAD ") + name, json.dumps(kw, ensure_ascii=False)[:400], flush=True)+ json.dump(R, open(a.out + "/check.json", "w"), indent=1, ensure_ascii=False)+++def msg_of(body):+ return body["choices"][0]["message"]+++BAD = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<tool_call>"]+++def functional():+ chat = [("capital", "What is the capital of France? Answer in one sentence.", "paris"),+ ("fib", "Write a Python function that returns the n-th Fibonacci number.", "def "),+ ("vaccin", "Explique en deux phrases comment fonctionne un vaccin.", "immun"),+ ("tips", "List three tips for staying focused while working from home.", "1"),+ ("math", "What is 17 times 23? Give only the number.", "391")]+ for nm, p, kw in chat:+ b, dt = post({"messages": [{"role": "user", "content": p}], "enable_thinking": False, "max_tokens": 200,+ "temperature": 0})+ m = msg_of(b)+ rec("chat_nothink_" + nm, kw in m["content"].lower() and "reasoning_content" not in m+ and not any(x in m["content"] for x in BAD) and b["choices"][0]["finish_reason"] in ("stop", "length"),+ text=m["content"][:160], finish=b["choices"][0]["finish_reason"], usage=b["usage"], secs=round(dt, 2))+ # thinking on: reasoning split+ b, dt = post({"messages": [{"role": "user", "content": "A farmer has 17 sheep and all but 9 run away. How many are left? Think briefly."}],+ "reasoning_effort": "low", "max_tokens": 3000, "temperature": 0})+ m = msg_of(b)+ rec("chat_think_on", bool(m.get("reasoning_content")) and "9" in m["content"] and b["choices"][0]["finish_reason"] == "stop"+ and "</think>" not in m["content"], reasoning_head=m.get("reasoning_content", "")[:100], content=m["content"][:200],+ finish=b["choices"][0]["finish_reason"], tokens=b["usage"]["completion_tokens"])+ # thinking cut by max_tokens -> finish_reason length, content empty+ b, _ = post({"messages": [{"role": "user", "content": "Prove that the square root of 2 is irrational."}], "max_tokens": 24, "temperature": 0})+ rec("think_cut_is_length", b["choices"][0]["finish_reason"] == "length" and b["usage"]["completion_tokens"] == 24,+ finish=b["choices"][0]["finish_reason"], completion_tokens=b["usage"]["completion_tokens"],+ has_reasoning=bool(msg_of(b).get("reasoning_content")))+ # tool round trip+ tools = [{"type": "function", "function": {"name": "get_weather", "description": "Get the current weather for a city",+ "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}}, "required": ["city"]}}}]+ msgs = [{"role": "user", "content": "What is the weather in Paris right now? Use the tool."}]+ b, _ = post({"messages": msgs, "tools": tools, "enable_thinking": False, "max_tokens": 200, "temperature": 0})+ m = msg_of(b)+ calls = m.get("tool_calls") or []+ args_ok = bool(calls) and "paris" in json.loads(calls[0]["function"]["arguments"]).get("city", "").lower()+ rec("tool_call", args_ok and b["choices"][0]["finish_reason"] == "tool_calls", calls=calls[:1], content=m["content"][:80])+ if calls:+ msgs2 = msgs + [m, {"role": "tool", "tool_call_id": calls[0]["id"], "content": "Sunny, 21 degrees Celsius."}]+ b, _ = post({"messages": msgs2, "tools": tools, "enable_thinking": False, "max_tokens": 200, "temperature": 0})+ t = msg_of(b)["content"]+ rec("tool_round_trip_answer", "21" in t and b["choices"][0]["finish_reason"] == "stop", text=t[:200])+ # streamed request+ ch, ttft = post({"messages": [{"role": "user", "content": "Write two sentences about the sea."}], "stream": True,+ "enable_thinking": False, "max_tokens": 120, "temperature": 0}, stream=True)+ text = "".join(c["choices"][0]["delta"].get("content", "") for c in ch if c.get("choices"))+ last = ch[-1]+ b, _ = post({"messages": [{"role": "user", "content": "Write two sentences about the sea."}],+ "enable_thinking": False, "max_tokens": 120, "temperature": 0})+ rec("stream", len(ch) > 5 and last["choices"][0]["finish_reason"] in ("stop", "length") and "usage" in last+ and text == msg_of(b)["content"], chunks=len(ch), ttft_s=round(ttft or 0, 3), usage=last.get("usage"),+ same_as_non_stream=text == msg_of(b)["content"])+ # image+ from PIL import Image, ImageDraw+ img = Image.new("RGB", (448, 448), (20, 40, 200))+ ImageDraw.Draw(img).rectangle([120, 120, 330, 330], fill=(230, 20, 20))+ buf = io.BytesIO(); img.save(buf, "PNG")+ uri = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()+ b, _ = post({"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": uri}},+ {"type": "text", "text": "What color is the square in the middle of the picture, and what color is the background? Answer briefly."}]}],+ "enable_thinking": False, "max_tokens": 80, "temperature": 0})+ t = msg_of(b)["content"].lower()+ rec("image", "red" in t and "blue" in t, text=t[:200], usage=b["usage"])+ # 3-turn conversation, streamed: re-prefilled tokens and TTFT per turn+ import random+ random.seed(3)+ pool = "".join(open(f).read() for f in sorted(glob.glob(str(ROOT / "exllamav3" / "generator" / "*.py")))[:6])+ system = "You are a code reviewer. Reference material:\n" + pool[:9000]+ convo = [{"role": "system", "content": system}]+ rows = []+ for q in ("Summarize what the Generator class does in two sentences.",+ "Which file holds the page table, and what is a page?", "Now give me one risk in the design."):+ convo.append({"role": "user", "content": q})+ ch, ttft = post({"messages": convo, "stream": True, "enable_thinking": False, "max_tokens": 100, "temperature": 0}, stream=True)+ usage = ch[-1].get("usage", {}); tm = ch[-1].get("timings", {})+ reply = "".join(c["choices"][0]["delta"].get("content", "") for c in ch if c.get("choices"))+ convo.append({"role": "assistant", "content": reply})+ rows.append({"prompt_tokens": usage.get("prompt_tokens"), "cached": usage["prompt_tokens_details"]["cached_tokens"],+ "reprefilled": tm.get("prompt_n"), "ttft_s": round(ttft or 0, 3), "prefill_ms": round(tm.get("prompt_ms", 0))})+ rec("three_turn", rows[1]["reprefilled"] < rows[1]["prompt_tokens"] * 0.5 and rows[2]["reprefilled"] < rows[2]["prompt_tokens"] * 0.5,+ turns=rows)+++def classes():+ from prompts10 import PROMPTS+ from spec_prompts import EXTRA+ out = []+ for k in ("chat", "prose", "code"):+ out += [(k, i, p) for i, p in enumerate(PROMPTS[k][:a.nper])]+ for k in ("multi", "copy"):+ out += [(k, i, p) for i, p in enumerate(EXTRA[k][:a.nper])]+ return out+++def gen(prompt, spec, ntok=None, **kw):+ b, _ = post({"messages": [{"role": "user", "content": prompt}], "enable_thinking": False, "max_tokens": ntok or a.ntok,+ "temperature": 0, "speculative": spec, "return_token_ids": True} | kw)+ return b+++def speed():+ ps = classes()+ gen("Hello", True, 24); gen("Hello", False, 24)+ res = {"plain": {}, "spec": {}}+ for ps_i in range(a.passes):+ order = ("plain", "spec") if ps_i % 2 == 0 else ("spec", "plain")+ for arm in order:+ gen("Hello", arm == "spec", 16) # settle after the generator rebuild+ for k, i, p in ps:+ b = gen(p, arm == "spec")+ res[arm].setdefault((k, i), []).append({"tps": b["timings"]["predicted_per_second"], "toks": b["token_ids"],+ "n": b["usage"]["completion_tokens"], "acc": b["timings"].get("accepted_draft_tokens")})+ rows, div = {}, []+ for (k, i, p) in ps:+ ref = res["plain"][(k, i)][0]["toks"]+ allt = [r["toks"] for arm in res for r in res[arm][(k, i)]]+ ident = all(t == ref for t in allt)+ if not ident:+ for t in allt:+ if t != ref:+ div.append({"cls": k, "idx": i, "first_div": next((j for j, (u, v) in enumerate(zip(ref, t)) if u != v), min(len(ref), len(t)))})+ break+ rows.setdefault(k, []).append({"plain": statistics.mean(r["tps"] for r in res["plain"][(k, i)]),+ "spec": statistics.mean(r["tps"] for r in res["spec"][(k, i)]), "ident": ident})+ table = {}+ for k, v in rows.items():+ pm, sm = statistics.mean(r["plain"] for r in v), statistics.mean(r["spec"] for r in v)+ table[k] = {"n": len(v), "plain_tps": round(pm, 1), "spec_tps": round(sm, 1), "gain_pct": round(100 * (sm / pm - 1), 1),+ "identical": f"{sum(r['ident'] for r in v)}/{len(v)}"}+ rec("speed_plain_vs_spec", not div, passes=a.passes, ntok=a.ntok, table=table, divergences=div)+++def warmcold():+ pool = "".join(open(f).read() for f in sorted(glob.glob(str(ROOT / "exllamav3" / "**" / "*.py"), recursive=True))[:40])+ qa = [("Explain what the first function in the material does.", "Now rewrite it in a simpler way."),+ ("List the classes you see in the material.", "Which one is the most complex and why?"),+ ("What is a recurrent state in this code?", "How is it checkpointed?"),+ ("Describe the cache design in three sentences.", "What could go wrong with it?"),+ ("Name three configuration options you can find.", "Which of them affects memory?")]+ rows = []+ for n, (q1, q2) in enumerate(qa):+ system = f"You are a code assistant. Material {n}:\n" + pool[n * 11000:n * 11000 + 11000]+ msgs = [{"role": "system", "content": system}, {"role": "user", "content": q1}]+ b = post({"messages": msgs, "enable_thinking": False, "max_tokens": 100, "temperature": 0})[0]+ msgs += [{"role": "assistant", "content": msg_of(b)["content"]}, {"role": "user", "content": q2}]+ warm = post({"messages": msgs, "enable_thinking": False, "max_tokens": 160, "temperature": 0, "return_token_ids": True})[0]+ # reference = the split cold run: fresh generator (cache_prompt false), turn 1 with max_tokens 1, then turn 2.+ # An unsplit cold run prefills in other chunk shapes and drifts by chunk-boundary numerics (not a cache defect).+ post({"messages": msgs[:2], "enable_thinking": False, "max_tokens": 1, "temperature": 0, "cache_prompt": False})+ ref = post({"messages": msgs, "enable_thinking": False, "max_tokens": 160, "temperature": 0, "return_token_ids": True})[0]+ w, c = warm["token_ids"], ref["token_ids"]+ fd = first_div(w, c)+ rows.append({"prompt_tokens": warm["usage"]["prompt_tokens"], "warm_cached": warm["usage"]["prompt_tokens_details"]["cached_tokens"],+ "ref_cached": ref["usage"]["prompt_tokens_details"]["cached_tokens"], "n_tokens": len(w), "first_divergence": fd})+ rec("warm_vs_cold_greedy", all(r["first_divergence"] is None for r in rows), rows=rows)+++def first_div(w, c):+ fd = next((j for j, (u, v) in enumerate(zip(w, c)) if u != v), None)+ return min(len(w), len(c)) if fd is None and len(w) != len(c) else fd+++def warmcold2():+ """Isolate the warm-vs-cold divergence: (A) plain decode, warm vs cold; (B) speculative, cold vs cold (noise floor)."""+ pool = "".join(open(f).read() for f in sorted(glob.glob(str(ROOT / "exllamav3" / "**" / "*.py"), recursive=True))[:40])+ qa = [("Explain what the first function in the material does.", "Now rewrite it in a simpler way."),+ ("List the classes you see in the material.", "Which one is the most complex and why?"),+ ("What is a recurrent state in this code?", "How is it checkpointed?"),+ ("Describe the cache design in three sentences.", "What could go wrong with it?"),+ ("Name three configuration options you can find.", "Which of them affects memory?")]+ base = {"enable_thinking": False, "temperature": 0, "return_token_ids": True}+ convs = []+ for n, (q1, q2) in enumerate(qa):+ system = f"You are a code assistant. Material {n}:\n" + pool[n * 11000:n * 11000 + 11000]+ msgs = [{"role": "system", "content": system}, {"role": "user", "content": q1}]+ b = post({"messages": msgs, "max_tokens": 100, "speculative": False} | base)[0]+ convs.append(msgs + [{"role": "assistant", "content": msg_of(b)["content"]}, {"role": "user", "content": q2}])+ plain = []+ for msgs in convs:+ post({"messages": msgs[:2], "max_tokens": 100, "speculative": False} | base)+ warm = post({"messages": msgs, "max_tokens": 160, "speculative": False} | base)[0]+ cold = post({"messages": msgs, "max_tokens": 160, "speculative": False, "cache_prompt": False} | base)[0]+ plain.append({"warm_cached": warm["usage"]["prompt_tokens_details"]["cached_tokens"], "first_divergence": first_div(warm["token_ids"], cold["token_ids"])})+ rec("plain_warm_vs_cold", all(r["first_divergence"] is None for r in plain), rows=plain)+ cc = []+ for msgs in convs:+ c1 = post({"messages": msgs, "max_tokens": 160, "cache_prompt": False} | base)[0]+ c2 = post({"messages": msgs, "max_tokens": 160, "cache_prompt": False} | base)[0]+ cc.append({"first_divergence": first_div(c1["token_ids"], c2["token_ids"])})+ rec("spec_cold_vs_cold", all(r["first_divergence"] is None for r in cc), rows=cc)+++def robust():+ import concurrent.futures as cf+ import http.client+ import urllib.parse+ u = urllib.parse.urlparse(a.url)+ conn = http.client.HTTPConnection(u.hostname, u.port, timeout=60)+ conn.request("POST", "/v1/chat/completions", json.dumps({"model": a.model, "stream": True, "max_tokens": 600, "enable_thinking": False,+ "messages": [{"role": "user", "content": "Write a long story about a lighthouse."}]}), {"Content-Type": "application/json"})+ r = conn.getresponse()+ for _ in range(6):+ r.fp.readline()+ conn.close() # client leaves mid-stream+ t0 = time.perf_counter()+ b, _ = post({"messages": [{"role": "user", "content": "Say hello."}], "enable_thinking": False, "max_tokens": 20, "temperature": 0})+ waited = time.perf_counter() - t0+ rec("client_disconnect_then_request", b["choices"][0]["message"]["content"] != "" and waited < 30, waited_s=round(waited, 1))+ with cf.ThreadPoolExecutor(3) as ex:+ futs = [ex.submit(post, {"messages": [{"role": "user", "content": f"Count to {k}."}], "enable_thinking": False,+ "max_tokens": 60, "temperature": 0}) for k in (3, 5, 7)]+ outs = [f.result()[0]["choices"][0]["message"]["content"] for f in futs]+ rec("three_concurrent", all(outs), outs=[o[:40] for o in outs])+ try:+ urllib.request.urlopen(urllib.request.Request(a.url + "/v1/chat/completions", b"{}", {"Content-Type": "application/json"}))+ rec("bad_request_400", False)+ except urllib.error.HTTPError as e:+ rec("bad_request_400", e.code == 400, body=e.read().decode()[:120])+ h = json.loads(urllib.request.urlopen(a.url + "/health").read())+ rec("health", h["status"] == "ok", health=h)+++for step in a.steps.split(","):+ {"functional": functional, "speed": speed, "warmcold": warmcold, "warmcold2": warmcold2, "robust": robust}[step]()+print("CHECK_DONE", sum(1 for c in R.get("checks", []) if not c["ok"]), "bad", flush=True)diff --git a/tools/qwen/spec_bench.py b/tools/qwen/spec_bench.pynew file mode 100644index 0000000..5008879--- /dev/null+++ b/tools/qwen/spec_bench.py@@ -0,0 +1,86 @@+# measure speculation policies, lossless check vs plain (t0). Arms: plain, fix2 (R=3), dyn, mix (dyn + n-gram).+# usage: spec_bench.py OUT.json [--ntok 160] [--budget 540] [--arms plain,fix2,dyn,mix]+import argparse, json, os, sys, time, torch+ap = argparse.ArgumentParser()+ap.add_argument("out"); ap.add_argument("--model", default="~/models/qwen38-td205")+ap.add_argument("--ntok", type=int, default=160); ap.add_argument("--budget", type=float, default=540)+ap.add_argument("--arms", default="plain,fix2,dyn,mix"); ap.add_argument("--nper", type=int, default=6)+ap.add_argument("--thf", type=float, default=0.6); ap.add_argument("--thv", type=float, default=0.3)+a = ap.parse_args()+torch.set_grad_enabled(False)+os.environ.setdefault("EXL3_MTP_FUSE_CATCHUP", "0")+ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, ROOT); sys.path.insert(0, os.path.join(ROOT, "tools", "glm")); sys.path.insert(0, os.path.join(ROOT, "tools", "qwen"))+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job+from exllamav3.generator.sampler import ArgmaxSampler+from transformers import AutoTokenizer+from prompts10 import PROMPTS+from spec_prompts import EXTRA+import spec_policy+from exllamav3.modules import moe_fused+from exllamav3.modules.quant import exl3 as qexl3+# specrow1: arm plain0 = plain greedy with the previous engine config (mf7 MoE kernel, lm_head loop, no GEMV_R_DEC1), every other arm = current config+CUR = (os.environ.get("EXL3_GEMV_R_DEC1", "0"), qexl3.WIDE_R["on"], moe_fused.MF9["variant"])+def set_cfg(old):+ os.environ["EXL3_GEMV_R_DEC1"], qexl3.WIDE_R["on"], moe_fused.MF9["variant"] = ("0", False, 0) if old else CUR+cfg = Config.from_directory(a.model); model = Model.from_config(cfg); tok = Tokenizer.from_config(cfg)+cache = Cache(model, max_num_tokens=4096, max_history=3); model.load(max_chunk_size=2048, progressbar=False)+dm = Model.from_config(cfg, component="mtp"); dcache = Cache(dm, max_num_tokens=4096, max_history=3); dm.load(progressbar=False)+hf = AutoTokenizer.from_pretrained(a.model)+def ids(u):+ p = hf.apply_chat_template([{"role": "user", "content": u}], tokenize=False, add_generation_prompt=True, enable_thinking=False)+ return tok.encode(p, add_bos=False, encode_special_tokens=True)+def make(arm):+ if arm in ("plain", "plain0"): return Generator(model=model, cache=cache, tokenizer=tok), None, {}+ n = 2 if arm == "fix2" else 3+ g = Generator(model=model, cache=cache, tokenizer=tok, draft_model=dm, draft_cache=dcache, num_draft_tokens=n)+ stats = {}+ if arm == "dyn": return g, spec_policy.install(g, dm, model, a.thf, a.thv, 3, None, stats), stats+ if arm == "mix": return g, spec_policy.install(g, dm, model, a.thf, a.thv, 3, (2, 3, 5), stats), stats+ return g, None, stats+GEN = {}+def run(arm, text, ntok):+ set_cfg(arm == "plain0")+ if arm not in GEN:+ for k in list(GEN):+ if GEN[k][1]: GEN[k][1]()+ GEN.clear()+ g, un, stats = make(arm); GEN[arm] = (g, un, stats)+ g, un, stats = GEN[arm]; stats.clear()+ job = Job(input_ids=ids(text), max_new_tokens=ntok, sampler=ArgmaxSampler(), stop_conditions=[])+ g.enqueue(job); toks = []; ttft = None; t0 = time.perf_counter(); nit = 0+ while g.num_remaining_jobs():+ for r in g.iterate():+ t = r.get("token_ids")+ if t is not None and t.numel():+ if ttft is None: torch.cuda.synchronize(); ttft = time.perf_counter() - t0+ toks += t.flatten().tolist()+ nit += 1+ torch.cuda.synchronize(); dec = time.perf_counter() - t0 - ttft+ return {"toks": toks, "tps": (len(toks) - 1) / dec, "iters": nit, "stats": dict(stats)}+arms = a.arms.split(",")+allp = [(k, i, p) for k in ("chat", "prose", "code") for i, p in enumerate(PROMPTS[k][:a.nper])] + [(k, i, p) for k, v in EXTRA.items() for i, p in enumerate(v[:4])]+for arm in arms: run(arm, "Hello", 24)+R = []; t0 = time.time()+for k, i, p in allp:+ if time.time() - t0 > a.budget: print("budget reached", flush=True); break+ row = {"kind": k, "idx": i}+ for arm in arms:+ row[arm] = run(arm, p, a.ntok)+ ref = row["plain"]["toks"] if "plain" in row else None+ for arm in arms:+ if ref is not None and arm != "plain":+ n = next((j for j, (u, v) in enumerate(zip(ref, row[arm]["toks"])) if u != v), None)+ row[arm]["first_div"] = n if n is not None else (None if len(ref) == len(row[arm]["toks"]) else min(len(ref), len(row[arm]["toks"])))+ R.append(row)+ print(k, i, " ".join(f"{arm} {row[arm]['tps']:.1f}" + ("" if arm == "plain" or row[arm].get("first_div") is None and True and ref is not None and row[arm].get("first_div") is None else f" DIV@{row[arm].get('first_div')}") for arm in arms), flush=True)+ json.dump(R, open(a.out, "w"))+import collections+print("SUMMARY (mean tok/s, identical/total)")+for k in ("chat", "prose", "code", "multi", "copy"):+ rs = [r for r in R if r["kind"] == k]+ if not rs: continue+ print("SUMMARY", k, " ".join(f"{arm} {sum(r[arm]['tps'] for r in rs)/len(rs):.1f}" + (f" ({sum(1 for r in rs if r[arm].get('first_div') is None)}/{len(rs)})" if arm != 'plain' else "") for arm in arms), flush=True)+for arm in ("dyn", "mix"):+ ss = [r[arm]["stats"] for r in R if arm in r]+ print("SUMMARY stats", arm, {k: sum(s.get(k, 0) for s in ss) for k in ("mtp", "ng", "rows")}, flush=True)diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.pynew file mode 100644index 0000000..9ca9e87--- /dev/null+++ b/tools/qwen/spec_policy.py@@ -0,0 +1,277 @@+# draft policy for Qwen MTP speculation, installed on a Generator without engine edits.+# (a) dynamic draft length from the drafter's own top-1 probability: a forward at depth i only if the running+# product reach_{i-1} >= thf; token i kept only if reach_i >= thv (depth 1 always kept); depth <= maxd+# (c) n-gram lookup: when the context suffix has an earlier match of length >= lmin, draft = its continuation+# (up to ngk tokens); one MTP forward still runs so the drafter cache has no hole at the current position+# Rows per verify step stay <= maxd + 1 (<= 4: the range proven for the fused MoE kernel).+import os, sys+from array import array+import numpy as np+import torch++class StopDraft(Exception):+ pass++def ngram_match(ctx, nmin, K):+ n = len(ctx); suf = ctx[n - nmin:]+ best = (0, [])+ if n < nmin + 1: return best+ for j in range(n - 1, nmin - 1, -1):+ if ctx[j - nmin:j] == suf:+ L = nmin+ while L < 32 and j - L - 1 >= 0 and ctx[j - L - 1] == ctx[n - L - 1]: L += 1+ if L > best[0]: best = (L, ctx[j:j + K])+ if L >= 16: break+ return best++# ---------------------------------------------------------------------------------------------- incremental index+# ngram_match above scans the whole context every round (host time grows with depth: 7.7 ms at 128K).+# NgramIndex returns exactly the same (L, continuation) with a cost per round that does not depend on the context.+# What the old function returns, in index terms (j = end position of an earlier gram, n = context length):+# - candidates: j in [nmin, n-1] whose gram ctx[j-nmin:j] equals the last nmin tokens;+# - L_j = longest common suffix of ctx[:j] and ctx[:n], capped at 32 (and at j);+# - if some candidate has L_j >= 16 the answer is the LARGEST such j (the break), else the largest L_j, ties -> largest j.+# Per order m in nmin..16 the index keeps latest[m][key] (newest end position of each m-gram) and prev[m][e] (the+# previous end position with the same key as the gram ending at e). prev[m][n] is then "the newest j <= n-1 whose+# m-gram equals the suffix", with no lookup at query time. Order 16 first, then down: the first order with a hit is+# the longest match; L is exact (extended to 32 for order 16). Rollback: truncation walks the removed positions+# newest first and restores latest[m] from prev[m] (exact inverse of the pushes).+# Keys are 62-bit double polynomial hashes; every hit is verified against the tokens and a failed check (a hash+# collision, probability ~1e-9 per hit) falls back to the old scan, so the result is exact either way.+# Memory: 16 key arrays (8 B) + 15 prev arrays (4 B) + 4 B tokens = ~190 B per token, plus the dicts of the+# newest position per distinct gram (<= 15 x ~100 B per token for text with few repeats): about 300 MB at 192K tokens.+_M1, _M2, _B1, _B2, _MASK = 2147483629, 2147483587, 1000003, 999983, (1 << 31) - 1+LMAX, LCAP = 16, 32++class NgramIndex:+ def __init__(self, nmin, lmax=LMAX):+ assert 1 <= nmin <= lmax+ self.nmin, self.lmax = nmin, lmax+ self.toks = array("i")+ self.key = [None] + [array("q", [-1]) for _ in range(lmax)]+ self.prev = [None] + [array("i", [-1]) if m >= nmin else None for m in range(1, lmax + 1)]+ self.latest = [None] + [{} if m >= nmin else None for m in range(1, lmax + 1)]+ self.fallbacks = 0++ def __len__(self):+ return len(self.toks)++ def push(self, t):+ e = len(self.toks) + 1; v = t + 1+ self.toks.append(t)+ key, prev, latest, nmin = self.key, self.prev, self.latest, self.nmin+ for m in range(1, self.lmax + 1):+ if e < m:+ key[m].append(-1)+ if m >= nmin: prev[m].append(-1)+ continue+ if m == 1: a1 = a2 = 0+ else:+ k = key[m - 1][e - 1]; a1 = k >> 31; a2 = k & _MASK+ k = (((a1 * _B1 + v) % _M1) << 31) | ((a2 * _B2 + v) % _M2)+ key[m].append(k)+ if m >= nmin:+ d = latest[m]; prev[m].append(d.get(k, -1)); d[k] = e++ def truncate(self, p):+ n = len(self.toks)+ assert 0 <= p <= n+ key, prev, latest = self.key, self.prev, self.latest+ for e in range(n, p, -1):+ for m in range(self.nmin, self.lmax + 1):+ k = key[m][e]+ if k >= 0:+ pv = prev[m][e]+ if pv >= 0: latest[m][k] = pv+ else: del latest[m][k]+ for m in range(1, self.lmax + 1):+ del key[m][p + 1:]+ if m >= self.nmin: del prev[m][p + 1:]+ del self.toks[p:]+ if n - p > max(4096, p):+ # a dict never gives memory back after deletes: copy the survivors so a long request does not pin ~300 MB for the+ # rest of the process life when the next prompt is short+ for m in range(self.nmin, self.lmax + 1):+ latest[m] = dict(latest[m])++ def extend(self, ids):+ """Append token ids (numpy int array). Small batches push one by one, large ones are built vectorised+ (same state as pushing, checked by the proof tests)."""+ d = len(ids)+ if d < 48:+ for t in ids.tolist(): self.push(t)+ return+ a = len(self.toks)+ ids = np.ascontiguousarray(ids, dtype=np.int64)+ v = ids + 1+ epos = np.arange(a + 1, a + d + 1, dtype=np.int64)+ for m in range(1, self.lmax + 1):+ if m == 1: pk = np.zeros(d, dtype=np.int64)+ else: pk = np.frombuffer(self.key[m - 1], dtype=np.int64)[a:a + d].copy()+ h1 = (((pk >> 31) * _B1) + v) % _M1+ h2 = (((pk & _MASK) * _B2) + v) % _M2+ k = (h1 << 31) | h2+ valid = epos >= m+ k[~valid] = -1+ self.key[m].frombytes(k.tobytes())+ if m < self.nmin: continue+ dct = self.latest[m]+ pv = np.full(d, -1, dtype=np.int32)+ kv = k[valid]; ev = epos[valid]+ if len(kv):+ order = np.argsort(kv, kind="stable")+ sk = kv[order]; se = ev[order]+ first = np.empty(len(sk), dtype=bool); first[0] = True; first[1:] = sk[1:] != sk[:-1]+ pin = np.empty(len(sk), dtype=np.int64); pin[0] = -1; pin[1:] = se[:-1]+ fk = sk[first].tolist()+ pin[first] = np.array([dct.get(x, -1) for x in fk], dtype=np.int64)+ pv[se - (a + 1)] = pin+ last = np.empty(len(sk), dtype=bool); last[-1] = True; last[:-1] = first[1:]+ dct.update(zip(sk[last].tolist(), se[last].tolist()))+ self.prev[m].frombytes(pv.tobytes())+ self.toks.frombytes(ids.astype(np.int32).tobytes())++ def match(self, K):+ """Same value as ngram_match(ctx, nmin, K) on ctx = the indexed tokens."""+ toks = self.toks; n = len(toks); nmin = self.nmin+ if n < nmin + 1: return (0, [])+ prev = self.prev+ for m in range(self.lmax, nmin - 1, -1):+ j = prev[m][n]+ if j >= 0: break+ else:+ return (0, [])+ L = m+ ok = toks[j - m:j] == toks[n - m:n]+ if ok:+ if m == self.lmax:+ while L < LCAP and j - L - 1 >= 0 and toks[j - L - 1] == toks[n - L - 1]: L += 1+ else:+ ok = not (j - m - 1 >= 0 and toks[j - m - 1] == toks[n - m - 1])+ if not ok:+ self.fallbacks += 1+ return ngram_match(toks.tolist(), nmin, K)+ return (L, toks[j:j + K].tolist())++ def sync_array(self, ids):+ """Make the index equal to ids (numpy int array): keep the longest common prefix, roll back, add the rest."""+ have = np.frombuffer(self.toks, dtype=np.int32)+ m = min(len(ids), len(have))+ neq = np.flatnonzero(ids[:m] != have[:m])+ p = int(neq[0]) if len(neq) else m+ del have+ if p < len(self.toks): self.truncate(p)+ if len(ids) > p: self.extend(ids[p:])+ return p++def _as_np(t):+ return t.flatten().numpy().astype(np.int64, copy=False)++class SeqFollower:+ """Keeps one NgramIndex equal to a SeqTensor of token ids. The tensor changes only by append and truncate+ (job.py: pinned_ids_valid relies on the same fact); truncate/clear are wrapped on the instance to keep a low-water+ mark, so the prefix below it is known unchanged. A new tensor (next request, loop-guard restart) is matched by+ common prefix, so multi-turn reuse costs the new tokens only. The last tokens are re-checked each sync as a belt."""+ TAIL = 16+ def __init__(self, nmin):+ self.idx = NgramIndex(nmin); self.sid = None; self.resyncs = 0++ def _hook(self, sid):+ sid._ng_lw = len(sid)+ o_tr, o_cl = sid.truncate, sid.clear+ def tr(nl):+ sid._ng_lw = min(sid._ng_lw, nl); o_tr(nl)+ def cl():+ sid._ng_lw = 0; o_cl()+ sid.truncate, sid.clear = tr, cl++ def sync(self, sid):+ idx = self.idx; n = len(sid)+ if sid is not self.sid:+ if n: idx.sync_array(_as_np(sid.torch()))+ else: idx.truncate(0)+ if not hasattr(sid, "_ng_lw"): self._hook(sid)+ self.sid = sid; sid._ng_lw = n+ return idx+ p = min(sid._ng_lw, len(idx), n)+ if p < len(idx): idx.truncate(p)+ t = min(self.TAIL, len(idx))+ if t and not np.array_equal(_as_np(sid.torch_slice(len(idx) - t, len(idx))), np.frombuffer(idx.toks, dtype=np.int32)[len(idx) - t:]):+ self.resyncs += 1+ idx.sync_array(_as_np(sid.torch()))+ elif n > len(idx):+ idx.extend(_as_np(sid.torch_slice(len(idx), n)))+ sid._ng_lw = n+ return idx++def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None):+ """ngram = (nmin, K, lmin) or None. Returns an uninstall function."""+ lm = model.modules[model.logit_layer_idx]+ st = {"i": 0, "reach": 1.0, "stop": False, "keep": None}+ orig_draft = type(g).iterate_draftmodel_mtp_gen.__get__(g)+ orig_sfs = dm.sample_from_state; orig_fwd = dm.forward; orig_lmf = lm.forward+ cap = {}+ fol = SeqFollower(ngram[0]) if ngram is not None else None+ orig_enqueue = g.enqueue+ def enq(job):+ # prime the index at enqueue: its cold build (about 1 s at 192K) lands in time-to-first-token, not in decode+ r = orig_enqueue(job)+ if fol is not None and os.environ.get("QWSPEC_NGRAM_IDX", "1") != "0":+ for j in (job if isinstance(job, list) else [job]):+ if len(getattr(j, "sequences", ())) == 1: fol.sync(j.sequences[0].sequence_ids)+ return r+ if fol is not None: g.enqueue = enq+ def lmf(*a, **k):+ o = orig_lmf(*a, **k); cap["lg"] = o; return o+ def fwd(*a, **k):+ if st["stop"]: raise StopDraft()+ return orig_fwd(*a, **k)+ def sfs(state, params):+ ids = orig_sfs(state, params)+ if st["mode"] == "mtp":+ p = torch.softmax(cap["lg"][..., :model.config.vocab_size].float().reshape(-1, model.config.vocab_size), -1).max().item()+ i = st["i"]; st["reach"] *= p+ if i > 0 and st["reach"] < thv:+ st["keep"] = i; raise StopDraft()+ st["i"] = i + 1+ if st["reach"] < thf or st["i"] >= maxd:+ st["stop"] = True; st["keep"] = st["i"]+ return ids+ def wrapped(results):+ st.update(i=0, reach=1.0, stop=False, keep=None, mode="mtp")+ job = next((j for j in g.active_jobs if j.is_prefill_done()), None)+ cont = None+ if ngram is not None and job is not None and len(g.active_jobs) == 1:+ seq = job.sequences[0]; n = len(seq.sequence_ids); K = min(ngram[1], maxd)+ if os.environ.get("QWSPEC_NGRAM_IDX", "1") == "0":+ L, c = ngram_match(seq.sequence_ids.torch_slice(0, n).flatten().tolist(), ngram[0], K)+ else:+ L, c = fol.sync(seq.sequence_ids).match(K)+ if os.environ.get("QWSPEC_NGRAM_SHADOW", "0") == "1":+ ref = ngram_match(seq.sequence_ids.torch_slice(0, n).flatten().tolist(), ngram[0], K)+ if stats is not None: stats["shadow"] = stats.get("shadow", 0) + 1+ if ref != (L, c):+ if stats is not None: stats["shadow_bad"] = stats.get("shadow_bad", 0) + 1+ raise RuntimeError(f"ngram index mismatch at n={n}: old {ref} new {(L, c)}")+ if L >= ngram[2] and c: cont = c+ if cont is not None:+ st["mode"] = "ng"; g.num_draft_tokens = 1+ try: out = orig_draft(results)+ finally: g.num_draft_tokens = maxd+ if out is None: return None+ if stats is not None: stats["ng"] = stats.get("ng", 0) + 1; stats["rows"] = stats.get("rows", 0) + 1 + len(cont)+ return torch.tensor([cont], dtype=torch.long)+ g.num_draft_tokens = maxd+ try:+ out = orig_draft(results)+ except StopDraft:+ out = g.draft_ids_pinned[:, :st["keep"]]+ if out is None: return None+ if stats is not None: stats["mtp"] = stats.get("mtp", 0) + 1; stats["rows"] = stats.get("rows", 0) + 1 + out.shape[-1]+ return out+ lm.forward = lmf; dm.forward = fwd; dm.sample_from_state = sfs+ g.iterate_draftmodel_mtp_gen = wrapped+ def uninstall():+ lm.forward = orig_lmf; dm.forward = orig_fwd; dm.sample_from_state = orig_sfs+ g.__dict__.pop("iterate_draftmodel_mtp_gen", None); g.__dict__.pop("enqueue", None)+ return uninstalldiff --git a/tools/qwen/spec_prompts.py b/tools/qwen/spec_prompts.pynew file mode 100644index 0000000..25681b5--- /dev/null+++ b/tools/qwen/spec_prompts.py@@ -0,0 +1,42 @@+CODE_SNIP = '''def moving_average(values, window):+ if window <= 0:+ raise ValueError("window must be positive")+ result = []+ total = 0.0+ for i, v in enumerate(values):+ total += v+ if i >= window:+ total -= values[i - window]+ if i >= window - 1:+ result.append(total / window)+ return result++def median(values):+ s = sorted(values)+ n = len(s)+ mid = n // 2+ if n % 2:+ return s[mid]+ return (s[mid - 1] + s[mid]) / 2+'''+QUOTE = ("The committee noted that the proposed regulation would require all operators of automated "+ "vehicles to maintain a continuous audit log of sensor inputs, control decisions and manual overrides, "+ "retained for no fewer than twenty-four months and made available to the supervisory authority within "+ "five working days of a written request. Operators who fail to comply may be subject to a fine of up to "+ "two percent of annual turnover.")+EXTRA = {+ "multi": [+ "Explique-moi en detail comment fonctionne une pompe a chaleur et pourquoi elle est plus efficace qu'un radiateur electrique.",+ "Escribe un cuento corto sobre un pescador que encuentra una lampara magica en la playa.",+ "Erklaere mir ausfuehrlich den Unterschied zwischen einer GmbH und einer AG in Deutschland.",+ "请详细介绍一下如何准备一次长途徒步旅行,包括装备、路线和安全注意事项。",+ "Spiegami come funziona il sistema immunitario umano, con esempi concreti.",+ "Redige une lettre formelle de reclamation a un fournisseur d'electricite pour une facture erronee.",+ ],+ "copy": [+ "Here is a Python module:\n\n```python\n" + CODE_SNIP + "```\n\nRewrite the whole module with type hints and docstrings, keeping the logic identical.",+ "Here is a Python module:\n\n```python\n" + CODE_SNIP + "```\n\nRename `values` to `data` everywhere and print the full updated module.",+ "Quote the following passage word for word, then summarize it in two sentences.\n\n" + QUOTE,+ "Here is a passage:\n\n" + QUOTE + "\n\nExtract every obligation as a bullet list, reusing the exact wording of the passage.",+ ],+}diff --git a/tools/qwen/test_guard.py b/tools/qwen/test_guard.pynew file mode 100644index 0000000..0becaf5--- /dev/null+++ b/tools/qwen/test_guard.py@@ -0,0 +1,402 @@+#!/usr/bin/env python3+"""Loop guard + seed + thinking budget: model-free tests (stub generator, no GPU, no exllamav3)."""+from __future__ import annotations++import asyncio+import os+import random+import re+import sys+import unittest+from pathlib import Path++import torch++sys.path.insert(0, str(Path(__file__).parent))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "evalgate"))+import serve+from test_serve import FakeEngine, with_client++CLOSE, CLOSE_SEQ = 9, [5, 9, 6] # stub token ids: </think>, and "\n</think>\n\n"+++class StubTok:+ def encode(self, text, add_bos=False, encode_special_tokens=False):+ return torch.tensor([[CLOSE] if text == serve.THINK_CLOSE else CLOSE_SEQ])+++class StubJob:+ jobs: list = []++ def __init__(self, input_ids, max_new_tokens, sampler, stop_conditions, embeddings=None, decode_special_tokens=False, seed=None):+ self.ids, self.max_new, self.seed, self.stops = input_ids.flatten().tolist(), max_new_tokens, seed, stop_conditions+ self.rng = random.Random(seed)+ StubJob.jobs.append(self)+++class StubGenerator:+ """Emits `per_iter` tokens per iterate() call from model(context) -> token id (0 = eos)."""++ def __init__(self, model, per_iter=3):+ self.model, self.per_iter, self.job, self.out = model, per_iter, None, []++ def enqueue(self, job):+ self.job, self.out = job, []++ def num_remaining_jobs(self):+ return 1 if self.job is not None else 0++ def cancel(self, job):+ self.job = None++ def iterate(self):+ j, toks, eos, reason = self.job, [], False, None+ for _ in range(self.per_iter):+ t = self.model(j.ids + self.out, j)+ if t in j.stops:+ eos, reason = True, "stop_token"+ break+ self.out.append(t)+ toks.append(t)+ if len(self.out) >= j.max_new:+ eos, reason = True, "max_new_tokens"+ break+ ev = {"job": j, "token_ids": torch.tensor(toks), "text": "".join("</think>" if t == CLOSE else f"<{t}>" for t in toks)}+ if eos:+ ev |= {"eos": True, "eos_reason": reason, "new_tokens": len(self.out), "prompt_tokens": len(j.ids),+ "cached_tokens": 0}+ self.job = None+ return [ev]+++def make_engine(model, per_iter=3):+ e = object.__new__(serve.QwenEngine)+ e.torch, e.Job, e.generator = torch, StubJob, StubGenerator(model, per_iter)+ e.tokenizer, e.eos, e.draft_model, e.spec_on, e.slot_store, e.last_stats = StubTok(), [0], None, False, None, {}+ e._encode = lambda prompt, urls: (torch.tensor([[100, 101, 102]]), [])+ e._sampler = lambda s: None+ StubJob.jobs = []+ return e+++def collect(engine, **kw):+ async def go():+ out = ""+ async for piece in engine.generate("p", sampling={"temperature": 0}, stop=[], **{"max_tokens": 600} | kw):+ out = out[:len(out) - int(piece)] if isinstance(piece, serve.Retract) else out + piece+ return out+ return asyncio.run(go()), engine.last_stats+++def answer_after_close(ctx):+ """Tokens 1000.. after the (natural or forced) close, then eos."""+ k = len(ctx) - 1 - ctx[::-1].index(CLOSE)+ n = len(ctx) - k - 1 - (1 if ctx[k + 1:k + 2] == [6] else 0)+ return 1000 + n if n < 8 else 0+++def loop_model(unique=40, period=9, loop_in="think"):+ """Greedy-like model: `unique` fresh tokens, then an endless cycle (in think or in answer)."""+ def m(ctx, job):+ gen = ctx[3:]+ if loop_in == "think":+ if CLOSE in gen:+ return answer_after_close(ctx)+ return 200 + len(gen) if len(gen) < unique else 500 + (len(gen) - unique) % period+ if CLOSE not in gen:+ return 200 + len(gen) if len(gen) < unique else CLOSE+ a = len(gen) - gen.index(CLOSE) - 1+ return 700 + a % period if a >= 3 else 600 + a+ return m+++def normal_model(ctx, job):+ gen = ctx[3:]+ if CLOSE in gen:+ return answer_after_close(ctx)+ return 200 + len(gen) if len(gen) < 300 else CLOSE+++class GuardEngineTests(unittest.TestCase):+ def test_normal_output_identical_guard_on_off(self):+ on, off = collect(make_engine(normal_model), reasoning_first=True, loop_guard=True), collect(make_engine(normal_model), reasoning_first=True, loop_guard=False)+ self.assertEqual(on, off)+ self.assertNotIn("loop_guard", on[1])+ self.assertEqual(len(on[1]["token_ids"]), 300 + 1 + 8)++ def test_final_check_recovers_answer_that_repeats_the_thinking_drafts(self):+ import loops+ draft = [800 + i for i in range(30)]++ def drafter(ctx, job): # thinking: 40 fresh tokens, then the same 30-token draft 3 times, then close; the answer copies the draft+ gen = ctx[3:]+ if CLOSE in gen:+ a = len(gen) - gen.index(CLOSE) - 1 - (1 if gen[gen.index(CLOSE) + 1:gen.index(CLOSE) + 2] == [6] else 0)+ k = gen[:gen.index(CLOSE)]+ drafts = sum(1 for i in range(len(k) - 29) if k[i:i + 30] == draft)+ if drafts >= 2:+ return draft[a] if a < 30 else 0+ return 1000 + a if a < 8 else 0+ n = len(gen)+ if n < 40:+ return 200 + n+ return CLOSE if n >= 40 + 90 else draft[(n - 40) % 30]+ off = collect(make_engine(drafter, per_iter=1), reasoning_first=True, loop_guard=True, loop_final=False)+ self.assertTrue(loops.is_loop(off[0]))+ text, st = collect(make_engine(drafter, per_iter=1), reasoning_first=True, loop_guard=True)+ self.assertEqual(st["loop_guard"]["kind"], "final")+ self.assertEqual(text.count("</think>"), 1)+ self.assertFalse(loops.is_loop(text), text[-200:])+ self.assertIn("<1007>", text)+ self.assertEqual(len(StubJob.jobs), 2)++ def test_final_check_recovers_think_loop_that_ends_at_the_cap(self):+ import loops++ def drift(ctx, job): # thinking never closes: 40 fresh tokens then a 70-token cycle (above the n-gram window)+ gen = ctx[3:]+ if CLOSE in gen:+ return answer_after_close(ctx)+ n = len(gen)+ return 200 + n if n < 40 else 500 + (n - 40) % 70+ text, st = collect(make_engine(drift, per_iter=1), reasoning_first=True, loop_guard=True, loop_final=False, max_tokens=300)+ self.assertEqual(st["eos_reason"], "max_new_tokens")+ self.assertTrue(loops.is_loop(text))+ text, st = collect(make_engine(drift, per_iter=1), reasoning_first=True, loop_guard=True, max_tokens=300)+ self.assertEqual(st["loop_guard"]["kind"], "final")+ self.assertFalse(loops.is_loop(text), text[-200:])+ self.assertIn("<1007>", text) # the answer was generated after the cut+ self.assertLessEqual(len(st["token_ids"]), 300) # discarded tokens are not charged to max_tokens++ def test_final_cut_unit(self):+ think = "".join(f"line {i} unique words here\n" for i in range(20)) + ("draft: the quiet man never spoke and all laughed loudly\n" * 4)+ ans = "the quiet man never spoke and all laughed loudly"+ full = think + "</think>" + ans+ self.assertTrue(serve.text_loop(full))+ c = serve.final_cut(full)+ self.assertFalse(serve.text_loop(think[:c] + "</think>" + ans))+ self.assertGreater(c, 0)+ self.assertFalse(serve.text_loop("fine text\n" * 3 + "</think>" + ans))++ def test_final_cut_leaves_no_span_that_the_answer_could_bring_to_three(self):+ span = "the committee agreed that the budget would be reviewed again next spring"+ think = "".join(f"line {i} unique words here\n" for i in range(20)) + span + "\n" + "middle line, different words entirely\n" + span + "\n" + "final line, nothing repeated\n"+ ans = "a short unrelated reply"+ self.assertEqual(serve.max_span_repeat(think), 2)+ c = serve.final_cut(think + "</think>" + ans)+ self.assertLessEqual(serve.max_span_repeat(think[:c].rstrip()), 1)+ self.assertLessEqual(c, think.index(span, think.index(span) + 1))++ def test_think_loop_closed_and_answer_follows(self):+ e = make_engine(loop_model(), per_iter=1)+ text, st = collect(e, reasoning_first=True, loop_guard=True)+ self.assertEqual(text.count("</think>"), 1)+ self.assertIn("\n</think>\n\n", text)+ self.assertIn("<1007>", text) # the answer proceeded (8 answer tokens then eos)+ self.assertEqual(st["loop_guard"]["kind"], "period")+ self.assertEqual(len(StubJob.jobs), 2)+ # restart context = prompt + thinking up to the end of the FIRST cycle + forced close+ self.assertEqual(StubJob.jobs[1].ids, [100, 101, 102] + [200 + i for i in range(40)] + [500 + i for i in range(9)] + CLOSE_SEQ)+ self.assertEqual(st["prompt_tokens"], 3)+ self.assertGreater(st["new_tokens"], len(st["token_ids"]))++ def test_visible_text_matches_kept_tokens_with_speculative_batches(self):+ piece = lambda x: f"<{x}>"+ for per_iter in (1, 2, 3, 4, 5):+ text, st = collect(make_engine(loop_model(), per_iter=per_iter), reasoning_first=True, loop_guard=True)+ toks = st["token_ids"]+ k = next(i for i in range(len(toks)) if toks[i:i + 3] == CLOSE_SEQ)+ expect = "".join(map(piece, toks[:k])) + serve.THINK_CLOSE_TEXT + "".join(map(piece, toks[k + 3:]))+ self.assertEqual(text, expect, per_iter) # the discarded tail was retracted, nothing else changed+ self.assertGreater(st["new_tokens"], len(toks)) # generated counts the discarded tail too++ def test_guard_off_runs_to_the_cap(self):+ text, st = collect(make_engine(loop_model()), reasoning_first=True, loop_guard=False, max_tokens=300)+ self.assertNotIn("</think>", text)+ self.assertEqual(st["eos_reason"], "max_new_tokens")++ def test_env_switch(self):+ os.environ["EXL3_LOOP_GUARD"] = "0"+ try:+ text, st = collect(make_engine(loop_model()), reasoning_first=True, max_tokens=300)+ finally:+ del os.environ["EXL3_LOOP_GUARD"]+ self.assertNotIn("</think>", text)++ def test_answer_loop_ends_the_turn(self):+ text, st = collect(make_engine(loop_model(loop_in="answer")), reasoning_first=True, loop_guard=True, max_tokens=900)+ self.assertEqual(st["eos_reason"], "loop_guard")+ self.assertEqual(st["loop_guard"]["phase"], "answer")+ self.assertLess(len(st["token_ids"]), 400)++ def test_budget_closes_think(self):+ text, st = collect(make_engine(normal_model, per_iter=1), reasoning_first=True, loop_guard=False, thinking_budget=50)+ self.assertEqual(st["loop_guard"]["kind"], "budget")+ self.assertEqual(StubJob.jobs[1].ids, [100, 101, 102] + [200 + i for i in range(50)] + CLOSE_SEQ)+ self.assertEqual(text.count("</think>"), 1 + 0)++ def test_budget_ignored_without_think_and_after_natural_close(self):+ text, st = collect(make_engine(normal_model), reasoning_first=False, thinking_budget=5, loop_guard=False)+ self.assertEqual(len(StubJob.jobs), 1)+ text, st = collect(make_engine(normal_model), reasoning_first=True, thinking_budget=5000)+ self.assertEqual(len(StubJob.jobs), 1)++ def test_cap_reached_during_restart(self):+ text, st = collect(make_engine(loop_model()), reasoning_first=True, loop_guard=True, loop_final=False, max_tokens=70)+ self.assertEqual(st["eos_reason"], "max_new_tokens")+ self.assertLessEqual(len(st["token_ids"]), 70 + 5)++ def test_seed_forwarded_and_reproducible(self):+ jobs = []+ for sd in (1234, 1234, 99):+ collect(make_engine(normal_model), reasoning_first=True, seed=sd)+ jobs.append(StubJob.jobs[0])+ a, b, c = jobs+ self.assertEqual((a.seed, b.seed, c.seed), (1234, 1234, 99))+ draw = lambda j: [j.rng.randint(0, 2**32 - 1) for _ in range(5)]+ self.assertEqual(draw(a), draw(b))+ self.assertNotEqual(draw(a), draw(c))++ def test_real_job_accepts_seed(self):+ src = (Path(__file__).resolve().parents[2] / "exllamav3" / "generator" / "job.py").read_text()+ self.assertTrue(re.search(r"seed: int = None", src) and "random.Random(seed)" in src)+++class HttpFieldTests(unittest.TestCase):+ def post(self, payload):+ eng = FakeEngine("hi")++ async def fn(client):+ r = await client.post("/v1/chat/completions", json={"model": "m", "messages": [{"role": "user", "content": "x"}]} | payload)+ return r.status+ return with_client(eng, fn), eng++ def test_fields_reach_engine(self):+ st, eng = self.post({"seed": 7, "thinking_budget": 300, "loop_guard": False})+ self.assertEqual(st, 200)+ kw = eng.calls[0][1]+ self.assertEqual((kw["seed"], kw["thinking_budget"], kw["loop_guard"], kw["reasoning_first"]), (7, 300, False, True))++ def test_defaults(self):+ st, eng = self.post({})+ kw = eng.calls[0][1]+ self.assertEqual((kw["seed"], kw["thinking_budget"], kw["loop_guard"]), (None, None, None))++ def test_bad_values_400(self):+ for bad in ({"seed": "x"}, {"seed": True}, {"thinking_budget": 0}, {"thinking_budget": "a"}, {"loop_guard": "yes"}):+ self.assertEqual(self.post(bad)[0], 400, bad)+++class RetractEngine(FakeEngine):+ async def generate(self, prompt, **kw):+ self.last_stats = dict(self.stats, loop_guard={"kind": "period"})+ for p in ("thinking ok ", "LOOPLOOP", serve.Retract(8), "\n</think>\n\n", "answer"):+ yield p+++class RetractHttpTests(unittest.TestCase):+ def post(self, stream):+ async def fn(client):+ r = await client.post("/v1/chat/completions", json={"model": "m", "stream": stream, "messages": [{"role": "user", "content": "x"}]})+ return await (r.text() if stream else r.json())+ return with_client(RetractEngine(""), fn)++ def test_non_stream_drops_the_discarded_tail(self):+ b = self.post(False)+ m = b["choices"][0]["message"]+ self.assertEqual((m["reasoning_content"], m["content"]), ("thinking ok", "answer"))+ self.assertEqual(b["timings"]["loop_guard"], {"kind": "period"})++ def test_stream_survives_retract(self):+ raw = self.post(True)+ self.assertIn("answer", raw)+ self.assertIn("[DONE]", raw)+++# ------------------------------------------------------------------ detector: no false positive on normal text++def tokenize(text):+ """Word-ish tokens -> ids, text pieces per token (stands in for the BPE)."""+ vocab: dict[str, int] = {}+ pieces = re.findall(r"\s+|\w+|[^\w\s]", text)+ return [vocab.setdefault(p, len(vocab) + 1000) for p in pieces], pieces+++def run_monitor(text, phase="think", chunk=3):+ ids, pieces = tokenize(text)+ m = serve.LoopMonitor(phase, None)+ for i in range(0, len(ids), chunk):+ hit = m.feed(ids[i:i + chunk], "".join(pieces[i:i + chunk]))+ if hit:+ return hit+ return None+++FALSE_POSITIVE_TEXTS = {+ "counting": " ".join(str(i) for i in range(1, 51)) + "\n" + "\n".join(f"{i}. item number {i}" for i in range(1, 51)),+ "bullets": "\n".join(f"- Point {i}: we must check the constraint number {i} again" for i in range(60)),+ "table": "| id | name | score |\n|----|------|-------|\n" + "\n".join(f"| {i} | user{i} | {i * 7 % 100} |" for i in range(80)),+ "code": "def f(x):\n y = x + 1\n" + " print('step')\n" * 5 + " return y\n" + "\n".join(f" v{i} = compute(a, b, {i})" for i in range(30)),+ "draft_rewrite": ("Need a haiku about dogs. Draft: the dog runs fast / the day is long and bright / warm sun on the grass. "+ "Check syllables: five seven five. Looks fine. Rewrite the draft: the dog runs fast / the day is long and bright / "+ "warm sun on the grass. Now verify no commas appear anywhere in the response. Good. Final: the dog runs fast / "+ "the day is long and bright / warm sun on the grass."),+ "letter_count": " ".join(f"{i}:{w}" for i, w in enumerate("the quick brown fox jumps over the lazy dog and keeps running far away".split() * 4)),+}+++class DetectorTests(unittest.TestCase):+ def test_no_false_positive(self):+ for name, text in FALSE_POSITIVE_TEXTS.items():+ for phase in ("think", "answer"):+ self.assertIsNone(run_monitor(text, phase), (name, phase))++ def test_exact_cycle_fires_think_and_reports_first_cycle_cut(self):+ pre = list(range(1000, 1040))+ cyc = [1, 2, 3, 4, 5, 6, 7, 8, 9]+ m = serve.LoopMonitor("think", None)+ hit = None+ for t in pre + cyc * 10:+ hit = hit or m.feed([t])+ self.assertEqual((hit["kind"], hit["period"]), ("period", 9))+ self.assertEqual(hit["cut"], 40 + 9)++ def test_period_one_and_answer_is_stricter(self):+ m = serve.LoopMonitor("think", None)+ hit = next((h for t in [7] * 60 if (h := m.feed([t]))), None)+ self.assertIsNotNone(hit)+ self.assertEqual(hit["at"], 48)+ m = serve.LoopMonitor("answer", None)+ hit = next((h for t in [7] * 60 if (h := m.feed([t]))), None)+ self.assertIsNone(hit) # 60 < answer min span 96++ def test_text_rule_fires_on_sustained_drift_only(self):+ cycle = ['"alpha beta" no.\n', '"gamma delta" no.\n', '"alpha beta" maybe.\n', '"epsilon zeta" no.\n']+ vocab = {}+ m, hit, n = serve.LoopMonitor("think", None), None, 0+ for rep in range(200):+ for p in cycle[:3] + [f'"drift{rep} word" no.\n']: # one drifting piece per cycle: no exact period+ tid = vocab.setdefault(p, 5000 + len(vocab))+ n += 1+ hit = hit or m.feed([tid], p)+ self.assertIsNotNone(hit)+ self.assertEqual(hit["kind"], "text")++ def test_close_token_switches_phase(self):+ m = serve.LoopMonitor("think", 9)+ self.assertIsNone(m.feed([1, 2, 3, 9, 4]))+ self.assertEqual(m.phase, "answer")+ self.assertEqual(m.ids, [4])++ def test_text_rule_equals_release_gate_rule(self):+ import loops+ samples = ["ab" * 800, "the quick brown fox " * 100, "hello world. " * 40 + "unique tail " * 5,+ "".join(chr(0x0e01 + i % 40) for i in range(1200)), FALSE_POSITIVE_TEXTS["table"] * 3]+ rng = random.Random(1)+ samples += ["".join(rng.choice("abc def\n") for _ in range(2500)) for _ in range(5)]+ for s in samples:+ self.assertEqual(serve.text_loop(s), bool(loops.is_loop(s)))+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/qwen/test_ngram_index.py b/tools/qwen/test_ngram_index.pynew file mode 100644index 0000000..1da6f5a--- /dev/null+++ b/tools/qwen/test_ngram_index.py@@ -0,0 +1,162 @@+# proof: NgramIndex / SeqFollower == the old ngram_match, CPU only.+# python tools/qwen/test_ngram_index.py [--fuzz 10000] [--docs DIR] (HIP_VISIBLE_DEVICES= CUDA_VISIBLE_DEVICES= nice -n 19)+import os, sys, json, random, time, argparse+os.environ.setdefault("HIP_VISIBLE_DEVICES", ""); os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))+import numpy as np, torch+torch.set_num_threads(1)+import spec_policy as sp+from exllamav3.util.tensor import SeqTensor++BR = {}+def hit(k): BR[k] = BR.get(k, 0) + 1++def check(idx, ctx, nmin, K, where):+ ref = sp.ngram_match(ctx, nmin, K); got = idx.match(K)+ assert ref == got, f"MISMATCH {where} n={len(ctx)} nmin={nmin} K={K}: old {ref} new {got}"+ L, c = ref+ if L == 0: hit("none")+ elif L >= 16: hit("L>=16"); hit("L=32") if L == 32 else None+ else: hit("L5-15" if L >= 5 else "L<5")+ if L and len(c) < K: hit("short_cont")+ if L and len(ctx) - len(c) - 0 >= 0:+ pass+ return ref++def same_state(a, b, where):+ assert a.toks == b.toks, where+ for m in range(1, a.lmax + 1):+ assert a.key[m] == b.key[m], f"{where}: key level {m}"+ if m >= a.nmin:+ assert a.prev[m] == b.prev[m], f"{where}: prev level {m}"+ assert a.latest[m] == b.latest[m], f"{where}: latest level {m}"++def gen_stream(rng, n):+ kind = rng.choice(["small", "blocks", "mixed", "zipf", "period"])+ if kind == "small":+ a = rng.randint(2, 6); return [rng.randrange(a) for _ in range(n)]+ if kind == "period":+ p = rng.randint(1, 20); base = [rng.randrange(1000) for _ in range(p)]+ s = [base[i % p] for i in range(n)]+ for _ in range(rng.randint(0, 3)):+ if n: s[rng.randrange(n)] = rng.randrange(1000)+ return s+ if kind == "blocks":+ blocks = [[rng.randrange(50) for _ in range(rng.randint(3, 40))] for _ in range(rng.randint(2, 8))]+ s = []+ while len(s) < n:+ b = rng.choice(blocks); s += b if rng.random() < 0.8 else b[:rng.randint(1, len(b))] + [rng.randrange(50)]+ return s[:n]+ if kind == "zipf":+ w = [1 / (i + 1) for i in range(300)]; return rng.choices(range(300), w, k=n)+ s = []+ while len(s) < n:+ if s and rng.random() < 0.5:+ i = rng.randrange(len(s)); l = rng.randint(2, 40); s += s[i:i + l]+ else: s += [rng.randrange(8) for _ in range(rng.randint(1, 10))]+ return s[:n]++def fuzz(cases, seed=1):+ rng = random.Random(seed); t0 = time.time()+ for c in range(cases):+ nmin = rng.choice([1, 2, 2, 2, 3, 4]); K = rng.choice([1, 2, 3, 3, 3, 5])+ n = rng.choice([0, 1, 2, 3, 5, 10, 40, 100, 300, 1000])+ stream = gen_stream(rng, n + 400)+ idx = sp.NgramIndex(nmin); ctx = []; src = 0+ sid = SeqTensor((1, 1), torch.long, -1, init_cap=64)+ fol = sp.SeqFollower(nmin)+ def sid_to(lst):+ sid.clear(); sid.append(torch.tensor([lst], dtype=torch.long)) if lst else None+ for step in range(rng.randint(5, 40)):+ op = rng.random()+ if op < 0.55 or not ctx: # accept 1-4 tokens+ k = rng.randint(1, 4); new = stream[src:src + k] or [rng.randrange(5)]+ src += len(new); ctx += new+ sid.append(torch.tensor([new], dtype=torch.long)); hit("append")+ elif op < 0.75: # rollback 1-4+ k = min(rng.randint(1, 4), len(ctx)); ctx = ctx[:len(ctx) - k]; sid.truncate(len(ctx)); hit("trunc")+ elif op < 0.85: # deep rollback then different continuation+ k = rng.randint(0, len(ctx)); ctx = ctx[:k]; sid.truncate(k)+ new = [rng.randrange(8) for _ in range(rng.randint(0, 30))]; ctx += new+ if new: sid.append(torch.tensor([new], dtype=torch.long))+ hit("deep")+ elif op < 0.92: # truncate then append SAME LENGTH different tokens (low-water mark case)+ k = min(rng.choice([rng.randint(1, 6), rng.randint(17, 80)]), len(ctx)); ctx = ctx[:len(ctx) - k]; sid.truncate(len(ctx))+ new = [rng.randrange(8) for _ in range(k)]; ctx += new; sid.append(torch.tensor([new], dtype=torch.long)); hit("same_len_swap")+ elif op < 0.94 and len(ctx) > 40: # middle swap: tokens differ below the last 16 (the tail belt cannot see it)+ k = rng.randint(17, min(60, len(ctx))); keep = ctx[len(ctx) - 16:]; head = ctx[:len(ctx) - k]+ ctx = head + [rng.randrange(8) for _ in range(k - 16)] + keep+ sid.truncate(len(head)); sid.append(torch.tensor([ctx[len(head):]], dtype=torch.long)); hit("middle_swap")+ elif op < 0.96: # set (clear + append)+ lst = ctx[:rng.randint(0, len(ctx))] + [rng.randrange(8) for _ in range(rng.randint(0, 50))]+ ctx = lst; sid.set(torch.tensor([lst], dtype=torch.long)) if lst else sid.clear(); hit("set")+ else: # big append (bulk path)+ new = stream[src:src + rng.randint(48, 300)]; src += len(new); ctx += new+ if new: sid.append(torch.tensor([new], dtype=torch.long)); hit("bulk")+ got = fol.sync(sid)+ assert len(got) == len(ctx) and list(got.toks) == ctx, f"case {c}: follower mirror differs"+ check(got, ctx, nmin, K, f"case {c} step {step}")+ if rng.random() < 0.05: # new SeqTensor sharing a prefix (next request)+ k = rng.randint(0, len(ctx)); ctx = ctx[:k] + [rng.randrange(8) for _ in range(rng.randint(0, 20))]+ sid = SeqTensor((1, 1), torch.long, -1, init_cap=64)+ if ctx: sid.append(torch.tensor([ctx], dtype=torch.long))+ hit("new_seq")+ # state equality: bulk/follower index == pure scalar pushes of the same tokens+ if c % 25 == 0:+ fol.sync(sid)+ ref = sp.NgramIndex(nmin)+ for t in ctx: ref.push(t)+ same_state(fol.idx, ref, f"case {c} state")+ hit("state_checked")+ print(f"fuzz {cases} cases OK in {time.time() - t0:.1f}s")++def streams_from_docs(dd):+ from tokenizers import Tokenizer+ tk = Tokenizer.from_file(os.path.expanduser("~/models/qwen38-yamz-v2-bal/tokenizer.json"))+ out = {}+ for L in (4096, 65536, 196608):+ d = json.load(open(f"{dd}/doc{L}.json")); out[L] = tk.encode(d["doc"], add_special_tokens=False).ids+ return out++def recorded(dd, rounds=300, seed=3):+ """Rounds of 1-4 accepted tokens (the shipped spec step) over real token streams, with 5% rollbacks of 1-4+ tokens (rejected / checkpoint restore) and a second 'turn' reusing the prefix through a new SeqTensor."""+ rng = random.Random(seed)+ for L, ids in streams_from_docs(dd).items():+ t0 = time.time(); nmin = 2; K = 3+ base = len(ids) - 2000 # prompt = ids[:base]; rounds continue through the document tail+ sid = SeqTensor((1, 1), torch.long, -1, init_cap=base + 4096)+ sid.append(torch.tensor([ids[:base]], dtype=torch.long))+ fol = sp.SeqFollower(nmin); ctx = ids[:base]; pos = base+ tb = time.time(); fol.sync(sid); cold = time.time() - tb+ n_hits = 0; times = []+ for r in range(rounds):+ if r % 20 == 19:+ k = rng.randint(1, 4); ctx = ctx[:-k]; sid.truncate(len(ctx)); pos -= k+ k = rng.randint(1, 4); new = ids[pos:pos + k]; pos += len(new); ctx = ctx + new+ sid.append(torch.tensor([new], dtype=torch.long))+ t1 = time.perf_counter(); got = fol.sync(sid); res = got.match(K); times.append(time.perf_counter() - t1)+ ref = sp.ngram_match(ctx, nmin, K); assert ref == res, f"recorded L={L} round {r}: old {ref} new {res}"+ n_hits += res[0] >= 5+ # second turn: new tensor = the whole context + new tokens (multi-turn reuse)+ ctx2 = ctx + [int(x) for x in np.random.RandomState(5).randint(0, 1000, 300)]+ sid2 = SeqTensor((1, 1), torch.long, -1, init_cap=len(ctx2) + 64); sid2.append(torch.tensor([ctx2], dtype=torch.long))+ tb = time.time(); got = fol.sync(sid2); turn2 = time.time() - tb+ assert sp.ngram_match(ctx2, nmin, K) == got.match(K)+ ref = sp.NgramIndex(nmin); ref.extend(np.array(ctx2, dtype=np.int64)); same_state(got, ref, "turn2 vs bulk rebuild")+ ref2 = sp.NgramIndex(nmin)+ for t in ctx2[:3000]: ref2.push(t)+ b = sp.NgramIndex(nmin); b.extend(np.array(ctx2[:3000], dtype=np.int64)); same_state(b, ref2, "bulk vs push (3000)")+ t_old = []+ for _ in range(20): t0o = time.perf_counter(); sp.ngram_match(sid.torch_slice(0, len(ctx)).flatten().tolist(), nmin, K); t_old.append(time.perf_counter() - t0o)+ print(f"recorded {L:>6}: ctx {len(ctx)} {rounds} rounds equal ({n_hits} with L>=5); cold build {cold:.2f}s, turn2 resync {turn2*1e3:.1f} ms, "+ f"new sync+match median {1e6*sorted(times)[len(times)//2]:.0f} us (max {1e6*max(times):.0f}), old tolist+scan median {1e3*sorted(t_old)[10]:.2f} ms; fallbacks {fol.idx.fallbacks}")++if __name__ == "__main__":+ ap = argparse.ArgumentParser(); ap.add_argument("--fuzz", type=int, default=10000); ap.add_argument("--docs", default=os.path.expanduser("$WORK_DIR"))+ ap.add_argument("--skip-recorded", action="store_true"); a = ap.parse_args()+ fuzz(a.fuzz)+ print("branches:", json.dumps(BR, sort_keys=True))+ if not a.skip_recorded: recorded(a.docs)+ print("ALL OK")diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pynew file mode 100644index 0000000..ce914f8--- /dev/null+++ b/tools/qwen/test_serve.py@@ -0,0 +1,459 @@+#!/usr/bin/env python3+"""qserve unit tests: model-free, fake engine (no GPU, no exllamav3 import)."""+from __future__ import annotations++import asyncio+import base64+import json+import os+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).parent))+import serve++PACK = Path(os.environ.get("QWEN_PACK", os.path.expanduser("~/models/qwen38-yamz-v1")))+THINK_TEMPLATE = ("{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}"+ "{% if tools %}TOOLS={{ tools|length }}{% endif %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n"+ "{% if enable_thinking is defined and enable_thinking is false %}<think>\n\n</think>\n\n"+ "{% else %}<think>\n{% endif %}{% endif %}"+ "{% if reasoning_effort is defined %}EFFORT={{ reasoning_effort }}{% endif %}")+TOOLS = [{"type": "function", "function": {"name": "get_weather", "parameters": {+ "type": "object", "properties": {"city": {"type": "string"}, "days": {"type": "integer"},+ "opts": {"type": "object"}}}}}]+CALL = ("<tool_call>\n<function=get_weather>\n<parameter=city>\n391\n</parameter>\n<parameter=days>\n3\n</parameter>\n"+ "<parameter=opts>\n{\"a\": [1, 2]}\n</parameter>\n</function>\n</tool_call>")+++class FakeEngine:+ ctx = 4096+ supports_vision = True+ spec_on = True++ def __init__(self, output: str, stats: dict | None = None):+ self.output, self.calls, self.last_stats = output, [], {}+ self.stats = stats or {"new_tokens": 7, "prompt_tokens": 11, "cached_tokens": 5, "eos_reason": "stop_token",+ "time_prefill": 0.5, "time_generate": 1.0, "token_ids": [1, 2, 3]}++ def count_tokens(self, text: str) -> int:+ return len(text.split())++ def spec_stats(self):+ return {"speculative": True}++ async def generate(self, prompt, **kw):+ self.calls.append((prompt, kw))+ self.last_stats = dict(self.stats)+ for i in range(0, len(self.output), 3): # small chunks cut tags in half+ yield self.output[i:i + 3]+++def run(coro):+ return asyncio.run(coro)+++def with_client(engine, fn, template=THINK_TEMPLATE, defaults=None):+ from aiohttp.test_utils import TestClient, TestServer++ async def go():+ client = TestClient(TestServer(serve.create_app(engine, "m", template, defaults or serve.load_defaults("/x"))))+ await client.start_server()+ try:+ return await fn(client)+ finally:+ await client.close()+ return run(go())+++def sse_events(raw: str):+ return [json.loads(line[6:]) for line in raw.split("\n\n") if line.startswith("data: ") and "[DONE]" not in line]+++class ParserTests(unittest.TestCase):+ def test_reasoning_first_split(self):+ m = serve.split_completion("let me think\nmore\n</think>\n\nThe answer.\n", True, None)+ self.assertEqual(m["reasoning_content"], "let me think\nmore")+ self.assertEqual(m["content"], "The answer.")++ def test_no_reasoning_when_thinking_off(self):+ m = serve.split_completion("Plain answer </think> stays", False, None)+ self.assertNotIn("reasoning_content", m)+ self.assertEqual(m["content"], "Plain answer </think> stays")++ def test_cut_during_thought_is_all_reasoning(self):+ m = serve.split_completion("still thinking", True, None)+ self.assertEqual((m["content"], m["reasoning_content"]), ("", "still thinking"))++ def test_stream_chunking_does_not_change_the_split(self):+ text = "ab\n</think>\n\nvisible text\n\n" + CALL+ whole = serve.split_completion(text, True, TOOLS)+ for size in (1, 2, 3, 5, 8):+ sp = serve.Splitter(True)+ pieces = []+ for i in range(0, len(text), size):+ pieces += sp.feed(text[i:i + size])+ pieces += sp.finish()+ self.assertEqual("".join(t for k, t in pieces if k == "content"), whole["content"], size)+ self.assertEqual("".join(t for k, t in pieces if k == "reasoning"), whole["reasoning_content"], size)+ self.assertEqual(serve.parse_tool_calls(sp.tool_text, TOOLS)[0]["function"]["arguments"],+ whole["tool_calls"][0]["function"]["arguments"])++ def test_tool_call_typed_arguments(self):+ calls = serve.parse_tool_calls(CALL, TOOLS)+ self.assertEqual(calls[0]["function"]["name"], "get_weather")+ # schema says string: "391" stays a string; integer and object are decoded+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"city": "391", "days": 3, "opts": {"a": [1, 2]}})++ def test_tool_call_json_body_and_truncated_call(self):+ c = serve.parse_tool_calls('<tool_call>{"name": "f", "arguments": {"x": 1}}</tool_call>', None)+ self.assertEqual((c[0]["function"]["name"], json.loads(c[0]["function"]["arguments"])), ("f", {"x": 1}))+ self.assertEqual(serve.parse_tool_calls("<tool_call>\n<function=f>\n<parameter=a>\n1", None), [])++ def test_two_tool_calls(self):+ m = serve.split_completion("</think>ok\n" + CALL + "\n" + CALL, True, TOOLS)+ self.assertEqual(len(m["tool_calls"]), 2)+ self.assertEqual(m["content"], "ok")+++class RequestTests(unittest.TestCase):+ def test_template_kwargs_precedence(self):+ d = {"enable_thinking": None, "reasoning_effort": "low"}+ self.assertEqual(serve.resolve_template_kwargs({}, d), {"reasoning_effort": "low"})+ self.assertEqual(serve.resolve_template_kwargs({"reasoning_effort": "high"}, d), {"reasoning_effort": "xhigh"})+ self.assertEqual(serve.resolve_template_kwargs({"chat_template_kwargs": {"enable_thinking": False}}, d),+ {"enable_thinking": False, "reasoning_effort": "low"})+ self.assertEqual(serve.resolve_template_kwargs({"reasoning_effort": "none"}, d), {"enable_thinking": False})+ with self.assertRaises(serve.BadRequest):+ serve.resolve_template_kwargs({"enable_thinking": "no"}, d)++ def test_sampling_defaults_come_from_generation_config(self):+ d = serve.load_defaults(str(PACK)) if PACK.is_dir() else serve.load_defaults("/x")+ self.assertEqual((d["temperature"], d["top_p"], d["top_k"]), (1.0, 0.95, 20))+ s = serve.sampling_from({"temperature": None, "top_k": 5}, d)+ self.assertEqual((s["temperature"], s["top_p"], s["top_k"]), (1.0, 0.95, 5))+ self.assertEqual(serve.sampling_from({"temperature": 0}, d)["temperature"], 0)+ with self.assertRaises(serve.BadRequest):+ serve.sampling_from({"top_p": 0}, d)++ def test_cli_flags_override_defaults(self):+ class A:+ default_temperature, default_top_p, default_top_k, default_min_p = 0.6, None, None, None+ default_reasoning_effort, no_thinking = "low", True+ d = serve.load_defaults(str(PACK) if PACK.is_dir() else "/x", A)+ self.assertEqual((d["temperature"], d["reasoning_effort"], d["enable_thinking"]), (0.6, "low", False))++ def test_extract_images_in_order(self):+ msgs = [{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": "u1"}}]},+ {"role": "user", "content": [{"type": "image_url", "image_url": {"url": "u2"}}]}]+ self.assertEqual(serve.extract_images(msgs), ["u1", "u2"])++ def test_load_image_data_uri_and_rejects(self):+ from PIL import Image+ import io+ buf = io.BytesIO()+ Image.new("RGB", (4, 4), (1, 2, 3)).save(buf, "PNG")+ img = serve.load_image("data:image/png;base64," + base64.b64encode(buf.getvalue()).decode())+ self.assertEqual(img.size, (4, 4))+ for bad in ("file:///etc/passwd", "data:image/png;base64,AAAA", ""):+ with self.assertRaises(serve.BadRequest):+ serve.load_image(bad)++ @unittest.skipUnless((PACK / "chat_template.jinja").is_file(), "no pack")+ def test_template_matches_hf_apply_chat_template(self):+ from transformers import AutoTokenizer+ hf = AutoTokenizer.from_pretrained(str(PACK))+ tpl = (PACK / "chat_template.jinja").read_text()+ history = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": "", "reasoning_content": "need the tool",+ "tool_calls": [{"id": "c1", "type": "function",+ "function": {"name": "get_weather", "arguments": json.dumps({"city": "Paris", "days": 2})}}]},+ {"role": "tool", "tool_call_id": "c1", "content": "sunny"},+ {"role": "user", "content": "thanks, and a joke?"}]+ for msgs, tools, kw in (+ ([{"role": "user", "content": "hi"}], None, {}),+ ([{"role": "user", "content": "hi"}], None, {"enable_thinking": False}),+ ([{"role": "user", "content": "hi"}], None, {"reasoning_effort": "low"}),+ ([{"role": "user", "content": "hi"}], TOOLS, {"enable_thinking": False}),+ (history, TOOLS, {}),+ ([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "x"}}, {"type": "text", "text": "what?"}]}],+ None, {"enable_thinking": False})):+ ref_msgs = [dict(m) for m in msgs]+ for m in ref_msgs: # HF wants dict arguments+ for c in m.get("tool_calls", []):+ c["function"] = dict(c["function"], arguments=json.loads(c["function"]["arguments"]))+ expect = hf.apply_chat_template(ref_msgs, tools=tools, tokenize=False, add_generation_prompt=True, **kw)+ self.assertEqual(serve.render_prompt(tpl, serve.normalize_messages(msgs), tools, **kw), expect)+++class HttpTests(unittest.TestCase):+ def chat(self, engine, payload, stream=False):+ async def fn(client):+ r = await client.post("/v1/chat/completions", json={"stream": stream, "model": "m"} | payload)+ return r.status, (await r.text() if stream else await r.json())+ return with_client(engine, fn)++ def test_models_and_health(self):+ async def fn(client):+ return await (await client.get("/v1/models")).json(), await (await client.get("/health")).json()+ models, health = with_client(FakeEngine(""), fn)+ self.assertEqual(models["data"][0]["id"], "m")+ self.assertEqual((health["status"], health["speculative"], health["vision"]), ("ok", True, True))++ def test_non_stream_reasoning_split_usage_timings(self):+ st, body = self.chat(FakeEngine("why\n</think>\n\nhello"), {"messages": [{"role": "user", "content": "hi"}]})+ self.assertEqual(st, 200)+ msg = body["choices"][0]["message"]+ self.assertEqual((msg["content"], msg["reasoning_content"]), ("hello", "why"))+ self.assertEqual(body["choices"][0]["finish_reason"], "stop")+ self.assertEqual(body["usage"], {"prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18,+ "prompt_tokens_details": {"cached_tokens": 5}})+ t = body["timings"]+ self.assertEqual((t["cache_n"], t["prompt_n"], t["prompt_ms"], t["predicted_per_second"]), (5, 6, 500.0, 7.0))++ def test_finish_reason_length_when_cut(self):+ eng = FakeEngine("half a thou", {"new_tokens": 4, "eos_reason": "max_new_tokens"})+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4})+ self.assertEqual(body["choices"][0]["finish_reason"], "length")+ self.assertEqual(body["choices"][0]["message"]["content"], "")+ self.assertEqual(body["choices"][0]["message"]["reasoning_content"], "half a thou")+ self.assertEqual(eng.calls[0][1]["max_tokens"], 4)++ def test_thinking_off_has_no_reasoning(self):+ eng = FakeEngine("plain answer")+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}], "enable_thinking": False})+ self.assertEqual(body["choices"][0]["message"], {"role": "assistant", "content": "plain answer"})+ self.assertIn("<think>\n\n</think>", eng.calls[0][0])+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}],+ "chat_template_kwargs": {"enable_thinking": True}, "reasoning_effort": "low"})+ self.assertTrue(eng.calls[1][0].endswith("<think>\nEFFORT=low"))++ def test_sampling_defaults_and_overrides_reach_the_engine(self):+ eng = FakeEngine("x")+ self.chat(eng, {"messages": [{"role": "user", "content": "hi"}]})+ self.assertEqual(eng.calls[0][1]["sampling"], {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0})+ self.chat(eng, {"messages": [{"role": "user", "content": "hi"}], "temperature": 0, "top_p": None})+ self.assertEqual(eng.calls[1][1]["sampling"]["temperature"], 0)+ self.assertEqual(eng.calls[1][1]["sampling"]["top_p"], 0.95)++ def test_tool_call_round_trip(self):+ eng = FakeEngine("</think>\n\n" + CALL)+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "weather?"}], "tools": TOOLS})+ choice = body["choices"][0]+ self.assertEqual(choice["finish_reason"], "tool_calls")+ call = choice["message"]["tool_calls"][0]+ self.assertEqual(json.loads(call["function"]["arguments"])["days"], 3)+ history = [{"role": "user", "content": "weather?"}, choice["message"],+ {"role": "tool", "tool_call_id": call["id"], "content": "sunny"}]+ st, body = self.chat(eng, {"messages": history, "tools": TOOLS})+ self.assertEqual(st, 200)+ self.assertIn("<|im_start|>tool\nsunny", eng.calls[1][0])++ def test_stream_matches_non_stream(self):+ text = "reason\n</think>\n\nvisible words\n\n" + CALL+ eng = FakeEngine(text)+ payload = {"messages": [{"role": "user", "content": "hi"}], "tools": TOOLS}+ _, whole = self.chat(eng, payload)+ st, raw = self.chat(eng, payload, stream=True)+ self.assertTrue(raw.rstrip().endswith("data: [DONE]"))+ ev = sse_events(raw)+ self.assertEqual(ev[0]["choices"][0]["delta"]["role"], "assistant")+ reasoning = "".join(e["choices"][0]["delta"].get("reasoning_content", "") for e in ev)+ content = "".join(e["choices"][0]["delta"].get("content", "") for e in ev)+ msg = whole["choices"][0]["message"]+ self.assertEqual((reasoning, content), (msg["reasoning_content"], msg["content"]))+ calls = [c for e in ev for c in e["choices"][0]["delta"].get("tool_calls", [])]+ self.assertEqual(calls[0]["function"]["name"], "get_weather")+ self.assertEqual(ev[-1]["choices"][0]["finish_reason"], "tool_calls")+ self.assertEqual(ev[-1]["usage"]["completion_tokens"], 7)+ self.assertIn("timings", ev[-1])++ def test_stream_length(self):+ eng = FakeEngine("abc", {"new_tokens": 2, "eos_reason": "max_new_tokens"})+ _, raw = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}]}, stream=True)+ self.assertEqual(sse_events(raw)[-1]["choices"][0]["finish_reason"], "length")++ def test_return_token_ids_and_cache_flags(self):+ eng = FakeEngine("x")+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}], "return_token_ids": True,+ "speculative": False, "cache_prompt": False})+ self.assertEqual(body["token_ids"], [1, 2, 3])+ kw = eng.calls[0][1]+ self.assertEqual((kw["speculative"], kw["cache_prompt"]), (False, False))++ def test_bad_requests_are_400_json(self):+ eng = FakeEngine("x")+ good = [{"role": "user", "content": "hi"}]+ for payload in ({"messages": []}, {"messages": "x"}, {"messages": good, "stream": "yes"},+ {"messages": good, "model": "other"}, {"messages": good, "max_tokens": 0},+ {"messages": good, "temperature": "hot"}, {"messages": good, "stop": [1]},+ {"messages": good, "tools": "x"}, {"messages": [{"content": "no role"}]},+ {"messages": good, "chat_template_kwargs": 3}):+ st, body = self.chat(eng, payload)+ self.assertEqual(st, 400, payload)+ self.assertIn("message", body["error"])+ self.assertEqual(eng.calls, [])++ def test_prompt_longer_than_context_is_rejected(self):+ st, body = self.chat(FakeEngine("x"), {"messages": [{"role": "user", "content": "w " * 5000}]})+ self.assertEqual(st, 400)+ self.assertIn("context", body["error"]["message"])++ def test_max_tokens_clipped_to_context(self):+ eng = FakeEngine("x")+ self.chat(eng, {"messages": [{"role": "user", "content": "w " * 4000}], "max_tokens": 9999})+ self.assertLessEqual(eng.calls[0][1]["max_tokens"], 4096 - 4000)++ def test_image_without_vision_and_placeholder_mismatch(self):+ eng = FakeEngine("x")+ part = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ msgs = [{"role": "user", "content": [part, {"type": "text", "text": "what"}]}]+ st, body = self.chat(eng, {"messages": msgs}) # fake template has no image placeholder+ self.assertEqual(st, 400)+ eng.supports_vision = False+ st, body = self.chat(eng, {"messages": msgs})+ self.assertIn("vision", body["error"]["message"])++ def test_images_reach_the_engine_in_order(self):+ tpl = THINK_TEMPLATE.replace("{{ m.content }}", "{{ m.content if m.content is string else '<|image_pad|>' }}")+ eng = FakeEngine("ok")++ async def fn(client):+ msgs = [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:u1"}},+ {"type": "text", "text": "what"}]}]+ r = await client.post("/v1/chat/completions", json={"model": "m", "messages": msgs})+ return r.status+ self.assertEqual(with_client(eng, fn, template=tpl), 200)+ self.assertEqual(eng.calls[0][1]["images"], ["data:u1"])++ def test_apply_template(self):+ async def fn(client):+ r = await client.post("/apply-template", json={"messages": [{"role": "user", "content": "hi"}],+ "enable_thinking": False})+ return await r.json()+ self.assertTrue(with_client(FakeEngine(""), fn)["prompt"].endswith("<think>\n\n</think>\n\n"))++ def test_invalid_json_is_400(self):+ async def fn(client):+ r = await client.post("/v1/chat/completions", data="{nope", headers={"Content-Type": "application/json"})+ return r.status+ self.assertEqual(with_client(FakeEngine(""), fn), 400)++ def test_requests_are_serialized(self):+ class Slow(FakeEngine):+ active = peak = 0++ async def generate(self, prompt, **kw):+ Slow.active += 1+ Slow.peak = max(Slow.peak, Slow.active)+ await asyncio.sleep(0.05)+ yield "x"+ Slow.active -= 1++ async def fn(client):+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}+ rs = await asyncio.gather(*[client.post("/v1/chat/completions", json=body) for _ in range(4)])+ return [r.status for r in rs]+ self.assertEqual(with_client(Slow("x"), fn), [200] * 4)+ self.assertEqual(Slow.peak, 1)++ def test_client_disconnect_cancels_the_job(self):+ class Endless(FakeEngine):+ stopped = False++ async def generate(self, prompt, cancel=None, **kw):+ for _ in range(2000):+ if cancel is not None and cancel.is_set():+ Endless.stopped = True+ return+ await asyncio.sleep(0.005)+ yield "word "++ async def fn(client):+ body = {"model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]}+ r = await client.post("/v1/chat/completions", json=body)+ await r.content.readline()+ r.close()+ for _ in range(100):+ await asyncio.sleep(0.05)+ if Endless.stopped:+ break+ r2 = await client.post("/v1/chat/completions", json={"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 1})+ return Endless.stopped+ self.assertTrue(with_client(Endless(""), fn))++ def test_completion_verbatim_prompt_and_slots(self):+ class Store:+ busy = False++ def slots(self):+ return [{"id": 0}]++ def erase(self):+ return {"id_slot": 0, "n_erased": 3}++ def save(self, name):+ return {"saved": name}++ eng = FakeEngine("raw text STOP tail", {"new_tokens": 3, "prompt_tokens": 9, "cached_tokens": 4, "eos_reason": "stop_token"})+ eng.slot_store = Store()++ async def fn(client):+ r = await (await client.post("/completion", json={"prompt": "<|im_start|>hi", "n_predict": 5, "stop": "STOP"})).json()+ e = await (await client.post("/slots/0?action=erase")).json()+ sv = await (await client.post("/slots/0?action=save", json={"filename": "a.bin"})).json()+ bad = await client.post("/slots/1?action=erase")+ bad2 = await client.post("/slots/0?action=nope")+ empty = await client.post("/completion", json={})+ return r, e, sv, bad.status, bad2.status, empty.status, await (await client.get("/slots")).json()+ r, e, sv, b1, b2, b3, sl = with_client(eng, fn)+ self.assertEqual((r["content"], r["tokens_cached"], r["stopped_word"], r["timings"]["prompt_n"]), ("raw text ", 4, "STOP", 5))+ self.assertEqual(eng.calls[0][0], "<|im_start|>hi")+ self.assertEqual((e["n_erased"], sv["saved"], b1, b2, b3, sl), (3, "a.bin", 400, 400, 400, [{"id": 0}]))++ def test_engine_error_is_500_json(self):+ class Boom(FakeEngine):+ async def generate(self, prompt, **kw):+ raise RuntimeError("kaput")+ yield ""+ st, body = self.chat(Boom(""), {"messages": [{"role": "user", "content": "hi"}]})+ self.assertEqual(st, 500)+ self.assertIn("kaput", body["error"]["message"])+++class MiscTests(unittest.TestCase):+ def test_sse_framing_and_stop_text(self):+ self.assertEqual(serve.sse({"a": 1}), b'data: {"a":1}\n\n')+ self.assertEqual(serve.stop_text("hello STOP x", ["STOP"]), ("hello ", "STOP"))++ def test_config_max_position(self):+ class C:+ config_dict = {"text_config": {"max_position_embeddings": 262144}}+ self.assertEqual(serve.config_max_position(C), 262144)++ def test_partial_tag_hold(self):+ self.assertEqual(serve._partial_tag("abc</thi", ["</think>"]), 5)+ self.assertEqual(serve._partial_tag("abc", ["</think>"]), 0)+++class ServeEnvDefaultsTest(unittest.TestCase):+ def test_prefill_set_is_default_and_overridable(self):+ d = dict(serve.SERVE_ENV)+ for k in ("EXL3_PLE_HIP", "EXL3_DQ_HIP", "EXL3_GR_HIP", "EXL3_GDN_FUSE", "EXL3_PF_SKIP"):+ self.assertEqual(d[k], "1")+ self.assertEqual(d["EXL3_PF_DEFER"], "1")+ self.assertEqual(d["EXL3_PREFILL_CHUNK"], "4096")+ self.assertEqual(len(d), len(serve.SERVE_ENV)) # no key twice+ saved = os.environ.get("EXL3_GDN_FUSE"); os.environ["EXL3_GDN_FUSE"] = "0"+ try:+ for k, v in serve.SERVE_ENV:+ os.environ.setdefault(k, v)+ self.assertEqual(os.environ["EXL3_GDN_FUSE"], "0") # the caller's value wins+ finally:+ if saved is None: os.environ.pop("EXL3_GDN_FUSE", None)+ else: os.environ["EXL3_GDN_FUSE"] = saved+++if __name__ == "__main__":+ unittest.main()