tests: wide top-k selection rule, cluster asset pin, decode-shaped identity cases down to the identity branch, decode scores timing; scripts/upstream-rest/arm_prof.py; plan analysis of rows 2.4/2.5

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-27 09:20:23 +01:00
co-authored by Claude Sonnet 5.5
parent a28b85f798
commit 6d75dcddd9
5 changed files with 165 additions and 1 deletions
+15
View File
@@ -42,3 +42,18 @@ pub(crate) const PIN: PtxPin = PtxPin {
pub(crate) fn admit() -> Result<(), KarDecodeError> {
admit_ptx(PTX, &PIN)
}
#[cfg(test)]
mod tests {
#[test]
fn the_asset_is_the_sealed_one_and_the_dynamic_shared_memory_holds_one_eighth_of_the_keys() {
assert!(super::admit().is_ok(), "qsa_cluster.ptx does not match its pin (reseal with scripts/gpu-bringup/reseal_own.py)");
let text = std::str::from_utf8(&super::PTX[..super::PTX.len() - 1]).expect("PTX is text");
assert!(text.contains(".visible .entry leleka_qsa_topk_cluster("));
assert!(text.contains("barrier.cluster.arrive") && text.contains("mapa.u64"), "the kernel must use cluster barriers and distributed shared memory");
// 65,538 blocks of a 262,144-cell context: 8,193 keys of 4 bytes per CTA
assert_eq!(super::dynamic_smem(65_538), 8_193 * 4);
assert_eq!(super::dynamic_smem(8), 4);
assert_eq!(super::dynamic_smem(9), 8);
}
}
+15
View File
@@ -69,6 +69,9 @@ pub(crate) fn topk_entry(tile_reach: usize) -> (usize, u32) {
None => TOPK_DEFAULT_WIDE,
}),
};
topk_choice(wide, tile_reach)
}
fn topk_choice(wide: bool, tile_reach: usize) -> (usize, u32) {
if wide && tile_reach >= TOPK_WIDE_MIN_BLOCKS { (TOPK_WIDE, 1024) } else { (TOPK_FAST, 256) }
}
/// The switch is on, the asset is the sealed one and the device can load it: the sealed image is sm_120; a build with `sm86` on a pre-Blackwell
@@ -93,6 +96,18 @@ pub(crate) fn usable(context: &crate::Context<'_>) -> bool {
#[cfg(test)]
mod tests {
#[test]
fn the_wide_topk_takes_only_the_long_tiles_and_only_when_asked() {
assert_eq!(super::topk_choice(false, 60_000), (super::TOPK_FAST, 256));
assert_eq!(super::topk_choice(true, super::TOPK_WIDE_MIN_BLOCKS - 1), (super::TOPK_FAST, 256));
assert_eq!(super::topk_choice(true, super::TOPK_WIDE_MIN_BLOCKS), (super::TOPK_WIDE, 1024));
assert_eq!(super::topk_choice(true, 65_538), (super::TOPK_WIDE, 1024));
// the entry indices are the positions in ENTRIES
for (i, name) in [(super::TOPK_FAST, "leleka_qsa_topk_fast"), (super::SCORE_SCAN_FAST, "leleka_qsa_score_scan_fast"), (super::TOPK_WIDE, "leleka_qsa_topk_wide"), (super::TOPK_WIDE_FAILED, "leleka_qsa_topk_wide_failed"), (super::TOPK_SAMPLE, "leleka_qsa_topk_sample")] {
assert_eq!(super::ENTRIES[i].to_str().unwrap(), name);
}
}
#[test]
fn the_asset_is_the_sealed_one_and_exports_its_entries() {
assert!(super::admit().is_ok(), "qsa_late.ptx does not match its pin (re-seal with scripts/gpu-bringup/seal_pins.py)");
+59 -1
View File
@@ -163,7 +163,12 @@ fn topk_variants_equal_the_original_and_are_timed() {
guard.finish().expect("finish");
let mut rng = Rng(0x9e3779b97f4a7c15);
// (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail (relu-sum like)
let cases: [(usize, usize, u8, &str); 19] = [
let cases: [(usize, usize, u8, &str); 24] = [
(100, 4, 3, "decode"),
(2_040, 4, 3, "decode"),
(2_049, 5, 1, "decode"),
(3_000, 4, 3, "decode"),
(9_999, 3, 2, "decode"),
(2_040, 256, 3, "prompt"),
(8_000, 256, 3, "prompt"),
(24_000, 256, 3, "prompt"),
@@ -264,3 +269,56 @@ fn topk_variants_equal_the_original_and_are_timed() {
eprintln!("{line} ids equal");
}
}
/// Timing only (row 2.5 follow-up): the decode window's block scores (`qsa_decode_scores`, the Original's multi-query kernel, 256 CTAs) next to its
/// top-k at the same shape, to see what the select costs per QSA layer at depth. Prints `QSA-DECODE-SCORES`.
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn decode_scores_are_timed_next_to_the_topk() {
assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes"));
let driver = Driver::load().expect("driver");
let device = driver.device(0).expect("device");
let context = device.create_context(6usize << 30).expect("context");
let workspace = context.native_batch_workspace().expect("workspace");
let stream = workspace.blas().expect("blas").stream();
let max_blocks = crate::serving_context::geometry().max_blocks();
let guard = context.enter().expect("enter");
let select = KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_decode_scores", c"qsa_topk_ref"]).expect("select module");
guard.finish().expect("finish");
let mut rng = Rng(0x1234_5678_9abc_def1);
for (pos, nq) in [(131_072usize, 4usize), (245_000, 1), (245_000, 4), (245_000, 5)] {
let n_bid_max = (pos + nq) / 4;
let pooled: Vec<f32> = (0..(max_blocks + 1) * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect();
let dead: Vec<f32> = (0..128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect();
let qidx: Vec<f32> = (0..nq * 4 * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect();
let mut steps = Vec::new();
for r in 0..nq {
let p = pos + r;
for x in [p, p + 1, (p + 1) / 4, (p + 1).min(CAP)] {
steps.extend_from_slice(&(x as i32).to_le_bytes());
}
}
let f = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
let (pooled_d, dead_d, qidx_d, steps_d) = (upload(&context, &f(&pooled)), upload(&context, &f(&dead)), upload(&context, &f(&qidx)), upload(&context, &steps));
let scores_d = upload(&context, &vec![0u8; nq * max_blocks * 4]);
let ids_d = upload(&context, &vec![0xffu8; nq * CAP * 4]);
let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle");
let guard = context.enter().expect("enter");
let time = |run: &mut dyn FnMut()| -> f64 {
run();
context.driver.api.synchronize().expect("sync");
let t0 = std::time::Instant::now();
for _ in 0..20 {
run();
}
context.driver.api.synchronize().expect("sync");
t0.elapsed().as_secs_f64() * 1e6 / 20.0
};
let mut sa = KernelArguments::new(vec![A::Address(h(&pooled_d)), A::Address(h(&dead_d)), A::Address(h(&qidx_d)), A::Address(h(&steps_d)), A::I32(nq as i32), A::I64(max_blocks as i64), A::Address(h(&scores_d))]);
let scores_us = time(&mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores"));
let mut ta = KernelArguments::new(vec![A::Address(h(&scores_d)), A::Address(h(&steps_d)), A::I64(max_blocks as i64), A::I64(CAP as i64), A::Address(h(&ids_d))]);
let topk_us = time(&mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk"));
guard.finish().expect("finish");
eprintln!("QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)");
}
}
+18
View File
@@ -90,6 +90,24 @@ Diff list above; no implementation, nothing measured.
### Not verified / not done
The 30-pass A/Bs (3 repetitions for 3.1, none for 0.6 because the mechanism is absent), the 256k-class A/B, the 2048-slot quality gate, anything on the laptop GPU. `cargo build/test` was not run on this laptop (by instruction); all builds and unit tests ran on the server from a tarball of the worktree.
## Rows 2.4 / 2.5: analysis (2026-10-27, branch `claude/upstream-rest`, from `claude/port-gpu-bringup` c40531f)
Method: read the upstream sources (`engine/strata/src/prefill/kernels.cu`, `src/kernels/cuda/qsa_select.cu`, `moe_mmq.cu`, `prefill.cpp`) against ours (`crates/cuda-driver/src/prefill_stage.cu`,
`qsa_late.cu`, `qsa_resident_index_program.rs`, the sealed `qsa_prompt_select.ptx` that the decode window launches as `qsa_topk_ref`). The upstream repository has no history in our tree, so the
commits are identified by content. Where the 256k workload stands (`night5-long-256k`, job on 2026-10-27, 5090): a 5-turn session to 243k tokens has TTFT 25.2-30.6 s per turn (chunk 2048,
per-layer ring: expert DMA dominates, 0.8-1.1 s of a ~1.2 s chunk) and decode 80-103 tok/s against 130-170 at short context. Two different things can move at depth: the prompt stages whose
cost grows with the position (QSA index: scores, top-k) and the decode window's QSA select (one `qsa_topk_ref` CTA per query, 12 layers).
| Item | Upstream | What we have | Verdict |
|---|---|---|---|
| GDN recurrence, 3 value heads per thread (`4e69f974`) | `gdn_rec_kh_kernel`: 64 blocks, cp.async blocks of 8 tokens, 2 barriers per token | the Original's `gdn_rec_cols_pipe` (192 blocks, 5 barriers) and our opt-in two-barrier `leleka_prefill_gdn_rec` | **ported** (`leleka_prefill_gdn_rec_kh`, opt-in): bit-identical, but only -6 % per launch on the 5090 (see Results); 64 blocks on 170 SMs leaves the card two thirds idle |
| no dead FP32 store in the GDN output norm | `gdn_out_norm` without the `y` store | `leleka_prefill_gdn_out_norm` writes `y` (nothing reads it afterwards: the projection takes `y16`) | **ported** as `leleka_prefill_gdn_out_norm_y16`, bit-identical y16 and status words |
| quantize each token's MoE input once, scatter to the K rows (`c675f5b7`) | `quantize_scatter_mmq_q8_1_cuda` instead of a gather over T*K rows | ggml `quantize_mmq_q8_1` with the id gather over T*K rows (sealed Original MMQ asset) | **not ported**: upstream's own number is 77.5 -> 58.1 ms for a 32K prompt on a 5090, i.e. at most ~5 ms of an 8192-token chunk (0.3 %), and it needs a new kernel in the MMQ q8_1 layout plus the inverse slot map |
| `DEQUANT_WIDE` (`5f843a92`) | wide dequantization of Q4_K/Q5_K/Q6_K/IQ4_XS, default on sm_86/sm_61 only | our `leleka_prefill_dequant_*` already run one thread per element (9 ms per chunk on the 5090, 36 ms per 2048-token chunk on the 3080) | **not applicable** to sm_120; a thread-per-8-values variant could only matter on the 3080 (not measured) |
| QSA top-k, 1,024-thread kernel past ~135K cells (`586367cb`) | `block_topk_wide_kernel` (per-warp histograms, 4 radix passes + count + emit) | `qsa_topk_ref` (Original, 256 threads, 704-byte stride between lanes) and our `leleka_qsa_topk_fast` (256 threads, coalesced, 6 passes) | **ported**, faster than `fast` from ~10k blocks (-45 % at 180k, -49 % at 245k per 256-row tile); upstream's one-read `sample` kernel measured and not used |
| QSA top-k on a thread-block cluster, sm_90+ (`d05d26e9`) | `block_topk_cluster_kernel`: 8 CTAs of 1,024 threads per query, histograms pushed through distributed shared memory | the decode window launches `qsa_topk_ref` with one 256-thread CTA per query (12 layers per window) | **ported** (`qsa_cluster.cu`, `cuLaunchKernelEx` inside the captured window): 183 -> 19.5 us per call at 245k tokens (4 queries) in the model-free probe |
| cluster greedy argmax (`6ef23b89`) | `sampler.cu` | one block per token, 79 us per window (`docs/chain-kernels.md`) | row 2.1/2.2 item, tier 2 |
## Not taken (reasons in the digest)
Qwen3.6-35B-A3B path, Metal/SYCL/HIP-only changes, K8V4 streaming and elastic KV (`--kv-grow`; our serve path excludes K8V4), the installers and host app.
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Per-arm sums of the PREFILL-PROFILE chunk stages of a replay log, and a paired summary of the arms of one kind.
usage: arm_prof.py FULL_LOG [STAGE ...] (default stages: gdn qsa moe inject)
Arms are split by `REPLAY-ARM start label=` lines; every `PREFILL-PROFILE first=F tokens=N total_ms=T <stage>=ms ...` line is one chunk of the arm that
is running. Prints per arm: chunks, tokens, the sum of total_ms and of each stage, and the same for the chunks that start past 100,000 tokens (the
position dependent part). The last table pools the arms by the label's letter (B1/B2/B3 -> B) and prints mean and spread over the pooled arms.
(docs/upstream-port-plan.md rows 2.4 / 2.5.)
"""
import re
import statistics
import sys
log = sys.argv[1]
stages = sys.argv[2:] or ["gdn", "qsa", "moe", "inject"]
arms = []
cur = None
for line in open(log, errors="replace"):
m = re.search(r"REPLAY-ARM start label=(\S+)", line)
if m:
cur = {"label": m[1], "chunks": []}
arms.append(cur)
continue
m = re.match(r"PREFILL-PROFILE first=(\d+) tokens=(\d+) total_ms=([\d.]+)", line)
if m and cur is not None:
row = {"first": int(m[1]), "tokens": int(m[2]), "total": float(m[3])}
for s in stages:
v = re.search(rf" {re.escape(s)}=([\d.]+)", line)
row[s] = float(v[1]) if v else 0.0
cur["chunks"].append(row)
def sums(chunks):
out = {"chunks": len(chunks), "tokens": sum(c["tokens"] for c in chunks), "total": sum(c["total"] for c in chunks)}
for s in stages:
out[s] = sum(c[s] for c in chunks)
return out
cols = ["chunks", "tokens", "total"] + stages
print("per arm (ms): " + " ".join(f"{c:>10}" for c in cols))
for a in arms:
for name, ch in (("all", a["chunks"]), ("pos>=100k", [c for c in a["chunks"] if c["first"] >= 100_000])):
s = sums(ch)
print(f"{a['label']:<8} {name:<14} " + " ".join(f"{s[c]:>10.0f}" for c in cols))
print("\npooled by arm letter (mean +- sd over the arms, ms):")
kinds = {}
for a in arms:
kinds.setdefault(re.sub(r"\d+$", "", a["label"]), []).append(a)
for k, group in kinds.items():
for name, pick in (("all", lambda a: a["chunks"]), ("pos>=100k", lambda a: [c for c in a["chunks"] if c["first"] >= 100_000])):
vals = [sums(pick(a)) for a in group]
cells = []
for c in ["total"] + stages:
xs = [v[c] for v in vals]
cells.append(f"{c} {statistics.mean(xs):.0f}+-{(statistics.stdev(xs) if len(xs) > 1 else 0):.0f}")
print(f"{k:<4} n={len(group)} {name:<10} " + " ".join(cells))