Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

GLM decode: VALU MLA absorb/unfold for 1-8 rows, opt-in EXL3_MLA_DEC_VALU=1

YanissAmz3da54b6e6aa6
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index bc2bb96..f8200c8 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -90,6 +90,7 @@
#include "dsa_topk_gfx12.cuh"
#include "add.cuh"
#include "fused_elt.cuh"
+#include "mla_dec_valu.cuh"
#include "kda_inter.cuh"
#include "quant/pack.cuh"
@@ -429,6 +430,10 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("skinny_set_onepass", &skinny_set_onepass, "skinny_set_onepass");
m.def("kda_gate", &kda_gate, "kda_gate");
m.def("kda_fb_gate", &kda_fb_gate, "kda_fb_gate");
+#if defined(USE_ROCM)
+ m.def("mla_absorb_dec", &mla_absorb_dec, "mla_absorb_dec");
+ m.def("mla_unfold_dec", &mla_unfold_dec, "mla_unfold_dec");
+#endif
m.def("kda_gb_norm", &kda_gb_norm, "kda_gb_norm");
m.def("kda_inter_off", &kda_inter_off, "kda_inter_off");
m.def("exl3_moe_gfx12_k3_prefill", &exl3_moe_gfx12_k3_prefill,
diff --git a/exllamav3/exllamav3_ext/mla_dec_valu.cu b/exllamav3/exllamav3_ext/mla_dec_valu.cu
new file mode 100644
index 0000000..8d09fda
--- /dev/null
+++ b/exllamav3/exllamav3_ext/mla_dec_valu.cu
@@ -0,0 +1,198 @@
+#if defined(USE_ROCM)
+#include <hip/hip_runtime.h>
+#include <hip/hip_fp16.h>
+#include <cstdint>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "util.h"
+#include "util.cuh"
+#include "mla_dec_valu.cuh"
+
+// MLA decode absorb / unfold for R <= 8 rows on VALU, bit-identical to the Triton WMMA kernels
+// (_mla_absorb_kernel / _mla_unfold_kernel in attention_fn/mla_triton.py).
+//
+// Numerics: v_wmma_f32_16x16x16_f16 equals a chain of 8 v_dot2_f32_f16 over k ascending from the running fp32 accumulator
+// (exl3_moe_valu.cuh, proven on device). Each output element here is one such chain over the whole K, started from 0.0f, then one
+// round-to-nearest-even half conversion, exactly tl.dot(acc over K) + acc.to(fp16). A row's bits do not depend on the other rows
+// or on R. Verified bitwise against the Triton kernels, R = 1..8, tools/glm/ext_test.py (CPU bounds: tools/glm/cpu_bounds.py).
+//
+// Why VALU: the Triton kernels read W_UK / W_UV at 140-145 GB/s in isolation (and about half of that in the model). One lane owns a
+// whole serial chain, so the weight stream is the only cost: absorb stages 32 W rows (one head) coalesced through LDS, 8 heads
+// adjacent in the grid so concurrently running waves share the same 4 KB row pages; unfold reads W rows coalesced (a lane owns a
+// v pair) with the rows 2k, 2k+1 packed into half2 for the dot2 chain.
+
+typedef _Float16 mdv_h2 __attribute__((ext_vector_type(2)));
+__device__ __forceinline__ float mdv_dot2(uint32_t a, uint32_t b, float c)
+{
+ return __builtin_amdgcn_fdot2(__builtin_bit_cast(mdv_h2, a), __builtin_bit_cast(mdv_h2, b), c, false);
+}
+__device__ __forceinline__ uint16_t mdv_h(float f) { return __half_as_ushort(__float2half_rn(f)); }
+
+// absorb: coalesced. One wave (32 lanes) = 32 consecutive n of one head. The wave loads the 32 row segments (2 * DN bytes each)
+// coalesced into LDS (pitch DN/8 + 1 uint4, conflict-free for lane-per-row b128 reads), then lane l runs the serial chain of row n0 + l.
+// grid (H, DC / 32) with HF (head fastest), 32 threads.
+#define MDV2_ROWS 32
+template <int R, int DN, int UN, bool HF>
+__global__ __launch_bounds__(MDV2_ROWS)
+void mla_absorb2_valu_kernel
+(
+ const uint16_t* __restrict__ q, const uint16_t* __restrict__ w, uint16_t* __restrict__ out,
+ const int qs, const int qk, const int heads, const int dc
+)
+{
+ constexpr int CH = DN / 8; // uint4 per row segment (32 for DN 256)
+ static_assert(CH == 32, "one lane per uint4 of a row segment");
+ __shared__ __align__(16) uint4 qsh[R][CH];
+ __shared__ __align__(16) uint4 wsh[MDV2_ROWS][CH + 1];
+ const int h = HF ? blockIdx.x : blockIdx.y;
+ const int l = threadIdx.x;
+ const int n0 = (HF ? blockIdx.y : blockIdx.x) * MDV2_ROWS;
+ #pragma unroll
+ for (int r = 0; r < R; ++r) qsh[r][l] = *((const uint4*) (q + (size_t) r * qs + (size_t) h * qk) + l);
+ #pragma unroll 1
+ for (int i0 = 0; i0 < MDV2_ROWS; i0 += UN)
+ {
+ uint4 v[UN];
+ #pragma unroll
+ for (int j = 0; j < UN; ++j)
+ v[j] = *((const uint4*) (w + (size_t) (n0 + i0 + j) * heads * DN + (size_t) h * DN) + l);
+ #pragma unroll
+ for (int j = 0; j < UN; ++j) wsh[i0 + j][l] = v[j];
+ }
+ __syncthreads();
+ float acc[R];
+ #pragma unroll
+ for (int r = 0; r < R; ++r) acc[r] = 0.0f;
+ #pragma unroll 4
+ for (int c = 0; c < CH; ++c)
+ {
+ const uint4 wv = wsh[l][c];
+ #pragma unroll
+ for (int r = 0; r < R; ++r)
+ {
+ const uint4 a = qsh[r][c];
+ float s = acc[r];
+ s = mdv_dot2(wv.x, a.x, s);
+ s = mdv_dot2(wv.y, a.y, s);
+ s = mdv_dot2(wv.z, a.z, s);
+ s = mdv_dot2(wv.w, a.w, s);
+ acc[r] = s;
+ }
+ }
+ #pragma unroll
+ for (int r = 0; r < R; ++r) out[((size_t) h * R + r) * dc + n0 + l] = mdv_h(acc[r]);
+}
+
+// out[r, h, v] = sum_k o[h, r, k] * w[k, h * DV + v]; one lane = a v pair, serial chain over k (pairs of rows k, k+1).
+// grid (H), DV / 2 threads. DC % (2 * UN) == 0.
+template <int R, int DV, int UN>
+__global__ __launch_bounds__(DV / 2)
+void mla_unfold_valu_kernel
+(
+ const uint16_t* __restrict__ o, const uint16_t* __restrict__ w, uint16_t* __restrict__ out,
+ const int heads, const int dc
+)
+{
+ extern __shared__ __align__(16) uint32_t osh[]; // [R][dc / 2]
+ const int h = blockIdx.x;
+ const int t = threadIdx.x;
+ const int dc2 = dc / 2;
+ for (int i = t; i < R * dc2; i += DV / 2) osh[i] = ((const uint32_t*) (o + (size_t) h * R * dc))[i];
+ __syncthreads();
+ const uint32_t* wp = (const uint32_t*) (w + (size_t) h * DV) + t;
+ const size_t rs = (size_t) heads * DV / 2; // row stride in uint32
+ float a0[R], a1[R];
+ #pragma unroll
+ for (int r = 0; r < R; ++r) { a0[r] = 0.0f; a1[r] = 0.0f; }
+ #pragma unroll 1
+ for (int k2 = 0; k2 < dc2; k2 += UN)
+ {
+ uint32_t wa[UN], wb[UN];
+ #pragma unroll
+ for (int j = 0; j < UN; ++j)
+ {
+ wa[j] = wp[(size_t) (2 * (k2 + j)) * rs];
+ wb[j] = wp[(size_t) (2 * (k2 + j) + 1) * rs];
+ }
+ #pragma unroll
+ for (int j = 0; j < UN; ++j)
+ {
+ const uint32_t p0 = (wa[j] & 0xffffu) | (wb[j] << 16);
+ const uint32_t p1 = (wa[j] >> 16) | (wb[j] & 0xffff0000u);
+ #pragma unroll
+ for (int r = 0; r < R; ++r)
+ {
+ const uint32_t ov = osh[r * dc2 + k2 + j];
+ a0[r] = mdv_dot2(p0, ov, a0[r]);
+ a1[r] = mdv_dot2(p1, ov, a1[r]);
+ }
+ }
+ }
+ #pragma unroll
+ for (int r = 0; r < R; ++r)
+ ((uint32_t*) out)[(((size_t) r * heads + h) * DV) / 2 + t] = (uint32_t) mdv_h(a0[r]) | ((uint32_t) mdv_h(a1[r]) << 16);
+}
+
+
+#define MDV_ABS_UN 4
+#define MDV_UNF_UN 4
+
+void mla_absorb_dec
+(
+ const at::Tensor& q, // (R, H, qk_dim) fp16, head stride qk_dim, row stride any multiple of 8
+ const at::Tensor& w_uk_flat, // (D_c, H * 256) fp16 contiguous
+ at::Tensor& out // (H, R, D_c) fp16 contiguous
+)
+{
+ const at::Device device = q.device();
+ const at::cuda::OptionalCUDAGuard device_guard(device);
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+ TORCH_CHECK(q.dim() == 3 && q.scalar_type() == at::kHalf && w_uk_flat.scalar_type() == at::kHalf && out.scalar_type() == at::kHalf,
+ "mla_absorb_dec: fp16 q (R, H, qk_dim), w, out");
+ const int R = q.size(0), H = q.size(1), qk = q.size(2);
+ const int dc = w_uk_flat.size(0);
+ TORCH_CHECK(R >= 1 && R <= 8, "mla_absorb_dec: 1..8 rows");
+ TORCH_CHECK(q.stride(2) == 1 && q.stride(1) == qk && qk % 8 == 0 && qk >= 256 && q.stride(0) % 8 == 0, "mla_absorb_dec: q layout");
+ TORCH_CHECK(((uintptr_t) q.data_ptr()) % 16 == 0 && ((uintptr_t) w_uk_flat.data_ptr()) % 16 == 0, "mla_absorb_dec: 16-byte alignment");
+ TORCH_CHECK(w_uk_flat.is_contiguous() && w_uk_flat.dim() == 2 && w_uk_flat.size(1) == (int64_t) H * 256 && dc % 32 == 0, "mla_absorb_dec: w shape");
+ TORCH_CHECK(out.is_contiguous() && out.numel() == (int64_t) H * R * dc, "mla_absorb_dec: out shape");
+ const uint16_t* qp = (const uint16_t*) q.data_ptr();
+ const uint16_t* wp = (const uint16_t*) w_uk_flat.data_ptr();
+ uint16_t* op = (uint16_t*) out.data_ptr();
+ const int qs = q.stride(0);
+ const dim3 grid(H, dc / MDV2_ROWS);
+ #define MDV_A(RR) case RR: mla_absorb2_valu_kernel<RR, 256, MDV_ABS_UN, true><<<grid, MDV2_ROWS, 0, stream>>>(qp, wp, op, qs, qk, H, dc); break;
+ switch (R) { MDV_A(1) MDV_A(2) MDV_A(3) MDV_A(4) MDV_A(5) MDV_A(6) MDV_A(7) MDV_A(8) }
+ #undef MDV_A
+ cuda_check(cudaPeekAtLastError());
+}
+
+void mla_unfold_dec
+(
+ const at::Tensor& o_lat, // (H, R, D_c) fp16 contiguous
+ const at::Tensor& w_uv_flat, // (D_c, H * 256) fp16 contiguous
+ at::Tensor& out // (R, H, 256) fp16 contiguous
+)
+{
+ const at::Device device = o_lat.device();
+ const at::cuda::OptionalCUDAGuard device_guard(device);
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+ TORCH_CHECK(o_lat.dim() == 3 && o_lat.scalar_type() == at::kHalf && w_uv_flat.scalar_type() == at::kHalf && out.scalar_type() == at::kHalf,
+ "mla_unfold_dec: fp16 o_lat (H, R, D_c), w, out");
+ const int H = o_lat.size(0), R = o_lat.size(1), dc = o_lat.size(2);
+ TORCH_CHECK(R >= 1 && R <= 8, "mla_unfold_dec: 1..8 rows");
+ TORCH_CHECK(o_lat.is_contiguous() && w_uv_flat.is_contiguous() && out.is_contiguous(), "mla_unfold_dec: contiguous only");
+ TORCH_CHECK(w_uv_flat.dim() == 2 && w_uv_flat.size(0) == dc && w_uv_flat.size(1) == (int64_t) H * 256 && dc % (2 * MDV_UNF_UN) == 0,
+ "mla_unfold_dec: w shape");
+ TORCH_CHECK(out.numel() == (int64_t) R * H * 256, "mla_unfold_dec: out shape");
+ TORCH_CHECK(((uintptr_t) o_lat.data_ptr()) % 4 == 0 && ((uintptr_t) w_uv_flat.data_ptr()) % 4 == 0 && ((uintptr_t) out.data_ptr()) % 4 == 0,
+ "mla_unfold_dec: 4-byte alignment");
+ const uint16_t* op_ = (const uint16_t*) o_lat.data_ptr();
+ const uint16_t* wp = (const uint16_t*) w_uv_flat.data_ptr();
+ uint16_t* outp = (uint16_t*) out.data_ptr();
+ #define MDV_U(RR) case RR: mla_unfold_valu_kernel<RR, 256, MDV_UNF_UN><<<H, 128, RR * dc * 2, stream>>>(op_, wp, outp, H, dc); break;
+ switch (R) { MDV_U(1) MDV_U(2) MDV_U(3) MDV_U(4) MDV_U(5) MDV_U(6) MDV_U(7) MDV_U(8) }
+ #undef MDV_U
+ cuda_check(cudaPeekAtLastError());
+}
+#endif
diff --git a/exllamav3/exllamav3_ext/mla_dec_valu.cuh b/exllamav3/exllamav3_ext/mla_dec_valu.cuh
new file mode 100644
index 0000000..d6c3780
--- /dev/null
+++ b/exllamav3/exllamav3_ext/mla_dec_valu.cuh
@@ -0,0 +1,6 @@
+#pragma once
+#include <ATen/Tensor.h>
+
+// glmsmall1: MLA decode absorb / unfold on VALU for R <= 8 rows, bit-identical to the Triton kernels (ROCm only)
+void mla_absorb_dec(const at::Tensor& q, const at::Tensor& w_uk_flat, at::Tensor& out);
+void mla_unfold_dec(const at::Tensor& o_lat, const at::Tensor& w_uv_flat, at::Tensor& out);
diff --git a/exllamav3/modules/attention_fn/mla_triton.py b/exllamav3/modules/attention_fn/mla_triton.py
index b0adb4b..e965c78 100644
--- a/exllamav3/modules/attention_fn/mla_triton.py
+++ b/exllamav3/modules/attention_fn/mla_triton.py
@@ -1259,12 +1259,42 @@ _PF_UNFOLD = {
}
+def _mla_ext():
+ from ...ext import exllamav3_ext
+ return exllamav3_ext
+
+
+def _dec_valu_on() -> bool:
+ """EXL3_MLA_DEC_VALU=1 (default off, read per call): decode / verify rows (R <= 8) of the MLA absorb and unfold run on the
+ VALU dot2-chain kernels (ext.mla_absorb_dec / mla_unfold_dec). Bit-identical to the Triton WMMA kernels."""
+ return os.environ.get("EXL3_MLA_DEC_VALU", "0") == "1" and torch.version.hip is not None
+
+
+def _dec_valu_ok(R, w_uk_flat, H, qk_nope, qk_dim, q) -> bool:
+ if R > 8 or not _dec_valu_on() or not hasattr(_mla_ext(), "mla_absorb_dec"):
+ return False
+ return (qk_nope == 256 and w_uk_flat.dtype == torch.half and w_uk_flat.is_contiguous() and w_uk_flat.shape[1] == H * 256 and
+ w_uk_flat.shape[0] % 32 == 0 and q.dtype == torch.half and q.stride(2) == 1 and q.stride(1) == qk_dim and
+ qk_dim % 8 == 0 and q.stride(0) % 8 == 0 and q.data_ptr() % 16 == 0 and w_uk_flat.data_ptr() % 16 == 0)
+
+
+def _dec_valu_unfold_ok(R, o_lat, w_uv_flat, H, v_head_dim) -> bool:
+ if R > 8 or not _dec_valu_on() or not hasattr(_mla_ext(), "mla_unfold_dec"):
+ return False
+ return (v_head_dim == 256 and o_lat.dtype == torch.half and w_uv_flat.dtype == torch.half and o_lat.is_contiguous() and
+ w_uv_flat.is_contiguous() and tuple(w_uv_flat.shape) == (o_lat.shape[2], H * 256) and o_lat.shape[2] % 8 == 0 and
+ o_lat.data_ptr() % 4 == 0 and w_uv_flat.data_ptr() % 4 == 0)
+
+
def mla_absorb(q: torch.Tensor, w_uk_flat: torch.Tensor, n_q_heads: int, qk_nope_head_dim: int):
"""(R, H, qk_head_dim) token-major queries -> (H, R, kv_lora_rank) head-major absorbed
queries, W_UK read from the flat layout."""
R, H, qk_dim = q.shape
D_c = w_uk_flat.shape[0]
out = torch.empty((H, R, D_c), dtype = torch.half, device = q.device)
+ if _dec_valu_ok(R, w_uk_flat, H, qk_nope_head_dim, qk_dim, q):
+ _mla_ext().mla_absorb_dec(q, w_uk_flat, out) # VALU dot2 chain, bitwise equal to the Triton dot
+ return out
block_m = min(64, triton.next_power_of_2(max(R, 16)))
# EXL3_MLA_ABSORB_CFG="bn,warps[,stages]" (read per call, default "128,4,2" = legacy): the N tile
# only splits output columns, the K reduction stays one dot over D_nope
@@ -1322,6 +1352,9 @@ def mla_unfold(o_lat: torch.Tensor, w_uv_flat: torch.Tensor, v_head_dim: int):
"""(H, R, kv_lora_rank) head-major latent output -> (R, H, v_head_dim) token-major."""
H, R, D_c = o_lat.shape
out = torch.empty((R, H, v_head_dim), dtype = torch.half, device = o_lat.device)
+ if _dec_valu_unfold_ok(R, o_lat, w_uv_flat, H, v_head_dim):
+ _mla_ext().mla_unfold_dec(o_lat, w_uv_flat, out) # see mla_absorb_dec
+ return out
block_m, block_k, block_n, stages, warps = _unfold_cfg(R, v_head_dim)
# A forced/default tile that does not fit in shared memory halves its k tile (probed once
# per (device, dims, tile) and remembered)
diff --git a/tools/glm/cpu_bounds.py b/tools/glm/cpu_bounds.py
new file mode 100644
index 0000000..5213e1f
--- /dev/null
+++ b/tools/glm/cpu_bounds.py
@@ -0,0 +1,101 @@
+"""CPU bounds proof for mla_dec_valu.cuh (index arithmetic transcribed 1:1), real GLM shapes, all R, all UN.
+Every global access index is enumerated for every (block, thread); asserts: in range, outputs written exactly once.
+Mutations (off-by-one in each index formula) must FAIL the same checks."""
+import numpy as np, itertools, sys
+import os
+H, DN, DC, DV = 64, 256, 512, 256
+QK = int(os.environ.get("QK", "256")) # GLM-5.3: NoPE q head = 256; QK=320 checks a rope-padded head
+QS_OPTS = (H * QK, H * QK + 64) # unpadded and padded q row stride (halves)
+def absorb(R, UN, qs, mut=None):
+ T = 256
+ nq = (R - 1) * qs + (H - 1) * QK + DN # q extent needed
+ qbuf = (R - 1) * qs + H * QK + 1 # a deliberately generous buffer: rows allocated (R, qs)
+ qbuf = R * qs
+ wbuf = DC * H * DN
+ obuf = H * R * DC
+ h, bx, tx = np.meshgrid(np.arange(H), np.arange(DC // T), np.arange(T), indexing="ij")
+ h, bx, tx = h.ravel(), bx.ravel(), tx.ravel()
+ n = bx * T + tx
+ # q staging: i < R*(DN/8), uint4 index = r*qs/8 .. in halves: r*qs + h*QK + 8*c
+ for hh in range(H):
+ i = np.arange(R * (DN // 8)); r = i // (DN // 8); c = i % (DN // 8)
+ idx = r * qs + hh * QK + 8 * c + (1 if mut == "q" else 0)
+ assert idx.min() >= 0 and idx.max() + 7 < qbuf, ("q oob", idx.max() + 7, qbuf)
+ assert (idx % 8 == 0).all(), "q uint4 misaligned"
+ assert qs % 8 == 0 and QK % 8 == 0
+ # w loads: uint4 index c0 + j over c0 in range(0, DN/8, UN): halves = n*H*DN + h*DN + 8*(c0+j)
+ cs = np.array([c0 + j for c0 in range(0, DN // 8, UN) for j in range(UN)])
+ assert cs.max() == DN // 8 - 1 and len(cs) == DN // 8 and DN // 8 % UN == 0, "UN does not tile DN/8"
+ wlo = n * H * DN + h * DN + (1 if mut == "w" else 0)
+ whi = wlo + 8 * cs.max() + 7
+ assert wlo.min() >= 0 and whi.max() < wbuf, ("w oob", whi.max(), wbuf)
+ # every w element read exactly once
+ seen = np.zeros(wbuf, np.int8)
+ for c in cs:
+ np.add.at(seen, wlo + 8 * c, 1) # first half of each uint4 (alignment-level check)
+ assert (wlo % 8 == 0).all()
+ # outputs
+ o = (h[:, None] * R + np.arange(R)[None, :]) * DC + n[:, None] + (DC if mut == "o" else 0)
+ assert o.min() >= 0 and o.max() < obuf, ("out oob", o.max(), obuf)
+ cnt = np.bincount(o.ravel(), minlength=obuf)
+ assert (cnt == 1).all(), "outputs not written exactly once"
+def absorb2(R, UN, qs, mut=None):
+ CH, ROWS = DN // 8, 32
+ assert CH == 32 and ROWS % UN == 0 and DC % ROWS == 0
+ qbuf, wbuf, obuf = R * qs, DC * H * DN, H * R * DC
+ h, bx, l = np.meshgrid(np.arange(H), np.arange(DC // ROWS), np.arange(32), indexing="ij"); h, bx, l = h.ravel(), bx.ravel(), l.ravel()
+ for hh in range(H):
+ for r in range(R):
+ idx = r * qs + hh * QK + 8 * np.arange(32) + (1 if mut == "q" else 0)
+ assert idx.max() + 7 < qbuf and (idx % 8 == 0).all(), "q oob/misaligned"
+ seen = np.zeros(wbuf // 8, np.int32)
+ for i in range(ROWS): # row i of the block, lane l loads uint4 l
+ n = bx * ROWS + i
+ idx = n * H * DN + h * DN + 8 * l + (8 if mut == "w" else 0)
+ assert idx.min() >= 0 and idx.max() + 7 < wbuf and (idx % 8 == 0).all(), ("w oob", idx.max() + 7, wbuf)
+ np.add.at(seen, idx // 8, 1)
+ assert (seen == 1).all(), "w uint4 not read exactly once"
+ # LDS: writes wsh[i][l] (pitch CH+1), reads wsh[l][c], c < CH: all within [32][33]
+ assert (31 * (CH + 1) + CH - 1) < 32 * (CH + 1)
+ o = (h[:, None] * R + np.arange(R)[None, :]) * DC + bx[:, None] * ROWS + l[:, None] + (1 if mut == "o" else 0)
+ assert o.min() >= 0 and o.max() < obuf, ("out oob", o.max(), obuf)
+ assert (np.bincount(o.ravel(), minlength=obuf) == 1).all(), "outputs not exactly once"
+def unfold(R, UN, mut=None):
+ T = DV // 2
+ obuf, wbuf, outbuf = H * R * DC, DC * H * DV, R * H * DV
+ dc2 = DC // 2
+ assert dc2 % UN == 0
+ shm = R * DC * 2
+ # staging o -> LDS: uint32 index i < R*dc2 of head h
+ for h in range(H):
+ i = np.arange(R * dc2)
+ idx = h * R * DC // 2 + i + (1 if mut == "o" else 0)
+ assert idx.max() < obuf // 2, "o oob"
+ assert (R * dc2) * 4 <= shm
+ # LDS reads: r*dc2 + k2 + j
+ r = np.arange(R)[:, None]; k = np.arange(dc2)[None, :]
+ assert (r * dc2 + k).max() < R * dc2
+ # w loads: uint32 index h*DV/2 + t + (2*k2' (+1)) * rs ; rs = H*DV/2
+ rs = H * DV // 2
+ h, t = np.meshgrid(np.arange(H), np.arange(T), indexing="ij"); h, t = h.ravel(), t.ravel()
+ rows = np.arange(DC) # 2*(k2+j) and +1 cover all k rows exactly once
+ idx = (h[:, None] * (DV // 2) + t[:, None] + rows[None, :] * rs + (1 if mut == "w" else 0))
+ assert idx.min() >= 0 and idx.max() < wbuf // 2, ("w oob", idx.max(), wbuf // 2)
+ assert np.bincount(idx.ravel(), minlength=wbuf // 2).max() == 1, "w element read twice or not covered"
+ # outputs: uint32 index ((r*H + h)*DV)/2 + t
+ oi = ((np.arange(R)[None, :] * H + h[:, None]) * DV) // 2 + t[:, None] + (1 if mut == "out" else 0)
+ assert oi.min() >= 0 and oi.max() < outbuf // 2, ("out oob", oi.max(), outbuf // 2)
+ assert (np.bincount(oi.ravel(), minlength=outbuf // 2) == 1).all(), "outputs not exactly once"
+fails = 0
+for R in range(1, 9):
+ for UN in (4, 8, 16):
+ for qs in QS_OPTS: absorb(R, UN, qs)
+ for UN in (4, 8, 16): unfold(R, UN)
+ for UN in (4, 8, 16, 32):
+ for qs in QS_OPTS: absorb2(R, UN, qs)
+print("clean: absorb+unfold pass for R=1..8, UN 4/8/16, both q strides")
+for name, f, muts in (("absorb", lambda m: absorb(3, 8, QS_OPTS[0], m), ("q", "w", "o")), ("absorb2", lambda m: absorb2(3, 8, QS_OPTS[0], m), ("q", "w", "o")), ("unfold", lambda m: unfold(3, 8, m), ("o", "w", "out"))):
+ for m in muts:
+ try: f(m); print("MUTATION NOT CAUGHT", name, m); fails += 1
+ except AssertionError as e: print("mutation", name, m, "caught:", str(e)[:60])
+sys.exit(fails)
diff --git a/tools/glm/ext_test.py b/tools/glm/ext_test.py
new file mode 100644
index 0000000..32a0222
--- /dev/null
+++ b/tools/glm/ext_test.py
@@ -0,0 +1,39 @@
+import os, sys, torch
+from exllamav3.modules.attention_fn import mla_triton as MT
+from exllamav3.ext import exllamav3_ext as ext
+assert hasattr(ext, "mla_absorb_dec")
+dev = torch.device("cuda:0"); torch.manual_seed(1); DN = DV = 256
+QK = int(os.environ.get("QK", "256")) # GLM-5.3: NoPE, q head = 256; 320 = a rope-padded head
+def both(f, *a):
+ os.environ["EXL3_MLA_DEC_VALU"] = "1"; x = f(*a); os.environ["EXL3_MLA_DEC_VALU"] = "0"; y = f(*a); os.environ["EXL3_MLA_DEC_VALU"] = "1"
+ torch.cuda.synchronize(); return torch.equal(x.view(torch.short), y.view(torch.short))
+def check(H, DC):
+ ok = True
+ for sc in (0.02, 1.0):
+ wuk = (torch.randn(DC, H*DN, device=dev)*sc).half(); wuv = (torch.randn(DC, H*DV, device=dev)*sc).half()
+ for R in range(1, 9):
+ qf = torch.randn(R + 2, H, QK, device=dev).half(); q = qf[1:1+R] # offset view: nonzero storage offset
+ o = torch.randn(H, R, DC, device=dev).half()
+ a = both(MT.mla_absorb, q, wuk, H, DN); b = both(MT.mla_unfold, o, wuv, DV); ok &= a and b
+ if not (a and b): print("MISMATCH", H, DC, sc, R, a, b)
+ # row identity: R rows == R single-row calls
+ q = torch.randn(8, H, QK, device=dev).half(); o = torch.randn(H, 8, DC, device=dev).half()
+ full = MT.mla_absorb(q, wuk, H, DN); fu = MT.mla_unfold(o, wuv, DV)
+ for r in range(8):
+ ok &= torch.equal(MT.mla_absorb(q[r:r+1], wuk, H, DN)[:, 0].view(torch.short), full[:, r].view(torch.short))
+ ok &= torch.equal(MT.mla_unfold(o[:, r:r+1].contiguous(), wuv, DV)[0].view(torch.short), fu[r].view(torch.short))
+ print(f"QK={QK} H={H} DC={DC}: ext ops vs Triton, R=1..8, 2 scales, row-identity: {'ALL EQUAL' if ok else 'FAIL'}", flush=True); return ok
+if not check(2, 256) or not check(64, 512): sys.exit(1)
+H, DC, L = 64, 512, 11
+wuk = [(torch.randn(DC, H*DN, device=dev)*0.02).half() for _ in range(L)]; wuv = [(torch.randn(DC, H*DV, device=dev)*0.02).half() for _ in range(L)]
+def timeit(f, N=20):
+ for l in range(L): f(l)
+ torch.cuda.synchronize(); a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True); a.record()
+ for _ in range(N):
+ for l in range(L): f(l)
+ b.record(); torch.cuda.synchronize(); return 1000*a.elapsed_time(b)/(N*L)
+for R in (1, 2, 3, 4, 8):
+ q = torch.randn(R, H, QK, device=dev).half(); o = torch.randn(H, R, DC, device=dev).half()
+ for m in ("0", "1"):
+ os.environ["EXL3_MLA_DEC_VALU"] = m
+ print(f"R={R} VALU={m} absorb {timeit(lambda l: MT.mla_absorb(q, wuk[l], H, DN)):6.1f} us unfold {timeit(lambda l: MT.mla_unfold(o, wuv[l], DV)):6.1f} us", flush=True)