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.

QSA top-k tiling: prefill-only gate, merge by one more pass of the single-pass kernel, CPU proof with mutants

YanissAmz97b675a92ca4
diff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.py
index 3b4bcd8..831d905 100644
--- a/exllamav3/modules/qsa_indexer.py
+++ b/exllamav3/modules/qsa_indexer.py
@@ -90,6 +90,24 @@ def merge_candidates(cand, k):
return torch.where(gi == 0x7FFFFFFF, -1, gi).to(torch.int32)
+def gather_tile(scores, tile_idx, t0, cand_s, cand_i):
+ """Write one tile's top-k into its slot of the candidate buffers: the tile's own fp16 scores (bits untouched, -inf at the
+ -1 pads) into cand_s (R, kp) and global pool indices (-1 pads) into cand_i (R, kp). Valid entries are ascending."""
+ li = tile_idx.long()
+ ok = li >= 0
+ cand_s.copy_(torch.where(ok, torch.gather(scores, 1, li.clamp(min = 0)), float("-inf")))
+ cand_i.copy_(torch.where(ok, li + t0, -1))
+
+
+def merge_tiles_topk(topk_fn, cand_s, cand_i, pos_out, pool_idx, k):
+ """Exact merge: one top-k pass of the single-pass kernel over the concatenated candidates (R, W), W a multiple of 128.
+ Tiles are disjoint and ascending and each tile's valid entries ascend, so buffer position order is global index order:
+ the kernel's rule (score descending, lowest position first among ties, ascending output) is the single pass's rule.
+ pos_out (R, kp) int32 scratch, pool_idx (R, kp) int32 result (-1 padded)."""
+ topk_fn(cand_s, pos_out, k, None, 0)
+ pool_idx.copy_(torch.where(pos_out >= 0, torch.gather(cand_i, 1, pos_out.long().clamp(min = 0)), -1))
+
+
class QSAIndexer(Module):
def __init__(
@@ -271,6 +289,11 @@ class QSAIndexer(Module):
# multiple of 128), each run through the same kernel, and the candidates are merged in torch under the kernel's own
# total order. Rows up to N pools stay one pass. 0 = always one full-width pass
TOPK_TILE = int(os.environ.get("EXL3_QSA_TOPK_TILE", 0))
+ # The tiled selection serves prefill chunks only: calls of at most TOPK_MIN_ROWS rows (decode, MTP verify rounds,
+ # bsz > 1 fallbacks) keep the single pass, whose result is identical. "topk" merges the tile candidates with one more
+ # pass of the same kernel over the (R, tiles * kp) candidate buffer; "torch" is the elementwise merge kept for A/B runs
+ TOPK_MIN_ROWS = int(os.environ.get("EXL3_QSA_TOPK_MIN_ROWS", 32))
+ TOPK_MERGE = os.environ.get("EXL3_QSA_TOPK_MERGE", "topk")
# Row count up to which the plane-update workspaces come from g_tensor_cache (decode-class
# calls: MTP verify, bsz > 1 fallbacks, where allocation latency matters); prefill chunks
# allocate per call, the static cache being meant for small buffers only
@@ -318,7 +341,7 @@ class QSAIndexer(Module):
k_sel = self.block_topk
kp = -(-k_sel // 32) * 32
tiled_topk = hasattr(ext, "dsa_topk_tile") and hasattr(ext, "dsa_topk_merge_tiles")
- torch_merge = not tiled_topk and self.TOPK_TILE > 0
+ torch_merge = not tiled_topk and self.TOPK_TILE > 0 and R > self.TOPK_MIN_ROWS
t_tile = self.TOPK_TILE // 128 * 128 if torch_merge else self.SEL_TILE
if block_table is not None:
t_tile = max(epp, t_tile // epp * epp) # tiles must start on a pool page
@@ -369,7 +392,7 @@ class QSAIndexer(Module):
elif T_slab <= t_tile or (not tiled_topk and not torch_merge):
sc = tile_scores(q_slab, rows, 0, T_slab)
ext.dsa_topk(sc, pool_idx, min(k_sel, T_slab), None, 0)
- elif torch_merge:
+ elif torch_merge and self.TOPK_MERGE == "torch":
cand = []
tile_idx = torch.empty((rows, kp), dtype = torch.int32, device = dev)
n_tiles = -(-T_slab // t_tile)
@@ -381,6 +404,19 @@ class QSAIndexer(Module):
cand.append(tile_candidates(sc, tile_idx, t0))
pool_idx[:, :k_sel] = merge_candidates(cand, k_sel)
pool_idx[:, k_sel:] = -1
+ elif torch_merge:
+ tile_idx = torch.empty((rows, kp), dtype = torch.int32, device = dev)
+ n_tiles = -(-T_slab // t_tile)
+ w = -(-(-(-T_slab // n_tiles)) // 128) * 128 # equal tiles, 128 aligned
+ W = -(-(n_tiles * kp) // 128) * 128
+ cand_s = torch.full((rows, W), float("-inf"), dtype = torch.half, device = dev)
+ cand_i = torch.full((rows, W), -1, dtype = torch.int32, device = dev)
+ for n, t0 in enumerate(range(0, T_slab, w)):
+ t1 = min(t0 + w, T_slab)
+ sc = tile_scores(q_slab, rows, t0, t1)
+ ext.dsa_topk(sc, tile_idx, min(k_sel, t1 - t0), None, 0)
+ gather_tile(sc, tile_idx, t0, cand_s[:, n * kp : (n + 1) * kp], cand_i[:, n * kp : (n + 1) * kp])
+ merge_tiles_topk(ext.dsa_topk, cand_s, cand_i, tile_idx, pool_idx, k_sel)
else:
# Tiled: each tile's local top-k becomes candidate slot 1 next to the running set
# in slot 0, and the native merge reduces the pair under the single-pass kernel's
diff --git a/tests/test_qsa_topk_tile_cpu.py b/tests/test_qsa_topk_tile_cpu.py
index 811d967..248c538 100644
--- a/tests/test_qsa_topk_tile_cpu.py
+++ b/tests/test_qsa_topk_tile_cpu.py
@@ -1,67 +1,117 @@
+"""CPU proof that the tiled selection (per-tile kernel pass + one merge pass of the same kernel) equals the single pass,
+tie order included. The kernel is emulated by its contract: the k largest 16-bit order keys above the -inf key, lowest
+position first among equal keys, ascending output, -1 padded to the output width."""
import ast, os, torch
SRC = os.environ.get("QSA_SRC") or os.path.join(os.path.dirname(__file__), "..", "exllamav3", "modules", "qsa_indexer.py")
+NAMES = ("tile_candidates", "merge_candidates", "gather_tile", "merge_tiles_topk")
def _load():
tree = ast.parse(open(SRC).read())
- keep = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in ("tile_candidates", "merge_candidates")]
+ keep = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in NAMES]
ns = {"torch": torch}
exec(compile(ast.Module(body = keep, type_ignores = []), SRC, "exec"), ns)
- return ns["tile_candidates"], ns["merge_candidates"]
+ return ns
-def _key(bits):
+def _key(scores):
+ bits = scores.view(torch.int16).to(torch.int32) & 0xFFFF
return torch.where(bits >= 0x8000, ~bits & 0xFFFF, bits | 0x8000)
-def _single_pass(scores, k):
- # the one-block-per-row kernel's contract: the k largest 16-bit order keys above the -inf key, earliest index first
- # among equal keys, emitted as ascending indices, -1 padded to the row width k
+def kernel(scores, out, k, t_ptr = None, t_seq = 0):
+ """dsa_topk_gfx12 contract, vectorised: stable descending sort of the key keeps the lowest position first among ties."""
R, T = scores.shape
- key = _key(scores.view(torch.int16).to(torch.int32) & 0xFFFF).long()
- out = torch.full((R, k), -1, dtype = torch.int32)
- for r in range(R):
- valid = (key[r] > 0x03FF).nonzero().flatten()
- order = sorted(valid.tolist(), key = lambda i: (-int(key[r, i]), i))[:k]
- sel = sorted(order)
- out[r, :len(sel)] = torch.tensor(sel, dtype = torch.int32)
+ assert scores.stride(1) == 1 and scores.stride(0) % 128 == 0 and out.shape[1] >= k and out.is_contiguous()
+ key = _key(scores)
+ order = torch.sort(key, dim = 1, descending = True, stable = True).indices[:, :k]
+ ok = torch.gather(key, 1, order) > 0x03FF
+ sel = torch.where(ok, order, T + 1).sort(dim = 1).values
+ res = torch.full(out.shape, -1, dtype = torch.int32)
+ res[:, :k] = torch.where(sel <= T - 1, sel, -1).to(torch.int32)
+ out.copy_(res)
+
+
+def single_pass(scores, kp, k):
+ pad = (-scores.shape[1]) % 128
+ s = torch.cat([scores, torch.full((scores.shape[0], pad), float("-inf"), dtype = torch.half)], 1) if pad else scores
+ out = torch.empty((scores.shape[0], kp), dtype = torch.int32)
+ kernel(s, out, min(k, scores.shape[1]))
return out
-def _tiled(scores, k, tile):
- tile_candidates, merge_candidates = _load()
+def tiled(scores, kp, k, tile, ns = None):
+ ns = ns or _load()
R, T = scores.shape
- cand = []
- for t0 in range(0, T, tile):
- sc = scores[:, t0: t0 + tile]
- local = _single_pass(sc, min(k, sc.shape[1]))
- kp = torch.full((R, k), -1, dtype = torch.int32)
- kp[:, :local.shape[1]] = local
- cand.append(tile_candidates(sc, kp, t0))
- return merge_candidates(cand, k)
+ n_tiles = -(-T // tile)
+ w = -(-(-(-T // n_tiles)) // 128) * 128
+ W = -(-(n_tiles * kp) // 128) * 128
+ cs = torch.full((R, W), float("-inf"), dtype = torch.half)
+ ci = torch.full((R, W), -1, dtype = torch.int32)
+ tile_idx = torch.empty((R, kp), dtype = torch.int32)
+ for n, t0 in enumerate(range(0, T, w)):
+ t1 = min(t0 + w, T)
+ sc = torch.full((R, -(-(t1 - t0) // 128) * 128), float("-inf"), dtype = torch.half)
+ sc[:, :t1 - t0] = scores[:, t0:t1]
+ kernel(sc, tile_idx, min(k, t1 - t0))
+ ns["gather_tile"](sc, tile_idx, t0, cs[:, n * kp:(n + 1) * kp], ci[:, n * kp:(n + 1) * kp])
+ pool = torch.empty((R, kp), dtype = torch.int32)
+ ns["merge_tiles_topk"](kernel, cs, ci, tile_idx, pool, k)
+ return pool
-def _scores(R, T, levels, neg_inf_frac, gen):
+def gen_scores(R, T, levels, neg_inf_frac, gen, nan = False):
vals = torch.tensor([0.0, -0.0, 0.5, -0.5, 1.0, -1.0, 0.25, 2.0, -2.0, 3.0][:levels], dtype = torch.half)
s = vals[torch.randint(0, levels, (R, T), generator = gen)]
s[torch.rand(R, T, generator = gen) < neg_inf_frac] = float("-inf")
+ if nan:
+ s[torch.rand(R, T, generator = gen) < 0.01] = float("nan")
+ s[torch.rand(R, T, generator = gen) < 0.01] = -float("nan")
return s
-def test_tiled_merge_equals_single_pass():
+CASES = [ # levels, -inf fraction, R, T, k, tile, nan
+ (3, 0.0, 4, 700, 40, 128, False), (10, 0.3, 4, 1000, 64, 256, False), (2, 0.0, 3, 513, 32, 100, False),
+ (6, 0.9, 4, 900, 50, 300, False), (10, 0.0, 3, 2048, 128, 512, False), (4, 0.99, 3, 700, 64, 200, False),
+ (5, 0.2, 3, 4000, 96, 1024, True),
+ # model shape: K = 512, tile 32768, pools 8K..262K (padding, T not a multiple of the tile, <k valid, heavy ties)
+ (3, 0.0, 2, 8192, 512, 32768, False), (3, 0.0, 2, 32768, 512, 32768, False), (3, 0.0, 2, 32769, 512, 32768, False),
+ (3, 0.5, 2, 65000, 512, 32768, False), (5, 0.0, 2, 100000, 512, 32768, True), (2, 0.0, 2, 131072, 512, 32768, False),
+ (3, 0.0, 1, 196609, 512, 32768, False), (3, 0.9995, 2, 262144, 512, 32768, False), (4, 0.2, 1, 262144, 512, 32768, True),
+]
+
+
+def test_tiled_equals_single_pass():
+ ns = _load()
gen = torch.Generator().manual_seed(3)
- for levels, frac, R, T, k, tile in [(3, 0.0, 6, 700, 40, 128), (10, 0.3, 5, 1000, 64, 256), (2, 0.0, 4, 513, 32, 100),
- (6, 0.9, 5, 900, 50, 300), (10, 0.0, 4, 2048, 128, 512), (4, 0.99, 3, 700, 64, 200)]:
- s = _scores(R, T, levels, frac, gen)
- ref = _single_pass(s, k)
- got = _tiled(s, k, tile)
+ for levels, frac, R, T, k, tile, nan in CASES:
+ s = gen_scores(R, T, levels, frac, gen, nan)
+ kp = -(-k // 32) * 32
+ ref, got = single_pass(s, kp, k), tiled(s, kp, k, tile, ns)
assert torch.equal(ref, got), (levels, frac, R, T, k, tile)
def test_fewer_valid_than_k_is_padded():
s = torch.full((2, 600), float("-inf"), dtype = torch.half)
s[0, 10] = 1.0; s[0, 400] = 1.0; s[1, 599] = -3.0
- got = _tiled(s, 8, 128)
- assert got[0].tolist() == [10, 400] + [-1] * 6
- assert got[1].tolist() == [599] + [-1] * 7
+ got = tiled(s, 32, 8, 128)
+ assert got[0].tolist() == [10, 400] + [-1] * 30
+ assert got[1].tolist() == [599] + [-1] * 31
+
+
+def test_ties_across_tile_border_take_lowest_index():
+ s = torch.full((1, 512), 1.0, dtype = torch.half) # every key equal: the k lowest indices win, across tiles
+ got = tiled(s, 32, 32, 128)
+ assert got[0].tolist() == list(range(32))
+ s[0, 130] = 2.0; s[0, 5] = 0.5
+ got = tiled(s, 32, 32, 128)
+ assert got[0].tolist() == [0, 1, 2, 3, 4] + list(range(6, 32)) + [130]
+
+
+def test_pad_slots_do_not_duplicate_position_zero():
+ s = torch.full((2, 700), float("-inf"), dtype = torch.half)
+ s[:, 0] = 3.0; s[:, 650] = 1.0; s[1, 300] = 2.0
+ got = tiled(s, 32, 8, 128)
+ assert got[0].tolist() == [0, 650] + [-1] * 30
+ assert got[1].tolist() == [0, 300, 650] + [-1] * 29