Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Merge PR #559 (blange48, crazyaimachine): batch slots, pipelined layer split, parking with a split

Niko122189351a799dc2
diff --cc serve/server.py
index cdf0cceb9,aadac1376..52c659377
--- a/serve/server.py
+++ b/serve/server.py
@@@ -306,76 -293,17 +307,87 @@@ def narrate_start(log_path: str, offset
print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True)
+class ConvCacheLog:
+ """#596: the engine's conversation cache as its log tells it (the engine writes "strata serve: conversation
+ cache: parked N tokens ...; parked=P bytes=B evictions=E" and "restored N tokens ...; parked=P bytes=B" to stderr,
+ which is the log): read on from where it was last read, from the start of the engine's current run."""
+ EVENT = re.compile(r"conversation cache: (parked|skipped|restored) (\d+) tokens.*?parked=(\d+) bytes=(\d+)"
+ r"(?: evictions=(\d+))?")
+ DROPPED = re.compile(r"conversation cache: dropped \d+ superseded .*?parked=(\d+)")
+ READ_MAX = 1 << 20 # at most the last MiB of new lines per read
+
+ def __init__(self):
+ self.key, self.pos = None, 0
+ self.reset()
+
+ def reset(self):
+ self.state = {"parked": 0, "bytes": 0, "evictions": 0, "parks": 0, "restores": 0, "last_event": None,
+ "last_tokens": None, "last_at": None}
+
+ def poll(self, path, start) -> dict:
+ """The state after the log's new lines; `start` is where the engine's current run began in it."""
+ if not path or start is None:
+ return dict(self.state)
+ if self.key != (path, start): # another start of the engine: its cache starts empty
+ self.key, self.pos = (path, start), start
+ self.reset()
+ try:
+ size = os.path.getsize(path)
+ if size < self.pos: # the log was emptied or replaced
+ self.pos = 0
+ if size - self.pos > self.READ_MAX:
+ self.pos = size - self.READ_MAX
+ with open(path, "rb") as f:
+ f.seek(self.pos)
+ data = f.read(size - self.pos)
+ except OSError:
+ return dict(self.state)
+ end = data.rfind(b"\n") + 1 # whole lines only: the rest is read next time
+ self.pos += end
+ now = time.time()
+ for line in data[:end].decode("utf-8", "replace").splitlines():
+ if "conversation cache:" not in line:
+ continue
+ m = self.EVENT.search(line)
+ if m:
+ st = self.state
+ st["parked"], st["bytes"] = int(m.group(3)), int(m.group(4))
+ if m.group(5) is not None:
+ st["evictions"] = int(m.group(5))
+ if m.group(1) != "skipped":
+ st["parks" if m.group(1) == "parked" else "restores"] += 1
+ st["last_event"], st["last_tokens"], st["last_at"] = m.group(1), int(m.group(2)), now
+ continue
+ m = self.DROPPED.search(line)
+ if m:
+ self.state["parked"] = int(m.group(1))
+ return dict(self.state)
+
+
+def conversation_cache_view(info: dict, hist: list, totals: dict, parked: dict) -> dict:
+ """#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in
+ --conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back."""
+ mib = info.get("conversation_cache_mib")
+ last = hist[-1] if hist else None
+ return {"enabled": isinstance(mib, int) and mib > 0, "budget_mib": mib if isinstance(mib, int) else None,
+ "slots": info.get("conversation_cache_slots"), **parked,
+ "requests": len(hist), "requests_reused": sum(1 for r in hist if (r.get("reused") or 0) > 0),
+ "reused_tokens": totals.get("reused", 0), "prompt_tokens": totals.get("prompt_tokens", 0),
+ "last_reused": last.get("reused") if last else None,
+ "last_prompt": last.get("prompt_tokens") if last else None}
+
+
+ _BTRACE = bool(os.environ.get("STRATA_BATCH_TRACE"))
+
+
+ def btrace(*a):
+ if _BTRACE:
+ print("[batch-trace]", threading.get_ident() % 10000, *a, file=sys.stderr, flush=True)
+
+
+ EOS_IDS = {248044, 248046} # <|endoftext|>, <|im_end|>: the engine's default --eos-ids
+
+
class StrataEngine:
"""The resident engine: `strata --serve` reads `GEN <max_new> <ids>` lines and streams `T <id>` lines, then
`DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough.
diff --cc src/core/native_dense.cpp
index 86d70fb80,eb4358211..e0609fdc5
--- a/src/core/native_dense.cpp
+++ b/src/core/native_dense.cpp
@@@ -146,8 -144,7 +152,8 @@@ bool NativeDense::load(const std::vecto
}
}
for (const auto& tensor : gguf.tensors()) {
- if (!eligible(tensor, include_ple_key)) continue;
+ if (!eligible(tensor, include_ple_key) || outside(tensor.name)) continue;
+ if (!in_range(tensor.name) && tensor.name.find("ple") == std::string::npos) continue;
if (!seen.insert(tensor.name).second) {
err = "native dense: duplicate tensor " + tensor.name; return false;
}
diff --cc src/core/verify.cpp
index 8a8b69bca,1a68d6fe3..868e32b18
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@@ -521,14 -409,15 +527,18 @@@ bool Verifier::record_window(int T, cud
const int64_t TS = (s.idx_block - 1) * ID;
const bool ple_on = ss.ple.ready() && ple_stage();
auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };
- const int G = (split_ && T >= 2) ? 2 : 1;
+ const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1; // a batch window is one group
static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
- auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); };
+ auto stamp = [&](int64_t l, int i, int grp) {
+ if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs);
+ if (trace_m_ != nullptr) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2 + grp), cs); // #649
+ };
const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T};
- groups_[T] = G;
+ if (!batch_rec_) groups_[T] = G;
+ const int64_t nQall = g.n_qsa_layers();
+ // a batch window: row t is slot t, whose state lives in its own session
+ auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) (row_base_ + t)] : ss; };
+ const int hrow0 = batch_rec_ ? row_base_ : 0; // a slot group's own hand-off rows
// ---- the window's inputs, from mapped staging
copy_i32_from_mapped(tok_, m_tok_, T, cs);
diff --cc src/program/generate.cpp
index b9a4440cc,83d853e6e..9978a45e4
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@@ -2144,40 -2000,34 +2160,43 @@@ int main(int argc, char** argv)
}
if (native_pack) skip.insert("token_embd.weight");
}
- // --trim-stage-weights: the layers each device runs, known before anything loads (explicit split only)
- const bool trim = o.trim_stage_weights && multi_gpu && !split_auto;
- if (o.trim_stage_weights && !trim)
+ // Layer split with explicit split points: every GPU holds only the dense weights of ITS layers (the PLE tensors
+ // stay everywhere). Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never
+ // reads - VRAM the expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50
+ // (PR #639), and the default waits for its author's re-run of the release branch on his cards.
+ const std::set<std::string> skip_base = skip;
- const bool stage_trim = multi_gpu && !split_auto && !split_at.empty() && [] {
++ // --trim-stage-weights (PR #559) is the same switch as STRATA_STAGE_TRIM=1 (PR #639)
++ const bool stage_trim = multi_gpu && !split_auto && !split_at.empty() && (o.trim_stage_weights || [] {
+ const char* v = std::getenv("STRATA_STAGE_TRIM");
+ return v != nullptr && v[0] != 0 && std::string(v) != "0";
- }();
++ }());
++ if (o.trim_stage_weights && !stage_trim)
+ std::fprintf(stderr, "strata generate: --trim-stage-weights needs an explicit --layer-split (ignored)\n");
- std::vector<std::string> pack_names;
- if (trim) {
- std::ifstream idx(o.pack + "/index.txt");
- for (std::string ln; std::getline(idx, ln);)
- if (!ln.empty() && ln[0] != '#') pack_names.push_back(ln.substr(0, ln.find(' ')));
- if (pack_names.empty()) {
- std::fprintf(stderr, "strata generate: --trim-stage-weights: cannot read %s/index.txt\n", o.pack.c_str());
- return 1;
+ // keep_routers: CUDA0 with --mmap-experts keeps every layer's router (ffn_gate_inp, ~2.5 MiB a layer) - the file
+ // tier's routing-aware prefetch (RouterLookahead, below) copies all of them from CUDA0's arena, and would
+ // otherwise turn itself off
+ auto add_foreign = [&](int64_t lb, int64_t le, std::set<std::string>& out, bool keep_routers) {
+ std::FILE* f = std::fopen((o.pack + "/index.txt").c_str(), "rb");
+ if (!f) return;
+ char line[1024], name[256];
+ while (std::fgets(line, sizeof line, f)) {
+ if (line[0] == '#' || std::sscanf(line, "%255s", name) != 1) continue;
+ const std::string n = name;
+ if (n.rfind("blk.", 0) != 0 || n.find("ple") != std::string::npos) continue;
+ if (keep_routers && n.ends_with(".ffn_gate_inp.weight")) continue;
+ const int64_t l = std::atoll(name + 4);
+ if (l < lb || l >= le) out.insert(n);
}
- std::fprintf(stderr, "strata generate: --trim-stage-weights: CUDA0 loads the dense weights of layers 0-%lld\n",
+ std::fclose(f);
+ };
+ if (stage_trim) {
+ add_foreign(0, split_at[0], skip, o.mmap_experts);
+ strata::core::NativeDense::set_layer_range(0, (int) split_at[0]);
+ std::fprintf(stderr, "strata generate: layer split: CUDA0 loads the dense weights of layers 0-%lld only\n",
(long long) split_at[0] - 1);
}
- auto range_skip = [&](int64_t lo, int64_t hi) { // skip + every blk.<l>. tensor outside [lo, hi)
- std::set<std::string> out = skip;
- for (const std::string& nm : pack_names) {
- if (nm.rfind("blk.", 0) != 0) continue;
- const long l = std::strtol(nm.c_str() + 4, nullptr, 10);
- if (l < lo || l >= hi) out.insert(nm);
- }
- return out;
- };
- const std::set<std::string> skip0 = trim ? range_skip(0, split_at[0]) : skip;
uint64_t pool_bytes = 0;
- if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip0.empty() ? nullptr : &skip0)) {
+ if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip.empty() ? nullptr : &skip)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
@@@ -5367,132 -5204,290 +5493,417 @@@
bool mrope_identity = true;
std::vector<float> img_rows;
std::vector<const float*> row_ptr;
+ // ---- #533: VRAM <reserve_mib>, between requests, only with --vram-elastic. It shrinks the expert cache
+ // until that much VRAM is free for other programs (a game, a CAD session), or grows it back towards its full
+ // size when more than that is free. Never on its own: only this command (the server's POST /v1/vram) moves
+ // it. A shrink gives back the cache's LAST segments: the experts in their slots become CPU misses, as any
+ // expert outside the cache is (no output changes beyond what a smaller cache decodes), the prompt path's
+ // loan moves down to the end of what is left (a smaller chunk when it no longer fits). A grow maps them
+ // again and puts each slot's expert back (or, when the adaptive tier already brought that one back, the
+ // most-routed missing expert of the same layer); the adaptive tier carries on from there.
+ std::vector<std::pair<int32_t, int32_t>> vram_evicted; // (residency index, slot) the shrinks took
+ const int64_t chunk_full = o.prefill_chunk; // the loan's chunk with the whole cache
+ auto relend = [&]() { // the prompt path's loan: the end of the slots left, its chunk as large as fits
+ if (pf_parts.empty() || pf_parts[0].first < 0) return;
+ PfPart& p = pf_parts[0];
+ const int64_t live = xcache.slots();
+ auto fits = [&](int64_t c) {
+ const int64_t k = part_slots(p, c);
+ return k > 0 && k + 128 <= live && !(o.prefill_auto && k * 100 > kAutoLendPct * live);
+ };
+ int64_t c = chunk_full;
+ while (c > 256 && !fits(c)) c = std::max<int64_t>(256, c / 2 / 256 * 256);
+ o.prefill_chunk = c;
+ p.first = (int32_t) std::max<int64_t>(0, live - part_slots(p, c));
+ p.first_now = -1; // laid out again at the next loan
+ };
+ auto vram_command = [&](const std::string& cmd, std::string& e) -> bool {
+ // `VRAM` alone: the reserve the engine started with (--vram-reserve-mib)
+ char* end = nullptr;
+ const bool bare = cmd.find_first_not_of(' ', 4) == std::string::npos;
+ const long long reserve = bare ? (long long) o.vram_reserve_mib : std::strtoll(cmd.c_str() + 4, &end, 10);
+ if (!bare && (end == cmd.c_str() + 4 || reserve < 0)) { e = "expected: VRAM [reserve_mib]"; return false; }
+ if (!xcache.segmented()) {
+ e = "VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)";
+ return false;
+ }
+ if (src.complement_ready()) {
+ e = "VRAM: not with the resident low-RAM mode (the cache holds experts RAM does not)";
+ return false;
+ }
+ if (peer.valid()) { e = "VRAM: not with --peer-device"; return false; }
+ for (const PfPart& p : pf_parts)
+ if (!p.lent.empty()) { e = "VRAM: a prompt's loan is still out"; return false; }
+ if (!ver.wait_commit(e)) return false;
+ apply_pending(true); // the adaptive tier's swaps in flight land first
+ if (cudaDeviceSynchronize() != cudaSuccess) {
+ e = std::string("VRAM: ") + cudaGetErrorString(cudaGetLastError());
+ return false;
+ }
+ const auto t0 = Clock::now();
+ size_t free_b = 0, total_b = 0;
+ cudaMemGetInfo(&free_b, &total_b);
+ const int64_t want_free = (int64_t) reserve << 20, mapped = xcache.mapped_bytes();
+ const int64_t before = xcache.slots();
+ // what stays at least: the prompt path's smallest loan (256 tokens) and the 128 slots it must leave
+ const int64_t floor_slots = std::min<int64_t>(xcache.full_slots(),
+ 128 + (pf_parts.empty() || pf_parts[0].first < 0 ? 0 : part_slots(pf_parts[0], 256)));
+ std::string note;
+ if ((int64_t) free_b < want_free) {
+ const int64_t floor_b = xcache.bytes_of(floor_slots);
+ int64_t keep = mapped - (want_free - (int64_t) free_b);
+ if (keep < floor_b) {
+ keep = floor_b;
+ note = " (the cache keeps its smallest size: the prompt path's buffers)";
+ }
+ if (!xcache.shrink(keep, e)) return false;
+ const int64_t live = xcache.slots();
+ for (size_t i = 0; i < host_res.size(); ++i)
+ if (host_res[i] >= live) {
+ vram_evicted.emplace_back((int32_t) i, host_res[i]);
+ host_res[i] = strata::core::kNotResident;
+ }
+ res_upload();
+ } else if (mapped < xcache.full_bytes()) {
+ std::string gerr;
+ if (!xcache.grow(mapped + ((int64_t) free_b - want_free), gerr)) note = " (" + gerr + ")";
+ const int64_t live = xcache.slots();
+ std::string ferr;
+ std::vector<std::pair<int32_t, int32_t>> keep_out;
+ for (const auto& [i, slot] : vram_evicted) {
+ if (slot >= live) { keep_out.emplace_back(i, slot); continue; }
+ const int64_t layer = i / g.n_expert;
+ int64_t pick = i;
+ if (host_res[(size_t) i] >= 0) { // back already (the adaptive tier): the layer's most-routed miss
+ pick = -1;
+ float best = -1.0f;
+ for (int64_t ex = 0; ex < g.n_expert; ++ex) {
+ const size_t j = (size_t) (layer * g.n_expert + ex);
+ if (host_res[j] >= 0) continue;
+ const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[j];
+ if (u > best) { best = u; pick = (int64_t) j; }
+ }
+ }
+ if (pick < 0) continue;
+ const uint8_t* b = srcp->blob(layer, pick % g.n_expert);
+ if (b == nullptr || !xcache.fill_slot_queued(slot, b, ferr,
+ (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(layer))) {
+ e = "VRAM: refilling the cache failed: " + ferr;
+ return false;
+ }
+ host_res[(size_t) pick] = slot;
+ }
+ vram_evicted.swap(keep_out);
+ if (!xcache.sync_queued(ferr)) { e = "VRAM: " + ferr; return false; }
+ res_upload();
+ }
+ relend();
+ cudaMemGetInfo(&free_b, &total_b);
+ std::fprintf(stderr, "strata serve: VRAM %lld MiB kept free: the expert cache %lld -> %lld of %lld slots "
+ "(%.2f of %.2f GiB), %lld MiB free now, prompt chunk %lld, in %.0f ms%s\n",
+ reserve, (long long) before, (long long) xcache.slots(), (long long) xcache.full_slots(),
+ (double) xcache.mapped_bytes() / 1073741824.0, (double) xcache.full_bytes() / 1073741824.0,
+ (long long) (free_b >> 20), (long long) o.prefill_chunk,
+ std::chrono::duration<double, std::milli>(Clock::now() - t0).count(), note.c_str());
+ std::printf("VRAM reserve_mib=%lld expert_slots=%lld expert_slots_full=%lld expert_cache_mib=%lld "
+ "expert_cache_full_mib=%lld vram_free_mib=%lld prompt_chunk=%lld\n", reserve,
+ (long long) xcache.slots(), (long long) xcache.full_slots(),
+ (long long) (xcache.mapped_bytes() >> 20), (long long) (xcache.full_bytes() >> 20),
+ (long long) (free_b >> 20), (long long) o.prefill_chunk);
+ return true;
+ };
- while (next_line(line)) {
+ // ---- --batch: the slots of the batch windows
+ struct BSlot {
+ bool active = false, stop = false;
+ int32_t x = 0; ///< the token the next window feeds (not yet in the slot's state)
+ int64_t p = 0; ///< its position
+ int64_t produced = 0, max_new = 0;
+ Clock::time_point t0;
+ };
+ std::vector<BSlot> bs((size_t) std::max(o.batch, 0));
+ // timing of the batch windows since the slots were last all idle (one stderr line then)
+ 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;
+ 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;
+ auto batch_on = [&] { for (const BSlot& b : bs) if (b.active) return true; return false; };
+ auto try_next_line = [&](std::string& out) -> bool {
+ std::lock_guard<std::mutex> lk(in_mu);
+ if (in_lines.empty()) return false;
+ out = std::move(in_lines.front());
+ in_lines.pop_front();
+ return true;
+ };
+ // the session a request just left behind (its prompt) -> slot b's sessions, on every stage
+ auto copy_to_slot = [&](int b, const std::vector<int32_t>& ids, std::string& e) -> bool {
+ const int64_t upto = (int64_t) ids.size();
+ for (size_t k = 0; k < bslot_ss.size(); ++k) {
+ strata::core::SessionState& from = k == 0 ? ss : stages[k - 1]->ss;
+ strata::core::SessionState& to = *bslot_ss[k][(size_t) b];
+ const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev);
+ if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; }
+ strata::core::ConversationCheckpoint ck;
+ ck.ids = ids;
+ if (!strata::core::conversation_checkpoint_save(ck, from, g, e) ||
+ !strata::core::conversation_checkpoint_restore(ck, to, g, e))
+ return false;
+ for (int64_t j = 0; j < from.qsa_alloc; ++j) {
+ strata::core::ConversationKv img;
+ if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e))
+ return false;
+ if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; }
+ if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e))
+ return false;
+ }
+ if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; }
+ }
+ return true;
+ };
+ // one batch window over slots [0, highest active], inactive slots below it fed a pad token at position 0
+ auto batch_step = [&]() -> bool {
+ int S = 0;
+ for (int b = 0; b < (int) bs.size(); ++b) if (bs[(size_t) b].active) S = b + 1;
+ if (S == 0) return true;
+ int32_t tok[strata::kernels::kVerifyMaxT] = {}, outb[strata::kernels::kVerifyMaxT] = {};
+ int64_t pos[strata::kernels::kVerifyMaxT] = {};
+ for (int b = 0; b < S; ++b)
+ if (bs[(size_t) b].active) { tok[b] = bs[(size_t) b].x; pos[b] = bs[(size_t) b].p; }
+ strata::core::progress().busy.store(true);
+ drive.d.layers = 0;
+ drive.d.experts = 0;
+ drive.d.failed = false;
+ apply_pending(false);
+ if (bt_windows == 0) {
+ 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;
+ }
+ const Clock::time_point w0 = Clock::now();
+ if (!ver.run_slots(S, tok, pos, win_pool_fn, win_pool_user, outb, err) || drive.d.failed) {
+ std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());
+ return false;
+ }
+ const Clock::time_point w1 = Clock::now();
+ if (!ver.commit_slots(err)) {
+ std::printf("ERR %s\n", err.c_str());
+ return false;
+ }
+ const Clock::time_point w2 = Clock::now();
+ auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration<double, std::milli>(b0 - a0).count(); };
+ bt_run += msd(w0, w1);
+ bt_commit += msd(w1, w2);
+ ++bt_windows;
+ bt_rows += S;
+ for (int b = 0; b < S; ++b) {
+ BSlot& sl = bs[(size_t) b];
+ if (!sl.active) continue;
+ const int32_t y = outb[b];
+ std::printf("BT %d %d\n", b, (int) y);
+ ++sl.produced;
+ const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
+ const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
+ : sl.p + 2 > o.max_context ? "length" : nullptr;
+ if (fin != nullptr) {
+ const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
+ std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms);
+ sl.active = false;
+ } else {
+ sl.x = y;
+ sl.p += 1;
+ }
+ }
+ std::fflush(stdout);
+ bt_emit += msd(w2, Clock::now());
+ strata::core::progress().busy.store(false);
+ 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;
+ 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,
+ (ver.ms_wait - bt_wait0) / w, (ver.ms_pool - bt_pool0) / w, bt_commit / w, bt_emit / w,
+ (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);
+ 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());
+ }
+ bt_run = bt_commit = bt_emit = 0;
+ bt_windows = bt_rows = bt_tokens = 0;
+ }
+ return true;
+ };
+ // ---- --batch-groups: the slot groups pipelined through the stages (--batch-groups G > 1 with a layer split)
+ const int n_pipe = (int) stages.size() + 1;
+ const bool piped = o.batch > 0 && o.batch_groups > 1 && n_pipe > 1;
+ if (o.batch > 0 && o.batch_groups > 1 && (o.batch % o.batch_groups != 0 || !piped)) {
+ std::fprintf(stderr, "strata serve: --batch-groups needs a layer split and to divide --batch\n");
+ return 1;
+ }
+ const int GS = piped ? o.batch / o.batch_groups : o.batch;
+ struct PGroup {
+ bool inflight = false;
+ int stage = 0; ///< the stage it runs on or waits for
+ int32_t tok[strata::kernels::kVerifyMaxT] = {};
+ int64_t pos[strata::kernels::kVerifyMaxT] = {};
+ int64_t since = 0; ///< tick it started waiting (fairness)
+ };
+ std::vector<PGroup> pg((size_t) (piped ? o.batch_groups : 0));
+ std::vector<int> 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;
+ return false;
+ };
+ // one turn: serve every running stage, hand finished groups on, start what can start
+ auto pump = [&](bool may_start) -> bool {
+ ++pipe_tick;
+ if (bt_windows == 0 && !pipe_inflight()) {
+ 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;
+ }
+ for (int k = 0; k < n_pipe; ++k) {
+ const int gi = stage_group[(size_t) k];
+ if (gi < 0) continue;
+ strata::core::Verifier& vk = stage_verifier(k);
+ const int r = vk.batch_poll(win_pool_fn, win_pool_user, err);
+ if (r < 0) { std::printf("ERR %s\n", err.c_str()); return false; }
+ if (r == 0) continue;
+ stage_group[(size_t) k] = -1;
+ PGroup& G = pg[(size_t) gi];
+ if (k + 1 < n_pipe) { G.stage = k + 1; G.since = pipe_tick; continue; }
+ // the last stage: the group's picks
+ const int32_t* outb = vk.batch_out();
+ for (int t = 0; t < GS; ++t) {
+ BSlot& sl = bs[(size_t) (gi * GS + t)];
+ if (!sl.active) continue;
+ const int32_t y = outb[t];
+ std::printf("BT %d %d\n", gi * GS + t, (int) y);
+ ++sl.produced;
+ ++bt_rows;
+ const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
+ const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
+ : sl.p + 2 > o.max_context ? "length" : nullptr;
+ if (fin != nullptr) {
+ const double ms = std::chrono::duration<double, std::milli>(Clock::now() - sl.t0).count();
+ std::printf("BDONE %d %lld %s %.1f\n", gi * GS + t, (long long) sl.produced, fin, ms);
+ sl.active = false;
+ } else {
+ sl.x = y;
+ sl.p += 1;
+ }
+ }
+ std::fflush(stdout);
+ ++bt_windows;
+ G.inflight = false;
+ }
+ // start waiting groups on free stages, the longest waiting first; a new step on stage 0 round-robin
+ for (int k = n_pipe - 1; k >= 0; --k) {
+ if (stage_group[(size_t) k] >= 0) continue;
+ int pick = -1;
+ if (k > 0) {
+ for (int gi = 0; gi < (int) pg.size(); ++gi)
+ if (pg[(size_t) gi].inflight && pg[(size_t) gi].stage == k &&
+ (pick < 0 || pg[(size_t) gi].since < pg[(size_t) pick].since))
+ pick = gi;
+ if (pick < 0) continue;
+ } else {
+ if (!may_start) continue;
+ for (int j = 0; j < (int) pg.size() && pick < 0; ++j) {
+ const int gi = (int) ((rr + j) % (int64_t) pg.size());
+ if (!pg[(size_t) gi].inflight && group_active(gi)) pick = gi;
+ }
+ if (pick < 0) continue;
+ rr = pick + 1;
+ PGroup& G = pg[(size_t) pick];
+ for (int t = 0; t < GS; ++t) {
+ const BSlot& sl = bs[(size_t) (pick * GS + t)];
+ G.tok[t] = sl.active ? sl.x : 0;
+ G.pos[t] = sl.active ? sl.p : 0;
+ }
+ G.inflight = true;
+ G.stage = 0;
+ drive.d.failed = false;
+ apply_pending(false);
+ }
+ PGroup& G = pg[(size_t) pick];
+ strata::core::progress().busy.store(true);
+ if (!stage_verifier(k).batch_launch(pick * GS, GS, G.tok, G.pos, err)) {
+ std::printf("ERR %s\n", err.c_str());
+ return false;
+ }
+ stage_group[(size_t) k] = pick;
+ }
+ if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; }
+ if (!pipe_inflight() && !batch_on() && bt_windows > 0) { // all idle: the timing line, as batch_step
+ const double w = (double) bt_windows, wall = std::chrono::duration<double, std::milli>(Clock::now() - bt_start).count();
+ std::fprintf(stderr, "strata batch (pipelined, %d groups of %d): %lld group-steps, %lld rows in %.0f ms = "
+ "%.1f rows/s (admissions included)\n", o.batch_groups, GS, (long long) bt_windows,
+ (long long) bt_rows, wall, 1000.0 * bt_rows / std::max(wall, 1e-9));
+ for (int k = 0; k < n_pipe; ++k) {
+ const std::string pr = stage_verifier(k).profile_report();
+ if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str());
+ }
+ bt_windows = bt_rows = 0;
+ strata::core::progress().busy.store(false);
+ }
+ return true;
+ };
+ auto pipe_drain = [&]() -> bool {
+ while (pipe_inflight())
+ if (!pump(false)) return false;
+ return true;
+ };
+ for (;;) {
+ if (batch_on() || (piped && pipe_inflight())) {
+ if (!try_next_line(line)) {
+ if (!(piped ? pump(true) : batch_step())) return 1;
+ continue;
+ }
+ // a request reads its prompt through every stage: the groups in flight finish first
+ if (piped && line.rfind("BSTOP ", 0) != 0 && !pipe_drain()) return 1;
+ } else if (!next_line(line)) {
+ break;
+ }
+ // --batch: BSTOP <slot> ends that slot at its next batch window; BGEN <slot> <max_new> ... reads the
+ // request's prompt and first token as a GEN 1, then continues it in that slot
+ if (line.rfind("BSTOP ", 0) == 0) {
+ const int b = std::atoi(line.c_str() + 6);
+ if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true;
+ continue;
+ }
+ if (line.rfind("VRAM", 0) == 0) { // #533 (above): between requests, not a request
+ std::string verr;
- if (!vram_command(line, verr)) std::printf("ERR %s\n", verr.c_str());
++ if (batch_on()) verr = "VRAM: not while batch slots are decoding";
++ else vram_command(line, verr);
++ if (!verr.empty()) std::printf("ERR %s\n", verr.c_str());
+ std::fflush(stdout);
+ continue;
+ }
+ admit_slot = -1;
+ if (line.rfind("BGEN ", 0) == 0 || line.rfind("BGENI ", 0) == 0) {
+ const bool bimg = line.rfind("BGENI ", 0) == 0;
+ char* e1 = nullptr;
+ const long b = std::strtol(line.c_str() + (bimg ? 6 : 5), &e1, 10);
+ char* e2 = nullptr;
+ const long long mn = std::strtoll(e1, &e2, 10);
+ if (bs.empty() || b < 0 || b >= (long) bs.size() || bs[(size_t) b].active || mn < 1 || e2 == e1) {
+ std::printf("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n", o.batch);
+ std::fflush(stdout);
+ continue;
+ }
+ admit_slot = (int) b;
+ admit_max_new = mn;
+ line = std::string(bimg ? "GENI 1" : "GEN 1") + e2;
+ }
// #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop)
if (!heat.empty() && line != "QUIT" && o.expert_profile_save_min > 0 &&
Clock::now() - profile_saved_at >= std::chrono::duration<double>(o.expert_profile_save_min * 60.0))
@@@ -6418,9 -6439,29 +6869,30 @@@
(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,
(long long) resume, (long long) req_hits, (long long) req_look,
(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),
- (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n);
+ (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n,
+ (long long) req_offload);
std::fflush(stdout);
+ if (admit_slot >= 0) { // --batch: BADM <slot> <1 = continues in the batch windows | 0 = done>
+ bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0;
+ if (cont && !copy_to_slot(admit_slot, live, err)) {
+ std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str());
+ cont = false;
+ }
+ if (cont) {
+ ver.set_slot_sampling(admit_slot, req_sp); // the request's own sampling, row by row
+ BSlot& sl = bs[(size_t) admit_slot];
+ sl = BSlot{};
+ sl.active = true;
+ sl.x = x;
+ sl.p = p;
+ sl.produced = 1;
+ sl.max_new = admit_max_new;
+ sl.t0 = Clock::now();
+ }
+ std::printf("BADM %d %d\n", admit_slot, cont ? 1 : 0);
+ std::fflush(stdout);
+ admit_slot = -1;
+ }
if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session
// "12288 of 98179" when cancelled mid-read (#471), the rate from what was read
char read_txt[64];