chain: probe harness fixes (sync after uploads), trimmed GR down variants, QSA phase profile, vocabulary replay job, doc draft

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-24 02:22:37 +02:00
co-authored by Claude Sonnet 5.5
parent 4ee333fea7
commit ce7eed156a
9 changed files with 3897 additions and 75101 deletions
+1 -3
View File
@@ -594,9 +594,7 @@ __device__ __forceinline__ void gr_down_body(const GrMulti& m) {
#define CHAIN_GR_DOWN(W, NB) \
extern "C" __global__ void __launch_bounds__((W) * 32) chain_gr_down_w##W##_nb##NB(GrMulti m) { gr_down_body<W, NB>(m); }
CHAIN_GR_DOWN(1, 3) CHAIN_GR_DOWN(1, 4)
CHAIN_GR_DOWN(2, 2) CHAIN_GR_DOWN(2, 3) CHAIN_GR_DOWN(2, 4)
CHAIN_GR_DOWN(4, 2) CHAIN_GR_DOWN(4, 3) CHAIN_GR_DOWN(4, 4)
CHAIN_GR_DOWN(4, 3)
CHAIN_GR_DOWN(8, 2) CHAIN_GR_DOWN(8, 3) CHAIN_GR_DOWN(8, 4)
// ------------------------------------------------------------------------------------------------------------------
File diff suppressed because it is too large Load Diff
@@ -35,7 +35,7 @@ pub(crate) const E_QSA_MERGE_N: &str = "chain_qsa_decode_merge_n";
pub(crate) static CHAIN: AssetSpec = AssetSpec {
name: "chain_window.ptx",
ptx: concat!(include_str!("chain_window.ptx"), "\0").as_bytes(),
sha: [71, 173, 118, 71, 168, 104, 246, 118, 214, 166, 192, 161, 212, 117, 254, 4, 109, 125, 149, 45, 234, 76, 179, 114, 214, 121, 63, 88, 156, 138, 182, 177],
sha: [179, 71, 154, 144, 78, 250, 34, 150, 223, 208, 102, 129, 88, 17, 29, 166, 253, 74, 178, 94, 35, 165, 15, 209, 196, 213, 62, 218, 241, 50, 6, 41],
entries: &[E_COPY_I32, E_WAIT_COPY_I32, E_COPY_ROWS, E_DOORBELL, E_GDN_AB, E_GR_SPLIT, E_GR_UP16, E_GR_UP8, E_QSA_CHUNK, E_SWIGLU_QUANT, E_SCALE_SIGMOID, E_SAMPLER_GREEDY, E_ROW_TOP_PROB, E_QSA_MERGE_N],
unsealed: "Original verifier asset unsealed: chain_window.ptx (latency-hoisted chain kernels)",
};
+67
View File
@@ -0,0 +1,67 @@
# Chain kernels: the GPU chain of the decode verify window and of the MTP draft step (`claude/chain-kernels`)
Status: tables of section 2 are measured (ledger CUPTI traces, jobs 9062/9004). Sections 4-6 are filled as the model-free probe and A/B jobs
(`tools/chain-probe/`, jobs `9c*`) report; a number without a job name is not measured.
## 0. Summary
* In the hit-heavy regime of real agent sessions the verify window is the GPU chain plus the host/PCIe waits. The port's chain is **the Original's chain**: kernel for kernel the
same launch shapes and the same durations (12,561 us per 4-row window for both, section 2). Nothing in the window is slower than the Original's equivalent, and nothing is faster,
so "the port must be faster than the Original" needs kernels that the Original does not have.
* The chain is **latency-bound, not bandwidth-bound**: 2,418 kernels per 4-row window, 25 to 60 per layer, HBM busy about a quarter of the time. The biggest losses against the
bandwidth floor are small-grid kernels with serial dependent loads: the hyper-connection read (3.4 ms, 27 % of the chain, about 4x its floor), the CPU-leg row copy and the plan
copy from mapped host memory, the GDN alpha/beta gates, the QSA decode attention chunk, the hyper-connection up projection.
* `chain_window.cu` holds bit-identical variants of those kernels (same operations, same order, loads issued ahead), plus a few fusions; all behind `LELEKA_CHAIN` (off by default).
* Draft vocabulary: section 7.
## 1. Tools
| tool | what |
| --- | --- |
| `tools/chain-probe/window_table.py` | per-role kernel table of the verify windows of two CUPTI traces (`claude/ledger`'s `tools/cupti-trace`, `scripts/profile/lct.py`) |
| `tools/chain-probe/chain_probe.cpp` | model-free probe: loads the sealed Original PTX and `chain_window.ptx`, runs both on real-size random inputs, compares **every output byte**, times both inside a CUDA graph with cold weights |
| `tools/chain-probe/mb_pdl.cu` | graph kernel-to-kernel latency with and without programmatic dependent launch, and prefetch-ahead |
| `tools/chain-probe/jobs/` | holder jobs: `9c5` paired A/B (chain off / on), `9c6` CUPTI traces of both arms, `9c7` draft vocabulary on the CRM replay |
| `scripts/chain/{build_rt,test_driver,seal_chain}.sh` | WSL builds, driver unit tests, compile+seal of `chain_window.ptx` with `compile_assets.py` / `seal_pins.py` |
## 2. The window, kernel by kernel (port against Original, hit regime)
Traces: ledger job 9062, `port-corpus-hit` (rt-base, no draft vocabulary bound) and `orig-corpus-hit` (unmodified Original, `--dump-routing` profile of the corpus's own routing,
static 2048 slots, ledger tracer). Windows of 4 rows (49 port / 115 Original windows) and 6 rows (6 / 22). "chain" = every kernel that is not a host or PCIe wait.
### 2.1 Four-row window
TABLE4
### 2.2 Six-row window
TABLE6
### 2.3 Gaps inside the graph
Every window is one stream and one graph; consecutive kernels start 64 to 128 ns after the previous one ends (98 % of 112,000 gaps in the 64-128 ns bin): 218 us per port window
(1.7 % of the chain), 239 us for the Original. There are no event gaps (no cross-stream edges) in the window. The graph kernel gap is therefore not where the chain is lost; the loss
is the 0.7 to 1.0 us a tiny kernel takes between its first and last thread, and the serial dependent loads of the small-grid kernels. The only exception in the Original's trace is
an 0.9 us hole after the QSA K projection (`native_mmvq_multi -> norm`, 11 us per window) which the port does not have.
### 2.4 Ranking against the floor (4 rows, HBM 1.69 TB/s)
| rank | family | port us/window | floor us | gap us | what limits it |
| --- | --- | ---: | ---: | ---: | --- |
| 1 | hyper-connection read: norm + staged down + up (96 calls, 13.1 MB each) | 3,391 | 910 (7.7 us HBM + 1.5 norm per call) | 2,480 | 41-block down projection 13 us (8 serial cp.async tiles), up 7.5 us (8 rows per warp loaded one behind the other) |
| 2 | routed experts gate/up + down (hits + staged) | 2,434 | 950 (1.6 GB) | ~1,500 | grouped MMQ at 12.5 us per call; ramp and tail of many small groups; not touched here |
| 3 | dense projections (qkv, z, out, q, k, v, shared) | 2,250 | ~2,000 | ~250 | at the HBM floor already |
| 4 | CPU-leg rows copy + plan copy + doorbell + their waits' PCIe reads | 1,040 | ~250 | ~790 | serial volatile loads from mapped host memory: 5 and 6 PCIe round trips |
| 5 | QSA decode attention chunk | 470 | ~60 | ~410 | 64 cells walked one dependent load at a time |
| 6 | GDN alpha/beta | 368 | ~100 | ~270 | 12 blocks, 10 dependent weight/activation rounds |
| 7 | greedy argmax (248,320 logits, one block per token) | 79 | 10 | ~70 | 243 dependent loads per thread |
| 8 | ~25 tiny kernels per layer (quantize, swiglu, scale, sigmoid, ...) | ~900 | | ~450 | launch + ramp (0.7-1.0 us each) |
Which families are slower than the Original's equivalents: none beyond noise; routed experts gate/up and down are +100 us each in the port because the 4-row set contains more groups
(the port's hit regime differs by about 2 experts per layer between the two runs); `doorbell` is 142 us faster in the port. Extra kernels the port has: the split QSA scores/topk/resolve
(`qsa_decode_scores`, `qsa_topk_ref`, `leleka_qsa_resolve`, `leleka_qsa_miss_copy`) replace the Original's `block_scores_multi`, `block_topk_reg` (+60 us), and the PLE history snapshot copies;
no port-only guard kernels exist in the verify window (they are in the MTP step, section 5).
## 7. The MTP draft vocabulary (coordinator request)
DRAFTVOCAB
+1
View File
@@ -19,5 +19,6 @@ for f in original_verify mtp_original_full_fused_gr mtp_original_full_attention
cp crates/cuda-driver/src/$f.ptx "$out/ptx/$f.ptx"
fi
done
"$nvcc" -ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false -I"$root/engine/strata/include" "$here/qsa_prof.cu" -o "$out/ptx/qsa_prof.ptx"
ls -la "$out" "$out/ptx"
sha256sum "$out"/chain_probe "$out"/mb_pdl "$out"/ptx/* > "$out/SHA256SUMS"
+36 -5
View File
@@ -49,8 +49,8 @@ static CUfunction get_fn(CUmodule m, const char* name) {
struct Dev {
CUdeviceptr p = 0; size_t n = 0;
void alloc(size_t bytes) { n = bytes; CU(cuMemAlloc(&p, bytes ? bytes : 1)); CU(cuMemsetD8(p, 0, bytes ? bytes : 1)); }
void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); }
void alloc(size_t bytes) { n = bytes; CU(cuMemAlloc(&p, bytes ? bytes : 1)); CU(cuMemsetD8(p, 0, bytes ? bytes : 1)); CU(cuCtxSynchronize()); }
void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); CU(cuCtxSynchronize()); }
std::vector<uint8_t> get() const { std::vector<uint8_t> v(n); CU(cuMemcpyDtoH(v.data(), p, n)); return v; }
};
@@ -225,6 +225,7 @@ static void gr_alloc(GrState& s, int T) {
}
static void gr_copy_in(GrState& dst, const GrState& src) {
CU(cuMemcpyDtoD(dst.R.p, src.R.p, src.R.n)); CU(cuMemcpyDtoD(dst.bo.p, src.bo.p, src.bo.n)); CU(cuMemcpyDtoD(dst.inj.p, src.inj.p, src.inj.n));
CU(cuCtxSynchronize());
}
static bool gr_compare(const char* tag, GrState& a, GrState& b, bool xn = true) {
bool ok = same((std::string(tag) + " R").c_str(), a.R.get(), b.R.get());
@@ -278,8 +279,7 @@ static void test_gr() {
// ---- the new down projection shapes: exactness against the Original's staged kernel, then timing
struct DV { const char* name; int W, NB; CUfunction f; };
std::vector<DV> dvs = {{"w1_nb3", 1, 3, 0}, {"w1_nb4", 1, 4, 0}, {"w2_nb2", 2, 2, 0}, {"w2_nb3", 2, 3, 0}, {"w2_nb4", 2, 4, 0}, {"w4_nb2", 4, 2, 0}, {"w4_nb3", 4, 3, 0}, {"w4_nb4", 4, 4, 0},
{"w8_nb2", 8, 2, 0}, {"w8_nb3", 8, 3, 0}, {"w8_nb4", 8, 4, 0}};
std::vector<DV> dvs = {{"w4_nb3", 4, 3, 0}, {"w8_nb2", 8, 2, 0}, {"w8_nb3", 8, 3, 0}, {"w8_nb4", 8, 4, 0}};
for (auto& v : dvs) {
char nm[64]; snprintf(nm, sizeof nm, "chain_gr_down_%s", v.name);
v.f = get_fn(mChain, nm);
@@ -442,6 +442,7 @@ static void test_tiny() {
{ void* a[] = {&g.p, &u.p, &h1.p, &q1.p, &nh}; launch(nSQ, grid, 1, 256, 0, a); }
CU(cuStreamSynchronize(g_s));
bool ok = same("swiglu_quant h", h0.get(), h1.get()) & same("swiglu_quant q", q0.get(), q1.get());
if (!ok) { auto a = h0.get(), b = h1.get(); int shown = 0; for (long long i = 0; i < nh && shown < 4; ++i) { float x, y; memcpy(&x, &a[4 * i], 4); memcpy(&y, &b[4 * i], 4); if (memcmp(&x, &y, 4)) { printf(" diag h[%lld]: old %.9g new %.9g (g=%.9g up=%.9g)\n", i, x, y, gh[i], uh[i]); ++shown; } } }
double to = time_graph([&](int) { void* a[] = {&g.p, &u.p, &h0.p, &nh}; launch(fSwi, grid, 1, 256, 0, a); void* b[] = {&h0.p, &q0.p, &nh}; launch(fQ, grid, 1, 256, 0, b); }, 200);
double tn = time_graph([&](int) { void* a[] = {&g.p, &u.p, &h1.p, &q1.p, &nh}; launch(nSQ, grid, 1, 256, 0, a); }, 200);
printf("RESULT swiglu_quant cap=%d ok=%d old_us=%.3f new_us=%.3f\n", cap, ok, to, tn);
@@ -501,6 +502,7 @@ static void test_sampler() {
CU(cuStreamSynchronize(g_s));
char tag[64]; snprintf(tag, sizeof tag, "sampler V=%d T=%d variant=%d", V, T, variant);
bool ok = same(tag, o0.get(), o1.get());
if (!ok) { auto a = o0.get(), b = o1.get(); for (int t = 0; t < T; ++t) { int32_t x, y; memcpy(&x, &a[4 * t], 4); memcpy(&y, &b[4 * t], 4); if (x != y) printf(" diag row %d: old idx %d (logit %.9g) new idx %d (logit %.9g)\n", t, x, lh[(size_t)t * V + x], y, lh[(size_t)t * V + y]); } }
double to = time_graph([&](int) { launch(fo, T, 1, 1024, shared, a0); }, 50);
double tn = time_graph([&](int) { launch(fn, T, 1, 1024, shared, a1); }, 50);
printf("RESULT sampler_greedy V=%d T=%d variant=%d ok=%d old_us=%.3f new_us=%.3f\n", V, T, variant, ok, to, tn);
@@ -522,12 +524,40 @@ static void test_sampler() {
}
}
static void test_qsaprof(const std::string& dir) {
CUmodule m = load_module(dir + "/qsa_prof.ptx");
CUfunction f = get_fn(m, "qsa_chunk_prof");
const int nkv = 2, G = 12, HD = 256, cap = 2051, chunks = 33, page = 4, cells = 4096;
const int pages = cells / page; const size_t rows = (size_t)pages * nkv * page;
std::vector<int8_t> kq(rows * HD), vq(rows * HD); std::vector<uint16_t> ks(rows * 4, 0x2c00), vs(rows * 4, 0x2c00);
for (auto& v : kq) v = (int8_t)(rnd() & 0xff); for (auto& v : vq) v = (int8_t)(rnd() & 0xff);
std::vector<int32_t> table(pages); for (int i = 0; i < pages; ++i) table[i] = (i * 7 + 3) % pages;
Dev dkq, dvq, dks, dvs, dtab, stamps; dkq.alloc(kq.size()); dvq.alloc(vq.size()); dks.alloc(ks.size() * 2); dvs.alloc(vs.size() * 2); dtab.alloc(pages * 4); stamps.alloc(64);
dkq.put(kq.data(), kq.size()); dvq.put(vq.data(), vq.size()); dks.put(ks.data(), ks.size() * 2); dvs.put(vs.data(), vs.size() * 2); dtab.put(table.data(), pages * 4);
for (int T : {1, 4}) {
std::vector<int32_t> ids((size_t)T * cap), step((size_t)T * 4);
for (int r = 0; r < T; ++r) { for (int j = 0; j < cap; ++j) ids[(size_t)r * cap + j] = (j * 2 + (j % 3)) % cells; std::sort(ids.begin() + (size_t)r * cap, ids.begin() + (size_t)(r + 1) * cap); step[r * 4] = cells - 1; step[r * 4 + 1] = cells; step[r * 4 + 2] = cells / 4; step[r * 4 + 3] = cap; }
std::vector<float> qh((size_t)T * nkv * G * HD); for (auto& v : qh) v = rndf();
size_t stride = (size_t)chunks * 24 * (HD + 2) + 64;
Dev q, did, dstep, a0; q.alloc(qh.size() * 4); did.alloc(ids.size() * 4); dstep.alloc(step.size() * 4); a0.alloc(stride * 4 * T);
q.put(qh.data(), qh.size() * 4); did.put(ids.data(), ids.size() * 4); dstep.put(step.data(), step.size() * 4);
int nk = nkv, ps = page, nch = chunks, cp = cap; float scale = 1.0f / 16.0f; long long st = (long long)stride;
CUdeviceptr pm = a0.p + (uint64_t)chunks * 24 * HD * 4, pl = pm + (uint64_t)chunks * 24 * 4;
void* a[] = {&stamps.p, &q.p, &dkq.p, &dvq.p, &dks.p, &dvs.p, &dtab.p, &did.p, &dstep.p, &nk, &ps, &scale, &a0.p, &pm, &pl, &nch, &cp, &st};
for (int rep = 0; rep < 3; ++rep) { CU(cuLaunchKernel(f, chunks, nkv, T, 256, 1, 1, 0, g_s, a, nullptr)); CU(cuStreamSynchronize(g_s)); }
auto b = stamps.get(); unsigned long long v[4]; memcpy(v, b.data(), 32);
int clk = 0; cuDeviceGetAttribute(&clk, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, 0);
printf("RESULT qsa_prof T=%d cycles setup=%llu scores=%llu softmax=%llu values=%llu (SM clock %d kHz: %.2f %.2f %.2f %.2f us)\n", T, v[0], v[1], v[2], v[3], clk,
v[0] * 1e3 / clk, v[1] * 1e3 / clk, v[2] * 1e3 / clk, v[3] * 1e3 / clk);
}
}
int main(int argc, char** argv) {
if (argc < 2) { fprintf(stderr, "usage: chain_probe PTXDIR [tests...]\n"); return 2; }
std::string dir = argv[1];
std::vector<std::string> tests;
for (int i = 2; i < argc; ++i) tests.push_back(argv[i]);
if (tests.empty()) tests = {"copy_i32", "copy_rows", "doorbell", "ab", "gr", "qsa", "tiny", "sampler"};
if (tests.empty()) tests = {"copy_i32", "copy_rows", "doorbell", "ab", "gr", "qsa", "tiny", "sampler", "qsaprof"};
CU(cuInit(0)); CUdevice dev; CU(cuDeviceGet(&dev, 0)); CUcontext ctx; CU(cuDevicePrimaryCtxRetain(&ctx, dev)); CU(cuCtxSetCurrent(ctx));
char name[256]; cuDeviceGetName(name, sizeof name, dev);
int maj, min; cuDeviceGetAttribute(&maj, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev); cuDeviceGetAttribute(&min, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev);
@@ -550,6 +580,7 @@ int main(int argc, char** argv) {
else if (t == "qsa") test_qsa();
else if (t == "tiny") test_tiny();
else if (t == "sampler") test_sampler();
else if (t == "qsaprof") test_qsaprof(dir);
else fprintf(stderr, "unknown test %s\n", t.c_str());
}
printf("RESULT summary failures=%d\n", g_fail);
@@ -0,0 +1,39 @@
# claude/chain-kernels: effect of the MTP draft vocabulary on acceptance and decode speed in agent traffic (coordinator request): the first 30 requests of the
# two captured Codex sessions (943b tic-tac-toe, conversation cache; 945 CRM, prefix cache auto) replayed through the port with the reference configuration
# (auto per-layer expert slots, spec_min_p 0.5, LELEKA_CHAIN=0 so only the vocabulary differs), three draft vocabularies:
# V0 = none (full 248,320-row head), V1 = the Original's shipped subset (106,299 ids, English/code + CJK), V3 = V1 + every Cyrillic token (124,737 ids).
# Trimmed on the coordinator's decision: ONLY the CRM session (3 arms) plus one 6-prompt corpus arm with V3 (the Ukrainian prompt 3 tokens per round with the Cyrillic
# union; the none / shipped numbers of the same corpus are in ledger job 9004, port-corpus-b / port-corpus-rt). Model job, 4 arms of ~7 min.
set -uo pipefail
A=$HOME/leleka-gates/assets; G=$HOME/work/gpu-runs
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own
export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$G/baseline/profile.bin LELEKA_GRAPH_EXEC_REUSE=off LELEKA_SERVE_PROFILE=1
export LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 LELEKA_REPLAY_COUNT=30 LELEKA_REPLAY_SPEC_MIN_P=0.5 LELEKA_CHAIN=0
BIN=${BIN:-$HOME/work/chain-bin/rt-t2}
OUT=$HOME/work/chain-bin/runs/9c7-vocab; mkdir -p $OUT
# V3 staging: the MTP pack's heavy files by symlink, the draft vocabulary replaced
V3=$HOME/work/chain-bin/rt-v3; mkdir -p $V3
for f in dense.bin dense.txt experts.bin; do ln -sf $A/data/mtp-rt/$f $V3/$f; done
cp $HOME/work/chain-bin/draft_vocab_plus_cyr.bin $V3/draft_vocab.bin
date -u +%FT%TZ; sha256sum $BIN $A/data/mtp-rt/draft_vocab.bin $V3/draft_vocab.bin
arm() { # name session rt_dir_or_none prefix_mib
echo "=== arm $1: session=$2 rt=$3"; date -u +%FT%TZ
local env_rt=()
[ "$3" != none ] && env_rt=(LELEKA_ORIGINAL_SERVE_RT_DIR=$3)
env "${env_rt[@]}" LELEKA_REPLAY_DIR=$HOME/work/codex-e2e/capture/$2 ${4:+LELEKA_REPLAY_PREFIX_MIB=$4} $BIN --ignored --test-threads=1 --nocapture original_serve_replay_smoke > $OUT/$1.log 2>&1
grep -E '^REPLAY (SUMMARY|config)|test result|panicked' $OUT/$1.log | cut -c1-400
awk '/^REPLAY #[0-9]+ file/{for(i=1;i<=NF;i++){split($i,k,"="); if(k[1]=="produced")p+=k[2]; if(k[1]=="rounds")r+=k[2]}} END{if(r>0) printf "tokens_per_round=%.3f (%d tokens / %d rounds)\n", p/r, p, r}' $OUT/$1.log
}
arm crm-V1 945-codex-crm $A/data/mtp-rt auto
arm crm-V0 945-codex-crm none auto
arm crm-V3 945-codex-crm $V3 auto
# the 6-prompt corpus with V3 (configuration of ledger job 9004 port-corpus-rt: static 2048 slots, standard profile)
( source ~/work/ledger/ledger-common.sh; export BIN
port_corpus chain-vocab-corpus-V3 0 0 LELEKA_ORIGINAL_SERVE_RT_DIR=$V3 LELEKA_CHAIN=0
grep -E "DBG corpus [0-9]+ output" $OUT/chain-vocab-corpus-V3.full | cut -c1-120 ) 2>&1 | tee $OUT/corpus-V3.log
date -u +%FT%TZ
+54
View File
@@ -120,6 +120,44 @@ static double chain_mv(int nm, int rows, int cols, const uint4* W, float* x, flo
return us;
}
// ---- test D: the previous (latency-bound) kernel prefetches the next kernel's weights into L2 ("prefetch ahead", no PDL needed).
// lat: every CTA sleeps `us` microseconds (a stand-in for a latency-bound kernel such as the hyper-connection read) and, when PF, issues
// prefetch.global.L2 for its share of `pf_bytes` at `pf` BEFORE sleeping.
template <int PF>
__global__ void lat(float* x, int us, const char* pf, size_t pf_bytes) {
if (PF) {
const size_t total = (size_t)gridDim.x * blockDim.x;
const size_t lines = pf_bytes / 128;
for (size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += total) asm volatile("prefetch.global.L2 [%0];" ::"l"(pf + i * 128));
}
for (int i = 0; i < us; ++i) __nanosleep(1000);
if (threadIdx.x == 0 && blockIdx.x == 0) x[0] += 1.0f;
}
template <int PF>
static double chain_lat_mv(int nm, int rows, int cols, const uint4* W, float* x, float* y, int us, int ctas, cudaStream_t s) {
cudaGraph_t g; cudaGraphExec_t ge;
CK(cudaStreamBeginCapture(s, cudaStreamCaptureModeGlobal));
const int cols8 = cols / 8;
const size_t per = (size_t)rows * cols * 2;
for (int i = 0; i < nm; ++i) {
const uint4* w = W + (size_t)i * rows * cols8;
const char* pf = (const char*)w;
size_t pfb = per;
float* xx = x; int uu = us;
void* a0[] = {&xx, &uu, &pf, &pfb};
launch_cfg((const void*)lat<PF>, dim3(ctas), dim3(256), s, false, a0);
const float* xc = x; int cc = cols8, rr = rows;
void* a1[] = {&w, &xc, &y, &cc, &rr};
launch_cfg((const void*)mv<0>, dim3((rows + 7) / 8), dim3(256), s, false, a1);
}
CK(cudaStreamEndCapture(s, &g));
CK(cudaGraphInstantiate(&ge, g, 0));
double t = time_graph(ge, s, 20);
CK(cudaGraphExecDestroy(ge)); CK(cudaGraphDestroy(g));
return t;
}
int main() {
cudaDeviceProp p; CK(cudaGetDeviceProperties(&p, 0));
printf("# %s sm_%d%d L2 %d MiB\n", p.name, p.major, p.minor, p.l2CacheSize >> 20);
@@ -148,5 +186,21 @@ int main() {
sh.name, nm, per, a / nm, b / nm, c / nm, per / 1.69e6);
CK(cudaFree(W)); CK(cudaFree(xa)); CK(cudaFree(ya)); CK(cudaFree(za));
}
// test D
for (auto& sh : shapes) {
size_t per = (size_t)sh.rows * sh.cols * 2;
int nm = (int)std::min<size_t>(40, (size_t)(1536ull << 20) / per);
uint4* W; CK(cudaMalloc(&W, per * nm)); CK(cudaMemset(W, 0x3c, per * nm));
float *xa, *ya; CK(cudaMalloc(&xa, 4 * 16384)); CK(cudaMalloc(&ya, 4 * 16384)); CK(cudaMemset(xa, 0, 4 * 16384));
for (int us : {0, 4, 8, 16, 32}) {
for (int ctas : {16, 160}) {
double a = chain_lat_mv<0>(nm, sh.rows, sh.cols, W, xa, ya, us, ctas, s);
double b = chain_lat_mv<1>(nm, sh.rows, sh.cols, W, xa, ya, us, ctas, s);
printf("RESULT prefetch_ahead shape=%s sleep_us=%d ctas=%d plain_us_per_pair=%.3f prefetched_us_per_pair=%.3f saved_us=%.3f\n", sh.name, us, ctas, a / nm, b / nm, (a - b) / nm);
}
}
CK(cudaFree(W)); CK(cudaFree(xa)); CK(cudaFree(ya));
}
return 0;
}
+204
View File
@@ -0,0 +1,204 @@
// Instrumented copy of the Original qsa_native_decode.cu chunk kernel (clock64 stamps per phase of block (5,0,0)); probe-only, never sealed.
// Literal Original qsa_decode_attn.cu fixed INT8 mode1; no prompt arithmetic substitution.
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <cfloat>
#include <cstdint>
#include <cmath>
constexpr int KV_Q8_GROUP=64,QK4_0=32,kStepCount=4,kStepWidth=3;
struct block_q4_0{uint16_t d;uint8_t qs[16];};
struct QsaAttnPools{const int8_t*k_q,*v_q;const uint16_t*k_scale,*v_scale;const int32_t*page_table;
const uint16_t*k_pool=nullptr,*v_pool=nullptr;const uint8_t*k_q4=nullptr,*v_q4=nullptr;
int keyless_n_rot=0;const int32_t*keyless_mrope=nullptr;const float*keyless_cos=nullptr,*keyless_sin=nullptr;};
__device__ int mrope_pos(const int32_t*,int,int); // discarded KV_MODE4 branch, never linked or selected
constexpr int HD = 256; // head_dim
constexpr int G = 12; // query heads per KV head (24 / 2)
constexpr int CHUNK = 64; // cells per block
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float warp_max(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
return v;
}
// 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8).
// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side.
__device__ __forceinline__ void load8_f16(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0;
const uint4 raw = *reinterpret_cast<const uint4*>(base);
const __half2* h2 = reinterpret_cast<const __half2*>(&raw);
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float2 f = __half22float2(h2[j]);
out[2 * j] = f.x;
out[2 * j + 1] = f.y;
}
}
__device__ __forceinline__ void load8_q8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0;
const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP];
const float sc = __half2float(__ushort_as_half(sbits));
const uint2 raw = *reinterpret_cast<const uint2*>(codes);
const int8_t* c = reinterpret_cast<const int8_t*>(&raw);
#pragma unroll
for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc;
}
__device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = d0 / QK4_0;
const int rem = d0 % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = (rem == 0 || rem == 16) ? 0 : 8;
const uint8_t* bytes = blk->qs + j;
if (rem < 16) {
#pragma unroll
for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d;
} else {
#pragma unroll
for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d;
}
}
template <int KV_MODE>
__device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out);
else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out);
else if constexpr (KV_MODE == 3) {
// hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call
// reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review)
if (value) load8_q4(p, value, row, d0, out);
else load8_q8(p, value, row, d0, out);
} else load8_q4(p, value, row, d0, out);
}
constexpr int KV_MODE=1;
extern "C" __global__ void __launch_bounds__(THREADS) qsa_chunk_prof(unsigned long long* stamps, const float* __restrict__ q,const int8_t*kq,const int8_t*vq,const uint16_t*ks,const uint16_t*vs,const int32_t*table,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ step, int n_kv_heads,
int page_size, float scale, float* __restrict__ part_acc,
float* __restrict__ part_m, float* __restrict__ part_l,
int n_chunks, int cap = 0, long long scratch_stride = 0) {
const long long c_start = clock64();
const QsaAttnPools p{kq,vq,ks,vs,table};
// batched form: query blockIdx.z, with its own q row, selection, step and scratch
q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
ids += (size_t) blockIdx.z * (size_t) cap;
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads
__shared__ float sp[G][CHUNK]; // scores, then probabilities
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
const int n_ids = __ldg(step + kStepWidth);
const int chunk = blockIdx.x, kvh = blockIdx.y;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int c0 = chunk * CHUNK;
const int n_here = min(CHUNK, n_ids - c0);
const int slot = kvh * n_chunks + chunk;
if (n_here <= 0) {
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
return;
}
for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
srow[t] = r;
}
__syncthreads();
const long long c1 = clock64();
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
for (int c = warp; c < CHUNK; c += WARPS) {
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
float k8[8];
load8<KV_MODE>(p, KV_MODE == 4, srow[c], lane * 8, k8);
if constexpr (KV_MODE == 4) {
const int d0 = lane * 8, half = p.keyless_n_rot / 2;
if (d0 < p.keyless_n_rot) {
float paired[8];
load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired);
const int cell = ids[c0 + c];
for (int d = 0; d < 8; ++d) {
const int pair = (d0 + d) % half;
const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair);
const float co = p.keyless_cos[(size_t)rotary_pos * half + pair];
const float si = p.keyless_sin[(size_t)rotary_pos * half + pair];
k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si;
}
}
}
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
s = warp_sum(s);
if (lane == 0) sp[h][c] = s * scale;
}
}
__syncthreads();
const long long c2 = clock64();
// per-head chunk max and exp-sum: warp w handles heads w and w+8.
for (int h = warp; h < G; h += WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float m = warp_max(fmaxf(a, b));
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
sp[h][lane] = ea;
sp[h][lane + 32] = eb;
const float l = warp_sum(ea + eb);
if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
}
__syncthreads();
const long long c3 = clock64();
// values: thread t owns dimension t for all 12 heads.
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
for (int c = 0; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
float v;
if constexpr (KV_MODE == 0) {
v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
} else if constexpr (KV_MODE == 1 || KV_MODE == 4) {
const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
v = (float) p.v_q[srow[c] * HD + t] * sc;
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = t / QK4_0;
const int rem = t % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = rem < 16 ? rem : (rem - 16);
const uint8_t byte = blk->qs[j];
const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
v = (float) nibble * d;
}
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
}
#pragma unroll
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
if (blockIdx.x == 5 && blockIdx.y == 0 && blockIdx.z == 0 && threadIdx.x == 0) {
const long long c4 = clock64();
stamps[0] = (unsigned long long)(c1 - c_start); stamps[1] = (unsigned long long)(c2 - c1); stamps[2] = (unsigned long long)(c3 - c2); stamps[3] = (unsigned long long)(c4 - c3);
}
}