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.

1.5.10: flat long-context curves

YanissAmz3c17f604cbd5
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 0c7bf1a..86f5d26 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -459,6 +459,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
py::arg("scores"), py::arg("indices"), py::arg("k") = 512);
m.def("dsa_topk_par", &dsa_topk_par, "dsa_topk_par",
py::arg("scores"), py::arg("indices"), py::arg("k") = 512, py::arg("nb") = 0);
+ m.def("dsa_topk_gfx12_v2", &dsa_topk_gfx12_v2, "dsa_topk_gfx12_v2",
+ py::arg("scores"), py::arg("indices"), py::arg("k") = 512, py::arg("threads") = 512);
m.def("pack_trellis", &pack_trellis, "pack_trellis");
m.def("unpack_trellis", &unpack_trellis, "unpack_trellis");
m.def("pack_signs", &pack_signs, "pack_signs");
diff --git a/exllamav3/exllamav3_ext/dsa_topk_gfx12.cu b/exllamav3/exllamav3_ext/dsa_topk_gfx12.cu
index 3b99303..2e25b62 100644
--- a/exllamav3/exllamav3_ext/dsa_topk_gfx12.cu
+++ b/exllamav3/exllamav3_ext/dsa_topk_gfx12.cu
@@ -20,6 +20,7 @@ constexpr int WAVE_SIZE = 32;
constexpr int THREADS = 1024;
constexpr int K_MAX = 512; // top-k and output width bound (QSA shape)
constexpr uint16_t KEY_NEG_INF = 0x03ff;
+constexpr int V2_MAX_WIDTH = 32768; // dsa_topk_gfx12_v2: THREADS * CH * 8 for both instantiations
__device__ __forceinline__ uint16_t topk_key(uint16_t bits)
{
@@ -153,6 +154,160 @@ void dsa_topk_gfx12_kernel(const half* __restrict__ scores, int* __restrict__ ou
for (; output < out_w; ++output) row_out[output] = -1;
}
+// ---------------------------------------------------------------------------------------------
+// v2: the same selection (bitwise-identical output), the row read from memory ONCE.
+//
+// v1 reads the row four times (coarse histogram, fine histogram, tie/high count, write), the first two with 2-byte
+// coalesced loads (one 64 B request per wave-load) and the last two with 2-byte loads at a 64 B lane stride. For a
+// 256-row x 32768 score tile that is memory-latency bound, not bandwidth bound (0.33 ms per call at 500K context).
+// v2 gives each thread CH consecutive 8-element chunks (16 B vector loads, thread t owns chunks
+// [n_chunks*t/THREADS, n_chunks*(t+1)/THREADS), so thread order is index order exactly like v1's element ranges),
+// keeps their 8*CH order keys in registers and runs every pass over the registers. Selection contract unchanged:
+// all keys above the threshold plus the first `ties_needed` keys equal to it by ascending index, ascending output,
+// -1 padding. Requires width <= THREADS * CH * 8 and a 16-byte aligned score base (host checks both).
+// ---------------------------------------------------------------------------------------------
+template <int THREADS>
+__device__ __forceinline__ int block_exclusive_scan_t(
+ int value, int lane, int warp, int* warp_sums, int* warp_offsets)
+{
+ constexpr int NW = THREADS / WAVE_SIZE;
+ int inclusive = value;
+ #pragma unroll
+ for (int offset = 1; offset < WAVE_SIZE; offset <<= 1)
+ {
+ const int other = __shfl_up_sync(0xffffffffu, inclusive, offset);
+ if (lane >= offset) inclusive += other;
+ }
+ if (lane == WAVE_SIZE - 1) warp_sums[warp] = inclusive;
+ __syncthreads();
+
+ if (warp == 0)
+ {
+ const int own = lane < NW ? warp_sums[lane] : 0;
+ int warp_inclusive = own;
+ #pragma unroll
+ for (int offset = 1; offset < WAVE_SIZE; offset <<= 1)
+ {
+ const int other = __shfl_up_sync(0xffffffffu, warp_inclusive, offset);
+ if (lane >= offset) warp_inclusive += other;
+ }
+ if (lane < NW) warp_offsets[lane] = warp_inclusive - own;
+ }
+ __syncthreads();
+ return warp_offsets[warp] + inclusive - value;
+}
+
+template <int THREADS, int CH>
+__global__ __launch_bounds__(THREADS)
+void dsa_topk_gfx12_v2_kernel(const half* __restrict__ scores, int* __restrict__ out, int width, int stride,
+ int K, int out_w)
+{
+ static_assert(THREADS >= 256 && THREADS % WAVE_SIZE == 0 && THREADS / WAVE_SIZE <= WAVE_SIZE, "block shape");
+ constexpr int NW = THREADS / WAVE_SIZE;
+ constexpr int NK = CH * 8;
+ const int tid = threadIdx.x;
+ const half* row_scores = scores + static_cast<size_t>(blockIdx.x) * stride;
+ int* row_out = out + static_cast<size_t>(blockIdx.x) * out_w;
+
+ __shared__ int hist[256];
+ __shared__ int search[2];
+ __shared__ int warp_sums[NW];
+ __shared__ int warp_offsets[NW];
+
+ if (tid < 256) hist[tid] = 0;
+
+ // One pass over memory. Chunk c covers elements [8c, 8c + 8); thread t owns chunks [c0, c1), c1 - c0 <= CH
+ // because n_chunks <= THREADS * CH. Elements at or past `width` are never read and get key 0 (invalid).
+ const int n_chunks = (width + 7) >> 3;
+ const int c0 = static_cast<int>(static_cast<int64_t>(n_chunks) * tid / THREADS);
+ const int c1 = static_cast<int>(static_cast<int64_t>(n_chunks) * (tid + 1) / THREADS);
+ uint16_t keys[NK];
+ #pragma unroll
+ for (int j = 0; j < CH; ++j)
+ {
+ const int c = c0 + j;
+ const int base = c * 8;
+ if (c < c1 && base + 8 <= width)
+ {
+ const uint4 v = *reinterpret_cast<const uint4*>(row_scores + base);
+ const uint32_t w4[4] = {v.x, v.y, v.z, v.w};
+ #pragma unroll
+ for (int e = 0; e < 8; ++e)
+ keys[j * 8 + e] = topk_key(static_cast<uint16_t>((w4[e >> 1] >> ((e & 1) * 16)) & 0xffffu));
+ }
+ else if (c < c1)
+ {
+ #pragma unroll
+ for (int e = 0; e < 8; ++e)
+ keys[j * 8 + e] = (base + e < width) ? topk_key(__half_as_ushort(row_scores[base + e]))
+ : static_cast<uint16_t>(0);
+ }
+ else
+ {
+ #pragma unroll
+ for (int e = 0; e < 8; ++e) keys[j * 8 + e] = 0;
+ }
+ }
+
+ __syncthreads();
+ #pragma unroll
+ for (int i = 0; i < NK; ++i)
+ if (keys[i] > KEY_NEG_INF) atomicAdd(&hist[keys[i] >> 8], 1);
+ __syncthreads();
+ if (tid == 0) find_descending_bucket(hist, K, search);
+ __syncthreads();
+
+ const int high_bucket = search[0];
+ const int count_above_high = search[1];
+ uint16_t threshold = KEY_NEG_INF;
+ int ties_needed = 0;
+ if (high_bucket >= 0)
+ {
+ if (tid < 256) hist[tid] = 0;
+ __syncthreads();
+ #pragma unroll
+ for (int i = 0; i < NK; ++i)
+ if (keys[i] > KEY_NEG_INF && (keys[i] >> 8) == high_bucket) atomicAdd(&hist[keys[i] & 0xff], 1);
+ __syncthreads();
+ if (tid == 0) find_descending_bucket(hist, K - count_above_high, search);
+ __syncthreads();
+ threshold = static_cast<uint16_t>((high_bucket << 8) | search[0]);
+ ties_needed = K - count_above_high - search[1];
+ }
+
+ const int lane = tid % WAVE_SIZE;
+ const int warp = tid / WAVE_SIZE;
+ int high_count = 0;
+ int tie_count = 0;
+ #pragma unroll
+ for (int i = 0; i < NK; ++i)
+ {
+ if (keys[i] > threshold && keys[i] > KEY_NEG_INF) ++high_count;
+ else if (keys[i] == threshold && keys[i] > KEY_NEG_INF) ++tie_count;
+ }
+
+ const int tie_offset = block_exclusive_scan_t<THREADS>(tie_count, lane, warp, warp_sums, warp_offsets);
+ const int local_ties = max(0, min(tie_count, ties_needed - tie_offset));
+ const int selected_count = high_count + local_ties;
+ int output = block_exclusive_scan_t<THREADS>(selected_count, lane, warp, warp_sums, warp_offsets);
+
+ int seen_ties = 0;
+ #pragma unroll
+ for (int i = 0; i < NK; ++i)
+ {
+ const int index = c0 * 8 + i; // chunk c0 + j, element e: 8 * (c0 + j) + e = c0 * 8 + (j * 8 + e)
+ if (keys[i] > threshold && keys[i] > KEY_NEG_INF)
+ row_out[output++] = index;
+ else if (keys[i] == threshold && keys[i] > KEY_NEG_INF)
+ {
+ if (seen_ties < local_ties) row_out[output++] = index;
+ ++seen_ties;
+ }
+ }
+ if (tid == THREADS - 1)
+ for (; output < out_w; ++output) row_out[output] = -1;
+}
+
bool is_gfx12_wave32(int device)
{
hipDeviceProp_t prop;
@@ -200,4 +355,40 @@ void dsa_topk_gfx12(const at::Tensor& scores, at::Tensor& indices, int64_t k)
cuda_check(hipPeekAtLastError());
}
+void dsa_topk_gfx12_v2(const at::Tensor& scores, at::Tensor& indices, int64_t k, int64_t threads)
+{
+ TORCH_CHECK(scores.is_cuda() && indices.is_cuda(), "dsa_topk_gfx12_v2 requires device tensors");
+ const at::cuda::OptionalCUDAGuard device_guard(scores.device());
+ const int device = scores.get_device();
+ TORCH_CHECK(is_gfx12_wave32(device), "dsa_topk_gfx12_v2 requires a wave32 gfx11.5/gfx12 part");
+ TORCH_CHECK(scores.device() == indices.device(), "dsa_topk_gfx12_v2 tensors must share a device");
+ TORCH_CHECK(scores.dtype() == at::kHalf && indices.dtype() == at::kInt,
+ "dsa_topk_gfx12_v2 requires fp16 scores and int32 indices");
+ TORCH_CHECK(scores.dim() == 2 && indices.dim() == 2 && scores.size(0) == indices.size(0),
+ "dsa_topk_gfx12_v2 requires matching 2D tensors");
+ TORCH_CHECK(scores.size(1) <= V2_MAX_WIDTH && scores.stride(0) <= INT_MAX,
+ "dsa_topk_gfx12_v2 requires score width <= 32768");
+ TORCH_CHECK(k >= 1 && k <= K_MAX, "dsa_topk_gfx12_v2 requires 1 <= k <= 512");
+ TORCH_CHECK(scores.size(1) >= 1 && scores.stride(1) == 1 && scores.stride(0) >= scores.size(1) &&
+ scores.stride(0) % 128 == 0,
+ "dsa_topk_gfx12_v2 requires scores with T >= 1 and a 128-aligned row stride");
+ TORCH_CHECK(reinterpret_cast<uintptr_t>(scores.data_ptr()) % 16 == 0,
+ "dsa_topk_gfx12_v2 requires a 16-byte aligned score base");
+ TORCH_CHECK(indices.size(1) >= k && indices.size(1) <= K_MAX && indices.is_contiguous(),
+ "dsa_topk_gfx12_v2 requires contiguous int32 [R, W] output with k <= W <= 512");
+ TORCH_CHECK(threads == 512 || threads == 1024, "dsa_topk_gfx12_v2 threads must be 512 or 1024");
+ if (scores.size(0) == 0) return;
+
+ hipStream_t stream = at::cuda::getCurrentCUDAStream(device).stream();
+ const half* sp = reinterpret_cast<const half*>(scores.data_ptr());
+ int* op = reinterpret_cast<int*>(indices.data_ptr());
+ const int w = static_cast<int>(scores.size(1)), st = static_cast<int>(scores.stride(0));
+ const int kk = static_cast<int>(k), ow = static_cast<int>(indices.size(1));
+ if (threads == 512)
+ dsa_topk_gfx12_v2_kernel<512, 8><<<scores.size(0), 512, 0, stream>>>(sp, op, w, st, kk, ow);
+ else
+ dsa_topk_gfx12_v2_kernel<1024, 4><<<scores.size(0), 1024, 0, stream>>>(sp, op, w, st, kk, ow);
+ cuda_check(hipPeekAtLastError());
+}
+
#endif // USE_ROCM
diff --git a/exllamav3/exllamav3_ext/dsa_topk_gfx12.cuh b/exllamav3/exllamav3_ext/dsa_topk_gfx12.cuh
index a66726b..65881c2 100644
--- a/exllamav3/exllamav3_ext/dsa_topk_gfx12.cuh
+++ b/exllamav3/exllamav3_ext/dsa_topk_gfx12.cuh
@@ -8,4 +8,8 @@
// contiguous int32 (R, W), k <= W <= 512, ascending indices then -1 padding.
void dsa_topk_gfx12(const at::Tensor& scores, at::Tensor& indices, int64_t k);
+// Same contract and bitwise-identical output, row read from memory once (width <= 32768, 16-byte aligned base,
+// threads 512 or 1024).
+void dsa_topk_gfx12_v2(const at::Tensor& scores, at::Tensor& indices, int64_t k, int64_t threads);
+
#endif
diff --git a/exllamav3/ext.py b/exllamav3/ext.py
index b489399..8767df8 100644
--- a/exllamav3/ext.py
+++ b/exllamav3/ext.py
@@ -303,11 +303,23 @@ if torch.version.hip:
# Keep the public API stable while using the native QSA kernel (k <= 512, moeA5) only for its
# validated gfx12 wave32 shape. Everything else retains the general PyTorch fallback.
if hasattr(exllamav3_ext, "dsa_topk_gfx12"):
+ # EXL3_DSA_TOPK_V2=1 (default off; env read per call): the row-in-registers kernel (dsa_topk_gfx12_v2, one memory
+ # pass instead of four, bitwise-identical selection) for rows of 8192 < width <= 32768 with a 16-byte aligned base
+ # (narrower rows are not faster: 82 vs 115 us at 2048). topk_v2_switch['on'] lets a harness flip it without the env.
+ # EXL3_DSA_TOPK_V2_THREADS = 512 | 1024.
+ topk_v2 = {"on": False, "threads": int(os.environ.get("EXL3_DSA_TOPK_V2_THREADS", "512"))}
+ setattr(exllamav3_ext, "topk_v2_switch", topk_v2)
+
def _dsa_topk_rocm(scores, indices, k, t_ptr = None, t_seq = 0):
if (
hasattr(exllamav3_ext, "dsa_topk_gfx12") and
_fb.dsa_topk_gfx12_supported(scores, indices, k, t_ptr, t_seq)
):
+ env_v2 = os.environ.get("EXL3_DSA_TOPK_V2") # read per call so one process can A/B it
+ use_v2 = topk_v2["on"] if env_v2 is None else env_v2 == "1"
+ if (use_v2 and 8192 < scores.shape[1] <= 32768 and scores.data_ptr() % 16 == 0 and
+ hasattr(exllamav3_ext, "dsa_topk_gfx12_v2")):
+ return exllamav3_ext.dsa_topk_gfx12_v2(scores, indices, k, topk_v2["threads"])
return exllamav3_ext.dsa_topk_gfx12(scores, indices, k)
return _fb.dsa_topk(scores, indices, k, t_ptr, t_seq)
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index 05eb157..5d0a1eb 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -847,7 +847,7 @@ class Generator:
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,
+ "block_table": seq.prefill_block_table(),
"cache": self.draft_cache,
"cache_seqlens": torch.tensor([pos], dtype = torch.int32),
"target_hidden": job.mtp_defer_carry,
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index 6742ffe..25ac005 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -1509,7 +1509,7 @@ class Job:
params = {
"attn_mode": "flash_attn",
- "block_table": seq.block_index_tensor,
+ "block_table": seq.prefill_block_table(),
"cache": self.generator.cache,
"cache_seqlens": torch.tensor([prefill_start], dtype = torch.int32),
"recurrent_states": [self.recurrent_state] if self.recurrent_state is not None else None,
@@ -1564,7 +1564,7 @@ class Job:
target_hidden = params.get("export_states"),
cache = self.generator.draft_cache,
params = {
- "block_table": seq.block_index_tensor,
+ "block_table": seq.prefill_block_table(),
"cache_seqlens": params["cache_seqlens"],
}
)
@@ -1582,7 +1582,7 @@ class Job:
draft_params = {
"target_hidden": shifted_hidden,
"attn_mode": "flash_attn",
- "block_table": seq.block_index_tensor,
+ "block_table": seq.prefill_block_table(),
"cache": self.generator.draft_cache,
"cache_seqlens": torch.tensor([prefill_start], dtype = torch.int32),
"indexed_embeddings": self.embeddings if self.generator.mtp_draft else None,
diff --git a/exllamav3/generator/pagetable.py b/exllamav3/generator/pagetable.py
index f429e6a..ad4707f 100644
--- a/exllamav3/generator/pagetable.py
+++ b/exllamav3/generator/pagetable.py
@@ -255,6 +255,19 @@ class Sequence:
dtype = torch.int32,
)
+ def prefill_block_table(self) -> torch.Tensor:
+ """
+ Block table for a prefill forward: the pages of the tokens the sequence holds now, not the pages reserved for
+ the replies still to come. A request without max_tokens reserves the whole cache, so the full table is as wide as
+ -c / 256 and every prefill chunk (target and drafter) would upload and index it for nothing. Whole pages,
+ padded to a multiple of 16 like the decode tables (generator.block_table_pages), never wider than the allocation.
+ """
+ bt = self.block_index_tensor
+ if os.environ.get("EXL3_PF_FULL_BT", "0") == "1": # the 1.5.9 behaviour (A/B switch, read per chunk)
+ return bt
+ w = (((len(self.sequence_ids) + 1 + PAGE_SIZE - 1) // PAGE_SIZE + 15) // 16) * 16
+ return bt if bt.shape[-1] <= w else bt[:, :w]
+
def allocate_pages(
self,
pagetable: PageTable,
diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.py
index 163fb42..1e17f3f 100644
--- a/exllamav3/model/model_ls.py
+++ b/exllamav3/model/model_ls.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from typing import Callable
import os
+import time
import torch
from ..modules.attn import prepare_for_attn
@@ -327,6 +328,7 @@ class Model_LSMixin(ABC):
):
for h in getattr(self.config, "moe_cpu_hosts", {}).values():
h.begin_pass()
+ span = _FWD_SPAN and x.dim() >= 3 and x.shape[1] <= 8 # (batch, rows, ..): decode/verify only, not prefill chunks
for module, instance, idx in self.fwd_modules:
params["layer_instance"] = instance
if module.caps.get("logits_output"):
@@ -336,7 +338,56 @@ class Model_LSMixin(ABC):
break
if (num := params.get("last_tokens_only")):
x = x[..., -num:, :].contiguous()
+ if span:
+ x = _span_module(module, x, params)
+ continue
x = module.prepare_for_device(x, params)
x = module.forward(x, params)
return x
+
+# EXL3_FWD_SPAN=1 (diagnostic, off by default): decode/verify forwards (<= 8 rows) time every module with a
+# device sync on both sides and print the ones over EXL3_FWD_SPAN_MS (default 150). A sampler thread dumps the
+# main thread's Python stack every 250 ms once a module has run past 400 ms, naming the op of a one-time stall.
+_FWD_SPAN = os.environ.get("EXL3_FWD_SPAN") == "1"
+_FWD_SPAN_MS = float(os.environ.get("EXL3_FWD_SPAN_MS", "150"))
+_span_state = {"t0": None, "name": "", "main": None}
+
+
+def _span_sampler():
+ import sys, traceback
+ last = None
+ while True:
+ time.sleep(0.25)
+ t0 = _span_state["t0"]
+ if t0 is None or time.perf_counter() - t0 < 0.4:
+ continue
+ fr = sys._current_frames().get(_span_state["main"])
+ if fr is None:
+ continue
+ st = traceback.extract_stack(fr)[-14:]
+ key = (t0, tuple((f.filename, f.lineno) for f in st))
+ if key == last:
+ continue
+ last = key
+ print(f"span-stack: {_span_state['name']} +{(time.perf_counter() - t0) * 1e3:.0f} ms", flush=True)
+ for f in st:
+ print(f"span-stack: {f.filename.split('/')[-1]}:{f.lineno} {f.name}: {(f.line or '')[:100]}", flush=True)
+
+
+def _span_module(module, x, params):
+ import threading
+ if _span_state["main"] is None:
+ _span_state["main"] = threading.get_ident()
+ threading.Thread(target = _span_sampler, daemon = True).start()
+ torch.cuda.synchronize()
+ _span_state["name"] = f"{module.key}[{params.get('layer_instance')}]"
+ t0 = _span_state["t0"] = time.perf_counter()
+ x = module.prepare_for_device(x, params)
+ x = module.forward(x, params)
+ torch.cuda.synchronize()
+ ms = (time.perf_counter() - t0) * 1e3
+ _span_state["t0"] = None
+ if ms >= _FWD_SPAN_MS:
+ print(f"span: {_span_state['name']} {type(module).__name__} {ms:.1f} ms rows={x.shape[1] if x.dim() > 2 else 0}", flush=True)
+ return x
diff --git a/exllamav3/modules/attention_fn/dsa_triton.py b/exllamav3/modules/attention_fn/dsa_triton.py
index 5f175cc..b09e875 100644
--- a/exllamav3/modules/attention_fn/dsa_triton.py
+++ b/exllamav3/modules/attention_fn/dsa_triton.py
@@ -1644,6 +1644,13 @@ def dsa_attn(
return out
+# GLM-5.3 prefill scorer (H_i 32, D_i 128, R >= 64 rows): 32x128 tiles, 4 warps, 2 stages. pf500 sweep (R 256, paged pooled keys,
+# 27 configs): 37.0-37.5 TFLOP/s against 35.1-35.8 for 64x128 / 8 warps / 2 stages, scores bitwise equal in all 54 cases
+# (T 32768 and 125000). EXL3_DSA_IDX_CFG="bm,bn,warps,stages" overrides, "0" restores 64,128,8,2.
+_idx_cfg_env = os.environ.get("EXL3_DSA_IDX_CFG", "32,128,4,2")
+_IDX_CFG_GLM = None if _idx_cfg_env == "0" else tuple(int(x) for x in _idx_cfg_env.split(","))
+
+
def dsa_indexer_scores(
q_idx, # (R, H_i, D_i) fp16, rope applied
weights, # (R, H_i) fp16 raw head weights (H_i ** -0.5 folded in-kernel)
@@ -1653,10 +1660,10 @@ def dsa_indexer_scores(
compress_rate,
bound_max, # entry count clamp (valid pool entries)
scores = None,
- block_m = 64,
- block_n = 128,
- num_warps = 8,
- num_stages = 2,
+ block_m = None, # None: 64 / 128 / 8 warps / 2 stages, or the GLM-5.3 prefill config below
+ block_n = None,
+ num_warps = None,
+ num_stages = None,
block_table = None, # (npr,) or (1, npr) i32 page table of the (single) job
epp = 0, # pool entries per page (paged mode)
scale = None, # None: D_i ** -0.5 * H_i ** -0.5 (DSA); QSA passes dk ** -0.5
@@ -1666,6 +1673,11 @@ def dsa_indexer_scores(
R, H_i, D_i = q_idx.shape
if scale is None:
scale = D_i ** -0.5 * H_i ** -0.5
+ cfg = _IDX_CFG_GLM if (H_i == 32 and D_i == 128 and R >= 64) else None
+ block_m = block_m if block_m is not None else (cfg[0] if cfg else 64)
+ block_n = block_n if block_n is not None else (cfg[1] if cfg else 128)
+ num_warps = num_warps if num_warps is not None else (cfg[2] if cfg else 8)
+ num_stages = num_stages if num_stages is not None else (cfg[3] if cfg else 2)
T = bound_max
if block_table is None:
T = k_idx.shape[0]
diff --git a/exllamav3/modules/mla_attn.py b/exllamav3/modules/mla_attn.py
index 4be6f50..0d5ae77 100644
--- a/exllamav3/modules/mla_attn.py
+++ b/exllamav3/modules/mla_attn.py
@@ -37,6 +37,16 @@ MAX_DECODE_QLEN = 16
_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
+# Query rows per indexer slab in the k-pool prefill path (one score matrix + top-k per slab). Default 256.
+_score_slab = None # None: read EXL3_DSA_PF_SLAB (default 256) per call
+# "running" (default): per-tile running top-k merge. "defer": keep each tile's candidates and take ONE top-k at the end
+# (same candidate set, a third of the glue launches at 4 tiles; ties among equal fp16 scores may order differently).
+_merge_mode = None # None: read EXL3_DSA_PF_MERGE per call (a harness may set "running" / "defer")
+# EXL3_DSA_PF_SORT=1: the tiled selection (context > one score tile = 131072 tokens) hands the sparse attention its pools in
+# score-descending order, the single-tile one (dsa_topk output) in ascending order. 1 sorts the tiled result ascending too
+# (-1 padding last, default): same key set per row, gathers walk memory forward. The attention sums in list order, so results
+# differ from the unsorted order at fp rounding level, not in the key set.
+_sort_tiled = None # None: read EXL3_DSA_PF_SORT per call (a harness may set True / False)
# Decode/verify has few query rows. When enabled, score the whole visible slab in one
# call instead of running the per-tile top-k merge below. Prefill remains tiled.
@@ -816,6 +826,43 @@ class MLAttention(Module):
return indices
+ def warm_indexer_strides(self, cache, max_seq):
+ """
+ Compile, ahead of the first long request, the indexer-scoring kernels at every score-row
+ stride a decode/verify call can use beyond one tile. Decode (<= 8 rows) scores the whole
+ visible slab in one call once it outgrows the score tile, and that call rounds the row
+ stride up to a power of two, a kernel constexpr: the first decode at a new power of two
+ (131072 tokens for a 4-token pool, 262144, ...) paid a Triton compile (0.4-4 s, twice: the
+ few-row kernel and the query-tiled one a lookup round with > 4 rows takes) inside the
+ user's first round. Pure compile: the dummy scores are discarded, no model state is touched.
+ Returns the number of strides warmed.
+ """
+ if self.indexer_mode != "full":
+ return 0
+ from .attention_fn.dsa_triton import dsa_indexer_scores
+ layer = cache.layers[self.layer_idx, 0]
+ P = self.index_kpool or 1
+ plane = layer.get_pool() if self.index_kpool else layer.get_idx()
+ epp = plane.shape[1]
+ H_i, D_i = self.index_n_heads, self.index_head_dim
+ t_tile = max(epp, _score_tile // epp * epp)
+ max_entries = max_seq // P
+ dev = plane.device
+ flat = plane.view(-1, D_i)
+ n = 0
+ stride = 1 << (t_tile).bit_length() # smallest power of two above one tile
+ while stride // 2 < max_entries:
+ bt = torch.zeros(stride // epp + 1, dtype = torch.int32, device = dev)
+ for R in (1, 5):
+ q = torch.zeros((R, H_i, D_i), dtype = torch.half, device = dev)
+ w = torch.zeros((R, H_i), dtype = torch.half, device = dev)
+ dsa_indexer_scores(q, w, flat, 0, P, stride, block_table = bt, epp = epp)
+ n += 1
+ stride *= 2
+ torch.cuda.synchronize(dev)
+ return n
+
+
def _update_pool_plane(self, idx_layer, block_table, host_seqlens, seqlen):
"""
Incrementally extend the pooled-key plane with the pools completed by this chunk's
@@ -898,8 +945,10 @@ class MLAttention(Module):
# exactly the visible-complete-pool count
wf = w # raw head weights, scales folded in-kernel
epp = pool_plane.shape[1]
- slab = 256
- t_tile = max(epp, _score_tile // epp * epp)
+ slab = _score_slab or int(os.environ.get("EXL3_DSA_PF_SLAB", "256"))
+ t_tile = max(epp, int(os.environ.get("EXL3_DSA_SCORE_TILE", _score_tile)) // epp * epp)
+ merge_defer = (_merge_mode or os.environ.get("EXL3_DSA_PF_MERGE", "running")) == "defer"
+ sort_tiled = _sort_tiled if _sort_tiled is not None else os.environ.get("EXL3_DSA_PF_SORT", "1") == "1"
for b in range(bsz):
pools_b = (host_seqlens[b] + seqlen) // P
base_cols = 0
@@ -950,8 +999,10 @@ class MLAttention(Module):
pool_idx = pool_idx.gather(1, o)
else:
i_backing = g_tensor_cache.get(dev, (slab * kp_sel,), torch.int32, "dsa_itile")
+ defer = merge_defer
run_scr = torch.full((rows, k_sel), -float("inf"), dtype = torch.half, device = dev)
run_idx = torch.full((rows, k_sel), -1, dtype = torch.int32, device = dev)
+ cands_s, cands_i = ([run_scr], [run_idx]) if defer else (None, None)
for t0 in range(0, pools_slab, t_tile):
t1 = min(t0 + t_tile, pools_slab)
sc = tile_scores(t0, t1, s_backing[: rows * s_stride].view(rows, s_stride))
@@ -962,12 +1013,23 @@ class MLAttention(Module):
t_scr = sc.gather(1, ti.clamp_min(0).long())
t_scr = t_scr.masked_fill(ti < 0, -float("inf"))
t_idx = torch.where(ti >= 0, ti + t0, ti)
+ if defer:
+ cands_s.append(t_scr)
+ cands_i.append(t_idx)
+ continue
cand_scr = torch.cat((run_scr, t_scr), dim = 1)
cand_idx = torch.cat((run_idx, t_idx), dim = 1)
run_scr, sel = cand_scr.topk(k_sel, dim = 1)
run_idx = cand_idx.gather(1, sel)
+ if defer:
+ run_scr, sel = torch.cat(cands_s, dim = 1).topk(k_sel, dim = 1)
+ run_idx = torch.cat(cands_i, dim = 1).gather(1, sel)
pool_idx = torch.where(
run_scr > -float("inf"), run_idx, run_idx.new_full((), -1))
+ if sort_tiled:
+ big = torch.iinfo(torch.int32).max
+ pool_idx = torch.where(pool_idx < 0, pool_idx.new_full((), big), pool_idx).sort(dim = 1).values
+ pool_idx = torch.where(pool_idx == big, pool_idx.new_full((), -1), pool_idx)
# Expand pools to raw token indices (one kernel when set;
# single-slab only so the tail offset is this slab's expand width)
diff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.py
index e53bf52..636255f 100644
--- a/exllamav3/modules/qsa_indexer.py
+++ b/exllamav3/modules/qsa_indexer.py
@@ -870,8 +870,6 @@ class QSAIndexer(Module):
bsz, seq = q.shape[:2]
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):
# Packed pages, dequantized online by the gather kernel
qk, sk, qv, sv, kb, vb = layer.get_qkv()
@@ -897,6 +895,10 @@ class QSAIndexer(Module):
n_used = (int(cache_seqlens_cpu.max().item()) + seq + page_size - 1) // page_size
o = qsa_prefill_q8(q_rows, qk, sk, qv, sv, indices, attn.sm_scale, block_table[0], n_used, page_size)
return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
+ # Built only for the Triton fallback: the HIP paths above read block_table[0], and this copy is
+ # rows x pages x 4 B (33 MB per layer per 4096-row chunk at -c 524288) written for nothing
+ bt_rows = block_table.int().unsqueeze(1).expand(bsz, seq, -1) \
+ .reshape(bsz * seq, -1).contiguous()
o = qsa_sparse_attend_rows(
q_rows,
k_arg, v_arg, indices, attn.sm_scale,
diff --git a/tests/test_dsa_topk_v2_cpu.py b/tests/test_dsa_topk_v2_cpu.py
new file mode 100644
index 0000000..2f034aa
--- /dev/null
+++ b/tests/test_dsa_topk_v2_cpu.py
@@ -0,0 +1,117 @@
+"""CPU proof for dsa_topk_gfx12_v2 (exllamav3_ext/dsa_topk_gfx12.cu): emulates the kernel's thread/chunk ownership,
+histogram, threshold search, scans and writes in python and checks (a) every memory read the kernel would issue is inside
+[0, width) of its row, (b) every write lands in [0, out_w), (c) the result equals the fp16-bit-key oracle that pins the v1
+contract (all keys above the threshold + the first ties_needed ties by ascending index, ascending output, -1 padding)."""
+import numpy as np
+import pytest
+
+NEG = 0x03ff
+
+
+def topk_key(bits):
+ bits = np.asarray(bits, dtype=np.uint32)
+ return np.where(bits & 0x8000, (~bits) & 0xffff, bits | 0x8000).astype(np.uint32)
+
+
+def oracle(bits, k, out_w):
+ keys = topk_key(bits)
+ cand = [(int(kv), i) for i, kv in enumerate(keys) if kv > NEG]
+ chosen = sorted(cand, key=lambda t: (-t[0], t[1]))[:k]
+ res = sorted(i for _, i in chosen)
+ return res + [-1] * (out_w - len(res))
+
+
+def desc_bucket(hist, target):
+ total = 0
+ for b in range(255, -1, -1):
+ if total + hist[b] >= target:
+ return b, total
+ total += hist[b]
+ return -1, total
+
+
+def emulate(bits, width, K, out_w, THREADS, CH):
+ assert width <= THREADS * CH * 8
+ n_chunks = (width + 7) >> 3
+ reads = []
+ keys_t = []
+ c0s = []
+ for t in range(THREADS):
+ c0 = n_chunks * t // THREADS
+ c1 = n_chunks * (t + 1) // THREADS
+ assert c1 - c0 <= CH
+ kk = np.zeros(CH * 8, dtype=np.uint32)
+ for j in range(CH):
+ c = c0 + j
+ base = c * 8
+ if c < c1 and base + 8 <= width:
+ reads.append((base, base + 8))
+ kk[j * 8:(j + 1) * 8] = topk_key(bits[base:base + 8])
+ elif c < c1:
+ for e in range(8):
+ if base + e < width:
+ reads.append((base + e, base + e + 1))
+ kk[j * 8 + e] = topk_key(bits[base + e:base + e + 1])[0]
+ keys_t.append(kk)
+ c0s.append(c0)
+ for lo, hi in reads:
+ assert 0 <= lo < hi <= width
+ allk = np.concatenate(keys_t)
+ hist = np.bincount((allk[allk > NEG] >> 8).astype(int), minlength=256)
+ hb, above = desc_bucket(hist, K)
+ thr, ties_needed = NEG, 0
+ if hb >= 0:
+ sel = allk[(allk > NEG) & ((allk >> 8) == hb)]
+ h2 = np.bincount((sel & 0xff).astype(int), minlength=256)
+ lb, below = desc_bucket(h2, K - above)
+ thr = (hb << 8) | lb
+ ties_needed = K - above - below
+ hc = [int(((k > thr) & (k > NEG)).sum()) for k in keys_t]
+ tc = [int(((k == thr) & (k > NEG)).sum()) for k in keys_t]
+ tie_off = np.concatenate(([0], np.cumsum(tc)[:-1]))
+ local = [max(0, min(tc[t], ties_needed - int(tie_off[t]))) for t in range(THREADS)]
+ selc = [hc[t] + local[t] for t in range(THREADS)]
+ out_off = np.concatenate(([0], np.cumsum(selc)[:-1]))
+ out = [None] * out_w
+ for t in range(THREADS):
+ o = int(out_off[t])
+ seen = 0
+ for i in range(CH * 8):
+ kv = keys_t[t][i]
+ idx = c0s[t] * 8 + i
+ if kv > thr and kv > NEG:
+ assert 0 <= o < out_w
+ out[o] = idx; o += 1
+ elif kv == thr and kv > NEG:
+ if seen < local[t]:
+ assert 0 <= o < out_w
+ out[o] = idx; o += 1
+ seen += 1
+ if t == THREADS - 1:
+ while o < out_w:
+ out[o] = -1; o += 1
+ assert None not in out
+ return out
+
+
[email protected]("THREADS,CH", [(512, 8), (1024, 4)])
[email protected]("kind", ["randn", "ties", "const", "ninf", "special", "sparse"])
+def test_v2_emulation_matches_oracle(THREADS, CH, kind):
+ rng = np.random.default_rng(1234)
+ for width in (1, 7, 8, 9, 63, 64, 65, 1000, 4095, 4097, 8192, 20001, 32768):
+ for K, out_w in ((512, 512), (1, 8), (17, 32), (300, 512)):
+ if kind == "randn":
+ bits = rng.standard_normal(width).astype(np.float16).view(np.uint16)
+ elif kind == "ties":
+ bits = ((rng.integers(0, 6, width) - 2) * 0.25).astype(np.float16).view(np.uint16)
+ elif kind == "const":
+ bits = np.full(width, 0.5, dtype=np.float16).view(np.uint16)
+ elif kind == "ninf":
+ bits = np.full(width, -np.inf, dtype=np.float16).view(np.uint16)
+ elif kind == "special":
+ bits = rng.integers(0, 65536, width).astype(np.uint16)
+ else:
+ x = rng.standard_normal(width).astype(np.float16)
+ x[rng.random(width) > 0.02] = -np.inf
+ bits = x.view(np.uint16)
+ assert emulate(bits, width, K, out_w, THREADS, CH) == oracle(bits, K, out_w), (kind, width, K, out_w)
diff --git a/tests/test_glm_round_tools.py b/tests/test_glm_round_tools.py
new file mode 100644
index 0000000..816f9d5
--- /dev/null
+++ b/tests/test_glm_round_tools.py
@@ -0,0 +1,38 @@
+"""CPU check of round_probe + round_replay against a fake generator and a fake SSE server."""
+import json, os, pathlib, sys, threading, time, types, http.server, argparse
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "tools" / "glm"))
+import round_probe, round_replay
+
+round_probe.torch.cuda.synchronize = lambda: None
+class Seq: sequence_ids = list(range(100));
+class Job:
+ sequences = [Seq()]; new_tokens = 0; draft_stats = []
+ def is_prefill_done(self): return True
+job = Job()
+class G:
+ active_jobs = [job]
+ def iterate(self):
+ time.sleep(0.002); job.new_tokens += 3; job.draft_stats.append((job.new_tokens, 2, 2)); return []
+g = G(); ls = {}
+import tempfile; log = tempfile.mktemp(suffix=".jsonl"); open(log, "w").close()
+round_probe.install(g, log, ls)
+for _ in range(5): g.iterate()
+recs, off = round_replay.read_rounds(log, 0)
+assert "req" in recs[0] and len(recs) == 6 and recs[1]["produced"] == 3 and recs[1]["acc"] == 2 and recs[1]["window"] == 2, recs
+print("probe ok", recs[1])
+
+class H(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *a): pass
+ def do_POST(self):
+ n = int(self.headers["content-length"]); self.rfile.read(n)
+ self.send_response(200); self.send_header("content-type", "text/event-stream"); self.end_headers()
+ for i in range(8):
+ self.wfile.write(("data: " + json.dumps({"choices": [{"delta": {"content": f"w{i} "}}]}) + "\n\n").encode()); self.wfile.flush(); time.sleep(0.01)
+ self.wfile.write(("data: " + json.dumps({"choices": [], "usage": {"completion_tokens": 8, "prompt_tokens": 10}, "timings": {"predicted_per_second": 33.0, "predicted_ms": 240, "prompt_per_second": 500, "prompt_ms": 20}}) + "\n\n").encode())
+ self.wfile.write(b"data: [DONE]\n\n")
+srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H); threading.Thread(target=srv.serve_forever, daemon=True).start()
+a = argparse.Namespace(base=f"http://127.0.0.1:{srv.server_port}", model="m", roundlog=log, max_tokens=8, think="{}", reqlog_dir="", salt="cold")
+for _ in range(4): g.iterate()
+r, off = round_replay.run_point(a, "x" * 1000, 500, "t", off)
+print({k: v for k, v in r.items() if k not in ("rounds_detail", "slowest5", "text")})
+assert r["rounds"] == 4 and r["decode_srv"] == 33.0 and r["acc_per_round"] == 2
diff --git a/tests/test_hip_dsa_topk_gfx12_v2.py b/tests/test_hip_dsa_topk_gfx12_v2.py
new file mode 100644
index 0000000..1f7d272
--- /dev/null
+++ b/tests/test_hip_dsa_topk_gfx12_v2.py
@@ -0,0 +1,74 @@
+"""dsa_topk_gfx12_v2 (row read once into registers) must be bitwise identical to dsa_topk_gfx12 (v1)."""
+from __future__ import annotations
+
+import pytest
+import torch
+
+if not (torch.version.hip and torch.cuda.is_available()):
+ pytest.skip("ROCm dsa_topk tests", allow_module_level = True)
+
+from exllamav3.ext import exllamav3_ext as ext
+
+if not (hasattr(ext, "dsa_topk_gfx12") and hasattr(ext, "dsa_topk_gfx12_v2")):
+ pytest.skip("dsa_topk_gfx12_v2 binding is unavailable (rebuild the extension)", allow_module_level = True)
+
+DEV = torch.device("cuda")
+WIDTHS = [1, 7, 8, 9, 15, 16, 127, 128, 129, 511, 512, 513, 1000, 1023, 1024, 1025, 4095, 4096, 4097, 8191, 8193,
+ 16384, 24576, 32001, 32767, 32768]
+
+
+def _storage(rows, width, kind, seed):
+ g = torch.Generator(device = DEV).manual_seed(seed)
+ stride = -(-width // 128) * 128
+ if kind == "randn":
+ x = torch.randn((rows, stride), generator = g, device = DEV, dtype = torch.half)
+ elif kind == "ties": # few distinct values: heavy threshold ties
+ x = (torch.randint(0, 6, (rows, stride), generator = g, device = DEV).half() - 2) * 0.25
+ elif kind == "const":
+ x = torch.full((rows, stride), 0.5, device = DEV, dtype = torch.half)
+ elif kind == "ninf":
+ x = torch.full((rows, stride), -float("inf"), device = DEV, dtype = torch.half)
+ elif kind == "sparse": # mostly -inf (causal mask look), some valid
+ x = torch.randn((rows, stride), generator = g, device = DEV, dtype = torch.half)
+ keep = torch.rand((rows, stride), generator = g, device = DEV) < 0.02
+ x = torch.where(keep, x, torch.full_like(x, -float("inf")))
+ elif kind == "special": # +-inf, +-NaN, +-0, subnormals mixed
+ raw = torch.randint(-32768, 32767, (rows, stride), generator = g, device = DEV, dtype = torch.int16)
+ x = raw.view(torch.half)
+ elif kind == "causal": # row r sees only the first (width * (r + 1)) // rows columns
+ x = torch.randn((rows, stride), generator = g, device = DEV, dtype = torch.half)
+ lim = ((torch.arange(rows, device = DEV) + 1) * width // rows).clamp_min(1)
+ col = torch.arange(stride, device = DEV)
+ x = torch.where(col.unsqueeze(0) < lim.unsqueeze(1), x, torch.full_like(x, -float("inf")))
+ else:
+ raise ValueError(kind)
+ return x[:, :width]
+
+
[email protected]("kind", ["randn", "ties", "const", "ninf", "sparse", "special", "causal"])
[email protected]("threads", [512, 1024])
+def test_v2_matches_v1_bitwise(kind, threads):
+ for width in WIDTHS:
+ for k, out_w in ((512, 512), (1, 8), (17, 32), (256, 256), (511, 512), (300, 512)):
+ rows = 6 if width > 8192 else 24
+ scores = _storage(rows, width, kind, seed = width * 7 + k)
+ a = torch.empty((rows, out_w), device = DEV, dtype = torch.int32)
+ b = torch.empty_like(a)
+ ext.dsa_topk_gfx12(scores, a, k)
+ ext.dsa_topk_gfx12_v2(scores, b, k, threads)
+ torch.cuda.synchronize()
+ assert torch.equal(a, b), (kind, threads, width, k, out_w)
+
+
+def test_v2_rejects_unsupported_shapes():
+ ok = torch.zeros((2, 32768), device = DEV, dtype = torch.half)
+ out = torch.empty((2, 512), device = DEV, dtype = torch.int32)
+ with pytest.raises(RuntimeError):
+ ext.dsa_topk_gfx12_v2(torch.zeros((2, 32896), device = DEV, dtype = torch.half), out, 512, 512)
+ with pytest.raises(RuntimeError):
+ ext.dsa_topk_gfx12_v2(ok, out, 512, 256)
+ with pytest.raises(RuntimeError): # unaligned base: a view offset by one element
+ base = torch.zeros((2 * 32768 + 256,), device = DEV, dtype = torch.half)
+ ext.dsa_topk_gfx12_v2(base[1:1 + 2 * 32768].view(2, 32768), out, 512, 512)
diff --git a/tests/test_prefill_block_table_cpu.py b/tests/test_prefill_block_table_cpu.py
new file mode 100644
index 0000000..d9b93dc
--- /dev/null
+++ b/tests/test_prefill_block_table_cpu.py
@@ -0,0 +1,40 @@
+import torch
+
+from exllamav3.constants import PAGE_SIZE
+from exllamav3.generator.generator import block_table_pages
+from exllamav3.generator.pagetable import Sequence
+
+
+def make_seq(n_tokens, n_pages):
+ seq = Sequence.__new__(Sequence)
+ seq.sequence_ids = list(range(n_tokens))
+ seq.block_index_tensor = torch.arange(n_pages, dtype = torch.int32).unsqueeze(0)
+ return seq
+
+
+def test_prefill_table_is_sliced_to_used_pages():
+ # a request without max_tokens reserves the whole cache: 2048 pages at -c 524288
+ seq = make_seq(8192, 2048)
+ bt = seq.prefill_block_table()
+ assert bt.shape == (1, block_table_pages(8192 + 1))
+ assert bt.is_contiguous()
+ assert torch.equal(bt, seq.block_index_tensor[:, :bt.shape[1]])
+ assert bt.shape[1] * PAGE_SIZE > 8192 # covers every page the chunks write
+
+
+def test_prefill_table_never_wider_than_allocation():
+ seq = make_seq(8192, 40) # prompt + 256 reply tokens: 33 pages, rounded up to 48 by the helper
+ assert seq.prefill_block_table() is seq.block_index_tensor
+ seq = make_seq(8192, 33)
+ assert seq.prefill_block_table() is seq.block_index_tensor
+
+
+def test_prefill_table_width_is_independent_of_cache_size():
+ widths = {make_seq(8192, p).prefill_block_table().shape[1] for p in (1064, 2048, 4096)}
+ assert len(widths) == 1
+
+
+def test_prefill_table_covers_page_boundary_token():
+ # len + 1 so the page after an exact multiple of PAGE_SIZE is inside the table
+ for n in (PAGE_SIZE * 16 - 1, PAGE_SIZE * 16, PAGE_SIZE * 16 + 1):
+ assert make_seq(n, 4096).prefill_block_table().shape[1] * PAGE_SIZE >= n + 1
diff --git a/tools/glm/round_probe.py b/tools/glm/round_probe.py
new file mode 100644
index 0000000..a673cf4
--- /dev/null
+++ b/tools/glm/round_probe.py
@@ -0,0 +1,72 @@
+"""Opt-in per-round decode log for serve.py. Off unless EXL3_ROUND_LOG names a file.
+
+One JSON line per decode round of a single active request (a round = one Generator.iterate() call
+after the prefill, GPU-synced on both sides, so ms is the real round time, the cost of the two
+syncs included):
+
+ t wall clock (time.time) at the round start; gaps between t+ms and the next t are time outside the rounds
+ n sequence length before the round (prompt + generated)
+ new job.new_tokens after the round
+ produced tokens the round added (accepted drafts + 1)
+ window drafted tokens the round verified (rows - 1); None = plain 1-row step
+ acc accepted draft tokens (from job.draft_stats)
+ kind "ng" for an n-gram lookup round, "dr" for the MTP drafter's own round
+ ms round wall time
+ prof EXL3_SPEC_PROF=1 only: the Generator's per-phase times (t_dfwd, t_verify, t_post, t_kvup, R)
+
+A line {"req": ...} marks the start of every request (first decode round of a new job).
+Rounds of batched requests (> 1 active) are not logged. The file is line-buffered: a client on the
+same box reads it by byte offset between requests (tools/glm/round_replay.py).
+"""
+import json
+import os
+import time
+
+import torch
+
+
+def install(g, path, lookup_stats=None):
+ f = open(path, "a", buffering=1)
+ orig = g.iterate
+ st = {"job": None}
+
+ def sync():
+ torch.cuda.synchronize()
+
+ def iterate():
+ act = g.active_jobs
+ job = act[0] if len(act) == 1 and act[0].is_prefill_done() and len(act[0].sequences) == 1 else None
+ if job is None:
+ return orig()
+ n = len(job.sequences[0].sequence_ids)
+ ng0 = (lookup_stats or {}).get("ng", 0)
+ ds0 = len(job.draft_stats)
+ n0 = job.new_tokens
+ if st["job"] is not job:
+ st["job"] = job
+ f.write(json.dumps({"req": id(job), "t": time.time(), "n": n}) + "\n")
+ prof_mod = None
+ if os.environ.get("EXL3_SPEC_PROF") == "1":
+ from exllamav3.generator import generator as GM
+ prof_mod = GM
+ GM._PROF_CUR.clear()
+ sync()
+ t0 = time.perf_counter()
+ tw = time.time()
+ out = orig()
+ sync()
+ ms = (time.perf_counter() - t0) * 1e3
+ rec = {"t": round(tw, 4), "n": n, "new": job.new_tokens, "produced": job.new_tokens - n0, "ms": round(ms, 3),
+ "kind": "ng" if (lookup_stats or {}).get("ng", 0) > ng0 else "dr"}
+ if len(job.draft_stats) > ds0:
+ _, w, a = job.draft_stats[-1]
+ rec["window"], rec["acc"] = int(w), int(a)
+ else:
+ rec["window"] = rec["acc"] = None
+ if prof_mod is not None:
+ rec["prof"] = {k: (round(v * 1e3, 3) if isinstance(v, float) else v) for k, v in prof_mod._PROF_CUR.items()}
+ f.write(json.dumps(rec) + "\n")
+ return out
+
+ g.iterate = iterate
+ return f
diff --git a/tools/glm/round_replay.py b/tools/glm/round_replay.py
new file mode 100644
index 0000000..734eec2
--- /dev/null
+++ b/tools/glm/round_replay.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+"""Replay long-context decode points against a running GLM server and break each one into rounds.
+
+Needs the server started with EXL3_ROUND_LOG=<file> (tools/glm/round_probe.py: one line per decode round)
+and optionally KYOJIN_REQLOG_DIR=<dir> (lifecycle events with timestamps). The script runs on the same box,
+reads the round file by byte offset between requests, and per point reports:
+
+ decode_srv server-reported predicted_per_second (generate window = first token -> eos event)
+ decode_cli client (tokens-1) / (last chunk - first chunk)
+ rounds, acc/round (accepted drafts per round), tok/round, ms/round (mean, p50, p95, max), kinds (dr / ng rounds)
+ gap_first_s server first-token event -> client first chunk, i.e. delay before the stream shows the first token
+ idle_s round-file wall time not covered by the rounds themselves (sum of gaps between rounds)
+ chunk_gap_max the biggest gap between two streamed chunks (and when it happened, in tokens)
+ text the generated text (JSON out) plus repetition stats (distinct 4-gram ratio of the token pieces)
+
+Points: --chars-from curve json gives the exact chars of the 131072 and 262144 points; --scale-from-131k
+derives the other depths (120K, 140K, 160K) from the 131K chars/token ratio and reports the real token count.
+Same request as curve.py (REVIEW + doc[:chars]), default thinking, temperature 0, max_tokens 256, cold
+(unique cache_salt per request). Order is interleaved: round r of every point before round r+1.
+
+usage: round_replay.py --base http://localhost:8011/v1 --model glm-5.3-exl3 --roundlog RL --out out.json \
+ --doc DOC.txt --chars-from curve.json [--reps 2] [--points 131072,262144,120000,140000,160000] [--reqlog-dir DIR]
+"""
+import argparse
+import glob
+import json
+import os
+import statistics
+import sys
+import time
+import urllib.request
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+REVIEW = ("Task: read the long document below, then write a very long, detailed essay (at least 800 words) "
+ "reviewing its topics one by one, in plain prose, no tool calls.\n\n")
+
+
+def post(base, path, body, timeout=3600):
+ req = urllib.request.Request(base + path, json.dumps(body).encode(), {"content-type": "application/json"})
+ return urllib.request.urlopen(req, timeout=timeout)
+
+
+def read_rounds(path, off):
+ """New lines of the round file since byte offset off -> (list of dicts, new offset)."""
+ out = []
+ with open(path, "rb") as f:
+ f.seek(off)
+ data = f.read()
+ end = data.rfind(b"\n") + 1
+ for line in data[:end].splitlines():
+ try:
+ out.append(json.loads(line))
+ except json.JSONDecodeError:
+ pass
+ return out, off + end
+
+
+def reqlog_events(d, t_from):
+ """Lifecycle lines of the newest requests-*.log with a timestamp >= t_from (event name + raw line)."""
+ files = sorted(glob.glob(os.path.join(d, "requests-*.log")), key=os.path.getmtime)
+ if not files:
+ return []
+ ev = []
+ for line in open(files[-1], errors="replace"):
+ if any(k in line for k in (" job_start", " job_first_token", " job_done", " job_error")):
+ ev.append(line.strip())
+ return ev[-4:]
+
+
+def pct(xs, q):
+ xs = sorted(xs)
+ return xs[min(len(xs) - 1, int(q * len(xs)))] if xs else None
+
+
+def distinct4(toks):
+ g = [tuple(toks[i:i + 4]) for i in range(len(toks) - 3)]
+ return round(len(set(g)) / len(g), 3) if g else None
+
+
+def run_point(a, doc, chars, tag, off):
+ body = {"model": a.model, "messages": [{"role": "user", "content": REVIEW + doc[:chars]}],
+ "max_tokens": a.max_tokens, "temperature": 0, "stream": True,
+ "stream_options": {"include_usage": True}, "cache_prompt": False,
+ "cache_salt": f"round-{tag}-{int(time.time())}" if a.salt == "cold" else "round-shared"}
+ body.update(json.loads(a.think))
+ chunks = [] # (t_wall, piece)
+ usage = timings = None
+ t_req = time.time()
+ for raw in post(a.base, "/chat/completions", body):
+ line = raw.decode().strip()
+ if not line.startswith("data:"):
+ continue
+ pay = line[5:].strip()
+ if pay == "[DONE]":
+ break
+ try:
+ d = json.loads(pay)
+ except json.JSONDecodeError:
+ continue
+ usage = d.get("usage") or usage
+ timings = d.get("timings") or timings
+ delta = (d.get("choices") or [{}])[0].get("delta") or {}
+ piece = delta.get("content") or delta.get("reasoning_content") or ""
+ if piece:
+ chunks.append((time.time(), piece))
+ t_end = time.time()
+ time.sleep(0.3)
+ recs, off = read_rounds(a.roundlog, off)
+ rounds = [r for r in recs if "ms" in r]
+ comp = (usage or {}).get("completion_tokens") or len(chunks)
+ tm = timings or {}
+ r = {"tag": tag, "chars": chars, "prompt_tokens": (usage or {}).get("prompt_tokens"),
+ "cached_tokens": ((usage or {}).get("prompt_tokens_details") or {}).get("cached_tokens"), "completion_tokens": comp,
+ "decode_srv": tm.get("predicted_per_second"), "predicted_ms": tm.get("predicted_ms"),
+ "prefill_srv": tm.get("prompt_per_second"), "prompt_ms": tm.get("prompt_ms")}
+ if len(chunks) > 1:
+ r["decode_cli"] = (comp - 1) / (chunks[-1][0] - chunks[0][0])
+ gaps = [(chunks[i + 1][0] - chunks[i][0], i) for i in range(len(chunks) - 1)]
+ gm = max(gaps)
+ r["chunk_gap_max_s"], r["chunk_gap_max_at"] = round(gm[0], 3), gm[1]
+ r["first_chunk_after_req_s"] = round(chunks[0][0] - t_req, 3)
+ r["stream_s"] = round(chunks[-1][0] - chunks[0][0], 3)
+ if rounds:
+ ms = [x["ms"] for x in rounds]
+ prod = [x["produced"] for x in rounds]
+ accs = [x["acc"] for x in rounds if x["acc"] is not None]
+ wins = [x["window"] for x in rounds if x["window"] is not None]
+ t0 = rounds[0]["t"]
+ tl = rounds[-1]["t"] + rounds[-1]["ms"] / 1e3
+ r.update(rounds=len(rounds), tok_per_round=round(sum(prod) / len(prod), 3),
+ acc_per_round=round(sum(accs) / len(accs), 3) if accs else None,
+ window_mean=round(sum(wins) / len(wins), 3) if wins else None,
+ ms_mean=round(statistics.mean(ms), 2), ms_p50=round(statistics.median(ms), 2),
+ ms_p95=round(pct(ms, 0.95), 2), ms_max=round(max(ms), 2),
+ n_ng=sum(1 for x in rounds if x["kind"] == "ng"),
+ n_dr=sum(1 for x in rounds if x["kind"] == "dr"),
+ ms_dr=round(statistics.mean([x["ms"] for x in rounds if x["kind"] == "dr"] or [0]), 2),
+ ms_ng=round(statistics.mean([x["ms"] for x in rounds if x["kind"] == "ng"] or [0]), 2),
+ rounds_sum_s=round(sum(ms) / 1e3, 3), rounds_span_s=round(tl - t0, 3),
+ idle_s=round(tl - t0 - sum(ms) / 1e3, 3),
+ round_tps=round(sum(prod) / (sum(ms) / 1e3), 2),
+ round_first_t_minus_chunk0=round(t0 - chunks[0][0], 3) if chunks else None,
+ first_round_ms=rounds[0]["ms"], slowest5=sorted(rounds, key=lambda x: -x["ms"])[:5],
+ rounds_detail=[{k: x.get(k) for k in ("n", "produced", "window", "acc", "kind", "ms", "prof")} for x in rounds])
+ text = "".join(p for _, p in chunks)
+ r["text"] = text
+ r["distinct4_pieces"] = distinct4([p for _, p in chunks])
+ r["distinct4_words"] = distinct4(text.split())
+ if a.reqlog_dir:
+ r["reqlog_tail"] = reqlog_events(a.reqlog_dir, t_req)
+ return r, off
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--base", required=True)
+ ap.add_argument("--model", default="glm-5.3-exl3")
+ ap.add_argument("--doc", required=True, help="the text file the growing prompt is cut from")
+ ap.add_argument("--chars-from", required=True, help="a served curve json (tools/glm/depth_curve.py output): its 131072 / 262144 points give the chars")
+ ap.add_argument("--roundlog", required=True)
+ ap.add_argument("--reqlog-dir", default="")
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--points", default="131072,262144,120000,140000,160000")
+ ap.add_argument("--reps", type=int, default=2)
+ ap.add_argument("--prelude", default="", help="depths (tokens, from the curve json) run ONCE before the reps, recorded under "
+ "'prelude': 8192,32768,65536 reproduces the curve's order on a fresh server (tells a one-time cost from a depth cost)")
+ ap.add_argument("--max-tokens", type=int, default=256)
+ ap.add_argument("--think", default="{}", help='thinking kwargs JSON; "{}" = default thinking as in the served curve')
+ ap.add_argument("--salt", choices=("cold", "shared"), default="cold",
+ help="cold: unique cache_salt per request (full prefill, the served method). shared: one salt, so a repeat or a "
+ "longer prefix of an earlier point reuses its cached prompt pages (cheap decode-only replays; cached_tokens "
+ "in usage tells how much)")
+ ap.add_argument("--warmup", type=int, default=1, help="discarded 8K requests first")
+ a = ap.parse_args()
+ a.base = a.base.rstrip("/")
+ doc = open(a.doc, encoding="utf-8").read()
+ ref = json.load(open(a.chars_from))["points"]
+ c131 = ref["131072"]["chars"]
+ ratio = c131 / ref["131072"]["usage"]["prompt_tokens"]
+ pts = {}
+ for t in (int(x) for x in a.points.split(",")):
+ pts[t] = ref[str(t)]["chars"] if str(t) in ref else int(t * ratio)
+ print("points (target tokens -> chars):", pts, flush=True)
+ off = os.path.getsize(a.roundlog) if os.path.exists(a.roundlog) else 0
+ res = {"argv": sys.argv, "started": time.strftime("%F %T"), "doc_chars": len(doc), "points": {str(k): [] for k in pts}}
+
+ def save():
+ json.dump(res, open(a.out + ".tmp", "w"), indent=1)
+ os.replace(a.out + ".tmp", a.out)
+
+ for w in range(a.warmup):
+ _, off = run_point(a, doc, ref["8192"]["chars"], f"warm{w}", off)
+ res["prelude"] = []
+ for t in (int(x) for x in a.prelude.split(",") if x):
+ r, off = run_point(a, doc, ref[str(t)]["chars"], f"pre{t}", off)
+ res["prelude"].append(dict(r, target=t))
+ save()
+ print(f"prelude {t}: srv={r['decode_srv'] and round(r['decode_srv'], 1)} cli={r.get('decode_cli') and round(r['decode_cli'], 1)} "
+ f"first_round_ms={r.get('first_round_ms')} rounds={r.get('rounds')} acc/rd={r.get('acc_per_round')}", flush=True)
+ for rep in range(a.reps):
+ for t, chars in pts.items():
+ r, off = run_point(a, doc, chars, f"p{t}-r{rep}", off)
+ res["points"][str(t)].append(r)
+ save()
+ print(f"{t} rep{rep}: tok={r['prompt_tokens']} srv={r['decode_srv'] and round(r['decode_srv'], 1)} "
+ f"cli={r.get('decode_cli') and round(r['decode_cli'], 1)} rounds={r.get('rounds')} "
+ f"acc/rd={r.get('acc_per_round')} tok/rd={r.get('tok_per_round')} ms/rd={r.get('ms_mean')} "
+ f"(p95 {r.get('ms_p95')}, max {r.get('ms_max')}) ng={r.get('n_ng')} idle={r.get('idle_s')} "
+ f"cached={r.get('cached_tokens')} first_round_ms={r.get('first_round_ms')} gap_first={r.get('round_first_t_minus_chunk0')} maxgap={r.get('chunk_gap_max_s')}@{r.get('chunk_gap_max_at')} "
+ f"d4={r.get('distinct4_words')}", flush=True)
+ print("DONE", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/glm/round_replay.sh b/tools/glm/round_replay.sh
new file mode 100755
index 0000000..f0d7082
--- /dev/null
+++ b/tools/glm/round_replay.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+# One arm of the 131K decode study: start a GLM server (-c 272384, own HOME) with the per-round log on, replay the
+# points, stop the server. The whole script is one GPU window. Environment:
+# KYOJIN_GLM_PACK the GLM-5.3-Flash EXL3 pack directory (required)
+# ROUND_DOC text file the prompts are cut from (required)
+# ROUND_CHARS served curve json with the 131072 / 262144 points (required)
+# tools/glm/round_replay.sh ARM [round_replay.py args...]
+# ARM names the single variable: base | dyn0 (EXL3_GLM_DYN=0) | nd1 | nd3 (--num-draft) | nongram (GLM_NGRAM=off)
+set -u
+ARM=${1:?arm}; shift
+KY=$(cd "$(dirname "$0")/../.." && pwd)
+PACK=${KYOJIN_GLM_PACK:?set KYOJIN_GLM_PACK to the GLM pack directory}
+DOC=${ROUND_DOC:?set ROUND_DOC}; CHARS=${ROUND_CHARS:?set ROUND_CHARS}
+export HOME=$KY/home; mkdir -p $HOME $KY/scratch
+cd $KY; source .venv/bin/activate; export EXL3_ROCM_SDK=$(rocm-sdk path --root); source tools/strix_halo/env.sh
+ND=2
+case $ARM in
+ base) ;;
+ dyn0) export EXL3_GLM_DYN=0 ;;
+ nd1) ND=1; export EXL3_GLM_DYN=0 ;; # a depth is only a depth with the dynamic stop off; compare with nd2dyn0 (=dyn0)
+ nd3) ND=3; export EXL3_GLM_DYN=0 ;;
+ nongram) export GLM_NGRAM=off ;;
+ *) echo "unknown arm $ARM"; exit 2 ;;
+esac
+TAG=round_$ARM; RL=$KY/scratch/$TAG.rounds.jsonl; : > $RL
+export EXL3_ROUND_LOG=$RL KYOJIN_REQLOG_DIR=$KY/scratch/$TAG.reqlog; rm -rf $KYOJIN_REQLOG_DIR
+LOG=$KY/scratch/$TAG.serve.log
+python -u tools/glm/serve.py --model $PACK --port 8013 -c 272384 --num-draft $ND > $LOG 2>&1 & SRV=$!
+for i in $(seq 1 240); do curl -s -m 10 localhost:8013/health | grep -qE '"status": *"ok"' && break; kill -0 $SRV 2>/dev/null || { echo "server died"; exit 1; }; sleep 15; done
+grep -E "two-stage draft head" $LOG
+python3 tools/glm/round_replay.py --base http://localhost:8013/v1 --roundlog $RL --reqlog-dir $KYOJIN_REQLOG_DIR \
+ --doc "$DOC" --chars-from "$CHARS" --out $KY/scratch/$TAG.json "$@" 2>&1 | tee $KY/scratch/$TAG.out
+kill $SRV; for i in $(seq 1 30); do kill -0 $SRV 2>/dev/null || break; sleep 5; done; kill -9 $SRV 2>/dev/null
+echo ARMDONE >> $KY/scratch/$TAG.out
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 2a29c94..5643a7a 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -704,6 +704,10 @@ class ResidentEngine:
import spec_policy
spec_policy.install_lookup(g, lookup, self.lookup_stats)
g.num_draft_tokens = self.num_draft # the drafter's own depth; lookup rounds bring their K tokens
+ if os.environ.get("EXL3_ROUND_LOG"): # opt-in per-round decode log (tools/glm/round_probe.py), off by default
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
+ import round_probe
+ round_probe.install(g, os.environ["EXL3_ROUND_LOG"], self.lookup_stats)
return g
def _rebuild_generator(self) -> None:
@@ -1073,6 +1077,25 @@ def warmup(engine: Any, template: str, prompt_tokens: int = 4608, decode_tokens:
return time.perf_counter() - t0
+def warm_indexer(engine) -> int:
+ """Compile the DSA indexer scorer at the power-of-two score strides a decode round reaches beyond one 32K tile
+ (first decode past 131072 tokens paid two Triton compiles in the user's first round). See
+ MLAttention.warm_indexer_strides. One representative attention per distinct (heads, dim, pool, page) config."""
+ import torch
+ seen, n = set(), 0
+ for m in engine.model.modules:
+ attn = getattr(m, "attn", None)
+ if attn is None or not hasattr(attn, "warm_indexer_strides") or getattr(attn, "indexer_mode", None) != "full":
+ continue
+ key = (attn.index_n_heads, attn.index_head_dim, attn.index_kpool)
+ if key in seen:
+ continue
+ seen.add(key)
+ n += attn.warm_indexer_strides(engine.cache, engine.cache.max_num_tokens)
+ torch.cuda.synchronize()
+ return n
+
+
def mem_line(stage: str) -> str:
"""GTT (whole unified-memory budget, all processes) next to this process's torch allocator."""
import torch
@@ -2004,6 +2027,14 @@ def main() -> None:
startup_health.stage("warm-up")
print(f"serve: warm-up {warmup(engine, template):.1f} s", flush=True)
print(mem_line("warm"), flush=True)
+ if os.environ.get("EXL3_WARM_INDEXER", "1") != "0":
+ t0 = time.perf_counter()
+ try:
+ warmed = warm_indexer(engine)
+ except Exception as e: # a warm-up is an optimisation: never keep the server from starting
+ import traceback; traceback.print_exc()
+ warmed = f"FAILED ({e!r})"
+ print(f"serve: indexer stride warm-up {warmed} stride(s) {time.perf_counter() - t0:.1f} s", flush=True)
if engine.supports_vision: # first tower pass pays kernel setup and allocator growth: not on the first user image
from PIL import Image
t0 = time.perf_counter()