diff --git a/core/config.cpp b/core/config.cpp index 184a640f..a619b23f 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -56,6 +56,9 @@ static const Flag g_flags[] = { "asks the driver, on requires peer access and stops without\n" "it, off exchanges through pinned host memory" }, { "--max-num-batched-tokens", "N", "the largest token count one step may carry" }, + { "--busy-prefill-chunk", "MODE", "a prefill chunk's share of a step that has other work: auto\n" + "(default) leaves decode rows and new requests their room,\n" + "off takes the whole step, N holds the chunk to N tokens" }, { "--max-num-seqs", "N", "the largest number of sequences one step may carry" }, { "--max-model-len", "N", "context bound; 0 takes the model's training context" }, { "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n" @@ -404,6 +407,18 @@ int config_parse(int argc, char** argv, Config* c) { } else if (S("--tp-wire-min-kb")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); } else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); } + else if (S("--busy-prefill-chunk")) { + if (!(v = need(i))) return RAD_E_INVAL; + char* end = nullptr; + const long long n = std::strtoll(v, &end, 10); + if (!std::strcmp(v, "auto")) c->busy_prefill_chunk = -1; + else if (!std::strcmp(v, "off")) c->busy_prefill_chunk = 0; + else if (end && end != v && *end == '\0' && n > 0) c->busy_prefill_chunk = n; + else { + RAD_ERR("--busy-prefill-chunk takes auto, off or a positive token count, not '%s'", v); + return RAD_E_INVAL; + } + } else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); } else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); } else if (S("--rope-scaling")) { diff --git a/core/engine.cpp b/core/engine.cpp index 3ba2831d..8d13055d 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1748,6 +1748,16 @@ int Engine::serve() { for (auto& rk : ranks_) rio.push_back({ rk->device, rk->ctx.stream(), &rk->program }); RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_)); + /* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS. A prefill chunk the scheduler holds back for + * other work in the step (--busy-prefill-chunk) is kept at or above it: under it every routed + * layer reads its pooled experts synchronously, which costs a long prefill far more than the + * step it shares saves. The largest over the ranks, since the step waits for the slowest. */ + { + int64_t stage_rows = 0; + for (auto& rk : ranks_) + if (rk->stager.enabled()) stage_rows = std::max(stage_rows, rk->stager.min_rows()); + sched_.set_stage_rows(stage_rows); + } for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get()); diff --git a/core/place/stager.h b/core/place/stager.h index 622a911d..00e1f52e 100644 --- a/core/place/stager.h +++ b/core/place/stager.h @@ -71,6 +71,10 @@ public: bool enabled() const { return !layers_.empty(); } int64_t buffer_bytes() const { return cap_; } + /* The smallest pass (in tokens) the stager arms for: a step under it reads every pooled + * expert of a routed layer synchronously. The scheduler keeps a held-back prefill chunk at + * or above it (Scheduler::set_stage_rows). */ + int64_t min_rows() const { return min_rows_; } size_t n_layers() const { return layers_.size(); } bool begin_pass(const RadBatch* b) override; diff --git a/core/rad_core.h b/core/rad_core.h index 219cfec9..c485409f 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -696,6 +696,13 @@ struct Config { * P2P should not quietly serve on something else. */ int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */ int64_t max_tok = 8192; /* --max-num-batched-tokens */ + /* --busy-prefill-chunk: how much of a step a prefill chunk may take when other work is + * pending in it (decode rows behind it, another prefill, a request waiting to be admitted). + * -1 = auto: the chunk leaves those their rows and a share for admission, and keeps at least + * the smallest pass the prefill stager arms for. 0 = off: the chunk takes every token the + * step has left, as 1.3.0 did. N > 0: the chunk is held to N tokens on such a step. + * Scheduler::step, docs/GUIDE.md. */ + int64_t busy_prefill_chunk = -1; int64_t max_seqs = 256; int64_t max_ctx = 0; /* 0 = the model's training context */ /* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the diff --git a/core/sched/metrics.h b/core/sched/metrics.h index 6c4a838b..4e1de4f8 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -46,6 +46,11 @@ struct SchedMetrics { * commit and staging with the card idle, so steps_ahead against steps is how much of the run * kept the card fed through the host's part of it. */ int64_t steps_ahead = 0; + /* PREFILL CHUNKS HELD BACK for other work in the same step (--busy-prefill-chunk): each is a + * chunk that would have taken more of the step and left decode rows behind it, or a request + * waiting to be admitted, with nothing. Zero under `off`, and on a load that never overlaps a + * prefill with anything else. */ + int64_t prefill_chunks_capped = 0; /* HOW LONG THE ENGINE SPENT INSIDE A STEP, cumulative nanoseconds, and the decode half of it * separately. Neither is a derived rate -- they are counters, and that is the point. diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 59e96598..c28fdabd 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -777,6 +777,97 @@ int64_t Scheduler::tail_checkpoint(int64_t target) const { return tail > I && tail - tail / I * I >= std::max(Q, I / 4) ? tail : -1; } +/* ------------------------------------------------------------------ a prefill sharing a step */ +void Scheduler::set_stage_rows(int64_t rows) { + stage_rows_ = rows > 0 ? rows : 0; + const int64_t n = cfg_.busy_prefill_chunk; + if (n == 0) { + RAD_INFO("scheduler: --busy-prefill-chunk off: a prefill chunk takes every token the step " + "has left, so decode rows behind it and requests waiting to start get none until " + "it ends"); + return; + } + const int64_t Q = std::max(geo_.quantum, 1); + if (n > 0) { + RAD_INFO("scheduler: --busy-prefill-chunk %lld: a prefill chunk sharing a step with other " + "work takes at most %lld tokens of it", (long long)n, (long long)(n / Q * Q)); + if (stage_rows_ > 0 && n < stage_rows_) + RAD_WARN("scheduler: --busy-prefill-chunk %lld is under the %lld-token step the prefill " + "stager overlaps at: a held-back chunk alone reads every routed layer's " + "pooled experts synchronously, which slows a long prefill far more than the " + "smaller step saves", (long long)n, (long long)stage_rows_); + return; + } + RAD_INFO("scheduler: --busy-prefill-chunk auto: a prefill chunk sharing a step leaves decode " + "rows and waiting requests their room and keeps at least %lld tokens%s", + (long long)std::max(Q, stage_rows_ / Q * Q), + stage_rows_ > 0 ? " (the prefill stager's smallest pass)" : ""); +} + +/* HOW MUCH OF THE STEP A PREFILL CHUNK MAY TAKE WHEN OTHER WORK WANTS IN. + * + * Without a cap the running loop hands a prefill row every token the step has left + * (plan_chunk(..., budget)). On a step budget of a few thousand tokens and a prompt of a few + * hundred thousand, that is every step for a minute or more, and in that time a decode row behind + * the prefill in running_ gets nothing (`want > budget` -> break) and admission never runs + * (`budget > 0`): a mostly-cached turn that needs a few hundred tokens waits for the whole of + * somebody else's prefill. The cap leaves `reserve` -- the rows behind it and a share for + * admission, worked out by step() -- and never goes under the floor. + * + * THE FLOOR is the smallest step the prefill stager overlaps (rounded down to the quantum: the + * rows the chunk shares the step with make up the difference). A step under it reads every + * routed layer's pooled experts synchronously, and on an expert-tiered placement that costs a + * long prefill far more than the shared step saves -- a budget set one token under the threshold + * measured -65 % prefill (#61). With no stager the floor is one quantum. + * + * AND THE REST OF THE INTERVAL STAYS ABOVE IT. A chunk ends on the checkpoint interval + * (plan_chunk), so a chunk held short of the boundary leaves a remainder that is the next step's + * whole chunk. Held to `budget - reserve`, that remainder is the size of the reserve -- a few + * hundred tokens, under the floor, and the slowest step of all. When the cap would leave such a + * remainder the interval is split into two chunks each at or above the floor instead: two staged + * steps, each with room for the rest of the step's work. */ +int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, + int64_t reserve, bool shared, bool rows_only) const { + const int64_t mode = cfg_.busy_prefill_chunk; + if (mode == 0 || budget <= 0) return budget; + /* auto holds a chunk back only for work that would otherwise get NOTHING this step -- rows + * behind it, a request waiting to start. Rows already planned ahead of it are in the step + * whatever the chunk takes, so auto leaves the chunk alone for them (it was never what + * starved them). An explicit N is the operator trading prefill speed for the latency of every + * other row, so it applies whenever the chunk shares the step at all. */ + if (reserve <= 0 && !(mode > 0 && shared)) return budget; + reserve = std::max(reserve, 0); + const int64_t Q = std::max(geo_.quantum, 1); + + int64_t cap = budget - reserve; + if (mode > 0) { + /* The operator's number. No floor: --busy-prefill-chunk N under the stager's step is a + * choice set_stage_rows warns about, not one this overrides. */ + cap = std::min(cap, mode); + } else { + const int64_t floor = std::max(Q, stage_rows_ / Q * Q); + cap = std::max(cap, floor); + const int64_t remaining = n_target - n_computed; + int64_t span = remaining; /* where this run of chunks must end */ + if (geo_.checkpoints()) { + const int64_t I = geo_.checkpoint_interval; + span = std::min(span, ((n_computed / I) + 1) * I - n_computed); + } + /* ...but not for decode rows alone. Their reserve is a few tokens, the chunk ends a + * quantum short of the boundary and the next step finishes the interval: the same pair of + * steps a prefill already runs whenever decode rows are planned AHEAD of it, so it adds + * no step shape the engine does not already pay for. Halving instead would hold a long + * prompt to half-interval chunks for as long as any request decodes behind it -- measured + * as the larger cost (NOTES: prefill-share run 2). The split is for a share (a request + * waiting to start, another prefill), which lasts a step or two. */ + if (!rows_only && cap < span && span - cap < floor && span - floor >= floor) + cap = span - floor; + } + cap = std::min(cap, budget); + cap = std::max(cap, Q); + return std::min(cap, budget); +} + /* ------------------------------------------------------------------ preemption */ void Scheduler::preempt_back() { int32_t slot = running_.back(); @@ -810,7 +901,7 @@ void Scheduler::preempt_back() { /* Admission checks the KV budget BEFORE a request enters running. A request admitted without the * blocks to run it is a request that will be preempted on its first step, which costs a full * recompute for nothing. */ -int Scheduler::admit_one(SchedReq& s, int64_t budget) { +int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { Request& r = *s.req; if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id)); @@ -902,7 +993,13 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) { int64_t target = s.seq_len(); int64_t ckpt = -1; - int64_t want = plan_chunk(r.n_computed, target, budget, &ckpt); + /* AN ADMISSION SHARES THE STEP THE SAME WAY. A cold prompt admitted with requests queued + * behind it would otherwise take every token left, and the queue behind it would wait a step + * for nothing; the hit above is known by now, so the cap is on what really has to run. */ + const int64_t cap = r.embed ? budget /* whole input or nothing: never held back (below) */ + : busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty()); + int64_t want = plan_chunk(r.n_computed, target, cap, &ckpt); + if (cap < budget && want > 0) admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr); /* The whole input or nothing this step (Request::embed): the next step starts with a whole * budget, and add_locked refused an input no budget holds. */ if (r.embed && want < target - (int64_t)r.n_computed) want = 0; @@ -1002,6 +1099,31 @@ const RadBatch* Scheduler::step() { * alone rather than as anything failing. */ const int depth = draft_.next_depth(); + /* WHAT ELSE WANTS INTO THIS STEP, for --busy-prefill-chunk (busy_cap). The rows still to be + * walked -- each decode row's 1 + the deepest window it can take, each prefill row a share -- + * and one share when a request is waiting and a sequence slot is free for it. Counted down as + * the loop walks, so a row's reserve is what is BEHIND it. No allocation: two counters. */ + const bool share_step = cfg_.busy_prefill_chunk != 0; + const int64_t share_tok = std::max(std::max(geo_.quantum, 1), + cfg_.max_tok / 8 / std::max(geo_.quantum, 1) + * std::max(geo_.quantum, 1)); + const int64_t dec_row_tok = 1 + std::max(depth, draft_.step_window()); + int64_t behind_dec = 0, behind_pf = 0; + if (share_step) { + for (int32_t slot : running_) { + const Request& rr = *reqs_[(size_t)slot]->req; + const int64_t tg = reqs_[(size_t)slot]->seq_len(); + const bool pf = (rr.n_computed < (int64_t)rr.prompt.size()) || (rr.n_computed + 1 < tg); + if (pf) ++behind_pf; else behind_dec += dec_row_tok; + } + } + const bool admit_waits = share_step && !waiting_.empty() && !free_cards_.empty() && + (int64_t)running_.size() < cfg_.max_seqs; + /* The first prefill chunk held back this step (its index in plan_.e before the sort) and what + * it would have taken: whatever the work it made room for did not use goes back to it. */ + int32_t capped_at = -1; + int64_t capped_full = 0; + /* ---------------------------------------------------------- running requests first */ /* Continuous batching: a request already holding blocks is served before a new one is let in, * because the alternative is admitting work that then preempts work already half done. */ @@ -1015,11 +1137,27 @@ const RadBatch* Scheduler::step() { const int64_t target = s.seq_len(); const bool prefill = (r.n_computed < (int64_t)r.prompt.size()) || (r.n_computed + 1 < target); + if (share_step) { + if (prefill) behind_pf = std::max(0, behind_pf - 1); + else behind_dec = std::max(0, behind_dec - dec_row_tok); + } int64_t ckpt = -1; int64_t want; if (prefill) { - want = plan_chunk(r.n_computed, target, budget, &ckpt); + const int64_t shares = share_step ? behind_pf + (admit_waits ? 1 : 0) : 0; + const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0; + const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(), + /*rows_only=*/shares == 0); + want = plan_chunk(r.n_computed, target, cap, &ckpt); + if (cap < budget && want > 0 && capped_at < 0) { + const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr); + if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; } + } + /* A PREFILL WITH NO ROOM LEFT DOES NOT STOP THE WALK. Under a quantum of budget it can + * take nothing this step, but a decode row behind it needs only 1 + its window -- so + * it is passed over rather than ending the loop (off keeps the old `break`). */ + if (want <= 0 && share_step) { ++i; continue; } } else { /* A verify step is 1 + n_draft query rows, which is why attention kernels take a * query length rather than assuming one (spec §10). */ @@ -1187,9 +1325,21 @@ const RadBatch* Scheduler::step() { * behind it is asked, exactly as for a context still being read off disk; the engine * runs the encoder before the next step (encodes_pending). */ if (s.req->media && !media_ready(s)) { ++at; continue; } - const int as = admit_one(s, budget); + /* One share left for the next request in the queue, when there is one and a slot + * for it (busy_cap). The embed path takes a whole input or nothing, so it is not + * held back: a share could only turn its admission into a refusal. */ + const int64_t areserve = + share_step && !s.req->embed && at + 1 < waiting_.size() && + (int64_t)plan_.e.size() + 1 < cfg_.max_seqs && free_cards_.size() > 1 + ? share_tok : 0; + admit_full_ = 0; + const int as = admit_one(s, budget, areserve); if (as == kAdmitWait) { ++at; continue; } if (as < 0) break; /* head of line: do not admit behind it */ + if (admit_full_ > s.sched_tokens && capped_at < 0) { + capped_at = (int32_t)plan_.e.size(); + capped_full = admit_full_; + } Request& r = *s.req; StepEntry e; @@ -1243,6 +1393,43 @@ const RadBatch* Scheduler::step() { } } + /* WHAT THE HELD-BACK CHUNK LEFT FOR OTHERS AND THEY DID NOT TAKE GOES BACK TO IT. The reserve + * is a forecast: a decode row drafts less than its window, an admission is refused (the pool + * is short, the head of the queue waits on a read), a step preempts and skips admission. A + * chunk held to the stager's floor in a step that then carries nothing else is a pass under + * the threshold -- exactly the slow step the floor exists to avoid -- so the unused budget is + * handed back, as far as the chunk's own geometry allows (plan_chunk) and only if the pool + * grants the blocks without a preemption; otherwise the chunk stays as planned. */ + if (capped_at >= 0) { + StepEntry& e = plan_.e[(size_t)capped_at]; + const Request& r = *e.req; + SchedReq& s = *reqs_[(size_t)e.slot]; + const int64_t had = e.n_tokens; + /* An explicit --busy-prefill-chunk N is a ceiling the operator chose, not a forecast: + * the chunk grows back to it at most. */ + int64_t limit = std::min(capped_full, had + budget); + if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk)); + int64_t ckpt = -1; + const int64_t grown = e.ckpt_slot < 0 && limit > had + ? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt) : had; + if (grown > had && kv_->ensure(r.id, r.n_computed + grown) >= 0) { + e.n_tokens = (int32_t)grown; + e.produces_token = (r.n_computed + grown >= s.seq_len()); + if (ckpt > 0) { + int32_t cs = -1; + if (pc_->reserve_checkpoint(r, ckpt, &cs) >= 0 && cs >= 0) { + e.ckpt_tok = (int32_t)(grown - 1); + e.ckpt_slot = cs; + ++m_.checkpoints_written; + } + } + s.sched_tokens = (int32_t)grown; + plan_.n_tok += grown - had; + budget -= grown - had; + } + if (e.n_tokens < capped_full) ++m_.prefill_chunks_capped; + } + if (plan_.e.empty()) return nullptr; /* THE DECODE ROWS FIRST, and both halves therefore contiguous. diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 1c1a6454..5976639b 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -465,6 +465,17 @@ public: int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget, int64_t* checkpoint_pos) const; + /* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS, in tokens (0 = no stager), set once by the + * engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it; see + * busy_cap. Also where the resolved policy is stated at startup. */ + void set_stage_rows(int64_t rows); + /* Visible for tests: the most a prefill chunk at `n_computed` of a `n_target`-token sequence + * may take of `budget` when `reserve` tokens of other work are still to be planned in the step + * and `shared` says rows are already planned ahead of it. Returns `budget` when + * --busy-prefill-chunk is off, or when auto has nothing to reserve. */ + int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve, + bool shared = false, bool rows_only = false) const; + private: Program* prog_ = nullptr; Config cfg_{}; @@ -472,6 +483,10 @@ private: KVGeom kvgeom_{}; /* Does this model carry recurrent state a prefix hit would have to restore? See admit_one. */ bool has_linear_state_ = false; + /* set_stage_rows: the prefill stager's smallest pass, 0 when it is not armed. */ + int64_t stage_rows_ = 0; + /* Set by admit_one when it held the admitted chunk back: what it would have taken. */ + int64_t admit_full_ = 0; IKVManager* kv_ = nullptr; IPrefixCache* pc_ = nullptr; @@ -719,7 +734,9 @@ private: /* RAD_OK, a negative status when the request cannot be admitted now -- nothing behind it is * either -- or kAdmitWait when its context is still being read off disk and the next request * may go ahead of it. */ - int admit_one(SchedReq& s, int64_t budget); + /* `reserve`: tokens of the step to leave for the requests queued behind this one + * (--busy-prefill-chunk; busy_cap). 0 plans the chunk on the whole budget, as before. */ + int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0); static constexpr int kAdmitWait = 1; /* The queue positions one step's admission took, kept to reuse the allocation. */ std::vector took_; diff --git a/core/server/adapters.h b/core/server/adapters.h index bc6bcb0a..04e06b82 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -294,6 +294,7 @@ public: o.steps_prefill = m.steps_prefill; o.steps_mixed = m.steps_mixed; o.steps_decode = m.steps_decode; o.steps_ahead = m.steps_ahead; + o.prefill_chunks_capped = m.prefill_chunks_capped; o.decode_rows_unspeculated = m.decode_rows_unspeculated; o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode; return o; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index cce072e3..b1a578fc 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -192,6 +192,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) { o["steps"] = m.steps; o["steps_prefill"] = m.steps_prefill; o["steps_mixed"] = m.steps_mixed; + o["prefill_chunks_capped"] = m.prefill_chunks_capped; o["steps_decode"] = m.steps_decode; /* WHAT THE STEPS COST, so the page does not have to divide wall clock by a step count. * That is the derivation this handler's header calls the page's job, and it is the one diff --git a/core/server/iface.h b/core/server/iface.h index 5d100858..36e8af27 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -132,6 +132,7 @@ struct SchedMetrics { int64_t steps_mixed = 0; int64_t steps_decode = 0; int64_t steps_ahead = 0; /* issued behind the step before, ahead of its commit */ + int64_t prefill_chunks_capped = 0; /* held back for other work in the step (--busy-prefill-chunk) */ int64_t decode_rows_unspeculated = 0; /* WHAT THE STEPS COST: cumulative nanoseconds spent inside a step, and the decode half of it * separately. A step time is not wall clock over a step count -- the engine idles between an diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index becd40ef..51b05de5 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -163,6 +163,7 @@ void Metrics::sample(const SchedMetrics& m) { c_steps_mixed_.inc(std::max(0.0, (double)m.steps_mixed - c_steps_mixed_.get())); c_steps_decode_.inc(std::max(0.0, (double)m.steps_decode - c_steps_decode_.get())); c_steps_ahead_.inc(std::max(0.0, (double)m.steps_ahead - c_steps_ahead_.get())); + c_prefill_capped_.inc(std::max(0.0, (double)m.prefill_chunks_capped - c_prefill_capped_.get())); c_rows_unspec_.inc(std::max(0.0, (double)m.decode_rows_unspeculated - c_rows_unspec_.get())); c_step_secs_.inc(std::max(0.0, (double)m.step_ns * 1e-9 - c_step_secs_.get())); @@ -332,6 +333,10 @@ std::string Metrics::render() const { w.counter("radiance:engine_steps_ahead_total", "Steps whose forward pass was issued behind the step before, ahead of its commit.", L, c_steps_ahead_.get()); + w.counter("radiance:engine_prefill_chunks_capped_total", + "Prefill chunks held back so decode rows and waiting requests got into the step " + "(--busy-prefill-chunk).", + L, c_prefill_capped_.get()); w.counter("radiance:decode_rows_unspeculated_total", "Decode rows that took no draft, for any reason.", L, c_rows_unspec_.get()); diff --git a/core/server/metrics.h b/core/server/metrics.h index 27396f32..832f6fce 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -144,6 +144,7 @@ private: /* STEPS BY SHAPE, and the decode rows a mixed step cost speculation. Exposed as counters so * two scrapes give the rate over a window rather than a number dominated by startup. */ Counter c_steps_prefill_, c_steps_mixed_, c_steps_decode_, c_rows_unspec_, c_steps_ahead_; + Counter c_prefill_capped_; /* SECONDS SPENT INSIDE A STEP, and the decode half of it. A step time is not wall clock over * a step count -- SchedMetrics::step_ns says why -- and without these every scraper has to * assume a saturated window and no prefill in it. */ diff --git a/docs/GUIDE.md b/docs/GUIDE.md index f7e7a529..2e5e6d6c 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -719,6 +719,24 @@ step, so a decode step queued behind one waits longer — but the prefill it is finishes sooner, and that is the larger term. Four decoders with a long prompt landing beside them finished in 29.5 s at a 2048 chunk against 31.9 s at 512. +**Nor does a long prefill lock out the work behind it** (`--busy-prefill-chunk`, default `auto`). +A chunk used to take every token the step had left, so for the whole of a long prompt's prefill — +a minute or more at 256K — a decode row behind it in the batch got no rows and a request that +arrived was not even admitted: a mostly-cached turn that needed a few hundred tokens waited for +somebody else's prompt to finish. Now, when other work is pending in a step, the chunk leaves it +room: one row plus the draft window for every decode row behind it, and a share of the budget +(an eighth, at least one quantum) for each prefill behind it and for the next request waiting to +start. It never drops under the smallest step the prefill stager overlaps (1025 tokens by +default), because under that every routed layer reads its pooled experts synchronously and the +prefill slows far more than the shared step saves; and where holding a chunk back for a waiting +request or another prefill would leave a short remainder before the checkpoint boundary, the +interval is split into two staged halves instead. Decode rows alone only take their few tokens: the +chunk ends a quantum short of the boundary and the next step finishes it, the same pair of steps a +prefill already runs when decode rows are ahead of it. A prompt with nothing beside it is planned exactly as before. `off` restores the old +behaviour; `--busy-prefill-chunk N` holds a shared chunk to N tokens (the startup line warns when +N is under the stager's step). `radiance:engine_prefill_chunks_capped_total` counts the chunks +held back. + **And check it did not cost you the prefix cache.** The arena it grows is charged before the split (§4.3), so the KV pool shrinks a little — here 516,864 → 499,920 pool tokens, 3.3% — and §4.3's cliff is sharp enough that 3% is worth confirming rather than assuming. On this shape it @@ -1028,6 +1046,7 @@ one line naming each one the command line moved. | flag | default | | |---|---|---| | `--max-num-batched-tokens N` | 8192 | largest token count one step may carry | +| `--busy-prefill-chunk MODE` | auto | a prefill chunk's share of a step that has other work: `auto` leaves decode rows behind it and waiting requests their room (§4.5), `off` takes the whole step, `N` holds it to N tokens | | `--max-num-seqs N` | 256 | largest number of sequences one step may carry | | `--max-model-len N` | 0 | context bound; 0 takes the model's training context | | `--rope-scaling SPEC` | — | `yarn:FACTOR[:ORIG]`: static YaRN over the container's own rotary keys, no reconvert; `none` takes a checkpoint's YaRN off ([YARN.md](YARN.md)) | diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index b1c9b83d..0737c421 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -1561,6 +1561,223 @@ TEST(a_running_prefill_does_not_suppress_the_draft) { CHECK_EQ(f.sch.plan().e[0].n_spec, 4); } +/* ================================================================== a prefill sharing a step */ +/* --busy-prefill-chunk. The shape that starves: the checkpoint interval as large as the step + * budget, so a long prefill's chunk can take the whole step every step. Here 512 and 512, the + * quantum 64; the sequence is long enough for many full chunks. */ +static void share_fixture(Fixture& f, int64_t mode) { + f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/4096); + f.cfg.checkpoint_interval = 512; + f.cfg.busy_prefill_chunk = mode; +} + +/* What 1.3.0 did, and `off` still does: once the long prefill owns the step, a request that + * arrives is not even admitted until it ends. */ +TEST(off_a_long_prefill_keeps_a_new_request_out_of_every_step) { + Fixture f; + share_fixture(f, /*off=*/0); + CHECK_OK(f.start()); + uint64_t a = f.submit(3500, 64); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); + f.commit_plain(); + uint64_t b = f.submit(100, 64); + for (int k = 0; k < 4; ++k) { + CHECK(f.sch.step() != nullptr); + CHECK_EQ((int)f.sch.plan().e.size(), 1); + CHECK_EQ(f.sch.plan().e[0].seq, a); + CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); + f.commit_plain(); + } + CHECK_EQ(f.sch.metrics().queue_depth, 1); + CHECK(f.sch.find(b) != nullptr); + CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 0); +} + +/* auto: the same arrival is admitted in the very next step, and its prompt finishes in two. */ +TEST(auto_a_request_arriving_during_a_long_prefill_is_admitted_at_once) { + Fixture f; + share_fixture(f, /*auto=*/-1); + CHECK_OK(f.start()); + uint64_t a = f.submit(3500, 64); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); /* alone: the whole step, as before */ + f.commit_plain(); + uint64_t b = f.submit(100, 64); + CHECK(f.sch.step() != nullptr); + CHECK_EQ((int)f.sch.plan().e.size(), 2); + CHECK_EQ(f.sch.metrics().queue_depth, 0); + int64_t a_tok = 0, b_tok = 0; + for (const StepEntry& e : f.sch.plan().e) { + if (e.seq == a) a_tok = e.n_tokens; + if (e.seq == b) b_tok = e.n_tokens; + } + CHECK(a_tok >= 64 && a_tok % 64 == 0); + CHECK(b_tok > 0); + CHECK(a_tok + b_tok <= 512); + CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 1); + f.commit_plain(11); + /* b's 100 tokens are done by the next step and it decodes beside the prefill from then on */ + for (int k = 0; k < 4; ++k) { + CHECK(f.sch.step() != nullptr); + bool saw_b = false; + for (const StepEntry& e : f.sch.plan().e) if (e.seq == b) saw_b = true; + CHECK(saw_b); + f.commit_plain(12); + } + CHECK((int)f.sch.find(b)->output.size() >= 2); +} + +/* A decode row BEHIND a long prefill in running_ (the prefill outranks it) is planned every step + * under auto; under off it is left out of every step that begins on an interval boundary. */ +static int decode_rows_seen(int64_t mode) { + Fixture f; + share_fixture(f, mode); + CHECK_OK(f.start()); + uint64_t b = f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); /* b's whole prompt: it decodes from the next step */ + f.commit_plain(11); + f.submit(3500, 64, /*priority=*/1); /* outranks b: walked first */ + int seen = 0; + for (int k = 0; k < 8; ++k) { + CHECK(f.sch.step() != nullptr); + for (const StepEntry& e : f.sch.plan().e) if (e.seq == b && !e.is_prefill) ++seen; + f.commit_plain(12); + } + return seen; +} + +TEST(auto_a_decode_row_behind_a_long_prefill_gets_every_step) { + CHECK_EQ(decode_rows_seen(-1), 8); + CHECK(decode_rows_seen(0) < 8); +} + +/* Nothing else wants in: the cap does not apply, and a lone prefill is planned chunk for chunk + * as before -- which is what keeps every single-request gate unchanged. */ +TEST(auto_a_lone_prefill_is_planned_as_before) { + std::vector plans[2]; + for (int m = 0; m < 2; ++m) { + Fixture f; + share_fixture(f, m == 0 ? 0 : -1); + CHECK_OK(f.start()); + f.submit(3000, 4); + for (int k = 0; k < 10; ++k) { + if (!f.sch.step()) break; + plans[m].push_back(f.sch.plan().e[0].n_tokens); + f.commit_plain(); + } + CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 0); + } + CHECK(plans[0] == plans[1]); +} + +/* An explicit N holds the chunk to N while something waits. */ +TEST(an_explicit_busy_prefill_chunk_holds_the_chunk_to_it) { + Fixture f; + share_fixture(f, 128); + CHECK_OK(f.start()); + uint64_t a = f.submit(3500, 64); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); /* alone */ + f.commit_plain(); + f.submit(100, 64); + CHECK(f.sch.step() != nullptr); + for (const StepEntry& e : f.sch.plan().e) + if (e.seq == a) CHECK_EQ(e.n_tokens, 128); +} + +/* The arithmetic, at the shape of a real deployment: a 2048-token step and interval, the stager + * arming at 1025 tokens (so a held-back chunk keeps 1024 and its step-mates make up the rest). */ +TEST(busy_cap_keeps_the_stager_floor_and_never_leaves_a_runt) { + Fixture f; + f.build(/*blocks=*/8192, /*states=*/64, /*max_tok=*/2048, /*max_ctx=*/8192); + f.cfg.checkpoint_interval = 2048; + CHECK_OK(f.start()); + f.sch.set_stage_rows(1025); + /* nothing reserved: the budget */ + CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 0), 2048); + /* a little reserved at an interval boundary: 2048 - 272 would leave a 272-token runt before + * the boundary, so the interval splits in two staged halves instead */ + CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 272), 1024); + /* half way to the boundary the rest of the interval already fits under the cap */ + CHECK(f.sch.busy_cap(1024, 100000, 2048, 272) >= 1024); + CHECK_EQ(f.sch.plan_chunk(1024, 100000, f.sch.busy_cap(1024, 100000, 2048, 272), nullptr), 1024); + /* more reserved than the floor allows for: the floor */ + CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 1500), 1024); + /* a prompt's last stretch, shorter than the cap: all of it */ + CHECK_EQ(f.sch.plan_chunk(0, 1500, f.sch.busy_cap(0, 1500, 2048, 272), nullptr), 1500); + /* a budget already under the floor: never more than the budget */ + CHECK_EQ(f.sch.busy_cap(0, 100000, 512, 64), 512); + /* decode rows alone behind it (2 rows x (1 + 3 drafts)): no split -- the chunk ends a quantum + * short of the boundary (1984) and the next step takes the remaining 64, the pair a prefill + * already runs with decode rows AHEAD of it */ + CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 8, false, /*rows_only=*/true), 2040); + CHECK_EQ(f.sch.plan_chunk(0, 100000, f.sch.busy_cap(0, 100000, 2048, 8, false, true), nullptr), 1984); + /* the same reserve with a share in it splits the interval */ + CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 8 + 256, false, false), 1024); +} + +/* The share left for a request that then does not start (here its context is still being read + * back from the host tier) goes back to the chunk that made room for it: the step is planned as + * if nothing had waited. */ +TEST(auto_a_share_nobody_takes_goes_back_to_the_prefill) { + Fixture f; + share_fixture(f, -1); + CHECK_OK(f.start()); + uint64_t a = f.submit(3500, 64); + CHECK(f.sch.step() != nullptr); + f.commit_plain(); + uint64_t b = f.submit(100, 64); + f.pc.reading.push_back(b); + CHECK(f.sch.step() != nullptr); + REQUIRE_EQ((int)f.sch.plan().e.size(), 1); + CHECK_EQ(f.sch.plan().e[0].seq, a); + CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); + CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 0); + CHECK_EQ(f.sch.metrics().queue_depth, 1); +} + +/* An explicit N also holds a chunk back for rows planned AHEAD of it -- the operator's trade of + * prefill speed for every other row's latency; auto leaves those alone. */ +TEST(an_explicit_busy_prefill_chunk_applies_to_rows_ahead_auto_does_not) { + for (int64_t mode : { (int64_t)-1, (int64_t)128 }) { + Fixture f; + share_fixture(f, mode); + CHECK_OK(f.start()); + uint64_t b = f.submit(100, 512, /*priority=*/1); /* outranks the prefill: planned first */ + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + uint64_t a = f.submit(3500, 64, /*priority=*/0); + CHECK(f.sch.step() != nullptr); /* b decodes, a is admitted behind it */ + f.commit_plain(12); + int64_t most = 0; bool saw_b = true; + for (int k = 0; k < 3; ++k) { + CHECK(f.sch.step() != nullptr); + bool here = false; + for (const StepEntry& e : f.sch.plan().e) { + if (e.seq == a) most = std::max(most, e.n_tokens); + if (e.seq == b) here = true; + } + saw_b = saw_b && here; + f.commit_plain(12); + } + CHECK(saw_b); + if (mode > 0) CHECK_EQ(most, 128); + else CHECK(most > 128); + } +} + +TEST(busy_cap_is_the_budget_when_off) { + Fixture f; + f.build(/*blocks=*/8192, /*states=*/64, /*max_tok=*/2048, /*max_ctx=*/8192); + f.cfg.checkpoint_interval = 2048; + f.cfg.busy_prefill_chunk = 0; + CHECK_OK(f.start()); + f.sch.set_stage_rows(1025); + CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 272), 2048); + CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 1500), 2048); +} + TEST(the_draft_depth_is_the_configured_one_whatever_the_acceptance_trace) { DraftController c; DraftController::Params p;