From 6fb110e557af17c4abc0e4038de9d86fe01901c6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 11:08:53 +0100 Subject: [PATCH] Opt-in research switches: STRATA_PAR_COUNTERS, STRATA_PIPED_CONCURRENT_MIN, multi-prompt layer-major read (Prefill::run_multi, BCO co-reads, server STRATA_COALESCE_PREFILL), STRATA_CRASH_BT --- include/strata/prefill/prefill.hpp | 18 +++ include/strata/program/par_counters.hpp | 93 +++++++++++ serve/server.py | 74 ++++++++- src/prefill/prefill.cpp | 205 +++++++++++++++++++----- src/program/generate.cpp | 156 +++++++++++++++++- 5 files changed, 496 insertions(+), 50 deletions(-) create mode 100644 include/strata/program/par_counters.hpp diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 549aff38..3e2e13c0 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -10,6 +10,8 @@ // Requires the native weights (`--native`): every quantized projection must carry its GGUF blocks. #pragma once +#include + #include "strata/core/expert_cache.hpp" #include "strata/core/expert_source.hpp" #include "strata/core/layer.hpp" @@ -265,6 +267,19 @@ public: /// Layer-major prefill (STRATA_PREFILL_LAYER_MAJOR=1): true while `on_chunk` reports a sub-chunk before the end of /// its super-chunk. The session state is already at the super-chunk's end then, so no checkpoint may be taken. /// On a layer split it is the last stage's (the one that reports the rows), asked through the first. + /// One prompt of a multi-prompt read (run_multi): its tokens, the position it starts at and, per stage of a layer split + /// (index 0 = the first stage), the session it reads into (nullptr / missing: that stage's own main session). + struct Seg { + const int64_t* tokens = nullptr; + int64_t n = 0; + int64_t pos0 = 0; + std::vector stage_ss; + }; + /// Several prompts in ONE layer-major pass (the streamed experts of a layer are read once for all of them). Each + /// prompt fills its own sessions; `on_chunk` / `on_stage_chunk` report the FIRST prompt only. Returns false with `err` + /// when the layer-major walk does not apply (then nothing was read; the caller reads the prompts one by one). + bool run_multi(const std::vector& segs, std::string& err); + bool layer_major_mid() const { const Prefill* p = this; while (p->next_ != nullptr) p = p->next_; @@ -282,8 +297,11 @@ private: int64_t lm_prepare_chain(int64_t n, std::string& why); void lm_release_chain(); bool run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); + struct LmSub { int seg = 0; int64_t c0 = 0, T = 0, t0 = 0; }; ///< a sub-chunk: prompt, first token, tokens, row in the super-chunk + bool lm_run(const std::vector& segs, int depth, const std::vector* given_super, std::string& err); void lm_release(); bool lm_mid_ = false; + bool lm_force_ = false; ///< run_multi: the walk even for a short total bool lm_by_default_ = false; ///< the walk is on because nothing was set (a wider VRAM margin, the measured super-chunk size) // Stage-1 pipeline: intermediate stages return after handing their chunk to // the direct successor. The public run() drains the chain once at prompt end. diff --git a/include/strata/program/par_counters.hpp b/include/strata/program/par_counters.hpp new file mode 100644 index 00000000..fce07ca9 --- /dev/null +++ b/include/strata/program/par_counters.hpp @@ -0,0 +1,93 @@ +// include/strata/program/par_counters.hpp - STRATA_PAR_COUNTERS=1: counters-only parallelism accounting (research, opt-in). +// +// Off (the default), every hook is one branch on a const bool and reads no clock. On, the batch loop (one host thread) +// adds plain integers and, at the places that already wait (a drain, an admission), two clock reads. Nothing here +// synchronizes a device. Printed to stderr as "strata par: ..." with the batch summary line (when the loop goes idle): +// windows group windows launched, rows carried, rows used by live slots, padded rows, histogram of live slots per window +// drains pipeline drains before a control line, by line kind (BGEN = an admission), groups in flight, ms waited +// admissions prompts admitted into a slot: prompt tokens, ms in the prompt phase, ms of the drain before it +// idle ticks with stage 0 free and no launchable group (no live slot / every group in flight) +// Stage busy/idle with reason stays in STRATA_P4_TIMING (pipe_probe.hpp); this adds what it lacked. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace strata::program { + +/// Expert-dispatch totals (cumulative in the engine); a span's delta is printed at flush. +struct ParEx { long long misses = 0, entries = 0, hits = 0, offload = 0, pcie = 0; double run_ms = 0, jobs_ms = 0, vwait_ms = 0, vpool_ms = 0; }; + +class ParCounters { +public: + using Ex = ParEx; + using Clock = std::chrono::steady_clock; + ParCounters() { const char* e = std::getenv("STRATA_PAR_COUNTERS"); on_ = e != nullptr && e[0] == '1' && e[1] == '\0'; } + bool on() const { return on_; } + + void window(int rows, int live) { + if (!on_) return; + ++windows_; rows_ += rows; used_ += live; + ++hist_[live < 0 ? 0 : (live > kHist - 1 ? kHist - 1 : live)]; + } + void drain(const std::string& line, int groups_in_flight, double ms) { + if (!on_) return; + const bool adm = line.rfind("BGEN", 0) == 0; + if (adm) { ++adm_drains_; adm_drain_ms_ += ms; } else { ++other_drains_; other_drain_ms_ += ms; } + if (groups_in_flight > 0) ++drains_busy_; + groups_at_drain_ += groups_in_flight; + } + void admission(long long prompt_tokens, double prompt_ms) { + if (!on_) return; + ++adm_; adm_tokens_ += prompt_tokens; adm_ms_ += prompt_ms; + } + void begin(const Ex& e, int layers) { if (on_) { ex0_ = e; layers_ = layers > 0 ? layers : 1; } } + void adapt(double ms) { if (on_) { ++adapt_; adapt_ms_ += ms; } } + void no_launch(bool any_live) { if (on_) { if (any_live) ++idle_all_inflight_; else ++idle_no_live_; } } + + void flush(double wall_ms, const ParEx& e = ParEx{}) { + if (!on_ || (windows_ == 0 && adm_ == 0 && adm_drains_ + other_drains_ == 0)) return; + std::fprintf(stderr, "strata par: wall %.0f ms; windows %lld rows %lld used %lld padded %lld (%.1f%% used); live slots/window:", + wall_ms, windows_, rows_, used_, rows_ - used_, rows_ ? 100.0 * used_ / rows_ : 0.0); + for (int i = 0; i < kHist; ++i) if (hist_[i]) std::fprintf(stderr, " %d:%lld", i, hist_[i]); + std::fprintf(stderr, "; drains: admission %lld (%.0f ms) other %lld (%.0f ms), %lld with groups in flight, avg %.2f groups; " + "admissions %lld, %lld prompt tokens in %.0f ms; adapt rounds %lld %.0f ms; " + "ticks without a launch: no live slot %lld, all groups in flight %lld\n", + adm_drains_, adm_drain_ms_, other_drains_, other_drain_ms_, drains_busy_, + (adm_drains_ + other_drains_) ? (double) groups_at_drain_ / (adm_drains_ + other_drains_) : 0.0, adm_, adm_tokens_, adm_ms_, + adapt_, adapt_ms_, idle_no_live_, idle_all_inflight_); + if (windows_ > 0 && (e.misses | e.entries | e.hits | e.offload) != 0) { + const double wl = (double) windows_ * layers_; + std::fprintf(stderr, "strata par experts: per window-layer: routed entries (CPU) %.2f, distinct CPU-computed experts %.2f, " + "GPU cache hits %.2f, PCIe/offload entries %.2f, distinct PCIe experts %.2f; ms per window: CPU pool run %.2f, " + "job build %.2f, verifier wait %.2f, verifier pool %.2f (of %.2f wall)\n", + (e.entries - ex0_.entries) / wl, (e.misses - ex0_.misses) / wl, (e.hits - ex0_.hits) / wl, + (e.offload - ex0_.offload) / wl, (e.pcie - ex0_.pcie) / wl, (e.run_ms - ex0_.run_ms) / windows_, + (e.jobs_ms - ex0_.jobs_ms) / windows_, (e.vwait_ms - ex0_.vwait_ms) / windows_, + (e.vpool_ms - ex0_.vpool_ms) / windows_, wall_ms / windows_); + } + std::fflush(stderr); + reset(); + } + +private: + static constexpr int kHist = 18; + void reset() { + windows_ = rows_ = used_ = adm_drains_ = other_drains_ = drains_busy_ = groups_at_drain_ = adm_ = adm_tokens_ = adapt_ = 0; + idle_no_live_ = idle_all_inflight_ = 0; + adm_drain_ms_ = other_drain_ms_ = adm_ms_ = adapt_ms_ = 0; + std::memset(hist_, 0, sizeof hist_); + } + bool on_ = false; + Ex ex0_{}; + int layers_ = 1; + long long windows_ = 0, rows_ = 0, used_ = 0, adm_drains_ = 0, other_drains_ = 0, drains_busy_ = 0, groups_at_drain_ = 0; + long long adm_ = 0, adm_tokens_ = 0, adapt_ = 0, idle_no_live_ = 0, idle_all_inflight_ = 0, hist_[kHist] = {}; + double adm_drain_ms_ = 0, other_drain_ms_ = 0, adm_ms_ = 0, adapt_ms_ = 0; +}; + +} // namespace strata::program diff --git a/serve/server.py b/serve/server.py index 5614dbf1..9a1a3804 100644 --- a/serve/server.py +++ b/serve/server.py @@ -327,6 +327,7 @@ def _timeout_env(name: str, default: float) -> float | None: # still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable). # STRATA_ENGINE_STALL_S overrides it (0 = off). Needs psutil (setup installs it); without it nothing is ended. ENGINE_STALL_S = _timeout_env("STRATA_ENGINE_STALL_S", 90.0) +PAR_COUNTERS = os.environ.get("STRATA_PAR_COUNTERS") == "1" # research counters (queue wait for a slot), shown in /v1/status # --batch: new requests take the control lines (one prompt read at a time) short prompts first: a prompt of at most # STRATA_ADMIT_SHORT_FIRST tokens goes before longer ones (opt-in; unset or 0: whoever gets the lock first), and a # longer one that waited STRATA_ADMIT_MAX_WAIT_S (default 30) counts as short. A chat question then waits for the one @@ -336,6 +337,13 @@ try: except ValueError: ADMIT_SHORT_FIRST = 0 ADMIT_MAX_WAIT_S = _timeout_env("STRATA_ADMIT_MAX_WAIT_S", 30.0) or 0.0 +# STRATA_COALESCE_PREFILL=N (research, PAR-H; needs the engine's BCO / BCOK lines): a request that takes the control lines +# for its admission also sends the prompts of up to N-1 requests still waiting for them (BCO , into free slots +# it reserves for them); the engine reads all the prompts in ONE layer-major pass, so the experts a layer streams are +# read once for all of them, and each waiting request then finds its prompt in its slot. 0 / unset: off. +COALESCE_PREFILL = max(0, int(os.environ.get("STRATA_COALESCE_PREFILL") or 0)) +COALESCE_TOKENS = max(256, int(os.environ.get("STRATA_COALESCE_TOKENS") or 16384)) # prompt tokens read together at most +COALESCE_WAIT_MS = max(0, int(os.environ.get("STRATA_COALESCE_WAIT_MS") or 0)) # a burst's later requests register within this long STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window @@ -1193,6 +1201,7 @@ class StrataEngine: self.slot_cv = threading.Condition() self.waiting = 0 # requests waiting for the control lines (ctl) self.admitting = 0 # #1603: ... and those that gave the lines back to wait for a slot + self.par_counters = {"queued": 0, "queue_wait_s": 0.0} self.wait_lens: list[list[int]] = [] # ... their prompt lengths (a long read gives way to short ones) self.ctl_epoch = 0 # how often the control lines were taken self.ctl = threading.Lock() # one admission or solo request on the control lines at a time @@ -1575,6 +1584,8 @@ class StrataEngine: f = line.split() self._ctl_result = ("badm", len(f) >= 3 and f[2] == "1") return + elif line.startswith("BCOK "): # STRATA_COALESCE_PREFILL: : the slot holds a waiting prompt + pass elif line.startswith("YIELDED "): # the read gave way (BYIELD): f = line.split() if len(f) >= 3 and f[1].lstrip("-").isdigit() and f[2].isdigit(): @@ -1726,11 +1737,11 @@ class StrataEngine: YIELDS_MAX = 2 # #656: how often one request's prompt read gives way to a shorter waiting one - def _take_control(self, cancel, plen: int, after_epoch: int | None = None, new: bool = False): + def _take_control(self, cancel, plen: int, after_epoch: int | None = None, new: bool = False, prompt=None): """Waits for the control lines (one prompt read at a time), yielding None heartbeats; False when cancelled. `after_epoch`: a request whose read gave way lets the requests waiting then go first. `new`: the request's first admission (STRATA_ADMIT_SHORT_FIRST orders only these).""" - entry = [plen, time.monotonic(), new] # (length, arrival, ordered: STRATA_ADMIT_SHORT_FIRST) + entry = [plen, time.monotonic(), new, prompt, cancel] # (length, arrival, ordered: STRATA_ADMIT_SHORT_FIRST; the prompt and request, for STRATA_COALESCE_PREFILL) with self.slot_cv: self.waiting += 1 self.wait_lens.append(entry) @@ -1784,6 +1795,51 @@ class StrataEngine: self.slot_cv.notify_all() return True + def _release_preslot(self, cancel): + """STRATA_COALESCE_PREFILL: the request that was given a slot ahead of its turn left before using it.""" + slot = getattr(cancel, "_strata_preslot", None) + if slot is None: + return + cancel._strata_preslot = None + with self.slot_cv: + self.slot_busy[slot] = False + self.slot_claims.discard(slot) + self.slot_cv.notify_all() + + def _coalesce(self, cancel, lead_prompt): + """STRATA_COALESCE_PREFILL (the caller holds the control lines and sends its BGEN right after): reserve free slots + for requests still waiting for the control lines and send their prompts as BCO lines; the engine reads them in the + same layer-major pass as the BGEN's prompt. Each follower finds its slot in cancel._strata_preslot.""" + picked = [] + total = len(lead_prompt) + if COALESCE_WAIT_MS > 0: + time.sleep(COALESCE_WAIT_MS / 1000.0) # the requests of a burst reach the server a few ms apart + with self.slot_cv: + for e in list(self.wait_lens): + if len(picked) >= COALESCE_PREFILL - 1: + break + prompt = e[3] if len(e) > 4 else None + rq = e[4] if len(e) > 4 else None + if prompt is None or rq is None or rq is cancel or getattr(rq, "_strata_preslot", None) is not None: + continue + if getattr(rq, "_strata_co", False) or len(prompt) < 32 or total + len(prompt) > COALESCE_TOKENS: + continue + slot = self.pick_slot(prompt) + if slot is None: + break + self.slot_busy[slot] = True + self.slot_claims.add(slot) + self.slot_held[slot] = [] + rq._strata_preslot = slot + rq._strata_co = True + total += len(prompt) + picked.append((slot, prompt)) + for slot, prompt in picked: + self._send(f"BCO {slot} {','.join(str(int(t)) for t in prompt)}") + if picked: + print(f"[strata] coalesce: {len(picked)} waiting prompt(s) ({total - len(lead_prompt)} tokens) read with this " + f"request's {len(lead_prompt)}", flush=True) + def _admit_next(self): """STRATA_ADMIT_SHORT_FIRST= (the caller holds slot_cv): the new request that takes the control lines next - one whose prompt is at most that long (it reads little) before a longer one, in arrival order within @@ -1839,12 +1895,17 @@ class StrataEngine: prompt, left = list(ids), int(max_new) reused0 = None # the first read's reused tokens: a continued leg's count includes this request's own output carry = {} # #1869: the figures of the legs that ended in a hand-back to the solo path (the final DONE adds to them) - ok = yield from self._take_control(cancel, len(prompt), new=True) + ok = yield from self._take_control(cancel, len(prompt), new=True, + prompt=prompt if (COALESCE_PREFILL > 1 and not embeddings) else None) if not ok: + self._release_preslot(cancel) return holding, born = True, self.gen # (the engine it now has the control lines of) btrace("ctl acquired") slot, gen0, reserved = None, None, None + pre = getattr(cancel, "_strata_preslot", None) + if pre is not None: # STRATA_COALESCE_PREFILL: a request before this one read the prompt into this slot + slot, cancel._strata_preslot = pre, None phase = "none" # solo -> (admit -> slot) ; "done" once the engine has finished with this request stop_sent = False yields, solo_again, refused = 0, 0, 0 @@ -1941,6 +2002,9 @@ class StrataEngine: if admit_wait: admit_wait = False self.admitting = max(0, self.admitting - 1) + if PAR_COUNTERS: # STRATA_PAR_COUNTERS=1: time spent waiting for a free slot + self.par_counters["queued"] += 1 + self.par_counters["queue_wait_s"] += time.monotonic() - admit_since break if not admit_wait: # #1603: counted while it waits for a slot (it holds no admit_wait, admit_since = True, time.monotonic() # control lines then) @@ -1993,6 +2057,8 @@ class StrataEngine: raise QueueWaitExpired("the inference queue wait deadline expired; retry later") self.slot_live[slot] = live self._last_done = None # (#879: this admission's DONE decides below) + if COALESCE_PREFILL > 1 and not embeddings: + self._coalesce(cancel, prompt) self._send(f"{head} {','.join(str(int(t)) for t in prompt)}") if deadline is not None: cancel._strata_queue_deadline = None @@ -4795,6 +4861,8 @@ class Service: slots = self.engine.slots_view() if hasattr(self.engine, "slots_view") else [] # the requests in flight that are not in a slot: the one alone on the solo path, or waiting their turn in_slots = sum(1 for x in slots if x["state"] != "idle") + if PAR_COUNTERS: + live["par_counters"] = dict(self.par_counters) live.update(parallel=par, running=running, slots=slots, outside_slots=max(0, running - in_slots), waiting=int(getattr(self.engine, "waiting", 0) or 0), admitting=int(getattr(self.engine, "admitting", 0) or 0)) diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 16a609a5..dcf8bc11 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -5882,6 +5882,11 @@ const char* lm_env_text() { // STRATA_PREFILL_LAYER_MAJOR as set (nullptr: uns } bool lm_env_explicit() { const char* e = lm_env_text(); return e != nullptr && e[0] != '\0'; } +bool lm_force_env() { // STRATA_PREFILL_LM_FORCE=1 (research): the layer-major walk even for a prompt under two chunks (the identity reference of a multi-prompt read) + static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_LM_FORCE"); return e != nullptr && e[0] == '1'; }(); + return v; +} + bool lm_even_env() { // even super-chunks (STRATA_PREFILL_LM_EVEN=0: the largest that fits, then the rest) static const bool v = [] { const char* e = std::getenv("STRATA_PREFILL_LM_EVEN"); return !(e && e[0] == '0'); }(); return v; @@ -5996,13 +6001,13 @@ int64_t Prefill::lm_prepare(int64_t n, std::string& why, int64_t cap) { if (m.fused_bufs) { why = "the fused expert layout"; return 0; } if (!m.GU || !m.Dm || (n_mmq > 0 && !m.ids_identity)) { why = "the MoE buffers are missing"; return 0; } // (an explicit STRATA_PREFILL_LM_TOKENS may be one chunk: the A/B against the default path, experts aside) - const int64_t min_s = lm_tokens_env() > 0 ? m.T : 2 * m.T; + const int64_t min_s = (lm_force_ || lm_force_env()) ? 1 : (lm_tokens_env() > 0 ? m.T : 2 * m.T); // (lm_force_: run_multi - several prompts, however short) if (n < min_s) { why = "a short prompt"; return 0; } const int64_t want = lm_tokens_env() > 0 ? lm_tokens_env() : (lm_by_default_ ? kLmDefaultOnTokens : kLmDefaultTokens); int64_t S = std::max(min_s, want / m.T * m.T); S = std::min(S, (n + m.T - 1) / m.T * m.T); if (cap > 0) { - if (cap % m.T != 0 || cap < min_s) { why = "the layer split's stages read different chunks"; return 0; } + if ((!lm_force_ && cap % m.T != 0) || cap < min_s) { why = "the layer split's stages read different chunks"; return 0; } S = std::min(S, cap); } const int64_t G = m.T * K; @@ -6148,15 +6153,57 @@ void Prefill::lm_release_chain() { } bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { + Seg one; + one.tokens = tokens; + one.n = n; + one.pos0 = pos0; + return lm_run(std::vector{one}, 0, nullptr, err); +} + +// Several prompts in ONE layer-major pass (PAR-H, 2026-10-30): the super-chunk is a list of sub-chunks, each from one +// prompt ("segment") with its own sessions; a layer's attention halves run per sub-chunk against that segment's +// session (GDN / QSA / PLE state), and the layer's experts are staged ONCE for every sub-chunk of the super-chunk - +// the streamed experts cost is shared by the prompts. A single segment with no sessions given is exactly the usual run. +bool Prefill::run_multi(const std::vector& segs, std::string& err) { + err.clear(); + if (segs.empty()) { err = "prefill: no prompt"; return false; } + int64_t total = 0; + for (const Seg& sg : segs) total += sg.n; + std::string why; + if (hand_in_ != nullptr || !impl_) { err = "prefill: multi-prompt read declined (chunk hand-off in use)"; return false; } + for (Prefill* q = this; q != nullptr; q = q->next_) q->lm_force_ = true; + struct ForceOff { Prefill* h; ~ForceOff() { for (Prefill* q = h; q != nullptr; q = q->next_) q->lm_force_ = false; } } force_off{this}; + if (lm_prepare_chain(total, why) <= 0) { err = "prefill: multi-prompt read declined: " + why; return false; } + bool ok = lm_run(segs, 0, nullptr, err); + std::string drain_err; + if (!drain_pipeline(drain_err) && ok) { + ok = false; + err = drain_err; + } + for (Prefill* q = this; q != nullptr; q = q->next_) q->lm_mid_ = false; + lm_release_chain(); + return ok; +} + +bool Prefill::lm_run(const std::vector& segs, int depth, const std::vector* given_super, std::string& err) { err.clear(); Impl& m = *impl_; const core::OnDevice on_device(m.device); const core::ModelGeometry& g = *m.g; - core::SessionState& ss = *m.ss; + // the session of segment i on THIS stage: the segment's own (stage depth `depth`), else this stage's main session + auto ss_of = [&](size_t i) -> core::SessionState* { + const Seg& sg = segs[i]; + return (size_t) depth < sg.stage_ss.size() && sg.stage_ss[(size_t) depth] != nullptr ? sg.stage_ss[(size_t) depth] : m.ss; + }; + core::SessionState* ssp = ss_of(0); + const bool multi = segs.size() > 1; + int64_t n = 0; // all the prompts' tokens + for (const Seg& sg : segs) n += sg.n; + const int64_t pos0 = segs[0].pos0; // (only the progress line's) const auto t_start = Clock::now(); const cudaStream_t cs = (cudaStream_t) m.cs; Impl::LmBufs& lb = m.lm; - const int64_t S = lb.S, L = g.n_layers; + const int64_t L = g.n_layers; // a layer split's stage (2026-10-24): its layers [LB, LE); a later stage's rows arrive in R_host, written by the // stage before it, and a stage before the last writes its final rows into the next stage's R_host, then runs // the next stage on that super-chunk on a thread while it reads its own next super-chunk (one hand-off buffer: @@ -6166,38 +6213,89 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st strata::kernels::QsaShapes s = core::qsa_shapes(g); // as 0.2.2's run_impl const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); - int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + std::vector> prevs(segs.size()); + for (size_t i = 0; i < segs.size(); ++i) prevs[i] = {ss_of(i)->ple_prev[0], ss_of(i)->ple_prev[1]}; PfTimer pt; // the MMQ row table lives in the borrowed cache slots when the prompt path borrows: written for every prompt // (none without an MMQ layer: the FP16 path has no such table) if (m.ids_identity) mmq::iota(m.ids_identity, m.T * K, m.cs); // ---- the PLE rows, read per chunk on a thread as run_impl does (the same state machine, in chunk order) - const bool ple_on = ss.ple.ready(); + const bool ple_on = m.ss->ple.ready(); static const bool ple_batch_env = [] { const char* v = std::getenv("STRATA_PLE_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled() && - (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) && + (m.ss->ple.w.key_bf16 != nullptr || m.ss->ple.w.key_native_data != nullptr) && m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64; - const int32_t prev0[2] = {prev[0], prev[1]}; - auto ple_gather = [&m, &ss, tokens, n, prev0](int64_t c0, int buf, std::string& e) -> bool { - const int64_t T = std::min(m.T, n - c0); - auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; + // ---- the plan. A segment is cut into pieces of at most S tokens (the usual super-chunks), each piece into + // sub-chunks of m.T tokens from the piece's start; pieces of several segments are packed into one super-chunk while + // their rows fit S. One segment: exactly the usual super-chunks. + const int64_t S = m.lm.S; + // the sub-chunk size of a multi-prompt read: what every stage of the chain can take (the stages' chunks may differ) + int64_t tsub = m.T; + if (lm_force_) + for (const Prefill* q = this; q != nullptr; q = q->next_) tsub = std::min(tsub, q->impl_->T); + std::vector> supers_own; + const std::vector>* supers_p = &supers_own; + std::vector> one_given; + if (given_super != nullptr) { + one_given.push_back(*given_super); + supers_p = &one_given; + } else { + std::vector cur; + int64_t cur_rows = 0; + for (size_t si = 0; si < segs.size(); ++si) + for (int64_t p0s = 0; p0s < segs[si].n; p0s += S) { + const int64_t piece = std::min(S, segs[si].n - p0s); + if (!cur.empty() && cur_rows + piece > S) { + supers_own.push_back(std::move(cur)); + cur.clear(); + cur_rows = 0; + } + for (int64_t c0s = 0; c0s < piece; c0s += tsub) { + LmSub sb; + sb.seg = (int) si; + sb.c0 = p0s + c0s; + sb.T = std::min(tsub, piece - c0s); + sb.t0 = cur_rows + c0s; + cur.push_back(sb); + } + cur_rows += piece; + } + if (!cur.empty()) supers_own.push_back(std::move(cur)); + } + const std::vector>& supers = *supers_p; + std::vector> flat; // every sub-chunk in order: (super-chunk, sub-chunk) + for (size_t si = 0; si < supers.size(); ++si) + for (size_t c = 0; c < supers[si].size(); ++c) flat.push_back({(int) si, (int) c}); + std::vector flat_base(supers.size(), 0); + for (size_t si = 1; si < supers.size(); ++si) flat_base[si] = flat_base[si - 1] + (int64_t) supers[si - 1].size(); + auto sub_at = [&](int64_t gi) -> const LmSub& { return supers[(size_t) flat[(size_t) gi].first][(size_t) flat[(size_t) gi].second]; }; + const std::array prev_none{-1, -1}; + (void) prev_none; + std::vector> prev0s = prevs; + auto ple_gather = [&m, &segs, &ss_of, &prev0s, &sub_at](int64_t gi, int buf, std::string& e) -> bool { + const LmSub& sb = sub_at(gi); + const int64_t* tokens = segs[(size_t) sb.seg].tokens; + core::SessionState* ssq = ss_of((size_t) sb.seg); + const int64_t c0 = sb.c0, T = sb.T; + const std::array& prev0 = prev0s[(size_t) sb.seg]; + auto at = [&](int64_t i) { return i < 2 ? prev0[(size_t) i] : (int32_t) tokens[i - 2]; }; int32_t pv[2] = {at(c0), at(c0 + 1)}; for (int64_t t = 0; t < T; ++t) { const int32_t tok = (int32_t) tokens[c0 + t]; - strata::kernels::ngram_rows(&tok, pv, 1, ss.ple.consts, + strata::kernels::ngram_rows(&tok, pv, 1, m.ss->ple.consts, m.ple_rows[buf].data() + t * strata::kernels::PLE_N_HEADS); pv[0] = pv[1]; pv[1] = tok; } - return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); + return m.ss->ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); }; std::string ple_next_err; std::future ple_next; int ple_buf = 0; - auto ple_land = [&](int64_t c0, int64_t T) -> bool { + auto ple_land = [&](int64_t gi, int64_t T) -> bool { const auto tp = Clock::now(); if (!ple_next.get()) { err = ple_next_err; return false; } // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before @@ -6208,12 +6306,12 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); return false; } - if (c0 + m.T < n) { + if (gi + 1 < (int64_t) flat.size()) { if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) { err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); return false; } - ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { + ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = gi + 1, b = ple_buf ^ 1] { strata::aux_cpus::pin_current_thread(); return ple_gather(c1, b, ple_next_err); }); @@ -6556,9 +6654,13 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st return true; }; - for (int64_t sc0 = 0; sc0 < n; sc0 += S) { - const int64_t Sn = std::min(S, n - sc0); - const int64_t nc = (Sn + m.T - 1) / m.T; + for (size_t sci = 0; sci < supers.size(); ++sci) { + const std::vector& subs = supers[sci]; + int64_t Sn = 0; + for (const LmSub& sb : subs) Sn = std::max(Sn, sb.t0 + sb.T); + const int64_t nc = (int64_t) subs.size(); + int64_t last_seg0 = -1; + for (int64_t c = 0; c < nc; ++c) if (subs[(size_t) c].seg == 0) last_seg0 = c; ++lm_supers; lm_mid_ = true; for (int64_t l = LB; l <= LE; ++l) { @@ -6567,8 +6669,8 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st // host mode: sub-chunk c's rows go up on the copy stream into buffer c % 2 (issued one sub-chunk ahead) auto r_buf = [&](int64_t c) { return (c & 1) ? lb.R2 : R_chunk; }; auto issue_up = [&](int64_t c) { - const int64_t cc0 = sc0 + c * m.T, TT = std::min(m.T, n - cc0); - cudaMemcpyAsync(r_buf(c), lb.R_host + (size_t) (c * m.T) * D, (size_t) TT * D * 4, cudaMemcpyHostToDevice, + const int64_t TT = subs[(size_t) c].T; + cudaMemcpyAsync(r_buf(c), lb.R_host + (size_t) subs[(size_t) c].t0 * D, (size_t) TT * D * 4, cudaMemcpyHostToDevice, m.copy); cudaEventRecord(lb.ev_in[c & 1], m.copy); }; @@ -6579,12 +6681,17 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st for (int64_t c = 0; c < nc; ++c) { if (should_stop && should_stop()) { err = "cancelled"; return false; } core::progress_beat(); - core::progress_at("reading the prompt (layer-major): layer", l, pos0 + sc0 + c * m.T); + const LmSub& sub = subs[(size_t) c]; + const Seg& sgm = segs[(size_t) sub.seg]; + const int64_t* const tokens = sgm.tokens; + ssp = ss_of((size_t) sub.seg); + core::progress_at("reading the prompt (layer-major): layer", l, sgm.pos0 + sub.c0); qsa_index = qsa_index0; gdn_index = gdn_index0; - const int64_t c0 = sc0 + c * m.T; // in this run's tokens - const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0; - const int64_t t0 = c * m.T; // in the super-chunk + const int64_t c0 = sub.c0; // in this prompt's tokens + const int64_t T = sub.T, p0 = sgm.pos0 + c0; + const int64_t t0 = sub.t0; // in the super-chunk + const int64_t gi = flat_base[sci] + c; // in the whole run m.R = lb.r_dev ? lb.R + t0 * D : r_buf(c); if (!lb.r_dev) { if (l > 0) { @@ -6635,11 +6742,14 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st if (!core::embed_row(*m.wt, g, tokens[c0 + t], m.emb + t * N, cs, err)) return false; gr_broadcast(m.emb, m.R, T, cs); if (ple_on && !ple_next.valid()) - ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c0, b = ple_buf] { + ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, gi, b = ple_buf] { strata::aux_cpus::pin_current_thread(); - return ple_gather(c0, b, ple_next_err); + return ple_gather(gi, b, ple_next_err); }); - for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; } + { + std::array& pvv = prevs[(size_t) sub.seg]; + for (int64_t t = 0; t < T; ++t) { pvv[0] = pvv[1]; pvv[1] = (int32_t) tokens[c0 + t]; } + } } else if (l > LB) { // (a later stage's first layer: the stage before wrote layer LB - 1) // the previous layer's experts: the hyper-connection write of its FFN half gr_write(m.R, acc, m.inj, HC, T, cs); @@ -6684,19 +6794,21 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); return false; } - lm_mid_ = c + 1 < nc; - if (on_stage_chunk && !lm_mid_ && !on_stage_chunk(p0 + T, err)) return false; - if (on_chunk && !on_chunk(m.R, T, p0, err)) return false; + lm_mid_ = c != last_seg0 && last_seg0 >= 0; + if (sub.seg == 0) { // (the reports are the first prompt's; the others only fill their sessions) + if (on_stage_chunk && !lm_mid_ && !on_stage_chunk(p0 + T, err)) return false; + if (on_chunk && !on_chunk(m.R, T, p0, err)) return false; + } } continue; } const core::LayerView v(*m.wt, l); - if (l == 1 && ple_on && !ple_land(c0, T)) return false; + if (l == 1 && ple_on && !ple_land(gi, T)) return false; // ---- the PLE block at layer 1 (run_impl's, batched or token by token) if (l == 1 && ple_on && ple_batch) { pt.mark(kPfPle, cs); const auto tp = Clock::now(); - const strata::kernels::PleWeights& pw = ss.ple.w; + const strata::kernels::PleWeights& pw = m.ss->ple.w; constexpr int64_t HD = strata::kernels::NG_HC_DIM; const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2(m.f16_io) ? 4 : 2) + 4096; const int64_t SB = std::min(T, (int64_t) (m.region_bytes / per_token)); @@ -6724,7 +6836,7 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N); if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f); try { - strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated, + strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ssp->ple_hist, pw, qn, gated, gate, (int) nb, cs); } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; } } @@ -6737,10 +6849,10 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st po.normalized = m.ple_norm; po.result = m.R + t * D; try { - strata::kernels::ple_block(m.ple_emb + t * N, m.R + t * D, ss.ple.hist, ss.ple.w, po, - ss.ple.scratch, cs); + strata::kernels::ple_block(m.ple_emb + t * N, m.R + t * D, ssp->ple_hist, m.ss->ple.w, po, + m.ss->ple.scratch, cs); } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; } - strata::kernels::ple_history_advance(ss.ple.hist, m.ple_norm, cs); + strata::kernels::ple_history_advance(ssp->ple_hist, m.ple_norm, cs); } stats_.ms_ple += ms_since(tp); } @@ -6798,7 +6910,7 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st *wsa = need(v, "ssm_a", err); if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false; pt.mark(kPfGdn, cs); - float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats; + float* state = ssp->gdn_state + (size_t) (gdn_index - ssp->gdn_ord0) * gdn_floats; float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false; if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false; @@ -6814,7 +6926,7 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st ++gdn_index; } else if (half == 0) { // ======================= QSA (run_impl's, without its debug dumps) ======================= - const core::QsaState& st = ss.qsa_states[qsa_index]; + const core::QsaState& st = ssp->qsa_states[qsa_index]; const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err), *wik = need(v, "indexer.k_proj.weight", err), @@ -6986,17 +7098,22 @@ bool Prefill::run_layer_major(const int64_t* tokens, int64_t n, int64_t pos0, st cudaGetErrorString(cudaGetLastError()); return false; } - if (on_stage_chunk && !on_stage_chunk(pos0 + sc0 + Sn, err)) return false; + if (on_stage_chunk && last_seg0 >= 0 && + !on_stage_chunk(segs[0].pos0 + subs[(size_t) last_seg0].c0 + subs[(size_t) last_seg0].T, err)) + return false; next_err_.clear(); - next_run_ = std::async(std::launch::async, [this, tokens, sc0, Sn, pos0] { + next_run_ = std::async(std::launch::async, [this, segs_c = std::make_shared>(segs), depth, + sp_super = std::make_shared>(supers[sci])] { strata::aux_cpus::pin_current_thread(); - return next_->run_layer_major(tokens + sc0, Sn, pos0 + sc0, next_err_); + return next_->lm_run(*segs_c, depth + 1, sp_super.get(), next_err_); }); } } lm_mid_ = false; - ss.ple_prev[0] = prev[0]; - ss.ple_prev[1] = prev[1]; + for (size_t i = 0; i < segs.size(); ++i) { + ss_of(i)->ple_prev[0] = prevs[i][0]; + ss_of(i)->ple_prev[1] = prevs[i][1]; + } if (ple_next.valid()) ple_next.wait(); if (cudaStreamSynchronize(cs) != cudaSuccess) { err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 956d2c56..34664a80 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -101,6 +101,13 @@ #include "strata/spec/suffix_drafter.hpp" #include "strata/spec/spec_start.hpp" #include "strata/program/batch_groups.hpp" +#include "strata/program/par_counters.hpp" +#if defined(__linux__) +#include +#include +#include +#include +#endif #include "strata/program/pipe_probe.hpp" #include "strata/kernels/cvec.hpp" #include "strata/core/progress.hpp" @@ -235,6 +242,35 @@ std::string vram_free_note() { return buf; } +#if defined(__linux__) +// STRATA_CRASH_BT=1 (research): a fatal signal prints the call stack to stderr (the addresses go through addr2line -e ) +namespace { +char g_crash_path[512] = ""; +void crash_bt_handler(int sig) { + void* frames[48]; + const int n = backtrace(frames, 48); + const char msg[] = "strata: fatal signal, call stack:\n"; + int fd = 2; + if (g_crash_path[0] != '\0') { + const int f = open(g_crash_path, O_WRONLY | O_CREAT | O_APPEND, 0644); + if (f >= 0) fd = f; + } + (void) !write(fd, msg, sizeof msg - 1); + backtrace_symbols_fd(frames, n, fd); + signal(sig, SIG_DFL); + raise(sig); +} +const bool crash_bt_installed = [] { + const char* v = std::getenv("STRATA_CRASH_BT"); + if (v == nullptr || v[0] == '\0' || v[0] == '0') return false; + if (v[0] != '1' || v[1] != '\0') std::snprintf(g_crash_path, sizeof g_crash_path, "%s", v); + for (int sg : {SIGFPE, SIGSEGV, SIGBUS, SIGABRT}) signal(sg, crash_bt_handler); + return true; +}(); +} // namespace +#endif + + // STRATA_PIPE_BYIELD_NODRAIN=1 (read once; off by default): with the pipelined groups, a BYIELD that reaches the main // loop is dropped without draining the groups first. A pipelined read never gives way (batch_read_piece), so the // BYIELD is for a read that has ended, and the drain (and the refill after it) did nothing for it @@ -12480,6 +12516,14 @@ int main(int argc, char** argv) { const bool batch_telemetry_enabled = batch_telemetry_env != nullptr && batch_telemetry_env[0] == '1' && batch_telemetry_env[1] == '\0'; strata::core::BatchWindowSampler batch_telemetry(batch_telemetry_enabled); + strata::program::ParCounters pc; // STRATA_PAR_COUNTERS=1: counters only (par_counters.hpp); off: a branch + auto pc_ex = [&]() { + strata::program::ParCounters::Ex e; + e.misses = drive.d.multi_misses; e.entries = drive.d.multi_entries; e.hits = drive.d.cache_hits; + e.offload = drive.d.offload_entries; e.pcie = drive.d.pcie_experts; e.run_ms = drive.d.ms_run; e.jobs_ms = drive.d.ms_jobs; + e.vwait_ms = ver.ms_wait; e.vpool_ms = ver.ms_pool; + return e; + }; auto report_batch_window = [&](int processed_rows, int active_rows, bool idle, Clock::time_point started) { if (!batch_telemetry_enabled) return; const auto sample = batch_telemetry.complete(processed_rows, active_rows, idle, started, Clock::now()); @@ -12491,6 +12535,12 @@ int main(int argc, char** argv) { }; int admit_slot = -1; ///< the slot the request being read will continue in (BGEN) long long admit_max_new = 0; + // BCO (research, PAR-H; STRATA_COALESCE_PREFILL on the server): prompts of waiting requests, read in + // the SAME layer-major pass as the next BGEN's prompt into the named idle slots' sessions (the experts a layer + // streams are shared), so their own admissions find the prompt in the slot and read nothing. BCOK + // says a slot holds its prompt; a declined or failed co-read says nothing and costs nothing. + struct CoReq { int slot = -1; std::vector ids; }; + std::vector co_pending, co_set; 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 lk(in_mu); @@ -12757,6 +12807,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; + if (pc.on()) pc.begin(pc_ex(), (int) g.n_layers); bt_a_rounds0 = a_rounds; bt_a_swapped0 = a_swapped; } const Clock::time_point w0 = Clock::now(); @@ -12869,8 +12920,10 @@ int main(int argc, char** argv) { } strata::core::progress().busy.store(was_busy); report_batch_window(S, A, !batch_on(), w0); + pc.window(S, A); if (!batch_on() && bt_windows > 0) { const double w = (double) bt_windows, wall = msd(bt_start, Clock::now()); + pc.flush(wall, pc_ex()); 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); @@ -13173,6 +13226,7 @@ int main(int argc, char** argv) { p4.span_start(bt_start); 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; + if (pc.on()) pc.begin(pc_ex(), (int) g.n_layers); } for (int k = 0; k < n_pipe; ++k) { const int gi = stage_group[(size_t) k]; @@ -13239,6 +13293,7 @@ int main(int argc, char** argv) { ++pa_windows; G.inflight = false; report_batch_window(G.S, G.active, !pipe_inflight() && !batch_on(), G.started); + pc.window(G.S, G.active); } // 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) { @@ -13366,6 +13421,7 @@ int main(int argc, char** argv) { 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(Clock::now() - bt_start).count(); p4.span_end(wall); + pc.flush(wall, pc_ex()); char pa_txt[160] = ""; if (pipe_adapt_every > 0) std::snprintf(pa_txt, sizeof pa_txt, "; adaptive tier (STRATA_PIPE_ADAPT_EVERY): %lld rounds, %lld experts " @@ -13406,10 +13462,11 @@ int main(int argc, char** argv) { // (STRATA_PIPE_BYIELD_NODRAIN: not for a BYIELD, which is dropped below) if (piped && line.rfind("BSTOP ", 0) != 0 && !(pipe_byield_nodrain_env() && line.rfind("BYIELD", 0) == 0)) { - const int in_flight = trace ? (int) std::count_if(pg.begin(), pg.end(), [](const PGroup& G) { + const int in_flight = (trace || pc.on()) ? (int) std::count_if(pg.begin(), pg.end(), [](const PGroup& G) { return G.inflight; }) : 0; const auto td = Clock::now(); if (!pipe_drain()) return 1; + if (pc.on()) pc.drain(line, in_flight, std::chrono::duration(Clock::now() - td).count()); if (trace) { // STRATA_TRACE: what the drain before this line cost (BGEN: an admission's first phase) line_drain_ms = std::chrono::duration(Clock::now() - td).count(); std::fprintf(stderr, "strata trace: drain for %.*s: %d groups in flight, %.1f ms\n", @@ -13430,6 +13487,21 @@ int main(int argc, char** argv) { if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true; continue; } + if (line.rfind("BCO ", 0) == 0) { // BCO : kept for the next BGEN + CoReq cr; + char* e1 = nullptr; + cr.slot = (int) std::strtol(line.c_str() + 4, &e1, 10); + for (const char* q = e1; q != nullptr && *q != '\0';) { + while (*q == ' ' || *q == ',') ++q; + if (*q == '\0') break; + char* e2 = nullptr; + cr.ids.push_back((int64_t) std::strtoll(q, &e2, 10)); + if (e2 == q) { cr.ids.clear(); break; } + q = e2; + } + if (cr.slot >= 0 && cr.slot < (int) bs.size() && cr.ids.size() >= 3) co_pending.push_back(std::move(cr)); + continue; + } if (line.rfind("BYIELD", 0) == 0) { // for a prompt read that has ended meanwhile if (trace && piped) std::fprintf(stderr, "strata trace: BYIELD dropped, %d groups in flight\n", @@ -13465,6 +13537,8 @@ int main(int argc, char** argv) { admit_slot = (int) b; admit_max_new = mn; adm_drain_ms = line_drain_ms; + co_set = std::move(co_pending); + co_pending.clear(); 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) @@ -15061,9 +15135,77 @@ int main(int argc, char** argv) { ConvCheckpoint::PromptPlan& p; ~SegPlanScope() { p = {}; } } seg_plan_scope{seg_plan}; + // the first run of a BGEN with co-reads: the waiting prompts are read in the same layer-major pass + bool co_tried = false; + auto co_run = [&](int64_t q, int64_t r, std::string& ce) -> bool { + using PSeg = strata::prefill::Prefill::Seg; + std::vector segs; + PSeg lead; + lead.tokens = ids.data() + q; + lead.n = r - q; + lead.pos0 = q; + segs.push_back(lead); + std::vector used; + for (const CoReq& c : co_set) { + if (c.slot < 0 || c.slot >= (int) bs.size() || c.slot == admit_slot || bs[(size_t) c.slot].active || + bs[(size_t) c.slot].partial) + continue; + bool dup = false; + for (const CoReq* u : used) dup = dup || u->slot == c.slot; + if (dup) continue; + PSeg sg; + sg.tokens = c.ids.data(); + sg.n = (int64_t) c.ids.size() - 1; // (the last token goes through the slot's own first window) + sg.pos0 = 0; + for (size_t k = 0; k < bslot_ss.size(); ++k) sg.stage_ss.push_back(bslot_ss[k][(size_t) c.slot].get()); + segs.push_back(sg); + used.push_back(&c); + } + if (segs.size() < 2) return sp.run(lead.tokens, lead.n, lead.pos0, ce); + for (const CoReq* c : used) { + park_slot(c->slot); // the conversation the slot holds, before this read overwrites it + for (size_t k = 0; k < bslot_ss.size(); ++k) { + const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev); + strata::core::session_zero(*bslot_ss[k][(size_t) c->slot], g, nullptr, nullptr); + cudaDeviceSynchronize(); + } + bs[(size_t) c->slot] = BSlot{}; // (it holds nothing until the read is done) + } + const auto tco = Clock::now(); + std::fprintf(stderr, "strata batch: co-read starting: %zu more prompt(s) with this request's %lld tokens\n", + used.size(), (long long) lead.n); + std::fflush(stderr); + if (!sp.run_multi(segs, ce)) { + if (ce.rfind("prefill: multi-prompt read declined", 0) == 0) { // nothing was read: the usual run + std::fprintf(stderr, "strata batch: co-read of %zu prompt(s) declined (%s)\n", used.size(), ce.c_str()); + ce.clear(); + return sp.run(lead.tokens, lead.n, lead.pos0, ce); + } + return false; + } + for (const CoReq* c : used) { + BSlot& sl = bs[(size_t) c->slot]; + sl = BSlot{}; + sl.ids.assign(c->ids.begin(), c->ids.end() - 1); + sl.cached = true; + sl.cvec = want_cvec; + std::printf("BCOK %d %lld\n", c->slot, (long long) sl.ids.size()); + } + std::fflush(stdout); + std::fprintf(stderr, "strata batch: co-read: %zu more prompt(s) read in the same pass as this request's %lld tokens " + "(%.0f ms)\n", used.size(), (long long) lead.n, + std::chrono::duration(Clock::now() - tco).count()); + return true; + }; auto run = [&](int64_t q, int64_t r) -> bool { if (planned) sp.force_chunk(plan.chunk, plan_single, plan.chunked); - const bool run_ok = sp.run(ids.data() + q, r - q, q, e); + bool run_ok; + if (!co_set.empty() && !co_tried && admit_slot >= 0 && req_imgs.empty()) { + co_tried = true; + run_ok = co_run(q, r, e); + } else { + run_ok = sp.run(ids.data() + q, r - q, q, e); + } if (run_ok && q == 0 && sp.kva_floor() > 0) { // KVA approximated the start of this prompt: remember which tokens kva_floors.note(ids.data(), sp.kva_floor()); if (use_mtp && mtp.cell_floor_enabled()) mtp.set_cell_floor(sp.kva_floor()); @@ -15157,7 +15299,14 @@ int main(int argc, char** argv) { } return true; }(); - if (piped && pr_conc && req_imgs.empty()) { // (with no slot decoding it only watches for a BYIELD) + // STRATA_PIPED_CONCURRENT_MIN=N (opt-in, with STRATA_PIPED_CONCURRENT=1): only a read of at least N tokens + // runs beside the decoding slots on its own thread; a shorter one takes the usual path (drained windows, + // no priority streams' cost on the short prompts' TTFT and throughput). Unset or 0: every read, as before. + static const int64_t pr_conc_min = [] { + const char* v = std::getenv("STRATA_PIPED_CONCURRENT_MIN"); + return v != nullptr ? (int64_t) std::max(0LL, std::atoll(v)) : (int64_t) 0; + }(); + if (piped && pr_conc && req_imgs.empty() && (b0 - a0) >= pr_conc_min) { // (with no slot decoding it only watches for a BYIELD) // the drafter's prompt pass captures its graphs and grows its records at first use, and the // prompt path's pinned upload slots grow at their first larger upload: done here, with nothing in // flight (on the reader's thread a capture, an allocation or a free takes the driver's lock and @@ -17180,6 +17329,7 @@ int main(int argc, char** argv) { const auto tc4 = Clock::now(); std::fprintf(stderr, "strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n", admit_slot, (long long) live.size(), std::chrono::duration(tc4 - tc0).count()); + pc.admission((long long) live.size(), prompt_ms); if (trace) { // STRATA_TRACE: the admission's phases (ms), from the drain before BGEN to this copy auto span = [](Clock::time_point a, Clock::time_point b) { return std::chrono::duration(b - a).count();