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.

Extend the exact R-row verify paths to 9-32 rows on ROCm

YanissAmz7f8a4f98af3c
diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cu b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
index 099fd8a..32bd02e 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
@@ -1416,7 +1416,7 @@ __global__ void moe_combine_kernel_r(MoeArgsR a)
constexpr int ROUTER_KCHUNK = 64;
constexpr int CTR_ROUTER = 4000; // one arrival counter per row: CTR_ROUTER + row
-constexpr int ROUTER_NORM_MAX_ROWS = 8;
+constexpr int ROUTER_NORM_MAX_ROWS = 32; // grid.y = row, one arrival counter per row (CTR_ROUTER + row); rows never share state
// 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
@@ -2335,6 +2335,10 @@ struct JobsR
};
constexpr int GEMV_R_ROW_BUDGET = MOE_R_MAX * MOE_R_KTW_MAX; // 128: max rpb * ktw
+// Rows per exl3_dec_gemv_r call. One block still holds at most MOE_R_MAX rows (LDS staging, accumulators); rows beyond that run as
+// further grid.y row chunks of the same launch. Every row keeps batch-1's ktw / kbs / reduction order, so the bits of a row do not
+// depend on how many rows the call carries (checked by tools/decode/gemv_r_probe.py and gemv_r_rows_bench.py).
+constexpr int GEMV_R_MAX_ROWS = 32;
// Tile ring depth for gemv_kernel_r. 0 (default) = batch-1's ring at RM 1, else 1: the 2-deep ring of
// the > 4 bpw formats (80 VGPRs of tile words) plus RM x 16 accumulators spilled 125 VGPRs at
// KB2 10 RM 2 (GLM lm_head, R 2 ran 5.0 ms vs 3.6 ms for two batch-1 launches). Result-neutral.
@@ -2480,7 +2484,7 @@ static void dec_gemv_r_impl
TORCH_CHECK(x.dtype() == at::kHalf && x.is_contiguous() && x.dim() == 2, "exl3_dec_gemv_r: x must be [R, K] fp16");
const int R = (int) x.size(0);
const int Kdim = (int) x.size(1);
- TORCH_CHECK(R >= 1 && R <= MOE_R_MAX, "exl3_dec_gemv_r: R must be 1..MOE_R_MAX");
+ TORCH_CHECK(R >= 1 && R <= GEMV_R_MAX_ROWS, "exl3_dec_gemv_r: R must be 1..GEMV_R_MAX_ROWS");
TORCH_CHECK(Kdim % 512 == 0, "exl3_dec_gemv_r: K must be a multiple of 512");
const int kb2 = kb2_of(K[0]);
int strips_total = 0;
@@ -2494,12 +2498,14 @@ static void dec_gemv_r_impl
// EXL3_GEMV_R_RPB caps rows per block (grid.y = ceil(R / rpb) row chunks, each re-reading the
// weights). Null result (glm-mtp step 4): RM 4 spills a little at KB2 >= 8 but a cap of 1 or 2
// always lost (lm_head R 4: 1.81 ms default vs 3.53 ms cap 2; R 3 verify 80.4 vs 94.5 ms).
- int rpb = std::max(1, std::min(R, GEMV_R_ROW_BUDGET / ktw));
+ int rpb = std::max(1, std::min(std::min(R, GEMV_R_ROW_BUDGET / ktw), MOE_R_MAX));
const int rpb_cap = env_int("EXL3_GEMV_R_RPB", 0);
if (rpb_cap > 0) rpb = std::min(rpb, rpb_cap);
// (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);
+ // 9..32 rows: row chunks of EXL3_GEMV_R_RPB9 rows (default 4: the 4-row instantiation does not spill), grid.y = ceil(R / rpb)
+ if (R > MOE_R_MAX && !(rpb_cap > 0) && rpb > 1) rpb = std::min(rpb, std::max(1, env_int("EXL3_GEMV_R_RPB9", 4)));
// EXL3_GEMV_R_RM6=1 (needs EXL3_GEMV_R_DEC1=1): 5 or 6 rows run in ONE launch of the 6-row instantiation (one decode pass,
// no VGPR spill at K*2 = 8 / 10) instead of a 4-row chunk plus a 1..2 row chunk. Same per-row arithmetic (rows are independent
@@ -2514,7 +2520,9 @@ static void dec_gemv_r_impl
jobs.kbs = kbs;
jobs.R = R;
jobs.rpb = rpb;
- jobs.swap = env_int("EXL3_GEMV_R_CHUNK_FAST", 0) != 0 && R > 4 && R > rpb; // 5..8 rows only: the <= 4 row launches keep their grid
+ // 5..8 rows only (the <= 4 row launches keep their grid); 9..32 rows swap by default (EXL3_GEMV_R_SWAP9=0 restores the plain grid):
+ // the chunks of one weight block then run side by side and share its reads through L2 instead of re-streaming the weights per chunk
+ jobs.swap = (env_int("EXL3_GEMV_R_CHUNK_FAST", 0) != 0 || (R > MOE_R_MAX && env_int("EXL3_GEMV_R_SWAP9", 1) != 0)) && R > 4 && R > rpb;
jobs.x_row_pitch = Kdim;
int blocks = 0, part = 0, ctr = 0;
for (int i = 0; i < n; ++i)
@@ -2546,6 +2554,7 @@ static void dec_gemv_r_impl
float* sp = scratch.data_ptr<float>();
int* cp = counters.data_ptr<int>();
const int nch = (R + rpb - 1) / rpb;
+ if (jobs.swap && blocks > 65535 && R > MOE_R_MAX) jobs.swap = 0; // the default-swapped 9+ row launch falls back to the plain grid
TORCH_CHECK(!jobs.swap || blocks <= 65535, "exl3_dec_gemv_r: too many blocks for the swapped grid");
const dim3 grid = jobs.swap ? dim3(nch, blocks) : dim3(blocks, nch);
if (rm6)
@@ -3097,7 +3106,7 @@ void exl3_dec_router_norm
const int E = gate.size(1);
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(NR >= 1 && NR <= ROUTER_NORM_MAX_ROWS, "exl3_dec_router_norm: rows 1..ROUTER_NORM_MAX_ROWS");
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]");
diff --git a/exllamav3/modules/block_graph.py b/exllamav3/modules/block_graph.py
index 4ca2cae..01795b1 100644
--- a/exllamav3/modules/block_graph.py
+++ b/exllamav3/modules/block_graph.py
@@ -34,6 +34,7 @@ from . import ablit_runtime
from torch.utils._pytree import tree_flatten, tree_unflatten
from .block_sparse_mlp import BlockSparseMLP
+from ..util.row_inv import ROW_INV_MAX_ROWS
from .gated_delta_net import GatedDeltaNet
from .mla_attn import MLAttention, MAX_DECODE_QLEN as _MLA_MAX_QLEN
@@ -45,13 +46,13 @@ BLOCK_GRAPH_MAX_SLOTS = max(1, _env_int("EXL3_BLOCK_GRAPH_MAX_SLOTS", 4))
# Rows above the dense GEMV cap reconstruct+hgemm; still captureable, but the first bounded
# implementation keeps the served decode envelope. Revisit after (B,Q) family measurements.
-BLOCK_GRAPH_MAX_ROWS = _env_int("EXL3_BLOCK_GRAPH_MAX_ROWS", 16)
+BLOCK_GRAPH_MAX_ROWS = _env_int("EXL3_BLOCK_GRAPH_MAX_ROWS", 16 if ROW_INV_MAX_ROWS <= 8 else ROW_INV_MAX_ROWS)
BLOCK_GRAPH_DEC_MOE = os.environ.get("EXL3_BLOCK_GRAPH_DEC_MOE", "1") == "1"
# R-row verify blocks (MTP/DFlash, union MoE on the device table): EXL3_BLOCK_GRAPH_VERIFY=1 graphs
# them. Off by default: at R=2 on the test box it replays but runs ~0.5 ms slower than eager (glm-mtp step 2b).
# Module global: a harness may flip it between arms.
BLOCK_GRAPH_VERIFY = os.environ.get("EXL3_BLOCK_GRAPH_VERIFY", "0") == "1"
-BLOCK_GRAPH_VERIFY_MAX_ROWS = 8 # MOE_R_MAX
+BLOCK_GRAPH_VERIFY_MAX_ROWS = max(8, ROW_INV_MAX_ROWS) # 8 = MOE_R_MAX; ROCm carries 9..32 rows as union slices / GEMV row chunks
BLOCK_GRAPH_DEBUG = os.environ.get("EXL3_BLOCK_GRAPH_DEBUG", "0") == "1"
# Piecewise capture of MLA/DSA blocks (GLM-5.3 DSA layers), see _mla_forward. The attention core
# (cache append, indexer keys/planes, top-k, sparse/dense attention) sizes its launches from host
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index 50e7897..e6a64d3 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -20,6 +20,7 @@ from ..model.model_tp_alloc import TPAllocation
from ..util import profile_opt
from ..util.tensor import g_tensor_cache, buffered_interleaved_arange
from .quant.exl3 import dec_workspace
+from ..util.row_inv import ROW_INV_MAX_ROWS, job_slices
from .block_sparse_mlp_routing import (
RoutingCFG, ROUTING_ACT_SIGMOID, ROUTING_ACT_SQRTSP,
routing_std, routing_std_bias, routing_ds3, routing_dots, routing_sqrtsp, routing_sqrtsp_hash,
@@ -56,6 +57,10 @@ MOEG_ROWS = int(os.environ.get("EXL3_MOE_GROUPED_ROWS", 1 << 20))
# restores the atomic adds
FUSED_DET = os.environ.get("EXL3_MOE_FUSED_DET", "1") != "0"
MAX_BSZN = 8 # must match MAX_BSZN in exllamav3_ext/libtorch/blocksparse_mlp.h
+# R-row union MoE (exl3_dec_moe_union): one kernel call carries at most MAX_BSZN (= MOE_R_MAX in exl3_dec.cu) rows; a verify step of 9..UNION_ROWS
+# rows runs as job-aligned slices of at most MAX_BSZN rows (each slice is the exact 2..8 row call, rows are independent in an MoE block).
+# ROCm only (the CUDA fused kernels have their own COOP_ROWS); EXL3_ROW_INV_MAX_ROWS=8 restores the single-call cap.
+UNION_ROWS = max(MAX_BSZN, ROW_INV_MAX_ROWS) if torch.version.hip else MAX_BSZN
# Row capacity of the fused decode kernels (exl3_moe_coop): up to this many token rows (bounded by 256 slots = rows * top_k) take
# them instead of the prefill-shaped exl3_moe kernel or row chunks; rows <= MAX_BSZN run exactly as before. The kernels group the
# slots by expert, so each picked expert is decoded once for all of its rows. CUDA only; EXL3_MOE_COOP_ROWS=8 restores the old cap
@@ -76,6 +81,12 @@ _FUSED_3INST_MIN = int(os.environ.get("EXL3_MOE_FUSED_3INST_MIN", "16"))
SYNC_FREE_TOKENS = os.environ.get("EXL3_MOE_SYNC_FREE_TOKENS", "1" if torch.version.hip is None else "0") != "0"
+def _union_slices(x: torch.Tensor, rows: int) -> list:
+ """Row ranges (lo, hi) of the union MoE kernel calls for `rows` token rows: one call up to MAX_BSZN rows, else job-aligned slices
+ (util.row_inv.job_slices). x is the MoE input (jobs, rows per job, H) of a verify forward."""
+ return job_slices(rows, int(x.shape[-2]) if x.dim() >= 3 else 1, MAX_BSZN)
+
+
# Expert-deduplicated grouped MoE (verify batches decode each picked expert once for all of its
# rows); EXL3_MOE_DEDUP=0 restores the per-assignment kernel
_MOE_DEDUP = os.environ.get("EXL3_MOE_DEDUP", "1") != "0"
@@ -1024,7 +1035,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
Ipad = self.intermediate_size_padded
Ru = MAX_BSZN
self.dec_moe_union_out = g_tensor_cache.get(
- self.device, (Ru, self.hidden_size), torch.float, "dec_moe_union_out")
+ self.device, (UNION_ROWS, self.hidden_size), torch.float, "dec_moe_union_out")
self.dec_moe_union_act = g_tensor_cache.get(
self.device, (Ru * numex, Ipad), torch.half, "dec_moe_union_act")
self.dec_moe_union_down_part = g_tensor_cache.get(
@@ -2255,7 +2266,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
# 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
+ 1 < bsz <= UNION_ROWS and self.support_dec_moe and self.tp_mode is None and
not (_MOE_VALU and self.support_hip_grouped and bsz <= 8) and
hasattr(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") and
@@ -2276,22 +2287,25 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
)
out_buf = res.view(bsz, -1) if fuse_res else self.dec_moe_union_out[:bsz]
scratch, counters = dec_workspace(y.device)
- ext.exl3_dec_moe_union(
- y, out_buf, selected_experts.contiguous(), routing_weights.contiguous(),
- self.multi_gate.ptrs_trellis, self.multi_gate.ptrs_suh, self.multi_gate.ptrs_svh,
- self.multi_up.ptrs_trellis, self.multi_up.ptrs_suh, self.multi_up.ptrs_svh,
- self.multi_down.ptrs_trellis, self.multi_down.ptrs_suh, self.multi_down.ptrs_svh,
- self.dec_moe_union_act[:bsz * numex],
- self.dec_moe_union_down_part[:bsz * numex],
- scratch, counters,
- self.intermediate_size_padded,
- self.multi_up.K,
- self.multi_down.K,
- fuse_res,
- self.act_limit,
- self.dec_moe_mcg,
- union_dev or union_v2,
- )
+ sel_c, wts_c = selected_experts.contiguous(), routing_weights.contiguous()
+ for lo, hi in _union_slices(x, bsz):
+ # one slice = the exact 2..8 row call (_union_slices never leaves a lone row: that would be the batch-1 kernel)
+ ext.exl3_dec_moe_union(
+ y[lo:hi], out_buf[lo:hi], sel_c[lo:hi], wts_c[lo:hi],
+ self.multi_gate.ptrs_trellis, self.multi_gate.ptrs_suh, self.multi_gate.ptrs_svh,
+ self.multi_up.ptrs_trellis, self.multi_up.ptrs_suh, self.multi_up.ptrs_svh,
+ self.multi_down.ptrs_trellis, self.multi_down.ptrs_suh, self.multi_down.ptrs_svh,
+ self.dec_moe_union_act[:(hi - lo) * numex],
+ self.dec_moe_union_down_part[:(hi - lo) * numex],
+ scratch, counters,
+ self.intermediate_size_padded,
+ self.multi_up.K,
+ self.multi_down.K,
+ fuse_res,
+ self.act_limit,
+ self.dec_moe_mcg,
+ union_dev or union_v2,
+ )
if fuse_res:
params["mlp_residual_done"] = True
return res
@@ -3057,7 +3071,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
# Also refuse above MAX_BSZN: prefill calls this with R = chunk size (hundreds+), where
# R sequential single-row launches would be catastrophically slower than the batched
# prefill path this falls back to -- this is not what the flag or the kernel is for.
- if os.environ.get("EXL3_DEC_MOE_UNION", "0") == "0" or R > MAX_BSZN or not params.get("dflash_verify"):
+ if os.environ.get("EXL3_DEC_MOE_UNION", "0") == "0" or R > UNION_ROWS or not params.get("dflash_verify"):
return None
try:
xa.view(R, -1)
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index feb09e4..61117b1 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -8,7 +8,7 @@ from . import Module, Linear
from ..ext import exllamav3_ext as ext
from ..model.model_tp_alloc import TPAllocation
from .gated_rmsnorm import GatedRMSNorm
-from .quant.exl3 import row_pad_pitch as _row_pad_pitch
+from .quant.exl3 import row_pad_pitch as _row_pad_pitch, MAX_BSZN_GEMV_R as _MAX_GEMV_R
_MIDCKPT_STREAM = None # EXL3_MIDCHUNK_CKPT=2 side stream for the checkpoint D2H
from ..cache import Cache
@@ -1022,7 +1022,7 @@ class GatedDeltaNet(Module):
"""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():
+ if rows > _MAX_GEMV_R 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")):
diff --git a/exllamav3/modules/moe_fused.py b/exllamav3/modules/moe_fused.py
index 0da95dd..54270c3 100644
--- a/exllamav3/modules/moe_fused.py
+++ b/exllamav3/modules/moe_fused.py
@@ -15,6 +15,7 @@ import time
import torch
from ..ext import exllamav3_ext as ext
from .hyperconnections import HyperConnection
+from ..util.row_inv import ROW_INV_MAX_ROWS, job_slices
MAX_ROWS = 4
# EXL3_VERIFY_ROW_SPLIT=1: 5..8 rows of one sequence run as fused sub-calls of at most 4 rows (per-row arithmetic unchanged)
@@ -176,7 +177,12 @@ class FusedMoEHalf:
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] <= (8 if R8["on"] else SPLIT_MAX_ROWS)
+ rows = x.shape[0] * x.shape[1]
+ lim = 8 if R8["on"] else SPLIT_MAX_ROWS
+ if rows <= lim:
+ return rows >= 1
+ # ROCm: a verify step of 9..ROW_INV_MAX_ROWS rows (several jobs x draft depth) runs as job-aligned sub-calls of the 8-row path
+ return lim >= 8 and rows <= ROW_INV_MAX_ROWS and bool(params.get("dflash_verify"))
def _wide_ok(self) -> bool:
"""The one-launch 5..8 row path exists for this block: mf9 at the default variant 0x160000 (six stage launches), native layout, no timing. The wide instantiations cover K2..K5 only (the K6 drafter layer takes the split path)."""
@@ -185,6 +191,13 @@ class FusedMoEHalf:
def __call__(self, x: torch.Tensor) -> torch.Tensor:
"""x (b, s, H, D) fp32 residual stack, updated in place and returned."""
+ rows = x.shape[0] * x.shape[1]
+ if rows > 8:
+ # whole jobs per call, at most 8 rows each: every row keeps the arithmetic of an 8-row (or shorter) round
+ xf = x.view(1, rows, *x.shape[2:])
+ for lo, hi in job_slices(rows, x.shape[1], 8):
+ self(xf[:, lo:hi])
+ return x
if x.shape[0] * x.shape[1] > MAX_ROWS and R8["on"] and self._wide_ok():
gr = self.gr
fq, fsc, uq, usc = gr.q8_set()
diff --git a/exllamav3/modules/quant/exl3.py b/exllamav3/modules/quant/exl3.py
index 0a3b81f..1e3b2ec 100644
--- a/exllamav3/modules/quant/exl3.py
+++ b/exllamav3/modules/quant/exl3.py
@@ -9,7 +9,8 @@ from ...util import profile_opt
from .. import row_split as _row_split
_row_split.install()
-MAX_BSZN_GEMV_R = 8 # must match MOE_R_MAX in exllamav3_ext/quant/exl3_dec.cu
+# rows of one exl3_dec_gemv_r call: GEMV_R_MAX_ROWS in exllamav3_ext/quant/exl3_dec.cu (ROCm: 9..32 rows run as grid.y row chunks); the 8-row MOE_R_MAX elsewhere
+MAX_BSZN_GEMV_R = min(32, max(1, int(os.environ.get("EXL3_GEMV_R_MAX_ROWS", "32" if torch.version.hip else "8"))))
# K >= this runs R batch-1 launches instead of one gemv_r launch (A/B knob; 99 = never loop)
DEC_GEMV_R_LOOP_MIN_K = int(os.environ.get("EXL3_DEC_GEMV_R_LOOP_MIN_K", "99"))
# EXL3_VERIFY_FUSE=1 routes every R-row (1 < R <= 8) dense EXL3 linear of the MTP/DFlash
@@ -237,6 +238,8 @@ _DEC_KB2 = (4, 5, 6, 8, 10, 12)
# dense projections also decode K7 (attention, linear-attention and shared-expert projections of 5 bpw packs); the routed-MoE kernels stop at K6
_DEC_KB2_DENSE = _DEC_KB2 + (14,)
DEC_SCRATCH_FLOATS = 2 << 20
+# arrival counters: the 8-row kernels fit 4096; a 32-row GEMV of a wide N (lm_head: 32 * ceil(N / 512)) needs up to ~16k
+DEC_COUNTERS = 16384
_dec_workspaces: dict = {}
@@ -259,14 +262,14 @@ def dec_workspace(device: torch.device):
ws = _dec_workspaces.get(key)
if ws is None:
ws = (torch.zeros(DEC_SCRATCH_FLOATS, dtype = torch.float, device = device),
- torch.zeros(4096, dtype = torch.int, device = device))
+ torch.zeros(DEC_COUNTERS, dtype = torch.int, device = device))
_dec_workspaces[key] = ws
return ws
# 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).
+# (same kernel, same per-row reduction order, so bit-exact). Counters are shared (R * ceil(N/512) <= 15520 <= DEC_COUNTERS for R <= 32).
# 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
@@ -523,15 +526,15 @@ class LinearEXL3:
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
+ if "scratch too small" not in str(e) and "counters too small" not in str(e): raise
loop = True
- if WIDE_R["on"] and rows <= 8:
+ if WIDE_R["on"] and rows <= MAX_BSZN_GEMV_R and "scratch too small" in str(e):
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 "scratch too small" not in str(e2) and "counters 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,
diff --git a/exllamav3/util/row_inv.py b/exllamav3/util/row_inv.py
index c6ab411..2a6d9bd 100644
--- a/exllamav3/util/row_inv.py
+++ b/exllamav3/util/row_inv.py
@@ -7,6 +7,36 @@ must purge the graphs when the flag flips (block_graph.purge()).
"""
import os
+import torch
+
ROW_INV = {"on": os.environ.get("EXL3_ROW_INV", "1") not in ("", "0")}
-# Rows a verify forward may have before the per-row exact paths give way to the batched ones.
-ROW_INV_MAX_ROWS = 8
+# Rows a verify forward may have before the per-row exact paths give way to the batched ones. ROCm (exl3_dec.cu, gfx11.5): the
+# R-row GEMV, the union MoE and the row loops carry up to 32 rows, every row with the bits of the one-row launch (rows 9..32 are
+# row chunks of the same arithmetic); other builds keep 8. EXL3_ROW_INV_MAX_ROWS overrides (8 restores the previous ROCm cap).
+ROW_INV_MAX_ROWS = max(1, int(os.environ.get("EXL3_ROW_INV_MAX_ROWS", "32" if torch.version.hip else "8")))
+
+
+def job_slices(rows: int, w: int, cap: int) -> list:
+ """Row ranges (lo, hi) that cut `rows` verify rows into calls of at most `cap` rows. `w` is the rows of one job (consecutive rows of
+ one sequence share most of their experts, so whole jobs stay together when they fit, w > 1 and rows % w == 0). The slices are
+ balanced, and none is a single row unless rows == 1 (a one-row call takes the batch-1 kernel)."""
+ if rows <= cap:
+ return [(0, rows)]
+ if 1 < w <= cap and rows % w == 0:
+ jobs = rows // w
+ n = -(-jobs // max(1, cap // w))
+ base, extra = divmod(jobs, n) # balanced: the first `extra` slices carry one more job
+ out, j = [], 0
+ for i in range(n):
+ k = base + (1 if i < extra else 0)
+ out.append((j * w, (j + k) * w))
+ j += k
+ return out
+ n = -(-rows // cap)
+ base, extra = divmod(rows, n)
+ out, r = [], 0
+ for i in range(n):
+ k = base + (1 if i < extra else 0)
+ out.append((r, r + k))
+ r += k
+ return out
diff --git a/tests/test_plain_rows_cpu.py b/tests/test_plain_rows_cpu.py
index a473405..82d0f86 100644
--- a/tests/test_plain_rows_cpu.py
+++ b/tests/test_plain_rows_cpu.py
@@ -7,7 +7,7 @@ def test_off_by_default_state_is_respected():
old = PLAIN_ROWS["on"]
try:
PLAIN_ROWS["on"] = False
- assert not any(plain_rows_verify(r, False) for r in range(0, 20))
+ assert not any(plain_rows_verify(r, False) for r in range(0, ROW_INV_MAX_ROWS + 4))
finally:
PLAIN_ROWS["on"] = old
@@ -17,7 +17,7 @@ def test_on_covers_rows_two_to_max_only():
try:
PLAIN_ROWS["on"] = True
ROW_INV["on"] = True
- got = [r for r in range(0, 20) if plain_rows_verify(r, False)]
+ got = [r for r in range(0, ROW_INV_MAX_ROWS + 4) if plain_rows_verify(r, False)]
assert got == list(range(2, ROW_INV_MAX_ROWS + 1))
assert not plain_rows_verify(4, True) # a drafted step is already marked by its caller
ROW_INV["on"] = False
diff --git a/tests/test_row_groups_cpu.py b/tests/test_row_groups_cpu.py
index c50963a..734b3ec 100644
--- a/tests/test_row_groups_cpu.py
+++ b/tests/test_row_groups_cpu.py
@@ -16,13 +16,13 @@ from exllamav3.util.row_inv import ROW_INV_MAX_ROWS
def test_cap_default_and_override(monkeypatch):
monkeypatch.delenv("EXL3_ROW_INV_GROUP_ROWS", raising=False)
- assert RG.group_rows_cap() == ROW_INV_MAX_ROWS == 8
+ assert RG.group_rows_cap() == ROW_INV_MAX_ROWS == (32 if torch.version.hip else 8)
monkeypatch.setenv("EXL3_ROW_INV_GROUP_ROWS", "1")
assert RG.group_rows_cap() == 1
monkeypatch.setenv("EXL3_ROW_INV_GROUP_ROWS", "0")
assert RG.group_rows_cap() == 1
monkeypatch.setenv("EXL3_ROW_INV_GROUP_ROWS", "")
- assert RG.group_rows_cap() == 8
+ assert RG.group_rows_cap() == ROW_INV_MAX_ROWS
@pytest.mark.parametrize("value,expect", [(None, False), ("", False), ("0", False), ("1", True)])
diff --git a/tests/test_row_invariance_cpu.py b/tests/test_row_invariance_cpu.py
index 89a0542..6ce1460 100644
--- a/tests/test_row_invariance_cpu.py
+++ b/tests/test_row_invariance_cpu.py
@@ -33,8 +33,8 @@ def test_row_caps_follow_the_flag(rowinv):
if "EXL3_MLA_DEC_ROWLOOP_MAX" in os.environ:
pytest.skip("explicit rowloop cap in the environment")
rowinv["on"] = True
- assert R._router_rows_max() == ROW_INV_MAX_ROWS == 8
- assert _rowloop_max() == 8
+ assert R._router_rows_max() == ROW_INV_MAX_ROWS == (32 if torch.version.hip else 8)
+ assert _rowloop_max() == ROW_INV_MAX_ROWS
rowinv["on"] = False
assert R._router_rows_max() == R.DEC_ROUTER_ROWS_MAX == 4
assert _rowloop_max() == 4
diff --git a/tests/test_row_slices_cpu.py b/tests/test_row_slices_cpu.py
new file mode 100644
index 0000000..9951f46
--- /dev/null
+++ b/tests/test_row_slices_cpu.py
@@ -0,0 +1,42 @@
+"""CPU checks for the 9..32 row verify caps on ROCm: how the union MoE splits a step into exact <= 8 row calls."""
+import pytest
+import torch
+
+from exllamav3.modules import block_sparse_mlp as B
+from exllamav3.util.row_inv import ROW_INV_MAX_ROWS
+
+
+def _x(jobs, w):
+ return torch.empty((jobs, w, 4), dtype=torch.half, device="meta")
+
+
+def test_caps_are_arch_keyed():
+ assert ROW_INV_MAX_ROWS == (32 if torch.version.hip else 8)
+ assert B.UNION_ROWS == (32 if torch.version.hip else B.MAX_BSZN)
+
+
[email protected]("jobs", range(1, 33))
[email protected]("w", range(1, 9))
+def test_slices_cover_rows_exactly(jobs, w):
+ rows = jobs * w
+ if rows > 32:
+ pytest.skip("above the union cap")
+ sl = B._union_slices(_x(jobs, w), rows)
+ assert sl[0][0] == 0 and sl[-1][1] == rows
+ assert all(a[1] == b[0] for a, b in zip(sl, sl[1:])) # contiguous, in order, no overlap
+ for lo, hi in sl:
+ assert hi - lo <= B.MAX_BSZN # each call is the exact <= 8 row kernel
+ if rows > 1:
+ assert hi - lo >= 2 or rows <= B.MAX_BSZN # a lone row would take the batch-1 kernel
+ if rows > B.MAX_BSZN and w > 1:
+ assert lo % w == 0 and hi % w == 0 # whole jobs stay in one slice
+
+
+def test_slice_plans_of_the_target_steps():
+ assert B._union_slices(_x(4, 3), 12) == [(0, 6), (6, 12)] # N=4 depth 2
+ assert B._union_slices(_x(4, 4), 16) == [(0, 8), (8, 16)] # N=4 depth 3
+ assert B._union_slices(_x(4, 2), 8) == [(0, 8)] # N=4 depth 1: one call, unchanged
+ assert B._union_slices(_x(3, 3), 9) == [(0, 6), (6, 9)]
+ assert B._union_slices(_x(12, 1), 12) == [(0, 6), (6, 12)] # plain multi-session step, balanced
+ assert B._union_slices(torch.empty((1, 11, 4), device="meta"), 11) == [(0, 6), (6, 11)] # one long job
+ assert B._union_slices(torch.empty((20, 4), device="meta"), 20) == [(0, 7), (7, 14), (14, 20)]
diff --git a/tools/decode/gemv_r_rows_bench.py b/tools/decode/gemv_r_rows_bench.py
index 3e9c303..a9d432b 100644
--- a/tools/decode/gemv_r_rows_bench.py
+++ b/tools/decode/gemv_r_rows_bench.py
@@ -29,8 +29,13 @@ ARMS = {
"D1c4f": {"EXL3_GEMV_R_DEC1": "1", "EXL3_GEMV_R_RPB": "4", "EXL3_GEMV_R_CHUNK_FAST": "1"},
"D1rm6": {"EXL3_GEMV_R_DEC1": "1", "EXL3_GEMV_R_RPB": "4", "EXL3_GEMV_R_CHUNK_FAST": "1", "EXL3_GEMV_R_RM6": "1"},
"D0": {},
+ # rows 9..32 (ROCm): block rows RPB9 (default 4), swap = row chunks on the fast grid axis (SWAP9 default 1)
+ "D9": {"EXL3_GEMV_R_DEC1": "1"},
+ "D9r2": {"EXL3_GEMV_R_DEC1": "1", "EXL3_GEMV_R_RPB9": "2"},
+ "D9r8": {"EXL3_GEMV_R_DEC1": "1", "EXL3_GEMV_R_RPB9": "8"},
+ "D9ns": {"EXL3_GEMV_R_DEC1": "1", "EXL3_GEMV_R_SWAP9": "0"},
}
-KEYS = ["EXL3_GEMV_R_DEC1", "EXL3_GEMV_R_RPB", "EXL3_GEMV_R_CHUNK_FAST", "EXL3_GEMV_R_RPB78", "EXL3_GEMV_R_RM6"]
+KEYS = ["EXL3_GEMV_R_DEC1", "EXL3_GEMV_R_RPB", "EXL3_GEMV_R_CHUNK_FAST", "EXL3_GEMV_R_RPB78", "EXL3_GEMV_R_RM6", "EXL3_GEMV_R_RPB9", "EXL3_GEMV_R_SWAP9"]
def setarm(name):
for k in KEYS: os.environ.pop(k, None)
os.environ.update(ARMS[name])
@@ -41,7 +46,7 @@ for name in a.shapes.split(","):
for R in [int(v) for v in a.rows.split(",")]:
x = (torch.randn(R, K, device=dev, generator=g) * 0.5).half().contiguous()
outs = [torch.empty(R, N, dtype=torch.half, device=dev) for N in Ns]
- scr = torch.zeros(R * 8 * sum(Ns) * 2, dtype=torch.float, device=dev); ctr = torch.zeros(8192, dtype=torch.int32, device=dev)
+ scr = torch.zeros(R * 8 * sum(Ns) * 2, dtype=torch.float, device=dev); ctr = torch.zeros(16384, dtype=torch.int32, device=dev)
def call():
if len(Ns) == 1: ext.exl3_dec_gemv_r(x, tr[0], suh[0], svh[0], outs[0], scr, ctr, KB, False)
else: ext.exl3_dec_gemv_r_multi(x, tr, suh, svh, outs, scr, ctr, Ks, False)