From 553b0b788c35f995fddc3ff3020143a7b4a980f1 Mon Sep 17 00:00:00 2001 From: Cass <867000+Cass67@users.noreply.github.com> Date: Fri, 9 Oct 2026 05:10:10 +0100 Subject: [PATCH 01/19] pipeline-windows: overlap three or more layer-split stages; HIP drafter scratch race --pipeline-windows 2 now runs on any layer split with two or more stages. Every stage but the last is a front stage: the guessed window follows the verified one through them one card behind (an odd verifier and an odd hand-off on every boundary, a pair of GDN snapshots on every front stage, commits and the undo per stage), and only the last stage waits for the verdict. The pipelined prompt read (--pipeline-windows 1) and --adapt-async stay two-stage. HIP: the draft layer's per-row gr_read used the last stage's session scratch (ss.block.gr), which that stage's verifier also uses in lm_head_mix. A chain launched at a verdict and the next window's last stage can run on the card at once after a guess that held, and the window's head then read a clobbered mix. The draft layer now carves its own GrWorkspace. Measured on 4x RX 7900 XT (Flash-Next GSQ-RCO IQ3_S, split 12,24,36, every expert in VRAM, greedy, reasoning off): decode 59.4 -> 67.6 tok/s at 4K and 51.8 -> 65.6 at 32K. Greedy text identical to the serial loop on four prompts with STRATA_IQ_MT_MIN=1 --pcie-frac 0 --adapt-every 0, also with every guess forced wrong. Debug knob STRATA_PIPELINE_SPEC_DEPTH. Two-stage path not re-run on two cards. --- docs/MULTI_GPU.md | 24 ++- include/strata/core/mtp.hpp | 3 + src/core/mtp.cpp | 7 +- src/program/generate.cpp | 389 +++++++++++++++++++++--------------- 4 files changed, 258 insertions(+), 165 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index bb80f0f0..39fe08b0 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -1,4 +1,4 @@ -# Strata on two or three GPUs (layer split) +# Strata on two or more GPUs (layer split) One model can run across several NVIDIA cards in one PC. The layers are split into contiguous ranges, one per GPU: the first card runs layers 0 to K-1, the next card runs K onward, and so on; the last card also runs the output head @@ -256,7 +256,10 @@ copied from earlier context (`--suffix-draft`) are guessed past as well, which i most. `--pipeline-windows 1` overlaps only the short prompt reads that go through the verify windows (`--short-read`). -Two cards, exactly two stages, `--serve`. In the config: +Two or more cards, `--serve`. With three or more stages every stage but the last is a front stage: the guessed +window follows the verified one through them one card behind (each front stage keeps its own pair of recurrent-state +copies and puts its state back on a wrong guess), and only the last stage waits for the verdict. `--pipeline-windows 1` +and the asynchronous tier stay two-stage. In the config: ``` "args": [ ..., "--pipeline-windows", "2" ], @@ -264,7 +267,8 @@ Two cards, exactly two stages, `--serve`. In the config: ``` - **Cost**: a second verify window on each card, 160 MiB more kept out of each card's expert cache, plus two copies - of the first card's recurrent state (about 3 MiB per GDN layer it runs) on the first card with `2`. + of the first card's recurrent state (about 3 MiB per GDN layer it runs) on the first card with `2` (on every front + card with three or more stages; only the first card's room is kept out of its cache, the others allocate theirs after). - **Same text**: the last card only ever runs windows that are verified, and every window row computes what it would in any other window, so the tokens are the serial loop's. With `STRATA_IQ_MT_MIN=1 --pcie-frac 0 --adapt-every 0` the greedy output is identical bit for bit to the serial loop's with the same expert caches. The pipeline keeps @@ -272,8 +276,8 @@ Two cards, exactly two stages, `--serve`. In the config: rounds them differently, and a near-tie can flip (a serial run given the same caches through `--vram-reserve-mib` matches it exactly). - **Off, with one line in the log saying why**, with `--batch` slots, `--peer-device`, the helper caches - (`--expert-cache-device1..3`, which `--remote-expert-opt` builds on), a split into three or more stages or onto one GPU - (`--split-device 0`), or no draft layer. A request with repetition penalties (`penalty_last_n`) or coupled + (`--expert-cache-device1..3`, which `--remote-expert-opt` builds on), a split onto one GPU (`--split-device 0`), or no + draft layer; on three or more stages also `--pipeline-windows 1` and `--adapt-async 1`. A request with repetition penalties (`penalty_last_n`) or coupled draft sampling decodes serially. - **With the resident RAM mode's asynchronous swaps** (`--adapt-async 1`, [DETAILS.md](DETAILS.md)) a round's steps advance between the verified windows. Each card's copies are queued by the decode loop itself while that card has @@ -285,8 +289,16 @@ Two cards, exactly two stages, `--serve`. In the config: 63.0 -> 71.1, Italian prose 41.6 -> 46.3, a copy-heavy edit (a 5 KB file back with a rename) 90.5 -> 117.9; mean 72.4 -> 84.0 (+16%). It pays when the windows are GPU-bound: with the experts read through the OS file cache (`--mmap-experts` on that 32 GB PC) the file reads dominate and it measured no faster. +- **Measured on four stages** (Flash-Next GSQ-RCO IQ3_S, 262K context, int8 KV, layer split 12,24,36 on 4x RX 7900 XT, + every expert in VRAM; greedy, reasoning off, 256 tokens, repository-text prompts): decode 59.4 -> 67.6 tok/s at 4K + (median of 3) and 51.8 -> 65.6 at 32K. A guessed window that holds costs ~15 ms against ~43 ms for a fresh one; about + a third of the guesses held. The greedy text was identical to the serial loop's on all four prompts (`STRATA_IQ_MT_MIN=1 + --pcie-frac 0 --adapt-every 0`), and with every guess forced wrong (`STRATA_PIPELINE_FORCE_MISS=1`). +- **HIP**: the draft layer's per-row `gr_read` used the last stage's session scratch (`ss.block.gr`), which that stage's + verifier also uses; a chain launched at a verdict and the next window's last stage then ran on the card at once and + the window's head read a clobbered mix (wrong tokens after a guess that held). The draft layer now has its own scratch. -The `STRATA_PIPELINE_*` tuning and test variables (THETA, FORCE_MISS, SWITCH, LOG, TRACE and the like) are read only with +The `STRATA_PIPELINE_*` tuning and test variables (THETA, FORCE_MISS, SWITCH, LOG, TRACE, SPEC_DEPTH and the like) are read only with `STRATA_PIPELINE_DEBUG=1`. `--pipeline-windows` and `--adapt-async 1` combine: the engine turns the asynchronous tier off beside `--pipeline-windows 2` only when `STRATA_PIPELINE_ADAPT_ASYNC=0` is set. What switches either one off is printed once at start ("is off: ..."). `--remote-expert-opt` does something only with a helper cache diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 827dac39..5f33fdd4 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -268,6 +268,9 @@ private: float *Rin_ = nullptr, *R_ = nullptr, *emb_ = nullptr, *en_ = nullptr, *e2_ = nullptr, *hn_ = nullptr, *h2_ = nullptr; float *mixed_ = nullptr, *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *bo_ = nullptr; float* xn_ = nullptr; + /// gr_read's scratch of the drafter's own (not the session's ss.block.gr: the last stage's verifier uses that one, + /// and with --pipeline-windows a chain and that stage's window can run on the card at once) + strata::kernels::GrWorkspace own_gr_; uint8_t* xq_ = nullptr; float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr; float* attn_scratch_ = nullptr; diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 7d46389d..4edcea80 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -387,6 +387,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session logits_ = b.take(T * (uint64_t) g.n_expert); w_ = b.take(T * K); ids_ = b.take(T * K); shared_ = b.take(T * N); parts_ = b.take(T * K * N); y_ = b.take(T * N); sample_ = b.take(T * N); + { + const strata::kernels::GrShapes gsh{g.n_embd, g.hc, g.hc_lr}; + uint8_t* gr_mem = b.take(strata::kernels::gr_workspace_bytes(gsh)); + if (gr_mem != nullptr) strata::kernels::gr_workspace_init(gsh, gr_mem, own_gr_); + } hit_slot_ = b.take(T * K); hit_dst_ = b.take(T * K); hit_count_ = b.take(4); grp_ptr_ = b.take(T * K); grp_start_ = b.take(T * K + 1); grp_counts_ = b.take(4); @@ -964,7 +969,7 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) { for (int t = 0; t < T; ++t) gr_read(R_ + (size_t) t * HC * N, f32("hyper_connection_mixer.hc_norm.weight"), bf16("hyper_connection_mixer.input_mix_weight_down.weight"), - bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, ss.block.gr, + bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, own_gr_, sample_ + t * N, dummy_inj_, cs); } native_quantize_q8_1(sample_, xq_, (int) N, T, cs); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3248acb1..09485128 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -245,7 +245,8 @@ bool refill_blocking() { using Clock = std::chrono::steady_clock; // --pipeline-windows: every STRATA_PIPELINE_* test and tuning variable (THETA, FORCE_MISS, SWITCH, LOG, TRACE, DOOM_SKIP, -// LOOKUP_PON, PRESTAGE, AGREE, SNAP_OVERLAP) is read only with STRATA_PIPELINE_DEBUG=1; without it the defaults apply. +// LOOKUP_PON, PRESTAGE, AGREE, SNAP_OVERLAP, SPEC_DEPTH) is read only with STRATA_PIPELINE_DEBUG=1; without it the +// defaults apply. static const char* pipe_dbg_env(const char* name) { static const bool on = [] { const char* v = std::getenv("STRATA_PIPELINE_DEBUG"); return v != nullptr && v[0] != 0 && v[0] != '0'; }(); return on ? std::getenv(name) : nullptr; @@ -3187,7 +3188,9 @@ int main(int argc, char** argv) { const char* off = !o.serve ? "it needs --serve" : split_same ? "it needs each stage of the layer split on its own GPU" : !multi_gpu ? "it needs a layer split on two GPUs" - : split_devs.size() != 1 ? "it needs a layer split into exactly two stages" + : split_devs.empty() ? "it needs a layer split into two or more stages" + : split_devs.size() > 1 && o.pipeline_windows == 1 ? "--pipeline-windows 1 needs exactly two stages" + : split_devs.size() > 1 && o.adapt_async ? "not with --adapt-async on three or more stages" : o.mtp.empty() || o.spec < 2 ? "it needs the MTP drafter (--mtp, --spec)" : o.batch != 0 ? "not with --batch slots" : o.peer_device >= 1 ? "not with --peer-device" @@ -7077,26 +7080,30 @@ int main(int argc, char** argv) { const int n_stages = split_devs.empty() ? 1 : (int) split_at.size() + 1; // --pipeline-windows (decided where the split was): two verifiers per stage, one for the even windows and one // for the odd ones, sharing one stream of their card, and a hand-off per parity - so stage 0 can run window - // K+1 while stage 1 still reads window K's hand-off - const bool pipe = o.pipeline_windows > 0 && n_stages == 2 && !split_same && stages.size() == 1; + // K+1 while stage 1 still reads window K's hand-off. With more stages every stage but the last is a "front" + // stage: window K+1 follows window K through them one card behind, and only the last stage waits for K's verdict + const bool pipe = o.pipeline_windows > 0 && n_stages >= 2 && !split_same && (int) stages.size() == n_stages - 1; strata::core::Verifier ver_b; SplitDrive split_drive_b; - cudaStream_t pl_stream[2] = {nullptr, nullptr}; + std::vector pl_stream(pipe ? (size_t) n_stages : 0, nullptr); + // stage st's verifier of one parity (0: the even windows, 1: the odd ones) + auto stage_ver_p = [&](int st, int par) -> strata::core::Verifier& { + if (st == 0) return par == 0 ? ver : ver_b; + return par == 0 ? stages[(size_t) st - 1]->ver : stages[(size_t) st - 1]->ver_b; + }; if (pipe) { - bool ok_p = cudaStreamCreateWithFlags(&pl_stream[0], cudaStreamNonBlocking) == cudaSuccess; - { - const strata::core::OnDevice on(stages[0]->dev); - ok_p = ok_p && cudaStreamCreateWithFlags(&pl_stream[1], cudaStreamNonBlocking) == cudaSuccess; + bool ok_p = true; + ok_p = cudaStreamCreateWithFlags(&pl_stream[0], cudaStreamNonBlocking) == cudaSuccess; // the current card + for (int st = 1; st < n_stages && ok_p; ++st) { + const strata::core::OnDevice on(stages[(size_t) st - 1]->dev); + ok_p = cudaStreamCreateWithFlags(&pl_stream[(size_t) st], cudaStreamNonBlocking) == cudaSuccess; } if (!ok_p) { std::fprintf(stderr, "strata serve: --pipeline-windows: stream creation failed\n"); return 1; } - for (strata::core::Verifier* v : {&ver, &ver_b}) { - v->set_stream(pl_stream[0]); - v->set_always_publish(true); - } - for (strata::core::Verifier* v : {&stages[0]->ver, &stages[0]->ver_b}) { - v->set_stream(pl_stream[1]); - v->set_always_publish(true); - } + for (int st = 0; st < n_stages; ++st) + for (int par = 0; par < 2; ++par) { + stage_ver_p(st, par).set_stream(pl_stream[(size_t) st]); + stage_ver_p(st, par).set_always_publish(true); + } } if (n_stages > 1) { const size_t hb = (size_t) strata::kernels::kVerifyMaxT * @@ -7159,17 +7166,22 @@ int main(int argc, char** argv) { if (pipe) { const size_t hb = (size_t) strata::kernels::kVerifyMaxT * (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); - float *hh = nullptr, *hand_b = nullptr; - if (cudaHostAlloc((void**) &hh, hb, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || - cudaHostGetDevicePointer((void**) &hand_b, hh, 0) != cudaSuccess) { - std::fprintf(stderr, "strata serve: --pipeline-windows: the second hand-off allocation failed\n"); - return 1; + std::vector hand_b((size_t) n_stages - 1, nullptr); // the odd windows' hand-off per boundary + for (float*& h : hand_b) { + float* hh = nullptr; + if (cudaHostAlloc((void**) &hh, hb, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || + cudaHostGetDevicePointer((void**) &h, hh, 0) != cudaSuccess) { + std::fprintf(stderr, "strata serve: --pipeline-windows: the second hand-off allocation failed\n"); + return 1; + } + std::memset(hh, 0, hb); } - std::memset(hh, 0, hb); - GpuStage& gs = *stages[0]; - ver_b.set_stage(0, split_at[0], nullptr, hand_b); - gs.ver_b.set_stage(split_at[0], -1, hand_b, nullptr); - { + ver_b.set_stage(0, split_at[0], nullptr, hand_b[0]); + for (int st = 1; st < n_stages; ++st) { + GpuStage& gs = *stages[(size_t) st - 1]; + const bool last = st + 1 == n_stages; + gs.ver_b.set_stage(split_at[(size_t) st - 1], last ? -1 : split_at[(size_t) st], hand_b[(size_t) st - 1], + last ? nullptr : hand_b[(size_t) st]); const strata::core::OnDevice on(gs.dev); strata::core::VerifyHits vs; vs.d_res = gs.d_res; @@ -7179,13 +7191,13 @@ int main(int argc, char** argv) { vs.slot_off = gs.cache.slot_offsets(); vs.n_slots = gs.cache.slots(); if (!gs.ver_b.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, o.spec, err)) { - std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA%d (the later " - "card): %s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", - gs.dev, err.c_str()); + std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA%d (stage %d): %s " + "(raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", + gs.dev, st + 1, err.c_str()); return 1; } - if (cudaMalloc((void**) &pl_mtp_R, (size_t) strata::kernels::kVerifyMaxT * (size_t) (g.hc * g.n_embd) * - sizeof(float)) != cudaSuccess) { + if (last && cudaMalloc((void**) &pl_mtp_R, (size_t) strata::kernels::kVerifyMaxT * (size_t) (g.hc * g.n_embd) * + sizeof(float)) != cudaSuccess) { std::fprintf(stderr, "strata serve: --pipeline-windows: the drafter's row buffer does not fit\n"); return 1; } @@ -7195,7 +7207,8 @@ int main(int argc, char** argv) { "%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", err.c_str()); return 1; } - ver_b.set_next(&gs.ver_b, &split_drive_b); // the setters reach it; the pipeline never chains run/commit + // the setters reach the later stages; the pipeline never chains run/commit + for (int st = 0; st + 1 < n_stages; ++st) stage_ver_p(st, 1).set_next(&stage_ver_p(st + 1, 1), &split_drive_b); } ver.set_remote_expert_opt(remote_opt.get()); if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all @@ -7248,12 +7261,11 @@ int main(int argc, char** argv) { } if (pipe) { // the odd windows' pool routing: the same as the even ones', with their plans split_drive_b = split_drive; - split_drive_b.plan[0] = ver_b.plan_sink(); - split_drive_b.plan[1] = stages[0]->ver_b.plan_sink(); - stages[0]->ver_b.set_split(o.spec_split); - stages[0]->ver_b.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); - ver_b.set_split(o.spec_split); - ver_b.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + for (int st = 0; st < n_stages; ++st) { + split_drive_b.plan[st] = stage_ver_p(st, 1).plan_sink(); + stage_ver_p(st, 1).set_split(o.spec_split); + stage_ver_p(st, 1).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + } } // the pool the verify windows call: with a layer split, the wrapper that routes each layer to its stage const strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ? &drive_pool_split : &drive_pool_multi; @@ -7269,34 +7281,59 @@ int main(int argc, char** argv) { // Window W reads the state its snapshot must hold and no window writes it (only commits do), so it is copied // on a side stream while W runs, into the buffer of W's parity, and only W's speculative commit waits for it // (STRATA_PIPELINE_SNAP_OVERLAP=0: one buffer, copied on the critical path). - const size_t pl_snap_bytes = pipe ? gdn_snapshot_bytes(ss) : 0; - float* pl_snap2[2] = {nullptr, nullptr}; - cudaStream_t pl_snap_stream = nullptr; - cudaEvent_t pl_snap_pre[2] = {nullptr, nullptr}, pl_snap_ev[2] = {nullptr, nullptr}; - bool pl_snap_overlap = false; + // With three or more stages every front stage (all but the last) runs speculative windows, so each keeps its own + // pair of snapshots, side stream and events. + struct PlSnap { + int dev = 0; + size_t bytes = 0; + void* state = nullptr; // the stage's GDN state (its session's) + float* buf[2] = {nullptr, nullptr}; + cudaStream_t side = nullptr; + cudaEvent_t pre[2] = {nullptr, nullptr}, ev[2] = {nullptr, nullptr}; + }; + const int pl_nf = pipe ? n_stages - 1 : 0; // the front stages + std::vector pl_snaps((size_t) pl_nf); + bool pl_snap_ok = false, pl_snap_overlap = false; if (pipe && o.pipeline_windows >= 2) { - if (cudaMalloc((void**) &pl_snap2[0], pl_snap_bytes) != cudaSuccess) { - std::fprintf(stderr, "strata serve: --pipeline-windows 2: the GDN snapshot (%.1f MiB) does not fit; the " - "decode stays serial\n", (double) pl_snap_bytes / 1048576.0); - cudaGetLastError(); - pl_snap2[0] = nullptr; - } else if ([] { const char* v = pipe_dbg_env("STRATA_PIPELINE_SNAP_OVERLAP"); return v == nullptr || std::atoi(v) != 0; }()) { - pl_snap_overlap = cudaMalloc((void**) &pl_snap2[1], pl_snap_bytes) == cudaSuccess && - cudaStreamCreateWithFlags(&pl_snap_stream, cudaStreamNonBlocking) == cudaSuccess; - for (int i = 0; i < 2 && pl_snap_overlap; ++i) - pl_snap_overlap = cudaEventCreateWithFlags(&pl_snap_pre[i], cudaEventDisableTiming) == cudaSuccess && - cudaEventCreateWithFlags(&pl_snap_ev[i], cudaEventDisableTiming) == cudaSuccess; - if (!pl_snap_overlap) cudaGetLastError(); + pl_snap_ok = true; + pl_snap_overlap = [] { const char* v = pipe_dbg_env("STRATA_PIPELINE_SNAP_OVERLAP"); return v == nullptr || std::atoi(v) != 0; }(); + for (int st = 0; st < pl_nf && pl_snap_ok; ++st) { + PlSnap& sn = pl_snaps[(size_t) st]; + strata::core::SessionState& sst = st == 0 ? ss : stages[(size_t) st - 1]->ss; + sn.dev = stage_ver_p(st, 0).device(); + sn.bytes = gdn_snapshot_bytes(sst); + sn.state = (void*) sst.gdn_state; + const strata::core::OnDevice on(sn.dev); + if (cudaMalloc((void**) &sn.buf[0], sn.bytes) != cudaSuccess) { + std::fprintf(stderr, "strata serve: --pipeline-windows 2: the GDN snapshot of stage %d (%.1f MiB) does " + "not fit; the decode stays serial\n", st + 1, (double) sn.bytes / 1048576.0); + cudaGetLastError(); + sn.buf[0] = nullptr; + pl_snap_ok = false; + break; + } + if (pl_snap_overlap) { + bool ok_s = cudaMalloc((void**) &sn.buf[1], sn.bytes) == cudaSuccess && + cudaStreamCreateWithFlags(&sn.side, cudaStreamNonBlocking) == cudaSuccess; + for (int i = 0; i < 2 && ok_s; ++i) + ok_s = cudaEventCreateWithFlags(&sn.pre[i], cudaEventDisableTiming) == cudaSuccess && + cudaEventCreateWithFlags(&sn.ev[i], cudaEventDisableTiming) == cudaSuccess; + if (!ok_s) { + cudaGetLastError(); + pl_snap_overlap = false; + } + } } } if (pipe) - std::fprintf(stderr, "strata serve: --pipeline-windows %d: two verifiers per stage, the stages overlap across " - "windows%s\n", o.pipeline_windows, - pl_snap2[0] == nullptr ? "" : pl_snap_overlap ? " (decode too; the GDN snapshots beside the window)" - : " (decode too; the GDN snapshot on the critical path)"); - // the verifiers by [stage][parity], their pool routing, and the drafter's events (in a pipelined prompt read, a - // stage-1 window waits until the drafter has read the rows of the same parity's previous window) - strata::core::Verifier* PV[2][2] = {{&ver, &ver_b}, {pipe ? &stages[0]->ver : nullptr, pipe ? &stages[0]->ver_b : nullptr}}; + std::fprintf(stderr, "strata serve: --pipeline-windows %d: two verifiers per stage, %d stages overlap across " + "windows%s\n", o.pipeline_windows, n_stages, + !pl_snap_ok ? "" : pl_snap_overlap ? " (decode too; the GDN snapshots beside the window)" + : " (decode too; the GDN snapshot on the critical path)"); + // the verifiers by [stage][parity] - the first stage and the LAST (stage 1 of a two-stage split; the decode loop + // reaches the middle stages through stage_ver_p) - their pool routing, and the drafter's events (in a pipelined + // prompt read, a stage-1 window waits until the drafter has read the rows of the same parity's previous window) + strata::core::Verifier* PV[2][2] = {{&ver, &ver_b}, {pipe ? &stages.back()->ver : nullptr, pipe ? &stages.back()->ver_b : nullptr}}; SplitDrive* PSD[2] = {&split_drive, &split_drive_b}; cudaEvent_t pl_mtp_ev[2] = {nullptr, nullptr}; bool pl_mtp_live[2] = {false, false}; @@ -7304,13 +7341,14 @@ int main(int argc, char** argv) { // every graph captured and the drafter's prompt path sized while nothing is in flight (a capture syncs its stream) auto pl_prepare = [&](std::string& e) -> bool { if (pl_prepared) return true; - for (int st = 0; st < 2; ++st) + for (int st = 0; st < n_stages; ++st) for (int par = 0; par < 2; ++par) { - const strata::core::OnDevice on(PV[st][par]->device()); - if (!PV[st][par]->capture_all(e)) return false; + strata::core::Verifier& v = stage_ver_p(st, par); + const strata::core::OnDevice on(v.device()); + if (!v.capture_all(e)) return false; } if (!mtp.prepare_prefill(e)) return false; - if (o.pipeline_windows >= 2 && pl_snap2[0] != nullptr && !mtp.prepare_chain(e)) return false; + if (o.pipeline_windows >= 2 && pl_snap_ok && !mtp.prepare_chain(e)) return false; const strata::core::OnDevice on(mtp.device()); for (cudaEvent_t& ev : pl_mtp_ev) if (ev == nullptr && cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) { @@ -7328,9 +7366,9 @@ int main(int argc, char** argv) { std::string e2; for (int round = 0; round < 10000000; ++round) { bool any = false; - for (int st = 0; st < 2; ++st) + for (int st = 0; st < n_stages && pipe; ++st) for (int par = 0; par < 2; ++par) { - strata::core::Verifier& v = *PV[st][par]; + strata::core::Verifier& v = stage_ver_p(st, par); if (!v.in_flight()) continue; any = true; if (v.service(&drive_pool_split, PSD[par], e2) < 0) return; @@ -7339,9 +7377,9 @@ int main(int argc, char** argv) { } if (!any) break; } - for (int st = 0; st < 2; ++st) { - const strata::core::OnDevice on(PV[st][0]->device()); - cudaStreamSynchronize(PV[st][0]->stream()); + for (int st = 0; st < n_stages && pipe; ++st) { + const strata::core::OnDevice on(stage_ver_p(st, 0).device()); + cudaStreamSynchronize(stage_ver_p(st, 0).stream()); } const strata::core::OnDevice on(mtp.device()); cudaStreamSynchronize(mtp.stream()); @@ -9980,7 +10018,8 @@ int main(int argc, char** argv) { // tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool { // (STRATA_LOGPOS reads every window's logits: the serial loop) - if (pipe && pl_pw >= 1 && std::getenv("STRATA_LOGPOS") == nullptr) return read_windows_pl(a, b, e); + // the pipelined prompt read stays two-stage (three or more stages read serially; only the decode overlaps) + if (pipe && n_stages == 2 && pl_pw >= 1 && std::getenv("STRATA_LOGPOS") == nullptr) return read_windows_pl(a, b, e); strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched" // every token is committed and the picks are discarded: no head sampling (see set_head_sampling) struct NoHeadSampling { @@ -10482,7 +10521,7 @@ int main(int argc, char** argv) { // and a window row computes what it would in any other window, so every emitted token is the serial loop's // (with STRATA_IQ_MT_MIN=1 bit for bit; sampled requests with the same Philox draw per position). bool pl_ran = false; - const bool pl_want = pipe && pl_pw >= 2 && pl_snap2[0] != nullptr; + const bool pl_want = pipe && pl_pw >= 2 && pl_snap_ok; const char* pl_serial = !pl_want ? nullptr : hist_n > 0 ? "repetition penalties (penalty_last_n)" : mtp.coupled() ? "coupled draft sampling" : nullptr; @@ -10504,31 +10543,36 @@ int main(int argc, char** argv) { int32_t tok[8] = {}; float prob[8] = {}; // prob[i]: the drafter's probability of tok[i + 1] float p_on = 0.0f; // the chain's estimate that the window before is accepted whole, tok[0] its bonus - bool ready = false, launched = false, finished = false, committed = false, s1 = false, s1_done = false; + // launched: on stage 0; finished: done on every front stage (all but the last); s1: on the last + bool ready = false, launched = false, finished = false, s1 = false, s1_done = false; + int fr = 0; // front stages done + bool fl = false; // in flight on front stage `fr` + uint32_t com = 0; // the front stages this window was committed on speculatively (bit per stage) bool spec = false; // launched speculatively (behind the window before, ahead of its verdict) bool made = false; // made from a chain (its outcome can be scored even when the gate held it) bool sfx = false; // a lookup window (the suffix drafter's drafts) int sfx_match = 0; }; - auto V0 = [&](const PW& w) -> strata::core::Verifier& { return *PV[0][w.seq & 1]; }; + // front stage `st`'s verifier of w's parity, and the last stage's + auto VF = [&](int st, const PW& w) -> strata::core::Verifier& { return stage_ver_p(st, w.seq & 1); }; auto V1 = [&](const PW& w) -> strata::core::Verifier& { return *PV[1][w.seq & 1]; }; auto SDf = [&](const PW& w) { return (void*) PSD[w.seq & 1]; }; const float theta = pl_theta; const int force_miss = pl_force_miss; static const bool pl_log = pipe_dbg_env("STRATA_PIPELINE_LOG") != nullptr; - const int dev0 = PV[0][0]->device(); - cudaStream_t s0 = PV[0][0]->stream(); - // the snapshot of the GDN state window `seq` reads (overlapped: before its launch, on the side stream) - auto snap_take = [&](int seq) -> bool { + // the snapshot of the GDN state window `seq` reads on front stage `st` (overlapped: before its launch + // there, on the stage's side stream) + auto snap_take = [&](int st, int seq) -> bool { if (!pl_snap_overlap) return true; - const strata::core::OnDevice on(dev0); + PlSnap& sn = pl_snaps[(size_t) st]; + const strata::core::OnDevice on(sn.dev); + cudaStream_t cs = pl_stream[(size_t) st]; const int q = seq & 1; - return cudaEventRecord(pl_snap_pre[q], s0) == cudaSuccess && - cudaStreamWaitEvent(pl_snap_stream, pl_snap_pre[q], 0) == cudaSuccess && - cudaMemcpyAsync(pl_snap2[q], ss.gdn_state, pl_snap_bytes, cudaMemcpyDeviceToDevice, - pl_snap_stream) == cudaSuccess && - cudaEventRecord(pl_snap_ev[q], pl_snap_stream) == cudaSuccess && - (cudaStreamQuery(pl_snap_stream), true); + return cudaEventRecord(sn.pre[q], cs) == cudaSuccess && + cudaStreamWaitEvent(sn.side, sn.pre[q], 0) == cudaSuccess && + cudaMemcpyAsync(sn.buf[q], sn.state, sn.bytes, cudaMemcpyDeviceToDevice, sn.side) == cudaSuccess && + cudaEventRecord(sn.ev[q], sn.side) == cudaSuccess && + (cudaStreamQuery(sn.side), true); }; PW A, B, D; // A: the oldest window not verified; B: the next; D: a wrong speculative window bool doomed = false; // D still runs: when it finishes, stage 0 goes back to undo_w's real commit @@ -10582,9 +10626,9 @@ int main(int argc, char** argv) { std::chrono::duration(Clock::now() - pl_tr0).count(), ev, seq, x0, x1); pl_trace += b; }; - auto pump0 = [&](PW& w) -> bool { - if (!w.launched || w.finished) return true; - strata::core::Verifier& v = V0(w); + auto pump0 = [&](PW& w) -> bool { // w's front stage in flight + if (!w.fl) return true; + strata::core::Verifier& v = VF(w.fr, w); // a doomed window (its guess was wrong) gets empty plans: no expert work on the CPU or the GPU for // its remaining layers, so it frees stage 0 and the pool sooner (its rows are discarded and the // undo restores everything it wrote). STRATA_PIPELINE_DOOM_SKIP=0: served in full. @@ -10593,8 +10637,9 @@ int main(int argc, char** argv) { if (v.service(skip ? nullptr : &drive_pool_split, SDf(w), err) < 0) return false; if (v.done(err)) { if (!v.pl_finish(nullptr, err)) return false; - w.finished = true; - tre("F0", w.seq, w.T, w.spec); + w.fl = false; + if (++w.fr == pl_nf) w.finished = true; + tre("F0", w.seq, w.fr, w.spec); } return err.empty(); }; @@ -10625,29 +10670,23 @@ int main(int argc, char** argv) { B.made = true; }; // events after all the work both stages' streams hold now, and whether they have passed - cudaEvent_t fence_ev[2] = {nullptr, nullptr}, exch_ev[2] = {nullptr, nullptr}; - { - const strata::core::OnDevice on0(dev0); - cudaEventCreateWithFlags(&fence_ev[0], cudaEventDisableTiming); - cudaEventCreateWithFlags(&exch_ev[0], cudaEventDisableTiming); + std::vector fence_ev((size_t) n_stages, nullptr), exch_ev((size_t) n_stages, nullptr); + for (int st = 0; st < n_stages; ++st) { + const strata::core::OnDevice on(stage_ver_p(st, 0).device()); + cudaEventCreateWithFlags(&fence_ev[(size_t) st], cudaEventDisableTiming); + cudaEventCreateWithFlags(&exch_ev[(size_t) st], cudaEventDisableTiming); } - { - const strata::core::OnDevice on1(stages[0]->dev); - cudaEventCreateWithFlags(&fence_ev[1], cudaEventDisableTiming); - cudaEventCreateWithFlags(&exch_ev[1], cudaEventDisableTiming); - } - auto stage_record = [&](cudaEvent_t* ev) { - { - const strata::core::OnDevice on(dev0); - cudaEventRecord(ev[0], s0); - (void) cudaStreamQuery(s0); + auto stage_record = [&](std::vector& ev) { // after the work every stage's stream holds now + for (int st = 0; st < n_stages; ++st) { + const strata::core::OnDevice on(stage_ver_p(st, 0).device()); + cudaEventRecord(ev[(size_t) st], pl_stream[(size_t) st]); + (void) cudaStreamQuery(pl_stream[(size_t) st]); } - const strata::core::OnDevice on(stages[0]->dev); - cudaEventRecord(ev[1], PV[1][0]->stream()); - (void) cudaStreamQuery(PV[1][0]->stream()); }; - auto stage_passed = [&](cudaEvent_t* ev) { - return cudaEventQuery(ev[0]) != cudaErrorNotReady && cudaEventQuery(ev[1]) != cudaErrorNotReady; + auto stage_passed = [&](std::vector& ev) { + for (cudaEvent_t e : ev) + if (cudaEventQuery(e) == cudaErrorNotReady) return false; + return true; }; // adapt()'s fence, on the tier's thread: it waits on the HOST. A device-side wait (the refill streams // waiting for the stages' events) would queue copies behind windows that need this loop, beside it. @@ -10750,7 +10789,7 @@ int main(int argc, char** argv) { for (int par = 0; par < 2; ++par) g_pl_diag.v[st][par] = PV[st][par]; strata::core::diag_pipeline_fn().store(&pl_diag_print); auto pw_bits = [](const PW& w) { - return (w.ready ? 1 : 0) | (w.launched ? 2 : 0) | (w.finished ? 4 : 0) | (w.committed ? 8 : 0) | + return (w.ready ? 1 : 0) | (w.launched ? 2 : 0) | (w.finished ? 4 : 0) | (w.com != 0 ? 8 : 0) | (w.s1 ? 16 : 0) | (w.s1_done ? 32 : 0); }; // per window class (0: fresh, 1: run speculatively ahead of its predecessor's verdict): the time from @@ -10798,17 +10837,24 @@ int main(int argc, char** argv) { } else if (!err.empty()) return die(err); } if (drive.d.failed) return die(drive.d.fail ? drive.d.fail : "the expert pool failed"); - // ---- a wrong speculative window has finished: stage 0 back to the verified window's real commit - if (doomed && D.finished) { - { - const strata::core::OnDevice on(dev0); - if (cudaMemcpyAsync(ss.gdn_state, pl_snap2[pl_snap_overlap ? (undo_w.seq & 1) : 0], - pl_snap_bytes, cudaMemcpyDeviceToDevice, s0) != cudaSuccess) - return die("restoring the GDN snapshot failed"); + // ---- a wrong speculative window has stopped (it is launched on no further stage once doomed): + // every front stage it ran on back to the verified window's real commit + if (doomed && !D.fl) { + for (int st = 0; st < pl_nf; ++st) { + if ((undo_w.com & (1u << st)) == 0) continue; + PlSnap& sn = pl_snaps[(size_t) st]; + { + const strata::core::OnDevice on(sn.dev); + if (cudaMemcpyAsync(sn.state, sn.buf[pl_snap_overlap ? (undo_w.seq & 1) : 0], sn.bytes, + cudaMemcpyDeviceToDevice, pl_stream[(size_t) st]) != cudaSuccess) + return die("restoring the GDN snapshot failed"); + } + if (st == 0) { + ss.ple_prev[0] = undo_ple[0]; + ss.ple_prev[1] = undo_ple[1]; + } + if (!VF(st, undo_w).pl_commit_async(undo_keep, err)) return die(err); } - ss.ple_prev[0] = undo_ple[0]; - ss.ple_prev[1] = undo_ple[1]; - if (!V0(undo_w).pl_commit_async(undo_keep, err)) return die(err); doomed = false; ++pl_undo; tre("U", undo_w.seq, undo_keep); @@ -10883,10 +10929,10 @@ int main(int argc, char** argv) { // stage B now (its PLE rows from the tokens before it as they will be once A is // committed whole), so its launch behind A is only the graph launch (never while a // rollback is pending: B's verifier is the one the undo commit reads) - if (B.ready && B.p_on >= theta && pl_prestage && !V0(B).in_flight() && !doomed) { + if (B.ready && B.p_on >= theta && pl_prestage && !VF(0, B).in_flight() && !doomed) { int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; for (int i = 0; i < A.T; ++i) { prev[0] = prev[1]; prev[1] = A.tok[i]; } - if (!V0(B).prestage(B.T, B.tok, B.p, prev, err)) return die(err); + if (!VF(0, B).prestage(B.T, B.tok, B.p, prev, err)) return die(err); } b_done = true; tre("CD", A.seq, chain_kind, (int) (1000.0f * B.p_on)); @@ -10897,42 +10943,59 @@ int main(int argc, char** argv) { } if (r == 1) chain_kind = 0; } - // ---- stage 0: A (never while a wrong window still holds stage 0's state) - if (A.ready && !A.launched && !doomed) { - if (A.p + A.T > o.max_context) { ending = true; continue; } - if (ajob) a_gap(0); // --adapt-async: stage 0 is idle until this launch - if (!snap_take(A.seq)) return die("the GDN snapshot failed"); - if (!V0(A).pl_launch(A.T, A.tok, A.p, err)) return die(err); - A.launched = true; - tre("L0", A.seq, A.T, 0); + // ---- the front stages: A on its next one (never while a wrong window still holds a front stage's + // state) + if (A.ready && !A.fl && A.fr < pl_nf && !doomed) { + const int st = A.fr; + if (st == 0 && A.p + A.T > o.max_context) { ending = true; continue; } + if (ajob && st == 0) a_gap(0); // --adapt-async: stage 0 is idle until this launch + if (!snap_take(st, A.seq)) return die("the GDN snapshot failed"); + if (!VF(st, A).pl_launch(A.T, A.tok, A.p, err)) return die(err); + A.fl = true; + if (st == 0) A.launched = true; + tre("L0", A.seq, A.T, st); } - // ---- stage 0: B, speculatively, right behind A - if (B.ready && !B.launched && A.finished && !A.committed && !doomed) { - if (B.p_on >= theta && B.p + B.T <= o.max_context) { - if (ajob) a_gap(0); // --adapt-async: stage 0 is idle until this launch + // ---- the front stages: B, speculatively, one stage behind A. On each stage A is committed there + // (its snapshot taken first) right before B launches, as stage 0 alone did with two stages + // STRATA_PIPELINE_SPEC_DEPTH=k (debug): B runs speculatively on the first k front stages only + static const int pl_spec_depth = [] { + const char* v = pipe_dbg_env("STRATA_PIPELINE_SPEC_DEPTH"); + return v ? std::max(1, std::atoi(v)) : 1 << 20; + }(); + if (B.ready && !B.fl && B.fr < pl_nf && B.fr < pl_spec_depth && A.fr > B.fr && !doomed) { + const int st = B.fr; + if (st > 0 || (B.p_on >= theta && B.p + B.T <= o.max_context)) { + if (ajob && st == 0) a_gap(0); // --adapt-async: stage 0 is idle until this launch + PlSnap& sn = pl_snaps[(size_t) st]; + cudaStream_t cs = pl_stream[(size_t) st]; { - const strata::core::OnDevice on(dev0); - if (pl_snap_overlap ? cudaStreamWaitEvent(s0, pl_snap_ev[A.seq & 1], 0) != cudaSuccess - : cudaMemcpyAsync(pl_snap2[0], ss.gdn_state, pl_snap_bytes, - cudaMemcpyDeviceToDevice, s0) != cudaSuccess) + const strata::core::OnDevice on(sn.dev); + if (pl_snap_overlap ? cudaStreamWaitEvent(cs, sn.ev[A.seq & 1], 0) != cudaSuccess + : cudaMemcpyAsync(sn.buf[0], sn.state, sn.bytes, + cudaMemcpyDeviceToDevice, cs) != cudaSuccess) return die("the GDN snapshot failed"); } - undo_ple[0] = ss.ple_prev[0]; - undo_ple[1] = ss.ple_prev[1]; - if (!V0(A).pl_commit_async(A.T, err) || !snap_take(B.seq) || - !V0(B).pl_launch(B.T, B.tok, B.p, err)) + if (st == 0) { + undo_ple[0] = ss.ple_prev[0]; + undo_ple[1] = ss.ple_prev[1]; + } + if (!VF(st, A).pl_commit_async(A.T, err) || !snap_take(st, B.seq) || + !VF(st, B).pl_launch(B.T, B.tok, B.p, err)) return die(err.empty() ? std::string("the GDN snapshot failed") : err); - A.committed = true; - B.launched = true; - B.spec = true; - tre("L0", B.seq, B.T, 1); - ++pl_spec; + A.com |= 1u << st; + B.fl = true; + if (st == 0) { + B.launched = true; + B.spec = true; + ++pl_spec; + } + tre("L0", B.seq, B.T, 10 + st); } else { B.ready = false; // not worth it: A's verdict decides the next window ++pl_gate; } } - // ---- stage 1: A, once its stage 0 is done + // ---- the last stage: A, once every front stage is done if (A.finished && !A.s1) { if (chain_kind == 1 && !B.ready) ++pl_late; // stage 0 idles until the chain has B if (ajob) a_gap(1); // --adapt-async: stage 1 is idle until this launch @@ -10990,8 +11053,13 @@ int main(int argc, char** argv) { last_verdict = now; } if (pl_log) - std::fprintf(stderr, "strata pipeline: verdict p=%lld T=%d a=%d B %s%s\n", (long long) A.p, A.T, a, - B.launched ? "launched" : B.ready ? "ready" : "none", on ? " ON" : ""); + std::fprintf(stderr, "strata pipeline: verdict p=%lld T=%d a=%d B %s%s (B front %d%s, A com %x) out", + (long long) A.p, A.T, a, B.launched ? "launched" : B.ready ? "ready" : "none", + on ? " ON" : "", B.fr, B.fl ? "+" : "", A.com); + if (pl_log) { + for (int i = 0; i <= a; ++i) std::fprintf(stderr, " %d", (int) outp[(size_t) i]); + std::fprintf(stderr, "\n"); + } x = outp[(size_t) a]; p = A.p + a + 1; if (!last && !ajob && !pl_adapt()) return die("an adaptive refill failed"); @@ -11006,16 +11074,22 @@ int main(int argc, char** argv) { tre("CL", A.seq, 1); early_used = false; b_done = false; + // A accepted whole: its commit on the front stages B has not reached yet (B, now A, runs there + // after it) + for (int st = 0; st < pl_nf; ++st) + if ((A.com & (1u << st)) == 0 && !VF(st, A).pl_commit_async(A.T, err)) return die(err); A = B; B = PW{}; } else { - if (B.launched) { // a wrong guess (or the end): undo once it has finished + // the front stages B never ran on take A's real commit now; those it did run on are undone + // (snapshot restored, the commit replayed) once it has stopped + for (int st = 0; st < pl_nf; ++st) + if ((A.com & (1u << st)) == 0 && !VF(st, A).pl_commit_async(a + 1, err)) return die(err); + if (B.launched) { // a wrong guess (or the end): undo once it has stopped doomed = true; D = B; undo_w = A; undo_keep = a + 1; - } else if (!A.committed) { - if (!V0(A).pl_commit_async(a + 1, err)) return die(err); } // B is D now (or dropped): never pump it twice (whichever copy saw the window complete first // would finish it, and the other would wait for it forever) @@ -11059,8 +11133,7 @@ int main(int argc, char** argv) { } } // the odd windows' counters and GPU profiles into the verifiers that report them - PV[0][0]->absorb_stats(*PV[0][1]); - PV[1][0]->absorb_stats(*PV[1][1]); + for (int st = 0; st < n_stages; ++st) stage_ver_p(st, 0).absorb_stats(stage_ver_p(st, 1)); if (!pl_adapt_ok) { std::printf("ERR an adaptive refill failed\n"); return 1; From 48f2c47d544fe26111863fea1abbf46c514a52b1 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Tue, 6 Oct 2026 17:15:03 -0400 Subject: [PATCH 02/19] batch-mtp: work with a layer split (slot drafters on the last stage's GPU, grouped slot rows through every stage) - generate.cpp: --batch-mtp accepted with a layer split on separate GPUs (refused with --batch-groups); slot drafters load from the last stage's slot sessions under the last stage's device guard and bind to its weights/head; their residual buffers, row copy (async on the drafter's stream) and draft-KV copies run on the drafter's device; every stage verifier gets the 8-row window size and the batch graph limit; slot-drafter logits are not charged to CUDA0. - verify.cpp: stage_batch's layout rules move to include/strata/core/batch_rows.hpp (CPU test batch_rows_test); grouped rows are allowed on a stage that hands rows on, the hand-off bound is kVerifyMaxT rows. - docs/BATCHING.md, --batch-mtp help text. --- CMakeLists.txt | 4 ++ docs/BATCHING.md | 25 +++++++--- include/strata/core/batch_rows.hpp | 30 ++++++++++++ src/core/verify.cpp | 28 +++-------- src/program/generate.cpp | 65 +++++++++++++++++++------ tests/core/batch_rows_test.cpp | 78 ++++++++++++++++++++++++++++++ 6 files changed, 187 insertions(+), 43 deletions(-) create mode 100644 include/strata/core/batch_rows.hpp create mode 100644 tests/core/batch_rows_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f54244b0..4ed15426 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1130,6 +1130,10 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp) target_include_directories(bf16_bits_test PRIVATE include) add_test(NAME bf16_bits_test COMMAND bf16_bits_test) + # the batch window's row layout (a slot's group of proposed rows, the layer split's hand-off capacity; header-only, CPU) + add_executable(batch_rows_test tests/core/batch_rows_test.cpp) + target_include_directories(batch_rows_test PRIVATE include) + add_test(NAME batch_rows_test COMMAND batch_rows_test) endif() add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 85beb7b0..4f706617 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -19,12 +19,22 @@ asked, with a note when it is more than setup would recommend. "parallel": 2 ``` -On one GPU with MTP (`--mtp` and `--spec`), `--batch-mtp` (in the config's `args`, or `STRATA_BATCH_MTP=1` in the -server's environment) lets each batch slot verify one MTP proposal per window. It is opt-in; without it the batch -behaviour described below is exactly the one without MTP. It needs VRAM per slot for the draft state and buffers, so -check the engine's free-memory log before using it on a smaller card. If it cannot run (one slot, no `--mtp`, a layer -split or helper GPU) the engine says so and batches as usual. RTX PRO 5000 owners measured +31% to +39% total -throughput with 2 to 4 clients (a RX R9700 run too); it has not been validated with a layer split. +With MTP (`--mtp` and `--spec`), `--batch-mtp` (in the config's `args`, or `STRATA_BATCH_MTP=1` in the server's +environment) lets each batch slot verify one MTP proposal per window. It is opt-in; without it the batch behaviour +described below is exactly the one without MTP. It needs VRAM per slot for the draft state and buffers, so check the +engine's free-memory log before using it on a smaller card. If it cannot run (one slot, no `--mtp`, `--batch-groups` +with a layer split, a layer split on one GPU) the engine says so and batches as usual. RTX PRO 5000 owners measured ++31% to +39% total throughput with 2 to 4 clients on one GPU (a RX R9700 run too). + +**With a layer split** (e.g. `"layer_split": "24"` on two GPUs, `"parallel": 2`, `--spec 4 --mtp ...`) it works the +same way, with the slot drafters on the **last stage's GPU** (where the solo drafter and the head are): each slot gets a +drafter that shares the solo drafter's weights and owns only its K/V ring and buffers (the engine logs `--batch-mtp: N +slot drafters on CUDAk (X MiB ... each)` at start; the K/V ring of each also keeps a pinned-RAM copy, as the solo +drafter's does). A window carries two rows per active slot (its token and its proposal) through every stage, so at most +four slots are in one window; more slots (`--batch` up to what fits) rotate through. The split keeps `--kv-pool-tokens` +and `--kv-resident` as without `--batch-mtp`. Not supported with a split: `--batch-groups` (pipelined slot groups; the +engine turns `--batch-mtp` off and says so). The code does not depend on the number of stages, but the two-stage split +is the one it was written for. With a layer split, the engine options go into the config's `args`: @@ -124,7 +134,8 @@ counter-based draw (Philox(seed, position)). - By default, batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo path keeps its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone). -- Grouped MTP currently uses one proposal per slot and requires one GPU; it does not support a layer split. +- `--batch-mtp` uses one proposal per slot. With a layer split it needs each stage on its own GPU and does not combine + with `--batch-groups` (pipelined slot groups). - Repetition / frequency / presence penalties are not applied in batch windows. - A prompt shorter than one chunk is read in one piece (the slots wait for it); a read gives way only at a chunk boundary, and not for pictures. diff --git a/include/strata/core/batch_rows.hpp b/include/strata/core/batch_rows.hpp new file mode 100644 index 00000000..f51b233b --- /dev/null +++ b/include/strata/core/batch_rows.hpp @@ -0,0 +1,30 @@ +#pragma once +// The row layout of a batch window (Verifier::stage_batch), as pure logic so a CPU test can pin it down. +// +// A batch window carries S rows, each a token of one slot. A slot owns one row (plain --batch) or a contiguous group +// of rows at consecutive positions (--batch-mtp: the slot's current token and its MTP proposal; a layer split's every +// stage sees the same layout). The rows travel between the stages of a layer split in hand-off buffers of +// `handoff_rows` rows, the window's group starting at row `hbase`. + +#include + +namespace strata::core { + +/// nullptr when the layout is valid, else why not. `rows[t]` is row t's slot, `pos[t]` its position. `n_slots`: the +/// slots the verifier holds; `max_t`: its window capacity; `via_handoff`: the stage hands its rows on or takes them from +/// another stage (a layer split), so [hbase, hbase + S) must fit the `handoff_rows` rows of the hand-off buffers. +inline const char* batch_rows_error(const int* rows, int S, const int64_t* pos, int n_slots, int max_t, int hbase, + bool via_handoff, int handoff_rows) { + if (S < 1 || S > max_t || hbase < 0 || (via_handoff && hbase + S > handoff_rows)) + return "verify: batch rows out of range (init_slots)"; + for (int t = 0; t < S; ++t) { + if (rows[t] < 0 || rows[t] >= n_slots) return "verify: a batch row's slot is out of range"; + for (int u = 0; u < t - 1; ++u) + if (rows[u] == rows[t] && rows[t - 1] != rows[t]) return "verify: a slot's proposed rows must be contiguous"; + if (t > 0 && rows[t] == rows[t - 1] && pos[t] != pos[t - 1] + 1) + return "verify: proposed rows must have consecutive positions"; + } + return nullptr; +} + +} // namespace strata::core diff --git a/src/core/verify.cpp b/src/core/verify.cpp index bc84c361..8f70e022 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1,4 +1,5 @@ // src/core/verify.cpp - see include/strata/core/verify.hpp. +#include "strata/core/batch_rows.hpp" #include "strata/core/verify.hpp" #include "strata/core/remote_expert_opt.hpp" #include "strata/core/dma_batch.hpp" @@ -2552,30 +2553,13 @@ bool Verifier::instantiate_evicting(cudaGraphExec_t& ex, cudaGraph_t graph, cons bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, std::string& err) { using namespace strata::kernels; - if (S < 1 || S > max_t_ || hbase < 0 || - (next_ != nullptr && hbase + S > (int) slots_.size())) { - err = "verify: batch rows out of range (init_slots)"; + // the row layout: a slot may own a contiguous group of rows (--batch-mtp), also across the stages of a layer split, + // whose hand-off buffers hold kVerifyMaxT rows (a stage that hands rows on or takes them) + if (const char* why = batch_rows_error(rows, S, pos, (int) slots_.size(), max_t_, hbase, + next_ != nullptr || lb_ > 0, kVerifyMaxT)) { + err = why; return false; } - for (int t = 0; t < S; ++t) { - if (rows[t] < 0 || rows[t] >= (int) slots_.size()) { - err = "verify: a batch row's slot is out of range"; - return false; - } - for (int u = 0; u < t - 1; ++u) - if (rows[u] == rows[t] && rows[t - 1] != rows[t]) { - err = "verify: a slot's proposed rows must be contiguous"; - return false; - } - if (t > 0 && rows[t] == rows[t - 1] && pos[t] != pos[t - 1] + 1) { - err = "verify: proposed rows must have consecutive positions"; - return false; - } - if (t > 0 && rows[t] == rows[t - 1] && next_ != nullptr) { - err = "verify: grouped slot rows do not support a layer split yet"; - return false; - } - } if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } const ModelGeometry& g = *g_; for (int t = 0; t < S; ++t) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 09485128..f6046aa2 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -770,8 +770,9 @@ void usage() { " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8\n" " normally; --batch-mtp waves more through eight-row windows),\n" " each slot with its own session (VRAM like the main one); docs/BATCHING.md\n" - " --batch-mtp --batch (opt-in, one GPU, needs --mtp and --spec): each slot also verifies one MTP\n" - " proposal per window (STRATA_BATCH_MTP=1 does the same); needs VRAM per slot\n" + " --batch-mtp --batch (opt-in, needs --mtp and --spec): each slot also verifies one MTP proposal per\n" + " window (STRATA_BATCH_MTP=1 does the same); works on one GPU and on a layer split (the\n" + " slot drafters sit on the last stage's GPU; not with --batch-groups); needs VRAM per slot\n" " --batch-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n" " --pipeline-windows N --serve with a layer split on two GPUs (opt-in): one conversation's verify windows\n" " with the GPUs overlapped - 1 = the prompt's short reads, 2 = decode as well\n" @@ -4114,12 +4115,17 @@ int main(int argc, char** argv) { // engine still starts and serves one request at a time. // --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): a slot also verifies one MTP proposal per window. Recommend, never // force: when it cannot run it is said and left off (plain batching still starts); default off = exactly 0.1.39. + // With a layer split the slots' drafters live on the LAST stage's GPU (where the solo drafter, the head and the final + // residual rows are); the windows are the ones --batch runs, two rows per slot, through every stage. const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP"); bool batch_mtp = o.batch_mtp || (batch_mtp_env != nullptr && batch_mtp_env[0] != '\0' && batch_mtp_env[0] != '0'); if (batch_mtp) { + // (--pipeline-windows is already off with --batch slots) const char* why = o.batch < 2 ? "it needs --batch 2 or more" : o.mtp.empty() ? "it needs --mtp" - : o.spec < 2 ? "it needs --spec T (T >= 2)" : (multi_gpu || split_same || !stages.empty()) - ? "it is for one GPU (no layer split or helper) for now" : !o.serve ? "it needs --serve" : nullptr; + : o.spec < 2 ? "it needs --spec T (T >= 2)" : split_same + ? "it needs each stage of a layer split on its own GPU" : (o.batch_groups > 1 && !stages.empty()) + ? "it does not combine with --batch-groups (pipelined slot groups) yet" + : !o.serve ? "it needs --serve" : nullptr; if (why != nullptr) { std::fprintf(stderr, "strata generate: WARNING: --batch-mtp is off: %s\n", why); batch_mtp = false; @@ -4237,9 +4243,13 @@ int main(int argc, char** argv) { if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } mtp.set_ple_session(&ss); if (batch_mtp) { + // Slot b's drafter lives where the solo drafter does (the guard above: the last stage's GPU), carved from the + // LAST stage's slot-b session (bslot_ss.back(): stage 0's on one GPU): it borrows that session's context + // length and RoPE table, which are on that device. Its PLE history is the first stage's slot session: PLE + // runs on the first stage, as for the solo drafter (`mtp.set_ple_session(&ss)` above). for (int b = 0; b < o.batch; ++b) { auto d = std::make_unique(); - if (!d->load(o.mtp, draft_geometry, *bslot_ss[0][(size_t) b], o.spec, err, o.mtp_window, &mtp)) { + if (!d->load(o.mtp, draft_geometry, *bslot_ss.back()[(size_t) b], o.spec, err, o.mtp_window, &mtp)) { std::fprintf(stderr, "strata generate: batch MTP slot %d: %s%s\n", b, err.c_str(), vram_free_note().c_str()); return 1; @@ -4248,6 +4258,14 @@ int main(int argc, char** argv) { d->set_ple_session(bslot_ss[0][(size_t) b].get()); slot_mtp.push_back(std::move(d)); } + if (!slot_mtp.empty()) { + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + std::fprintf(stderr, "strata generate: --batch-mtp: %d slot drafters on CUDA%d (%.0f MiB of private K/V " + "state and buffers each, sharing the solo drafter's weights); %.2f GiB free there\n", + (int) slot_mtp.size(), mtp.device(), (double) slot_mtp.front()->vram_bytes() / 1048576.0, + (double) fb / 1073741824.0); + } } } // THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so @@ -4589,8 +4607,10 @@ int main(int argc, char** argv) { // ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199) int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded()) ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; - for (const auto& d : slot_mtp) - mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); + // (with a layer split the slot drafters bind on the last stage, whose cache is sized from what is free there) + if (stages.empty()) + for (const auto& d : slot_mtp) + mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first; const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t slots = ((int64_t) free_b - reserve) / blob; @@ -7143,7 +7163,11 @@ int main(int argc, char** argv) { vs.slot_off = gs.cache.slot_offsets(); vs.n_slots = gs.cache.slots(); gs.ver.set_remote_expert_opt(remote_opt.get()); - ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, std::max(o.spec, o.batch), err); + // --batch-mtp: every stage runs the same 2-rows-per-slot windows as the first (up to kVerifyMaxT + // rows, the hand-off's size) and bounds its captured batch layouts like the first (below) + if (batch_mtp) gs.ver.set_batch_graph_limit(64); + ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, + batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err); split_drive.cache_base[st] = gs.cache.device_slot(0); split_drive.cache_slot_off[st] = gs.cache.slot_offsets(); split_drive.pcie_num[st] = pcie_num_of(gs.pcie_frac); @@ -7223,6 +7247,9 @@ int main(int argc, char** argv) { auto free_slot_mtp_rows = [](float* p) { if (p != nullptr) (void) cudaFree(p); }; std::vector> slot_mtp_rows; if (batch_mtp) { + // like the solo drafter's `bind` above: the last stage's weights (embedding) and head, and the residual + // buffers on the drafter's device (the last stage's GPU with a layer split) + const strata::core::OnDevice on_slot_mtp(mtp.device()); for (int b = 0; b < o.batch; ++b) { float* r = nullptr; const size_t bytes = (size_t) o.spec * (size_t) g.hc * (size_t) g.n_embd * sizeof(float); @@ -7232,7 +7259,8 @@ int main(int argc, char** argv) { return 1; } slot_mtp_rows.emplace_back(r, free_slot_mtp_rows); - if (!slot_mtp[(size_t) b]->bind(wt, &native_head, r, err, &mtp)) { + if (!slot_mtp[(size_t) b]->bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, r, err, + &mtp)) { std::fprintf(stderr, "strata serve: batch MTP slot %d: %s%s\n", b, err.c_str(), vram_free_note().c_str()); return 1; @@ -8799,7 +8827,10 @@ int main(int argc, char** argv) { if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } } if (batch_mtp) { - // Admission first builds the solo draft KV; copy it into the slot before drafting. + // Admission first builds the solo draft KV; copy it into the slot before drafting. Both drafters' K/V + // are on the drafter's device (the last stage's GPU with a layer split): the copy's ring refill is a + // kernel launch there. + const strata::core::OnDevice on_mtp(mtp.device()); strata::core::ConversationKv image; if (!mtp.idle(e) || !slot_mtp[(size_t) b]->idle(e) || !strata::core::conversation_kv_save(image, mtp.kv_state(), draft_geometry, upto, false, e) || @@ -8843,7 +8874,8 @@ int main(int argc, char** argv) { if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } } if (batch_mtp) { - // A returning solo request resumes from its slot's draft KV. + // A returning solo request resumes from its slot's draft KV (on the drafter's device, as above). + const strata::core::OnDevice on_mtp(mtp.device()); strata::core::ConversationKv image; if (!slot_mtp[(size_t) b]->idle(e) || !mtp.idle(e) || !strata::core::conversation_kv_save(image, slot_mtp[(size_t) b]->kv_state(), @@ -8947,10 +8979,15 @@ int main(int argc, char** argv) { sl.p += 1; } if (batch_mtp && sl.active) { + // The slot's two residual rows (the final residuals of the last stage: ver.final_R_all() follows the + // chain, so with a layer split they are on the last stage's GPU, where the drafters are). The copy is + // queued on the drafter's own stream after the window's host sync, so the draft graph reads it. + const strata::core::OnDevice on_slot_mtp(slot_mtp[(size_t) b]->device()); const size_t stride = (size_t) g.hc * (size_t) g.n_embd; - if (cudaMemcpy(slot_mtp_rows[(size_t) b].get(), - ver.final_R_all() + (size_t) first[t] * stride, - 2 * stride * sizeof(float), cudaMemcpyDeviceToDevice) != cudaSuccess || + if (cudaMemcpyAsync(slot_mtp_rows[(size_t) b].get(), + ver.final_R_all() + (size_t) first[t] * stride, + 2 * stride * sizeof(float), cudaMemcpyDeviceToDevice, + slot_mtp[(size_t) b]->stream()) != cudaSuccess || !slot_mtp[(size_t) b]->draft(2, outb + first[t], pos[first[t]], keep[b] - 1, sl.draft.data(), err)) { std::printf("ERR batch MTP slot %d: %s\n", b, err.c_str()); diff --git a/tests/core/batch_rows_test.cpp b/tests/core/batch_rows_test.cpp new file mode 100644 index 00000000..f3493d15 --- /dev/null +++ b/tests/core/batch_rows_test.cpp @@ -0,0 +1,78 @@ +// The batch window's row layout (include/strata/core/batch_rows.hpp): plain one-row slots, a slot's contiguous group of +// proposed rows (--batch-mtp), and the hand-off capacity of a layer split's stages. Header-only, CPU. +#include "strata/core/batch_rows.hpp" + +#include +#include +#include + +namespace { +int failures = 0; +void check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; + } +} +const char* run(const int* rows, const long long* p, int S, int n_slots, int max_t, int hbase, bool handoff) { + int64_t pos[8]; + for (int t = 0; t < S; ++t) pos[t] = p[t]; + return strata::core::batch_rows_error(rows, S, pos, n_slots, max_t, hbase, handoff, 8); +} +} // namespace + +int main() { + using strata::core::batch_rows_error; + // plain batch: one row per slot, any positions + { + const int rows[] = {0, 1, 2}; + const long long pos[] = {10, 500, 3}; + check(run(rows, pos, 3, 3, 8, 0, false) == nullptr, "one row per slot"); + check(run(rows, pos, 3, 3, 8, 0, true) == nullptr, "one row per slot through the hand-off"); + } + // --batch-mtp: a slot's two rows at consecutive positions; also on a layer split (S > slots) + { + const int rows[] = {1, 1, 0, 0}; + const long long pos[] = {40, 41, 7, 8}; + check(run(rows, pos, 4, 2, 8, 0, false) == nullptr, "two rows per slot, one stage"); + check(run(rows, pos, 4, 2, 8, 0, true) == nullptr, "two rows per slot across a layer split (S > slots)"); + } + // eight rows = four slots of two: the whole hand-off + { + const int rows[] = {0, 0, 1, 1, 2, 2, 3, 3}; + const long long pos[] = {1, 2, 5, 6, 9, 10, 20, 21}; + check(run(rows, pos, 8, 4, 8, 0, true) == nullptr, "eight rows fill the hand-off"); + check(run(rows, pos, 8, 4, 8, 1, true) != nullptr, "a group past the hand-off's end"); + check(run(rows, pos, 8, 4, 8, 1, false) == nullptr, "no hand-off: the base does not bound the rows"); + } + // refused layouts + { + const int rows[] = {0, 1, 0}; + const long long pos[] = {5, 9, 6}; + check(run(rows, pos, 3, 2, 8, 0, false) != nullptr, "a slot's rows must be contiguous"); + } + { + const int rows[] = {0, 0}; + const long long pos[] = {5, 7}; + check(run(rows, pos, 2, 1, 8, 0, false) != nullptr, "a slot's rows need consecutive positions"); + } + { + const int rows[] = {0, 2}; + const long long pos[] = {5, 7}; + check(run(rows, pos, 2, 2, 8, 0, false) != nullptr, "a slot past the slots held"); + const int neg[] = {-1}; + const long long p1[] = {1}; + check(run(neg, p1, 1, 2, 8, 0, false) != nullptr, "a negative slot"); + } + { + const int rows[] = {0, 0, 0}; + const long long pos[] = {1, 2, 3}; + check(run(rows, pos, 3, 1, 2, 0, false) != nullptr, "more rows than the window holds"); + check(run(rows, pos, 0, 1, 8, 0, false) != nullptr, "an empty window"); + check(run(rows, pos, 3, 1, 8, -1, false) != nullptr, "a negative hand-off base"); + check(run(rows, pos, 3, 1, 8, 0, false) == nullptr, "three rows of one slot are a group"); + } + if (failures != 0) return EXIT_FAILURE; + std::printf("batch_rows_test: ok\n"); + return EXIT_SUCCESS; +} From 70fc0ba46d654972cb50a192678970b925255bd6 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Tue, 6 Oct 2026 17:17:42 -0400 Subject: [PATCH 03/19] batch-mtp: log the accepted proposals in the batch summary --- src/program/generate.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index f6046aa2..e07686df 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8791,7 +8791,7 @@ int main(int argc, char** argv) { double bt_run = 0, bt_commit = 0, bt_emit = 0; double bt_wait0 = 0, bt_pool0 = 0; int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0; - int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0; + int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0, bt_accepted = 0; // bt_accepted: --batch-mtp proposals taken Clock::time_point bt_start = Clock::now(); int admit_slot = -1; ///< the slot the request being read will continue in (BGEN) long long admit_max_new = 0; @@ -8956,7 +8956,10 @@ int main(int argc, char** argv) { bt_run += msd(w0, w1); bt_commit += msd(w1, w2); ++bt_windows; - for (int a = 0; a < A; ++a) bt_rows += keep[active[a]]; + for (int a = 0; a < A; ++a) { + bt_rows += keep[active[a]]; + bt_accepted += keep[active[a]] - 1; + } for (int t = 0; t < A; ++t) { const int b = active[t]; BSlot& sl = bs[(size_t) b]; @@ -9014,8 +9017,12 @@ int main(int argc, char** argv) { const std::string pr = (k == 0 ? ver : stages[k - 1]->ver).profile_report(); if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %zu (ms/window):%s\n", k + 1, pr.c_str()); } + if (batch_mtp) // each slot-window offers one proposal and yields 1 + (accepted) tokens + std::fprintf(stderr, "strata batch: MTP proposals accepted %lld of %lld (%.1f%%)\n", + (long long) bt_accepted, (long long) (bt_rows - bt_accepted), + 100.0 * (double) bt_accepted / (double) std::max(bt_rows - bt_accepted, 1)); bt_run = bt_commit = bt_emit = 0; - bt_windows = bt_rows = bt_tokens = 0; + bt_windows = bt_rows = bt_tokens = bt_accepted = 0; } return true; }; From cb6c549c8a0a56c70c7b2cb4a70973f1965e452a Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:51:07 -0400 Subject: [PATCH 04/19] batch-groups: the 0.1.41 auto default gives way to --batch-mtp (one group, said once) --batch-groups auto became the default for a layer split with --batch >= 2, but the --batch-mtp gate ran before the groups were resolved: it saw 1 group, kept batch-MTP on, and the groups were then raised to 2 - pipelined groups do not run the slots' MTP drafts (#1413). The resolution is now a pure helper (include/strata/program/batch_groups.hpp, CPU test src/program/batch_groups_test.cpp): with --batch-mtp and no --batch-groups the default is one group and the log says why; --batch-groups N (N > 1) or --batch-groups auto given on the command line pipelines the groups and turns --batch-mtp off, as before. --- CMakeLists.txt | 4 ++ docs/BATCHING.md | 2 +- include/strata/program/batch_groups.hpp | 62 +++++++++++++++++ src/program/batch_groups_test.cpp | 93 +++++++++++++++++++++++++ src/program/generate.cpp | 46 ++++++++---- 5 files changed, 194 insertions(+), 13 deletions(-) create mode 100644 include/strata/program/batch_groups.hpp create mode 100644 src/program/batch_groups_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4ed15426..ac489599 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1134,6 +1134,10 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(batch_rows_test tests/core/batch_rows_test.cpp) target_include_directories(batch_rows_test PRIVATE include) add_test(NAME batch_rows_test COMMAND batch_rows_test) + # how many pipelined slot groups --batch runs with: the 0.1.41 default, and --batch-mtp keeping it serial (header-only, CPU) + add_executable(batch_groups_test src/program/batch_groups_test.cpp) + target_include_directories(batch_groups_test PRIVATE include) + add_test(NAME batch_groups_test COMMAND batch_groups_test) endif() add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 4f706617..0b234a8f 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -47,7 +47,7 @@ With a layer split, the engine options go into the config's `args`: | --- | --- | | `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | | `--batch-groups G` | with a layer split (default: auto, below): the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | -| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. | +| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--batch-mtp` and no `--batch-groups` the default is one group (the slots' MTP drafts do not run in pipelined groups) and the log says so; `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off. | | `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by diff --git a/include/strata/program/batch_groups.hpp b/include/strata/program/batch_groups.hpp new file mode 100644 index 00000000..0cc7c1d9 --- /dev/null +++ b/include/strata/program/batch_groups.hpp @@ -0,0 +1,62 @@ +// include/strata/program/batch_groups.hpp - how many pipelined slot groups `--batch` runs with. +// +// `--batch-groups N` pipelines N groups of slots through the stages of a layer split; `--batch-groups auto` picks the +// most groups (at most one per stage) that divide the slots. Since 0.1.41 a layer split with `--batch` >= 2 and no +// `--batch-groups` at all means `auto`. The pipelined path does not run `--batch-mtp`'s drafts, so when `--batch-mtp` +// is asked for and the number of groups was NOT given, `auto` resolves to one group (the serial windows the drafts run +// in) and says why. A number or `auto` given on the command line is honoured as before. +// +// Pure (no GPU, no environment read): generate.cpp passes in what it knows. +#pragma once + +namespace strata::program::batch_groups { + +/// What kept `auto` from pipelining. +enum class Serial { None, BatchMtp }; + +struct Input { + bool set = false; ///< --batch-groups was given (a number or `auto`) + bool auto_given = false; ///< ... as `auto` + int given = 1; ///< the number given (1 when none) + int batch = 0; ///< the slots + int later_stages = 0; ///< the layer split's stages after CUDA0 (0: no layer split) + bool batch_mtp = false; ///< --batch-mtp is on (it passed the gates that do not concern the groups) +}; + +struct Result { + int groups = 1; + bool from_auto = false; ///< the number came from `auto` (given or the 0.1.41 default) + Serial serial = Serial::None; ///< `auto` would have pipelined, but --batch-mtp needs the serial windows + int would_be = 1; ///< what `auto` would have picked without it (== groups unless `serial`) +}; + +/// The most groups, at most one per stage of the layer split (`later_stages` + 1 GPUs), that divide `batch`. +inline int auto_groups(int later_stages, int batch) { + int best = 1; + if (later_stages <= 0) return best; + for (int d = 2; d <= later_stages + 1 && d <= batch; ++d) + if (batch % d == 0) best = d; + return best; +} + +inline Result resolve(const Input& in) { + Result r; + r.groups = in.given; + r.would_be = in.given; + const bool defaulted = !in.set && in.later_stages > 0 && in.batch > 1; // the 0.1.41 default + if (!in.auto_given && !defaulted) return r; + r.from_auto = true; + r.would_be = auto_groups(in.later_stages, in.batch); + r.groups = r.would_be; + if (!in.set && r.would_be > 1 && in.batch_mtp) { // only the default gives way; `--batch-groups auto` asked for the pipeline + r.serial = Serial::BatchMtp; + r.groups = 1; + } + return r; +} + +inline const char* serial_what(Serial s) { + return s == Serial::BatchMtp ? "--batch-mtp" : ""; +} + +} // namespace strata::program::batch_groups diff --git a/src/program/batch_groups_test.cpp b/src/program/batch_groups_test.cpp new file mode 100644 index 00000000..065fd5f6 --- /dev/null +++ b/src/program/batch_groups_test.cpp @@ -0,0 +1,93 @@ +// src/program/batch_groups_test.cpp - how many pipelined slot groups --batch runs with (header-only, CPU). +// +// 1. `auto` picks the most groups, at most one per stage, that divide the slots; +// 2. a layer split with --batch >= 2 and no --batch-groups means `auto` (0.1.41); +// 3. --batch-mtp turns that default into one group, and says which feature did it; +// 4. a number or `auto` given explicitly is honoured, with or without --batch-mtp; +// 5. no layer split: the number given (1) stays. +#include "strata/program/batch_groups.hpp" + +#include + +namespace bg = strata::program::batch_groups; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + std::printf(" %-78s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} +bg::Input in(int batch, int stages) { + bg::Input i; + i.batch = batch; + i.later_stages = stages; + return i; +} +} // namespace + +int main() { + std::printf("batch_groups_test\n"); + check(bg::auto_groups(0, 4) == 1, "auto: no layer split, one group"); + check(bg::auto_groups(1, 2) == 2 && bg::auto_groups(1, 4) == 2 && bg::auto_groups(1, 3) == 1, + "auto: two GPUs, 2 groups when the slots divide by 2"); + check(bg::auto_groups(3, 8) == 4 && bg::auto_groups(3, 6) == 3 && bg::auto_groups(3, 2) == 2, + "auto: at most one group per GPU, and a divisor of the slots"); + + { // the 0.1.41 default + const auto r = bg::resolve(in(2, 1)); + check(r.groups == 2 && r.from_auto && r.serial == bg::Serial::None, "layer split, --batch 2, nothing given: 2 groups"); + } + { + const auto r = bg::resolve(in(1, 1)); + check(r.groups == 1 && !r.from_auto, "--batch 1: no default"); + } + { + const auto r = bg::resolve(in(2, 0)); + check(r.groups == 1 && !r.from_auto, "no layer split: one group"); + } + + { // the shape this is for: parallel 2 on a 2-GPU split with --batch-mtp + bg::Input i = in(2, 1); + i.batch_mtp = true; + const auto r = bg::resolve(i); + check(r.groups == 1 && r.from_auto && r.serial == bg::Serial::BatchMtp && r.would_be == 2, + "--batch-mtp, nothing given: one group, because of --batch-mtp"); + check(bg::serial_what(r.serial)[0] == '-', "the reason names the feature"); + } + { // nothing to give way: the slots do not divide, so auto is one group anyway and there is nothing to say + bg::Input i = in(3, 1); + i.batch_mtp = true; + const auto r = bg::resolve(i); + check(r.groups == 1 && r.serial == bg::Serial::None && r.would_be == 1, "auto would be 1 group anyway: no reason"); + } + { // explicit values are honoured + bg::Input i = in(4, 1); + i.set = true; + i.given = 2; + i.batch_mtp = true; + const auto r = bg::resolve(i); + check(r.groups == 2 && !r.from_auto && r.serial == bg::Serial::None, "--batch-groups 2 with --batch-mtp: 2"); + i.given = 1; + check(bg::resolve(i).groups == 1, "--batch-groups 1: 1 (the opt-out)"); + i.given = 4; // not checked here: generate.cpp refuses what does not divide + check(bg::resolve(i).groups == 4, "--batch-groups 4 is returned as given"); + } + { + bg::Input i = in(2, 1); + i.set = true; + i.auto_given = true; + i.batch_mtp = true; + const auto r = bg::resolve(i); + check(r.groups == 2 && r.from_auto && r.serial == bg::Serial::None, + "--batch-groups auto with --batch-mtp: auto asked for the pipeline, 2 groups"); + } + { + bg::Input i = in(2, 0); + i.set = true; + i.given = 2; + check(bg::resolve(i).groups == 2, "an explicit number without a split is returned (the engine warns)"); + } + + std::printf("%s\n", g_fail == 0 ? "batch_groups_test: all passed" : "batch_groups_test: FAILED"); + return g_fail == 0 ? 0 : 1; +} diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e07686df..fe1c48e0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -72,6 +72,7 @@ #include "strata/spec/draft_policy.hpp" #include "strata/spec/draft_source.hpp" #include "strata/spec/suffix_drafter.hpp" +#include "strata/program/batch_groups.hpp" #include "strata/kernels/cvec.hpp" #include "strata/core/progress.hpp" #include "strata/core/device.hpp" @@ -4117,15 +4118,31 @@ int main(int argc, char** argv) { // force: when it cannot run it is said and left off (plain batching still starts); default off = exactly 0.1.39. // With a layer split the slots' drafters live on the LAST stage's GPU (where the solo drafter, the head and the final // residual rows are); the windows are the ones --batch runs, two rows per slot, through every stage. + // --batch-groups: given as a number or auto, or (0.1.41) auto by default for a layer split with --batch >= 2. The + // pipelined slot groups do not run --batch-mtp's drafts, so when it is asked for and the groups were not given, the + // default is one group (batch_groups.hpp). Evaluated again once the slots that fit are known, and BEFORE the + // --batch-mtp gate below, which must see the resolved number. + auto batch_groups_for = [&](bool mtp_on) { + strata::program::batch_groups::Input bin; + bin.set = o.batch_groups_set; + bin.auto_given = o.batch_groups_auto; + bin.given = o.batch_groups; + bin.batch = o.batch; + bin.later_stages = (int) stages.size(); + bin.batch_mtp = mtp_on; + return strata::program::batch_groups::resolve(bin); + }; const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP"); bool batch_mtp = o.batch_mtp || (batch_mtp_env != nullptr && batch_mtp_env[0] != '\0' && batch_mtp_env[0] != '0'); if (batch_mtp) { // (--pipeline-windows is already off with --batch slots) const char* why = o.batch < 2 ? "it needs --batch 2 or more" : o.mtp.empty() ? "it needs --mtp" : o.spec < 2 ? "it needs --spec T (T >= 2)" : split_same - ? "it needs each stage of a layer split on its own GPU" : (o.batch_groups > 1 && !stages.empty()) - ? "it does not combine with --batch-groups (pipelined slot groups) yet" + ? "it needs each stage of a layer split on its own GPU" : !o.serve ? "it needs --serve" : nullptr; + // the groups it would run with (the default gives way to it: one group; a number or auto given pipelines) + if (why == nullptr && !stages.empty() && batch_groups_for(true).groups > 1) + why = "it does not combine with --batch-groups (pipelined slot groups) yet"; if (why != nullptr) { std::fprintf(stderr, "strata generate: WARNING: --batch-mtp is off: %s\n", why); batch_mtp = false; @@ -4147,17 +4164,22 @@ int main(int argc, char** argv) { } // --batch-groups auto: the pipeline needs one group per GPU stage to keep every card busy (4 x R9700, 8 clients: // 90 tok/s in one group, 136 in 2, 166 in 4). The most groups, at most one per stage, that divide the slots. + // The default (0.1.41: a layer split with --batch pipelines one group per stage; --batch-groups 1 opts out) gives + // way to --batch-mtp, which needs the serial windows: one group, said once. + int groups_said = 0; auto resolve_groups_auto = [&] { - // default (0.1.41): a layer split with --batch pipelines one group per stage; --batch-groups 1 opts out - if (!o.batch_groups_set && !stages.empty() && o.batch > 1) o.batch_groups_auto = true; - if (!o.batch_groups_auto) return; - int best = 1; - for (int d = 2; d <= (int) stages.size() + 1 && d <= o.batch; ++d) - if (o.batch % d == 0) best = d; - if (stages.empty()) best = 1; - o.batch_groups = best; - std::fprintf(stderr, "strata generate: --batch-groups auto: %d group%s of %d slot%s\n", best, best == 1 ? "" : "s", - o.batch / best, o.batch / best == 1 ? "" : "s"); + const auto r = batch_groups_for(batch_mtp); + if (!r.from_auto) return; + o.batch_groups = r.groups; + if (groups_said == r.groups) return; // (the second call, once the slots that fit are known, says nothing new) + groups_said = r.groups; + if (r.serial != strata::program::batch_groups::Serial::None) + std::fprintf(stderr, "strata generate: --batch-groups auto: 1 group of %d slot%s - %s does not run in pipelined " + "groups; --batch-groups %d would pipeline them and turn it off\n", o.batch, + o.batch == 1 ? "" : "s", strata::program::batch_groups::serial_what(r.serial), r.would_be); + else + std::fprintf(stderr, "strata generate: --batch-groups auto: %d group%s of %d slot%s\n", r.groups, + r.groups == 1 ? "" : "s", o.batch / r.groups, o.batch / r.groups == 1 ? "" : "s"); }; if (o.batch > 0) resolve_groups_auto(); if (o.batch > 0 && o.batch_groups > 1 && (stages.empty() || o.batch % o.batch_groups != 0)) { From f90bec6f44e289852092b0e14a6340488977aaaf Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 16:01:50 -0400 Subject: [PATCH 05/19] batch-mtp: not with helper expert caches on a layer split (not run); docs say how it meets --batch-groups The 0.1.41 default --batch-groups auto, the pipelined path's lack of slot drafts and the helper-cache refusal are written down in docs/BATCHING.md (the limits list and the --batch-mtp paragraph). --- docs/BATCHING.md | 21 ++++++++++++--------- src/program/generate.cpp | 3 +++ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 0b234a8f..4a14aa10 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -22,19 +22,21 @@ asked, with a note when it is more than setup would recommend. With MTP (`--mtp` and `--spec`), `--batch-mtp` (in the config's `args`, or `STRATA_BATCH_MTP=1` in the server's environment) lets each batch slot verify one MTP proposal per window. It is opt-in; without it the batch behaviour described below is exactly the one without MTP. It needs VRAM per slot for the draft state and buffers, so check the -engine's free-memory log before using it on a smaller card. If it cannot run (one slot, no `--mtp`, `--batch-groups` -with a layer split, a layer split on one GPU) the engine says so and batches as usual. RTX PRO 5000 owners measured -+31% to +39% total throughput with 2 to 4 clients on one GPU (a RX R9700 run too). +engine's free-memory log before using it on a smaller card. If it cannot run (one slot, no `--mtp`, a layer split with +`--batch-groups` above 1 or with helper-GPU expert caches or `--remote-expert-opt`, a layer split with two stages on one +GPU) the engine says so and batches as usual. RTX PRO 5000 owners measured +31% to +39% total throughput with 2 to 4 +clients on one GPU (a RX R9700 run too). **With a layer split** (e.g. `"layer_split": "24"` on two GPUs, `"parallel": 2`, `--spec 4 --mtp ...`) it works the same way, with the slot drafters on the **last stage's GPU** (where the solo drafter and the head are): each slot gets a drafter that shares the solo drafter's weights and owns only its K/V ring and buffers (the engine logs `--batch-mtp: N slot drafters on CUDAk (X MiB ... each)` at start; the K/V ring of each also keeps a pinned-RAM copy, as the solo drafter's does). A window carries two rows per active slot (its token and its proposal) through every stage, so at most -four slots are in one window; more slots (`--batch` up to what fits) rotate through. The split keeps `--kv-pool-tokens` -and `--kv-resident` as without `--batch-mtp`. Not supported with a split: `--batch-groups` (pipelined slot groups; the -engine turns `--batch-mtp` off and says so). The code does not depend on the number of stages, but the two-stage split -is the one it was written for. +four slots are in one window; more slots (`--batch` up to what fits) rotate through. The windows run through the stages +one after the other (`--batch-groups 1`): on 0.1.41 a layer split with `--batch` 2 or more pipelines the slots in groups +by default, and the pipelined path does not run the slots' MTP drafts, so with `--batch-mtp` and no `--batch-groups` the +engine runs one group and says so; `--batch-groups G` (G above 1) or `--batch-groups auto` given on the command line +keeps the pipeline and turns `--batch-mtp` off. Only a layer split of two stages on two GPUs has been run. With a layer split, the engine options go into the config's `args`: @@ -134,8 +136,9 @@ counter-based draw (Philox(seed, position)). - By default, batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo path keeps its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone). -- `--batch-mtp` uses one proposal per slot. With a layer split it needs each stage on its own GPU and does not combine - with `--batch-groups` (pipelined slot groups). +- `--batch-mtp` uses one proposal per slot. With a layer split it needs each stage on its own GPU, does not combine + with `--batch-groups` above 1 (pipelined slot groups run no drafts, #1413) and has not been run with helper expert + caches. - Repetition / frequency / presence penalties are not applied in batch windows. - A prompt shorter than one chunk is read in one piece (the slots wait for it); a read gives way only at a chunk boundary, and not for pictures. diff --git a/src/program/generate.cpp b/src/program/generate.cpp index fe1c48e0..64be47d7 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4143,6 +4143,9 @@ int main(int argc, char** argv) { // the groups it would run with (the default gives way to it: one group; a number or auto given pipelines) if (why == nullptr && !stages.empty() && batch_groups_for(true).groups > 1) why = "it does not combine with --batch-groups (pipelined slot groups) yet"; + // (a layer split with helper-GPU expert caches or --remote-expert-opt has not been run with slot drafters) + if (why == nullptr && !stages.empty() && (remote_caches || o.remote_expert_opt)) + why = "it is not run with helper expert caches on a layer split"; if (why != nullptr) { std::fprintf(stderr, "strata generate: WARNING: --batch-mtp is off: %s\n", why); batch_mtp = false; From de71d7bef4617566d2e5d6f9c9d9848d1c199961 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:41:40 -0400 Subject: [PATCH 06/19] docs: batch MTP on a layer split - measured on 2x RTX 3080 20 GB (0.1.41 build and the earlier 0.1.40.3 runs), with what was not measured --- docs/BATCHING.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 4a14aa10..343289f0 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -38,6 +38,41 @@ by default, and the pipelined path does not run the slots' MTP drafts, so with ` engine runs one group and says so; `--batch-groups G` (G above 1) or `--batch-groups auto` given on the command line keeps the pipeline and turns `--batch-mtp` off. Only a layer split of two stages on two GPUs has been run. +Measured on a layer split of 2x RTX 3080 20 GB (220 W cap) with a Xeon E5-2696 v4, UD-Q4_K_XL, `"layer_split": "23"`, +`"parallel": 2`, `--spec 4`: two concurrent greedy decodes of 300 tokens, the two streams' tok/s added, median of +the measurements (10 rounds of two streams after each restart of the engine, 20 measurements per restart). The +engine was 0.1.41 with the rest of our production stack on it (the shared KV pool, and the adaptive expert tier +running in batch windows in the first two arms; the pipelined path of the third never adapts in windows), so this is +`--batch-mtp` on top of that, not this change alone on main. + +| arm | aggregate tok/s | restarts, measurements | per window | +| --- | --- | --- | --- | +| `--batch-mtp`, one group | **89.2** | 3, 60 | 3.3 rows, 34.6 ms, 66-67% of the proposals accepted | +| no `--batch-mtp`, one serial group | 77.3 | 2, 40 | 2.0 rows, 23.7 ms | +| no `--batch-mtp`, `--batch-groups` unset (the 0.1.41 default: two pipelined groups of one slot) | 77.7 | 1, 20 | one row per group step | + +That is +15.4% for `--batch-mtp` against serial windows without it (95% bootstrap interval of the ratio of medians ++12.5% to +17.9%) and +14.8% against the pipelined default; the two arms without it tie. One stream alone decodes the +same with and without it (81.7 and 82.0 tok/s), and the two slot drafters cost 35 to 110 expert-cache slots on the +last GPU (50 MiB of private state each). + +The pipelined default is better in one place: a new prompt of about 48k tokens arriving while one stream decodes was +read at 2508 tok/s with pipelined groups and 1217 tok/s in serial windows, and the decoding stream finished sooner +(25.0 against 18.0 tok/s over its whole run); `--batch-mtp` does not change that. So it pays where concurrent decodes +dominate; with long reads arriving beside decodes the pipelined groups can be the better choice. Not measured: more +than two stages (the report on #1253 found no gain at four stages), more than two slots, sampled decoding, an +upstream-main binary (the pipelined arm is our build, started with the flags 0.1.41 resolves to). + +Earlier, on engine 0.1.40.3 with this change and the same two cards, two concurrent streams: UD-Q4_K_XL 39.9 to 43.5 +tok/s without and 44.5 to 51.3 with `--batch-mtp` (2 runs per arm), and a small Coder IQ1_M test model with all +experts in VRAM 84.0 without and 101.2 with it, the greedy text of both streams identical. + +Text: with the same expert cache on both arms (the slot drafters take VRAM, so the cache differs unless the +reserve is adjusted) and `--pcie-frac 0`, `--adapt-every 0`, the greedy text with `--batch-mtp` was equal to the text +without it for 5 short prompts in all 6 comparisons (one restart per arm). That is text equality, not a bit-exactness +proof, and a 25k-token prompt read while the other stream decodes was not repeatable between two identical streams +of the same arm. + With a layer split, the engine options go into the config's `args`: ``` From e989c6719413c10b388d22ea7804a01f5bd25331 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:39:43 -0400 Subject: [PATCH 07/19] batch: the adaptive VRAM expert tier keeps adapting in batch windows; per-stage timing in the strata batch line batch_step now runs adapt() every --adapt-every windows on a thread beside the commit and the drafts, lands the swaps (apply_pending) before the window ends, and pauses while a prompt holds a loan of cache slots. The timing line adds the adaptive tier's rounds/swaps and wait, each stage's GPU-reach wait and pool time, and the VRAM/PCIe/CPU entry split. --- docs/BATCHING.md | 13 +++++++ src/program/generate.cpp | 76 +++++++++++++++++++++++++++++++++++----- 2 files changed, 81 insertions(+), 8 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 343289f0..8779937d 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -139,6 +139,19 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske - Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`). - A client that disconnects stops its slot (`BSTOP`); the others go on. +## The VRAM expert tier keeps adapting in batch windows + +Batch windows count which experts they route to, and every `--adapt-every` windows (default 4) the engine swaps the +most-routed experts that are not in VRAM into the cache in place of the least-routed resident ones, the same rule the +solo path uses (`--adapt-swaps` and `--adapt-decay` apply too; on a layer split every GPU's cache adapts). It runs when the +tier is not the whole model and both `--adapt-every` and `--adapt-swaps` are above 0. The copies run beside the +window's commit and drafts and have landed before the next window starts. It pauses while a prompt holds a loan of cache +slots (a long prompt read beside decoding slots). The `strata batch:` log line shows the rounds and swaps, each stage's +GPU-reach wait and pool time, and how many routed entries the VRAM tier, the PCIe share and the CPU served per window. +Swaps move experts between the GPU and the CPU, which round differently, so greedy outputs can differ from run to run; +`--adapt-every 1000000` keeps the tier fixed (as in the exactness settings below). The pipelined `--batch-groups` path +does not adapt. + ## Exactness A batch row's arithmetic is the single-token window's, so with greedy decoding **every conversation of a batch diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 64be47d7..4c4b492d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8817,6 +8817,14 @@ int main(int argc, char** argv) { double bt_wait0 = 0, bt_pool0 = 0; int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0; int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0, bt_accepted = 0; // bt_accepted: --batch-mtp proposals taken + // per stage (0 = CUDA0's verifier): the GPU-reach wait and pool time when the timed windows began; and the routed + // (token, expert) entries the CPU and the PCIe share had served by then (bt_hits0 holds the VRAM entries) + std::vector bt_stage_wait0, bt_stage_pool0; + int64_t bt_cpu_ent0 = 0, bt_off_ent0 = 0; + // the adaptive VRAM tier in batch windows: windows seen since the engine started (--adapt-every counts them), and, + // since the last timing line, its rounds, the experts it swapped in and the ms a window waited for it + int64_t ba_window = 0, bt_adapt_rounds = 0, bt_adapt_swaps = 0; + double bt_adapt_wait = 0; Clock::time_point bt_start = Clock::now(); int admit_slot = -1; ///< the slot the request being read will continue in (BGEN) long long admit_max_new = 0; @@ -8912,6 +8920,7 @@ int main(int argc, char** argv) { } return true; }; + auto stage_verifier = [&](int k) -> strata::core::Verifier& { return k == 0 ? ver : stages[(size_t) k - 1]->ver; }; // one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched, // so it keeps the conversation it holds auto batch_step = [&]() -> bool { @@ -8956,6 +8965,13 @@ int main(int argc, char** argv) { bt_start = Clock::now(); bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool; bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts; + bt_stage_wait0.assign(stages.size() + 1, 0.0); + bt_stage_pool0.assign(stages.size() + 1, 0.0); + for (size_t k = 0; k <= stages.size(); ++k) { + bt_stage_wait0[k] = stage_verifier((int) k).ms_wait; + bt_stage_pool0[k] = stage_verifier((int) k).ms_pool; + } + bt_cpu_ent0 = drive.d.multi_entries; bt_off_ent0 = drive.d.offload_entries; } const Clock::time_point w0 = Clock::now(); if (!ver.run_slot_rows(rows, S, tok, pos, win_pool_fn, win_pool_user, outb, err) || drive.d.failed) { @@ -8963,6 +8979,20 @@ int main(int argc, char** argv) { return false; } const Clock::time_point w1 = Clock::now(); + // The adaptive VRAM tier, as the solo loop runs it: every --adapt-every windows, on a thread beside the commit and + // the drafts. Every stage's window has finished here (run_slot_rows synchronised each stage's stream), and + // nothing in flight reads the cache slots a swap overwrites; the swapped-in experts are landed (apply_pending) + // before this window ends, so no other path (a prompt chunk read between windows, a loan of cache slots, a KV + // growth) ever meets swaps in flight. Not while a prompt holds a loan of cache slots: its lent experts are + // marked missing and are put back when the loan ends. + struct AdaptRun { + std::thread th; + bool ok = true; + ~AdaptRun() { if (th.joinable()) th.join(); } // an error return below still joins it + } adapt_run; + if (!drive.d.usage.empty() && !ajob && (++ba_window % o.adapt_every) == 0 && pending.empty() && + std::none_of(pf_parts.begin(), pf_parts.end(), [](const PfPart& p) { return !p.lent.empty(); })) + adapt_run.th = std::thread([&] { adapt_run.ok = adapt(); }); // Accept the proposal only when the target picked it and there is room to emit both tokens. std::vector keep(bs.size(), 0); for (int a = 0; a < A; ++a) { @@ -9026,18 +9056,49 @@ int main(int argc, char** argv) { } std::fflush(stdout); bt_emit += msd(w2, Clock::now()); + if (adapt_run.th.joinable()) { + const Clock::time_point wa = Clock::now(); + adapt_run.th.join(); + if (!adapt_run.ok) { + std::printf("ERR an adaptive refill failed\n"); + return false; + } + ++bt_adapt_rounds; + bt_adapt_swaps += (int64_t) pending.size(); + apply_pending(true); // the copies land and the tables follow (the next window plans from them) + bt_adapt_wait += msd(wa, Clock::now()); + } strata::core::progress().busy.store(was_busy); if (!batch_on() && bt_windows > 0) { const double w = (double) bt_windows, wall = msd(bt_start, Clock::now()); const double L = (double) g.n_layers; + const double e_vram = (double) (drive.d.cache_hits - bt_hits0), e_pcie = (double) (drive.d.offload_entries - bt_off_ent0), + e_cpu = (double) (drive.d.multi_entries - bt_cpu_ent0); + const double e_all = std::max(e_vram + e_pcie + e_cpu, 1.0); + std::string per_stage; // every stage's own host wait for its GPU and its pool time (run_slot_rows recurses) + for (size_t k = 0; k <= stages.size(); ++k) { + char sb[96]; + std::snprintf(sb, sizeof sb, "%sCUDA%d wait %.2f + pool %.2f", k == 0 ? "" : ", ", k == 0 ? 0 : stages[k - 1]->dev, + (stage_verifier((int) k).ms_wait - bt_stage_wait0[k]) / w, + (stage_verifier((int) k).ms_pool - bt_stage_pool0[k]) / w); + per_stage += sb; + } + char adapt_txt[160] = ""; + if (!drive.d.usage.empty()) + std::snprintf(adapt_txt, sizeof adapt_txt, "; adaptive tier: %lld rounds, %lld experts swapped in", + (long long) bt_adapt_rounds, (long long) bt_adapt_swaps); std::fprintf(stderr, "strata batch: %lld windows, avg %.2f rows, %.2f ms/window = run %.2f (CUDA0 GPU-reach " - "wait %.2f + CPU experts %.2f) + commit %.2f + emit %.2f; per layer-window: CPU experts " - "%.2f, VRAM hits %.2f, PCIe %.2f; %.1f rows/s over %.0f ms of wall time (admissions " - "included)\n", - (long long) bt_windows, bt_rows / w, (bt_run + bt_commit + bt_emit) / w, bt_run / w, + "wait %.2f + CPU experts %.2f) + commit %.2f + emit %.2f + adapt wait %.2f; per stage " + "(ms/window): %s; per layer-window: CPU experts %.2f, VRAM hits %.2f, PCIe %.2f; routed " + "entries per window: VRAM %.1f (%.1f%%), PCIe %.1f (%.1f%%), CPU %.1f (%.1f%%)%s; %.1f rows/s " + "over %.0f ms of wall time (admissions included)\n", + (long long) bt_windows, bt_rows / w, (bt_run + bt_commit + bt_emit + bt_adapt_wait) / w, bt_run / w, (ver.ms_wait - bt_wait0) / w, (ver.ms_pool - bt_pool0) / w, bt_commit / w, bt_emit / w, + bt_adapt_wait / w, per_stage.c_str(), (drive.d.multi_misses - bt_miss0) / (w * L), (drive.d.cache_hits - bt_hits0) / (w * L), - (drive.d.pcie_experts - bt_pcie0) / (w * L), 1000.0 * bt_rows / std::max(wall, 1e-9), wall); + (drive.d.pcie_experts - bt_pcie0) / (w * L), e_vram / w, 100.0 * e_vram / e_all, e_pcie / w, + 100.0 * e_pcie / e_all, e_cpu / w, 100.0 * e_cpu / e_all, adapt_txt, + 1000.0 * bt_rows / std::max(wall, 1e-9), wall); for (size_t k = 0; k <= stages.size(); ++k) { const std::string pr = (k == 0 ? ver : stages[k - 1]->ver).profile_report(); if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %zu (ms/window):%s\n", k + 1, pr.c_str()); @@ -9046,8 +9107,8 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata batch: MTP proposals accepted %lld of %lld (%.1f%%)\n", (long long) bt_accepted, (long long) (bt_rows - bt_accepted), 100.0 * (double) bt_accepted / (double) std::max(bt_rows - bt_accepted, 1)); - bt_run = bt_commit = bt_emit = 0; - bt_windows = bt_rows = bt_tokens = bt_accepted = 0; + bt_run = bt_commit = bt_emit = bt_adapt_wait = 0; + bt_windows = bt_rows = bt_tokens = bt_accepted = bt_adapt_rounds = bt_adapt_swaps = 0; } return true; }; @@ -9071,7 +9132,6 @@ int main(int argc, char** argv) { std::vector pg((size_t) (piped ? o.batch_groups : 0)); std::vector stage_group((size_t) n_pipe, -1); int64_t pipe_tick = 0, rr = 0; - auto stage_verifier = [&](int k) -> strata::core::Verifier& { return k == 0 ? ver : stages[(size_t) k - 1]->ver; }; auto pipe_inflight = [&] { for (const PGroup& x : pg) if (x.inflight) return true; return false; }; auto group_active = [&](int gi) { for (int t = 0; t < GS; ++t) if (bs[(size_t) (gi * GS + t)].active) return true; From 495dc43690c68747619a4b88e08f962c45a7dd8d Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Tue, 6 Oct 2026 20:18:07 -0400 Subject: [PATCH 08/19] batch: tick the asynchronous adaptive tier (--adapt-async 1) between batch windows; --adapt-min-gain batch_step advances the async round one step per window (never between a prompt's chunks), commands drain the round in flight before they run, a round with nothing to swap ends at its first step, and --adapt-min-gain sets the bar a swap must clear (default 1.5, as before) for both tiers. --adapt-async is no longer refused with --batch slots (still with --batch-groups). --- docs/BATCHING.md | 14 +++++++-- docs/DETAILS.md | 5 ++-- src/program/generate.cpp | 65 +++++++++++++++++++++++++++++++--------- 3 files changed, 65 insertions(+), 19 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 8779937d..4217c60b 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -144,14 +144,22 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske Batch windows count which experts they route to, and every `--adapt-every` windows (default 4) the engine swaps the most-routed experts that are not in VRAM into the cache in place of the least-routed resident ones, the same rule the solo path uses (`--adapt-swaps` and `--adapt-decay` apply too; on a layer split every GPU's cache adapts). It runs when the -tier is not the whole model and both `--adapt-every` and `--adapt-swaps` are above 0. The copies run beside the -window's commit and drafts and have landed before the next window starts. It pauses while a prompt holds a loan of cache -slots (a long prompt read beside decoding slots). The `strata batch:` log line shows the rounds and swaps, each stage's +tier is not the whole model and both `--adapt-every` and `--adapt-swaps` are above 0. By default the round runs beside the +window's commit and drafts and has landed before the next window starts. It stands still while a long prompt is read +between decoding windows (the prompt may hold a loan of cache slots). The `strata batch:` log line shows the rounds and swaps, each stage's GPU-reach wait and pool time, and how many routed entries the VRAM tier, the PCIe share and the CPU served per window. Swaps move experts between the GPU and the CPU, which round differently, so greedy outputs can differ from run to run; `--adapt-every 1000000` keeps the tier fixed (as in the exactness settings below). The pipelined `--batch-groups` path does not adapt. +With `--adapt-async 1` (needs the resident RAM mode) the round does not hold a window up: each batch window moves the +round on one step (table changes and uploads on the main thread, the copies on a helper thread and the cards' refill +streams), as on the solo path. A request that arrives finishes the round in flight before it starts, and a prompt read +between decoding windows does not move it. `--adapt-min-gain F` (default 1.5) raises the bar a swap must clear (the +routing count of the expert coming in against the one going out), so fewer experts move per round; both tiers use it. +The log line's `adapt wait` is the time the main thread spent on the tier per window (the blocking tier: waiting for +its round). + ## Exactness A batch row's arithmetic is the single-token window's, so with greedy decoding **every conversation of a batch diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9547e112..41e2dc6e 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -167,8 +167,9 @@ other ~18 GB), a 32 GB PC with a 12-16 GB GPU the Coder; IQ3_XXS on a 32 GB PC s - The cache still follows the conversation (`--adapt-every`): a swap copies the evicted expert back from VRAM into the RAM place of the one that replaces it, so the RAM copy keeps holding exactly what the GPU does not. - `--adapt-async 1` (opt-in, `--serve`): the swaps of a round advance between decode windows on a helper thread - (copy back, copy in, move into RAM) instead of one window waiting for the whole round. Not with `--batch` or - `--peer-device` (the blocking tier runs there). With `--pipeline-windows 2` (two windows in flight, see + (copy back, copy in, move into RAM) instead of one window waiting for the whole round. With `--batch` slots it + advances between their windows too (docs/BATCHING.md); not with `--batch-groups` or `--peer-device` (the blocking + tier runs there). With `--pipeline-windows 2` (two windows in flight, see [MULTI_GPU.md](MULTI_GPU.md)) the copies into the evicted slots and the moves into RAM also wait until the windows that were in flight when they were decided have completed (`STRATA_PIPELINE_ADAPT_ASYNC=0`: the blocking tier there). It is not bit-exact from run to run: which window first computes a swapped-in expert on the GPU (which diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 4c4b492d..7b89e141 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -573,6 +573,9 @@ struct Options { /// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency. int adapt_every = 4; float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay) + /// an expert is swapped into the VRAM tier only when its decayed routing count beats the one it replaces by more than + /// this (--adapt-min-gain; both the blocking and the asynchronous tier) + float adapt_min_gain = 1.5f; /// --adapt-async 1 (--serve with the resident RAM mode; opt-in): the adaptive tier's rounds advance between verify /// windows on a helper thread instead of one window waiting for a whole round (see the tier in the --serve block). /// Not bit-exact run to run. 0 = the blocking tier. @@ -905,6 +908,8 @@ void usage() { " --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n" " with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n" " does not fit. Same answers as --mmap-experts for the same placement.\n" + " --adapt-min-gain F the adaptive tier swaps an expert in only when its decayed routing count beats\n" + " the one it replaces by more than F (default 1.5; higher = fewer, surer swaps)\n" " --adapt-async 1 --serve with the resident RAM mode (opt-in): the adaptive tier's swaps\n" " advance between verify windows instead of a window waiting for a whole\n" " round. Not bit-exact run to run. 0 (default) = the blocking tier.\n"); @@ -1899,6 +1904,7 @@ int main(int argc, char** argv) { else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac")); else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every")); else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay")); + else if (a == "--adapt-min-gain") o.adapt_min_gain = (float) std::atof(next("--adapt-min-gain")); else if (a == "--adapt-async") o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0; else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p")); else if (a == "--stop-eos") o.stop_eos = true; @@ -6365,11 +6371,11 @@ int main(int argc, char** argv) { // share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason. // --adapt-async (opt-in): where the asynchronous adaptive tier does not apply, the blocking tier runs, said once. // It exchanges experts between the GPU caches and the resident RAM copy only (the copy is checked once it is - // built, below). Not beside the --batch slots (their windows run between a request's prompt chunks), a peer - // tier or the helper GPUs' tier, which pick their swaps from the same table. The pipelined decode loop - // (--pipeline-windows 2) has windows in flight at every tick: there the steps that overwrite something a window - // may still read wait for those windows (see adapt_tick); STRATA_PIPELINE_ADAPT_ASYNC=0 keeps the blocking tier - // beside it instead. + // built, below). Beside the --batch slots it advances between their windows, never between a prompt's chunks; + // not with --batch-groups (pipelined slot groups), a peer tier or the helper GPUs' tier, which pick their swaps + // from the same table. The pipelined decode loop (--pipeline-windows 2) has windows in flight at every tick: + // there the steps that overwrite something a window may still read wait for those windows (see adapt_tick); + // STRATA_PIPELINE_ADAPT_ASYNC=0 keeps the blocking tier beside it instead. auto adapt_async_off = [&](const char* why) { std::fprintf(stderr, "strata generate: --adapt-async 1 is off (%s): the blocking adaptive tier\n", why); o.adapt_async = 0; @@ -6382,7 +6388,7 @@ int main(int argc, char** argv) { const char* why = !o.serve ? "it needs --serve" : o.adapt_every <= 0 || o.adapt_swaps <= 0 ? "the adaptive tier is off" : !o.resident_cpu_experts ? "it needs the resident RAM mode, --resident-experts" - : o.batch > 0 ? "not with --batch slots" + : o.batch > 0 && o.batch_groups > 1 ? "not with --batch-groups (the pipelined slot groups)" : peer.valid() ? "not with --peer-device" : remote_opt ? "not with --remote-expert-opt" : o.pipeline_windows >= 2 && !pl_async ? "not with --pipeline-windows 2 (STRATA_PIPELINE_ADAPT_ASYNC=0)" @@ -7987,7 +7993,7 @@ int main(int argc, char** argv) { std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), [](auto& a, auto& b) { return a.first < b.first; }); for (size_t i = 0; i < nc; ++i) { - if (cand[i].first < vict[i].first + 1.5f) break; + if (cand[i].first < vict[i].first + o.adapt_min_gain) break; swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); } } @@ -8186,7 +8192,7 @@ int main(int argc, char** argv) { std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), [](auto& a, auto& b) { return a.first < b.first; }); for (size_t i = 0; i < nc; ++i) { - if (cand[i].first < vict[i].first + 1.5f) break; + if (cand[i].first < vict[i].first + o.adapt_min_gain) break; all.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); } } @@ -8361,6 +8367,11 @@ int main(int argc, char** argv) { aswaps[k++] = w; } aswaps.resize(k); + if (aswaps.empty()) { // nothing to move (converged, or the table moved since the snapshot): the round ends here + a_ms += std::chrono::duration(Clock::now() - a_t0).count(); + astate = AState::Idle; + continue; + } for (AHome& h : ahomes) h.used = false; if (pl) { // the copies in at each card's next gap: after this step, so fenced (see above) a_res_dirty = true; @@ -8825,6 +8836,8 @@ int main(int argc, char** argv) { // since the last timing line, its rounds, the experts it swapped in and the ms a window waited for it int64_t ba_window = 0, bt_adapt_rounds = 0, bt_adapt_swaps = 0; double bt_adapt_wait = 0; + bool in_prompt_read = false; // batch_step runs between a prompt's chunks: the adaptive tier stands still then + int64_t bt_a_rounds0 = 0, bt_a_swapped0 = 0; // the asynchronous tier's counters when the timed windows began Clock::time_point bt_start = Clock::now(); int admit_slot = -1; ///< the slot the request being read will continue in (BGEN) long long admit_max_new = 0; @@ -8961,6 +8974,18 @@ int main(int argc, char** argv) { drive.d.experts = 0; drive.d.failed = false; apply_pending(false); + // --adapt-async: the round in flight moves on a step when its job and copies are done (or a due round starts). + // Never between a prompt's chunks (its loan of cache slots and its chunks read the tables); a request drains + // the round before its prompt starts (adapt_tick(true) where the request begins). The main thread's part is + // small (the table changes and uploads); the copies are on the helper thread and the cards' refill streams. + if (ajob && !in_prompt_read) { + const Clock::time_point ta = Clock::now(); + if (!adapt_tick(false)) { + std::printf("ERR an adaptive refill failed\n"); + return false; + } + bt_adapt_wait += std::chrono::duration(Clock::now() - ta).count(); + } if (bt_windows == 0) { bt_start = Clock::now(); bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool; @@ -8972,6 +8997,7 @@ int main(int argc, char** argv) { bt_stage_pool0[k] = stage_verifier((int) k).ms_pool; } bt_cpu_ent0 = drive.d.multi_entries; bt_off_ent0 = drive.d.offload_entries; + bt_a_rounds0 = a_rounds; bt_a_swapped0 = a_swapped; } const Clock::time_point w0 = Clock::now(); if (!ver.run_slot_rows(rows, S, tok, pos, win_pool_fn, win_pool_user, outb, err) || drive.d.failed) { @@ -8983,15 +9009,14 @@ int main(int argc, char** argv) { // the drafts. Every stage's window has finished here (run_slot_rows synchronised each stage's stream), and // nothing in flight reads the cache slots a swap overwrites; the swapped-in experts are landed (apply_pending) // before this window ends, so no other path (a prompt chunk read between windows, a loan of cache slots, a KV - // growth) ever meets swaps in flight. Not while a prompt holds a loan of cache slots: its lent experts are - // marked missing and are put back when the loan ends. + // growth) ever meets swaps in flight. Not between a prompt's chunks: a loan of cache slots marks its lent + // experts missing, and they are put back when the loan ends. (With --adapt-async the tier is ticked above.) struct AdaptRun { std::thread th; bool ok = true; ~AdaptRun() { if (th.joinable()) th.join(); } // an error return below still joins it } adapt_run; - if (!drive.d.usage.empty() && !ajob && (++ba_window % o.adapt_every) == 0 && pending.empty() && - std::none_of(pf_parts.begin(), pf_parts.end(), [](const PfPart& p) { return !p.lent.empty(); })) + if (!drive.d.usage.empty() && !ajob && !in_prompt_read && (++ba_window % o.adapt_every) == 0 && pending.empty()) adapt_run.th = std::thread([&] { adapt_run.ok = adapt(); }); // Accept the proposal only when the target picked it and there is room to emit both tokens. std::vector keep(bs.size(), 0); @@ -9084,7 +9109,11 @@ int main(int argc, char** argv) { per_stage += sb; } char adapt_txt[160] = ""; - if (!drive.d.usage.empty()) + if (!drive.d.usage.empty() && ajob) + std::snprintf(adapt_txt, sizeof adapt_txt, + "; adaptive tier (async): %lld rounds started, %lld experts swapped in", + (long long) (a_rounds - bt_a_rounds0), (long long) (a_swapped - bt_a_swapped0)); + else if (!drive.d.usage.empty()) std::snprintf(adapt_txt, sizeof adapt_txt, "; adaptive tier: %lld rounds, %lld experts swapped in", (long long) bt_adapt_rounds, (long long) bt_adapt_swaps); std::fprintf(stderr, "strata batch: %lld windows, avg %.2f rows, %.2f ms/window = run %.2f (CUDA0 GPU-reach " @@ -9272,6 +9301,12 @@ int main(int argc, char** argv) { std::fflush(stdout); continue; } + // a command may touch the expert cache (a request lends slots, a K/V growth moves them, a session restore + // quiesces it): a round of the asynchronous tier that the batch windows left in flight lands first + if (!adapt_tick(true)) { + std::printf("ERR an adaptive refill failed\n"); + return 1; + } admit_slot = -1; if (line.rfind("BGEN ", 0) == 0 || line.rfind("BGENI ", 0) == 0) { const bool bimg = line.rfind("BGENI ", 0) == 0; @@ -10404,9 +10439,11 @@ int main(int argc, char** argv) { if (decode_share <= 0.0 || !batch_on()) continue; const double budget = decode_share * std::chrono::duration(Clock::now() - tq).count(); const auto td = Clock::now(); + in_prompt_read = true; do { - if (!batch_step()) { batch_fatal = true; e = "a batch window failed"; return false; } + if (!batch_step()) { in_prompt_read = false; batch_fatal = true; e = "a batch window failed"; return false; } } while (batch_on() && std::chrono::duration(Clock::now() - td).count() < budget); + in_prompt_read = false; ++il_parts; il_ms += std::chrono::duration(Clock::now() - td).count(); if (trace) { From b5d520313a3fdc506c8466a049fea353e3b25893 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 16:04:03 -0400 Subject: [PATCH 09/19] batch-groups: --adapt-async 1 also keeps the 0.1.41 auto default at one group (said once) The pipelined slot groups never run the adaptive tier, so --adapt-async 1 with --batch on a layer split and no --batch-groups resolves auto to one group, like --batch-mtp (batch_groups.hpp, batch_groups_test); --batch-groups G or auto given on the command line is honoured and turns --adapt-async off through the existing gate. --- docs/BATCHING.md | 2 +- include/strata/program/batch_groups.hpp | 21 ++++++++++++--------- src/program/batch_groups_test.cpp | 19 ++++++++++++++++--- src/program/generate.cpp | 9 +++++---- 4 files changed, 34 insertions(+), 17 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 4217c60b..c739615e 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -84,7 +84,7 @@ With a layer split, the engine options go into the config's `args`: | --- | --- | | `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | | `--batch-groups G` | with a layer split (default: auto, below): the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | -| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--batch-mtp` and no `--batch-groups` the default is one group (the slots' MTP drafts do not run in pipelined groups) and the log says so; `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off. | +| `--batch-groups auto` | the default on a layer split since 0.1.41 (give no `--batch-groups`): the engine pipelines one group per GPU stage (the most that divide the slots; 8 slots on 4 GPUs = 4 groups of 2) and says so (`INFO batch_groups=G`). `--batch-groups 1` turns it off (all slots in one window, GPU after GPU). Measured, 8 clients, total tok/s against one group: 4 x R9700 166 against 86, 2 GPUs 109 against 78, 3 GPUs 110 against 78. With `--batch-mtp` or `--adapt-async 1` and no `--batch-groups` the default is one group (the slots' MTP drafts and the adaptive tier between batch windows do not run in pipelined groups) and the log says so; `--batch-groups G` or `--batch-groups auto` given with `--batch-mtp` pipelines the groups and turns `--batch-mtp` off, and given with `--adapt-async 1` pipelines the groups and turns `--adapt-async` off (the pipelined path does not adapt). | | `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by diff --git a/include/strata/program/batch_groups.hpp b/include/strata/program/batch_groups.hpp index 0cc7c1d9..e0d87589 100644 --- a/include/strata/program/batch_groups.hpp +++ b/include/strata/program/batch_groups.hpp @@ -2,9 +2,10 @@ // // `--batch-groups N` pipelines N groups of slots through the stages of a layer split; `--batch-groups auto` picks the // most groups (at most one per stage) that divide the slots. Since 0.1.41 a layer split with `--batch` >= 2 and no -// `--batch-groups` at all means `auto`. The pipelined path does not run `--batch-mtp`'s drafts, so when `--batch-mtp` -// is asked for and the number of groups was NOT given, `auto` resolves to one group (the serial windows the drafts run -// in) and says why. A number or `auto` given on the command line is honoured as before. +// `--batch-groups` at all means `auto`. The pipelined path does not run `--batch-mtp`'s drafts or the batch +// adaptive tier (`--adapt-async 1` between batch windows), so when one of those is asked for and the number of groups +// was NOT given, `auto` resolves to one group (the serial windows they run in) and says why. A number or `auto` +// given on the command line is honoured as before. // // Pure (no GPU, no environment read): generate.cpp passes in what it knows. #pragma once @@ -12,7 +13,7 @@ namespace strata::program::batch_groups { /// What kept `auto` from pipelining. -enum class Serial { None, BatchMtp }; +enum class Serial { None, BatchMtp, AdaptAsync }; struct Input { bool set = false; ///< --batch-groups was given (a number or `auto`) @@ -21,12 +22,13 @@ struct Input { int batch = 0; ///< the slots int later_stages = 0; ///< the layer split's stages after CUDA0 (0: no layer split) bool batch_mtp = false; ///< --batch-mtp is on (it passed the gates that do not concern the groups) + bool adapt_async = false; ///< --adapt-async 1 was asked for }; struct Result { int groups = 1; bool from_auto = false; ///< the number came from `auto` (given or the 0.1.41 default) - Serial serial = Serial::None; ///< `auto` would have pipelined, but --batch-mtp needs the serial windows + Serial serial = Serial::None; ///< `auto` would have pipelined, but this feature needs the serial windows int would_be = 1; ///< what `auto` would have picked without it (== groups unless `serial`) }; @@ -48,15 +50,16 @@ inline Result resolve(const Input& in) { r.from_auto = true; r.would_be = auto_groups(in.later_stages, in.batch); r.groups = r.would_be; - if (!in.set && r.would_be > 1 && in.batch_mtp) { // only the default gives way; `--batch-groups auto` asked for the pipeline - r.serial = Serial::BatchMtp; - r.groups = 1; + if (!in.set && r.would_be > 1) { // only the default gives way; `--batch-groups auto` asked for the pipeline + if (in.batch_mtp) r.serial = Serial::BatchMtp; + else if (in.adapt_async) r.serial = Serial::AdaptAsync; + if (r.serial != Serial::None) r.groups = 1; } return r; } inline const char* serial_what(Serial s) { - return s == Serial::BatchMtp ? "--batch-mtp" : ""; + return s == Serial::BatchMtp ? "--batch-mtp" : s == Serial::AdaptAsync ? "--adapt-async 1" : ""; } } // namespace strata::program::batch_groups diff --git a/src/program/batch_groups_test.cpp b/src/program/batch_groups_test.cpp index 065fd5f6..19145638 100644 --- a/src/program/batch_groups_test.cpp +++ b/src/program/batch_groups_test.cpp @@ -2,8 +2,8 @@ // // 1. `auto` picks the most groups, at most one per stage, that divide the slots; // 2. a layer split with --batch >= 2 and no --batch-groups means `auto` (0.1.41); -// 3. --batch-mtp turns that default into one group, and says which feature did it; -// 4. a number or `auto` given explicitly is honoured, with or without --batch-mtp; +// 3. --batch-mtp (or --adapt-async 1) turns that default into one group, and says which feature did it; +// 4. a number or `auto` given explicitly is honoured, with or without those features; // 5. no layer split: the number given (1) stays. #include "strata/program/batch_groups.hpp" @@ -46,7 +46,7 @@ int main() { check(r.groups == 1 && !r.from_auto, "no layer split: one group"); } - { // the shape this is for: parallel 2 on a 2-GPU split with --batch-mtp + { // the production shape: parallel 2 on a 2-GPU split with --batch-mtp bg::Input i = in(2, 1); i.batch_mtp = true; const auto r = bg::resolve(i); @@ -54,6 +54,18 @@ int main() { "--batch-mtp, nothing given: one group, because of --batch-mtp"); check(bg::serial_what(r.serial)[0] == '-', "the reason names the feature"); } + { + bg::Input i = in(2, 1); + i.adapt_async = true; + const auto r = bg::resolve(i); + check(r.groups == 1 && r.serial == bg::Serial::AdaptAsync, "--adapt-async 1, nothing given: one group"); + } + { + bg::Input i = in(2, 1); + i.batch_mtp = true; + i.adapt_async = true; + check(bg::resolve(i).serial == bg::Serial::BatchMtp, "both: --batch-mtp is named"); + } { // nothing to give way: the slots do not divide, so auto is one group anyway and there is nothing to say bg::Input i = in(3, 1); i.batch_mtp = true; @@ -65,6 +77,7 @@ int main() { i.set = true; i.given = 2; i.batch_mtp = true; + i.adapt_async = true; const auto r = bg::resolve(i); check(r.groups == 2 && !r.from_auto && r.serial == bg::Serial::None, "--batch-groups 2 with --batch-mtp: 2"); i.given = 1; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7b89e141..5619988d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4125,9 +4125,9 @@ int main(int argc, char** argv) { // With a layer split the slots' drafters live on the LAST stage's GPU (where the solo drafter, the head and the final // residual rows are); the windows are the ones --batch runs, two rows per slot, through every stage. // --batch-groups: given as a number or auto, or (0.1.41) auto by default for a layer split with --batch >= 2. The - // pipelined slot groups do not run --batch-mtp's drafts, so when it is asked for and the groups were not given, the - // default is one group (batch_groups.hpp). Evaluated again once the slots that fit are known, and BEFORE the - // --batch-mtp gate below, which must see the resolved number. + // pipelined slot groups run neither --batch-mtp's drafts nor the batch adaptive tier (--adapt-async 1), so when one of + // them is asked for and the groups were not given, the default is one group (batch_groups.hpp). Evaluated again + // once the slots that fit are known, and BEFORE the --batch-mtp gate below, which must see the resolved number. auto batch_groups_for = [&](bool mtp_on) { strata::program::batch_groups::Input bin; bin.set = o.batch_groups_set; @@ -4136,6 +4136,7 @@ int main(int argc, char** argv) { bin.batch = o.batch; bin.later_stages = (int) stages.size(); bin.batch_mtp = mtp_on; + bin.adapt_async = o.adapt_async != 0; return strata::program::batch_groups::resolve(bin); }; const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP"); @@ -4174,7 +4175,7 @@ int main(int argc, char** argv) { // --batch-groups auto: the pipeline needs one group per GPU stage to keep every card busy (4 x R9700, 8 clients: // 90 tok/s in one group, 136 in 2, 166 in 4). The most groups, at most one per stage, that divide the slots. // The default (0.1.41: a layer split with --batch pipelines one group per stage; --batch-groups 1 opts out) gives - // way to --batch-mtp, which needs the serial windows: one group, said once. + // way to --batch-mtp and --adapt-async 1, which need the serial windows: one group, said once. int groups_said = 0; auto resolve_groups_auto = [&] { const auto r = batch_groups_for(batch_mtp); From 2eafe7f90da2a9cde892b0bed0da5f7ae423e0d8 Mon Sep 17 00:00:00 2001 From: noon-at-cgn <75719527+noon-at-cgn@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:41:56 -0400 Subject: [PATCH 10/19] docs: the adaptive tier in batch windows - measured on 2x RTX 3080 20 GB, tier on, blocking, frozen and off --- docs/BATCHING.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index c739615e..b90cadcd 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -160,6 +160,23 @@ routing count of the expert coming in against the one going out), so fewer exper The log line's `adapt wait` is the time the main thread spent on the tier per window (the blocking tier: waiting for its round). +Measured with the same setup as the `--batch-mtp` numbers above (2x RTX 3080 20 GB, UD-Q4_K_XL, `"layer_split": "23"`, +`"parallel": 2`, `--batch-mtp`, engine 0.1.41 with our production stack; two concurrent greedy decodes, the streams' +tok/s added, median of 20 measurements per restart): + +| tier | aggregate tok/s | restarts | per window | routed entries served from VRAM | +| --- | --- | --- | --- | --- | +| `--adapt-async 1 --adapt-every 2` | **89.2** | 3 | 34.6 ms, adapt wait 0.2 ms | 92.1% | +| blocking, `--adapt-every 2` | 74.7 | 1 | 41.4 ms, adapt wait 8.4 ms | 92.3% | +| none, the cache frozen from a profile the tier had learned on the same prompts | 69.5 | 1 | 43.6 ms | 77.2% | +| none, `--adapt-every 0` | 45.2 | 2 | 66-68 ms | 52.7% | + +The switch changes the tier in the solo path as well (there is no switch for batch windows alone), so the table +compares the tier as a whole, not "batch windows only": the solo decode speed moves the same way (81.7, 66.3, 69.0 and +43.1 tok/s). The prompts are the benchmark's own, eight topics that repeat, which the tier learns quickly, so on a +more varied workload the gain may be smaller (not measured). Upstream main runs no tier in batch windows, and this +was not measured against an upstream binary. + ## Exactness A batch row's arithmetic is the single-token window's, so with greedy decoding **every conversation of a batch From 3a55dfd253e0807973de8091235f8786c4498dcd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 15:19:04 +0200 Subject: [PATCH 11/19] HIP: STRATA_HEAD_MIX_MULTI and STRATA_ONE_TOKEN_COMMIT as opt-ins (=1), default stays off (#1479) Patch from the issue by jkuepker. Co-authored-by: jkuepker <20614147+jkuepker@users.noreply.github.com> --- src/core/mtp.cpp | 3 ++- src/core/verify.cpp | 12 ++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 4edcea80..03bcdf5f 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -857,7 +857,8 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) { }(); static const bool head_mix_multi_on = [] { #if defined(STRATA_USE_HIP) - return false; + const char* v = std::getenv("STRATA_HEAD_MIX_MULTI"); // HIP: opt-in (=1) + return v != nullptr && std::atoi(v) != 0; #else const char* v = std::getenv("STRATA_HEAD_MIX_MULTI"); return v == nullptr || std::atoi(v) != 0; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 8f70e022..518cbc21 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -190,7 +190,11 @@ bool sh_stream_on() { // STRATA_HEAD_MIX_MULTI=0 does too): bitwise the same sums. bool head_mix_multi_enabled() { #if defined(STRATA_USE_HIP) - return false; + static const bool on = [] { + const char* v = std::getenv("STRATA_HEAD_MIX_MULTI"); // HIP: opt-in (=1) + return v != nullptr && std::atoi(v) != 0; + }(); + return on; #else static const bool on = [] { const char* v = std::getenv("STRATA_HEAD_MIX_MULTI"); @@ -202,7 +206,11 @@ bool head_mix_multi_enabled() { bool one_token_self_commit() { #if defined(STRATA_USE_HIP) - return false; + static const bool on = [] { + const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT"); // HIP: opt-in (=1) + return v != nullptr && std::atoi(v) != 0; + }(); + return on; #else static const bool on = [] { const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT"); From 52f548f45afae83f580c1ef858668942bf11b06d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 15:20:31 +0200 Subject: [PATCH 12/19] server: death_note scans the last 256 KB for the watchdog line, so a long verify trace cannot hide it (#1705) --- serve/server.py | 10 ++++++---- serve/test_server.py | 12 ++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/serve/server.py b/serve/server.py index c21f335a..0f034bc2 100644 --- a/serve/server.py +++ b/serve/server.py @@ -797,15 +797,17 @@ class StrataEngine: """Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM.""" if getattr(self, "silent_note", None): # #481: the server ended it, not the OS or the engine itself return self.silent_note - tail = "" + tail = wide = "" try: with open(self.log_path, "rb") as f: f.seek(0, 2) - f.seek(max(0, f.tell() - 4096)) - tail = f.read().decode("utf-8", "replace") + f.seek(max(0, f.tell() - 262144)) + wide = f.read().decode("utf-8", "replace") + tail = wide[-4096:] except (OSError, TypeError): pass - for line in reversed(tail.splitlines()): + # #1705: STRATA_VERIFY_TRACE dumps are ~30 KB and push the watchdog's line out of a 4 KB tail + for line in reversed(wide.splitlines()): if "issue #29" in line: return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log " "line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.") diff --git a/serve/test_server.py b/serve/test_server.py index ccd8408c..2fd3a4b1 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -4072,6 +4072,18 @@ class SilentEngine(unittest.TestCase): self.assertIn("#481", engine.death_note()) self.assertNotIn("STOP", engine.proc.stdin.getvalue()) # nothing is listening: no STOP, no drain + def test_death_note_finds_the_watchdog_line_under_a_long_trace(self): + # #1705: STRATA_VERIFY_TRACE dumps (~30 KB) after the watchdog's line must not hide it + import tempfile + engine = self.bare(0.3) + with tempfile.TemporaryDirectory() as d: + engine.log_path = os.path.join(d, "e.log") + with open(engine.log_path, "w", encoding="utf-8") as f: + f.write("strata serve: no progress for 60 s during a request (issue #29)\n") + f.write("strata verify trace: dump\n" * 1500) + engine.proc.poll.return_value = -6 + self.assertIn("a hang it caught", engine.death_note()) + def test_prompt_chunks_set_the_wait(self): # a PP line every second, at 100 tok/s: far over a 0.3 s silence, but each chunk is on time for its size engine = self.bare(0.3) From 92507aac3833fb0b389c4369bd3fc3fa63b75901 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 15:24:07 +0200 Subject: [PATCH 13/19] setup: on a unified-memory APU write the expert cache as a number that leaves the OS its RAM, not auto (#1715) --- docs/STRIX_HALO.md | 1 + setup.py | 28 +++++++++++++++++++++++++ tools/test_setup_unsloth.py | 42 +++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) diff --git a/docs/STRIX_HALO.md b/docs/STRIX_HALO.md index 85a908c9..6365cac7 100644 --- a/docs/STRIX_HALO.md +++ b/docs/STRIX_HALO.md @@ -20,6 +20,7 @@ What the engine does differently on this chip: - **The hipBLASLt table** `tools/hip/gfx1151-hipblaslt-100401.txt` (ROCm 7.14.1's hipBLASLt 1.x `100401`), including the prompt shapes at `--prefill 16384` (T 16383 / 16384). Setup's own ROCm for gfx1151 (the 7.14.0a20260608 wheels, hipBLASLt 1.4.0) takes `tools/hip/gfx1151-hipblaslt-100400.txt`: the same shapes, calibrated against that library (docs/AMD_HIP.md, Tuning table). +- **The expert cache and the RAM budget share the RAM.** For a model with a RAM budget (UD-IQ4_XS, UD-Q4_K_XL) setup writes a number for `--expert-cache` (the RAM less 24 GB less the budget), not `auto`: `auto` counts all the memory the OS can give back at start, and with a 55 GiB budget and a desktop open it took the room the OS needed (#1715, a global OOM on a 128 GB box). The number is in the config's `args`; `--expert-cache N` there sets it. An engine run by hand should pass one too. ## 1. The toolchain (no root needed) diff --git a/setup.py b/setup.py index 321e2bc9..2ba9740e 100644 --- a/setup.py +++ b/setup.py @@ -1538,6 +1538,22 @@ def resident_budget_gib(model, ram, kv_ram_gb=0.0) -> int: return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824))) +UMA_EXPERTS = 24576 # the Flash-Next model's experts (48 layers x 512): the most an expert cache can hold + + +def uma_expert_cache(model, ram, budget_gib, kv_ram_gb=0.0): + """#1715: on a unified-memory APU (Strix Halo) the GPU's expert cache and the RAM budget of experts are both RAM. + `--expert-cache auto` sizes the cache from the memory the OS can give back at start, which counts all the RAM the + budget has not taken yet: a 128 GB box with a 55 GiB budget and the desktop open was killed by the OOM killer. So + there setup writes a number, not `auto`: the RAM less UNSLOTH_RAM_LEFT_GB less the budget (and a KV cache streamed + to RAM), in slots (an expert is priced at 1.1x the average one: the Q8_0 downs are bigger). None when no room is left + (the config keeps `auto`). A recommendation: the number is in the config's args, and --expert-cache N there sets it.""" + slot_gib = MODELS[model]["arena_gb"] * 1e9 / UMA_EXPERTS * 1.1 / 2**30 + room = ram - UNSLOTH_RAM_LEFT_GB - budget_gib - math.ceil(kv_ram_gb) + slots = min(UMA_EXPERTS, int(room / slot_gib)) + return slots if slots >= 256 else None + + def budget_choice(model, ram, asked) -> float: """S4: UD-Q4_K_XL's RAM budget: --resident-budget-gib N as given, else the recommendation (resident_budget_gib). More than the recommendation is kept, with what it risks (the owner's rule: setup recommends, it never forces).""" @@ -5478,6 +5494,18 @@ def main() -> int: warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off") if budget is not None and not q4_split: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N args += ["--resident-budget-gib", f"{budget:g}"] # GiB kept in RAM (#498: a layer split had no budget) + if gpu.get("uma") and "--expert-cache" in args: + # #1715: the cache and the budget draw on the same RAM: a number that leaves the OS its room, not `auto` + slots = uma_expert_cache(model, ram, budget, kv_ram_gb if "--kv-resident" in args else 0.0) + if slots is not None: + args[args.index("--expert-cache") + 1] = str(slots) + ok(f"expert cache: {slots} slots (not auto): this GPU shares the RAM with the {budget:g} GiB budget, " + f"so setup leaves {UNSLOTH_RAM_LEFT_GB} GB of the RAM for the OS and the desktop (#1715). " + "--expert-cache N in the config's args sets it") + else: + warn(f"this GPU shares the RAM, and the {budget:g} GiB RAM budget leaves almost none for the expert " + "cache: it stays on auto, which may take the room the OS needs (#1715). A smaller " + "--resident-budget-gib leaves room") if vision != "none": args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])] if vision == "gpu" and a.vram_reserve_mib is None and 0 < gpu.get("vram_gb", 0.0) <= 12.5: diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index b9ba0536..27a7b9a3 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -556,6 +556,48 @@ class IQ4XS(Base): self.assertIn("RAM budget: 40 GiB of UD-IQ4_XS's experts", out) +class StrixHaloCache(Base): + """#1715: on a unified-memory APU the expert cache and the RAM budget are the same RAM: setup writes a cache size + that leaves the OS room, not `--expert-cache auto` (it OOM-killed a 128 GB Strix Halo with the desktop open).""" + + HALO = [{"index": 0, "name": "AMD Radeon 8060S", "vram_gb": 2.0, "arch": "gfx1151", "driver": "amdgpu", + "uma": True, "dedicated_gb": 2.0, "shared_gb": 112.0}] + + def run_halo(self, ram, argv=("--context", "8192"), amd=None): + with mock.patch.object(setup, "get_prebuilt_hip", lambda *a, **k: self.t / "engine"), mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "build_engine_hip", lambda *a, **k: self.t / "engine"): + return self.main([*argv, "--backend", "hip"], version="0.1.41", amd=self.HALO if amd is None else amd, + ram=ram, m="UD-IQ4_XS") + + def test_cache_is_a_number_that_leaves_room(self): + code, out, cfg = self.run_halo(124.0) + self.assertEqual(code, 0, out) + args = cfg["args"] + self.assertEqual(args[args.index("--resident-budget-gib") + 1], "55") + slots = int(args[args.index("--expert-cache") + 1]) + # 124 - 24 (left) - 55 (budget) = 45 GiB of 1.1 x the average expert (59.5 GB / 24576) + self.assertEqual(slots, int(45 / (59.5e9 / setup.UMA_EXPERTS * 1.1 / 2**30))) + self.assertTrue(0 < slots < setup.UMA_EXPERTS) + self.assertIn("expert cache: %d slots (not auto)" % slots, out) + + def test_never_more_than_all_the_experts(self): + self.assertEqual(setup.uma_expert_cache("UD-IQ4_XS", 512.0, 55), setup.UMA_EXPERTS) + + def test_no_room_keeps_auto_and_says_so(self): + self.assertIsNone(setup.uma_expert_cache("UD-IQ4_XS", 64.0, 40)) + code, out, cfg = self.run_halo(64.0, ("--context", "8192", "--resident-budget-gib", "40")) + self.assertEqual(code, 0, out) + args = cfg["args"] + self.assertEqual(args[args.index("--expert-cache") + 1], "auto") + self.assertIn("leaves almost none for the expert cache", out) + + def test_a_discrete_card_keeps_auto(self): + r9700 = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201", + "driver": "amdgpu"}] + code, out, cfg = self.run_halo(124.0, amd=r9700) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["args"][cfg["args"].index("--expert-cache") + 1], "auto") + + class LayerSplit(unittest.TestCase): """#498: UD-Q4_K_XL across GPUs - asked at setup (one GPU by default), and a start with --gpus no longer keeps the RAM budget the engine refused with a split (it exited with code 2). #642: from RESIDENT_SPLIT_ENGINE the From 115e8ce33463dbd8598d0d10743bb31362223c58 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 15:50:58 +0200 Subject: [PATCH 14/19] Windows HIP: the auto cache's 2560 MiB reserve floor also covers 16 GB cards (they report 15.9 GiB) (#1709; Windows HIP test pending) --- src/program/generate.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 5619988d..694aa0ac 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4617,7 +4617,7 @@ int main(int argc, char** argv) { // windows, the prompt path) comes out of the reserve. 0.1.40 ended a 20 GB RX 7900 XT with 2,170 MiB free // (its write-back check cut the cache); 0.1.40.2 passed that check with the default 700 MiB and ended with // 323 MiB, where Windows paged and decode fell from 52 to 21-25 tok/s. --vram-reserve-mib 2600 fixed it. So on - // Windows HIP an auto cache on a card of 16 GiB or more keeps a floor of kWddmAutoReserveMib. CUDA on Windows is + // Windows HIP an auto cache on a card of 16 GB (15 GiB and up, #1709) keeps a floor of kWddmAutoReserveMib. CUDA on Windows is // left as it was: the same 0.1.40 / 0.1.40.2 pair on an RTX 5070 ended with the same slots and free VRAM, and a // floor there would only cost 16 GB+ NVIDIA cards ~1.8 GiB of cache. A reserve given on the command line is // kept as it is; a smaller card keeps its own sizing (#496 lowers the reserve further when the cache would not @@ -4626,7 +4626,8 @@ int main(int argc, char** argv) { if (!o.vram_reserve_given && o.vram_reserve_mib < kWddmAutoReserveMib) { #if defined(_WIN32) && defined(STRATA_USE_HIP) size_t fb_now = 0, tb_now = 0; - if (cudaMemGetInfo(&fb_now, &tb_now) == cudaSuccess && tb_now >= (16ull << 30)) { + // #1709: a 16 GB card (RX 9070 XT, 7800 XT) reports 15.9 GiB, just under 16: the floor is for 15 GiB and up + if (cudaMemGetInfo(&fb_now, &tb_now) == cudaSuccess && tb_now >= (15ull << 30)) { std::fprintf(stderr, "strata generate: expert cache auto: Windows keeps %d MiB free after the cache on a card " "this size (the default %d MiB left 323 MiB on a 20 GB card and Windows paged, #1376); " "--vram-reserve-mib N sets it\n", kWddmAutoReserveMib, o.vram_reserve_mib); From 94bf9e58703bddfe0d5109574220ac7e47b68d8c Mon Sep 17 00:00:00 2001 From: Andrey Bash <117385366+0FL01@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:00:51 +0300 Subject: [PATCH 15/19] perf(gfx906): add guarded opt-in query LDS swizzle for batched QSA Preserve FP operation order and invert a bijective shared-query layout at its vector loads. Limit the path to the current gfx906 wave64 device, INT8 pools and warp scoring. Default remains off. Add deterministic GPU parity/timing and host-guard probes, plus scoped component and model receipts. The clean upstream build passed both-card byte checks; model gains are recorded separately on the frozen experimental stack. --- CMakeLists.txt | 5 + bench/gfx906_qsa_query_swizzle_probe.cpp | 284 ++++++++++ .../README.md | 104 ++++ .../results.json | 519 ++++++++++++++++++ bench/test_gfx906_qsa_query_swizzle_guard.py | 130 +++++ src/kernels/cuda/qsa_decode_attn.cu | 70 ++- 6 files changed, 1108 insertions(+), 4 deletions(-) create mode 100644 bench/gfx906_qsa_query_swizzle_probe.cpp create mode 100644 bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md create mode 100644 bench/results/2026-10-08-gfx906-qsa-query-swizzle/results.json create mode 100644 bench/test_gfx906_qsa_query_swizzle_guard.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ac489599..a02445b0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1608,3 +1608,8 @@ if(STRATA_HIP_GFX906) endif() set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP) endif() + +if(STRATA_HIP_GFX906) + add_executable(gfx906_qsa_query_swizzle_probe bench/gfx906_qsa_query_swizzle_probe.cpp) + target_link_libraries(gfx906_qsa_query_swizzle_probe PRIVATE strata_kernels ${_strata_gpu_runtime_target}) +endif() diff --git a/bench/gfx906_qsa_query_swizzle_probe.cpp b/bench/gfx906_qsa_query_swizzle_probe.cpp new file mode 100644 index 00000000..da4d8bf0 --- /dev/null +++ b/bench/gfx906_qsa_query_swizzle_probe.cpp @@ -0,0 +1,284 @@ +// Standalone HIP INT8 QSA query-LDS-swizzle component probe. +// Adapted from the cell-probability probe; input generation and full-byte dump are unchanged. +// Build/link in the project with strata_kernels + hip::host (or its HIP runtime target). +// Usage: gfx906_qsa_query_swizzle_probe [nq=32] [ctx=65536] [reps=20] [output.bin] [--masked-pages] +// Output path may instead be supplied by STRATA_QSA_PROBE_OUT. It is required. +// Run candidate environment settings in SEPARATE processes: the dispatcher caches them. +// No prompt-attention entry point, architecture skip, model loading, or repository writes. +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; +namespace { +constexpr int64_t kBatch = 32; +constexpr size_t kGuard = 64; +constexpr uint64_t kSeed = 0x7161736150524f42ull; + +[[noreturn]] void fail(const char* why) { + std::fprintf(stderr, "qsa_query_swizzle_probe: %s\n", why); + std::exit(2); +} +void ck(hipError_t e, const char* what) { + if (e != hipSuccess) { + std::fprintf(stderr, "%s: %s\n", what, hipGetErrorString(e)); + std::exit(2); + } +} +#define HIP_CHECK(x) ck((x), #x) + +// Fixed integer generator and exact binary fractions avoid library-dependent +// normal distributions and never inspect the candidate environment setting. +struct Rng { + uint64_t state = kSeed; + uint32_t next() { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + return uint32_t((state * 2685821657736338717ull) >> 32); + } + size_t below(size_t n) { return size_t(next()) % n; } + template void shuffle(std::vector& v) { + for (size_t n = v.size(); n > 1; --n) std::swap(v[n - 1], v[below(n)]); + } +}; + +template struct Device { + T* p = nullptr; + explicit Device(size_t n) { HIP_CHECK(hipMalloc(reinterpret_cast(&p), n * sizeof(T))); } + explicit Device(const std::vector& v) : Device(v.size()) { + HIP_CHECK(hipMemcpy(p, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice)); + } + ~Device() { if (p) (void) hipFree(p); } + Device(const Device&) = delete; + Device& operator=(const Device&) = delete; +}; + +uint64_t hash_bytes(uint64_t hash, const void* ptr, size_t bytes) { + const auto* p = static_cast(ptr); + for (size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull; + return hash; +} +template void hash_vector(uint64_t& hash, const std::vector& v) { + hash = hash_bytes(hash, v.data(), v.size() * sizeof(T)); +} +int64_t positive(const char* text) { + errno = 0; + char* end = nullptr; + const long long n = std::strtoll(text, &end, 10); + if (errno || end == text || *end || n <= 0 || n > INT32_MAX) + fail("nq, ctx, and reps must be positive int32 values"); + return int64_t(n); +} +const char* env(const char* name) { + const char* value = std::getenv(name); + return value ? value : ""; +} + +std::vector read_checked(const Device& storage, size_t count) { + std::vector host(count + 2 * kGuard); + HIP_CHECK(hipMemcpy(host.data(), storage.p, host.size() * sizeof(float), hipMemcpyDeviceToHost)); + for (size_t i = 0; i < host.size(); ++i) { + if (i >= kGuard && i < kGuard + count) { + if (!std::isfinite(host[i])) { + std::fprintf(stderr, "nonfinite or unwritten output at float %zu\n", i - kGuard); + fail("output check failed"); + } + } else { + uint32_t bits; + std::memcpy(&bits, &host[i], sizeof(bits)); + if (bits != UINT32_MAX) fail("output guard changed"); + } + } + return std::vector(host.begin() + kGuard, host.begin() + kGuard + count); +} + +int run(int64_t nq, int64_t ctx, int reps, const char* output, bool masked) { + if (ctx < nq) fail("ctx must be >= nq (query positions are ctx-nq through ctx-1)"); + const char* lane = std::getenv("STRATA_ATTN_LANECELL"); + if (lane && lane[0] == '1') fail("unset STRATA_ATTN_LANECELL or set it to 0 for this probe"); + static_assert(sizeof(float) == 4 && std::numeric_limits::is_iec559, + "probe requires IEEE binary32 output"); + const k::QsaShapes s = k::qsa_real_shapes(); + // Match prefill.cpp: use the model's actual 4-cell page layout. + if (s.n_head != 24 || s.n_head_kv != 2 || s.head_dim != 256 || s.page_size != 4) + fail("unexpected model geometry"); + const int64_t hd = s.head_dim, nh = s.n_head, nkvh = s.n_head_kv, ps = s.page_size; + const int64_t pages = (ctx + ps - 1) / ps, rows = pages * nkvh * ps; + const int64_t cap = k::qsa_selection_width(ctx, s); + const size_t count = size_t(nq) * size_t(nh * hd); + Rng rng; + std::vector kq(size_t(rows * hd)), vq(kq.size()); + std::vector ks(size_t(rows * (hd / 64))), vs(ks.size()); + for (auto* v : {&kq, &vq}) + for (auto& x : *v) x = int8_t(int(rng.next() % 255) - 127); + // Positive finite binary16 scales, directly encoded: [2^-8, 2^-5). + for (auto* v : {&ks, &vs}) + for (auto& x : *v) x = uint16_t(0x1c00u + rng.next() % 0x0c00u); + std::vector table(size_t(pages), 0); + std::iota(table.begin(), table.end(), 0); + rng.shuffle(table); + const auto physical = table; + if (masked) + for (int64_t page = 1; page < pages; page += 3) table[size_t(page)] = -1; + + // The decode kernel reads ids[c0+t] only for t ids(size_t(nq * cap) + kGuard, 0); + std::vector steps(size_t(nq * k::kStepCount), 0); + std::vector query(count); + for (auto& x : query) x = float(int(rng.next() % 4096) - 2048) * (1.0f / 1024.0f); + std::vector old_cells; + for (int64_t i = 0; i < nq; ++i) { + const int64_t pos = ctx - nq + i, nkv = pos + 1; + const int64_t width = k::qsa_selection_width(nkv, s); + k::qsa_step_fill(steps.data() + i * k::kStepCount, pos, s); + int32_t* sel = ids.data() + i * cap; + if (width == nkv) { + std::iota(sel, sel + width, 0); + } else { + // Same selection pattern as qsa_prompt_attn_parity: a recent + // 512-cell window plus a sorted older set drifting ~3% per query. + constexpr int64_t recent = 512; + const int64_t older = width - recent; + if (int64_t(old_cells.size()) != older) { + std::vector all(size_t(nkv - recent), 0); + std::iota(all.begin(), all.end(), 0); + rng.shuffle(all); + old_cells.assign(all.begin(), all.begin() + older); + } else { + for (int64_t r = 0; r < older / 32; ++r) { + const int32_t cell = int32_t(rng.below(size_t(nkv - recent))); + if (std::find(old_cells.begin(), old_cells.end(), cell) == old_cells.end()) + old_cells[rng.below(size_t(older))] = cell; + } + } + std::copy(old_cells.begin(), old_cells.end(), sel); + std::iota(sel + older, sel + width, int32_t(nkv - recent)); + std::sort(sel, sel + width); + } + bool valid_page = false; + for (int64_t c = 0; c < width; ++c) { + if (sel[c] < 0 || sel[c] >= nkv || (c && sel[c - 1] >= sel[c])) + fail("selection must be unique, sorted, and causal"); + valid_page |= table[size_t(sel[c] / ps)] >= 0; + } + // Restore a selected logical page if necessary, never allow an + // all-masked query to make a vacuous zero-output equality check pass. + if (!valid_page) { + const size_t page = size_t(sel[0] / ps); + table[page] = physical[page]; + } + } + size_t masked_selected = 0; + for (int64_t i = 0; i < nq; ++i) + for (int32_t c = 0; c < steps[size_t(i * k::kStepCount + k::kStepWidth)]; ++c) + masked_selected += table[size_t(ids[size_t(i * cap + c)] / ps)] < 0; + uint64_t input_hash = 14695981039346656037ull; + hash_vector(input_hash, kq); hash_vector(input_hash, vq); + hash_vector(input_hash, ks); hash_vector(input_hash, vs); + hash_vector(input_hash, table); hash_vector(input_hash, ids); + hash_vector(input_hash, steps); hash_vector(input_hash, query); + + Device dk(kq), dv(vq); + Device dks(ks), dvs(vs); + Device dtable(table), dids(ids), dsteps(steps); + Device dq(query), dout(count + 2 * kGuard); + const uint64_t stride = k::qsa_decode_attn_scratch_floats(cap, s); + Device scratch(size_t(std::min(kBatch, nq)) * size_t(stride)); + k::QsaAttnPools pools; + pools.k_q = dk.p; pools.v_q = dv.p; pools.k_scale = dks.p; pools.v_scale = dvs.p; + pools.page_table = dtable.p; + HIP_CHECK(hipMemset(dout.p, 0xff, (count + 2 * kGuard) * sizeof(float))); + HIP_CHECK(hipMemset(scratch.p, 0xff, size_t(std::min(kBatch, nq)) * size_t(stride) * sizeof(float))); + auto launch = [&] { + for (int64_t t = 0; t < nq; t += kBatch) + k::qsa_decode_attn_batch(dq.p + t * nh * hd, pools, dids.p + t * cap, + dsteps.p + t * k::kStepCount, cap, s, scratch.p, dout.p + kGuard + t * nh * hd, + std::min(kBatch, nq - t), nullptr); + HIP_CHECK(hipGetLastError()); + }; + launch(); + HIP_CHECK(hipDeviceSynchronize()); + const auto first = read_checked(dout, count); + constexpr int warmups = 3; + for (int i = 0; i < warmups; ++i) launch(); + HIP_CHECK(hipDeviceSynchronize()); + hipEvent_t begin = nullptr, end = nullptr; + HIP_CHECK(hipEventCreate(&begin)); HIP_CHECK(hipEventCreate(&end)); + std::vector times(size_t(reps), 0.0f); + for (int i = 0; i < reps; ++i) { + // Excluded from event duration; the last timed invocation must also + // overwrite every logical output element instead of inheriting it. + HIP_CHECK(hipMemsetAsync(dout.p + kGuard, 0xff, count * sizeof(float), nullptr)); + HIP_CHECK(hipEventRecord(begin, nullptr)); + launch(); + HIP_CHECK(hipEventRecord(end, nullptr)); + HIP_CHECK(hipEventSynchronize(end)); + HIP_CHECK(hipEventElapsedTime(×[size_t(i)], begin, end)); + } + const auto result = read_checked(dout, count); + if (std::memcmp(first.data(), result.data(), count * sizeof(float)) != 0) + fail("first and final invocation differ byte-for-byte within this process"); + const uint64_t output_hash = hash_bytes(14695981039346656037ull, result.data(), count * sizeof(float)); + std::FILE* file = std::fopen(output, "wb"); + if (!file) fail("cannot open output file"); + const size_t written = std::fwrite(result.data(), sizeof(float), count, file); + const int close_status = std::fclose(file); + if (written != count || close_status != 0) fail("cannot write complete output file"); + std::sort(times.begin(), times.end()); + const float median = reps % 2 ? times[size_t(reps / 2)] + : 0.5f * (times[size_t(reps / 2 - 1)] + times[size_t(reps / 2)]); + int device = 0; + hipDeviceProp_t prop{}; + HIP_CHECK(hipGetDevice(&device)); HIP_CHECK(hipGetDeviceProperties(&prop, device)); + std::printf("device=%s arch=%s nq=%lld ctx=%lld cap=%lld page_size=%lld batch=%lld reps=%d warmups=%d\n", + prop.name, prop.gcnArchName, (long long)nq, (long long)ctx, (long long)cap, + (long long)ps, (long long)kBatch, reps, warmups); + std::printf("QUERY_SWIZZLE=%s LANECELL=%s seed=%016llx masked_pages=%zu masked_selected=%zu\n", + env("STRATA_GFX906_ATTN_QUERY_SWIZZLE"), env("STRATA_ATTN_LANECELL"), (unsigned long long)kSeed, + size_t(std::count(table.begin(), table.end(), -1)), masked_selected); + std::printf("INPUT_FNV1A64=%016llx OUTPUT_FNV1A64=%016llx output_floats=%zu output_bytes=%zu\n", + (unsigned long long)input_hash, (unsigned long long)output_hash, count, count * sizeof(float)); + std::printf("PASS finite_written_guards_and_repeat median_ms=%.6f min_ms=%.6f max_ms=%.6f us_per_query=%.6f output=%s\n", + median, times.front(), times.back(), double(median) * 1000.0 / double(nq), output); + HIP_CHECK(hipEventDestroy(begin)); HIP_CHECK(hipEventDestroy(end)); + return 0; +} +} // namespace + +int main(int argc, char** argv) { + try { + std::vector args; + bool masked = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--masked-pages") == 0) masked = true; + else args.push_back(argv[i]); + } + if (args.size() > 4) fail("usage: probe [nq] [ctx] [reps] [output.bin] [--masked-pages]"); + const int64_t nq = args.size() > 0 ? positive(args[0]) : 32; + const int64_t ctx = args.size() > 1 ? positive(args[1]) : 65536; + const int reps = args.size() > 2 ? int(positive(args[2])) : 20; + const char* output = args.size() > 3 ? args[3] : std::getenv("STRATA_QSA_PROBE_OUT"); + if (!output || !*output) fail("pass output.bin as fourth positional argument or set STRATA_QSA_PROBE_OUT"); + return run(nq, ctx, reps, output, masked); + } catch (const std::exception& e) { + std::fprintf(stderr, "qsa_query_swizzle_probe: %s\n", e.what()); + return 2; + } +} diff --git a/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md new file mode 100644 index 00000000..38c5de49 --- /dev/null +++ b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md @@ -0,0 +1,104 @@ +# QSA query LDS swizzle qualification + +8 October 2026 + +## Conclusion + +The opt-in gfx906 query-LDS swizzle improves the measured INT8 batched-QSA component by **14.646806%** on the final clean upstream patch. It preserves every output byte in the tested component cases. One isolated full-model comparison at 65,536 input tokens and 1,024 generated tokens measures **1.185195% higher prompt throughput** and **1.048564% lower request latency**, with all generated token IDs equal. + +These results support a narrowly scoped, default-off upstream proposal. They do not establish a general speedup across workloads, model-level equivalence beyond the tested pairs, or production readiness. + +## Change and dispatch scope + +The change permutes only the shared-memory query layout in `attn_chunk_kernel`: `q(d) = d XOR ((d >> 3) & 4)`. The scoring loads invert the permutation. The mapping is bijective and self-inverse over the 256 dimensions, preserves 16-byte load alignment and the 12 KiB query tile, and leaves the logical floating-point operands and operation order unchanged. Score reduction, softmax, value accumulation and merge code are unchanged. + +Enable with `STRATA_GFX906_ATTN_QUERY_SWIZZLE=1`; the default is off. The runtime guard requires the calling thread's current device to be exactly gfx906, allowing normal architecture-feature suffixes, with a 64-lane wavefront. It checks the current device on each eligible dispatch, caches properties per thread and last device ordinal, and fails closed on HIP errors. + +The opt-in applies to INT8 pools in `qsa_decode_attn_batch`, including PREFILL, VERIFY and MTP calls with `n_q=1`. A main model using k8v4 can still reach this path through its INT8 MTP drafter. `qsa_decode_attn_step`, other pool formats, lane-cell scoring and other GPU/default paths retain their existing dispatch. + +## Component evidence + +The final parity matrix covers both gfx906 GPUs, both the hardened experimental build and the clean upstream build, both flag states, and these three geometries: + +| Queries | Context | Page masking | Output bytes per run | +|---:|---:|---|---:| +| 1 | 4 | None | 24,576 | +| 33 | 4,096 | Masked pages | 811,008 | +| 32 | 65,536 | None | 786,432 | + +All **24 runs**, representing 12 on/off comparisons across the four build/device combinations, match raw output bytes for their geometry. The probe uses deterministic inputs, shuffled physical pages, finite/output-write checks and output canaries. These checks cover the tested inputs; they are not a general memory-safety proof. The source-extracted host guard test passes **31 mock-HIP checks**, including architecture rejection, device changes, API failures, recovery and independent thread caches. + +The final clean-build timing screen uses GPU 0, `n_q=32`, context 65,536, unmasked pages and separate A/B/B/A processes with 50 repetitions per run. A is flag off; B is flag on. Each value below is a run's measured median for the batched attention component, including chunk and merge. + +| Run | A1 | B1 | B2 | A2 | +|---|---:|---:|---:|---:| +| Median ms | 1.188960 | 1.036240 | 1.036560 | 1.187439 | + +Throughput gain is `(mean(A medians) / mean(B medians) - 1) × 100 = 14.646806%`. This is an A/B/B/A component screen, not a model benchmark or a confidence interval. + +The initial experimental component screen measured 14.791570%, below the predeclared 20% gate. That gate did **not** pass. An explicit cost-benefit exception allowed one bounded 64K/1,024-output model comparison because the layout change was small and the measured component benefit was stable. The final clean-build screen also remains below 20%. + +## Compiled kernel audit + +The compiled baseline and swizzled kernels retain 24 `ds_read_b128` query reads each. The resource comparison is: + +| Property | Baseline | Swizzled | +|---|---:|---:| +| Encoded static instructions | 1,000 | 1,005 | +| VGPRs | 41 | 42 | +| SGPRs | 42 | 42 | +| Total LDS bytes | 15,872 | 15,872 | +| Reported occupancy, waves per SIMD | 4 | 4 | +| Scratch bytes | 0 | 0 | +| SGPR / VGPR spills | 0 / 0 | 0 / 0 | + +An earlier instruction-count script included an ellipsis line and reported 1,001/1,006; the encoded-instruction counts above correct that error. The bank-layout analysis motivates the change, but measured speedup is not a direct hardware bank-conflict-counter measurement. + +Guard hardening preserves the entire disassembled device text, all 10 function symbols, addresses and machine encodings, and the emitted AMDGPU resource notes relative to the qualified experimental kernel. Only the input-object pathname was removed for comparison. HSACO file hashes differ; the differing bytes outside those inspected views have not been located, so no precise cause is claimed. This audit compares pre-hardening and hardened experimental builds; it does not assert whole-binary identity with rebased upstream main. + +## Isolated QSA full-model result + +Both arms use the same experimental HC + grouped-MMQ + PR #1525 dequantization stack; only the QSA query-swizzle flag changes. Fresh native processes use INT8 KV, no prompt reuse, a 65,536-token code prompt and 1,024 output tokens. Sampling is temperature 0, top-p 1, top-k 1, seed 12345. The candidate was run before the control. + +| Metric | QSA off | QSA on | Change | +|---|---:|---:|---:| +| Prompt throughput, tokens/s | 617.712871 | 625.033976 | +1.185195% | +| Native prompt time, s | 106.0946 | 104.8519 | −1.171313% | +| Request wall time, s | 126.382110 | 125.056913 | −1.048564% | +| Generation throughput, tokens/s | 50.537205 | 50.748591 | +0.418279% | + +All 1,024 token IDs match; speculative accepted/offered counts also match at 648/872. This is one matched pair, recorded before final host-guard hardening. The later ISA audit establishes unchanged device code across that hardening; the fresh combined-stack tests below exercise the final hardened engine. The small generation-throughput movement is noise-scale and does not establish a generation improvement. + +## Combined stack result against the stable baseline + +These fresh comparisons measure the complete HC + grouped-MMQ + PR #1525 dequantization + QSA candidate against the stable engine. They cannot attribute the combined gain to QSA alone. The component and isolated/full-stack percentages must not be added. + +| Code prompt | Stable PP, tokens/s | Combined PP, tokens/s | PP change | Request latency change | TG change | +|---|---:|---:|---:|---:|---:| +| 4,096 tokens | 347.622402 | 368.640369 | +6.046206% | −2.343515% | +0.188068% | +| 65,536 tokens | 597.968207 | 624.674728 | +4.466211% | −3.664980% | +0.376379% | + +Each context has one matched pair with 1,024 output tokens and all token IDs equal within the pair. These use the final hardened candidate engine. The 4K pair ran control then candidate; the 64K pair ran candidate then control. Generation changes are noise-scale. The stable service was restored after the tests; the candidate was not deployed to production. + +For all model tables, PP is the reported full prompt-token count divided by native prompt time; the last prompt token executes in the first decode window. TG is actual output count divided by native decode time. Request wall time is measured separately from model loading. No cross-quantization quality or equal-token claim is made. + +## Provenance and limits + +- Hardware scope: two gfx906 wave64 GPUs; the runtime reports AMD Radeon Pro VII. Results are specific to the tested hardware and pinned build stack. +- Model: `Qwen3.8-Flash-Next-GSQ-RCO-abliterated-IQ3_XXS-Q2_0`, engine version 0.1.40, INT8 KV. The configured capacity is 204,800 tokens; the new QSA candidate was tested only at the prompt lengths reported above. +- Experimental source HEAD: `f152172332693c933b8a3104ce193d8a4315c2b4`, plus campaign changes. It is a separate source scope from the clean PR. +- Pinned llama.cpp revision: `3cf03257f219afbe7334045ff7c6a06ac68c627d`. +- Clean upstream base: `fb58e0dbc8399662c0e47c76578c6e878b14f6cf`. +- Final clean patch SHA-256: `9c81295b8cdf8354fe0e5bc6de36a547199becd1a8fc2a79daabf2b9da9548c6`. +- Final clean probe SHA-256: `a5723bfd34720b690a4031a978ecdfd8c65a35a26cf4ba0471fa4e969570882d`. +- Pre-hardening model-engine SHA-256 used for the isolated QSA pair: `1d9fb9de4e5f5d63fd30257e4077caafa46dde61b5c4d4ac045a3a0f63b78d42`. +- Final hardened model-engine SHA-256: `3d2650fe62fdea24679ac90401eac505b541ccc47886e59885a639c438cb4c17`. +- Stable model-engine SHA-256: `ce794788d64313236bbc24b47a3f8e06c841034afaf4e19a2fc5ffd84e337f14`. +- Build image digest: `sha256:bccb7ee7e7a78274519db9a43ba63c34ddd2e74bb60f8764a8f50aaee1f2c646`. The clean probe uses Release, HIP gfx906, portable/native-expert settings, and grouped-MMQ build options disabled. No floating-point compiler-policy change is part of the QSA patch. +- Compiler verified in that image: AMD Clang `23.0.0git`, ROCm llvm-project revision `46fcb339fb61119b337f973c7ca9e710a319fdd0`, patched revision `440716f8b87be9d8e20ed910e10e5b6d14d57cf6`. The ROCm distribution version is unrecorded because its version file is empty. + +The clean rebased PR has component and host-guard validation; the full-model comparisons belong to the experimental stack. No full-model run on rebased main, new 200K test, new API qualification, CI pass or production deployment is claimed. Earlier HC/MMQ 200K and API qualification does not qualify this new QSA candidate. + +The overlap review found no direct duplicate, but upstream PR #1402 introduces a third kernel-template argument `G`, conflicting with this patch's third boolean argument. The two changes require coordination before merging. PR #1535 concerns the separate top-k work. + +Evidence reviewed: final component/model/combined receipts, build receipts, the final clean patch, and the source/ISA and hardened-ISA audit records. diff --git a/bench/results/2026-10-08-gfx906-qsa-query-swizzle/results.json b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/results.json new file mode 100644 index 00000000..e3b84fa7 --- /dev/null +++ b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/results.json @@ -0,0 +1,519 @@ +{ + "component": { + "parity": [ + { + "tag": "hardened-build-gpu0-nq1-ctx4-mask0-mode0", + "build": "hardened-build", + "gpu": 0, + "mode": 0, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03056 + }, + { + "tag": "hardened-build-gpu0-nq1-ctx4-mask0-mode1", + "build": "hardened-build", + "gpu": 0, + "mode": 1, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03056 + }, + { + "tag": "hardened-build-gpu0-nq33-ctx4096-mask1-mode0", + "build": "hardened-build", + "gpu": 0, + "mode": 0, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 1.02304 + }, + { + "tag": "hardened-build-gpu0-nq33-ctx4096-mask1-mode1", + "build": "hardened-build", + "gpu": 0, + "mode": 1, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 0.96928 + }, + { + "tag": "hardened-build-gpu0-nq32-ctx65536-mask0-mode0", + "build": "hardened-build", + "gpu": 0, + "mode": 0, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.188 + }, + { + "tag": "hardened-build-gpu0-nq32-ctx65536-mask0-mode1", + "build": "hardened-build", + "gpu": 0, + "mode": 1, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.03792 + }, + { + "tag": "hardened-build-gpu1-nq1-ctx4-mask0-mode0", + "build": "hardened-build", + "gpu": 1, + "mode": 0, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03088 + }, + { + "tag": "hardened-build-gpu1-nq1-ctx4-mask0-mode1", + "build": "hardened-build", + "gpu": 1, + "mode": 1, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03088 + }, + { + "tag": "hardened-build-gpu1-nq33-ctx4096-mask1-mode0", + "build": "hardened-build", + "gpu": 1, + "mode": 0, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 1.02272 + }, + { + "tag": "hardened-build-gpu1-nq33-ctx4096-mask1-mode1", + "build": "hardened-build", + "gpu": 1, + "mode": 1, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 0.96688 + }, + { + "tag": "hardened-build-gpu1-nq32-ctx65536-mask0-mode0", + "build": "hardened-build", + "gpu": 1, + "mode": 0, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.186721 + }, + { + "tag": "hardened-build-gpu1-nq32-ctx65536-mask0-mode1", + "build": "hardened-build", + "gpu": 1, + "mode": 1, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.03312 + }, + { + "tag": "clean-pr-build-gpu0-nq1-ctx4-mask0-mode0", + "build": "clean-pr-build", + "gpu": 0, + "mode": 0, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03056 + }, + { + "tag": "clean-pr-build-gpu0-nq1-ctx4-mask0-mode1", + "build": "clean-pr-build", + "gpu": 0, + "mode": 1, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03056 + }, + { + "tag": "clean-pr-build-gpu0-nq33-ctx4096-mask1-mode0", + "build": "clean-pr-build", + "gpu": 0, + "mode": 0, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 1.02512 + }, + { + "tag": "clean-pr-build-gpu0-nq33-ctx4096-mask1-mode1", + "build": "clean-pr-build", + "gpu": 0, + "mode": 1, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 0.97328 + }, + { + "tag": "clean-pr-build-gpu0-nq32-ctx65536-mask0-mode0", + "build": "clean-pr-build", + "gpu": 0, + "mode": 0, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.19024 + }, + { + "tag": "clean-pr-build-gpu0-nq32-ctx65536-mask0-mode1", + "build": "clean-pr-build", + "gpu": 0, + "mode": 1, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.03744 + }, + { + "tag": "clean-pr-build-gpu1-nq1-ctx4-mask0-mode0", + "build": "clean-pr-build", + "gpu": 1, + "mode": 0, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03056 + }, + { + "tag": "clean-pr-build-gpu1-nq1-ctx4-mask0-mode1", + "build": "clean-pr-build", + "gpu": 1, + "mode": 1, + "nq": 1, + "ctx": 4, + "masked": false, + "bytes": 24576, + "sha256": "02664df8e50693193060413c9f8eaf55131eaf456b74245e8347b24e824c7c6f", + "median_ms": 0.03072 + }, + { + "tag": "clean-pr-build-gpu1-nq33-ctx4096-mask1-mode0", + "build": "clean-pr-build", + "gpu": 1, + "mode": 0, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 1.022081 + }, + { + "tag": "clean-pr-build-gpu1-nq33-ctx4096-mask1-mode1", + "build": "clean-pr-build", + "gpu": 1, + "mode": 1, + "nq": 33, + "ctx": 4096, + "masked": true, + "bytes": 811008, + "sha256": "24122feb972bfa4d0c33cacf0133b831b697a9e87af7085900d2a0447d73d4c8", + "median_ms": 0.96704 + }, + { + "tag": "clean-pr-build-gpu1-nq32-ctx65536-mask0-mode0", + "build": "clean-pr-build", + "gpu": 1, + "mode": 0, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.188481 + }, + { + "tag": "clean-pr-build-gpu1-nq32-ctx65536-mask0-mode1", + "build": "clean-pr-build", + "gpu": 1, + "mode": 1, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.0328 + } + ], + "timing": [ + { + "tag": "timing-A1", + "build": "clean-pr-build", + "gpu": 0, + "mode": 0, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.18896 + }, + { + "tag": "timing-B1", + "build": "clean-pr-build", + "gpu": 0, + "mode": 1, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.03624 + }, + { + "tag": "timing-B2", + "build": "clean-pr-build", + "gpu": 0, + "mode": 1, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.03656 + }, + { + "tag": "timing-A2", + "build": "clean-pr-build", + "gpu": 0, + "mode": 0, + "nq": 32, + "ctx": 65536, + "masked": false, + "bytes": 786432, + "sha256": "a00011ca8b03549db7aeaea38307583373bfdfebfa31e34207763903af9879a2", + "median_ms": 1.187439 + } + ], + "component_throughput_gain_pct": 14.646806252412215, + "passed": true, + "production_restore": { + "passed": true + } + }, + "model/summary.json": { + "results": [ + { + "tag": "code65536-B1", + "passed": true, + "prompt_tokens": 65536, + "actual_outputs": 1024, + "PP": 625.033976494465, + "TG": 50.74859128055942, + "prompt_ms": 104851.9, + "decode_ms": 20177.9, + "request_wall_s": 125.05691278600716, + "accepted": 648, + "offered": 872, + "sampling": { + "temperature": 0, + "top_p": 1, + "top_k": 1, + "seed": 12345 + }, + "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70" + }, + { + "tag": "code65536-A1", + "passed": true, + "prompt_tokens": 65536, + "actual_outputs": 1024, + "PP": 617.7128713431221, + "TG": 50.537204562167176, + "prompt_ms": 106094.6, + "decode_ms": 20262.3, + "request_wall_s": 126.38210993001121, + "accepted": 648, + "offered": 872, + "sampling": { + "temperature": 0, + "top_p": 1, + "top_k": 1, + "seed": 12345 + }, + "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70" + } + ], + "decision": { + "micro_20pct_gate_passed": false, + "exception": "bounded cost-benefit qualification of stable14.79pct exact component improvement with tiny layout change", + "PP_gain_pct": 1.1851954995570013, + "prompt_latency_reduction_pct": 1.1713131488313322, + "request_latency_reduction_pct": 1.0485638708974898, + "TG_change_pct": 0.41827940469523206, + "all1024_output_ids_equal": true, + "qualified_single_pair": true + }, + "production_api_restored": true, + "finished_utc": "2026-10-08T22:23:53.765633+00:00" + }, + "combined-final/summary.json": { + "results": [ + { + "tag": "code4096-production", + "passed": true, + "prompt_tokens": 4096, + "actual_outputs": 1024, + "PP": 347.622401955376, + "TG": 55.877810943101764, + "prompt_ms": 11782.9, + "decode_ms": 18325.7, + "request_wall_s": 30.113095285007148, + "accepted": 684, + "offered": 855, + "sampling": { + "temperature": 0, + "top_p": 1, + "top_k": 1, + "seed": 12345 + }, + "output_ids_sha256": "0af681458e937914e536b7a5b78531d638fd9742da28a04e9c0c9443b0c57abd" + }, + { + "tag": "code4096-combined", + "passed": true, + "prompt_tokens": 4096, + "actual_outputs": 1024, + "PP": 368.64036864036865, + "TG": 55.98289897382909, + "prompt_ms": 11111.1, + "decode_ms": 18291.3, + "request_wall_s": 29.407390481006587, + "accepted": 684, + "offered": 855, + "sampling": { + "temperature": 0, + "top_p": 1, + "top_k": 1, + "seed": 12345 + }, + "output_ids_sha256": "0af681458e937914e536b7a5b78531d638fd9742da28a04e9c0c9443b0c57abd" + }, + { + "tag": "code65536-combined", + "passed": true, + "prompt_tokens": 65536, + "actual_outputs": 1024, + "PP": 624.6747280106604, + "TG": 50.71214912541352, + "prompt_ms": 104912.2, + "decode_ms": 20192.4, + "request_wall_s": 125.13095494700246, + "accepted": 648, + "offered": 872, + "sampling": { + "temperature": 0, + "top_p": 1, + "top_k": 1, + "seed": 12345 + }, + "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70" + }, + { + "tag": "code65536-production", + "passed": true, + "prompt_tokens": 65536, + "actual_outputs": 1024, + "PP": 597.9682073910243, + "TG": 50.52199482938959, + "prompt_ms": 109597.8, + "decode_ms": 20268.4, + "request_wall_s": 129.89145007400657, + "accepted": 648, + "offered": 872, + "sampling": { + "temperature": 0, + "top_p": 1, + "top_k": 1, + "seed": 12345 + }, + "output_ids_sha256": "186fecea5448e82653f96f6d88abac69b05ad7665d375f6de5930952ed506b70" + } + ], + "decision": { + "4096": { + "PP_gain_pct": 6.0462060462060485, + "request_latency_reduction_pct": 2.343514664704427, + "TG_change_pct": 0.1880675512402119, + "all1024_output_ids_equal": true + }, + "65536": { + "PP_gain_pct": 4.4662107934063, + "request_latency_reduction_pct": 3.664979584331207, + "TG_change_pct": 0.3763792317901693, + "all1024_output_ids_equal": true + } + }, + "production_api_restored": true, + "finished_utc": "2026-10-08T22:52:40.940327+00:00" + }, + "hardened-build/build.json": { + "exit_code": 0, + "patch_sha256": "2c9e370619a8bc24304c161857c77d5b453a58549c6326e4d1ee7888d8c20344", + "binaries": { + "strata": "3d2650fe62fdea24679ac90401eac505b541ccc47886e59885a639c438cb4c17", + "gfx906_qsa_query_swizzle_probe": "9ddc0446706a1f6f4f283869196eecc36176ae7819f28661fcdf681fd5cbe528" + } + }, + "clean-pr-build/build.json": { + "exit_code": 0, + "upstream_base": "fb58e0dbc8399662c0e47c76578c6e878b14f6cf", + "source_sha256": "db957776b99f66d9f695832adc5302631a97036d717d2bd9bd7d4ff5ff154f85", + "probe_sha256": "a5723bfd34720b690a4031a978ecdfd8c65a35a26cf4ba0471fa4e969570882d" + } +} diff --git a/bench/test_gfx906_qsa_query_swizzle_guard.py b/bench/test_gfx906_qsa_query_swizzle_guard.py new file mode 100644 index 00000000..813ce784 --- /dev/null +++ b/bench/test_gfx906_qsa_query_swizzle_guard.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Compile the production host guard with mock HIP calls; no GPU or HIP SDK needed. + +The helper and dispatch expression are extracted from their single production +definition so this test cannot accidentally validate a copied implementation. +Run from any directory with Python 3 and a C++17 compiler (CXX, default c++). +""" +import os +from pathlib import Path +import re +import shlex +import subprocess +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +source = (ROOT / "src/kernels/cuda/qsa_decode_attn.cu").read_text() +start = source.index("bool query_swizzle_gfx906_device() {") +end = source.index("\n}\n", start) + 3 +guard = source[start:end] +dispatch = re.search(r"^ const bool use_query_swizzle = .*;", source, re.MULTILINE) +if dispatch is None or "if (use_query_swizzle) {" not in source: + raise RuntimeError("production query-swizzle dispatch changed; update the test") + +prefix = r''' +#include "strata/kernels/gfx_arch.hpp" +#include +#include +#include +#include +#include +using strata::kernels::gfx_arch_is; +constexpr int hipSuccess = 0; +struct hipDeviceProp_t { char gcnArchName[64]; int warpSize; }; +struct Mock { + int device = 0, device_calls = 0, property_calls = 0, clear_calls = 0; + bool fail_device = false, fail_properties = false; +}; +thread_local Mock mock; +int hipGetDevice(int* device) { + ++mock.device_calls; + *device = mock.device; + return mock.fail_device ? 1 : hipSuccess; +} +int hipGetDeviceProperties(hipDeviceProp_t* prop, int device) { + ++mock.property_calls; + if (mock.fail_properties) return 1; + static const char* names[] = { + "gfx906", "gfx908", "gfx906:sramecc-:xnack-", "gfx9060", + "gfx906", "", "gfx906-other", "gfx906" + }; + if (device < 0 || device >= 8) return 1; + std::strcpy(prop->gcnArchName, names[device]); + prop->warpSize = device == 4 ? 32 : 64; + return hipSuccess; +} +int hipGetLastError() { ++mock.clear_calls; return hipSuccess; } +int checks = 0; +void require(bool condition, const char* message) { + ++checks; + if (!condition) { std::fprintf(stderr, "FAIL: %s\n", message); std::exit(1); } +} +''' + +tests = r''' +int main() { + require(!active(false, false, 1), "opt-in off"); + require(!active(true, true, 1), "lane-cell wins"); + for (int mode : {0, 2, 3}) require(!active(true, false, mode), "other pool modes"); + require(mock.device_calls == 0 && mock.property_calls == 0, "inactive dispatch makes no HIP queries"); + require(active(true, false, 1), "gfx906 wave64 accepted"); + require(active(true, false, 1), "same-device cache accepted"); + require(mock.device_calls == 2 && mock.property_calls == 1, "ordinal checked each time, properties cached"); + mock.device = 1; + require(!active(true, false, 1), "gfx908 rejected after device switch"); + require(!active(true, false, 1) && mock.property_calls == 2, "unsupported result cached"); + mock.device = 0; + require(active(true, false, 1) && mock.property_calls == 3, "switch back refreshes properties"); + mock.device = 2; + require(active(true, false, 1), "exact gfx906 name with feature suffix accepted"); + for (int device : {3, 4, 5, 6}) { + mock.device = device; + require(!active(true, false, 1), "lookalike name, wave32, or empty name rejected"); + } + mock.device = 0; + require(active(true, false, 1), "restore supported device"); + int properties = mock.property_calls, clears = mock.clear_calls; + mock.fail_device = true; + require(!active(true, false, 1), "current-device API error fails closed"); + require(mock.property_calls == properties && mock.clear_calls == clears + 1, "device error avoids property query"); + mock.fail_device = false; + require(active(true, false, 1) && mock.property_calls == properties + 1, "device error invalidates cache"); + mock.device = -1; + require(!active(true, false, 1), "negative ordinal fails closed"); + mock.device = 0; + require(active(true, false, 1) && mock.property_calls == properties + 2, "invalid ordinal invalidates cache"); + mock.device = 7; + mock.fail_properties = true; + properties = mock.property_calls; + clears = mock.clear_calls; + require(!active(true, false, 1), "property API error cannot reuse another device's cached approval"); + require(!active(true, false, 1), "repeated property failure stays closed"); + require(mock.property_calls == properties + 2 && mock.clear_calls == clears + 2, "property errors remain retryable"); + mock.fail_properties = false; + require(active(true, false, 1) && mock.property_calls == properties + 3, "property query recovers"); + mock.device = 0; + require(active(true, false, 1), "parent thread caches ordinal zero"); + std::thread other([] { + require(active(true, false, 1) && mock.property_calls == 1, "new thread independently queries the same ordinal"); + mock.device = 1; + require(!active(true, false, 1), "other thread caches an unsupported ordinal"); + }); + other.join(); + properties = mock.property_calls; + require(active(true, false, 1) && mock.property_calls == properties, "other thread cannot replace parent cache"); + std::printf("PASS query-swizzle host guard: %d checks (mock HIP, no GPU)\n", checks); +} +''' + +program = prefix + guard + "\nbool active(bool query_swizzle, bool lane_cell, int kv_mode) {\n" +program += dispatch.group(0) + "\n return use_query_swizzle;\n}\n" + tests +with tempfile.TemporaryDirectory(prefix="qsa-swizzle-guard-") as directory: + cpp = Path(directory) / "guard_test.cpp" + binary = Path(directory) / "guard_test" + cpp.write_text(program) + command = shlex.split(os.environ.get("CXX", "c++")) + command += ["-std=c++17", "-Wall", "-Wextra", "-Werror", "-pthread", "-I", str(ROOT / "include"), + str(cpp), "-o", str(binary)] + subprocess.run(command, check=True) + subprocess.run([str(binary)], check=True) diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 2df09136..fa789608 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -2,6 +2,9 @@ #include "strata/kernels/qsa_decode_attn.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/kv_q4.hpp" +#if defined(STRATA_HIP_GFX906) +#include "strata/kernels/gfx_arch.hpp" +#endif #include #include @@ -81,7 +84,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo } else load8_q4(p, value, row, d0, out); } -template +template __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int n_kv_heads, @@ -108,7 +111,15 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest 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]; + // Opt-in gfx906 batched attention: a bijective XOR of query dimensions in LDS only. It swaps the two + // float4 halves of lanes whose bit 2 is set, retaining 16-byte alignment and the 12 KB tile. + // The scoring reads undo this permutation; FP operands and operation order are unchanged. + static_assert(!QUERY_SWIZZLE || !LANE_CELL, "query swizzle is for warp scoring only"); + for (int i = t; i < G * HD; i += THREADS) { + const int d = i % HD; + const int sd = QUERY_SWIZZLE ? (d ^ ((d >> 3) & 4)) : d; + sq[i / HD][sd] = q[(size_t) (kvh * G) * HD + i]; + } if (t < CHUNK) { long long r = -1; if (t < n_here) { @@ -166,8 +177,9 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest load8(p, false, srow[c], lane * 8, k8); #pragma unroll for (int h = 0; h < G; ++h) { - const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); - const float4 qb = *reinterpret_cast(&sq[h][lane * 8 + 4]); + const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0; + const float4 qa = *reinterpret_cast(&sq[h][lane * 8 + qflip]); + const float4 qb = *reinterpret_cast(&sq[h][lane * 8 + (qflip ^ 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); @@ -482,6 +494,34 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_ attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f; } +#if defined(STRATA_HIP_GFX906) +// The compat backend can target other architectures. Check the calling thread's current device, +// caching only its last ordinal so a layer split or another thread cannot reuse the wrong answer. +bool query_swizzle_gfx906_device() { + static thread_local int cached_device = -1; + static thread_local bool cached_supported = false; + int device = -1; + if (hipGetDevice(&device) != hipSuccess || device < 0) { + cached_device = -1; + cached_supported = false; + (void) hipGetLastError(); + return false; + } + if (device != cached_device) { + cached_device = -1; + cached_supported = false; + hipDeviceProp_t prop{}; + if (hipGetDeviceProperties(&prop, device) != hipSuccess) { + (void) hipGetLastError(); + return false; + } + cached_supported = gfx_arch_is(prop.gcnArchName, "gfx906") && prop.warpSize == 64; + cached_device = device; + } + return cached_supported; +} +#endif + #if defined(STRATA_ATTN_PRE75_BUILT) // CUDA: the current device is below sm_75; HIP: it is gfx103x (per device: a layer split can mix cards). // STRATA_ATTN_PRE75=0 turns PR #540's kernel off (A/B); on HIP =1 also runs it on another wave32 card. @@ -546,6 +586,19 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 cudaStream_t st = (cudaStream_t) stream; // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); +#if defined(STRATA_HIP_GFX906) + static const bool query_swizzle = [] { + const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1'; + }(); + const bool use_query_swizzle = query_swizzle && !lane_cell && kv_mode == 1 && query_swizzle_gfx906_device(); + static const bool query_swizzle_trace = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE_TRACE") != nullptr; + static thread_local bool query_swizzle_said = false; + if (query_swizzle_trace && !query_swizzle_said) { + query_swizzle_said = true; + std::fprintf(stderr, "strata attn-query-swizzle: active=%d nq=%lld cap=%lld kv_mode=%d lane_cell=%d\n", + use_query_swizzle, (long long) n_q, (long long) cap, kv_mode, lane_cell); + } +#endif #define STRATA_ATTN_LC(M) attn_chunk_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride) if (lane_cell) { if (kv_mode == 3) STRATA_ATTN_LC(3); @@ -554,6 +607,15 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 else STRATA_ATTN_LC(0); } else #undef STRATA_ATTN_LC +#if defined(STRATA_HIP_GFX906) + // Opt-in INT8 batched attention: prefill, verification and MTP (including n_q=1). + // Other pool formats and lane-cell scoring keep their paths; qsa_decode_attn_step is unchanged. + // A k8v4 model's MTP drafter uses INT8 pools and can therefore take this path. + if (use_query_swizzle) { + attn_chunk_kernel<1, false, true><<>>(q, pools, ids, steps, + (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + } else +#endif if (kv_mode == 3) STRATA_ATTN_CHUNK(3)<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); From 254f5aeca9b573b2f5a16c16fe6f650c66d88d5c Mon Sep 17 00:00:00 2001 From: Andrey Bash <117385366+0FL01@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:38:16 +0300 Subject: [PATCH 16/19] docs(gfx906): record 200K and API qualification for the combined candidate Record archived-control output parity, verified candidate process, tools, CPU vision and cache restoration. No fresh 200K speed comparison or production promotion is claimed. --- .../README.md | 31 ++++++++++++++++--- .../service-qualification.json | 1 + 2 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 bench/results/2026-10-08-gfx906-qsa-query-swizzle/service-qualification.json diff --git a/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md index 38c5de49..9e5dd4f2 100644 --- a/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md +++ b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/README.md @@ -8,6 +8,8 @@ The opt-in gfx906 query-LDS swizzle improves the measured INT8 batched-QSA compo These results support a narrowly scoped, default-off upstream proposal. They do not establish a general speedup across workloads, model-level equivalence beyond the tested pairs, or production readiness. +The final hardened combined engine also passes a 200,000-token capacity run and targeted API/cache regression checks. Those qualifications apply to the frozen experimental stack; they do not extend the clean upstream patch's component-only validation to full-model testing. + ## Change and dispatch scope The change permutes only the shared-memory query layout in `attn_chunk_kernel`: `q(d) = d XOR ((d >> 3) & 4)`. The scoring loads invert the permutation. The mapping is bijective and self-inverse over the 256 dimensions, preserves 16-byte load alignment and the 12 KiB query tile, and leaves the logical floating-point operands and operation order unchanged. Score reduction, softmax, value accumulation and merge code are unchanged. @@ -78,14 +80,33 @@ These fresh comparisons measure the complete HC + grouped-MMQ + PR #1525 dequant | 4,096 tokens | 347.622402 | 368.640369 | +6.046206% | −2.343515% | +0.188068% | | 65,536 tokens | 597.968207 | 624.674728 | +4.466211% | −3.664980% | +0.376379% | -Each context has one matched pair with 1,024 output tokens and all token IDs equal within the pair. These use the final hardened candidate engine. The 4K pair ran control then candidate; the 64K pair ran candidate then control. Generation changes are noise-scale. The stable service was restored after the tests; the candidate was not deployed to production. +Each context has one matched pair with 1,024 output tokens and all token IDs equal within the pair. These use the final hardened candidate engine. The 4K pair ran control then candidate; the 64K pair ran candidate then control. Generation changes are noise-scale. The stable service was restored after the tests; the candidate was not promoted to production. For all model tables, PP is the reported full prompt-token count divided by native prompt time; the last prompt token executes in the first decode window. TG is actual output count divided by native decode time. Request wall time is measured separately from model loading. No cross-quantization quality or equal-token claim is made. +## Capacity and service qualification + +The final hardened engine (`3d2650fe62fdea24679ac90401eac505b541ccc47886e59885a639c438cb4c17`) completed a fresh **200,000-token prompt plus 256 generated tokens** with a configured capacity of 204,800 and INT8 KV. All 256 output IDs match the archived stable `ce794788…` control. This is a capacity and output-parity qualification against an archived control, **not a fresh speed comparison**. No incremental QSA or combined-stack speedup is inferred from this run. + +Targeted API testing verified the actual candidate executable hash and active candidate flags, including the QSA opt-in, then passed: + +- Synthetic forced tool call and tool-result roundtrip +- Two synthetic image requests through CPU vision, followed by text +- Unauthenticated-request HTTP 401 and root-route HTTP 404 checks +- Synthetic A/auxiliary/A RAM prompt-cache restoration + +| Cache request | Elapsed time, s | Cached prompt tokens | +|---|---:|---:| +| A, cold | 14.3541 | 0 | +| A, warm | 0.4073 | 6,423 | +| A, restored after auxiliary request | 0.3868 | 6,423 | + +The three A requests returned the same result. This synthetic cache regression is not a replay of a client session or a general service benchmark. The original configuration and Compose files were restored byte-for-byte, and the stable `ce794788…` API was healthy afterward. No production promotion occurred. + ## Provenance and limits - Hardware scope: two gfx906 wave64 GPUs; the runtime reports AMD Radeon Pro VII. Results are specific to the tested hardware and pinned build stack. -- Model: `Qwen3.8-Flash-Next-GSQ-RCO-abliterated-IQ3_XXS-Q2_0`, engine version 0.1.40, INT8 KV. The configured capacity is 204,800 tokens; the new QSA candidate was tested only at the prompt lengths reported above. +- Model: `Qwen3.8-Flash-Next-GSQ-RCO-abliterated-IQ3_XXS-Q2_0`, engine version 0.1.40, INT8 KV. The configured capacity is 204,800 tokens; the final candidate completed the 200,000-token qualification described above. - Experimental source HEAD: `f152172332693c933b8a3104ce193d8a4315c2b4`, plus campaign changes. It is a separate source scope from the clean PR. - Pinned llama.cpp revision: `3cf03257f219afbe7334045ff7c6a06ac68c627d`. - Clean upstream base: `fb58e0dbc8399662c0e47c76578c6e878b14f6cf`. @@ -97,8 +118,10 @@ For all model tables, PP is the reported full prompt-token count divided by nati - Build image digest: `sha256:bccb7ee7e7a78274519db9a43ba63c34ddd2e74bb60f8764a8f50aaee1f2c646`. The clean probe uses Release, HIP gfx906, portable/native-expert settings, and grouped-MMQ build options disabled. No floating-point compiler-policy change is part of the QSA patch. - Compiler verified in that image: AMD Clang `23.0.0git`, ROCm llvm-project revision `46fcb339fb61119b337f973c7ca9e710a319fdd0`, patched revision `440716f8b87be9d8e20ed910e10e5b6d14d57cf6`. The ROCm distribution version is unrecorded because its version file is empty. -The clean rebased PR has component and host-guard validation; the full-model comparisons belong to the experimental stack. No full-model run on rebased main, new 200K test, new API qualification, CI pass or production deployment is claimed. Earlier HC/MMQ 200K and API qualification does not qualify this new QSA candidate. +The clean rebased patch has component and host-guard validation; the full-model comparisons, 200K capacity run and API/cache qualification belong to the frozen experimental stack. No full-model run on rebased main, upstream CI pass or production promotion is claimed. Single matched speed pairs and targeted synthetic service tests do not establish broader workload or service equivalence. The overlap review found no direct duplicate, but upstream PR #1402 introduces a third kernel-template argument `G`, conflicting with this patch's third boolean argument. The two changes require coordination before merging. PR #1535 concerns the separate top-k work. -Evidence reviewed: final component/model/combined receipts, build receipts, the final clean patch, and the source/ISA and hardened-ISA audit records. +The branch at commit `26f776a` is published. Creating the new PR returned HTTP 403, so no new PR exists; the accompanying PR text remains a draft. + +Evidence reviewed: final component/model/combined receipts, build receipts, the final clean patch, source/ISA and hardened-ISA audit records, and the sanitized capacity/API/cache qualification receipt. diff --git a/bench/results/2026-10-08-gfx906-qsa-query-swizzle/service-qualification.json b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/service-qualification.json new file mode 100644 index 00000000..647a8da3 --- /dev/null +++ b/bench/results/2026-10-08-gfx906-qsa-query-swizzle/service-qualification.json @@ -0,0 +1 @@ +{"capacity": {"decision": {"capacity_passed": true, "archived_stable_output_ids_equal": true, "fresh_speed_comparison": false, "new_prompt_tokens": 200000, "capacity": 204800}, "result": {"tag": "code200000-combined", "passed": true, "kv": "int8", "prompt_tokens": 200000, "actual_outputs": 256, "prompt_ms": 334740.7, "decode_ms": 5835.9, "PP": 597.4773907086889, "TG": 43.86641306396614, "engine_total_s": 340.57660000000004, "request_wall_s": 340.6550010840001, "load_wall_s": 30.593625943001825, "accepted": 161, "offered": 227, "cache_hits": 150355, "lookups": 155040, "prompt_reused": 0, "prompt_read": 200000, "sampling": {"temperature": 0, "top_p": 1, "top_k": 1, "seed": 12345}, "metric_scope": "PP=reported full prompt count /native prompt_ms; last prompt token executes in first decode window. TG=actual outputs/native decode_ms. Native wall/load separate. No quality or equal-token claim across KV quantizations."}, "production_restored": true}, "api": {"passed": true, "candidate_binary_sha256": "3d2650fe62fdea24679ac90401eac505b541ccc47886e59885a639c438cb4c17", "candidate_flags": {"STRATA_GFX906_HC_F16": "1", "STRATA_HC_F16_SCALE_PROBE": "1", "STRATA_HC_F16_EXACT_INPUT": "1", "STRATA_HC_F16_AUDIT": "0", "STRATA_HC_F16_TRACE": "1", "STRATA_GFX906_MMQ_OPT_CAP": "32", "STRATA_GFX906_ATTN_QUERY_SWIZZLE": "1", "STRATA_ATTN_LANECELL": "0", "STRATA_GFX906_ATTN_QUERY_SWIZZLE_TRACE": "1"}, "tools": "passed", "vision": "passed", "parking": "passed", "original_configuration_restored": true, "finished_utc": "2026-10-08T23:23:15.669875+00:00"}, "cache": {"passed": true, "rows": [{"tag": "cold", "elapsed_s": 14.35406114399666, "content": "42", "usage": {"prompt_tokens": 6430, "completion_tokens": 3, "total_tokens": 6433, "prompt_tokens_details": {"cached_tokens": 0}}, "cached_tokens": 0}, {"tag": "warm", "elapsed_s": 0.4072986069950275, "content": "42", "usage": {"prompt_tokens": 6430, "completion_tokens": 3, "total_tokens": 6433, "prompt_tokens_details": {"cached_tokens": 6423}}, "cached_tokens": 6423}, {"tag": "auxiliary", "elapsed_s": 0.5429617629997665, "content": "TEST", "usage": {"prompt_tokens": 17, "completion_tokens": 2, "total_tokens": 19, "prompt_tokens_details": {"cached_tokens": 0}}, "cached_tokens": 0}, {"tag": "restored", "elapsed_s": 0.3868003759998828, "content": "42", "usage": {"prompt_tokens": 6430, "completion_tokens": 3, "total_tokens": 6433, "prompt_tokens_details": {"cached_tokens": 6423}}, "cached_tokens": 6423}], "scope": "synthetic A/title/A RAM parking regression, not a client replay"}} From 354f982118dd2ec028a0ef0a63f933c719585a9e Mon Sep 17 00:00:00 2001 From: Andrey Bash <117385366+0FL01@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:14:41 +0300 Subject: [PATCH 17/19] gfx906: add opt-in reduce12 QSA score reduction Follow query-swizzle #1661 with the existing reduce-scatter pairing for 12 heads. Keep default paths and softmax/value/merge unchanged. Public component parity and timing passed; model evidence uses frozen stack. --- src/kernels/cuda/qsa_decode_attn.cu | 77 +++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index fa789608..624036c6 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -84,7 +84,37 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo } else load8_q4(p, value, row, d0, out); } -template +// Exact-intent score reduce-scatter: the same butterfly pairs as twelve warp_sum calls, +// with 16 shuffle exchanges instead of 60. Used only by the opt-in gfx906 INT8 +// query-swizzled specialization; softmax, value accumulation and merge are unchanged. +__device__ __forceinline__ float reduce12_gfx906(const float (&part)[16], int lane) { + float r8[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const bool hi = (lane & 16) != 0; + r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16); + } + float r4[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const bool hi = (lane & 8) != 0; + r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8); + } + float r2[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const bool hi = (lane & 4) != 0; + r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4); + } + const bool hi2 = (lane & 2) != 0; + const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2); + return r1 + __shfl_xor_sync(0xffffffffu, r1, 1); +} +__device__ __forceinline__ int reduce12_head_of_lane(int lane) { + return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1); +} + +template __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int n_kv_heads, @@ -173,6 +203,25 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest if (lane < G) sp[lane][c] = -FLT_MAX; continue; } + if constexpr (REDUCE12) { + float k8[8]; + load8(p, false, srow[c], lane * 8, k8); + float part[16]; +#pragma unroll + for (int h = 0; h < G; ++h) { + const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0; + const float4 qa = *reinterpret_cast(&sq[h][lane * 8 + qflip]); + const float4 qb = *reinterpret_cast(&sq[h][lane * 8 + (qflip ^ 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; + part[h] = s; + } +#pragma unroll + for (int h = G; h < 16; ++h) part[h] = 0.0f; + const float score = reduce12_gfx906(part, lane); + const int head = reduce12_head_of_lane(lane); + if ((lane & 1) == 0 && head < G) sp[head][c] = score * scale; + } else { float k8[8]; load8(p, false, srow[c], lane * 8, k8); #pragma unroll @@ -185,6 +234,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest s = warp_sum(s); if (lane == 0) sp[h][c] = s * scale; } + } } __syncthreads(); // per-head chunk max and exp-sum: warp w handles heads w and w+8. @@ -612,8 +662,29 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 // Other pool formats and lane-cell scoring keep their paths; qsa_decode_attn_step is unchanged. // A k8v4 model's MTP drafter uses INT8 pools and can therefore take this path. if (use_query_swizzle) { - attn_chunk_kernel<1, false, true><<>>(q, pools, ids, steps, - (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + // use_query_swizzle already requires INT8, warp scoring, and the calling + // thread's current device to be exactly gfx906 with a 64-lane wavefront. + static const bool reduce12 = [] { + const char* v = std::getenv("STRATA_GFX906_ATTN_REDUCE12"); + return v && v[0] == '1' && v[1] == '\0'; + }(); + if (reduce12) { + attn_chunk_kernel<1, false, true, true><<>>(q, pools, ids, steps, + (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + static const bool trace = [] { + const char* v = std::getenv("STRATA_GFX906_ATTN_REDUCE12_TRACE"); + return v && v[0] == '1' && v[1] == '\0'; + }(); + static thread_local bool said = false; + if (trace && !said) { + said = true; + std::fprintf(stderr, "strata attn-reduce12: selected=1 query_swizzle=1 kv_mode=1 nq=%lld cap=%lld\n", + (long long) n_q, (long long) cap); + } + } else { + attn_chunk_kernel<1, false, true><<>>(q, pools, ids, steps, + (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + } } else #endif if (kv_mode == 3) From 0b3139ec18479c8807fddeeaf3d7df69aae0d014 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 16:54:45 +0200 Subject: [PATCH 18/19] gfx906 build: refuse a wave32 card at start with a message (#1728); docs: community-tested, opt-in note --- docs/AMD_HIP.md | 2 ++ src/program/generate.cpp | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 8b1e7565..e75208ab 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -468,6 +468,8 @@ gfx906 is wave64 and has no WMMA and no packed byte arithmetic, so the wave32 ba (32-wide shuffles, a ballot of its own half). The hot kernels have wave64 layouts of their own (below). Setup does not build it yet: build by hand, and run `serve/server.py` with a config as on any other card. +**Community-tested, opt-in (0.1.42).** The gfx906 build is maintained with its users: we have no gfx906 card, so what is here was measured by community members on their MI50s (the attention switches `STRATA_GFX906_ATTN_QUERY_SWIZZLE=1` and `STRATA_GFX906_ATTN_REDUCE12=1`, PRs #1661 and #1718 by 0FL01, are off by default and compiled only into this build) and the engine here is checked to compile for gfx906, nothing more. Nothing in it changes the builds for other cards. A wave32 card seen by this build is refused at start with a message (#1728). Please report how it runs on your card. + **ROCm.** AMD's current ROCm releases no longer ship gfx906 libraries. The build and the measurements below used HIP 7.14 from the community image [`mixa3607/rocm-gfx906:7.14-complete`](https://hub.docker.com/r/mixa3607/rocm-gfx906) (rocBLAS/hipBLAS with gfx906 kernels), on the kernel's amdgpu driver (Ubuntu 24.04, kernel 6.8). hipBLASLt is not diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 694aa0ac..5e334ef8 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2064,6 +2064,23 @@ int main(int argc, char** argv) { if (cudaGetDeviceProperties(&ad, 0) == cudaSuccess) strata::core::apply_arch_defaults(ad.gcnArchName); else (void) cudaGetLastError(); } +#endif +#if defined(STRATA_HIP_GFX906) + { // #1728: the gfx906 build's kernels assume 64-lane waves; on a wave32 card they would fault or give wrong + // numbers, so say so before the first launch (the ready-made wave32 engine is the one for those cards) + int n_dev = 0; + if (cudaGetDeviceCount(&n_dev) == cudaSuccess) { + for (int d = 0; d < n_dev; ++d) { + cudaDeviceProp wp{}; + if (cudaGetDeviceProperties(&wp, d) == cudaSuccess && wp.warpSize != 64) { + std::fprintf(stderr, "strata generate: this engine was built for gfx906 (wave64, STRATA_HIP_GFX906), but GPU %d " + "(%s) has %d-lane waves: use the ready-made engine for that card, or hide it " + "(HIP_VISIBLE_DEVICES)\n", d, wp.name, wp.warpSize); + return 2; + } + } + } else (void) cudaGetLastError(); + } #endif strata::core::set_coupled_draft(o.coupled_draft); { // --host-core / STRATA_HOST_CORE, before the pool and the session pin any thread From ca2730b14b949d78d9283bd792be575d5b4e8c5e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 9 Oct 2026 18:11:08 +0200 Subject: [PATCH 19/19] docs: PF_FUSED KL re-check on IQ3_S / IQ3_XXS / Q2_0 (stays opt-in) --- docs/AMD_HIP.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index e75208ab..66250f25 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -357,6 +357,7 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39 kernels alone are 1.48x / 1.20x / 1.14x MMQ's at 4K / 16K / 32K. Quality: first-token KL against the FP16 prompt path at 4K (48 prompts) is 1.10x MMQ's, which that sample cannot tell apart from MMQ's; top-1 agreed on 48 of 48 (every prompt's top token was the same one, so that check says little); 4 of 4 long-context retrieval checks passed. + 0.1.42 re-check on an R9700 (Linux, ROCm 7.14), 12 prompts of 1.5K-24K tokens, first-token KL against the FP16 prompt path (MMQ / fused): IQ3_S 0.00332 / 0.00284, top-1 12 of 12 for both; IQ3_XXS 0.00335 / 0.00452 on one sample and 0.00344 / 0.00323 on a second (24 prompts pooled: 0.00340 / 0.00388, top-1 24 of 24 for both); the Q2_0 pack does not take these kernels on gfx12 (output bit-identical to MMQ). Because the IQ3_XXS pool is not at or below MMQ's, the flag stays opt-in. Measured on Linux only. gfx1200 builds the same kernels and was not run; Windows and K-quant packs (`STRATA_PF_FUSED_KQ=1`) were not measured. - **Known:** rarely (about 1 start in 10) a HIP run's greedy output differs from another start's at some token, on one card or two and on engine 0.1.29 as well; not yet explained.