From c8c79b17ea087d6d1546bbf7e56adc986f57dba3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:03:30 +0200 Subject: [PATCH] batch MTP (#846): opt-in --batch-mtp / STRATA_BATCH_MTP=1, warn instead of refusing, 1-row groups keep the 0.1.39 commit kernel, LRU graph cache only under the flag, the real draft geometry Co-authored-by: rkcth <16263985+rkcth@users.noreply.github.com> --- docs/BATCHING.md | 14 +++++------ include/strata/core/verify.hpp | 5 ++++ serve/server.py | 4 +-- src/core/verify.cpp | 45 +++++++++++++++++++++------------- src/program/generate.cpp | 43 ++++++++++++++++++++------------ 5 files changed, 69 insertions(+), 42 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 47597779..e1896fd9 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -19,12 +19,12 @@ asked, with a note when it is more than setup would recommend. "parallel": 2 ``` -On one GPU with MTP enabled, set `MULTI_CONCURRENCY=TRUE` in the server's -environment to let batch slots use one MTP proposal each. It is opt-in; without -it, the batch behavior described below is unchanged. The grouped path has only -been tested on an AMD R9700. It needs additional VRAM per slot for draft state -and buffers, so check the engine's free-memory log before using it on a smaller -card. It has not been validated on NVIDIA or with a layer split. +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 a layer split, the engine options go into the config's `args`: @@ -65,7 +65,7 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske - **When a second request arrives**, the first is stopped (`STOP`) and continues in a batch slot with its prompt plus what it generated so far - the engine's prompt cache holds exactly that, so nothing is read again - and the new request is admitted next to it. By default, a request in a slot decodes **without MTP drafts** (one token per window). - With `MULTI_CONCURRENCY=TRUE`, each slot verifies one MTP proposal alongside its current token. + With `--batch-mtp`, each slot verifies one MTP proposal alongside its current token. - **A request left alone in a slot** (the others finished, nobody waits) goes back to the solo path: the slot is stopped, the engine copies its sessions back and decodes with MTP drafts again (at most twice per request; with `--prompt-cache 0` it stays in the slot; `STRATA_PARALLEL_SOLO=0` turns it off). The draft layer's own K/V was diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index c76b9249..b091ddba 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -154,6 +154,8 @@ public: /// Commit an accepted prefix in each contiguous slot group of the last window. `keep` has /// one entry per slot (indexed by slot ID), each in 1..that slot's group length. bool commit_slot_prefixes(const int* keep, std::string& err); + /// --batch-mtp: slot rotation makes many row layouts, so bound the captured batch graph pairs (LRU). 0 = unbounded. + void set_batch_graph_limit(size_t n) { batch_graph_limit_ = n; } // ---- The stages of a layer split as a PIPELINE. A batch window over the slot GROUP // [base, base + S) is launched on ONE stage with its commit right behind it on the stage's stream (a batch window @@ -225,6 +227,9 @@ private: int brow_[8] = {}; ///< ... and row t is slot brow_[t] bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group) std::map, cudaGraphExec_t> exec_bm_, commit_bm_; ///< full row layout avoids slot-ID collisions + std::map, uint64_t> bm_used_; ///< last use of each captured layout (LRU, only with a graph limit) + uint64_t bm_tick_ = 0; + size_t batch_graph_limit_ = 0; ///< 0: keep every captured batch graph (0.1.39); N: LRU-evict beyond N layouts int last_rows_[8] = {}; ///< the slots of the last batch window's rows std::vector bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs std::vector k = batch_key(rows, S, hbase); diff --git a/serve/server.py b/serve/server.py index be4ddc92..f7251a87 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1612,7 +1612,7 @@ def engine_args(cfg: dict) -> list[str]: return learned_profile_args(cfg, args) -PARALLEL_MAX = 8 # normal batch mode; grouped MTP waves more slots through eight-row windows +PARALLEL_MAX = 8 # the engine's batch window holds at most 8 rows (kVerifyMaxT); --batch-mtp waves more through it def parallel_args(cfg: dict, args: list[str]) -> list[str]: @@ -1630,7 +1630,7 @@ def parallel_args(cfg: dict, args: list[str]) -> list[str]: return [] if n <= 1: return [] - if n > PARALLEL_MAX and os.environ.get("MULTI_CONCURRENCY") != "TRUE": + if n > PARALLEL_MAX and "--batch-mtp" not in args and os.environ.get("STRATA_BATCH_MTP", "0") in ("", "0"): print(f'[strata] "parallel": {n} - the engine runs at most {PARALLEL_MAX} requests together; it will use ' f"{PARALLEL_MAX}", flush=True) return ["--batch", str(n)] diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 4e76f995..84789cba 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1890,7 +1890,8 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri beta_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV, z_ + (size_t) first * ZV, (const float*) wnm->data, EPS, y_dummy_ + (size_t) first * ZV, (int) g.ssm_k_heads, - (int) HV, t - first, keep, cs_, t - first); + (int) HV, t - first, keep, cs_, + t - first > 1 ? t - first : 0); // a 1-row group keeps the 0.1.39 kernel } ++gdn_index; } else { @@ -1973,23 +1974,33 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok return false; } refresh_ar(); - // Slot rotation creates new layouts; bound the captured graph pairs. - const auto key = bkey(rows, S, hbase); - constexpr size_t graph_limit = 32; - if (exec_bm_.find(key) == exec_bm_.end() && exec_bm_.size() >= graph_limit) { - if (cudaStreamSynchronize(cs_) != cudaSuccess) { - err = "verify: synchronizing before batch graph eviction failed"; - return false; - } - auto old = exec_bm_.begin(); - const auto old_key = old->first; - if (old->second) cudaGraphExecDestroy(old->second); - exec_bm_.erase(old); - auto commit_old = commit_bm_.find(old_key); - if (commit_old != commit_bm_.end()) { - if (commit_old->second) cudaGraphExecDestroy(commit_old->second); - commit_bm_.erase(commit_old); + // --batch-mtp only (limit 0 = 0.1.39: no eviction): slot rotation creates new layouts; bound the captured graph + // pairs, evicting the least recently used layout. + if (batch_graph_limit_ > 0) { + const auto key = bkey(rows, S, hbase); + if (exec_bm_.find(key) == exec_bm_.end() && exec_bm_.size() >= batch_graph_limit_) { + if (cudaStreamSynchronize(cs_) != cudaSuccess) { + err = "verify: synchronizing before batch graph eviction failed"; + return false; + } + auto old = exec_bm_.begin(); + uint64_t oldest = UINT64_MAX; + for (auto it = exec_bm_.begin(); it != exec_bm_.end(); ++it) { + const auto u = bm_used_.find(it->first); + const uint64_t t = u == bm_used_.end() ? 0 : u->second; + if (t < oldest) { oldest = t; old = it; } + } + const auto old_key = old->first; + if (old->second) cudaGraphExecDestroy(old->second); + exec_bm_.erase(old); + bm_used_.erase(old_key); + auto commit_old = commit_bm_.find(old_key); + if (commit_old != commit_bm_.end()) { + if (commit_old->second) cudaGraphExecDestroy(commit_old->second); + commit_bm_.erase(commit_old); + } } + bm_used_[key] = ++bm_tick_; } if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false; const Clock::time_point t0 = Clock::now(); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 2aa845eb..3f544145 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -491,6 +491,7 @@ struct Options { /// The --batch slots in this many groups pipelined through the stages of a layer split (stage k /// runs one group while stage k+1 runs another). 1 = every slot in one window, stage after stage. int batch_groups = 1; + bool batch_mtp = false; ///< --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): one MTP proposal per batch slot std::string spec_oracle; int spec_corrupt = 0; /// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it. @@ -652,8 +653,10 @@ void usage() { " default 512), so the command `VRAM ` (the server's POST /v1/vram) can\n" " give VRAM back to other programs between requests and take it back later\n" " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8\n" - " normally; MULTI_CONCURRENCY=TRUE waves more through eight-row windows),\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-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n" " --trim-stage-weights an explicit --layer-split: each GPU loads only its own layers' dense weights\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" @@ -1431,6 +1434,7 @@ int main(int argc, char** argv) { else if (a == "--slots") o.batch = std::atoi(next("--slots")); // the same as --batch else if (a == "--trim-stage-weights") o.trim_stage_weights = true; else if (a == "--batch-groups") o.batch_groups = std::atoi(next("--batch-groups")); + else if (a == "--batch-mtp") o.batch_mtp = true; else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle"); else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt")); else if (a == "--mtp") o.mtp = next("--mtp"); @@ -2962,8 +2966,19 @@ int main(int argc, char** argv) { // slot of the batch windows. Before the expert cache is sized, so `--expert-cache auto` leaves them room. // Recommend, never force: a count the engine cannot run is said and adjusted (or batching left off) - the // engine still starts and serves one request at a time. - const char* multi_concurrency = std::getenv("MULTI_CONCURRENCY"); - const bool batch_mtp_requested = multi_concurrency != nullptr && std::strcmp(multi_concurrency, "TRUE") == 0; + // --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. + 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) { + 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; + if (why != nullptr) { + std::fprintf(stderr, "strata generate: WARNING: --batch-mtp is off: %s\n", why); + batch_mtp = false; + } + } std::vector>> bslot_ss; if (o.batch != 0) { const int cap = strata::kernels::kVerifyMaxT; @@ -2972,7 +2987,7 @@ int main(int argc, char** argv) { if (off != nullptr) { std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off); o.batch = 0; - } else if (o.batch > cap && !batch_mtp_requested) { + } else if (o.batch > cap && !batch_mtp) { std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " "slots\n", o.batch, cap, cap); o.batch = cap; @@ -3036,11 +3051,9 @@ int main(int argc, char** argv) { // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts. // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages. strata::core::MtpDrafter mtp; - const bool batch_mtp = batch_mtp_requested; - if (batch_mtp && (o.batch < 2 || o.mtp.empty() || multi_gpu)) { - std::fprintf(stderr, "strata generate: MULTI_CONCURRENCY=TRUE needs at least two slots, --mtp and one GPU\n"); - return 2; - } + // the draft layer's geometry (the canonical model's MTP head), `static` because MtpDrafter keeps a reference; the batch + // slots' draft-KV copies use this one too + static const strata::core::ModelGeometry draft_geometry{}; std::vector> slot_mtp; if (!o.mtp.empty()) { if (o.spec < 2) { @@ -3050,7 +3063,6 @@ int main(int argc, char** argv) { if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference - static const strata::core::ModelGeometry draft_geometry{}; // with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1); if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } @@ -5201,6 +5213,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str()); } 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 if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err) || !mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, ver.final_R_all(), err)) { @@ -6050,12 +6063,11 @@ int main(int argc, char** argv) { } if (batch_mtp) { // Admission first builds the solo draft KV; copy it into the slot before drafting. - static const strata::core::ModelGeometry draft_g{}; 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_g, upto, false, e) || + !strata::core::conversation_kv_save(image, mtp.kv_state(), draft_geometry, upto, false, e) || !strata::core::conversation_kv_restore(image, slot_mtp[(size_t) b]->kv_state(), - draft_g, upto, false, e) || + draft_geometry, upto, false, e) || cudaDeviceSynchronize() != cudaSuccess) return false; slot_mtp[(size_t) b]->set_prompt_len(upto); @@ -6095,12 +6107,11 @@ int main(int argc, char** argv) { } if (batch_mtp) { // A returning solo request resumes from its slot's draft KV. - static const strata::core::ModelGeometry draft_g{}; 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(), - draft_g, upto, false, e) || - !strata::core::conversation_kv_restore(image, mtp.kv_state(), draft_g, upto, false, e) || + draft_geometry, upto, false, e) || + !strata::core::conversation_kv_restore(image, mtp.kv_state(), draft_geometry, upto, false, e) || cudaDeviceSynchronize() != cudaSuccess) return false; mtp.set_prompt_len(upto);