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.

ROCm: native Triton cache writer for any K/V width 2..8, qdec.hip guards and debug counters, bench tooling

YanissAmzf4c8dc089687
diff --git a/doc/env_vars.md b/doc/env_vars.md
index dc71d26..88faca5 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -1226,6 +1226,23 @@ build step) that reads the packed pages directly. `EXL3_QDEC=0` falls back to th
disables its CUDA-graph capture path, `EXL3_QDEC_ROWS` selects the many-row kernel for verify steps (q_len 2..8 at
head dim 256): `0` off, `1` only where the single-row kernel cannot serve, `2` always.
+#### `EXL3_QWRITE_TRITON` (default `1`; ROCm)
+
+Native Triton writer for the quantized paged cache (K/V bits 2..8, `attention_fn/qwrite_triton.py`): one launch appends the new
+rows of K and V with the same arithmetic and packed plane layout as the PyTorch fallback (bit-identical words and scales,
+`tests/test_qwrite.py`). The fallback needs ~70 launches per layer (decode append 402 us, 4096-row prefill chunk 5.2 ms at
+K/V 6,6 per layer; native 17 us / 89 us). `0` restores the fallback.
+
+#### `EXL3_QDEC_HIP` (default `0`; ROCm gfx11.5)
+
+HIP counterpart of `EXL3_QDEC` for AMD (Strix Halo): a wave32 WMMA kernel (`attention_fn/qdec.hip`, compiled with hipcc at first
+use and cached under `~/.cache/exllamav3`) that dequantizes the packed K/V pages straight into the WMMA operands, plus a small
+combine kernel. Used for quantized-KV decode (K/V bits 2..8, head dim 128 or 256, q_len up to 6 at head dim 128 / 3 at 256) with
+full attention, no softcap; windowed layers, 1-bit planes and bigger shapes keep the Triton kernels. `0` keeps the Triton kernels.
+Tuning knobs for A/B work: `EXL3_QDEC_HIP_NW` (waves per CTA, default 4), `EXL3_QDEC_HIP_DW` (waves splitting the head dim),
+`EXL3_QDEC_HIP_WAVES` (target resident waves for the split count), `EXL3_QDEC_HIP_SPL` (fixed split count),
+`EXL3_QDEC_HIP_MAXO` (accumulator budget per lane, default 96).
+
#### `EXL3_PREFILL_WIDE` (default `1`)
Models with sliding-window attention only and a fused MoE (Flint): prompts that fit are prefilled in one pass, in
diff --git a/exllamav3/ext_fallbacks.py b/exllamav3/ext_fallbacks.py
index d8a2b75..82ba5fd 100644
--- a/exllamav3/ext_fallbacks.py
+++ b/exllamav3/ext_fallbacks.py
@@ -837,11 +837,12 @@ def quant_cache_paged(
k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
cache_seqlens, block_table, page_size, seq_len, compand_a = 0.0, in_contiguous = False,
):
- """Paged cache append: native Triton writer for the 8-bit layout, torch fallback otherwise."""
+ """Paged cache append: native Triton writer (8-bit layout, or any 2..8-bit plane layout), torch fallback otherwise."""
if (
not _QW_OFF and compand_a == 0.0 and seq_len > 0 and k_in.is_cuda and
k_out.ndim == 3 and v_out.ndim == 3 and k_out_scales.shape[-1] in (8, 16, 32, 64) and
- k_out.shape[-1] == k_out_scales.shape[-1] * 8 and v_out.shape[-1] == k_out.shape[-1] and
+ k_out.shape[-1] % k_out_scales.shape[-1] == 0 and v_out.shape[-1] % k_out_scales.shape[-1] == 0 and
+ 2 <= k_out.shape[-1] // k_out_scales.shape[-1] <= 8 and 2 <= v_out.shape[-1] // k_out_scales.shape[-1] <= 8 and
v_out_scales.shape == k_out_scales.shape and
k_in.dtype == torch.float16 and v_in.dtype == torch.float16 and
k_in.is_contiguous() and v_in.is_contiguous() and page_size == 256 and
@@ -851,9 +852,16 @@ def quant_cache_paged(
k_in.shape == v_in.shape and k_in.numel() >= block_table.shape[0] * seq_len * (k_out_scales.shape[-1] * 32) and
(in_contiguous or k_in.numel() == k_out.shape[0] * page_size * k_out_scales.shape[-1] * 32)
):
- from .modules.attention_fn.qwrite_triton import quant_cache_paged8
- quant_cache_paged8(k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
- cache_seqlens, block_table, seq_len, in_contiguous)
+ kb = k_out.shape[-1] // k_out_scales.shape[-1]
+ vb = v_out.shape[-1] // k_out_scales.shape[-1]
+ if kb == 8 and vb == 8:
+ from .modules.attention_fn.qwrite_triton import quant_cache_paged8
+ quant_cache_paged8(k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
+ cache_seqlens, block_table, seq_len, in_contiguous)
+ else:
+ from .modules.attention_fn.qwrite_triton import quant_cache_paged_bits
+ quant_cache_paged_bits(k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
+ cache_seqlens, block_table, seq_len, in_contiguous, kb, vb)
return
_quant_cache_paged_torch(k_in, k_out, k_out_scales, v_in, v_out, v_out_scales,
cache_seqlens, block_table, page_size, seq_len, compand_a, in_contiguous)
diff --git a/exllamav3/modules/attention_fn/qdec.hip b/exllamav3/modules/attention_fn/qdec.hip
index dffa95a..47e14c1 100644
--- a/exllamav3/modules/attention_fn/qdec.hip
+++ b/exllamav3/modules/attention_fn/qdec.hip
@@ -203,9 +203,9 @@ qdec_split(
auto slab_rows = [&](int it) {
int n0 = n_start + (sw + it * NSW) * 16;
- int page = n0 / PAGE;
+ int page = min(n0 / PAGE, num_pages_per_seq - 1); // never past the block table row (cache_seqlens is trusted otherwise)
int phys = block_table[batch * num_pages_per_seq + page];
- row0 = phys * PAGE + (n0 - page * PAGE);
+ row0 = phys * PAGE + min(n0 - page * PAGE, PAGE - 16);
lim = n_end - 1 - n0; // last valid token of the slab (>= 0)
};
auto load_k = [&]() {
diff --git a/exllamav3/modules/attention_fn/qwrite_triton.py b/exllamav3/modules/attention_fn/qwrite_triton.py
index 92cbc41..aa9d748 100644
--- a/exllamav3/modules/attention_fn/qwrite_triton.py
+++ b/exllamav3/modules/attention_fn/qwrite_triton.py
@@ -68,3 +68,74 @@ def quant_cache_paged8(k_in, k_out, k_sc, v_in, v_out, v_sc, cache_seqlens, bloc
_quant_cache_paged8_kernel[(bsz * seq_len,)](
k_in, v_in, k_out, v_out, k_sc, v_sc, cache_seqlens, block_table,
seq_len, block_table.shape[1], in_contig=bool(in_contiguous), G=G, num_warps=1)
+
+
+def _quant_row_bits(inp, out, sc, src, dst, G: tl.constexpr, BITS: tl.constexpr):
+ """_quant_row8 for any width 2..8: codes = floor(v/scale * 2^(B-1) + 2^(B-1)) clamped to [0, 2^B), packed as the cache's
+ power-of-two bit planes, highest plane first (8, 4, 2, 1 bits per value, the planes B contains); plane of width W is W words,
+ value i of the group in word i // (32 / W) at bit (i % (32 / W)) * W."""
+ og = tl.arange(0, G)[:, None]
+ oi = tl.arange(0, 32)[None, :]
+ x = tl.load(inp + src * (G * 32) + og * 32 + oi).to(tl.float32)
+ x = _h32_stage(x, G, 1)
+ x = _h32_stage(x, G, 2)
+ x = _h32_stage(x, G, 4)
+ x = _h32_stage(x, G, 8)
+ x = _h32_stage(x, G, 16)
+ x = x * 0.17677669529663688
+ s = tl.max(tl.abs(x), axis=1) + 1.0e-10
+ inv = tl.math.div_rn(tl.full((G,), 1.0, tl.float32), s)
+ v = x * inv[:, None]
+ M: tl.constexpr = float(1 << (BITS - 1))
+ c = tl.floor(v * M + M)
+ c = tl.minimum(tl.maximum(c, 0.0), float((1 << BITS) - 1)).to(tl.int32)
+ base = dst * (G * BITS)
+ po = 0
+ if BITS & 8:
+ f = tl.reshape((c >> (BITS - 8)) & 255, (G, 8, 4))
+ words = tl.sum(f << ((tl.arange(0, 4) * 8)[None, None, :]), axis=2)
+ tl.store(out + base + og * BITS + po + tl.arange(0, 8)[None, :], words)
+ po += 8
+ if BITS & 4:
+ f = tl.reshape((c >> (BITS & 3)) & 15, (G, 4, 8))
+ words = tl.sum(f << ((tl.arange(0, 8) * 4)[None, None, :]), axis=2)
+ tl.store(out + base + og * BITS + po + tl.arange(0, 4)[None, :], words)
+ po += 4
+ if BITS & 2:
+ f = tl.reshape((c >> (BITS & 1)) & 3, (G, 2, 16))
+ words = tl.sum(f << ((tl.arange(0, 16) * 2)[None, None, :]), axis=2)
+ tl.store(out + base + og * BITS + po + tl.arange(0, 2)[None, :], words)
+ po += 2
+ if BITS & 1:
+ f = tl.reshape(c & 1, (G, 1, 32))
+ words = tl.sum(f << (tl.arange(0, 32)[None, None, :]), axis=2)
+ tl.store(out + base + og * BITS + po + tl.arange(0, 1)[None, :], words)
+ tl.store(sc + dst * G + tl.arange(0, G), s.to(tl.float16))
+
+
+def _quant_cache_paged_bits_kernel(
+ k_in, v_in, k_out, v_out, k_sc, v_sc, seqlens, btable,
+ seq_len, pages_per_seq, in_contig: tl.constexpr, G: tl.constexpr, KB: tl.constexpr, VB: tl.constexpr,
+):
+ row = tl.program_id(0)
+ b = row // seq_len
+ t = row % seq_len
+ tok = tl.load(seqlens + b) + t
+ page = tl.load(btable + b * pages_per_seq + tok // 256)
+ dst = page.to(tl.int64) * 256 + tok % 256
+ if in_contig:
+ src = row.to(tl.int64)
+ else:
+ src = dst
+ _quant_row_bits(k_in, k_out, k_sc, src, dst, G, KB)
+ _quant_row_bits(v_in, v_out, v_sc, src, dst, G, VB)
+
+
+def quant_cache_paged_bits(k_in, k_out, k_sc, v_in, v_out, v_sc, cache_seqlens, block_table, seq_len, in_contiguous, k_bits, v_bits):
+ G = k_sc.shape[-1]
+ bsz = block_table.shape[0]
+ _quant_cache_paged_bits_kernel[(bsz * seq_len,)](
+ k_in, v_in, k_out, v_out, k_sc, v_sc, cache_seqlens, block_table,
+ seq_len, block_table.shape[1], in_contig=bool(in_contiguous), G=G, KB=k_bits, VB=v_bits, num_warps=1)
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index 4690a7d..9f528a8 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -1094,26 +1094,44 @@ from . import qdec_hip as _qh
_QDEC_HIP = _qh.ENABLED
+_QDEC_HIP_DEBUG = os.environ.get("EXL3_QDEC_HIP_DEBUG") == "1"
+_qdec_hip_stats = {}
+
+
+def _qdec_hip_note(key):
+ _qdec_hip_stats[key] = _qdec_hip_stats.get(key, 0) + 1
+
+
+if _QDEC_HIP_DEBUG:
+ import atexit
+ atexit.register(lambda: print("QDEC_HIP calls:", dict(sorted(_qdec_hip_stats.items(), key = lambda kv: str(kv[0]))), flush = True))
+
+
def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap, sinks, out,
num_splits, max_kv_len, qc, kv_append_len, n_kv_heads):
"""The qdec.hip path of paged_attn_triton_decode, or None when the call is outside its shapes (the Triton kernels then run it)"""
k_scales, v_scales, qck, qcv = qc
- if (q.dtype != torch.float16 or q.ndim != 4 or not q.is_contiguous() or num_splits is not None
- or not all(t.is_contiguous() for t in (k_cache, v_cache, k_scales, v_scales, block_table, cache_seqlens))
- or block_table.dtype != torch.int32 or cache_seqlens.dtype != torch.int32 or k_cache.dtype != torch.int32
- or v_cache.dtype != torch.int32 or k_scales.dtype != torch.float16 or v_scales.dtype != torch.float16):
+ why = None
+ if q.dtype != torch.float16 or q.ndim != 4: why = "q dtype/rank"
+ elif not q.is_contiguous(): why = "q not contiguous"
+ elif num_splits is not None: why = "num_splits given"
+ elif not all(t.is_contiguous() for t in (k_cache, v_cache, k_scales, v_scales, block_table, cache_seqlens)): why = "cache tensor not contiguous"
+ elif block_table.dtype != torch.int32 or cache_seqlens.dtype != torch.int32: why = "table/seqlens dtype"
+ elif k_cache.dtype != torch.int32 or v_cache.dtype != torch.int32 or k_scales.dtype != torch.float16 or v_scales.dtype != torch.float16: why = "cache dtype"
+ if why is not None:
+ if _QDEC_HIP_DEBUG: _qdec_hip_note(("no", why))
return None
bsz, q_len, n_q_heads, head_dim = q.shape
if softmax_scale is None:
softmax_scale = 1.0 / math.sqrt(head_dim)
window_left, window_right = _normalize_window(window_size)
sinks, has_sinks = _prep_sinks(sinks, n_q_heads, q)
- if has_sinks and (sinks.dtype != torch.float32 or not sinks.is_contiguous()):
- return None
cfg = _qh.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, k_cache.shape[1], causal, softmax_scale,
window_left, window_right, softcap, kv_append_len, has_sinks)
if cfg is None:
+ if _QDEC_HIP_DEBUG: _qdec_hip_note(("no", f"cfg q_len {q_len} hd {head_dim} {n_q_heads}/{n_kv_heads} bits {qck},{qcv} window {window_left},{window_right} softcap {softcap} append {kv_append_len}"))
return None
+ if _QDEC_HIP_DEBUG: _qdec_hip_note(("hip", f"q_len {q_len} hd {head_dim} bits {qck},{qcv} sinks {has_sinks}"))
max_k_len = block_table.shape[1] * k_cache.shape[1] + kv_append_len
if max_kv_len is not None:
max_k_len = min(max_k_len, max_kv_len + kv_append_len)
diff --git a/tests/ab_decode.py b/tests/ab_decode.py
new file mode 100644
index 0000000..1ebdae2
--- /dev/null
+++ b/tests/ab_decode.py
@@ -0,0 +1,56 @@
+"""ab_decode.py PACK SETTINGS.json [--depth 4096] [--kv 16|K,V] [--win 48] [--reps 6]
+In-process A/B of decode-time environment knobs that the C++ extension reads on every call (getenv): one prefill, then one long greedy job whose
+tokens are cut into windows; window i runs under settings[i % len(settings)] (a list of {"name":..., "env": {VAR: value or null}}), reps windows each.
+Alternating inside one process cancels the box-wide drift that makes separate runs differ by +-10 %. Prints per-setting median/min/max tok/s."""
+import argparse, json, os, sys, time, statistics
+ROOT = os.environ.get("ENG") or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.cache import CacheLayer_quant
+from exllamav3.generator.sampler.presets import GreedySampler
+ap = argparse.ArgumentParser(); ap.add_argument("pack"); ap.add_argument("settings"); ap.add_argument("--depth", type=int, default=4096)
+ap.add_argument("--kv", default="16"); ap.add_argument("--win", type=int, default=48); ap.add_argument("--reps", type=int, default=6)
+a = ap.parse_args()
+settings = json.load(open(a.settings))
+cfg = Config.from_directory(a.pack); model = Model.from_config(cfg); tok = Tokenizer.from_config(cfg)
+total = a.win * len(settings) * a.reps + 2 * a.win
+ctx = ((a.depth + total + 512 + 255) // 256) * 256
+if a.kv == "16": cache = Cache(model, max_num_tokens=ctx)
+else:
+ kb, vb = (int(x) for x in a.kv.split(",")); cache = Cache(model, max_num_tokens=ctx, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)
+model.load(progressbar=False)
+gen = Generator(model=model, cache=cache, tokenizer=tok)
+D = os.path.join(ROOT, "exllamav3/conversion/standard_cal_data")
+s = open(f"{D}/wiki.utf8", encoding="utf8").read()
+ids = tok.encode(s[3000:3000 + a.depth * 8], add_bos=False).flatten()[:a.depth].view(1, -1)
+job = Job(input_ids=ids, max_new_tokens=total, sampler=GreedySampler(), stop_conditions=[])
+gen.enqueue(job)
+base_env = {}
+for st in settings:
+ for k in st["env"]: base_env.setdefault(k, os.environ.get(k))
+def apply(st):
+ for k, v in base_env.items():
+ if v is None: os.environ.pop(k, None)
+ else: os.environ[k] = v
+ for k, v in st["env"].items():
+ if v is None: os.environ.pop(k, None)
+ else: os.environ[k] = str(v)
+n = -a.win; cur = None; stamps = []; results = {st["name"]: [] for st in settings}; widx = -1
+apply(settings[0])
+while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("text", "") == "": continue
+ n += 1
+ if n < 0: continue # warm-up window
+ if n % a.win == 0:
+ now = time.time()
+ if widx >= 0 and stamps: results[settings[widx % len(settings)]["name"]].append(a.win / (now - stamps[-1]))
+ widx += 1; stamps.append(now)
+ if widx < len(settings) * a.reps: apply(settings[widx % len(settings)])
+ else: gen.cancel(job) if hasattr(gen, "cancel") else None
+print(f"depth {a.depth} kv {a.kv} window {a.win} tokens x {a.reps} reps per setting")
+b = statistics.median(results[settings[0]["name"]]) if results[settings[0]["name"]] else 1
+for st in settings:
+ v = results[st["name"]]
+ if v: print(f" {st['name']:28s} median {statistics.median(v):6.2f} tok/s ({statistics.median(v) / b * 100 - 100:+5.1f} % vs {settings[0]['name']}) min {min(v):.2f} max {max(v):.2f} n={len(v)}")
diff --git a/tests/prof_decode.py b/tests/prof_decode.py
new file mode 100644
index 0000000..8c064f6
--- /dev/null
+++ b/tests/prof_decode.py
@@ -0,0 +1,48 @@
+"""prof_decode.py PACK [--depth 4096] [--kv 16|K,V] [--steps 24]: kernel-time table of steady greedy decode steps (torch profiler).
+Prints per-kernel total/avg us per step (top 40) and the step wall time, to find where a decode step spends its time."""
+import argparse, os, sys, time
+ROOT = os.environ.get("ENG") or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+import torch
+from torch.profiler import profile, ProfilerActivity
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.cache import CacheLayer_quant
+from exllamav3.generator.sampler.presets import GreedySampler
+ap = argparse.ArgumentParser(); ap.add_argument("pack"); ap.add_argument("--depth", type=int, default=4096); ap.add_argument("--kv", default="16")
+ap.add_argument("--steps", type=int, default=24); ap.add_argument("--top", type=int, default=40); ap.add_argument("--noprof", action="store_true")
+a = ap.parse_args()
+cfg = Config.from_directory(a.pack); model = Model.from_config(cfg); tok = Tokenizer.from_config(cfg)
+ctx = ((a.depth + a.steps + 512 + 255) // 256) * 256
+if a.kv == "16": cache = Cache(model, max_num_tokens=ctx)
+else:
+ kb, vb = (int(x) for x in a.kv.split(",")); cache = Cache(model, max_num_tokens=ctx, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)
+model.load(progressbar=False)
+gen = Generator(model=model, cache=cache, tokenizer=tok)
+D = os.path.join(ROOT, "exllamav3/conversion/standard_cal_data")
+s = open(f"{D}/wiki.utf8", encoding="utf8").read()
+ids = tok.encode(s[3000:3000 + a.depth * 8], add_bos=False).flatten()[:a.depth].view(1, -1)
+job = Job(input_ids=ids, max_new_tokens=a.steps + 40, sampler=GreedySampler(), stop_conditions=[])
+gen.enqueue(job)
+n = 0; prof = None; t0 = None
+while gen.num_remaining_jobs():
+ if a.noprof:
+ for r in gen.iterate():
+ if r.get("text", "") != "": n += 1
+ continue
+ if n == 16 and prof is None:
+ torch.cuda.synchronize(); prof = profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]); prof.__enter__(); t0 = time.time()
+ for r in gen.iterate():
+ if r.get("text", "") != "": n += 1
+ if prof is not None and n >= 16 + a.steps:
+ torch.cuda.synchronize(); wall = time.time() - t0; prof.__exit__(None, None, None); break
+if a.noprof: print("decoded", n, "tokens"); sys.exit(0)
+print(f"wall per step {wall / a.steps * 1000:.2f} ms ({a.steps / wall:.1f} tok/s under the profiler)")
+ev = prof.key_averages()
+rows = sorted(ev, key=lambda e: -e.device_time_total)
+tot = sum(e.device_time_total for e in rows if e.device_type == torch.autograd.DeviceType.CUDA) if hasattr(torch.autograd, "DeviceType") else 0
+print(f"{'kernel':80s} {'calls/step':>10s} {'us/step':>9s} {'avg us':>8s}")
+tot_us = 0
+for e in rows[:a.top]:
+ if e.device_time_total <= 0: continue
+ print(f"{e.key[:80]:80s} {e.count / a.steps:10.1f} {e.device_time_total / a.steps:9.1f} {e.device_time_total / max(e.count, 1):8.1f}")
+print("sum of listed device us/step:", sum(e.device_time_total for e in rows[:a.top] if e.device_time_total > 0) / a.steps)
diff --git a/tests/test_qwrite.py b/tests/test_qwrite.py
new file mode 100644
index 0000000..5780c0f
--- /dev/null
+++ b/tests/test_qwrite.py
@@ -0,0 +1,50 @@
+"""Native Triton paged cache writer (any K/V width 2..8) vs the PyTorch fallback: the packed words and fp16 scales must be bit-identical.
+python tests/test_qwrite.py"""
+import os, sys, time
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+import torch
+from exllamav3 import ext_fallbacks as fb
+
+dev = torch.device("cuda"); torch.manual_seed(0)
+PAGE = 256; bad = 0
+for kvh, hd in ((4, 128), (2, 256)):
+ dim = kvh * hd; G = dim // 32
+ for kb, vb in ((8, 8), (6, 6), (4, 4), (5, 3), (7, 2), (2, 8), (3, 3), (4, 8), (2, 2)):
+ for bsz, seq_len, contig in ((1, 1, True), (2, 1, True), (1, 37, True), (2, 300, True), (1, 40, False)):
+ pages = bsz * (-(-(seq_len + 80) // PAGE)) + 2
+ seqlens = torch.tensor([17 * (i + 1) for i in range(bsz)], dtype=torch.int32, device=dev)
+ ppseq = -(-(int(seqlens.max()) + seq_len) // PAGE) + 1
+ bt = torch.randperm(pages, device=dev)[: bsz * ppseq].to(torch.int32).view(bsz, ppseq).contiguous()
+ n_in = bsz * seq_len * dim if contig else pages * PAGE * dim
+ k_in = (torch.randn(n_in, device=dev) * torch.exp(torch.randn(n_in, device=dev))).clamp(-60000, 60000).to(torch.float16)
+ v_in = (torch.randn(n_in, device=dev) * 2).to(torch.float16)
+ shp = (bsz, seq_len, kvh, hd) if contig else (pages, PAGE, kvh, hd)
+ k_in = k_in.view(shp); v_in = v_in.view(shp)
+ outs = []
+ for native in (True, False):
+ fb._QW_OFF = not native
+ ko = torch.zeros(pages, PAGE, G * kb, dtype=torch.int32, device=dev); vo = torch.zeros(pages, PAGE, G * vb, dtype=torch.int32, device=dev)
+ ks = torch.zeros(pages, PAGE, G, dtype=torch.float16, device=dev); vs = torch.zeros_like(ks)
+ fb.quant_cache_paged(k_in, ko, ks, v_in, vo, vs, seqlens, bt, PAGE, seq_len, 0.0, contig)
+ outs.append((ko, vo, ks, vs))
+ ok = all(torch.equal(a, b) for a, b in zip(*outs))
+ if not ok:
+ bad += 1
+ nd = [int((a != b).sum()) for a, b in zip(*outs)]
+ print(f"MISMATCH kvh{kvh} hd{hd} k{kb}v{vb} bsz{bsz} seq{seq_len} contig{contig}: differing elements k,v,ks,vs = {nd}")
+print("writer: all identical" if not bad else f"writer: {bad} mismatching configs")
+# speed: decode-sized (1 row) and prefill-sized (4096 rows) append, native vs fallback
+for kb, vb in ((6, 6), (4, 4)):
+ kvh, hd = 4, 128; dim = kvh * hd; G = dim // 32
+ for seq_len in (1, 4096):
+ pages = -(-(seq_len + 300) // PAGE) + 1
+ bt = torch.arange(pages, device=dev, dtype=torch.int32).view(1, -1); seqlens = torch.tensor([100], dtype=torch.int32, device=dev)
+ k_in = torch.randn(1, seq_len, kvh, hd, device=dev).to(torch.float16); v_in = torch.randn(1, seq_len, kvh, hd, device=dev).to(torch.float16)
+ for native in (True, False):
+ fb._QW_OFF = not native
+ ko = torch.zeros(pages, PAGE, G * kb, dtype=torch.int32, device=dev); vo = torch.zeros(pages, PAGE, G * vb, dtype=torch.int32, device=dev)
+ ks = torch.zeros(pages, PAGE, G, dtype=torch.float16, device=dev); vs = torch.zeros_like(ks)
+ for _ in range(3): fb.quant_cache_paged(k_in, ko, ks, v_in, vo, vs, seqlens, bt, PAGE, seq_len, 0.0, True)
+ torch.cuda.synchronize(); t = time.perf_counter(); n = 20 if seq_len == 1 else 3
+ for _ in range(n): fb.quant_cache_paged(k_in, ko, ks, v_in, vo, vs, seqlens, bt, PAGE, seq_len, 0.0, True)
+ torch.cuda.synchronize(); print(f"k{kb}v{vb} rows {seq_len:5d} {'native ' if native else 'fallback'}: {(time.perf_counter() - t) / n * 1e6:10.1f} us/call")
diff --git a/tools/bench_flint.py b/tools/bench_flint.py
index 94343db..8885d71 100644
--- a/tools/bench_flint.py
+++ b/tools/bench_flint.py
@@ -64,7 +64,10 @@ if ttft is None: # no token came back: the job errored (printed above), e.g.
print(json.dumps({"depth": a.depth, "kv": a.kv, "error": "no tokens generated", "ctx": ctx}), flush=True)
sys.exit(1)
tg = (len(times) - 1) / (times[-1] - times[0]) if len(times) > 2 else 0.0
-res = {"depth": a.depth, "kv": a.kv, "ttft": ttft, "pp": a.depth / ttft, "tg": tg, "ntok": ntok,
+# --gen of 3 x 64 or more: also report the steady decode rate of each consecutive 64-token window and their median (shared-box noise)
+wins = [(63 / (times[i + 63] - times[i])) for i in range(0, len(times) - 63, 64)] if len(times) >= 127 else []
+if wins: tg = sorted(wins)[len(wins) // 2]
+res = {"depth": a.depth, "kv": a.kv, "ttft": ttft, "pp": a.depth / ttft, "tg": tg, "tg_windows": wins, "ntok": ntok,
"peak_gib": torch.cuda.max_memory_allocated() / 2**30, "reserved_gib": torch.cuda.max_memory_reserved() / 2**30}
print(json.dumps(res), flush=True)
if a.out: json.dump(res, open(a.out, "w"))
diff --git a/tools/qwen/gate_texts.py b/tools/qwen/gate_texts.py
new file mode 100644
index 0000000..9573f2d
--- /dev/null
+++ b/tools/qwen/gate_texts.py
@@ -0,0 +1,27 @@
+"""usage: gate_texts.py PORT MODEL_ID OUT.json DEPTH[,DEPTH...] [N=128]: three greedy answers (temperature 0, N tokens) per depth to real-text
+prompts of ~DEPTH tokens, saved for a text-equality comparison of two server builds/flags (gate_texts.py A.json B.json compare mode:
+gate_texts.py --cmp A.json B.json)."""
+import sys, json, time, os, urllib.request
+if sys.argv[1] == "--cmp":
+ A, B = json.load(open(sys.argv[2])), json.load(open(sys.argv[3]))
+ for k in A:
+ for i, (a, b) in enumerate(zip(A[k], B[k])):
+ div = next((j for j in range(min(len(a), len(b))) if a[j] != b[j]), None)
+ print(f"depth {k} prompt {i}: {'IDENTICAL' if div is None and len(a) == len(b) else 'DIVERGES at char ' + str(div)} ({len(a)}/{len(b)} chars)")
+ sys.exit(0)
+port, mid, out, depths = sys.argv[1:5]; n = int(sys.argv[5]) if len(sys.argv) > 5 else 128
+D = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "exllamav3", "conversion", "standard_cal_data")
+def post(body, t=3600):
+ r = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", json.dumps({"model": mid, **body}).encode(), {"Content-Type": "application/json"})
+ return json.load(urllib.request.urlopen(r, timeout=t))
+srcs = [open(f"{D}/{f}", encoding="utf8").read() for f in ("wiki.utf8", "c4.utf8", "technical.utf8")]
+res = {}
+for d in (int(x) for x in depths.split(",")):
+ res[str(d)] = []
+ for i, s in enumerate(srcs):
+ off = 4000 * (i + 1) + 77 * d % 5000
+ prompt = s[off:off + int(d * 4.2)]
+ r = post({"messages": [{"role": "user", "content": prompt + "\n\nSummarize the text above in three sentences."}], "max_tokens": n, "temperature": 0, "enable_thinking": False})
+ res[str(d)].append(r["choices"][0]["message"]["content"])
+ print(f"depth {d} prompt {i}: {r['usage']['prompt_tokens']} prompt tokens, {len(res[str(d)][-1])} chars", flush=True)
+json.dump(res, open(out, "w"))