From 15a4be9c7a2fa4e445f0ee1ba18a53f917c48e39 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 01:17:13 +0100 Subject: [PATCH 01/17] spec: the draft-cost table learns from the first seconds of a busy run The learned window costs came from one continuous learning stretch. On a GPU that slows down under sustained load (measured on an M5 Max: 1 row 14 %, 3 rows 21 %, 5 rows 27 % slower after 75 s of continuous load) the stretch priced 5 rows at 1.38 times 3 rows against 1.30 for a request that arrives after a pause, so the fixed table priced two profitable 5-row lookup windows per request out. The learner now keeps each round with the busy age it ran at (seconds since the last pause of 0.5 s or more between requests, measured at the request's arrival). Rounds of the first 6 s are fresh, the rest late. The table uses the fresh rounds when a size with 20 samples of both differs by more than 2 % between them, and every round otherwise (the Radeon 780M shows no difference, so it keeps all its rounds). A stretch that never pauses ends after three times the round quota when a fifth of the quota is fresh. Sizes with fewer than 20 samples above the measured ones continue the straight line through the two largest measured sizes; the table never falls from one size to the next. The file header is version 2, so tables already learned are learned again; a table is still written whole or not at all, only when the stretch is ready, and is fixed from then on. --- include/strata/spec/draft_policy.hpp | 47 +++++++++--- src/program/generate.cpp | 15 +++- src/spec/draft_policy.cpp | 68 +++++++++++++---- src/spec/draft_policy_test.cpp | 106 +++++++++++++++++++++++++-- 4 files changed, 204 insertions(+), 32 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index 29e37d7e6c..ef5850493a 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -35,25 +35,46 @@ namespace strata::spec { /// The round times of a learning stretch, by context bucket and window size, for a fixed cost table. Keeps up to kKeep /// samples per (bucket, size) in arrival order. +/// +/// Which rounds count (measured, phaseA-tests/par/RESULTS-DRAFT-COSTS.md): on an Apple M5 Max a GPU that has been busy for more than about 7 s runs +/// slower, and unevenly by window size (after 75 s of continuous load 5 rows cost 27 % more and 1 row 14 % more, so 5 rows against 3 rows read 1.38 +/// instead of 1.30), while a request that arrives after a pause of half a second runs in the fast state at once; the Radeon 780M shows no such +/// difference (round times within 1 % at any load time). The table is what requests after a pause cost. add() takes the busy age of the round +/// (`busy_age_s`: the seconds since the last pause of kIdleS or more) and keeps the rounds of the first kFreshS seconds ("fresh") apart from the later +/// ones ("late"); the table uses the fresh rounds only when the late ones differ from them by more than kStateTol in some size that has min_n of +/// both (a state effect), and all rounds otherwise (the engine does not need the split on a machine that has no such difference, and more rounds +/// measure the rare sizes better). class CostLearner { public: static constexpr int kMaxT = 16; static constexpr int kCtxBuckets = 3; static constexpr int kKeep = 4096; - void add(int bucket, int t, double ms); + static constexpr double kFreshS = 6.0; ///< a round is fresh when the engine has been busy for at most this long (M5 Max: flat to 7.5 s, +3 % at 7.5-10 s) + static constexpr double kIdleS = 0.5; ///< a pause of this length (no request running) starts a new busy run; the caller measures it (M5 Max: 0.5 s restores the fast state) + static constexpr double kStateTol = 0.02; ///< late against fresh round times beyond this in some size = a state effect + static constexpr int kFallbackFactor = 3; ///< with a state effect, a stretch with this many times min_rounds timed rounds of any age ends with the fresh ones ... + static constexpr int kFallbackShare = 5; ///< ... when they are at least 1 / kFallbackShare of min_rounds + /// `busy_age_s` < 0: unknown (counts as fresh). + void add(int bucket, int t, double ms, double busy_age_s = -1.0); void reset(); - int64_t rounds() const { return rounds_; } - int samples(int bucket, int t) const; + int64_t rounds() const { return rounds_; } ///< the fresh rounds + int64_t late_rounds() const { return late_; } ///< the rounds after the engine had been busy for more than kFreshS + int samples(int bucket, int t) const; ///< fresh samples of a size + /// A state effect in `bucket`: some size has at least `min_n` fresh and `min_n` late samples and their trimmed means differ by more than kStateTol. + bool state_effect(int bucket, int min_n) const; /// The table of `bucket` for windows 1..n (n = the largest size seen in that bucket; empty when the bucket has none): - /// the trimmed mean (the lowest and highest kTrim share dropped) of each size with at least `min_n` samples; the other - /// sizes are filled between measured neighbours (linear in the size) or, outside them, by the policy's prior shape. + /// the trimmed mean (the lowest and highest kTrim share dropped) of each size with at least `min_n` samples; a size in between two + /// measured ones is linear in the size; a size above the measured ones continues the straight line through the two largest measured + /// sizes (one measured size: the policy's prior shape), below them the prior shape; the table never falls from one size to the next. std::vector table(int bucket, int min_n) const; struct Verdict { bool ready = false; ///< enough rounds, and every bucket with data has a size with min_n samples bool disturbed = false; ///< the stretch looks disturbed: do not keep a table from it (start learning again) std::string why; ///< what was seen (for the log) }; - /// Ready after `min_rounds` timed rounds. Disturbed (each check per size with at least 2 x min_n samples): + /// Ready after `min_rounds` usable rounds (fresh and late ones when no bucket has a state effect, the fresh ones when one has), or, with a state + /// effect, after kFallbackFactor x `min_rounds` rounds of any age when at least `min_rounds` / kFallbackShare of them are fresh (one long burst + /// keeps only its first kFreshS seconds). Disturbed (each check per size with at least 2 x min_n samples, on the samples the table uses): /// (1) its trimmed means of the first and the second half of its samples differ by more than kDriftMax; /// (2) more than kSpikeMax of its samples are above twice its median; /// (3) a measured size is cheaper than a measured smaller one by more than kOrderSlack (a round of more rows cannot be cheaper). @@ -64,13 +85,17 @@ public: static constexpr double kOrderSlack = 0.10; private: - std::array, kMaxT + 1>, kCtxBuckets> s_{}; + /// The samples of every size of `bucket` that the table uses: the fresh ones, or fresh + late. + std::array, kMaxT + 1> sets(int bucket, bool pooled) const; + std::array, kMaxT + 1>, kCtxBuckets> s_{}; // fresh + std::array, kMaxT + 1>, kCtxBuckets> late_s_{}; // late int64_t rounds_ = 0; + int64_t late_ = 0; }; /// The per-machine table file of --draft-costs: text, one table per context bucket, valid only for the `key` it was learned under /// (card, driver, engine, model, drafter and the settings that move a round's cost; the engine builds it). -/// strata-draft-costs 1 +/// strata-draft-costs 2 (1: tables learned from every round of a stretch; they are learned again) /// key /// bucket <0..2> ,,... /// share <0..1> (optional: the CPU prompt share learned on this machine, src/prefill/prefill.cpp) @@ -150,6 +175,9 @@ public: /// Learning a fixed table: every timed round also goes to learner() (raw round time, in its context bucket). Off by default. void set_learning(bool on) { learning_ = on; } bool learning() const { return learning_; } + /// How long the engine has been busy (seconds since its last pause of CostLearner::kIdleS), as the caller measures it, for the round + /// observe() is about to be given; < 0 (the default): unknown. Only the learner reads it. + void set_busy_age(double s) { busy_age_ = s; } CostLearner& learner() { return learner_; } const CostLearner& learner() const { return learner_; } @@ -197,6 +225,7 @@ private: bool robust_ = false; bool fixed_ = false; // set_fixed_costs: no round time changes a cost bool learning_ = false; // set_learning: round times also go to learner_ + double busy_age_ = -1.0; // set_busy_age CostLearner learner_; double clamp_sample(int t, double ms) const; static constexpr int kPBuckets = 8; @@ -205,7 +234,7 @@ private: // Gated proposals (observe_committed / defer_cost / apply_costs); all zero or empty on any other path. std::array, kCtxBuckets> tried_{}; // lookup windows of that size run with no time yet std::array, kCtxBuckets> delayed_n_{}; // of cost_n_: times applied by apply_costs (not new probes) - struct HeldCost { int64_t end; int bucket; int t; double ms; }; + struct HeldCost { int64_t end; int bucket; int t; double ms; double age; }; std::vector held_; // defer_cost, oldest first }; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 03597409dc..53e2460cbc 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14549,6 +14549,10 @@ int main(int argc, char** argv) { constexpr int kDraftCostMinN = 20; // a window size needs this many rounds to be measured (fewer: filled in) std::string dc_key; bool dc_learning = false; + // how long the engine has been busy: the learner keeps only the rounds of the first seconds of a busy run (CostLearner::kFreshS); a busy run + // starts at a request that begins CostLearner::kIdleS or more after the last one ended (the GPU runs slower and steeper after a long load) + Clock::time_point dc_busy_since = Clock::now(), dc_last_end = Clock::now(); + bool dc_seen_request = false; bool dc_pcie_pending = false; // a loaded table without a PCIe share: written into it once PcieAuto has settled strata::spec::CostFile dc_file; // that table, as loaded if (!o.draft_costs.empty() && !policy.fixed()) { @@ -16269,7 +16273,14 @@ int main(int argc, char** argv) { continue; } const bool geni = line.rfind("GENI ", 0) == 0; - if (geni || line.rfind("GEN ", 0) == 0) refresh_file_tier(); + if (geni || line.rfind("GEN ", 0) == 0) { + refresh_file_tier(); + if (dc_learning) { // the request's arrival, before its prompt is read: a pause since the last one ended starts a new busy run + const Clock::time_point dc_now = Clock::now(); + if (!dc_seen_request || std::chrono::duration(dc_now - dc_last_end).count() >= strata::spec::CostLearner::kIdleS) dc_busy_since = dc_now; + dc_seen_request = true; + } + } if (!geni && line.rfind("GEN ", 0) != 0) { std::printf("ERR expected: GEN or GENI \n"); continue; @@ -19975,6 +19986,7 @@ int main(int argc, char** argv) { tr_k = 0; } if (spec_cost && use_mtp && timed_round && !from_sfx) policy.observe_probs(dwin_s.data(), T_mtp - 1, a); + if (dc_learning) policy.set_busy_age(std::chrono::duration(Clock::now() - dc_busy_since).count()); if (timed_round && !eos && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, std::chrono::duration(Clock::now() - round0).count()); @@ -19991,6 +20003,7 @@ int main(int argc, char** argv) { if (hold_on && std::strcmp(finish, "length") == 0 && produced_n >= req_hold_n && (produced_n < max_new || admit_slot >= 0)) finish = "hold"; if (!keep_sync()) { std::printf("ERR %s\n", err.c_str()); return 1; } const double decode_ms = std::chrono::duration(Clock::now() - d0).count(); + dc_last_end = Clock::now(); // the busy run goes on when the next request starts within CostLearner::kIdleS of this if (use_df2 && o.draft_auto && bandit_key != 0 && produced_n >= 48 && decode_ms > 0.0) { DraftBandit& b = bandit[bandit_key]; const int w = req_df2 ? 1 : 0; diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 6c26a697fe..84973c4daa 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -79,19 +79,45 @@ double median_of(std::vector v) { static_assert(CostLearner::kMaxT == DraftPolicy::kMaxT && CostLearner::kCtxBuckets == DraftPolicy::kCtxBuckets, "one table shape"); -void CostLearner::add(int bucket, int t, double ms) { +void CostLearner::add(int bucket, int t, double ms, double busy_age_s) { if (!(ms > 0.0) || !std::isfinite(ms)) return; bucket = std::clamp(bucket, 0, kCtxBuckets - 1); t = std::clamp(t, 1, kMaxT); - ++rounds_; - auto& v = s_[(size_t) bucket][(size_t) t]; + const bool late = busy_age_s > kFreshS; // a GPU that has been busy for long can run in another state than a request after a pause finds it + ++(late ? late_ : rounds_); + auto& v = (late ? late_s_ : s_)[(size_t) bucket][(size_t) t]; if ((int) v.size() < kKeep) v.push_back((float) ms); } void CostLearner::reset() { for (auto& b : s_) for (auto& v : b) v.clear(); + for (auto& b : late_s_) + for (auto& v : b) v.clear(); rounds_ = 0; + late_ = 0; +} + +bool CostLearner::state_effect(int bucket, int min_n) const { + if (bucket < 0 || bucket >= kCtxBuckets) return false; + const int need = std::max(1, min_n); + for (int t = 1; t <= kMaxT; ++t) { + const auto& f = s_[(size_t) bucket][(size_t) t]; + const auto& l = late_s_[(size_t) bucket][(size_t) t]; + if ((int) f.size() < need || (int) l.size() < need) continue; + const double tf = trimmed_mean(f), tl = trimmed_mean(l); + if (tf > 0.0 && std::fabs(tl - tf) / tf > kStateTol) return true; + } + return false; +} + +std::array, CostLearner::kMaxT + 1> CostLearner::sets(int bucket, bool pooled) const { + std::array, kMaxT + 1> out; + for (int t = 1; t <= kMaxT; ++t) { + out[(size_t) t] = s_[(size_t) bucket][(size_t) t]; + if (pooled) out[(size_t) t].insert(out[(size_t) t].end(), late_s_[(size_t) bucket][(size_t) t].begin(), late_s_[(size_t) bucket][(size_t) t].end()); + } + return out; } int CostLearner::samples(int bucket, int t) const { @@ -102,7 +128,7 @@ int CostLearner::samples(int bucket, int t) const { std::vector CostLearner::table(int bucket, int min_n) const { std::vector out; if (bucket < 0 || bucket >= kCtxBuckets) return out; - const auto& b = s_[(size_t) bucket]; + const std::array, kMaxT + 1> b = sets(bucket, !state_effect(bucket, min_n)); int top = 0; std::array got{}; std::vector seen; @@ -125,24 +151,30 @@ std::vector CostLearner::table(int bucket, int min_n) const { if (u > t && hi == 0) hi = u; } if (lo > 0 && hi > 0) out.push_back(got[(size_t) lo] + (got[(size_t) hi] - got[(size_t) lo]) * (t - lo) / (double) (hi - lo)); - else { - const int u = hi > 0 ? hi : lo; - out.push_back(got[(size_t) u] * kShape[t] / kShape[u]); - } + else if (hi > 0) out.push_back(got[(size_t) hi] * kShape[t] / kShape[hi]); // below every measured size: the prior shape + else if (seen.size() >= 2) { // above them: the straight line through the two largest measured sizes (a size with a few samples is not trusted) + const int u2 = seen[seen.size() - 1], u1 = seen[seen.size() - 2]; + const double slope = std::max(0.0, (got[(size_t) u2] - got[(size_t) u1]) / (double) (u2 - u1)); + out.push_back(got[(size_t) u2] + slope * (t - u2)); + } else out.push_back(got[(size_t) lo] * kShape[t] / kShape[lo]); } + for (size_t i = 1; i < out.size(); ++i) out[i] = std::max(out[i], out[i - 1]); // more rows never cost less return out; } CostLearner::Verdict CostLearner::check(int64_t min_rounds, int min_n) const { Verdict v; char b[160]; - bool any = false, every_bucket_ok = true; + bool any = false, every_bucket_ok = true, effect = false; for (int k = 0; k < kCtxBuckets; ++k) { bool has = false, measured = false; double prev_ms = 0.0; int prev_t = 0; + const bool eff = state_effect(k, min_n); + effect = effect || eff; + const std::array, kMaxT + 1> use = sets(k, !eff); for (int t = 1; t <= kMaxT; ++t) { - const auto& s = s_[(size_t) k][(size_t) t]; + const auto& s = use[(size_t) t]; has = has || !s.empty(); if ((int) s.size() < std::max(1, min_n)) continue; measured = true; @@ -175,14 +207,18 @@ CostLearner::Verdict CostLearner::check(int64_t min_rounds, int min_n) const { any = any || measured; if (has && !measured) every_bucket_ok = false; } - v.ready = rounds_ >= min_rounds && any && every_bucket_ok; + // no state effect: every round counts. With one: the fresh rounds, or, for a stretch that never paused (one long burst keeps only its first kFreshS + // seconds), kFallbackFactor x the quota in rounds of any age when the fresh ones are at least 1 / kFallbackShare of the quota + const bool enough = effect ? (rounds_ >= min_rounds || (rounds_ + late_ >= kFallbackFactor * min_rounds && rounds_ * kFallbackShare >= min_rounds)) + : rounds_ + late_ >= min_rounds; + v.ready = enough && any && every_bucket_ok; return v; } // ---------------------------------------------------------------------------------------------------- the table file namespace { -constexpr const char* kCostFileHead = "strata-draft-costs 1"; +constexpr const char* kCostFileHead = "strata-draft-costs 2"; // 2: learned from the rounds of the first seconds of a busy run; a version 1 file is learned again // the path as UTF-8 (the server passes it so); on Windows a plain std::string would be read in the ANSI code page std::filesystem::path utf8_path(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); } std::string one_line(std::string s) { @@ -439,7 +475,7 @@ DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) { t = std::clamp(t, 1, kMaxT); - if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms); + if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_); if (round_ms > 0 && !fixed_) { round_ms = clamp_sample(t, round_ms); const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha; // a running mean for the first samples @@ -476,7 +512,7 @@ void DraftPolicy::observe_committed(bool lookup, int t, int accepted, int match) } void DraftPolicy::defer_cost(int64_t end, int t, double round_ms) { - if (round_ms > 0 && (learning_ || !fixed_)) held_.push_back({end, bk_, std::clamp(t, 1, kMaxT), round_ms}); + if (round_ms > 0 && (learning_ || !fixed_)) held_.push_back({end, bk_, std::clamp(t, 1, kMaxT), round_ms, busy_age_}); } void DraftPolicy::apply_costs(int64_t committed) { @@ -484,7 +520,7 @@ void DraftPolicy::apply_costs(int64_t committed) { const int bucket_now = bk_; for (; n < held_.size() && held_[n].end < committed; ++n) { const HeldCost& h = held_[n]; - if (learning_) learner_.add(h.bucket, h.t, h.ms); + if (learning_) learner_.add(h.bucket, h.t, h.ms, h.age); if (fixed_) continue; bk_ = h.bucket; // observe()'s update, in the bucket the round ran in const double ms = clamp_sample(h.t, h.ms); @@ -584,7 +620,7 @@ int DraftPolicy::chain(int t_mtp, double p_mtp, int k_avail, int match) const { void DraftPolicy::observe_chain(int t_mtp, int k, int accepted, int match, double round_ms) { const int t = std::clamp(t_mtp + k, 1, kMaxT); - if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms); + if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_); if (round_ms > 0 && !fixed_) { round_ms = clamp_sample(t, round_ms); const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha; // a running mean for the first samples diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index bb425d597f..dba0b1053c 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -8,6 +8,7 @@ // 5. the policy never proposes a window beyond its cap. #include "strata/spec/draft_policy.hpp" +#include #include #include #include @@ -279,6 +280,89 @@ int main() { check(p.learner().rounds() == 3 && p.learner().samples(0, 4) == 2 && p.learner().samples(0, 2) == 1, "learning on: observe, observe_chain and held times are collected"); } + { + // The fixture of the Mac lane's fresh learning run (M5 Max, Q2_0, 30 requests of 256 tokens): sample counts and mean round ms per window size. + // 4 rows had 2 samples: its value comes from its neighbours, not from the two samples. + using strata::spec::CostLearner; + const auto fill = [](CostLearner& L, int t, int n, double ms, double age) { // n samples around ms (+-1 %, mean ms) + for (int i = 0; i < n; ++i) L.add(0, t, ms * (1.0 + 0.005 * ((i % 5) - 2)), age); + }; + CostLearner M; + fill(M, 1, 1193, 13.50, 2.0); fill(M, 2, 894, 15.74, 2.0); fill(M, 3, 1834, 18.40, 2.0); fill(M, 4, 2, 22.62, 2.0); fill(M, 5, 83, 24.95, 2.0); + const std::vector t = M.table(0, 20); + check(t.size() == 5 && std::fabs(t[0] - 13.50) < 0.05 && std::fabs(t[2] - 18.40) < 0.05 && std::fabs(t[4] - 24.95) < 0.05, "fit: the well-sampled sizes are their trimmed means"); + check(t.size() == 5 && std::fabs(t[3] - (18.40 + 24.95) / 2.0) < 0.05, "fit: 4 rows (2 samples) lie between its neighbours, not at its own 22.62"); + check(M.rounds() == 4006 && M.late_rounds() == 0, "fit: all 4,006 rounds of the fixture were fresh"); + // a size above the measured ones (5 rows with 8 samples): the straight line through the two largest measured sizes + CostLearner E; + fill(E, 1, 600, 12.5, 2.0); fill(E, 2, 400, 14.2, 2.0); fill(E, 3, 700, 16.2, 2.0); fill(E, 5, 8, 99.0, 2.0); + const std::vector e = E.table(0, 20); + check(e.size() == 5 && std::fabs(e[3] - (16.2 + 2.0)) < 0.05 && std::fabs(e[4] - (16.2 + 4.0)) < 0.05, + "fit: 4 and 5 rows above the measured sizes continue the line through 2 and 3 rows (8 samples of 5 rows are not trusted)"); + bool mono = true; + for (size_t i = 1; i < e.size(); ++i) mono &= e[i] >= e[i - 1]; + CostLearner Dn; // a size measured cheaper than the one before it (noise): the table does not fall + fill(Dn, 1, 100, 20.0, 2.0); fill(Dn, 2, 100, 19.0, 2.0); fill(Dn, 3, 100, 25.0, 2.0); + const std::vector d = Dn.table(0, 20); + mono &= d.size() == 3 && d[1] >= d[0] && d[2] >= d[1]; + check(mono, "fit: the table never falls from one size to the next"); + // busy age: a fast state for the first seconds of a run, a slow and steeper one later; only the first is kept + CostLearner B; + for (int i = 0; i < 1400; ++i) { + B.add(0, 1, 12.5, 4.0); B.add(0, 2, 14.2, 4.0); B.add(0, 3, 16.2, 4.0); // fresh (the first seconds of a run) + B.add(0, 1, 14.5, 60.0); B.add(0, 2, 17.1, 60.0); B.add(0, 3, 20.2, 60.0); // the same machine after a minute of load + if (i % 25 == 0) { B.add(0, 5, 21.3, 4.0); B.add(0, 5, 27.7, 60.0); } + } + const std::vector b = B.table(0, 20); + check(B.rounds() == 4200 + 56 && B.late_rounds() == 4200 + 56, "busy age: late rounds are counted and not kept"); + check(b.size() == 5 && std::fabs(b[2] - 16.2) < 0.05 && std::fabs(b[4] / b[2] - 21.3 / 16.2) < 0.01, + "busy age: the table is the fast state (5 rows against 3 rows 1.31, not 1.37 of the late rounds)"); + CostLearner U; // an age that is not known counts as fresh + U.add(0, 3, 16.0); + check(U.rounds() == 1 && U.late_rounds() == 0, "busy age: an unknown age (none given) is kept"); + // readiness: a stretch that never paused ends with its first seconds after 3 x the quota; one that is mid-way is not ready + CostLearner Bur; + for (int i = 0; i < 300; ++i) { Bur.add(0, 1, 12.5, 2.0); Bur.add(0, 2, 14.2, 2.0); Bur.add(0, 3, 16.2, 2.0); } // 900 fresh rounds + check(!Bur.check(1000, 20).ready, "ready: 900 fresh rounds and nothing else is not ready"); + for (int i = 0; i < 700; ++i) Bur.add(0, 3, 20.2, 90.0); + check(!Bur.check(1000, 20).ready, "ready: late rounds below 3 x the quota do not end a short stretch"); + CostLearner Bur2; // one long burst: 330 fresh rounds, then 2,700 late ones + for (int i = 0; i < 110; ++i) { Bur2.add(0, 1, 12.5, 2.0); Bur2.add(0, 2, 14.2, 2.0); Bur2.add(0, 3, 16.2, 2.0); } + for (int i = 0; i < 2000; ++i) Bur2.add(0, 3, 20.2, 90.0); + check(!Bur2.check(1000, 20).ready, "ready: 330 fresh + 2,000 late rounds (under 3 x the quota) is not ready"); + for (int i = 0; i < 700; ++i) Bur2.add(0, 3, 20.2, 90.0); + const CostLearner::Verdict bv = Bur2.check(1000, 20); + const std::vector bt = Bur2.table(0, 20); + check(bv.ready && !bv.disturbed && bt.size() == 3 && std::fabs(bt[2] - 16.2) < 0.05, + "ready: one burst that never paused ends after 3 x the quota, with the table of its first seconds"); + CostLearner Few; // 150 fresh rounds only: not enough even after a very long burst + for (int i = 0; i < 50; ++i) { Few.add(0, 1, 12.5, 2.0); Few.add(0, 2, 14.2, 2.0); Few.add(0, 3, 16.2, 2.0); } + for (int i = 0; i < 5000; ++i) Few.add(0, 3, 20.2, 90.0); + check(!Few.check(1000, 20).ready, "ready: under a fifth of the quota kept is never ready"); + // a machine without a state effect (the Radeon 780M: 75.5 ms for one row early, 76.0 late; windows of 1, 3 and 6 rows): every round counts, the rare sizes + // get all their samples (3 rows: 8 fresh + 100 late) + CostLearner R; + fill(R, 1, 80, 75.5, 2.0); fill(R, 3, 8, 111.0, 2.0); fill(R, 6, 3, 178.0, 2.0); + fill(R, 1, 1200, 76.0, 40.0); fill(R, 3, 100, 111.2, 40.0); fill(R, 6, 14, 178.1, 40.0); + const std::vector rt = R.table(0, 20); + check(!R.state_effect(0, 20), "pooled: 0.7 % between early and late rounds is no state effect"); + check(rt.size() == 6 && std::fabs(rt[2] - 111.1) < 0.2 && std::fabs(rt[0] - 76.0) < 0.2, "pooled: the table uses every round (3 rows from 108 samples)"); + check(R.check(1000, 20).ready, "pooled: ready after the quota of rounds of any age"); + check(B.state_effect(0, 20), "state effect: 16 % between early and late rounds is one"); + // the policy hands the age to the learner, and a held (gated) time keeps the age it had + DraftPolicy pa(6); + pa.set_learning(true); + pa.set_busy_age(30.0); + pa.observe(false, 3, 1, 0, 20.0); + pa.set_busy_age(2.0); + pa.observe(false, 3, 1, 0, 16.0); + check(pa.learner().rounds() == 1 && pa.learner().late_rounds() == 1 && pa.learner().samples(0, 3) == 1, "policy: a round is kept by the busy age it ran at"); + pa.set_busy_age(40.0); + pa.defer_cost(5, 3, 21.0); + pa.set_busy_age(1.0); + pa.apply_costs(100); + check(pa.learner().rounds() == 1 && pa.learner().late_rounds() == 2, "policy: a held time keeps the busy age of its round"); + } { // The table file: a round trip, another key, a cut-short file, a missing file, a folder that does not exist yet. namespace fs = std::filesystem; @@ -298,9 +382,9 @@ int main() { "file: read back with its key, every bucket as written"); check(!strata::spec::read_cost_file(path, "card B|engine 1|model m spec 6", r, why) && !why.empty(), "file: another key is not loaded"); check(!strata::spec::read_cost_file((dir / "none.costs").string(), c.key, r, why), "file: a missing file is not loaded"); - { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18"; } + { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18"; } check(!strata::spec::read_cost_file(path, "x", r, why), "file: a cut-short file (no end line) is not loaded"); - { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,abc\nend\n"; } + { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,abc\nend\n"; } check(!strata::spec::read_cost_file(path, "x", r, why), "file: a malformed table is not loaded"); check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why), "file: a bad file is replaced whole"); check(!fs::exists(fs::path(path + ".tmp"), ec), "file: no temporary file is left"); @@ -308,21 +392,31 @@ int main() { c.cpu_share = 0.45; check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && r.cpu_share == 0.45, "file: the CPU prompt share is stored and read back with the table"); - { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\nshare 1.7\nend\n"; } + { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\nshare 1.7\nend\n"; } check(!strata::spec::read_cost_file(path, "x", r, why), "file: a share outside 0..1 is not loaded"); // the decode PCIe share PcieAuto settled on (repeatable output): stored and read back; a file written before it has none, and // still loads (the engine then refines the share as before and writes it) - { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\nshare 0.900\nend\n"; } + { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\nshare 0.900\nend\n"; } check(strata::spec::read_cost_file(path, "x", r, why) && r.cpu_share == 0.9 && r.pcie_frac < 0.0, "file: a file from before the PCIe share loads, with no PCIe share"); c.pcie_frac = 0.15; check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && r.pcie_frac == 0.15 && r.cpu_share == 0.45 && r.tables[0].size() == 4, "file: the PCIe share is stored and read back with the table and the prompt share"); - { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\npcie -0.2\nend\n"; } + { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\npcie -0.2\nend\n"; } check(!strata::spec::read_cost_file(path, "x", r, why), "file: a PCIe share outside 0..1 is not loaded"); - { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\npcie 0.15x\nend\n"; } + { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\npcie 0.15x\nend\n"; } check(!strata::spec::read_cost_file(path, "x", r, why), "file: a malformed PCIe share is not loaded"); + // version 1 (learned from every round, so from the slow state of a long burst): not loaded, learned again + { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\nend\n"; } + check(!strata::spec::read_cost_file(path, "x", r, why) && why.find("format") != std::string::npos, "file: a version 1 table is not loaded (learned again)"); + // a start closed in the middle of learning leaves no table: nothing is written before the stretch is ready, and a half-written temporary file + // (the process died while writing) is never read as the table + fs::remove(fs::path(path), ec); + { std::ofstream f(path + ".tmp", std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18"; } + check(!strata::spec::read_cost_file(path, "x", r, why), "file: a half-written temporary file beside a missing table is not a table"); + check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && !fs::exists(fs::path(path + ".tmp"), ec), + "file: the next write replaces the leftover temporary file and the table loads"); fs::remove_all(dir, ec); } std::printf(g_fail ? "FAIL\n" : "PASS\n"); From 1e50a146ed298edbfb23b06591b8525fe4a84888 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 02:05:23 +0100 Subject: [PATCH 02/17] spec: a learning stretch measures the window sizes it can pick The draft-cost table was filled in for every size with fewer than 20 rounds. On the Radeon 780M two sizes had 2 and 6-12 rounds, the filled values (134.6 / 129.7 ms against 143 measured for 4 rows) lay below the measured trend, and a frozen table of guessed sizes can lose to live costs. - After 300 rounds of a learning stretch, a lookup proposal long enough for a size that has under 30 samples takes that size's window (smallest size first), at most 40 times per size and 150 times in a stretch. Nothing is forced when learning is off or the costs are fixed. A learning stretch was never repeatable: window sizes follow the live costs. - A size with 5 to 19 rounds counts by its median when that median is not below the fill and at most 1.5 times it; a handful of stalled rounds does not. - A size above the measured ones continues the steeper of the last segment's slope and the slope over all measured sizes, and the table is written up to the largest allowed window size (so no size is left to the prior shape). - CostLearner::table gains an `upto` argument; DraftPolicy gains reset_learning(), top_size() and forced_rounds(). - Unit test draft_policy_test: 103 of 103 (15 new: table fill rules, forced-round budget, per-size cap, none when fixed or not learning, a size no proposal reaches). --- include/strata/spec/draft_policy.hpp | 31 +++++++++-- src/program/generate.cpp | 6 +-- src/spec/draft_policy.cpp | 70 ++++++++++++++++++++----- src/spec/draft_policy_test.cpp | 77 ++++++++++++++++++++++++++++ 4 files changed, 162 insertions(+), 22 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index ef5850493a..a958803a38 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -62,11 +62,15 @@ public: int samples(int bucket, int t) const; ///< fresh samples of a size /// A state effect in `bucket`: some size has at least `min_n` fresh and `min_n` late samples and their trimmed means differ by more than kStateTol. bool state_effect(int bucket, int min_n) const; - /// The table of `bucket` for windows 1..n (n = the largest size seen in that bucket; empty when the bucket has none): - /// the trimmed mean (the lowest and highest kTrim share dropped) of each size with at least `min_n` samples; a size in between two - /// measured ones is linear in the size; a size above the measured ones continues the straight line through the two largest measured - /// sizes (one measured size: the policy's prior shape), below them the prior shape; the table never falls from one size to the next. - std::vector table(int bucket, int min_n) const; + /// The table of `bucket` for windows 1..n (n = the largest size seen in that bucket, or `upto` when that is larger; empty when the bucket has none): + /// the trimmed mean (the lowest and highest kTrim share dropped) of each size with at least `min_n` samples; a size with kWeakN to min_n - 1 + /// samples counts with its median when that is within [fill, kWeakMax x fill] (a rough measurement, never below the trend); a size in between two measured ones is linear in the size; a size above the + /// measured ones continues the straight line through them with the steeper of the last segment's slope and the slope over all measured sizes + /// (costs grow at least that fast: a fill never falls below the measured trend; one measured size: the policy's prior shape), below them the + /// prior shape; the table never falls from one size to the next. + std::vector table(int bucket, int min_n, int upto = 0) const; + static constexpr int kWeakN = 5; ///< samples from which a size below min_n counts by its median ... + static constexpr double kWeakMax = 1.5; ///< ... when that median is not below the fill and at most this many times it (a stalled handful is not a measurement) struct Verdict { bool ready = false; ///< enough rounds, and every bucket with data has a size with min_n samples bool disturbed = false; ///< the stretch looks disturbed: do not keep a table from it (start learning again) @@ -175,6 +179,20 @@ public: /// Learning a fixed table: every timed round also goes to learner() (raw round time, in its context bucket). Off by default. void set_learning(bool on) { learning_ = on; } bool learning() const { return learning_; } + /// Measuring the sizes the policy can pick (learning only): after kExploreAfter timed rounds, a lookup proposal long enough for a size + /// that has fewer than kExploreN samples in the current context bucket takes that size's window instead (the smallest such size), at + /// most kExplorePerSize times per size and kExploreBudget times in a stretch. The tokens of a learning stretch were never repeatable + /// (the windows follow the live costs); a window's size can change the batch the verifier runs, and with it the tokens. A size that + /// no proposal ever reaches keeps its filled-in cost (CostLearner::table). + static constexpr int kExploreAfter = 300; + static constexpr int kExploreN = 30; + static constexpr int kExplorePerSize = 40; + static constexpr int kExploreBudget = 150; + int forced_rounds() const { return forced_total_; } + /// Start the learning stretch again: the learner's samples and the forced-round counts. + void reset_learning(); + /// The largest allowed window size (the table is written up to it). + int top_size() const { return fit(max_t_); } /// How long the engine has been busy (seconds since its last pause of CostLearner::kIdleS), as the caller measures it, for the round /// observe() is about to be given; < 0 (the default): unknown. Only the learner reads it. void set_busy_age(double s) { busy_age_ = s; } @@ -226,6 +244,9 @@ private: bool fixed_ = false; // set_fixed_costs: no round time changes a cost bool learning_ = false; // set_learning: round times also go to learner_ double busy_age_ = -1.0; // set_busy_age + int explore_size(int lookup_k) const; // the size a learning stretch measures next, 0 = none (choose() counts it) + mutable int forced_total_ = 0; // windows taken for their size's sake, this stretch + mutable std::array forced_{}; // ... by size CostLearner learner_; double clamp_sample(int t, double ms) const; static constexpr int kPBuckets = 8; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 53e2460cbc..7578c0b38b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -20021,12 +20021,12 @@ int main(int argc, char** argv) { const strata::spec::CostLearner::Verdict v = policy.learner().check(kDraftCostRounds, kDraftCostMinN); if (v.ready && v.disturbed) { std::fprintf(stderr, "strata serve: draft costs: the learning stretch looks disturbed (%s): it is learned again\n", v.why.c_str()); - policy.learner().reset(); + policy.reset_learning(); } else if (v.ready) { strata::spec::CostFile cf; cf.key = dc_key; for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k) - cf.tables[(size_t) k] = policy.learner().table(k, kDraftCostMinN); + cf.tables[(size_t) k] = policy.learner().table(k, kDraftCostMinN, policy.top_size()); // the CPU prompt share, when it is on and balancing from measured times: its balance as measured so far, to a 0.05 // step (0.5 when no short prompt has measured it yet: on an RTX A6000 a fixed 0.5 read a 981-token chunk as fast as the // balancing share, 1,001-1,009 against 995-997 ms); fixed from now on like the table @@ -20046,7 +20046,7 @@ int main(int argc, char** argv) { if (!cf.tables[(size_t) k].empty()) policy.set_fixed_costs(cf.tables[(size_t) k].data(), (int) cf.tables[(size_t) k].size(), k); policy.set_learning(false); - policy.learner().reset(); + policy.reset_learning(); dc_learning = false; std::string t0; char b[24]; diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 84973c4daa..99c10b4dd5 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -125,13 +125,13 @@ int CostLearner::samples(int bucket, int t) const { return (int) s_[(size_t) bucket][(size_t) t].size(); } -std::vector CostLearner::table(int bucket, int min_n) const { +std::vector CostLearner::table(int bucket, int min_n, int upto) const { std::vector out; if (bucket < 0 || bucket >= kCtxBuckets) return out; const std::array, kMaxT + 1> b = sets(bucket, !state_effect(bucket, min_n)); int top = 0; std::array got{}; - std::vector seen; + std::vector seen; // the measured sizes (min_n samples), ascending; a rough one (kWeakN samples) joins when it is accepted below for (int t = 1; t <= kMaxT; ++t) { if (!b[(size_t) t].empty()) top = t; if ((int) b[(size_t) t].size() >= std::max(1, min_n)) { @@ -140,23 +140,40 @@ std::vector CostLearner::table(int bucket, int min_n) const { } } if (top == 0 || seen.empty()) return out; - for (int t = 1; t <= top; ++t) { - if (got[(size_t) t] > 0.0) { - out.push_back(got[(size_t) t]); - continue; - } + top = std::max(top, std::min(upto, kMaxT)); + // the cost of an unmeasured size from the measured ones: linear between two, the prior shape below them, above them the straight line with the + // steeper of the last segment's slope and the slope over all measured sizes (never flatter than the measured trend) + const auto fill = [&](int t) { int lo = 0, hi = 0; for (const int u : seen) { if (u < t) lo = u; if (u > t && hi == 0) hi = u; } - if (lo > 0 && hi > 0) out.push_back(got[(size_t) lo] + (got[(size_t) hi] - got[(size_t) lo]) * (t - lo) / (double) (hi - lo)); - else if (hi > 0) out.push_back(got[(size_t) hi] * kShape[t] / kShape[hi]); // below every measured size: the prior shape - else if (seen.size() >= 2) { // above them: the straight line through the two largest measured sizes (a size with a few samples is not trusted) - const int u2 = seen[seen.size() - 1], u1 = seen[seen.size() - 2]; - const double slope = std::max(0.0, (got[(size_t) u2] - got[(size_t) u1]) / (double) (u2 - u1)); - out.push_back(got[(size_t) u2] + slope * (t - u2)); - } else out.push_back(got[(size_t) lo] * kShape[t] / kShape[lo]); + if (lo > 0 && hi > 0) return got[(size_t) lo] + (got[(size_t) hi] - got[(size_t) lo]) * (t - lo) / (double) (hi - lo); + if (hi > 0) return got[(size_t) hi] * kShape[t] / kShape[hi]; + if (seen.size() < 2) return got[(size_t) lo] * kShape[t] / kShape[lo]; + const int u2 = seen.back(), u1 = seen[seen.size() - 2], u0 = seen.front(); + const double slope = std::max({0.0, (got[(size_t) u2] - got[(size_t) u1]) / (double) (u2 - u1), (got[(size_t) u2] - got[(size_t) u0]) / (double) (u2 - u0)}); + return got[(size_t) u2] + slope * (t - u2); + }; + for (int t = 1; t <= top; ++t) { + if (got[(size_t) t] > 0.0) { + out.push_back(got[(size_t) t]); + continue; + } + double v = fill(t); + const int n = (int) b[(size_t) t].size(); + if (n >= kWeakN) { // a few rounds: their median counts when it is not below the trend and not far above it (a stalled handful does not) + std::vector s = b[(size_t) t]; + std::sort(s.begin(), s.end()); + const double med = n % 2 ? (double) s[(size_t) n / 2] : 0.5 * ((double) s[(size_t) n / 2 - 1] + (double) s[(size_t) n / 2]); + if (med >= v && med <= kWeakMax * v) { + v = med; + got[(size_t) t] = med; + seen.insert(std::upper_bound(seen.begin(), seen.end(), t), t); + } + } + out.push_back(v); } for (size_t i = 1; i < out.size(); ++i) out[i] = std::max(out[i], out[i - 1]); // more rows never cost less return out; @@ -445,6 +462,14 @@ DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const Pick p; p.t = std::clamp(t_mtp, 1, max_t_); if (lookup_k <= 0) return p; + if (learning_ && !fixed_) { // a learning stretch measures the sizes it has too few rounds of, when a proposal is long enough for one + const int s = explore_size(lookup_k); + if (s > 0) { + p.lookup = true; + p.t = s; + return p; + } + } const double base = mtp_tokens(p.t) / cost_ms(p.t); const double q = lookup_rate(match); double e = 1.0, qi = 1.0, best = 0.0; @@ -473,6 +498,23 @@ DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const return p; } +int DraftPolicy::explore_size(int lookup_k) const { + if (learner_.rounds() + learner_.late_rounds() < kExploreAfter || forced_total_ >= kExploreBudget) return 0; + for (int s = 2; s <= std::min(lookup_k + 1, max_t_); ++s) { + if (!allowed(s) || forced_[(size_t) s] >= kExplorePerSize || learner_.samples(bk_, s) >= kExploreN) continue; + ++forced_[(size_t) s]; + ++forced_total_; + return s; + } + return 0; +} + +void DraftPolicy::reset_learning() { + learner_.reset(); + forced_total_ = 0; + forced_.fill(0); +} + void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) { t = std::clamp(t, 1, kMaxT); if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_); diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index dba0b1053c..624f3d89b8 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -419,6 +419,83 @@ int main() { "file: the next write replaces the leftover temporary file and the table loads"); fs::remove_all(dir, ec); } + { + // sizes with too few samples: a rough measurement counts when it is not below the trend, a stalled handful does not, and a fill above the + // measured sizes never flattens the measured trend (Radeon 780M, 11-13: sizes 1 / 3 measured at 76.2 / 111.6 ms, size 4 with 6 rounds at 143) + using strata::spec::CostLearner; + const auto fill = [](CostLearner& L, int t, int n, double ms) { + for (int i = 0; i < n; ++i) L.add(0, t, ms * (1.0 + 0.004 * ((i % 5) - 2))); + }; + CostLearner R; + fill(R, 1, 1279, 76.2); fill(R, 2, 2, 97.0); fill(R, 3, 126, 111.6); fill(R, 4, 6, 143.0); + const std::vector t = R.table(0, 20); + check(t.size() == 4 && std::fabs(t[3] - 143.0) < 0.5, "sizes: 6 rounds of 4 rows (143 ms, above the line's 129) count by their median"); + check(t.size() == 4 && std::fabs(t[1] - (76.2 + 111.6) / 2.0) < 0.2, "sizes: 2 rounds of 2 rows are filled in linearly"); + const std::vector u = R.table(0, 20, 6); + bool mono = u.size() == 6; + for (size_t i = 1; i < u.size(); ++i) mono &= u[i] >= u[i - 1]; + check(u.size() == 6 && mono && u[4] >= 143.0 + 0.9 * (143.0 - 111.6) && u[5] > u[4], "sizes: 5 and 6 rows continue the steeper measured slope (32 ms a row), not the first segment's 18"); + CostLearner S; + fill(S, 1, 600, 12.5); fill(S, 2, 400, 14.2); fill(S, 3, 700, 16.2); fill(S, 4, 6, 99.0); + const std::vector s = S.table(0, 20); + check(s.size() == 4 && std::fabs(s[3] - 18.2) < 0.05, "sizes: a handful of rounds 5x above the trend (a stall) is not a measurement"); + CostLearner Q; // costs 10 / 20 / 35: the fill goes on at 15 ms a row, not at 10 + fill(Q, 1, 100, 10.0); fill(Q, 2, 100, 20.0); fill(Q, 3, 100, 35.0); + const std::vector q = Q.table(0, 20, 5); + check(q.size() == 5 && q[3] >= 35.0 + 15.0 - 0.1 && q[4] >= 35.0 + 30.0 - 0.1, "sizes: a size above the measured ones never costs less than the last slope says"); + check(Q.table(0, 20, 3).size() == 3 && Q.table(1, 20, 5).empty(), "sizes: upto adds nothing below the largest size seen, and an empty bucket stays empty"); + // the learning stretch measures the sizes it has too few rounds of + const auto feed = [](DraftPolicy& p, int n) { + for (int i = 0; i < n; ++i) { p.observe(false, 1, 0, 0, 76.0); if (i % 4 == 0) p.observe(false, 3, 2, 0, 111.0); } + }; + DraftPolicy y(8); + y.set_learning(true); + feed(y, 100); + y.choose(1, 5, 3); + check(y.forced_rounds() == 0, "explore: nothing is forced in the first rounds of a stretch"); + feed(y, 300); + const DraftPolicy::Pick f1 = y.choose(1, 5, 3); + check(f1.lookup && f1.t == 2 && y.forced_rounds() == 1, "explore: after the first rounds the smallest size with few samples is taken, if a proposal reaches it"); + const DraftPolicy::Pick f2 = y.choose(1, 1, 3); + check(y.forced_rounds() == 2 && f2.lookup && f2.t == 2, "explore: a proposal of one draft reaches 2 rows only"); + int per[DraftPolicy::kMaxT + 1] = {}; + for (int i = 0; i < 700; ++i) { + const DraftPolicy::Pick pk = y.choose(1, 7, 3); + per[pk.t] += pk.lookup ? 1 : 0; + y.observe(pk.lookup, pk.t, pk.t > 1 ? pk.t - 1 : 0, 3, 76.0 + 17.0 * (pk.t - 1)); + } + int worst = 0; + for (int i = 2; i <= 8; ++i) worst = std::max(worst, per[i]); + check(y.forced_rounds() == DraftPolicy::kExploreBudget, "explore: the forced rounds stop at the stretch's budget"); + const int before = y.forced_rounds(); + for (int i = 0; i < 50; ++i) y.choose(1, 7, 3); + check(y.forced_rounds() == before, "explore: nothing is forced once the budget is spent"); + DraftPolicy z(8); // the cap per size: with a budget left over, one size is still not forced more than kExplorePerSize times + z.set_learning(true); + feed(z, 400); + z.set_busy_age(100.0); // every round of size 2 lands in the late set: no fresh sample ever arrives + for (int i = 0; i < 200; ++i) { const DraftPolicy::Pick pk = z.choose(1, 1, 3); z.observe(pk.lookup, pk.t, 0, 3, 95.0); } + check(z.forced_rounds() == DraftPolicy::kExplorePerSize, "explore: a size is forced at most kExplorePerSize times"); + z.reset_learning(); + check(z.forced_rounds() == 0 && z.learner().rounds() == 0, "explore: a new stretch starts with a new budget"); + DraftPolicy n(8); // not learning, or fixed: the policy never takes a window for its size's sake + feed(n, 400); + n.choose(1, 5, 3); + DraftPolicy x(8); + x.set_learning(true); + feed(x, 400); + const double ms[3] = {76.0, 95.0, 111.0}; + x.set_fixed_costs(ms, 3); + for (int i = 0; i < 20; ++i) x.choose(1, 5, 3); + check(n.forced_rounds() == 0 && x.forced_rounds() == 0, "explore: not while learning is off, and not once the costs are fixed"); + DraftPolicy w(8); // a size no proposal reaches stays filled in + w.set_learning(true); + feed(w, 600); + for (int i = 0; i < 100; ++i) { const DraftPolicy::Pick pk = w.choose(1, 1, 3); w.observe(pk.lookup, pk.t, 1, 3, 95.0); } + const std::vector wt = w.learner().table(0, 20, 6); + check(w.learner().samples(0, 4) == 0 && wt.size() == 6 && wt[3] > wt[2] && wt[5] > wt[3], "explore: a size no proposal reaches is filled in above the measured ones"); + (void) worst; + } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; } From c43347d0945ae1fbebbfcb43e332d54989d9c272 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 02:25:47 +0100 Subject: [PATCH 03/17] spec: a learning stretch times window sizes past its proposals with filler rows Sizes 5 and 6 of the Radeon 780M and 4 and 5 of the M5 Max were never reached by a lookup proposal in a prose learning stretch, so their table entries were filled in (780M: 174.9 and 206.1 ms against 160 and 178 measured by live costs; the lookup of 5 rows was then priced out and the frozen table lost 1.9-2.5 % on code and JSON to live costs). - choose() takes pad_cap: during learning, when the caller allows it (a deterministic proposal, never a probabilistic window), the window of the smallest size with under 30 samples is run even when the proposal is shorter; the rows past the proposal repeat its last token, which the verifier rejects. Pick::pad says how many rows are filler. - A window run this way goes to the learner and to the cost of its size (observe_forced) and to no lookup or MTP statistic. - The forced-round budget is 200 per stretch (40 per size). - Unit test draft_policy_test: 108 of 108 (5 new: padded window, filler count, forced round feeds no statistic, pad_cap of one draft). --- include/strata/spec/draft_policy.hpp | 17 +++++++++++------ src/program/generate.cpp | 17 ++++++++++++++--- src/spec/draft_policy.cpp | 22 ++++++++++++++++++---- src/spec/draft_policy_test.cpp | 16 ++++++++++++++++ 4 files changed, 59 insertions(+), 13 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index a958803a38..cfbf2dcbc4 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -128,11 +128,16 @@ public: struct Pick { bool lookup = false; int t = 1; // window size (1 + drafts) + int pad = 0; // a learning stretch's window longer than the proposal: this many rows past it are filler (the caller fills them) }; /// `t_mtp`: the MTP's window; `lookup_k`: the lookup proposal's length (0 = none); `match`: its match length. - Pick choose(int t_mtp, int lookup_k, int match) const; + /// pad_cap > 0 (learning, a deterministic proposal): a window may be longer than the proposal, up to pad_cap drafts, its extra rows filler + /// that the verifier will most likely reject; only a learning stretch asks for one (see explore below). + Pick choose(int t_mtp, int lookup_k, int match, int pad_cap = 0) const; /// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft). void observe(bool lookup, int t, int accepted, int match, double round_ms); + /// The round of a window run for its size's sake (Pick::pad > 0): its time goes to the learner and the cost of that size, its outcome to no statistic. + void observe_forced(int t, double round_ms); /// Gated proposals, inside one generation: a round's committed outcome only, never its time. `t` is the /// lookup window chosen before the draws, or the configured MTP window; both are fixed by the history. A /// lookup window counts as a probe of its size, so a size whose cost is still guessed is tried kProbes times, @@ -179,15 +184,15 @@ public: /// Learning a fixed table: every timed round also goes to learner() (raw round time, in its context bucket). Off by default. void set_learning(bool on) { learning_ = on; } bool learning() const { return learning_; } - /// Measuring the sizes the policy can pick (learning only): after kExploreAfter timed rounds, a lookup proposal long enough for a size - /// that has fewer than kExploreN samples in the current context bucket takes that size's window instead (the smallest such size), at - /// most kExplorePerSize times per size and kExploreBudget times in a stretch. The tokens of a learning stretch were never repeatable + /// Measuring the sizes the policy can pick (learning only): after kExploreAfter timed rounds, a lookup proposal (padded with filler rows up to + /// pad_cap when the caller allows it, else long enough as it is) takes the window of a size that has fewer than kExploreN samples in the + /// current context bucket instead (the smallest such size), at most kExplorePerSize times per size and kExploreBudget times in a stretch. The tokens of a learning stretch were never repeatable /// (the windows follow the live costs); a window's size can change the batch the verifier runs, and with it the tokens. A size that /// no proposal ever reaches keeps its filled-in cost (CostLearner::table). static constexpr int kExploreAfter = 300; static constexpr int kExploreN = 30; static constexpr int kExplorePerSize = 40; - static constexpr int kExploreBudget = 150; + static constexpr int kExploreBudget = 200; int forced_rounds() const { return forced_total_; } /// Start the learning stretch again: the learner's samples and the forced-round counts. void reset_learning(); @@ -244,7 +249,7 @@ private: bool fixed_ = false; // set_fixed_costs: no round time changes a cost bool learning_ = false; // set_learning: round times also go to learner_ double busy_age_ = -1.0; // set_busy_age - int explore_size(int lookup_k) const; // the size a learning stretch measures next, 0 = none (choose() counts it) + int explore_size(int lookup_k, int pad_cap) const; // the size a learning stretch measures next, 0 = none (choose() counts it) mutable int forced_total_ = 0; // windows taken for their size's sake, this stretch mutable std::array forced_{}; // ... by size CostLearner learner_; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7578c0b38b..33a2f7efb1 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -19485,6 +19485,7 @@ int main(int argc, char** argv) { policy.set_context(p); const bool merged = first_window && merge_T > 0; // the prompt's last tokens and the first token bool from_sfx = false; + int sfx_pad = 0; // a learning stretch's lookup window longer than the proposal: the filler rows (DraftPolicy::Pick::pad) int sfx_match = 0; bool dfr_lookup = false; int dfr_T = 0, dfr_match = 0; @@ -19540,9 +19541,17 @@ int main(int argc, char** argv) { // chooses, and the lookup is taken without asking whether the MTP's first guess agrees const bool probabilistic = use_mtp && !req_df2 && mtp.prob(); // DFlash2's candidates are not draws from the MTP's q if (k > 0 && (probabilistic || !draft_on || sbuf[0] == drafts[0])) { + // a learning stretch may run a longer window than the proposal to time that size: the extra rows repeat the proposal's last + // token, which the verifier rejects (a deterministic proposal only: a probabilistic window keeps its own draws) const strata::spec::DraftPolicy::Pick pk = probabilistic - ? source_policy.choose(S_mtp, k, sfx_match) : policy.choose(T, k, sfx_match); - if (pk.lookup && !trace_nopick) { T = pk.t; from_sfx = true; } + ? source_policy.choose(S_mtp, k, sfx_match) : policy.choose(T, k, sfx_match, dc_learning ? S_look - 1 : 0); + if (pk.lookup && !trace_nopick && pk.t - 1 <= (int) sbuf.size()) { + T = pk.t; from_sfx = true; + if (pk.pad > 0) { + sfx_pad = pk.pad; + for (int i = k; i < k + pk.pad; ++i) sbuf[(size_t) i] = sbuf[(size_t) k - 1]; + } + } if (pk.lookup && !trace_nopick && o.lookup_max_t > 0) { // --lookup-max-t: a size whose window graph fits const int t = graph_fits(T); if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; } @@ -19987,7 +19996,9 @@ int main(int argc, char** argv) { } if (spec_cost && use_mtp && timed_round && !from_sfx) policy.observe_probs(dwin_s.data(), T_mtp - 1, a); if (dc_learning) policy.set_busy_age(std::chrono::duration(Clock::now() - dc_busy_since).count()); - if (timed_round && !eos && chain_n == 0) + if (timed_round && !eos && chain_n == 0 && sfx_pad > 0 && from_sfx) // a window run for its size's sake: its time only + policy.observe_forced(T, std::chrono::duration(Clock::now() - round0).count()); + else if (timed_round && !eos && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, std::chrono::duration(Clock::now() - round0).count()); else if (timed_round && !eos) // a chained window: its MTP part, its chain, its cost diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 99c10b4dd5..7c1b92f4a3 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -458,15 +458,16 @@ double DraftPolicy::mtp_tokens(int t) const { return 1.0 + 0.7 * (t - 1); // before any MTP window of this size: a typical acceptance } -DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const { +DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match, int pad_cap) const { Pick p; p.t = std::clamp(t_mtp, 1, max_t_); if (lookup_k <= 0) return p; if (learning_ && !fixed_) { // a learning stretch measures the sizes it has too few rounds of, when a proposal is long enough for one - const int s = explore_size(lookup_k); + const int s = explore_size(lookup_k, pad_cap); if (s > 0) { p.lookup = true; p.t = s; + p.pad = std::max(0, s - 1 - lookup_k); return p; } } @@ -498,9 +499,9 @@ DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const return p; } -int DraftPolicy::explore_size(int lookup_k) const { +int DraftPolicy::explore_size(int lookup_k, int pad_cap) const { if (learner_.rounds() + learner_.late_rounds() < kExploreAfter || forced_total_ >= kExploreBudget) return 0; - for (int s = 2; s <= std::min(lookup_k + 1, max_t_); ++s) { + for (int s = 2; s <= std::min(std::max(lookup_k, pad_cap) + 1, max_t_); ++s) { if (!allowed(s) || forced_[(size_t) s] >= kExplorePerSize || learner_.samples(bk_, s) >= kExploreN) continue; ++forced_[(size_t) s]; ++forced_total_; @@ -509,6 +510,19 @@ int DraftPolicy::explore_size(int lookup_k) const { return 0; } +void DraftPolicy::observe_forced(int t, double round_ms) { + t = std::clamp(t, 1, kMaxT); + if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_); + if (round_ms > 0 && !fixed_) { + round_ms = clamp_sample(t, round_ms); + const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha; + cost_[bk_][t] = cost_n_[bk_][t] > 0 ? (1.0 - alpha) * cost_[bk_][t] + alpha * round_ms : round_ms; + cost_n_[bk_][t] += 1.0; + last_[bk_][t] = rounds_; + } + rounds_ += 1.0; +} + void DraftPolicy::reset_learning() { learner_.reset(); forced_total_ = 0; diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 624f3d89b8..f0a9e62dbb 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -458,6 +458,7 @@ int main() { check(f1.lookup && f1.t == 2 && y.forced_rounds() == 1, "explore: after the first rounds the smallest size with few samples is taken, if a proposal reaches it"); const DraftPolicy::Pick f2 = y.choose(1, 1, 3); check(y.forced_rounds() == 2 && f2.lookup && f2.t == 2, "explore: a proposal of one draft reaches 2 rows only"); + y.set_busy_age(100.0); // late rounds: no size gets a fresh sample, so the per-size cap (40) and then the budget end the forcing int per[DraftPolicy::kMaxT + 1] = {}; for (int i = 0; i < 700; ++i) { const DraftPolicy::Pick pk = y.choose(1, 7, 3); @@ -495,6 +496,21 @@ int main() { const std::vector wt = w.learner().table(0, 20, 6); check(w.learner().samples(0, 4) == 0 && wt.size() == 6 && wt[3] > wt[2] && wt[5] > wt[3], "explore: a size no proposal reaches is filled in above the measured ones"); (void) worst; + // a padded window: a short proposal, a size past it that has no samples, the caller allows filler rows + DraftPolicy g(8); + g.set_learning(true); + feed(g, 400); + for (int i = 0; i < 40; ++i) g.observe_forced(2, 95.0); // size 2 measured (3 is fed already) + const DraftPolicy::Pick np = g.choose(1, 1, 3); + check(g.forced_rounds() == 0 || !np.lookup || np.pad == 0, "pad: without pad_cap a proposal of one draft never makes a longer window"); + const DraftPolicy::Pick gp = g.choose(1, 1, 3, 7); + check(gp.lookup && gp.t == 4 && gp.pad == 2 && g.forced_rounds() == 1, "pad: with pad_cap the smallest unmeasured size is run, 2 filler rows past the proposal"); + const double q0 = g.lookup_rate(3); + for (int i = 0; i < 30; ++i) g.observe_forced(4, 143.0); + check(g.lookup_rate(3) == q0 && g.learner().samples(0, 4) == 30, "pad: a forced round feeds the learner and no lookup statistic"); + const DraftPolicy::Pick g5 = g.choose(1, 1, 3, 7); + check(g5.lookup && g5.t == 5 && g5.pad == 3, "pad: the next unmeasured size follows once one has its samples"); + check(g.choose(1, 1, 3, 1).pad == 0, "pad: a pad_cap of one draft makes no filler"); } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; From bcbaf72dd489fc6617015c02a2376384c294dce8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 02:33:20 +0100 Subject: [PATCH 04/17] spec: a learning stretch times window sizes in the rounds where they count, on every round On the M5 Max the learning burst is one busy run, so only its first 6 seconds (about 375 rounds) are fresh rounds, and the sizes the table is made of must be measured there. The forced rounds of the previous commit started after 300 rounds (after the fresh seconds) and needed a lookup proposal: sizes 4 and 5 reached 68 and 95 rounds in the whole burst but under 20 fresh ones, so the table still filled them (12.651, 14.315, 16.398, 18.481, 20.564). - A round with no lookup and no chain may run its MTP / drafter window at another size (DraftPolicy::explore_window): the smallest size under 30 usable samples, not the size the round already has, up to the widest window; rows past the real drafts are whatever the drafts array holds (valid ids, rejected by the verifier). Deterministic windows only (not a probabilistic MTP window, not a gated proposal), learning only. - Forced rounds start after 100 rounds and happen only while they count: in the first 6 seconds of a busy run, or when the stretch has shown no state effect (size with 20 fresh and 20 late samples agreeing within 2 %); a stretch with only late rounds so far does not force. - A forced round goes to the learner and the size's cost and to no MTP / lookup / probability statistic (observe_forced; observe_probs skipped). - Usable samples = fresh ones with a state effect, fresh + late otherwise (CostLearner::usable, state_known). - Budget 300 forced rounds per stretch, 40 per size. - Unit test draft_policy_test: 116 of 116. --- include/strata/spec/draft_policy.hpp | 14 ++++++- src/program/generate.cpp | 14 +++++-- src/spec/draft_policy.cpp | 38 ++++++++++++++++-- src/spec/draft_policy_test.cpp | 60 ++++++++++++++++++++-------- 4 files changed, 101 insertions(+), 25 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index cfbf2dcbc4..706d13c517 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -62,6 +62,10 @@ public: int samples(int bucket, int t) const; ///< fresh samples of a size /// A state effect in `bucket`: some size has at least `min_n` fresh and `min_n` late samples and their trimmed means differ by more than kStateTol. bool state_effect(int bucket, int min_n) const; + /// Some size of `bucket` has at least `min_n` fresh and `min_n` late samples: state_effect() says something (a fresh-only machine is told apart from one without effect). + bool state_known(int bucket, int min_n) const; + /// The samples of size `t` that table() would use now: the fresh ones when there is a state effect, fresh + late otherwise. + int usable(int bucket, int t, int min_n) const; /// The table of `bucket` for windows 1..n (n = the largest size seen in that bucket, or `upto` when that is larger; empty when the bucket has none): /// the trimmed mean (the lowest and highest kTrim share dropped) of each size with at least `min_n` samples; a size with kWeakN to min_n - 1 /// samples counts with its median when that is within [fill, kWeakMax x fill] (a rough measurement, never below the trend); a size in between two measured ones is linear in the size; a size above the @@ -189,11 +193,15 @@ public: /// current context bucket instead (the smallest such size), at most kExplorePerSize times per size and kExploreBudget times in a stretch. The tokens of a learning stretch were never repeatable /// (the windows follow the live costs); a window's size can change the batch the verifier runs, and with it the tokens. A size that /// no proposal ever reaches keeps its filled-in cost (CostLearner::table). - static constexpr int kExploreAfter = 300; + static constexpr int kExploreAfter = 100; static constexpr int kExploreN = 30; static constexpr int kExplorePerSize = 40; - static constexpr int kExploreBudget = 200; + static constexpr int kExploreBudget = 300; int forced_rounds() const { return forced_total_; } + /// The MTP / drafter window of a round that the caller has just decided (`t` rows, at most `cap` rows possible): the size to run instead when + /// a learning stretch wants to time one (rows past the drafts are the caller's filler), else 0. Same limits as for a lookup window. Forced + /// rounds happen only while they count: in the first kFreshS seconds of a busy run, or when the stretch has shown no state effect. + int explore_window(int t, int cap) const; /// Start the learning stretch again: the learner's samples and the forced-round counts. void reset_learning(); /// The largest allowed window size (the table is written up to it). @@ -250,6 +258,8 @@ private: bool learning_ = false; // set_learning: round times also go to learner_ double busy_age_ = -1.0; // set_busy_age int explore_size(int lookup_k, int pad_cap) const; // the size a learning stretch measures next, 0 = none (choose() counts it) + int explore_next(int reach, int skip) const; // the smallest size 2..reach (not `skip`) that still needs rounds; counts it; 0 = none + bool explore_ok() const; // a forced round counts now (fresh phase, or no state effect) mutable int forced_total_ = 0; // windows taken for their size's sake, this stretch mutable std::array forced_{}; // ... by size CostLearner learner_; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 33a2f7efb1..fbf5a9fb17 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -19591,6 +19591,14 @@ int main(int argc, char** argv) { chain_n = std::max(0, t - T); } } + // a learning stretch times the window sizes the round's own rule does not reach: the MTP / drafter window of a round with no lookup and no + // chain is run at another size (the rows past the real drafts are whatever the drafts array holds: valid ids that the verifier rejects); + // a deterministic window only, and only the learning stretch (DraftPolicy::explore_window) + bool win_forced = false; + if (dc_learning && draft_on && !first_window && !merged && !from_sfx && chain_n == 0 && !gated_proposal && !(use_mtp && !req_df2 && mtp.prob())) { + const int sx = policy.explore_window(T, std::min(S_mtp, (int) drafts.size() + 1)); + if (sx > 0 && p + sx <= o.max_context) { T = sx; win_forced = true; } + } const int T_mtp = T; T += chain_n; const bool timed_round = !first_window; @@ -19994,9 +20002,9 @@ int main(int argc, char** argv) { std::fprintf(df2_trace, "\n"); tr_k = 0; } - if (spec_cost && use_mtp && timed_round && !from_sfx) policy.observe_probs(dwin_s.data(), T_mtp - 1, a); + if (spec_cost && use_mtp && timed_round && !from_sfx && !win_forced) policy.observe_probs(dwin_s.data(), T_mtp - 1, a); if (dc_learning) policy.set_busy_age(std::chrono::duration(Clock::now() - dc_busy_since).count()); - if (timed_round && !eos && chain_n == 0 && sfx_pad > 0 && from_sfx) // a window run for its size's sake: its time only + if (timed_round && !eos && chain_n == 0 && ((sfx_pad > 0 && from_sfx) || win_forced)) // a window run for its size's sake: its time only policy.observe_forced(T, std::chrono::duration(Clock::now() - round0).count()); else if (timed_round && !eos && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, @@ -21836,7 +21844,7 @@ int main(int argc, char** argv) { t_cycle_ms[(size_t) T] += round_ms; ++t_cycle_n[(size_t) T]; } - if (spec_cost && use_mtp && timed_round && !from_sfx) policy.observe_probs(dwin.data(), T_mtp - 1, a); + if (spec_cost && use_mtp && timed_round && !from_sfx && !win_forced) policy.observe_probs(dwin.data(), T_mtp - 1, a); if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms); else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms); if (rounds % 64 == 0) diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 7c1b92f4a3..647eb3c739 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -120,6 +120,21 @@ std::array, CostLearner::kMaxT + 1> CostLearner::sets(int buc return out; } +bool CostLearner::state_known(int bucket, int min_n) const { + if (bucket < 0 || bucket >= kCtxBuckets) return false; + const int need = std::max(1, min_n); + for (int t = 1; t <= kMaxT; ++t) + if ((int) s_[(size_t) bucket][(size_t) t].size() >= need && (int) late_s_[(size_t) bucket][(size_t) t].size() >= need) return true; + return false; +} + +int CostLearner::usable(int bucket, int t, int min_n) const { + if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > kMaxT) return 0; + int n = (int) s_[(size_t) bucket][(size_t) t].size(); + if (!state_effect(bucket, min_n)) n += (int) late_s_[(size_t) bucket][(size_t) t].size(); + return n; +} + int CostLearner::samples(int bucket, int t) const { if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > kMaxT) return 0; return (int) s_[(size_t) bucket][(size_t) t].size(); @@ -499,10 +514,16 @@ DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match, int pa return p; } -int DraftPolicy::explore_size(int lookup_k, int pad_cap) const { - if (learner_.rounds() + learner_.late_rounds() < kExploreAfter || forced_total_ >= kExploreBudget) return 0; - for (int s = 2; s <= std::min(std::max(lookup_k, pad_cap) + 1, max_t_); ++s) { - if (!allowed(s) || forced_[(size_t) s] >= kExplorePerSize || learner_.samples(bk_, s) >= kExploreN) continue; +bool DraftPolicy::explore_ok() const { + const double age = busy_age_ < 0.0 ? 0.0 : busy_age_; + if (age <= CostLearner::kFreshS) return true; // a fresh round: it counts on every machine + return learner_.state_known(bk_, 20) && !learner_.state_effect(bk_, 20); // a late round counts only where the stretch has shown no state effect +} + +int DraftPolicy::explore_next(int reach, int skip) const { + if (learner_.rounds() + learner_.late_rounds() < kExploreAfter || forced_total_ >= kExploreBudget || !explore_ok()) return 0; + for (int s = 2; s <= std::min(reach, max_t_); ++s) { + if (s == skip || !allowed(s) || forced_[(size_t) s] >= kExplorePerSize || learner_.usable(bk_, s, 20) >= kExploreN) continue; ++forced_[(size_t) s]; ++forced_total_; return s; @@ -510,6 +531,15 @@ int DraftPolicy::explore_size(int lookup_k, int pad_cap) const { return 0; } +int DraftPolicy::explore_size(int lookup_k, int pad_cap) const { + return explore_next(std::max(lookup_k, pad_cap) + 1, 0); +} + +int DraftPolicy::explore_window(int t, int cap) const { + if (!learning_ || fixed_) return 0; + return explore_next(cap, t); +} + void DraftPolicy::observe_forced(int t, double round_ms) { t = std::clamp(t, 1, kMaxT); if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_); diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index f0a9e62dbb..61fb30e2a4 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -450,7 +450,7 @@ int main() { }; DraftPolicy y(8); y.set_learning(true); - feed(y, 100); + feed(y, 40); y.choose(1, 5, 3); check(y.forced_rounds() == 0, "explore: nothing is forced in the first rounds of a stretch"); feed(y, 300); @@ -458,24 +458,21 @@ int main() { check(f1.lookup && f1.t == 2 && y.forced_rounds() == 1, "explore: after the first rounds the smallest size with few samples is taken, if a proposal reaches it"); const DraftPolicy::Pick f2 = y.choose(1, 1, 3); check(y.forced_rounds() == 2 && f2.lookup && f2.t == 2, "explore: a proposal of one draft reaches 2 rows only"); - y.set_busy_age(100.0); // late rounds: no size gets a fresh sample, so the per-size cap (40) and then the budget end the forcing - int per[DraftPolicy::kMaxT + 1] = {}; - for (int i = 0; i < 700; ++i) { - const DraftPolicy::Pick pk = y.choose(1, 7, 3); - per[pk.t] += pk.lookup ? 1 : 0; - y.observe(pk.lookup, pk.t, pk.t > 1 ? pk.t - 1 : 0, 3, 76.0 + 17.0 * (pk.t - 1)); + DraftPolicy y16(16); // the budget: 14 sizes that need 30 rounds each are more than the stretch's budget + y16.set_learning(true); + feed(y16, 400); + for (int i = 0; i < 1200; ++i) { + const DraftPolicy::Pick pk = y16.choose(1, 15, 3); + y16.observe(pk.lookup, pk.t, pk.t > 1 ? pk.t - 1 : 0, 3, 76.0 + 17.0 * (pk.t - 1)); } - int worst = 0; - for (int i = 2; i <= 8; ++i) worst = std::max(worst, per[i]); - check(y.forced_rounds() == DraftPolicy::kExploreBudget, "explore: the forced rounds stop at the stretch's budget"); - const int before = y.forced_rounds(); - for (int i = 0; i < 50; ++i) y.choose(1, 7, 3); - check(y.forced_rounds() == before, "explore: nothing is forced once the budget is spent"); + check(y16.forced_rounds() == DraftPolicy::kExploreBudget, "explore: the forced rounds stop at the stretch's budget"); + const int before = y16.forced_rounds(); + for (int i = 0; i < 50; ++i) y16.choose(1, 15, 3); + check(y16.forced_rounds() == before, "explore: nothing is forced once the budget is spent"); DraftPolicy z(8); // the cap per size: with a budget left over, one size is still not forced more than kExplorePerSize times z.set_learning(true); feed(z, 400); - z.set_busy_age(100.0); // every round of size 2 lands in the late set: no fresh sample ever arrives - for (int i = 0; i < 200; ++i) { const DraftPolicy::Pick pk = z.choose(1, 1, 3); z.observe(pk.lookup, pk.t, 0, 3, 95.0); } + for (int i = 0; i < 200; ++i) { const DraftPolicy::Pick pk = z.choose(1, 1, 3); z.observe(pk.lookup, pk.t, 0, 3, 0.0); } // no time, so no sample ever arrives check(z.forced_rounds() == DraftPolicy::kExplorePerSize, "explore: a size is forced at most kExplorePerSize times"); z.reset_learning(); check(z.forced_rounds() == 0 && z.learner().rounds() == 0, "explore: a new stretch starts with a new budget"); @@ -495,7 +492,38 @@ int main() { for (int i = 0; i < 100; ++i) { const DraftPolicy::Pick pk = w.choose(1, 1, 3); w.observe(pk.lookup, pk.t, 1, 3, 95.0); } const std::vector wt = w.learner().table(0, 20, 6); check(w.learner().samples(0, 4) == 0 && wt.size() == 6 && wt[3] > wt[2] && wt[5] > wt[3], "explore: a size no proposal reaches is filled in above the measured ones"); - (void) worst; + // the window of a round that has no proposal: any undersampled size up to the cap, but not the size it already is + DraftPolicy m(8); + m.set_learning(true); + feed(m, 400); + check(m.explore_window(3, 6) == 2 && m.forced_rounds() == 1, "window: the smallest unmeasured size is run, not the one the round already has"); + check(m.explore_window(2, 6) == 4, "window: a size with samples (3 rows) is skipped, the next unmeasured one is run"); + check(m.explore_window(1, 1) == 0, "window: a cap of one row leaves nothing to run"); + DraftPolicy m0(8); + feed(m0, 400); + check(m0.explore_window(3, 6) == 0, "window: nothing while learning is off"); + // a late round counts only where the stretch has shown no state effect + DraftPolicy e1(8); // fresh 76 ms, late 80 ms: a state effect + e1.set_learning(true); + e1.set_busy_age(2.0); + for (int i = 0; i < 60; ++i) e1.observe(false, 1, 0, 0, 76.0); + e1.set_busy_age(100.0); + for (int i = 0; i < 60; ++i) e1.observe(false, 1, 0, 0, 80.0); + check(e1.explore_window(3, 6) == 0, "gate: a late round is not forced when the stretch has a state effect"); + e1.set_busy_age(2.0); + check(e1.explore_window(3, 6) == 2, "gate: a fresh round is"); + DraftPolicy e2(8); // fresh and late alike: no state effect + e2.set_learning(true); + e2.set_busy_age(2.0); + for (int i = 0; i < 60; ++i) e2.observe(false, 1, 0, 0, 76.0); + e2.set_busy_age(100.0); + for (int i = 0; i < 60; ++i) e2.observe(false, 1, 0, 0, 76.2); + check(e2.explore_window(3, 6) == 2, "gate: a late round is forced when the stretch shows no state effect"); + DraftPolicy e3(8); // late rounds only so far: unknown, so not forced + e3.set_learning(true); + e3.set_busy_age(100.0); + for (int i = 0; i < 150; ++i) e3.observe(false, 1, 0, 0, 76.0); + check(e3.explore_window(3, 6) == 0, "gate: a late round is not forced while the stretch cannot tell yet"); // a padded window: a short proposal, a size past it that has no samples, the caller allows filler rows DraftPolicy g(8); g.set_learning(true); From f3ebb13687a8b5abb1129e877ce08ceeaa9503cd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 02:34:44 +0100 Subject: [PATCH 05/17] spec: restore the CLI loop's observe_probs line The previous commit also changed the CLI loop's observe_probs condition, but that loop has no forced-window variable, so the Metal build failed there. The line is back as it was; only the serve loop changes. --- src/program/generate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index fbf5a9fb17..c57ba23823 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -21844,7 +21844,7 @@ int main(int argc, char** argv) { t_cycle_ms[(size_t) T] += round_ms; ++t_cycle_n[(size_t) T]; } - if (spec_cost && use_mtp && timed_round && !from_sfx && !win_forced) policy.observe_probs(dwin.data(), T_mtp - 1, a); + if (spec_cost && use_mtp && timed_round && !from_sfx) policy.observe_probs(dwin.data(), T_mtp - 1, a); if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms); else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms); if (rounds % 64 == 0) From 5d26d6f4ba7c6460c7ce516ed4db90d409ffb891 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 02:41:31 +0100 Subject: [PATCH 06/17] spec: a learning stretch can time a lookup-type window in a round that has no proposal On the M5 Max the MTP window is at most 3 rows, so windows of 4 and 5 rows exist only as lookup windows, and a prose learning stretch has a lookup proposal in about 2 % of its rounds: with forcing limited to the first 6 seconds of a busy run (the rounds that count), sizes 4 and 5 got 11 and 31 rounds in the burst (table 12.808, 14.397, 16.526, 18.810, 21.094). - DraftPolicy::explore_lookup(cap): in a round with no lookup proposal, a learning stretch may run a lookup-type window of the smallest unmeasured size (2..cap rows); every row after the first is filler (the MTP's own first guess repeated, which the verifier rejects). Same limits as the other forced windows: from round 100, only while the rounds count, 40 per size, 300 per stretch, deterministic windows only, learning only. - Unit test draft_policy_test: 117 of 117. --- include/strata/spec/draft_policy.hpp | 2 ++ src/program/generate.cpp | 13 +++++++++++++ src/spec/draft_policy.cpp | 5 +++++ src/spec/draft_policy_test.cpp | 4 ++++ 4 files changed, 24 insertions(+) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index 706d13c517..0f5b655841 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -202,6 +202,8 @@ public: /// a learning stretch wants to time one (rows past the drafts are the caller's filler), else 0. Same limits as for a lookup window. Forced /// rounds happen only while they count: in the first kFreshS seconds of a busy run, or when the stretch has shown no state effect. int explore_window(int t, int cap) const; + /// A round with no lookup proposal: the size of a lookup-type window (2..cap rows, every row after the first filler) a learning stretch wants to time, else 0. + int explore_lookup(int cap) const; /// Start the learning stretch again: the learner's samples and the forced-round counts. void reset_learning(); /// The largest allowed window size (the table is written up to it). diff --git a/src/program/generate.cpp b/src/program/generate.cpp index c57ba23823..af20fd1ff4 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -19557,6 +19557,19 @@ int main(int argc, char** argv) { if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; } T = t; } + } else if (k == 0 && dc_learning && draft_on && !probabilistic && !trace_nopick) { + // no proposal at all: a learning stretch may still time a lookup-type window size (every row after the first is filler, + // the MTP's own first guess repeated; the verifier rejects them), so that sizes only lookups reach get measured + const int s = policy.explore_lookup(std::min(S_look, (int) sbuf.size() + 1)); + if (s > 0) { + T = s; from_sfx = true; sfx_pad = s - 1; sfx_match = 0; + for (int i = 0; i < s - 1; ++i) sbuf[(size_t) i] = drafts[0]; + if (o.lookup_max_t > 0) { // --lookup-max-t: a size whose window graph fits + const int t = graph_fits(T); + if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; } + T = t; + } + } } } } diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 647eb3c739..5c814bb46e 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -535,6 +535,11 @@ int DraftPolicy::explore_size(int lookup_k, int pad_cap) const { return explore_next(std::max(lookup_k, pad_cap) + 1, 0); } +int DraftPolicy::explore_lookup(int cap) const { + if (!learning_ || fixed_) return 0; + return explore_next(cap, 0); +} + int DraftPolicy::explore_window(int t, int cap) const { if (!learning_ || fixed_) return 0; return explore_next(cap, t); diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 61fb30e2a4..c2a6062a75 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -502,6 +502,10 @@ int main() { DraftPolicy m0(8); feed(m0, 400); check(m0.explore_window(3, 6) == 0, "window: nothing while learning is off"); + DraftPolicy lk(8); // a round with no proposal at all: a lookup-type window of an unmeasured size + lk.set_learning(true); + feed(lk, 400); + check(lk.explore_lookup(5) == 2 && lk.explore_lookup(1) == 0 && m0.explore_lookup(5) == 0, "window: a round without a proposal can time a lookup-type size, only while learning"); // a late round counts only where the stretch has shown no state effect DraftPolicy e1(8); // fresh 76 ms, late 80 ms: a state effect e1.set_learning(true); From c3a861156d6f93e59a3dfc241b4a472918202a88 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 03:54:17 +0100 Subject: [PATCH 07/17] spec: a fixed draft-cost table is calibrated against real rounds, size by size The learned costs come from a learning stretch (forced windows with filler rows, a burst of prose). On an M5 Max a real round of 2, 3 and 5 rows costs about 2 % more, which flips a close choice between a 4 and a 5 row lookup window: JSON decode 6 % slower than live costs. After a table is fixed, every real round (never a forced one) of a size that still has its learned cost is kept, clamped to 0.85-1.30 x the learned cost, and only the first 6 s of a busy run when the learning stretch showed a load-time effect. The rounds are kept in the table file across starts (state, real, cal lines). At 16 rounds a size takes their mean, is marked real in the file and never changes again; a mean outside 0.86-1.29 x the learned cost drops the rounds and collects again. A size that real requests never reach keeps its learned cost. The new cost applies from the next request. Unit test draft_policy_test: 145 of 145. --- include/strata/spec/draft_policy.hpp | 31 ++++++++ src/program/generate.cpp | 28 +++++++- src/spec/draft_policy.cpp | 104 ++++++++++++++++++++++++++- src/spec/draft_policy_test.cpp | 78 ++++++++++++++++++++ 4 files changed, 237 insertions(+), 4 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index 0f5b655841..600b1b8408 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -109,11 +109,20 @@ private: /// share <0..1> (optional: the CPU prompt share learned on this machine, src/prefill/prefill.cpp) /// pcie <0..1> (optional: the decode PCIe share PcieAuto settled on, src/program/generate.cpp) /// end +/// The real rounds of one size seen since the table was learned: n rounds, their sum in ms (each clamped to [kCalibLo, kCalibHi] x the learned cost). +struct CalAcc { + int n = 0; + double sum = 0.0; +}; struct CostFile { std::string key; std::array, CostLearner::kCtxBuckets> tables{}; double cpu_share = -1.0; ///< < 0: none stored double pcie_frac = -1.0; ///< the decode PCIe share PcieAuto settled on; < 0: none stored (a file from before it: refined, then written) + /// Calibration against real requests (see DraftPolicy::start_calibration); a file without these lines has none done. + bool state_effect = false; ///< the learning stretch showed a load-time effect: only fresh real rounds are counted + std::array real{}; ///< bit t-1: the cost of size t is a median of real rounds, no longer the learned one + std::array, CostLearner::kCtxBuckets> cal{}; ///< real rounds collected so far for the sizes not yet replaced }; /// false (with `why` for the log) when the file is missing, unreadable, malformed or truncated, or was learned under another key: the caller /// then learns a new table. Never throws. @@ -211,6 +220,23 @@ public: /// How long the engine has been busy (seconds since its last pause of CostLearner::kIdleS), as the caller measures it, for the round /// observe() is about to be given; < 0 (the default): unknown. Only the learner reads it. void set_busy_age(double s) { busy_age_ = s; } + /// Calibration of a fixed table against real requests. The learned costs come from a learning stretch (forced windows with filler rows, a burst of + /// prose), and a real round of the same size can cost a little more (measured on an M5 Max: 2 % on 2, 3 and 5 rows) - enough to flip a close choice + /// between a 4 and a 5 row window (JSON decode 6 % slower than live costs). After a table is fixed, every real round (never a forced one) of a size + /// whose cost is still the learned one is kept (clamped to [kCalibLo, kCalibHi] x the learned cost; only the first kFreshS seconds of a busy run when + /// the machine has a load-time effect), across starts through the table file (CostFile::cal). At kCalibN rounds the size's cost becomes their mean + /// (a result outside [kCalibOkLo, kCalibOkHi] x the learned cost means a disturbed stretch: the rounds are dropped and collected again) and the size + /// is marked real (CostFile::real) for good: no later change, so the windows of a repeated start are the same. A size that real requests never reach + /// keeps its learned cost (nothing is guessed from other sizes). real and cal come from the file (CostFile). + static constexpr int kCalibN = 16; + static constexpr double kCalibLo = 0.85, kCalibHi = 1.30, kCalibOkLo = 0.86, kCalibOkHi = 1.29; + void start_calibration(bool state_effect, const std::array& real, + const std::array, kCtxBuckets>& cal); + bool calibrating() const { return calib_on_; } + bool calib_dirty() const { return calib_dirty_; } + /// At a request's end: replaces the sizes that have kCalibN real rounds and puts the table, the real marks and the rounds collected so far into + /// cf (its other fields stay); report says which sizes changed (empty when none). True when cf should be written (something changed). + bool calibrate(CostFile& cf, std::string& report); CostLearner& learner() { return learner_; } const CostLearner& learner() const { return learner_; } @@ -259,6 +285,11 @@ private: bool fixed_ = false; // set_fixed_costs: no round time changes a cost bool learning_ = false; // set_learning: round times also go to learner_ double busy_age_ = -1.0; // set_busy_age + bool calib_on_ = false, calib_dirty_ = false, calib_fresh_only_ = false; + std::array fixed_n_{}; // the length of each bucket's fixed table + std::array real_{}; + std::array, kCtxBuckets> cal_{}; + void calib_add(int bucket, int t, double ms, double age); int explore_size(int lookup_k, int pad_cap) const; // the size a learning stretch measures next, 0 = none (choose() counts it) int explore_next(int reach, int skip) const; // the smallest size 2..reach (not `skip`) that still needs rounds; counts it; 0 = none bool explore_ok() const; // a forced round counts now (fresh phase, or no state effect) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index af20fd1ff4..3c58501e69 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14549,6 +14549,7 @@ int main(int argc, char** argv) { constexpr int kDraftCostMinN = 20; // a window size needs this many rounds to be measured (fewer: filled in) std::string dc_key; bool dc_learning = false; + bool dc_calib = false; // a table is used and its sizes are being calibrated against real rounds (DraftPolicy::start_calibration) // how long the engine has been busy: the learner keeps only the rounds of the first seconds of a busy run (CostLearner::kFreshS); a busy run // starts at a request that begins CostLearner::kIdleS or more after the last one ended (the GPU runs slower and steeper after a long load) Clock::time_point dc_busy_since = Clock::now(), dc_last_end = Clock::now(); @@ -14566,6 +14567,9 @@ int main(int argc, char** argv) { policy.set_fixed_costs(cf.tables[(size_t) k].data(), (int) cf.tables[(size_t) k].size(), k); sizes += (sizes.empty() ? "" : ", ") + std::to_string(cf.tables[(size_t) k].size()); } + dc_file = cf; + policy.start_calibration(cf.state_effect, cf.real, cf.cal); + dc_calib = policy.calibrating(); if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share); std::string extra = cf.cpu_share >= 0.0 ? "; CPU prompt share " + std::to_string(cf.cpu_share).substr(0, 4) : ""; if (dc_pcie_ok && cf.pcie_frac >= 0.0) { // PcieAuto's settled share: fixed, no refinement in this run @@ -14573,7 +14577,6 @@ int main(int argc, char** argv) { extra += "; PCIe share " + std::to_string(cf.pcie_frac).substr(0, 4); } else if (dc_pcie_ok) { // a file from before the stored PCIe share: refined as before, then written into the file dc_pcie_pending = true; - dc_file = cf; extra += "; PCIe share: refined in this run, then stored"; } std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request " @@ -16275,7 +16278,7 @@ int main(int argc, char** argv) { const bool geni = line.rfind("GENI ", 0) == 0; if (geni || line.rfind("GEN ", 0) == 0) { refresh_file_tier(); - if (dc_learning) { // the request's arrival, before its prompt is read: a pause since the last one ended starts a new busy run + if (dc_learning || dc_calib) { // the request's arrival, before its prompt is read: a pause since the last one ended starts a new busy run const Clock::time_point dc_now = Clock::now(); if (!dc_seen_request || std::chrono::duration(dc_now - dc_last_end).count() >= strata::spec::CostLearner::kIdleS) dc_busy_since = dc_now; dc_seen_request = true; @@ -20016,7 +20019,7 @@ int main(int argc, char** argv) { tr_k = 0; } if (spec_cost && use_mtp && timed_round && !from_sfx && !win_forced) policy.observe_probs(dwin_s.data(), T_mtp - 1, a); - if (dc_learning) policy.set_busy_age(std::chrono::duration(Clock::now() - dc_busy_since).count()); + if (dc_learning || dc_calib) policy.set_busy_age(std::chrono::duration(Clock::now() - dc_busy_since).count()); if (timed_round && !eos && chain_n == 0 && ((sfx_pad > 0 && from_sfx) || win_forced)) // a window run for its size's sake: its time only policy.observe_forced(T, std::chrono::duration(Clock::now() - round0).count()); else if (timed_round && !eos && chain_n == 0) @@ -20059,6 +20062,7 @@ int main(int argc, char** argv) { cf.key = dc_key; for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k) cf.tables[(size_t) k] = policy.learner().table(k, kDraftCostMinN, policy.top_size()); + cf.state_effect = policy.learner().state_effect(0, kDraftCostMinN); // real rounds are counted by the same rule (fresh only, or all) // the CPU prompt share, when it is on and balancing from measured times: its balance as measured so far, to a 0.05 // step (0.5 when no short prompt has measured it yet: on an RTX A6000 a fixed 0.5 read a 981-token chunk as fast as the // balancing share, 1,001-1,009 against 995-997 ms); fixed from now on like the table @@ -20080,6 +20084,9 @@ int main(int argc, char** argv) { policy.set_learning(false); policy.reset_learning(); dc_learning = false; + dc_file = cf; + policy.start_calibration(cf.state_effect, cf.real, cf.cal); + dc_calib = policy.calibrating(); std::string t0; char b[24]; for (size_t i = 0; i < cf.tables[0].size(); ++i) { @@ -20098,6 +20105,20 @@ int main(int argc, char** argv) { "on%s%s\n", t0.c_str(), saved ? "" : " (not saved: ", saved ? "" : (why + "; the next start learns again)").c_str()); } } + // --draft-costs, calibration: the real rounds of this request that the sizes still at their learned cost have collected; a size with + // kCalibN of them takes their mean (the file is rewritten whole, the new cost applies from the next request on, no later change) + if (dc_calib && policy.calib_dirty()) { + strata::spec::CostFile cc = dc_file; + std::string rep, why; + if (policy.calibrate(cc, rep)) { + const bool saved = strata::spec::write_cost_file(o.draft_costs, cc, why); + dc_file = cc; + if (!rep.empty()) + std::fprintf(stderr, "strata serve: draft costs: calibrated against real requests: %s%s\n", rep.c_str(), + saved ? "" : (" (not saved: " + why + ")").c_str()); + } + dc_calib = policy.calibrating(); + } // --draft-costs with a table from before the stored PCIe share: once PcieAuto has settled (three readings, or it gave up), its // share goes into the file beside the table and is fixed from the next request; the next start loads it if (dc_pcie_pending && !pcie_auto.on) { @@ -20107,6 +20128,7 @@ int main(int argc, char** argv) { cf.pcie_frac = o.pcie_frac; std::string why; const bool saved = strata::spec::write_cost_file(o.draft_costs, cf, why); + dc_file = cf; fix_pcie_share(cf.pcie_frac); std::fprintf(stderr, "strata serve: draft costs: the PCIe share settled at %.2f; it is %s and fixed from the next request on\n", cf.pcie_frac, saved ? "stored with this machine's table" : ("not stored (" + why + ")").c_str()); diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 5c814bb46e..6198fc638a 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -285,6 +285,29 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o out.pcie_frac = s; continue; } + if (line.rfind("state ", 0) == 0) { // calibration lines (DraftPolicy::start_calibration); a file without them has no calibration done + if (line != "state 0" && line != "state 1") { why = "a malformed state"; return false; } + out.state_effect = line == "state 1"; + continue; + } + if (line.rfind("real ", 0) == 0) { + int rb = -1; + unsigned m = 0; + if (std::sscanf(line.c_str(), "real %d %u", &rb, &m) != 2 || rb < 0 || rb >= CostLearner::kCtxBuckets) { why = "a malformed real mark"; return false; } + out.real[(size_t) rb] = m; + continue; + } + if (line.rfind("cal ", 0) == 0) { + int cb = -1, ct = -1, cn = -1; + double cs = -1.0; + if (std::sscanf(line.c_str(), "cal %d %d %d %lf", &cb, &ct, &cn, &cs) != 4 || cb < 0 || cb >= CostLearner::kCtxBuckets || ct < 1 || ct > CostLearner::kMaxT + || cn < 0 || cn > 100000 || !(cs >= 0.0) || !(cs < 1e9)) { + why = "a malformed calibration line"; + return false; + } + out.cal[(size_t) cb][(size_t) ct] = CalAcc{cn, cs}; + continue; + } int b = -1, used = 0; if (std::sscanf(line.c_str(), "bucket %d %n", &b, &used) < 1 || used == 0 || b < 0 || b >= CostLearner::kCtxBuckets) { why = "a malformed line"; @@ -332,6 +355,16 @@ bool write_cost_file(const std::string& path, const CostFile& c, std::string& wh } f << "\n"; } + if (c.state_effect) f << "state 1\n"; + for (int k = 0; k < CostLearner::kCtxBuckets; ++k) { + if (c.real[(size_t) k] != 0u) f << "real " << k << " " << c.real[(size_t) k] << "\n"; + for (int t = 1; t <= CostLearner::kMaxT; ++t) { + const CalAcc& a = c.cal[(size_t) k][(size_t) t]; + if (a.n <= 0 || (c.real[(size_t) k] >> (t - 1) & 1u)) continue; + std::snprintf(b, sizeof b, "%.4f", a.sum); + f << "cal " << k << " " << t << " " << a.n << " " << b << "\n"; + } + } if (c.cpu_share >= 0.0) { std::snprintf(b, sizeof b, "share %.3f\n", std::min(c.cpu_share, 1.0)); f << b; @@ -363,6 +396,7 @@ void DraftPolicy::set_fixed_costs(const double* ms, int n, int bucket) { held_.clear(); if (ms == nullptr || n <= 0) return; bucket = std::clamp(bucket, 0, kCtxBuckets - 1); + fixed_n_[(size_t) bucket] = std::min(n, kMaxT); for (int t = 1; t <= kMaxT; ++t) { // the table replaces what was measured; sizes past its end scale from it (cost_ms) const bool in = t <= n && ms[t - 1] > 0.0; cost_[bucket][t] = in ? ms[t - 1] : 0.0; @@ -567,6 +601,7 @@ void DraftPolicy::reset_learning() { void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) { t = std::clamp(t, 1, kMaxT); if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_); + if (calib_on_ && round_ms > 0) calib_add(bk_, t, round_ms, busy_age_); if (round_ms > 0 && !fixed_) { round_ms = clamp_sample(t, round_ms); const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha; // a running mean for the first samples @@ -586,6 +621,72 @@ void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double ro } } +// ---- calibration of a fixed table against real requests (see the header) + +void DraftPolicy::start_calibration(bool state_effect, const std::array& real, + const std::array, kCtxBuckets>& cal) { + calib_fresh_only_ = state_effect; + real_ = real; + cal_ = cal; + calib_dirty_ = false; + calib_on_ = false; + for (int k = 0; k < kCtxBuckets; ++k) { + const int n = fixed_n_[(size_t) k]; + for (int t = 1; t <= n; ++t) + if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true; + } +} + +void DraftPolicy::calib_add(int bucket, int t, double ms, double age) { + if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > fixed_n_[(size_t) bucket]) return; + if (real_[(size_t) bucket] >> (t - 1) & 1u) return; + if (calib_fresh_only_ && age > CostLearner::kFreshS) return; // the table is what rounds of the first seconds of a busy run cost + const double base = cost_[(size_t) bucket][(size_t) t]; + if (!(base > 0.0)) return; + CalAcc& a = cal_[(size_t) bucket][(size_t) t]; + if (a.n >= kCalibN) return; + a.sum += std::clamp(ms, kCalibLo * base, kCalibHi * base); // one stalled round moves the mean by at most (kCalibHi - 1) / kCalibN + a.n += 1; + calib_dirty_ = true; +} + +bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { + report.clear(); + if (!calib_on_ && !calib_dirty_) return false; + char b[96]; + bool changed = calib_dirty_; + for (int k = 0; k < kCtxBuckets; ++k) { + const int n = fixed_n_[(size_t) k]; + for (int t = 1; t <= n; ++t) { + if (real_[(size_t) k] >> (t - 1) & 1u) continue; + CalAcc& a = cal_[(size_t) k][(size_t) t]; + if (a.n < kCalibN) continue; + const double v = a.sum / a.n, base = cost_[(size_t) k][(size_t) t]; + if (v >= kCalibOkLo * base && v <= kCalibOkHi * base) { + std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v); + report += b; + cost_[(size_t) k][(size_t) t] = v; + real_[(size_t) k] |= 1u << (t - 1); + } + a = CalAcc{}; // replaced, or disturbed (rounds dropped, collected again) + } + for (int t = 2; t <= n; ++t) // more rows never cost less + if (cost_[(size_t) k][(size_t) t] < cost_[(size_t) k][(size_t) t - 1]) cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t - 1]; + if (n > 0) { + cf.tables[(size_t) k].assign(cost_[(size_t) k].begin() + 1, cost_[(size_t) k].begin() + 1 + n); + cf.real[(size_t) k] = real_[(size_t) k]; + for (int t = 0; t <= kMaxT; ++t) cf.cal[(size_t) k][(size_t) t] = cal_[(size_t) k][(size_t) t]; + } + } + cf.state_effect = calib_fresh_only_; + calib_dirty_ = false; + calib_on_ = false; + for (int k = 0; k < kCtxBuckets; ++k) + for (int t = 1; t <= fixed_n_[(size_t) k]; ++t) + if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true; + return changed || !report.empty(); +} + void DraftPolicy::observe_committed(bool lookup, int t, int accepted, int match) { t = std::clamp(t, 1, kMaxT); rounds_ += 1.0; @@ -603,7 +704,7 @@ void DraftPolicy::observe_committed(bool lookup, int t, int accepted, int match) } void DraftPolicy::defer_cost(int64_t end, int t, double round_ms) { - if (round_ms > 0 && (learning_ || !fixed_)) held_.push_back({end, bk_, std::clamp(t, 1, kMaxT), round_ms, busy_age_}); + if (round_ms > 0 && (learning_ || calib_on_ || !fixed_)) held_.push_back({end, bk_, std::clamp(t, 1, kMaxT), round_ms, busy_age_}); } void DraftPolicy::apply_costs(int64_t committed) { @@ -612,6 +713,7 @@ void DraftPolicy::apply_costs(int64_t committed) { for (; n < held_.size() && held_[n].end < committed; ++n) { const HeldCost& h = held_[n]; if (learning_) learner_.add(h.bucket, h.t, h.ms, h.age); + if (calib_on_) calib_add(h.bucket, h.t, h.ms, h.age); if (fixed_) continue; bk_ = h.bucket; // observe()'s update, in the bucket the round ran in const double ms = clamp_sample(h.t, h.ms); diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index c2a6062a75..72d99f9f8b 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -544,6 +544,84 @@ int main() { check(g5.lookup && g5.t == 5 && g5.pad == 3, "pad: the next unmeasured size follows once one has its samples"); check(g.choose(1, 1, 3, 1).pad == 0, "pad: a pad_cap of one draft makes no filler"); } + { // calibration against real rounds + using strata::spec::CalAcc; + using strata::spec::CostFile; + using strata::spec::CostLearner; + using strata::spec::read_cost_file; + using strata::spec::write_cost_file; + const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90}; + DraftPolicy c(8); + c.set_fixed_costs(tab, 5, 0); + std::array real0{}; + std::array, CostLearner::kCtxBuckets> cal0{}; + c.start_calibration(false, real0, cal0); + check(c.calibrating() && !c.calib_dirty(), "calib: on after a table is fixed, nothing collected"); + for (int i = 0; i < 15; ++i) c.observe(false, 3, 2, 0, 16.70); + CostFile cf; + std::string rep; + check(c.calibrate(cf, rep) && rep.empty() && cf.cal[0][3].n == 15, "calib: 15 real rounds are kept, nothing replaced"); + check(std::fabs(c.cost_ms(3) - 16.41) < 1e-9, "calib: the cost of a size stays at the learned one under kCalibN rounds"); + c.observe(false, 3, 2, 0, 16.70); + check(c.calibrate(cf, rep) && !rep.empty(), "calib: the 16th real round replaces the cost"); + check(std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && (cf.real[0] & 4u) && std::fabs(cf.tables[0][2] - 16.70) < 1e-9, "calib: the cost is the mean, the size is marked real, the file has it"); + check(std::fabs(c.cost_ms(5) - 20.90) < 1e-9 && std::fabs(c.cost_ms(4) - 18.57) < 1e-9, "calib: a size without real rounds keeps its learned cost (nothing guessed)"); + for (int i = 0; i < 40; ++i) c.observe(false, 3, 2, 0, 15.0); + check(!c.calib_dirty() && std::fabs(c.cost_ms(3) - 16.70) < 1e-9, "calib: a real size never changes again"); + // a lookup size reached once per request: rounds come across starts through the file + DraftPolicy d(8); + d.set_fixed_costs(tab, 5, 0); + CostFile cd; + cd.key = "k"; + cd.tables[0].assign(tab, tab + 5); + std::array, CostLearner::kCtxBuckets> cal1 = cal0; + for (int start = 0; start < 16; ++start) { + DraftPolicy e(8); + e.set_fixed_costs(tab, 5, 0); + e.start_calibration(false, real0, cal1); + e.observe(true, 4, 2, 0, 18.9); + std::string r2; + check(e.calibrate(cd, r2), "calib: a start with one real round of a size writes the file"); + cal1 = cd.cal; + real0 = cd.real; + } + check((cd.real[0] & 8u) != 0 && std::fabs(cd.tables[0][3] - 18.9) < 1e-9 && cd.cal[0][4].n == 0, "calib: 16 starts of one round each calibrate the size"); + // the file round trip: state, real, cal + CostFile w; + w.key = "k2"; + w.tables[0].assign(tab, tab + 5); + w.state_effect = true; + w.real[0] = 6u; + w.cal[0][4] = CalAcc{7, 131.0}; + const std::string path = "dp_calib_test.costs"; + std::string why; + check(write_cost_file(path, w, why), "calib file: written"); + CostFile r; + check(read_cost_file(path, "k2", r, why) && r.state_effect && r.real[0] == 6u && r.cal[0][4].n == 7 && std::fabs(r.cal[0][4].sum - 131.0) < 1e-3 && r.cal[0][2].n == 0, + "calib file: state, real marks and collected rounds come back"); + std::remove(path.c_str()); + // a machine with a load-time effect counts only the first kFreshS seconds of a busy run + DraftPolicy f(8); + f.set_fixed_costs(tab, 5, 0); + f.start_calibration(true, real0 = {}, cal0); + f.set_busy_age(2.0); + for (int i = 0; i < 10; ++i) f.observe(false, 2, 1, 0, 14.6); + f.set_busy_age(50.0); + for (int i = 0; i < 10; ++i) f.observe(false, 2, 1, 0, 17.0); + CostFile cfz; + std::string rz; + f.calibrate(cfz, rz); + check(cfz.cal[0][2].n == 10, "calib: with a state effect only fresh rounds are counted"); + // a disturbed stretch (a stalled machine) is dropped, not taken + DraftPolicy g(8); + g.set_fixed_costs(tab, 5, 0); + g.start_calibration(false, real0 = {}, cal0); + for (int i = 0; i < 16; ++i) g.observe(false, 1, 0, 0, 40.0); + CostFile cg; + std::string rg; + g.calibrate(cg, rg); + check(rg.empty() && std::fabs(g.cost_ms(1) - 12.68) < 1e-9 && cg.cal[0][1].n == 0 && (cg.real[0] & 1u) == 0, "calib: rounds far above the learned cost are dropped"); + } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; } From d71da59b29246e7bb94e7d641d71210ae62b8488 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 03:58:17 +0100 Subject: [PATCH 08/17] spec: sizes not yet calibrated follow the sizes that are A size that real requests reach rarely (the 4-row lookup: about one round per request) stayed at its learned price for 16 requests while the sizes next to it were already calibrated, and a price that is only a little lower than its neighbours' flips a close choice (JSON decode 6 % slower than live costs). The table file now keeps the learned costs on its bucket lines and the cost of each real size on rc lines. A size with 2 or more rows that is not real yet is priced at its learned cost x the mean of (real cost / learned cost) over the real sizes of 2 or more rows, until it has its own 16 rounds (all sizes scaled alike would change no choice). Nothing is scaled while no such size is real. Unit test draft_policy_test: 147 of 147. --- include/strata/spec/draft_policy.hpp | 12 ++++- src/program/generate.cpp | 4 +- src/spec/draft_policy.cpp | 81 +++++++++++++++++++++++----- src/spec/draft_policy_test.cpp | 66 +++++++++++++++-------- 4 files changed, 126 insertions(+), 37 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index 600b1b8408..814a1acbba 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -123,6 +123,7 @@ struct CostFile { bool state_effect = false; ///< the learning stretch showed a load-time effect: only fresh real rounds are counted std::array real{}; ///< bit t-1: the cost of size t is a median of real rounds, no longer the learned one std::array, CostLearner::kCtxBuckets> cal{}; ///< real rounds collected so far for the sizes not yet replaced + std::array, CostLearner::kCtxBuckets> real_cost{}; ///< the cost of a size marked real (the table lines keep the learned costs) }; /// false (with `why` for the log) when the file is missing, unreadable, malformed or truncated, or was learned under another key: the caller /// then learns a new table. Never throws. @@ -227,11 +228,16 @@ public: /// the machine has a load-time effect), across starts through the table file (CostFile::cal). At kCalibN rounds the size's cost becomes their mean /// (a result outside [kCalibOkLo, kCalibOkHi] x the learned cost means a disturbed stretch: the rounds are dropped and collected again) and the size /// is marked real (CostFile::real) for good: no later change, so the windows of a repeated start are the same. A size that real requests never reach - /// keeps its learned cost (nothing is guessed from other sizes). real and cal come from the file (CostFile). + /// keeps its learned cost, except for the provisional step below. real, cal and real_cost come from the file (CostFile). + /// Provisional step: a size that is not real yet and has 2 or more rows is priced at its learned cost x the mean of (real cost / learned cost) over the + /// real sizes of 2 or more rows (when there are some), so a size that real requests reach rarely (the 4-row lookup: about one round per request) is not + /// left at a price that the sizes next to it have already left. Scaling every size alike would change no choice (the policy compares costs with each + /// other); this changes the prices relative to each other, from the engine's own measurements, and only until the size has its own 16 rounds. static constexpr int kCalibN = 16; static constexpr double kCalibLo = 0.85, kCalibHi = 1.30, kCalibOkLo = 0.86, kCalibOkHi = 1.29; void start_calibration(bool state_effect, const std::array& real, - const std::array, kCtxBuckets>& cal); + const std::array, kCtxBuckets>& cal, + const std::array, kCtxBuckets>& real_cost); bool calibrating() const { return calib_on_; } bool calib_dirty() const { return calib_dirty_; } /// At a request's end: replaces the sizes that have kCalibN real rounds and puts the table, the real marks and the rounds collected so far into @@ -289,7 +295,9 @@ private: std::array fixed_n_{}; // the length of each bucket's fixed table std::array real_{}; std::array, kCtxBuckets> cal_{}; + std::array, kCtxBuckets> learned_{}, real_cost_{}; // the table as fixed (learned); the cost of each real size void calib_add(int bucket, int t, double ms, double age); + void apply_provisional(); int explore_size(int lookup_k, int pad_cap) const; // the size a learning stretch measures next, 0 = none (choose() counts it) int explore_next(int reach, int skip) const; // the smallest size 2..reach (not `skip`) that still needs rounds; counts it; 0 = none bool explore_ok() const; // a forced round counts now (fresh phase, or no state effect) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3c58501e69..04f52a8f92 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14568,7 +14568,7 @@ int main(int argc, char** argv) { sizes += (sizes.empty() ? "" : ", ") + std::to_string(cf.tables[(size_t) k].size()); } dc_file = cf; - policy.start_calibration(cf.state_effect, cf.real, cf.cal); + policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost); dc_calib = policy.calibrating(); if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share); std::string extra = cf.cpu_share >= 0.0 ? "; CPU prompt share " + std::to_string(cf.cpu_share).substr(0, 4) : ""; @@ -20085,7 +20085,7 @@ int main(int argc, char** argv) { policy.reset_learning(); dc_learning = false; dc_file = cf; - policy.start_calibration(cf.state_effect, cf.real, cf.cal); + policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost); dc_calib = policy.calibrating(); std::string t0; char b[24]; diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 6198fc638a..79f4a8cabc 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -308,6 +308,16 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o out.cal[(size_t) cb][(size_t) ct] = CalAcc{cn, cs}; continue; } + if (line.rfind("rc ", 0) == 0) { + int rb = -1, rt = -1; + double rv = -1.0; + if (std::sscanf(line.c_str(), "rc %d %d %lf", &rb, &rt, &rv) != 3 || rb < 0 || rb >= CostLearner::kCtxBuckets || rt < 1 || rt > CostLearner::kMaxT || !(rv > 0.0) || !(rv < 1e5)) { + why = "a malformed real cost"; + return false; + } + out.real_cost[(size_t) rb][(size_t) rt] = rv; + continue; + } int b = -1, used = 0; if (std::sscanf(line.c_str(), "bucket %d %n", &b, &used) < 1 || used == 0 || b < 0 || b >= CostLearner::kCtxBuckets) { why = "a malformed line"; @@ -358,6 +368,11 @@ bool write_cost_file(const std::string& path, const CostFile& c, std::string& wh if (c.state_effect) f << "state 1\n"; for (int k = 0; k < CostLearner::kCtxBuckets; ++k) { if (c.real[(size_t) k] != 0u) f << "real " << k << " " << c.real[(size_t) k] << "\n"; + for (int t = 1; t <= CostLearner::kMaxT; ++t) + if ((c.real[(size_t) k] >> (t - 1) & 1u) && c.real_cost[(size_t) k][(size_t) t] > 0.0) { + std::snprintf(b, sizeof b, "%.4f", c.real_cost[(size_t) k][(size_t) t]); + f << "rc " << k << " " << t << " " << b << "\n"; + } for (int t = 1; t <= CostLearner::kMaxT; ++t) { const CalAcc& a = c.cal[(size_t) k][(size_t) t]; if (a.n <= 0 || (c.real[(size_t) k] >> (t - 1) & 1u)) continue; @@ -401,6 +416,7 @@ void DraftPolicy::set_fixed_costs(const double* ms, int n, int bucket) { const bool in = t <= n && ms[t - 1] > 0.0; cost_[bucket][t] = in ? ms[t - 1] : 0.0; cost_n_[bucket][t] = in ? 1e6 : 0.0; + learned_[(size_t) bucket][(size_t) t] = cost_[bucket][t]; } } @@ -623,11 +639,38 @@ void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double ro // ---- calibration of a fixed table against real requests (see the header) +void DraftPolicy::apply_provisional() { + for (int k = 0; k < kCtxBuckets; ++k) { + const int n = fixed_n_[(size_t) k]; + if (n <= 0) continue; + double sum = 0.0; + int cnt = 0; + for (int t = 2; t <= n; ++t) + if ((real_[(size_t) k] >> (t - 1) & 1u) && learned_[(size_t) k][(size_t) t] > 0.0) { + sum += real_cost_[(size_t) k][(size_t) t] / learned_[(size_t) k][(size_t) t]; + ++cnt; + } + const double r = cnt > 0 ? sum / cnt : 1.0; + for (int t = 1; t <= n; ++t) { + if (real_[(size_t) k] >> (t - 1) & 1u) cost_[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t]; + else cost_[(size_t) k][(size_t) t] = learned_[(size_t) k][(size_t) t] * (t >= 2 ? r : 1.0); + } + for (int t = 2; t <= n; ++t) // more rows never cost less + if (cost_[(size_t) k][(size_t) t] < cost_[(size_t) k][(size_t) t - 1]) cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t - 1]; + } +} + void DraftPolicy::start_calibration(bool state_effect, const std::array& real, - const std::array, kCtxBuckets>& cal) { + const std::array, kCtxBuckets>& cal, + const std::array, kCtxBuckets>& real_cost) { calib_fresh_only_ = state_effect; real_ = real; cal_ = cal; + real_cost_ = real_cost; + for (int k = 0; k < kCtxBuckets; ++k) // a mark without a cost (a damaged file) is no mark + for (int t = 1; t <= kMaxT; ++t) + if ((real_[(size_t) k] >> (t - 1) & 1u) && !(real_cost_[(size_t) k][(size_t) t] > 0.0)) real_[(size_t) k] &= ~(1u << (t - 1)); + apply_provisional(); calib_dirty_ = false; calib_on_ = false; for (int k = 0; k < kCtxBuckets; ++k) { @@ -641,7 +684,7 @@ void DraftPolicy::calib_add(int bucket, int t, double ms, double age) { if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > fixed_n_[(size_t) bucket]) return; if (real_[(size_t) bucket] >> (t - 1) & 1u) return; if (calib_fresh_only_ && age > CostLearner::kFreshS) return; // the table is what rounds of the first seconds of a busy run cost - const double base = cost_[(size_t) bucket][(size_t) t]; + const double base = learned_[(size_t) bucket][(size_t) t]; if (!(base > 0.0)) return; CalAcc& a = cal_[(size_t) bucket][(size_t) t]; if (a.n >= kCalibN) return; @@ -654,28 +697,42 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { report.clear(); if (!calib_on_ && !calib_dirty_) return false; char b[96]; - bool changed = calib_dirty_; + bool changed = calib_dirty_, replaced = false; for (int k = 0; k < kCtxBuckets; ++k) { const int n = fixed_n_[(size_t) k]; for (int t = 1; t <= n; ++t) { if (real_[(size_t) k] >> (t - 1) & 1u) continue; CalAcc& a = cal_[(size_t) k][(size_t) t]; if (a.n < kCalibN) continue; - const double v = a.sum / a.n, base = cost_[(size_t) k][(size_t) t]; + const double v = a.sum / a.n, base = learned_[(size_t) k][(size_t) t]; if (v >= kCalibOkLo * base && v <= kCalibOkHi * base) { std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v); report += b; - cost_[(size_t) k][(size_t) t] = v; + real_cost_[(size_t) k][(size_t) t] = v; real_[(size_t) k] |= 1u << (t - 1); + replaced = true; } a = CalAcc{}; // replaced, or disturbed (rounds dropped, collected again) } - for (int t = 2; t <= n; ++t) // more rows never cost less - if (cost_[(size_t) k][(size_t) t] < cost_[(size_t) k][(size_t) t - 1]) cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t - 1]; - if (n > 0) { - cf.tables[(size_t) k].assign(cost_[(size_t) k].begin() + 1, cost_[(size_t) k].begin() + 1 + n); - cf.real[(size_t) k] = real_[(size_t) k]; - for (int t = 0; t <= kMaxT; ++t) cf.cal[(size_t) k][(size_t) t] = cal_[(size_t) k][(size_t) t]; + } + if (replaced) { + std::array, kCtxBuckets> before = cost_; + apply_provisional(); + for (int k = 0; k < kCtxBuckets; ++k) + for (int t = 1; t <= fixed_n_[(size_t) k]; ++t) + if (!(real_[(size_t) k] >> (t - 1) & 1u) && std::fabs(cost_[(size_t) k][(size_t) t] - before[(size_t) k][(size_t) t]) > 0.005) { + std::snprintf(b, sizeof b, "%s%d rows (not real yet) %.2f -> %.2f", report.empty() ? "" : ", ", t, before[(size_t) k][(size_t) t], cost_[(size_t) k][(size_t) t]); + report += b; + } + } + for (int k = 0; k < kCtxBuckets; ++k) { + const int n = fixed_n_[(size_t) k]; + if (n <= 0) continue; + cf.tables[(size_t) k].assign(learned_[(size_t) k].begin() + 1, learned_[(size_t) k].begin() + 1 + n); // the file keeps the learned costs + cf.real[(size_t) k] = real_[(size_t) k]; + for (int t = 0; t <= kMaxT; ++t) { + cf.cal[(size_t) k][(size_t) t] = cal_[(size_t) k][(size_t) t]; + cf.real_cost[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t]; } } cf.state_effect = calib_fresh_only_; @@ -684,7 +741,7 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { for (int k = 0; k < kCtxBuckets; ++k) for (int t = 1; t <= fixed_n_[(size_t) k]; ++t) if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true; - return changed || !report.empty(); + return changed || replaced; } void DraftPolicy::observe_committed(bool lookup, int t, int accepted, int match) { diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 72d99f9f8b..0f9e40c49a 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -550,60 +550,74 @@ int main() { using strata::spec::CostLearner; using strata::spec::read_cost_file; using strata::spec::write_cost_file; + using Cal = std::array, CostLearner::kCtxBuckets>; + using Rc = std::array, CostLearner::kCtxBuckets>; + using Real = std::array; const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90}; + const Cal cal0{}; + const Rc rc0{}; DraftPolicy c(8); c.set_fixed_costs(tab, 5, 0); - std::array real0{}; - std::array, CostLearner::kCtxBuckets> cal0{}; - c.start_calibration(false, real0, cal0); + c.start_calibration(false, Real{}, cal0, rc0); check(c.calibrating() && !c.calib_dirty(), "calib: on after a table is fixed, nothing collected"); for (int i = 0; i < 15; ++i) c.observe(false, 3, 2, 0, 16.70); CostFile cf; std::string rep; check(c.calibrate(cf, rep) && rep.empty() && cf.cal[0][3].n == 15, "calib: 15 real rounds are kept, nothing replaced"); - check(std::fabs(c.cost_ms(3) - 16.41) < 1e-9, "calib: the cost of a size stays at the learned one under kCalibN rounds"); + check(std::fabs(c.cost_ms(3) - 16.41) < 1e-9 && std::fabs(c.cost_ms(4) - 18.57) < 1e-9, "calib: under kCalibN rounds every cost stays the learned one"); c.observe(false, 3, 2, 0, 16.70); check(c.calibrate(cf, rep) && !rep.empty(), "calib: the 16th real round replaces the cost"); - check(std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && (cf.real[0] & 4u) && std::fabs(cf.tables[0][2] - 16.70) < 1e-9, "calib: the cost is the mean, the size is marked real, the file has it"); - check(std::fabs(c.cost_ms(5) - 20.90) < 1e-9 && std::fabs(c.cost_ms(4) - 18.57) < 1e-9, "calib: a size without real rounds keeps its learned cost (nothing guessed)"); + const double r3 = 16.70 / 16.41; + check(std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && (cf.real[0] & 4u) && std::fabs(cf.real_cost[0][3] - 16.70) < 1e-9 && std::fabs(cf.tables[0][2] - 16.41) < 1e-9, + "calib: the size takes the mean, is marked real; the file keeps the learned cost beside it"); + check(std::fabs(c.cost_ms(4) - 18.57 * r3) < 1e-6 && std::fabs(c.cost_ms(5) - 20.90 * r3) < 1e-6 && std::fabs(c.cost_ms(2) - 14.30 * r3) < 1e-6 && std::fabs(c.cost_ms(1) - 12.68) < 1e-9, + "calib: sizes not real yet (2 rows and more) are priced at learned x the real sizes' ratio, size 1 stays"); for (int i = 0; i < 40; ++i) c.observe(false, 3, 2, 0, 15.0); check(!c.calib_dirty() && std::fabs(c.cost_ms(3) - 16.70) < 1e-9, "calib: a real size never changes again"); - // a lookup size reached once per request: rounds come across starts through the file - DraftPolicy d(8); - d.set_fixed_costs(tab, 5, 0); + // a lookup size reached once per request: its rounds come across starts through the file CostFile cd; cd.key = "k"; - cd.tables[0].assign(tab, tab + 5); - std::array, CostLearner::kCtxBuckets> cal1 = cal0; + Cal cal1 = cal0; + Real real1{}; + Rc rc1 = rc0; for (int start = 0; start < 16; ++start) { DraftPolicy e(8); e.set_fixed_costs(tab, 5, 0); - e.start_calibration(false, real0, cal1); + e.start_calibration(false, real1, cal1, rc1); e.observe(true, 4, 2, 0, 18.9); std::string r2; check(e.calibrate(cd, r2), "calib: a start with one real round of a size writes the file"); cal1 = cd.cal; - real0 = cd.real; + real1 = cd.real; + rc1 = cd.real_cost; } - check((cd.real[0] & 8u) != 0 && std::fabs(cd.tables[0][3] - 18.9) < 1e-9 && cd.cal[0][4].n == 0, "calib: 16 starts of one round each calibrate the size"); - // the file round trip: state, real, cal + check((cd.real[0] & 8u) != 0 && std::fabs(cd.real_cost[0][4] - 18.9) < 1e-9 && cd.cal[0][4].n == 0 && std::fabs(cd.tables[0][3] - 18.57) < 1e-9, + "calib: 16 starts of one round each calibrate the size"); + DraftPolicy again(8); // a start from that file: size 4 real, the others provisional at 18.9 / 18.57 + again.set_fixed_costs(tab, 5, 0); + again.start_calibration(false, real1, cal1, rc1); + check(std::fabs(again.cost_ms(4) - 18.9) < 1e-9 && std::fabs(again.cost_ms(5) - 20.90 * 18.9 / 18.57) < 1e-6, "calib: a restart gives the same costs"); + // the file round trip: state, real, real cost, cal CostFile w; w.key = "k2"; w.tables[0].assign(tab, tab + 5); w.state_effect = true; w.real[0] = 6u; + w.real_cost[0][2] = 14.6; + w.real_cost[0][3] = 16.7; w.cal[0][4] = CalAcc{7, 131.0}; const std::string path = "dp_calib_test.costs"; std::string why; check(write_cost_file(path, w, why), "calib file: written"); CostFile r; - check(read_cost_file(path, "k2", r, why) && r.state_effect && r.real[0] == 6u && r.cal[0][4].n == 7 && std::fabs(r.cal[0][4].sum - 131.0) < 1e-3 && r.cal[0][2].n == 0, - "calib file: state, real marks and collected rounds come back"); + check(read_cost_file(path, "k2", r, why) && r.state_effect && r.real[0] == 6u && r.cal[0][4].n == 7 && std::fabs(r.cal[0][4].sum - 131.0) < 1e-3 && r.cal[0][2].n == 0 && + std::fabs(r.real_cost[0][2] - 14.6) < 1e-9 && std::fabs(r.real_cost[0][3] - 16.7) < 1e-9, + "calib file: state, real marks, real costs and collected rounds come back"); std::remove(path.c_str()); // a machine with a load-time effect counts only the first kFreshS seconds of a busy run DraftPolicy f(8); f.set_fixed_costs(tab, 5, 0); - f.start_calibration(true, real0 = {}, cal0); + f.start_calibration(true, Real{}, cal0, rc0); f.set_busy_age(2.0); for (int i = 0; i < 10; ++i) f.observe(false, 2, 1, 0, 14.6); f.set_busy_age(50.0); @@ -615,12 +629,22 @@ int main() { // a disturbed stretch (a stalled machine) is dropped, not taken DraftPolicy g(8); g.set_fixed_costs(tab, 5, 0); - g.start_calibration(false, real0 = {}, cal0); - for (int i = 0; i < 16; ++i) g.observe(false, 1, 0, 0, 40.0); + g.start_calibration(false, Real{}, cal0, rc0); + for (int i = 0; i < 16; ++i) g.observe(false, 2, 0, 0, 40.0); CostFile cg; std::string rg; g.calibrate(cg, rg); - check(rg.empty() && std::fabs(g.cost_ms(1) - 12.68) < 1e-9 && cg.cal[0][1].n == 0 && (cg.real[0] & 1u) == 0, "calib: rounds far above the learned cost are dropped"); + check(rg.empty() && std::fabs(g.cost_ms(2) - 14.30) < 1e-9 && cg.cal[0][2].n == 0 && (cg.real[0] & 2u) == 0, "calib: rounds far above the learned cost are dropped"); + // a size that real requests never reach, and a machine whose real sizes are all 1 row: nothing is scaled + DraftPolicy h(8); + h.set_fixed_costs(tab, 5, 0); + h.start_calibration(false, Real{}, cal0, rc0); + for (int i = 0; i < 16; ++i) h.observe(false, 1, 0, 0, 13.0); + CostFile ch; + std::string rh; + h.calibrate(ch, rh); + check((ch.real[0] & 1u) != 0 && std::fabs(h.cost_ms(1) - 13.0) < 1e-9 && std::fabs(h.cost_ms(2) - 14.30) < 1e-9 && std::fabs(h.cost_ms(5) - 20.90) < 1e-9, + "calib: a real 1-row size scales nothing else"); } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; From 5938e506daad33ad90b6b86abca67dccd0250cc4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 04:42:54 +0100 Subject: [PATCH 09/17] spec: a table that is not fully calibrated yet is held back, live costs decide meanwhile A learned draft-cost table was used from its first request on, with only part of its sizes calibrated against real rounds. On a JSON request that costs 5 % against live costs (the 4-row window is priced under a real round). Now the table is loaded but not used while any of its sizes is not calibrated: the policy decides with live costs exactly as without a table, the real rounds are collected meanwhile, and the table (the real costs) takes over for good at the end of the request in which the last size is calibrated. A table file that already has every size calibrated is used from the first round, as before. The provisional pooled-scale step is removed: it only mattered for a table in use with sizes not yet calibrated, which no longer happens. The unit test covers: a held table picks and prices like a policy without a table, one calibrated size does not bring the table into use, the last one does, a fully calibrated file is used at once. --- include/strata/spec/draft_policy.hpp | 20 ++++++--- src/program/generate.cpp | 18 ++++++-- src/spec/draft_policy.cpp | 65 ++++++++++++++++++---------- src/spec/draft_policy_test.cpp | 52 +++++++++++++++------- 4 files changed, 106 insertions(+), 49 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index 814a1acbba..870eeae714 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -228,11 +228,10 @@ public: /// the machine has a load-time effect), across starts through the table file (CostFile::cal). At kCalibN rounds the size's cost becomes their mean /// (a result outside [kCalibOkLo, kCalibOkHi] x the learned cost means a disturbed stretch: the rounds are dropped and collected again) and the size /// is marked real (CostFile::real) for good: no later change, so the windows of a repeated start are the same. A size that real requests never reach - /// keeps its learned cost, except for the provisional step below. real, cal and real_cost come from the file (CostFile). - /// Provisional step: a size that is not real yet and has 2 or more rows is priced at its learned cost x the mean of (real cost / learned cost) over the - /// real sizes of 2 or more rows (when there are some), so a size that real requests reach rarely (the 4-row lookup: about one round per request) is not - /// left at a price that the sizes next to it have already left. Scaling every size alike would change no choice (the policy compares costs with each - /// other); this changes the prices relative to each other, from the engine's own measurements, and only until the size has its own 16 rounds. + /// keeps its learned cost. real, cal and real_cost come from the file (CostFile). + /// Until every size of the table is real the table is not used: the policy decides with live costs, exactly as without a table (a half-calibrated + /// table priced a JSON request 5 % slower than live costs), and only collects the real rounds; once the last size is calibrated the table + /// (the real costs) decides for good. static constexpr int kCalibN = 16; static constexpr double kCalibLo = 0.85, kCalibHi = 1.30, kCalibOkLo = 0.86, kCalibOkHi = 1.29; void start_calibration(bool state_effect, const std::array& real, @@ -240,6 +239,10 @@ public: const std::array, kCtxBuckets>& real_cost); bool calibrating() const { return calib_on_; } bool calib_dirty() const { return calib_dirty_; } + /// While a loaded table still has sizes that are not calibrated (calibrating()), the table is held back: the policy decides with live costs + /// exactly as without a table (fixed() is false), and the real rounds are collected meanwhile. Once the last size is calibrated (at a request's + /// end, calibrate()) the table takes over for good. table_held() is true in that stretch. + bool table_held() const { return held_table_; } /// At a request's end: replaces the sizes that have kCalibN real rounds and puts the table, the real marks and the rounds collected so far into /// cf (its other fields stay); report says which sizes changed (empty when none). True when cf should be written (something changed). bool calibrate(CostFile& cf, std::string& report); @@ -296,8 +299,13 @@ private: std::array real_{}; std::array, kCtxBuckets> cal_{}; std::array, kCtxBuckets> learned_{}, real_cost_{}; // the table as fixed (learned); the cost of each real size + bool held_table_ = false; // a table is loaded but not used yet: live costs decide (see table_held()) + bool live_saved_ = false; + std::array, kCtxBuckets> live_cost_{}, live_n_{}; // the live costs as they were when the table was set void calib_add(int bucket, int t, double ms, double age); - void apply_provisional(); + void apply_table(); + void hold_table(); // back to the live costs (fixed_ off) for the buckets that have a table + void use_table(); // all sizes calibrated: the table (real costs) decides, fixed_ on int explore_size(int lookup_k, int pad_cap) const; // the size a learning stretch measures next, 0 = none (choose() counts it) int explore_next(int reach, int skip) const; // the smallest size 2..reach (not `skip`) that still needs rounds; counts it; 0 = none bool explore_ok() const; // a forced round counts now (fresh phase, or no state effect) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 04f52a8f92..edef2fae01 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14579,8 +14579,13 @@ int main(int argc, char** argv) { dc_pcie_pending = true; extra += "; PCIe share: refined in this run, then stored"; } - std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request " - "gives the same tokens on every start\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); + if (dc_calib) + std::fprintf(stderr, "strata serve: draft costs: this machine's table is loaded (%s; window sizes %s%s), not used yet: the " + "windows follow live costs until every size is calibrated against real requests\n", + o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); + else + std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request " + "gives the same tokens on every start\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); } else { policy.set_learning(true); dc_learning = true; @@ -20101,8 +20106,10 @@ int main(int argc, char** argv) { std::snprintf(b, sizeof b, "; PCIe share %.2f", cf.pcie_frac); t0 += b; } - std::fprintf(stderr, "strata serve: draft costs: this machine's table is learned (%s); it is fixed from the next request " - "on%s%s\n", t0.c_str(), saved ? "" : " (not saved: ", saved ? "" : (why + "; the next start learns again)").c_str()); + std::fprintf(stderr, "strata serve: draft costs: this machine's table is learned (%s); %s%s%s\n", t0.c_str(), + dc_calib ? "live costs decide until every size is calibrated against real requests, then it is fixed" + : "it is fixed from the next request on", + saved ? "" : " (not saved: ", saved ? "" : (why + "; the next start learns again)").c_str()); } } // --draft-costs, calibration: the real rounds of this request that the sizes still at their learned cost have collected; a size with @@ -20118,6 +20125,9 @@ int main(int argc, char** argv) { saved ? "" : (" (not saved: " + why + ")").c_str()); } dc_calib = policy.calibrating(); + if (!dc_calib && policy.fixed()) + std::fprintf(stderr, "strata serve: draft costs: every size is calibrated; this machine's table decides the windows from the next " + "request on\n"); } // --draft-costs with a table from before the stored PCIe share: once PcieAuto has settled (three readings, or it gave up), its // share goes into the file beside the table and is fixed from the next request; the next start loads it diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 79f4a8cabc..d0cd09a03e 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -407,7 +407,13 @@ DraftPolicy::DraftPolicy(int max_t, double margin) } void DraftPolicy::set_fixed_costs(const double* ms, int n, int bucket) { + if (!fixed_ && !live_saved_) { // the live costs at this point: start_calibration() may hand them back + live_cost_ = cost_; + live_n_ = cost_n_; + live_saved_ = true; + } fixed_ = true; + held_table_ = false; held_.clear(); if (ms == nullptr || n <= 0) return; bucket = std::clamp(bucket, 0, kCtxBuckets - 1); @@ -639,22 +645,13 @@ void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double ro // ---- calibration of a fixed table against real requests (see the header) -void DraftPolicy::apply_provisional() { +void DraftPolicy::apply_table() { + if (!fixed_) return; // a held table: cost_ is the live cost, not touched for (int k = 0; k < kCtxBuckets; ++k) { const int n = fixed_n_[(size_t) k]; if (n <= 0) continue; - double sum = 0.0; - int cnt = 0; - for (int t = 2; t <= n; ++t) - if ((real_[(size_t) k] >> (t - 1) & 1u) && learned_[(size_t) k][(size_t) t] > 0.0) { - sum += real_cost_[(size_t) k][(size_t) t] / learned_[(size_t) k][(size_t) t]; - ++cnt; - } - const double r = cnt > 0 ? sum / cnt : 1.0; - for (int t = 1; t <= n; ++t) { - if (real_[(size_t) k] >> (t - 1) & 1u) cost_[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t]; - else cost_[(size_t) k][(size_t) t] = learned_[(size_t) k][(size_t) t] * (t >= 2 ? r : 1.0); - } + for (int t = 1; t <= n; ++t) + cost_[(size_t) k][(size_t) t] = real_[(size_t) k] >> (t - 1) & 1u ? real_cost_[(size_t) k][(size_t) t] : learned_[(size_t) k][(size_t) t]; for (int t = 2; t <= n; ++t) // more rows never cost less if (cost_[(size_t) k][(size_t) t] < cost_[(size_t) k][(size_t) t - 1]) cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t - 1]; } @@ -670,7 +667,7 @@ void DraftPolicy::start_calibration(bool state_effect, const std::array> (t - 1) & 1u) && !(real_cost_[(size_t) k][(size_t) t] > 0.0)) real_[(size_t) k] &= ~(1u << (t - 1)); - apply_provisional(); + apply_table(); calib_dirty_ = false; calib_on_ = false; for (int k = 0; k < kCtxBuckets; ++k) { @@ -678,6 +675,35 @@ void DraftPolicy::start_calibration(bool state_effect, const std::array> (t - 1) & 1u)) calib_on_ = true; } + if (calib_on_ && fixed_ && live_saved_) hold_table(); // not calibrated: live costs decide, as without a table +} + +void DraftPolicy::hold_table() { + for (int k = 0; k < kCtxBuckets; ++k) { + if (fixed_n_[(size_t) k] <= 0) continue; + cost_[(size_t) k] = live_cost_[(size_t) k]; + cost_n_[(size_t) k] = live_n_[(size_t) k]; + } + fixed_ = false; + held_table_ = true; + held_.clear(); +} + +void DraftPolicy::use_table() { + fixed_ = true; + apply_table(); // every size is real: its real cost + for (int k = 0; k < kCtxBuckets; ++k) { + const int n = fixed_n_[(size_t) k]; + if (n <= 0) continue; + for (int t = 1; t <= kMaxT; ++t) { + const bool in = t <= n && cost_[(size_t) k][(size_t) t] > 0.0; + if (!in) cost_[(size_t) k][(size_t) t] = 0.0; + cost_n_[(size_t) k][(size_t) t] = in ? 1e6 : 0.0; + } + } + fixed_ = true; + held_table_ = false; + held_.clear(); } void DraftPolicy::calib_add(int bucket, int t, double ms, double age) { @@ -715,16 +741,6 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { a = CalAcc{}; // replaced, or disturbed (rounds dropped, collected again) } } - if (replaced) { - std::array, kCtxBuckets> before = cost_; - apply_provisional(); - for (int k = 0; k < kCtxBuckets; ++k) - for (int t = 1; t <= fixed_n_[(size_t) k]; ++t) - if (!(real_[(size_t) k] >> (t - 1) & 1u) && std::fabs(cost_[(size_t) k][(size_t) t] - before[(size_t) k][(size_t) t]) > 0.005) { - std::snprintf(b, sizeof b, "%s%d rows (not real yet) %.2f -> %.2f", report.empty() ? "" : ", ", t, before[(size_t) k][(size_t) t], cost_[(size_t) k][(size_t) t]); - report += b; - } - } for (int k = 0; k < kCtxBuckets; ++k) { const int n = fixed_n_[(size_t) k]; if (n <= 0) continue; @@ -741,6 +757,7 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { for (int k = 0; k < kCtxBuckets; ++k) for (int t = 1; t <= fixed_n_[(size_t) k]; ++t) if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true; + if (held_table_ && !calib_on_) use_table(); // the last size is calibrated: the table decides from the next round on return changed || replaced; } diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 0f9e40c49a..04c552de4c 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -556,22 +556,34 @@ int main() { const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90}; const Cal cal0{}; const Rc rc0{}; - DraftPolicy c(8); + DraftPolicy c(8), live(8); // `live` has no table: a held table must decide exactly like it c.set_fixed_costs(tab, 5, 0); c.start_calibration(false, Real{}, cal0, rc0); - check(c.calibrating() && !c.calib_dirty(), "calib: on after a table is fixed, nothing collected"); - for (int i = 0; i < 15; ++i) c.observe(false, 3, 2, 0, 16.70); + check(c.calibrating() && !c.calib_dirty() && c.table_held() && !c.fixed(), "calib: a table with uncalibrated sizes is held back: live costs, nothing collected yet"); + bool same = true; + for (int i = 0; i < 15; ++i) { + const DraftPolicy::Pick pa = c.choose(i % 3 + 1, 5, 2), pb = live.choose(i % 3 + 1, 5, 2); + same = same && pa.lookup == pb.lookup && pa.t == pb.t && std::fabs(c.cost_ms(3) - live.cost_ms(3)) < 1e-12; + c.observe(false, 3, 2, 0, 16.70); + live.observe(false, 3, 2, 0, 16.70); + } CostFile cf; std::string rep; + check(same && std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && std::fabs(c.cost_ms(4) - live.cost_ms(4)) < 1e-12, + "calib: while held back, picks and costs equal those of a policy without a table (the live cost follows the rounds)"); check(c.calibrate(cf, rep) && rep.empty() && cf.cal[0][3].n == 15, "calib: 15 real rounds are kept, nothing replaced"); - check(std::fabs(c.cost_ms(3) - 16.41) < 1e-9 && std::fabs(c.cost_ms(4) - 18.57) < 1e-9, "calib: under kCalibN rounds every cost stays the learned one"); c.observe(false, 3, 2, 0, 16.70); - check(c.calibrate(cf, rep) && !rep.empty(), "calib: the 16th real round replaces the cost"); - const double r3 = 16.70 / 16.41; - check(std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && (cf.real[0] & 4u) && std::fabs(cf.real_cost[0][3] - 16.70) < 1e-9 && std::fabs(cf.tables[0][2] - 16.41) < 1e-9, - "calib: the size takes the mean, is marked real; the file keeps the learned cost beside it"); - check(std::fabs(c.cost_ms(4) - 18.57 * r3) < 1e-6 && std::fabs(c.cost_ms(5) - 20.90 * r3) < 1e-6 && std::fabs(c.cost_ms(2) - 14.30 * r3) < 1e-6 && std::fabs(c.cost_ms(1) - 12.68) < 1e-9, - "calib: sizes not real yet (2 rows and more) are priced at learned x the real sizes' ratio, size 1 stays"); + check(c.calibrate(cf, rep) && !rep.empty() && (cf.real[0] & 4u) && std::fabs(cf.real_cost[0][3] - 16.70) < 1e-9 && std::fabs(cf.tables[0][2] - 16.41) < 1e-9, + "calib: the 16th real round marks the size real; the file keeps the learned cost beside it"); + check(c.table_held() && !c.fixed() && c.calibrating(), "calib: one real size is not enough: the table stays held back"); + // the other four sizes get their 16 rounds: the table takes over at that request's end, at the real costs + const double rt[5] = {12.90, 14.60, 16.70, 19.90, 21.30}; + for (int t = 1; t <= 5; ++t) + if (t != 3) + for (int i = 0; i < 16; ++i) c.observe(t == 4 || t == 5, t, 1, 0, rt[t - 1]); + check(c.calibrate(cf, rep) && c.fixed() && !c.table_held() && !c.calibrating(), "calib: with the last size calibrated the table is used"); + check(std::fabs(c.cost_ms(1) - 12.90) < 1e-9 && std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && std::fabs(c.cost_ms(4) - 19.90) < 1e-9 && std::fabs(c.cost_ms(5) - 21.30) < 1e-9, + "calib: the real costs decide"); for (int i = 0; i < 40; ++i) c.observe(false, 3, 2, 0, 15.0); check(!c.calib_dirty() && std::fabs(c.cost_ms(3) - 16.70) < 1e-9, "calib: a real size never changes again"); // a lookup size reached once per request: its rounds come across starts through the file @@ -593,10 +605,21 @@ int main() { } check((cd.real[0] & 8u) != 0 && std::fabs(cd.real_cost[0][4] - 18.9) < 1e-9 && cd.cal[0][4].n == 0 && std::fabs(cd.tables[0][3] - 18.57) < 1e-9, "calib: 16 starts of one round each calibrate the size"); - DraftPolicy again(8); // a start from that file: size 4 real, the others provisional at 18.9 / 18.57 + DraftPolicy again(8); // a start from that file: size 4 real, the others not: the table is held back again.set_fixed_costs(tab, 5, 0); again.start_calibration(false, real1, cal1, rc1); - check(std::fabs(again.cost_ms(4) - 18.9) < 1e-9 && std::fabs(again.cost_ms(5) - 20.90 * 18.9 / 18.57) < 1e-6, "calib: a restart gives the same costs"); + check(again.table_held() && !again.fixed() && again.calibrating(), "calib: a restart with sizes still uncalibrated keeps the table held back"); + { // a file with every size real: the table is used from the first round, at the real costs + Real all{}; + all[0] = 31u; + Rc rcall = rc0; + for (int t = 1; t <= 5; ++t) rcall[0][(size_t) t] = tab[t - 1] * 1.03; + DraftPolicy u(8); + u.set_fixed_costs(tab, 5, 0); + u.start_calibration(false, all, cal0, rcall); + check(u.fixed() && !u.table_held() && !u.calibrating() && std::fabs(u.cost_ms(4) - 18.57 * 1.03) < 1e-9 && std::fabs(u.cost_ms(1) - 12.68 * 1.03) < 1e-9, + "calib: a start from a fully calibrated file uses the table at the real costs"); + } // the file round trip: state, real, real cost, cal CostFile w; w.key = "k2"; @@ -634,7 +657,7 @@ int main() { CostFile cg; std::string rg; g.calibrate(cg, rg); - check(rg.empty() && std::fabs(g.cost_ms(2) - 14.30) < 1e-9 && cg.cal[0][2].n == 0 && (cg.real[0] & 2u) == 0, "calib: rounds far above the learned cost are dropped"); + check(rg.empty() && g.table_held() && cg.cal[0][2].n == 0 && (cg.real[0] & 2u) == 0, "calib: rounds far above the learned cost are dropped"); // a size that real requests never reach, and a machine whose real sizes are all 1 row: nothing is scaled DraftPolicy h(8); h.set_fixed_costs(tab, 5, 0); @@ -643,8 +666,7 @@ int main() { CostFile ch; std::string rh; h.calibrate(ch, rh); - check((ch.real[0] & 1u) != 0 && std::fabs(h.cost_ms(1) - 13.0) < 1e-9 && std::fabs(h.cost_ms(2) - 14.30) < 1e-9 && std::fabs(h.cost_ms(5) - 20.90) < 1e-9, - "calib: a real 1-row size scales nothing else"); + check((ch.real[0] & 1u) != 0 && h.table_held() && !h.fixed(), "calib: one real size does not bring the table into use"); } std::printf(g_fail ? "FAIL\n" : "PASS\n"); return g_fail ? 1 : 0; From 669b34a324de58445045af8d6bf803a4206b093a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 04:48:58 +0100 Subject: [PATCH 10/17] spec: a held table is used after 100 requests even when a size is never reached Holding the table back until every size is calibrated would hold it back for good on a machine whose real requests never reach the long lookup sizes (the RTX PRO 6000 table has 12 sizes, the rounds of the sizes 7 to 12 are rare). The number of requests that ran while the table was held back is kept in the table file ("reqs"); after 100 of them the table is used, and a size that real requests have not reached is priced at its learned cost times the mean ratio real / learned of the real sizes of 2 or more rows (the step of the earlier calibration, restored for this case only), a size of 1 row at its learned cost. Calibration of those sizes goes on in use. A start from a file with 100 or more requests uses the table at once. --- include/strata/spec/draft_policy.hpp | 9 +++-- src/program/generate.cpp | 12 +++---- src/spec/draft_policy.cpp | 50 ++++++++++++++++++++++++---- src/spec/draft_policy_test.cpp | 28 +++++++++++++++- 4 files changed, 84 insertions(+), 15 deletions(-) diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index 870eeae714..571b67013b 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -120,6 +120,7 @@ struct CostFile { double cpu_share = -1.0; ///< < 0: none stored double pcie_frac = -1.0; ///< the decode PCIe share PcieAuto settled on; < 0: none stored (a file from before it: refined, then written) /// Calibration against real requests (see DraftPolicy::start_calibration); a file without these lines has none done. + int reqs = 0; ///< requests that ran while the table was held back (DraftPolicy::kCalibReqs ends the holding) bool state_effect = false; ///< the learning stretch showed a load-time effect: only fresh real rounds are counted std::array real{}; ///< bit t-1: the cost of size t is a median of real rounds, no longer the learned one std::array, CostLearner::kCtxBuckets> cal{}; ///< real rounds collected so far for the sizes not yet replaced @@ -231,12 +232,15 @@ public: /// keeps its learned cost. real, cal and real_cost come from the file (CostFile). /// Until every size of the table is real the table is not used: the policy decides with live costs, exactly as without a table (a half-calibrated /// table priced a JSON request 5 % slower than live costs), and only collects the real rounds; once the last size is calibrated the table - /// (the real costs) decides for good. + /// (the real costs) decides for good. A size that real requests do not reach (the long lookup sizes of a big GPU) would hold it back for good, so after + /// kCalibReqs requests the table is used anyway: such a size is priced at its learned cost x the mean (real / learned) of the real + /// sizes of 2 or more rows (a size 1 at its learned cost) until it has its own kCalibN rounds. The count is kept in the file (CostFile::reqs). static constexpr int kCalibN = 16; + static constexpr int kCalibReqs = 100; // requests that may run while the table is held back; then a size not reached keeps a scaled learned cost static constexpr double kCalibLo = 0.85, kCalibHi = 1.30, kCalibOkLo = 0.86, kCalibOkHi = 1.29; void start_calibration(bool state_effect, const std::array& real, const std::array, kCtxBuckets>& cal, - const std::array, kCtxBuckets>& real_cost); + const std::array, kCtxBuckets>& real_cost, int reqs = 0); bool calibrating() const { return calib_on_; } bool calib_dirty() const { return calib_dirty_; } /// While a loaded table still has sizes that are not calibrated (calibrating()), the table is held back: the policy decides with live costs @@ -299,6 +303,7 @@ private: std::array real_{}; std::array, kCtxBuckets> cal_{}; std::array, kCtxBuckets> learned_{}, real_cost_{}; // the table as fixed (learned); the cost of each real size + int reqs_ = 0; // requests that ran while the table was held back (the file keeps it) bool held_table_ = false; // a table is loaded but not used yet: live costs decide (see table_held()) bool live_saved_ = false; std::array, kCtxBuckets> live_cost_{}, live_n_{}; // the live costs as they were when the table was set diff --git a/src/program/generate.cpp b/src/program/generate.cpp index edef2fae01..0674ed003a 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14568,7 +14568,7 @@ int main(int argc, char** argv) { sizes += (sizes.empty() ? "" : ", ") + std::to_string(cf.tables[(size_t) k].size()); } dc_file = cf; - policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost); + policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs); dc_calib = policy.calibrating(); if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share); std::string extra = cf.cpu_share >= 0.0 ? "; CPU prompt share " + std::to_string(cf.cpu_share).substr(0, 4) : ""; @@ -14581,7 +14581,7 @@ int main(int argc, char** argv) { } if (dc_calib) std::fprintf(stderr, "strata serve: draft costs: this machine's table is loaded (%s; window sizes %s%s), not used yet: the " - "windows follow live costs until every size is calibrated against real requests\n", + "windows follow live costs until every size is calibrated against real requests (or 100 requests have run)\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); else std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request " @@ -20090,7 +20090,7 @@ int main(int argc, char** argv) { policy.reset_learning(); dc_learning = false; dc_file = cf; - policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost); + policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs); dc_calib = policy.calibrating(); std::string t0; char b[24]; @@ -20107,14 +20107,14 @@ int main(int argc, char** argv) { t0 += b; } std::fprintf(stderr, "strata serve: draft costs: this machine's table is learned (%s); %s%s%s\n", t0.c_str(), - dc_calib ? "live costs decide until every size is calibrated against real requests, then it is fixed" + dc_calib ? "live costs decide until every size is calibrated against real requests (or 100 requests have run), then it is fixed" : "it is fixed from the next request on", saved ? "" : " (not saved: ", saved ? "" : (why + "; the next start learns again)").c_str()); } } // --draft-costs, calibration: the real rounds of this request that the sizes still at their learned cost have collected; a size with // kCalibN of them takes their mean (the file is rewritten whole, the new cost applies from the next request on, no later change) - if (dc_calib && policy.calib_dirty()) { + if (dc_calib && (policy.calib_dirty() || policy.table_held())) { strata::spec::CostFile cc = dc_file; std::string rep, why; if (policy.calibrate(cc, rep)) { @@ -20126,7 +20126,7 @@ int main(int argc, char** argv) { } dc_calib = policy.calibrating(); if (!dc_calib && policy.fixed()) - std::fprintf(stderr, "strata serve: draft costs: every size is calibrated; this machine's table decides the windows from the next " + std::fprintf(stderr, "strata serve: draft costs: calibration is over; this machine's table decides the windows from the next " "request on\n"); } // --draft-costs with a table from before the stored PCIe share: once PcieAuto has settled (three readings, or it gave up), its diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index d0cd09a03e..7c08354ce5 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -290,6 +290,12 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o out.state_effect = line == "state 1"; continue; } + if (line.rfind("reqs ", 0) == 0) { + int rq = -1; + if (std::sscanf(line.c_str(), "reqs %d", &rq) != 1 || rq < 0 || rq > 1000000) { why = "a malformed request count"; return false; } + out.reqs = rq; + continue; + } if (line.rfind("real ", 0) == 0) { int rb = -1; unsigned m = 0; @@ -366,6 +372,7 @@ bool write_cost_file(const std::string& path, const CostFile& c, std::string& wh f << "\n"; } if (c.state_effect) f << "state 1\n"; + if (c.reqs > 0) f << "reqs " << c.reqs << "\n"; for (int k = 0; k < CostLearner::kCtxBuckets; ++k) { if (c.real[(size_t) k] != 0u) f << "real " << k << " " << c.real[(size_t) k] << "\n"; for (int t = 1; t <= CostLearner::kMaxT; ++t) @@ -650,8 +657,20 @@ void DraftPolicy::apply_table() { for (int k = 0; k < kCtxBuckets; ++k) { const int n = fixed_n_[(size_t) k]; if (n <= 0) continue; - for (int t = 1; t <= n; ++t) - cost_[(size_t) k][(size_t) t] = real_[(size_t) k] >> (t - 1) & 1u ? real_cost_[(size_t) k][(size_t) t] : learned_[(size_t) k][(size_t) t]; + // a size that is not real (real requests never reached it in kCalibReqs requests): its learned cost x the mean (real / learned) of the real sizes of + // 2 or more rows, so it is not left at a price that the sizes next to it have left (size 1 stays); no real size of 2+ rows: its learned cost + double sum = 0.0; + int cnt = 0; + for (int t = 2; t <= n; ++t) + if ((real_[(size_t) k] >> (t - 1) & 1u) && learned_[(size_t) k][(size_t) t] > 0.0) { + sum += real_cost_[(size_t) k][(size_t) t] / learned_[(size_t) k][(size_t) t]; + ++cnt; + } + const double r = cnt > 0 ? sum / cnt : 1.0; + for (int t = 1; t <= n; ++t) { + if (real_[(size_t) k] >> (t - 1) & 1u) cost_[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t]; + else cost_[(size_t) k][(size_t) t] = learned_[(size_t) k][(size_t) t] * (t >= 2 ? r : 1.0); + } for (int t = 2; t <= n; ++t) // more rows never cost less if (cost_[(size_t) k][(size_t) t] < cost_[(size_t) k][(size_t) t - 1]) cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t - 1]; } @@ -659,7 +678,8 @@ void DraftPolicy::apply_table() { void DraftPolicy::start_calibration(bool state_effect, const std::array& real, const std::array, kCtxBuckets>& cal, - const std::array, kCtxBuckets>& real_cost) { + const std::array, kCtxBuckets>& real_cost, int reqs) { + reqs_ = std::max(reqs, 0); calib_fresh_only_ = state_effect; real_ = real; cal_ = cal; @@ -675,7 +695,9 @@ void DraftPolicy::start_calibration(bool state_effect, const std::array> (t - 1) & 1u)) calib_on_ = true; } - if (calib_on_ && fixed_ && live_saved_) hold_table(); // not calibrated: live costs decide, as without a table + // not calibrated: live costs decide, as without a table, until kCalibReqs requests have collected real rounds (a size real requests do not reach + // would hold the table back for good) + if (calib_on_ && reqs_ < kCalibReqs && fixed_ && live_saved_) hold_table(); } void DraftPolicy::hold_table() { @@ -722,8 +744,9 @@ void DraftPolicy::calib_add(int bucket, int t, double ms, double age) { bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { report.clear(); if (!calib_on_ && !calib_dirty_) return false; + if (held_table_) ++reqs_; // a request that ran while the table is held back char b[96]; - bool changed = calib_dirty_, replaced = false; + bool changed = calib_dirty_ || held_table_, replaced = false; // a held table: the request count changed for (int k = 0; k < kCtxBuckets; ++k) { const int n = fixed_n_[(size_t) k]; for (int t = 1; t <= n; ++t) { @@ -741,6 +764,16 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { a = CalAcc{}; // replaced, or disturbed (rounds dropped, collected again) } } + if (replaced && fixed_) { // the table is in use with sizes that were not reached: their scaled costs follow the real sizes + std::array, kCtxBuckets> before = cost_; + apply_table(); + for (int k = 0; k < kCtxBuckets; ++k) + for (int t = 1; t <= fixed_n_[(size_t) k]; ++t) + if (!(real_[(size_t) k] >> (t - 1) & 1u) && std::fabs(cost_[(size_t) k][(size_t) t] - before[(size_t) k][(size_t) t]) > 0.005) { + std::snprintf(b, sizeof b, "%s%d rows (not real yet) %.2f -> %.2f", report.empty() ? "" : ", ", t, before[(size_t) k][(size_t) t], cost_[(size_t) k][(size_t) t]); + report += b; + } + } for (int k = 0; k < kCtxBuckets; ++k) { const int n = fixed_n_[(size_t) k]; if (n <= 0) continue; @@ -752,12 +785,17 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { } } cf.state_effect = calib_fresh_only_; + cf.reqs = reqs_; calib_dirty_ = false; calib_on_ = false; for (int k = 0; k < kCtxBuckets; ++k) for (int t = 1; t <= fixed_n_[(size_t) k]; ++t) if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true; - if (held_table_ && !calib_on_) use_table(); // the last size is calibrated: the table decides from the next round on + // the last size is calibrated, or kCalibReqs requests have not reached the rest: the table decides from the next round on + if (held_table_ && (!calib_on_ || reqs_ >= kCalibReqs)) { + use_table(); + if (calib_on_) report += std::string(report.empty() ? "" : ", ") + "table in use, sizes real requests did not reach keep a scaled learned cost"; + } return changed || replaced; } diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 04c552de4c..81e35dbacd 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -620,11 +620,37 @@ int main() { check(u.fixed() && !u.table_held() && !u.calibrating() && std::fabs(u.cost_ms(4) - 18.57 * 1.03) < 1e-9 && std::fabs(u.cost_ms(1) - 12.68 * 1.03) < 1e-9, "calib: a start from a fully calibrated file uses the table at the real costs"); } + { // sizes that real requests never reach: after kCalibReqs requests the table is used anyway, those sizes at a scaled learned cost + DraftPolicy bd(8); + bd.set_fixed_costs(tab, 5, 0); + bd.start_calibration(false, Real{}, cal0, rc0, 0); + CostFile cb; + std::string rb; + for (int i = 0; i < 16; ++i) bd.observe(false, 2, 1, 0, 14.60); + bd.calibrate(cb, rb); + for (int rq = 2; rq < DraftPolicy::kCalibReqs; ++rq) { + bd.observe(false, 3, 2, 0, 16.70); + bd.calibrate(cb, rb); + } + check(bd.table_held() && !bd.fixed() && cb.reqs == DraftPolicy::kCalibReqs - 1, "budget: held back before the last request of the budget"); + bd.observe(false, 3, 2, 0, 16.70); + const bool wr = bd.calibrate(cb, rb); + const double rr = (14.60 / 14.30 + 16.70 / 16.41) / 2.0; + check(wr && bd.fixed() && !bd.table_held() && cb.reqs == DraftPolicy::kCalibReqs && bd.calibrating(), "budget: after kCalibReqs requests the table is used, calibration goes on"); + check(std::fabs(bd.cost_ms(2) - 14.60) < 1e-9 && std::fabs(bd.cost_ms(3) - 16.70) < 1e-9 && std::fabs(bd.cost_ms(1) - 12.68) < 1e-9 && + std::fabs(bd.cost_ms(4) - 18.57 * rr) < 1e-6 && std::fabs(bd.cost_ms(5) - 20.90 * rr) < 1e-6, + "budget: real sizes at their real cost, sizes not reached at learned x the mean ratio, size 1 at its learned cost"); + DraftPolicy bs(8); // a start from that file: used at once + bs.set_fixed_costs(tab, 5, 0); + bs.start_calibration(false, cb.real, cb.cal, cb.real_cost, cb.reqs); + check(bs.fixed() && !bs.table_held() && std::fabs(bs.cost_ms(4) - 18.57 * rr) < 1e-6, "budget: a start after the budget uses the table at once, same prices"); + } // the file round trip: state, real, real cost, cal CostFile w; w.key = "k2"; w.tables[0].assign(tab, tab + 5); w.state_effect = true; + w.reqs = 7; w.real[0] = 6u; w.real_cost[0][2] = 14.6; w.real_cost[0][3] = 16.7; @@ -633,7 +659,7 @@ int main() { std::string why; check(write_cost_file(path, w, why), "calib file: written"); CostFile r; - check(read_cost_file(path, "k2", r, why) && r.state_effect && r.real[0] == 6u && r.cal[0][4].n == 7 && std::fabs(r.cal[0][4].sum - 131.0) < 1e-3 && r.cal[0][2].n == 0 && + check(read_cost_file(path, "k2", r, why) && r.state_effect && r.reqs == 7 && r.real[0] == 6u && r.cal[0][4].n == 7 && std::fabs(r.cal[0][4].sum - 131.0) < 1e-3 && r.cal[0][2].n == 0 && std::fabs(r.real_cost[0][2] - 14.6) < 1e-9 && std::fabs(r.real_cost[0][3] - 16.7) < 1e-9, "calib file: state, real marks, real costs and collected rounds come back"); std::remove(path.c_str()); From 5f68ad34267d5cc3ca79e63269ea983bc90e32a3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 04:55:07 +0100 Subject: [PATCH 11/17] spec test: a size keeps collecting real rounds after the held table is used Covers the case where the table is used after 100 requests with sizes not yet reached: once such a size is chosen and has 16 real rounds, it becomes real and its cost is replaced. --- src/spec/draft_policy_test.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 81e35dbacd..d28b9c75af 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -644,6 +644,9 @@ int main() { bs.set_fixed_costs(tab, 5, 0); bs.start_calibration(false, cb.real, cb.cal, cb.real_cost, cb.reqs); check(bs.fixed() && !bs.table_held() && std::fabs(bs.cost_ms(4) - 18.57 * rr) < 1e-6, "budget: a start after the budget uses the table at once, same prices"); + for (int i = 0; i < 16; ++i) bd.observe(true, 4, 2, 0, 19.90); // a size the policy now chooses collects its own rounds while the table is in use + check(bd.calibrate(cb, rb) && bd.fixed() && (cb.real[0] & 8u) && std::fabs(bd.cost_ms(4) - 19.90) < 1e-9 && cb.reqs == DraftPolicy::kCalibReqs, + "budget: in use, a size with its own kCalibN rounds becomes real"); } // the file round trip: state, real, real cost, cal CostFile w; From b32583330976bc1d5a080cca2d2520856eb4a737 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 04:58:36 +0100 Subject: [PATCH 12/17] serve: a held draft-cost table leaves the CPU prompt share and the PCIe share live too A table that is held back (live costs decide) also stored a CPU prompt share and a PCIe share, and the engine fixed both at load, so a first start after a fresh table still differed from a start without a table. The stored shares are now fixed when the table takes over (the end of the request in which the last size is calibrated, or the 100th held request), not before. A table that is used at once (every size calibrated, or 100 requests run) fixes them at load as before. The log line at take-over says which case it was. --- src/program/generate.cpp | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 0674ed003a..a86d86487d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14556,6 +14556,11 @@ int main(int argc, char** argv) { bool dc_seen_request = false; bool dc_pcie_pending = false; // a loaded table without a PCIe share: written into it once PcieAuto has settled strata::spec::CostFile dc_file; // that table, as loaded + bool dc_shares_due = false; // the table is held back (live costs): its stored CPU prompt share / PCIe share are fixed when it takes over + auto dc_apply_shares = [&](const strata::spec::CostFile& cf) { + if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share); + if (dc_pcie_ok && cf.pcie_frac >= 0.0) fix_pcie_share(cf.pcie_frac); + }; if (!o.draft_costs.empty() && !policy.fixed()) { dc_key = draft_costs_key(argc, argv, o.draft_costs_key, spec_cost); strata::spec::CostFile cf; @@ -14570,10 +14575,10 @@ int main(int argc, char** argv) { dc_file = cf; policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs); dc_calib = policy.calibrating(); - if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share); + if (policy.table_held()) dc_shares_due = true; // a held table leaves the shares live too: they are fixed when the table takes over + else dc_apply_shares(cf); std::string extra = cf.cpu_share >= 0.0 ? "; CPU prompt share " + std::to_string(cf.cpu_share).substr(0, 4) : ""; if (dc_pcie_ok && cf.pcie_frac >= 0.0) { // PcieAuto's settled share: fixed, no refinement in this run - fix_pcie_share(cf.pcie_frac); extra += "; PCIe share " + std::to_string(cf.pcie_frac).substr(0, 4); } else if (dc_pcie_ok) { // a file from before the stored PCIe share: refined as before, then written into the file dc_pcie_pending = true; @@ -20081,8 +20086,6 @@ int main(int argc, char** argv) { if (dc_pcie_ok) cf.pcie_frac = o.pcie_frac; std::string why; const bool saved = strata::spec::write_cost_file(o.draft_costs, cf, why); - if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share); - if (cf.pcie_frac >= 0.0) fix_pcie_share(cf.pcie_frac); for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k) if (!cf.tables[(size_t) k].empty()) policy.set_fixed_costs(cf.tables[(size_t) k].data(), (int) cf.tables[(size_t) k].size(), k); @@ -20092,6 +20095,8 @@ int main(int argc, char** argv) { dc_file = cf; policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs); dc_calib = policy.calibrating(); + if (policy.table_held()) dc_shares_due = true; // the shares stay live until the table takes over + else dc_apply_shares(cf); std::string t0; char b[24]; for (size_t i = 0; i < cf.tables[0].size(); ++i) { @@ -20115,6 +20120,7 @@ int main(int argc, char** argv) { // --draft-costs, calibration: the real rounds of this request that the sizes still at their learned cost have collected; a size with // kCalibN of them takes their mean (the file is rewritten whole, the new cost applies from the next request on, no later change) if (dc_calib && (policy.calib_dirty() || policy.table_held())) { + const bool dc_was_held = policy.table_held(); strata::spec::CostFile cc = dc_file; std::string rep, why; if (policy.calibrate(cc, rep)) { @@ -20125,9 +20131,14 @@ int main(int argc, char** argv) { saved ? "" : (" (not saved: " + why + ")").c_str()); } dc_calib = policy.calibrating(); - if (!dc_calib && policy.fixed()) - std::fprintf(stderr, "strata serve: draft costs: calibration is over; this machine's table decides the windows from the next " - "request on\n"); + if (dc_was_held && policy.fixed()) { // the table takes over: the stored shares are fixed with it + if (dc_shares_due) dc_apply_shares(dc_file); + dc_shares_due = false; + std::fprintf(stderr, "strata serve: draft costs: %s; this machine's table decides the windows from the next request on%s\n", + dc_calib ? "100 requests have run, sizes real requests did not reach keep a scaled learned cost until they have their own rounds" + : "every size is calibrated", + dc_file.cpu_share >= 0.0 || dc_file.pcie_frac >= 0.0 ? " (the stored shares are fixed with it)" : ""); + } } // --draft-costs with a table from before the stored PCIe share: once PcieAuto has settled (three readings, or it gave up), its // share goes into the file beside the table and is fixed from the next request; the next start loads it @@ -20139,9 +20150,11 @@ int main(int argc, char** argv) { std::string why; const bool saved = strata::spec::write_cost_file(o.draft_costs, cf, why); dc_file = cf; - fix_pcie_share(cf.pcie_frac); - std::fprintf(stderr, "strata serve: draft costs: the PCIe share settled at %.2f; it is %s and fixed from the next request on\n", - cf.pcie_frac, saved ? "stored with this machine's table" : ("not stored (" + why + ")").c_str()); + if (policy.table_held()) dc_shares_due = true; // held back: fixed when the table takes over + else fix_pcie_share(cf.pcie_frac); + std::fprintf(stderr, "strata serve: draft costs: the PCIe share settled at %.2f; it is %s and fixed %s\n", + cf.pcie_frac, saved ? "stored with this machine's table" : ("not stored (" + why + ")").c_str(), + policy.table_held() ? "when the table takes over" : "from the next request on"); } // the last commit (set_commit_async): the session is complete before anything reads or copies it if (!ver.wait_commit(err)) { From 8b225dcb2e096783032a7aeafdef1f0e78e4b019 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 06:13:43 +0100 Subject: [PATCH 13/17] spec: a machine with no draft-cost table builds one from its normal requests, no learning stretch A start with no table file (a new engine, driver, model or setting discards it) ran a learning stretch: forced filler windows to time every window size, for about 1,000 rounds. On a short JSON request that cost 43 % on an RTX PRO 6000 (chat 6 %), and it would hit every user after every release. Now such a start is passive from the first request: live costs decide exactly as without a table, nothing is forced, and the rounds the policy runs anyway are counted per size (only the first seconds of a busy run, the rule the table was tuned on; no detection of a load-time effect is needed). A size is real at 16 own rounds; the file keeps the sums across restarts ("fresh" file, no table lines yet). When every size is real, or after 100 requests, the table takes over: real costs, and for a size never reached the live cost at that moment (the policy's own prior when none was measured); such a size keeps collecting. The CPU prompt share is stored only when a short prompt has measured it. The old one-start stretch stays behind STRATA_DRAFT_COSTS_LEARN=1 for test harnesses (register entry: research, harness switch); the server and the launcher never set it. --- data/settings-register.json | 205 ++++++++++++++++----------- include/strata/spec/draft_policy.hpp | 11 ++ src/program/generate.cpp | 35 ++++- src/spec/draft_policy.cpp | 62 +++++++- src/spec/draft_policy_test.cpp | 76 ++++++++++ 5 files changed, 297 insertions(+), 92 deletions(-) diff --git a/data/settings-register.json b/data/settings-register.json index 4e615fd624..272f8e0f3d 100644 --- a/data/settings-register.json +++ b/data/settings-register.json @@ -277,7 +277,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21182, + "line": 21303, "backend": "cuda-hip", "fn": "getenv" } @@ -384,7 +384,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21171, + "line": 21292, "backend": "cuda-hip", "fn": "getenv" } @@ -425,7 +425,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21170, + "line": 21291, "backend": "cuda-hip", "fn": "getenv" } @@ -460,7 +460,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21172, + "line": 21293, "backend": "cuda-hip", "fn": "getenv" } @@ -2046,7 +2046,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17867, + "line": 17913, "backend": "cuda-hip", "fn": "getenv" } @@ -2080,7 +2080,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17711, + "line": 17757, "backend": "cuda-hip", "fn": "getenv" }, @@ -2159,7 +2159,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14768, + "line": 14807, "backend": "cuda-hip", "fn": "getenv" } @@ -2192,7 +2192,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14770, + "line": 14809, "backend": "cuda-hip", "fn": "getenv" } @@ -2225,7 +2225,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14769, + "line": 14808, "backend": "cuda-hip", "fn": "getenv" } @@ -2552,7 +2552,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14789, + "line": 14828, "backend": "cuda-hip", "fn": "getenv" } @@ -2604,7 +2604,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17931, + "line": 17977, "backend": "cuda-hip", "fn": "getenv" } @@ -2791,7 +2791,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18472, + "line": 18518, "backend": "cuda-hip", "fn": "getenv" }, @@ -3064,13 +3064,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17184, + "line": 17230, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 17317, + "line": 17363, "backend": "cuda-hip", "fn": "getenv" }, @@ -3206,7 +3206,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20547, + "line": 20668, "backend": "cuda-hip", "fn": "getenv" } @@ -4056,7 +4056,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18719, + "line": 18765, "backend": "cuda-hip", "fn": "getenv" }, @@ -4626,13 +4626,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19904, + "line": 19980, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 19904, + "line": 19980, "backend": "cuda-hip", "fn": "getenv" } @@ -5554,7 +5554,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21534, + "line": 21655, "backend": "cuda-hip", "fn": "getenv" } @@ -6028,6 +6028,39 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_DRAFT_COSTS_LEARN", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "src/program/generate.cpp", + "line": 14571, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": "off", + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "research", + "owner": "program", + "note": "TEST / HARNESS SWITCH, not for users: =1 makes a start with no draft-cost table file run the old one-start learning stretch (forced filler windows, a burst of requests) and then use the fixed table; without it a machine with no table builds one from the rounds of its normal requests while live costs decide (no stretch). The server and the launcher never set it.", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_DRAFT_KEEP", "backends": [ @@ -6188,13 +6221,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19776, + "line": 19852, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21751, + "line": 21872, "backend": "cuda-hip", "fn": "getenv" }, @@ -7725,7 +7758,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18658, + "line": 18704, "backend": "cuda-hip", "fn": "getenv" }, @@ -7767,7 +7800,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18673, + "line": 18719, "backend": "cuda-hip", "fn": "getenv" }, @@ -8062,7 +8095,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18002, + "line": 18048, "backend": "cuda-hip", "fn": "env_on" } @@ -13566,7 +13599,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20547, + "line": 20668, "backend": "cuda-hip", "fn": "getenv" } @@ -15024,7 +15057,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17158, + "line": 17204, "backend": "cuda-hip", "fn": "getenv" } @@ -15929,19 +15962,19 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17472, + "line": 17518, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 17512, + "line": 17558, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 18518, + "line": 18564, "backend": "cuda-hip", "fn": "getenv" }, @@ -15997,7 +16030,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17516, + "line": 17562, "backend": "cuda-hip", "fn": "getenv" }, @@ -16202,13 +16235,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18691, + "line": 18737, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21648, + "line": 21769, "backend": "cuda-hip", "fn": "getenv" }, @@ -18983,7 +19016,7 @@ "first_commit": "465cd61dfb", "first_date": "2026-10-12", "since": "v0.1.44", - "last_commit": "4d958fbdbf", + "last_commit": "37f0d8c688", "last_date": "2026-11-12", "status": "default", "owner": "core", @@ -23589,7 +23622,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18435, + "line": 18481, "backend": "cuda-hip", "fn": "getenv" }, @@ -23762,8 +23795,8 @@ "first_commit": "6e31946cbe", "first_date": "2026-11-05", "since": "v0.2.12", - "last_commit": "3d209733d2", - "last_date": "2026-11-08", + "last_commit": "75d91db5e2", + "last_date": "2026-11-12", "status": "default", "owner": "prefill", "note": "[auto] on by default for some GPU architectures only (gfx1151 (Windows) src/core/arch_defaults.cpp:189=1); opt-in elsewhere; the variable overrides it", @@ -25890,11 +25923,11 @@ "doc_mentions": [ "docs/STRIX_HALO.md:156" ], - "first_commit": null, - "first_date": null, + "first_commit": "37f0d8c688", + "first_date": "2026-11-12", "since": null, - "last_commit": null, - "last_date": null, + "last_commit": "75d91db5e2", + "last_date": "2026-11-12", "status": "rollback", "owner": "prefill", "note": "[reviewed] The staged walk's fused group entry for a layer that has no MMQ tile but that the fused kernels cover (UD-Q4_K_XL on gfx1151 without STRATA_MMQ_KQ; every layer of a build without llama.cpp's MMQ): a prompt chunk below the long-prompt floor runs its routed experts on the fused kernels, streaming only the routed ones, instead of the dequantize + FP16 GEMM path. Unset: on for Windows gfx1151 with a layer set that has no MMQ tile and the fused kernels on every layer; off elsewhere. =1 asks for it on any card (research), =0 turns it off (the long-prompt path from 64 tokens on that class). src/prefill/prefill.cpp staged_fo_on, include/strata/prefill/staged_fo_rule.hpp.", @@ -26491,7 +26524,7 @@ }, { "file": "src/program/generate.cpp", - "line": 17993, + "line": 18039, "backend": "cuda-hip", "fn": "getenv" } @@ -26528,7 +26561,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18019, + "line": 18065, "backend": "cuda-hip", "fn": "getenv" } @@ -26596,7 +26629,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18039, + "line": 18085, "backend": "cuda-hip", "fn": "getenv" } @@ -26629,7 +26662,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18257, + "line": 18303, "backend": "cuda-hip", "fn": "getenv" } @@ -26664,7 +26697,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18261, + "line": 18307, "backend": "cuda-hip", "fn": "getenv" } @@ -26744,7 +26777,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18253, + "line": 18299, "backend": "cuda-hip", "fn": "getenv" } @@ -26814,7 +26847,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19033, + "line": 19079, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -26971,7 +27004,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18862, + "line": 18908, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27056,7 +27089,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17341, + "line": 17387, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27096,7 +27129,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18789, + "line": 18835, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27136,7 +27169,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18982, + "line": 19028, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27176,7 +27209,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19029, + "line": 19075, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27255,7 +27288,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19189, + "line": 19235, "backend": "cuda-hip", "fn": "pipe_dbg_env" } @@ -27289,7 +27322,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17344, + "line": 17390, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27329,7 +27362,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17337, + "line": 17383, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27369,7 +27402,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18846, + "line": 18892, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27414,7 +27447,7 @@ }, { "file": "src/program/generate.cpp", - "line": 15611, + "line": 15650, "backend": "cuda-hip", "fn": "getenv" } @@ -28384,7 +28417,7 @@ }, { "file": "src/program/generate.cpp", - "line": 17731, + "line": 17777, "backend": "cuda-hip", "fn": "getenv" } @@ -28683,7 +28716,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18000, + "line": 18046, "backend": "cuda-hip", "fn": "env_on" }, @@ -29571,7 +29604,7 @@ "first_commit": "3e3d69b4d4", "first_date": "2026-09-30", "since": "v0.1.40.1", - "last_commit": "f33e9fa7b8", + "last_commit": "75d91db5e2", "last_date": "2026-11-12", "status": "rollback", "owner": "prefill", @@ -32181,7 +32214,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19621, + "line": 19697, "backend": "cuda-hip", "fn": "getenv" } @@ -32570,7 +32603,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17551, + "line": 17597, "backend": "cuda-hip", "fn": "getenv" } @@ -32607,7 +32640,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17592, + "line": 17638, "backend": "cuda-hip", "fn": "getenv" }, @@ -34474,7 +34507,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18682, + "line": 18728, "backend": "cuda-hip", "fn": "getenv" } @@ -34507,7 +34540,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18685, + "line": 18731, "backend": "cuda-hip", "fn": "getenv" } @@ -34982,7 +35015,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14832, + "line": 14871, "backend": "cuda-hip", "fn": "getenv" } @@ -35338,7 +35371,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17125, + "line": 17171, "backend": "cuda-hip", "fn": "getenv" }, @@ -35386,7 +35419,7 @@ }, { "file": "src/program/generate.cpp", - "line": 17098, + "line": 17144, "backend": "cuda-hip", "fn": "getenv" }, @@ -35550,7 +35583,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21402, + "line": 21523, "backend": "cuda-hip", "fn": "getenv" } @@ -35594,7 +35627,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21450, + "line": 21571, "backend": "cuda-hip", "fn": "getenv" } @@ -35664,7 +35697,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20597, + "line": 20718, "backend": "cuda-hip", "fn": "getenv" } @@ -35943,13 +35976,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18629, + "line": 18675, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21405, + "line": 21526, "backend": "cuda-hip", "fn": "getenv" } @@ -35982,7 +36015,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18630, + "line": 18676, "backend": "cuda-hip", "fn": "getenv" } @@ -36015,7 +36048,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21390, + "line": 21511, "backend": "cuda-hip", "fn": "getenv" } @@ -36048,7 +36081,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21492, + "line": 21613, "backend": "cuda-hip", "fn": "getenv" } @@ -36471,7 +36504,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18001, + "line": 18047, "backend": "cuda-hip", "fn": "env_on" } @@ -36870,7 +36903,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20568, + "line": 20689, "backend": "cuda-hip", "fn": "getenv" }, @@ -37094,7 +37127,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 22182, + "line": 22303, "backend": "hip", "fn": "getenv" } @@ -37536,7 +37569,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20155, + "line": 20276, "backend": "cuda-hip", "fn": "getenv" }, @@ -37617,7 +37650,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20193, + "line": 20314, "backend": "cuda-hip", "fn": "getenv" }, @@ -37871,7 +37904,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18126, + "line": 18172, "backend": "cuda-hip", "fn": "getenv" } @@ -37991,7 +38024,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18043, + "line": 18089, "backend": "cuda-hip", "fn": "getenv" } @@ -39007,7 +39040,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20738, + "line": 20859, "backend": "cuda-hip", "fn": "getenv" }, @@ -39063,13 +39096,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21247, + "line": 21368, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21284, + "line": 21405, "backend": "cuda-hip", "fn": "getenv" }, diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index 571b67013b..d180b644c4 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -121,6 +121,7 @@ struct CostFile { double pcie_frac = -1.0; ///< the decode PCIe share PcieAuto settled on; < 0: none stored (a file from before it: refined, then written) /// Calibration against real requests (see DraftPolicy::start_calibration); a file without these lines has none done. int reqs = 0; ///< requests that ran while the table was held back (DraftPolicy::kCalibReqs ends the holding) + bool fresh = false; ///< a file with no table yet: the real rounds of the sizes are being collected while live costs decide (DraftPolicy::start_passive); no "bucket" lines bool state_effect = false; ///< the learning stretch showed a load-time effect: only fresh real rounds are counted std::array real{}; ///< bit t-1: the cost of size t is a median of real rounds, no longer the learned one std::array, CostLearner::kCtxBuckets> cal{}; ///< real rounds collected so far for the sizes not yet replaced @@ -241,6 +242,14 @@ public: void start_calibration(bool state_effect, const std::array& real, const std::array, kCtxBuckets>& cal, const std::array, kCtxBuckets>& real_cost, int reqs = 0); + /// A machine without a table file builds one from the rounds its live-cost policy runs anyway, with no learning stretch and no forced window: from the + /// first request on the table is held back (live costs decide, exactly as without --draft-costs); only the first kFreshS seconds of a busy run are counted + /// (a machine without a load-time effect just gets fewer samples); a size is real at kCalibN own rounds (the file keeps the sums, so counts survive a + /// restart); when every size up to `n` is real, or after kCalibReqs requests, the table takes over: the real costs, and for a size never reached the live + /// cost at that moment (the policy's own prior when it never measured one); such a size keeps collecting like any size of a table that is in use. + /// cf: the file as read (or an empty one with only the key); n: the table length (top_size()). + void start_passive(const CostFile& cf, int n); + bool passive() const { return passive_; } bool calibrating() const { return calib_on_; } bool calib_dirty() const { return calib_dirty_; } /// While a loaded table still has sizes that are not calibrated (calibrating()), the table is held back: the policy decides with live costs @@ -304,6 +313,8 @@ private: std::array, kCtxBuckets> cal_{}; std::array, kCtxBuckets> learned_{}, real_cost_{}; // the table as fixed (learned); the cost of each real size int reqs_ = 0; // requests that ran while the table was held back (the file keeps it) + bool passive_ = false; // start_passive: no learned table until the take-over (learned_ is zero before it) + void take_over_passive(); // the learned cost of every size not real: the live cost now (a real one keeps its own); then use_table() bool held_table_ = false; // a table is loaded but not used yet: live costs decide (see table_held()) bool live_saved_ = false; std::array, kCtxBuckets> live_cost_{}, live_n_{}; // the live costs as they were when the table was set diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a86d86487d..59d128c08e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14565,7 +14565,29 @@ int main(int argc, char** argv) { dc_key = draft_costs_key(argc, argv, o.draft_costs_key, spec_cost); strata::spec::CostFile cf; std::string why; - if (strata::spec::read_cost_file(o.draft_costs, dc_key, cf, why)) { + // a machine with no table (a new engine, driver, model or setting discards the file) builds one from the rounds of its normal requests, with live + // costs deciding meanwhile: no learning stretch. The old one-start stretch (forced filler windows, a burst of requests) runs only for the test + // harnesses that set STRATA_DRAFT_COSTS_LEARN=1; the server and the launcher never do. + const char* dc_lv = std::getenv("STRATA_DRAFT_COSTS_LEARN"); + const bool dc_force_learn = dc_lv != nullptr && dc_lv[0] == '1'; + const bool dc_read_ok = strata::spec::read_cost_file(o.draft_costs, dc_key, cf, why); + if (dc_read_ok && cf.fresh) { // a file of the passive stretch: the real rounds collected so far + dc_file = cf; + policy.start_passive(cf, policy.top_size()); + dc_calib = true; + std::fprintf(stderr, "strata serve: draft costs: this machine's table is being built from real requests (%s; %d requests so far): live costs " + "decide until every window size has %d own rounds or %d requests have run\n", + o.draft_costs.c_str(), cf.reqs, strata::spec::DraftPolicy::kCalibN, strata::spec::DraftPolicy::kCalibReqs); + } else if (!dc_read_ok && !dc_force_learn) { // no table yet + cf.key = dc_key; + cf.fresh = true; + dc_file = cf; + policy.start_passive(cf, policy.top_size()); + dc_calib = true; + std::fprintf(stderr, "strata serve: draft costs: no table for this machine yet (%s: %s): it is built from real requests, live costs decide " + "until every window size has %d own rounds or %d requests have run\n", + o.draft_costs.c_str(), why.c_str(), strata::spec::DraftPolicy::kCalibN, strata::spec::DraftPolicy::kCalibReqs); + } else if (dc_read_ok) { std::string sizes; for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k) if (!cf.tables[(size_t) k].empty()) { @@ -20120,10 +20142,19 @@ int main(int argc, char** argv) { // --draft-costs, calibration: the real rounds of this request that the sizes still at their learned cost have collected; a size with // kCalibN of them takes their mean (the file is rewritten whole, the new cost applies from the next request on, no later change) if (dc_calib && (policy.calib_dirty() || policy.table_held())) { - const bool dc_was_held = policy.table_held(); + const bool dc_was_held = policy.table_held(), dc_was_passive = policy.passive(); strata::spec::CostFile cc = dc_file; std::string rep, why; if (policy.calibrate(cc, rep)) { + if (dc_was_passive && !policy.passive()) { // the table is made: the shares go in with it, the CPU share only when a short prompt has measured it + if (strata::prefill::Prefill::cpu_share_balancing() && sp.stats().cpu_share_readings > 0) + cc.cpu_share = std::clamp(std::round(sp.stats().cpu_share_balanced * 20.0) / 20.0, 0.05, 0.9); + if (dc_pcie_ok) { + if (!pcie_auto.on) cc.pcie_frac = o.pcie_frac; + else dc_pcie_pending = true; + } + dc_shares_due = true; + } const bool saved = strata::spec::write_cost_file(o.draft_costs, cc, why); dc_file = cc; if (!rep.empty()) diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 7c08354ce5..0d2622dcfd 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -290,6 +290,7 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o out.state_effect = line == "state 1"; continue; } + if (line == "fresh 1") { out.fresh = true; continue; } if (line.rfind("reqs ", 0) == 0) { int rq = -1; if (std::sscanf(line.c_str(), "reqs %d", &rq) != 1 || rq < 0 || rq > 1000000) { why = "a malformed request count"; return false; } @@ -344,7 +345,7 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o out.tables[(size_t) b] = std::move(v); any = true; } - if (!ended || !any) { why = "the file is cut short"; return false; } + if (!ended || (!any && !out.fresh) || (any && out.fresh)) { why = "the file is cut short"; return false; } out.key = key; return true; } @@ -373,6 +374,7 @@ bool write_cost_file(const std::string& path, const CostFile& c, std::string& wh } if (c.state_effect) f << "state 1\n"; if (c.reqs > 0) f << "reqs " << c.reqs << "\n"; + if (c.fresh) f << "fresh 1\n"; for (int k = 0; k < CostLearner::kCtxBuckets; ++k) { if (c.real[(size_t) k] != 0u) f << "real " << k << " " << c.real[(size_t) k] << "\n"; for (int t = 1; t <= CostLearner::kMaxT; ++t) @@ -700,6 +702,47 @@ void DraftPolicy::start_calibration(bool state_effect, const std::array> (t - 1) & 1u) && (!(real_cost_[0][(size_t) t] > 0.0) || t > fixed_n_[0])) real_[0] &= ~(1u << (t - 1)); + reqs_ = std::max(cf.reqs, 0); + held_table_ = true; + fixed_ = false; + calib_on_ = true; + calib_dirty_ = false; +} + +void DraftPolicy::take_over_passive() { + const int bk_was = bk_; + for (int k = 0; k < kCtxBuckets; ++k) { + const int n = fixed_n_[(size_t) k]; + for (int t = 1; t <= n; ++t) { + double v; + if (real_[(size_t) k] >> (t - 1) & 1u) v = real_cost_[(size_t) k][(size_t) t]; // a real size: its own cost + else if (cost_n_[k][t] > 0 && cost_[k][t] > 0.0) v = cost_[k][t]; // a size never reached 16 rounds: what the live estimator has now + else { + bk_ = k; + v = cost_ms(t); // never measured: the policy's own prior, as without a table + bk_ = bk_was; + } + if (!(v > 0.0)) v = t > 1 ? learned_[(size_t) k][(size_t) t - 1] : 1.0; + learned_[(size_t) k][(size_t) t] = v; + } + } + passive_ = false; +} + void DraftPolicy::hold_table() { for (int k = 0; k < kCtxBuckets; ++k) { if (fixed_n_[(size_t) k] <= 0) continue; @@ -732,7 +775,8 @@ void DraftPolicy::calib_add(int bucket, int t, double ms, double age) { if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > fixed_n_[(size_t) bucket]) return; if (real_[(size_t) bucket] >> (t - 1) & 1u) return; if (calib_fresh_only_ && age > CostLearner::kFreshS) return; // the table is what rounds of the first seconds of a busy run cost - const double base = learned_[(size_t) bucket][(size_t) t]; + double base = learned_[(size_t) bucket][(size_t) t]; + if (!(base > 0.0) && passive_) base = cost_n_[bucket][t] > 0 ? cost_[bucket][t] : 0.0; // no learned table: the live cost of the size is the reference if (!(base > 0.0)) return; CalAcc& a = cal_[(size_t) bucket][(size_t) t]; if (a.n >= kCalibN) return; @@ -754,7 +798,7 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { CalAcc& a = cal_[(size_t) k][(size_t) t]; if (a.n < kCalibN) continue; const double v = a.sum / a.n, base = learned_[(size_t) k][(size_t) t]; - if (v >= kCalibOkLo * base && v <= kCalibOkHi * base) { + if (!(base > 0.0) || (v >= kCalibOkLo * base && v <= kCalibOkHi * base)) { // no learned cost (passive): the clamped rounds are taken as they are std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v); report += b; real_cost_[(size_t) k][(size_t) t] = v; @@ -777,7 +821,7 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { for (int k = 0; k < kCtxBuckets; ++k) { const int n = fixed_n_[(size_t) k]; if (n <= 0) continue; - cf.tables[(size_t) k].assign(learned_[(size_t) k].begin() + 1, learned_[(size_t) k].begin() + 1 + n); // the file keeps the learned costs + if (!(passive_ && !fixed_)) cf.tables[(size_t) k].assign(learned_[(size_t) k].begin() + 1, learned_[(size_t) k].begin() + 1 + n); // the file keeps the learned costs cf.real[(size_t) k] = real_[(size_t) k]; for (int t = 0; t <= kMaxT; ++t) { cf.cal[(size_t) k][(size_t) t] = cal_[(size_t) k][(size_t) t]; @@ -786,6 +830,7 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { } cf.state_effect = calib_fresh_only_; cf.reqs = reqs_; + cf.fresh = passive_; calib_dirty_ = false; calib_on_ = false; for (int k = 0; k < kCtxBuckets; ++k) @@ -793,6 +838,15 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true; // the last size is calibrated, or kCalibReqs requests have not reached the rest: the table decides from the next round on if (held_table_ && (!calib_on_ || reqs_ >= kCalibReqs)) { + if (passive_) { + take_over_passive(); + for (int k = 0; k < kCtxBuckets; ++k) { + const int n = fixed_n_[(size_t) k]; + if (n > 0) cf.tables[(size_t) k].assign(learned_[(size_t) k].begin() + 1, learned_[(size_t) k].begin() + 1 + n); + } + cf.fresh = false; + changed = true; + } use_table(); if (calib_on_) report += std::string(report.empty() ? "" : ", ") + "table in use, sizes real requests did not reach keep a scaled learned cost"; } diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index d28b9c75af..7a86fec7df 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -648,6 +648,82 @@ int main() { check(bd.calibrate(cb, rb) && bd.fixed() && (cb.real[0] & 8u) && std::fabs(bd.cost_ms(4) - 19.90) < 1e-9 && cb.reqs == DraftPolicy::kCalibReqs, "budget: in use, a size with its own kCalibN rounds becomes real"); } + { // a machine with no table: built from the real rounds, no learning stretch, live costs decide until the take-over + CostFile c0; + c0.key = "k"; + c0.fresh = true; + DraftPolicy p(8), lv(8); + p.start_passive(c0, 5); + check(p.passive() && p.table_held() && !p.fixed() && p.calibrating() && !p.learning(), "passive: held from the first request, no learning"); + bool same = true; + for (int i = 0; i < 40; ++i) { + const DraftPolicy::Pick pa = p.choose(i % 3 + 1, 5, 2), pb = lv.choose(i % 3 + 1, 5, 2); + same = same && pa.lookup == pb.lookup && pa.t == pb.t && pa.pad == 0 && std::fabs(p.cost_ms(3) - lv.cost_ms(3)) < 1e-12; + p.set_busy_age(2.0); + p.observe(i % 3 == 0, i % 3 + 1, 1, 0, 12.7 + 2.0 * (i % 3)); + lv.observe(i % 3 == 0, i % 3 + 1, 1, 0, 12.7 + 2.0 * (i % 3)); + } + check(same && p.forced_rounds() == 0, "passive: picks and costs equal a policy without a table, no forced window"); + CostFile cp; + std::string rp; + check(p.calibrate(cp, rp) && cp.fresh && cp.tables[0].empty() && cp.reqs == 1, "passive: the file has no table yet, one request counted"); + // only the first seconds of a busy run are counted + DraftPolicy q(8); + q.start_passive(c0, 5); + q.set_busy_age(2.0); + for (int i = 0; i < 10; ++i) q.observe(false, 2, 1, 0, 14.6); + q.set_busy_age(50.0); + for (int i = 0; i < 10; ++i) q.observe(false, 2, 1, 0, 14.6); + CostFile cq; + q.calibrate(cq, rp); + check(cq.cal[0][2].n == 9 && cq.fresh, "passive: rounds late in a busy run are not counted; the first round of a size has no live cost to clamp to"); + // the sums survive a restart: 9 + 7 more = 16 own rounds make the size real + cq.key = "k"; + std::string wpath = "dp_passive_test.costs", wwhy; + check(write_cost_file(wpath, cq, wwhy), "passive: file written"); + CostFile cr; + check(read_cost_file(wpath, "k", cr, wwhy) && cr.fresh && cr.tables[0].empty() && cr.cal[0][2].n == 9, "passive: a file with no table reads back"); + std::remove(wpath.c_str()); + DraftPolicy r(8); + r.start_passive(cr, 5); + r.set_busy_age(1.0); + for (int i = 0; i < 8; ++i) r.observe(false, 2, 1, 0, 14.6); + CostFile cs; + check(r.calibrate(cs, rp) && (cs.real[0] & 2u) && std::fabs(cs.real_cost[0][2] - 14.6) < 1e-9 && r.passive(), "passive: the size is real after 16 own rounds across a restart"); + // take-over by every size real: the real costs, a table in the file + DraftPolicy a(8); + a.start_passive(c0, 5); + a.set_busy_age(1.0); + const double rt[5] = {12.9, 14.6, 16.7, 19.9, 21.3}; + for (int t = 1; t <= 5; ++t) + for (int i = 0; i < 17; ++i) a.observe(t >= 4, t, 1, 0, rt[t - 1]); + CostFile ca; + check(a.calibrate(ca, rp) && a.fixed() && !a.passive() && !a.table_held() && !a.calibrating() && !ca.fresh && ca.tables[0].size() == 5, "passive: every size real: the table takes over, the file has a table"); + check(std::fabs(a.cost_ms(1) - 12.9) < 1e-9 && std::fabs(a.cost_ms(4) - 19.9) < 1e-9 && std::fabs(ca.tables[0][2] - 16.7) < 1e-9, "passive: the real costs decide, the file keeps them as the table"); + // take-over after kCalibReqs requests: a size never reached takes the live cost, a never measured one the policy's prior + DraftPolicy b(8), lb(8); + b.start_passive(c0, 5); + b.set_busy_age(1.0); + for (int i = 0; i < 17; ++i) { + b.observe(false, 2, 1, 0, 14.6); + lb.observe(false, 2, 1, 0, 14.6); + } + for (int i = 0; i < 6; ++i) { + b.observe(true, 4, 2, 0, 19.9); + lb.observe(true, 4, 2, 0, 19.9); + } + CostFile cb2; + for (int rq = 0; rq < DraftPolicy::kCalibReqs; ++rq) { + b.observe(false, 2, 1, 0, 14.6); + b.calibrate(cb2, rp); + } + check(b.fixed() && !b.passive() && cb2.reqs == DraftPolicy::kCalibReqs && cb2.tables[0].size() == 5, "passive: after kCalibReqs requests the table takes over"); + check(std::fabs(cb2.tables[0][1] - 14.6) < 1e-9 && std::fabs(cb2.tables[0][3] - 19.9) < 1e-9 && std::fabs(cb2.tables[0][2] - lb.cost_ms(3)) < 0.1 && std::fabs(b.cost_ms(4) - 19.9) < 1e-9, + "passive: real size 2 at its real cost, size 4 at its live cost, size 3 (never measured) at the policy's prior"); + for (int i = 0; i < 17; ++i) b.observe(true, 4, 2, 0, 20.1); // the unreached size keeps collecting + CostFile cb3 = cb2; + check(b.calibrate(cb3, rp) && (cb3.real[0] & 8u) && std::fabs(b.cost_ms(4) - (5 * 19.9 + 11 * 20.1) / 16.0) < 1e-6, "passive: after the take-over a size still collects and becomes real at 16 own rounds"); + } // the file round trip: state, real, real cost, cal CostFile w; w.key = "k2"; From 4e818231af1bba682e4a3bbec1651e05565295ca Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 06:37:40 +0100 Subject: [PATCH 14/17] spec: log line of a size calibrated without a learned cost says "real", not "0.00 ->" The engine's calibration log line printed "3 rows 0.00 -> 16.85" for a size of a table that is being built from real requests (no learned cost yet). It now prints "3 rows real 16.85". Text of one log line only; no decision or file changes. --- src/spec/draft_policy.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index 0d2622dcfd..d1706d93ae 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -799,7 +799,8 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { if (a.n < kCalibN) continue; const double v = a.sum / a.n, base = learned_[(size_t) k][(size_t) t]; if (!(base > 0.0) || (v >= kCalibOkLo * base && v <= kCalibOkHi * base)) { // no learned cost (passive): the clamped rounds are taken as they are - std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v); + if (base > 0.0) std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v); + else std::snprintf(b, sizeof b, "%s%d rows real %.2f", report.empty() ? "" : ", ", t, v); report += b; real_cost_[(size_t) k][(size_t) t] = v; real_[(size_t) k] |= 1u << (t - 1); From 84e11a773241c030a64ca04500d5b1659d919e26 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 08:56:40 +0100 Subject: [PATCH 15/17] spec: warm every verify window width once before the first request; log text of a taken-over table A window width builds its graph / pipeline on its first run. A width the policy first picks inside a long request paid that cost there: on the M5 Max with IQ3_S the first five-row lookup round cost 37 ms instead of 25 ms in 5 of 8 launches of the table arm, because the release and the live costs happen to run one five-row round in the first (untimed) request. serve now runs one dummy window per allowed width 1..S before the first request is read, then session_zero() as a request that reuses nothing does; no checkpoint, conversation entry, RNG draw, policy sample or statistic is touched. Single-stage, non-batch, non-pipelined serve only. STRATA_WINDOW_WARM=0 turns it off (research switch, in the settings register). The engine prints the ms of every width and the total. The load line of a table that is in use but still collects sizes no longer says "not used yet" (policy.table_held() picks the text). --- data/settings-register.json | 184 +++++++++++++++++++++--------------- src/program/generate.cpp | 41 +++++++- 2 files changed, 146 insertions(+), 79 deletions(-) diff --git a/data/settings-register.json b/data/settings-register.json index 272f8e0f3d..d9472ce9f7 100644 --- a/data/settings-register.json +++ b/data/settings-register.json @@ -277,7 +277,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21303, + "line": 21342, "backend": "cuda-hip", "fn": "getenv" } @@ -384,7 +384,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21292, + "line": 21331, "backend": "cuda-hip", "fn": "getenv" } @@ -425,7 +425,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21291, + "line": 21330, "backend": "cuda-hip", "fn": "getenv" } @@ -460,7 +460,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21293, + "line": 21332, "backend": "cuda-hip", "fn": "getenv" } @@ -2046,7 +2046,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17913, + "line": 17952, "backend": "cuda-hip", "fn": "getenv" } @@ -2080,7 +2080,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17757, + "line": 17796, "backend": "cuda-hip", "fn": "getenv" }, @@ -2159,7 +2159,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14807, + "line": 14811, "backend": "cuda-hip", "fn": "getenv" } @@ -2192,7 +2192,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14809, + "line": 14813, "backend": "cuda-hip", "fn": "getenv" } @@ -2225,7 +2225,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14808, + "line": 14812, "backend": "cuda-hip", "fn": "getenv" } @@ -2552,7 +2552,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14828, + "line": 14832, "backend": "cuda-hip", "fn": "getenv" } @@ -2604,7 +2604,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17977, + "line": 18016, "backend": "cuda-hip", "fn": "getenv" } @@ -2791,7 +2791,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18518, + "line": 18557, "backend": "cuda-hip", "fn": "getenv" }, @@ -3064,13 +3064,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17230, + "line": 17269, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 17363, + "line": 17402, "backend": "cuda-hip", "fn": "getenv" }, @@ -3206,7 +3206,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20668, + "line": 20707, "backend": "cuda-hip", "fn": "getenv" } @@ -4056,7 +4056,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18765, + "line": 18804, "backend": "cuda-hip", "fn": "getenv" }, @@ -4626,13 +4626,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19980, + "line": 20019, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 19980, + "line": 20019, "backend": "cuda-hip", "fn": "getenv" } @@ -5554,7 +5554,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21655, + "line": 21694, "backend": "cuda-hip", "fn": "getenv" } @@ -6221,13 +6221,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19852, + "line": 19891, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21872, + "line": 21911, "backend": "cuda-hip", "fn": "getenv" }, @@ -7758,7 +7758,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18704, + "line": 18743, "backend": "cuda-hip", "fn": "getenv" }, @@ -7800,7 +7800,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18719, + "line": 18758, "backend": "cuda-hip", "fn": "getenv" }, @@ -8095,7 +8095,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18048, + "line": 18087, "backend": "cuda-hip", "fn": "env_on" } @@ -13599,7 +13599,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20668, + "line": 20707, "backend": "cuda-hip", "fn": "getenv" } @@ -15057,7 +15057,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17204, + "line": 17243, "backend": "cuda-hip", "fn": "getenv" } @@ -15962,19 +15962,19 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17518, + "line": 17557, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 17558, + "line": 17597, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 18564, + "line": 18603, "backend": "cuda-hip", "fn": "getenv" }, @@ -16030,7 +16030,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17562, + "line": 17601, "backend": "cuda-hip", "fn": "getenv" }, @@ -16235,13 +16235,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18737, + "line": 18776, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21769, + "line": 21808, "backend": "cuda-hip", "fn": "getenv" }, @@ -23622,7 +23622,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18481, + "line": 18520, "backend": "cuda-hip", "fn": "getenv" }, @@ -26524,7 +26524,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18039, + "line": 18078, "backend": "cuda-hip", "fn": "getenv" } @@ -26561,7 +26561,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18065, + "line": 18104, "backend": "cuda-hip", "fn": "getenv" } @@ -26629,7 +26629,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18085, + "line": 18124, "backend": "cuda-hip", "fn": "getenv" } @@ -26662,7 +26662,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18303, + "line": 18342, "backend": "cuda-hip", "fn": "getenv" } @@ -26697,7 +26697,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18307, + "line": 18346, "backend": "cuda-hip", "fn": "getenv" } @@ -26777,7 +26777,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18299, + "line": 18338, "backend": "cuda-hip", "fn": "getenv" } @@ -26847,7 +26847,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19079, + "line": 19118, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27004,7 +27004,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18908, + "line": 18947, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27089,7 +27089,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17387, + "line": 17426, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27129,7 +27129,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18835, + "line": 18874, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27169,7 +27169,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19028, + "line": 19067, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27209,7 +27209,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19075, + "line": 19114, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27288,7 +27288,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19235, + "line": 19274, "backend": "cuda-hip", "fn": "pipe_dbg_env" } @@ -27322,7 +27322,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17390, + "line": 17429, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27362,7 +27362,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17383, + "line": 17422, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27402,7 +27402,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18892, + "line": 18931, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27447,7 +27447,7 @@ }, { "file": "src/program/generate.cpp", - "line": 15650, + "line": 15654, "backend": "cuda-hip", "fn": "getenv" } @@ -28417,7 +28417,7 @@ }, { "file": "src/program/generate.cpp", - "line": 17777, + "line": 17816, "backend": "cuda-hip", "fn": "getenv" } @@ -28716,7 +28716,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18046, + "line": 18085, "backend": "cuda-hip", "fn": "env_on" }, @@ -32214,7 +32214,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19697, + "line": 19736, "backend": "cuda-hip", "fn": "getenv" } @@ -32603,7 +32603,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17597, + "line": 17636, "backend": "cuda-hip", "fn": "getenv" } @@ -32640,7 +32640,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17638, + "line": 17677, "backend": "cuda-hip", "fn": "getenv" }, @@ -34507,7 +34507,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18728, + "line": 18767, "backend": "cuda-hip", "fn": "getenv" } @@ -34540,7 +34540,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18731, + "line": 18770, "backend": "cuda-hip", "fn": "getenv" } @@ -35015,7 +35015,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14871, + "line": 14875, "backend": "cuda-hip", "fn": "getenv" } @@ -35371,7 +35371,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17171, + "line": 17210, "backend": "cuda-hip", "fn": "getenv" }, @@ -35419,7 +35419,7 @@ }, { "file": "src/program/generate.cpp", - "line": 17144, + "line": 17183, "backend": "cuda-hip", "fn": "getenv" }, @@ -35583,7 +35583,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21523, + "line": 21562, "backend": "cuda-hip", "fn": "getenv" } @@ -35627,7 +35627,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21571, + "line": 21610, "backend": "cuda-hip", "fn": "getenv" } @@ -35697,7 +35697,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20718, + "line": 20757, "backend": "cuda-hip", "fn": "getenv" } @@ -35976,13 +35976,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18675, + "line": 18714, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21526, + "line": 21565, "backend": "cuda-hip", "fn": "getenv" } @@ -36015,7 +36015,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18676, + "line": 18715, "backend": "cuda-hip", "fn": "getenv" } @@ -36048,7 +36048,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21511, + "line": 21550, "backend": "cuda-hip", "fn": "getenv" } @@ -36081,7 +36081,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21613, + "line": 21652, "backend": "cuda-hip", "fn": "getenv" } @@ -36504,7 +36504,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18047, + "line": 18086, "backend": "cuda-hip", "fn": "env_on" } @@ -36903,7 +36903,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20689, + "line": 20728, "backend": "cuda-hip", "fn": "getenv" }, @@ -37127,7 +37127,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 22303, + "line": 22342, "backend": "hip", "fn": "getenv" } @@ -37569,7 +37569,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20276, + "line": 20315, "backend": "cuda-hip", "fn": "getenv" }, @@ -37650,7 +37650,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20314, + "line": 20353, "backend": "cuda-hip", "fn": "getenv" }, @@ -37904,7 +37904,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18172, + "line": 18211, "backend": "cuda-hip", "fn": "getenv" } @@ -38024,7 +38024,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18089, + "line": 18128, "backend": "cuda-hip", "fn": "getenv" } @@ -39040,7 +39040,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20859, + "line": 20898, "backend": "cuda-hip", "fn": "getenv" }, @@ -39096,13 +39096,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21368, + "line": 21407, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21405, + "line": 21444, "backend": "cuda-hip", "fn": "getenv" }, @@ -40834,6 +40834,34 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_WINDOW_WARM", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "src/program/generate.cpp", + "line": 15936, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "status": "research", + "owner": "program", + "note": "TEST/HARNESS SWITCH, not for users: =0 turns off the window warm-up (one dummy verify window per allowed width 1..S before the first request is read, then session_zero); default on. For the A/B that shows the warm-up changes no token.", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_WMMA_BF16", "backends": [ diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 59d128c08e..8e85433760 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14606,10 +14606,14 @@ int main(int argc, char** argv) { dc_pcie_pending = true; extra += "; PCIe share: refined in this run, then stored"; } - if (dc_calib) + if (dc_calib && policy.table_held()) std::fprintf(stderr, "strata serve: draft costs: this machine's table is loaded (%s; window sizes %s%s), not used yet: the " "windows follow live costs until every size is calibrated against real requests (or 100 requests have run)\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); + else if (dc_calib) + std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s); sizes real requests have not " + "reached yet keep collecting rounds and change the table once when they have their own\n", + o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); else std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request " "gives the same tokens on every start\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str()); @@ -15922,6 +15926,41 @@ int main(int argc, char** argv) { if (!pump(false)) return false; return pmtp_settle(); }; + // ---- window warm-up (lane DRAFT-COSTS): the first run of a window width builds its graph / pipeline (srv118 CUDA: a capture; Metal: the first execution), so a + // width that the policy first picks inside a long request pays it there (M5 Max, IQ3_S: +60 ms on the first five-row lookup round, in the timed code request in 5 of 8 launches + // with a table, because the release and the live costs happen to pay it in request 1). One dummy window per allowed width 1..S, once, before the first request is read; it + // changes nothing a request can see: the windows write K/V cells 0..T-1 and the recurrent state of the session, and session_zero() below zeroes the session exactly as a request + // that reuses nothing does (the engine's state after session_init); no checkpoint, conversation entry, RNG draw, policy sample or statistic is touched (the policy's observe_* + // calls live in the decode loop); the expert cache may page in what the dummy token routes to (speed only). STRATA_WINDOW_WARM=0: off (research switch). + { + static const bool warm_off = [] { const char* v = std::getenv("STRATA_WINDOW_WARM"); return v != nullptr && v[0] == '0'; }(); + if (!warm_off && S >= 2 && n_stages == 1 && !batch_on() && !piped) { + const Clock::time_point w0 = Clock::now(); + std::vector wtok((size_t) S, 1), wout((size_t) S + 1, 0); + std::string werr, wlist; + bool wok = true; + for (int t = 1; t <= S && wok; ++t) { + if (!policy.allowed(t)) continue; + const Clock::time_point t0 = Clock::now(); + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + wok = ver.run(t, wtok.data(), 0, win_pool_fn, win_pool_user, wout.data(), werr) && !drive.d.failed; + char wb[48]; + std::snprintf(wb, sizeof wb, "%s%d:%.0f", wlist.empty() ? "" : " ", t, + std::chrono::duration(Clock::now() - t0).count()); + wlist += wb; + } + strata::core::session_zero(ss, g, nullptr, main_cs); + cudaStreamSynchronize(main_stream); + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + std::fprintf(stderr, "strata serve: window warm-up: ms per width %s, total %.0f ms%s%s\n", wlist.c_str(), + std::chrono::duration(Clock::now() - w0).count(), wok ? "" : "; a window failed: ", + wok ? "" : werr.c_str()); + } + } for (;;) { line_drain_ms = 0.0; strata::core::manifest::instance().flush_if_dirty("request"); // STRATA_MANIFEST: what the last request added (a no-op when off) From 94485016356ac1bc5dc8711cb66ca622cc2b8ba4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 09:23:03 +0100 Subject: [PATCH 16/17] spec: a real draft-cost price is the median of its 16 rounds, the monotone guard lowers an outlier; the window warm-up runs before READY srv118 JSON lost 2.4 % (10 of 12 pairs) with the passive table. A/B with hand-edited copies of the table as taken over (par/dc/w5c): the cause was the real price of 2 rows, 20.08 ms instead of about 8.3. The old "more rows never cost less" pass only raised: that one price became the price of every size from 2 to 7 rows and the policy took 12-row windows. Setting 2 rows to 8.5 ms brought the window counts and the speed back (JSON +2.4 % against off), setting sizes 7-12 to the earlier values did not. - A size's real price is now the median of its 16 collected rounds (CalAcc keeps the rounds, "cal b t n sum v1..vn" in the file; a line without them keeps the mean). A cold first-use round, a stall or another process no longer moves it. - The guard in apply_table lowers from the trusted side: a guessed size, or a real size below another real size, is lowered to the price of the next larger size first; a real size above an unreached next size is kept and that guess is lifted to it. The Q2_0 4-row / 5-row and the IQ3_S 4-row / 5-row inversions of the taken-over files and the srv118 2-row outlier are fixtures of the unit test (179 of 179). - The window warm-up (one dummy verify window per allowed width, then session_zero) now runs before the READY line, from the options (lookup_size_mask), single-stage serve without --batch. --- data/settings-register.json | 168 +++++++++++++-------------- include/strata/spec/draft_policy.hpp | 8 +- src/program/generate.cpp | 72 ++++++------ src/spec/draft_policy.cpp | 55 +++++++-- src/spec/draft_policy_test.cpp | 121 ++++++++++++++++++- 5 files changed, 296 insertions(+), 128 deletions(-) diff --git a/data/settings-register.json b/data/settings-register.json index d9472ce9f7..3b34ee2202 100644 --- a/data/settings-register.json +++ b/data/settings-register.json @@ -277,7 +277,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21342, + "line": 21344, "backend": "cuda-hip", "fn": "getenv" } @@ -384,7 +384,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21331, + "line": 21333, "backend": "cuda-hip", "fn": "getenv" } @@ -425,7 +425,7 @@ }, { "file": "src/program/generate.cpp", - "line": 21330, + "line": 21332, "backend": "cuda-hip", "fn": "getenv" } @@ -460,7 +460,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21332, + "line": 21334, "backend": "cuda-hip", "fn": "getenv" } @@ -2046,7 +2046,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17952, + "line": 17954, "backend": "cuda-hip", "fn": "getenv" } @@ -2080,7 +2080,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17796, + "line": 17798, "backend": "cuda-hip", "fn": "getenv" }, @@ -2159,7 +2159,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14811, + "line": 14848, "backend": "cuda-hip", "fn": "getenv" } @@ -2192,7 +2192,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14813, + "line": 14850, "backend": "cuda-hip", "fn": "getenv" } @@ -2225,7 +2225,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14812, + "line": 14849, "backend": "cuda-hip", "fn": "getenv" } @@ -2552,7 +2552,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14832, + "line": 14869, "backend": "cuda-hip", "fn": "getenv" } @@ -2604,7 +2604,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18016, + "line": 18018, "backend": "cuda-hip", "fn": "getenv" } @@ -2791,7 +2791,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18557, + "line": 18559, "backend": "cuda-hip", "fn": "getenv" }, @@ -3064,13 +3064,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17269, + "line": 17271, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 17402, + "line": 17404, "backend": "cuda-hip", "fn": "getenv" }, @@ -3206,7 +3206,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20707, + "line": 20709, "backend": "cuda-hip", "fn": "getenv" } @@ -4056,7 +4056,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18804, + "line": 18806, "backend": "cuda-hip", "fn": "getenv" }, @@ -4626,13 +4626,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20019, + "line": 20021, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 20019, + "line": 20021, "backend": "cuda-hip", "fn": "getenv" } @@ -5554,7 +5554,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21694, + "line": 21696, "backend": "cuda-hip", "fn": "getenv" } @@ -6036,7 +6036,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14571, + "line": 14608, "backend": "cuda-hip", "fn": "getenv" } @@ -6069,13 +6069,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14532, + "line": 14569, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 14532, + "line": 14569, "backend": "cuda-hip", "fn": "getenv" } @@ -6108,7 +6108,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14531, + "line": 14568, "backend": "cuda-hip", "fn": "getenv" } @@ -6221,13 +6221,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19891, + "line": 19893, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21911, + "line": 21913, "backend": "cuda-hip", "fn": "getenv" }, @@ -7758,7 +7758,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18743, + "line": 18745, "backend": "cuda-hip", "fn": "getenv" }, @@ -7800,7 +7800,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18758, + "line": 18760, "backend": "cuda-hip", "fn": "getenv" }, @@ -8095,7 +8095,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18087, + "line": 18089, "backend": "cuda-hip", "fn": "env_on" } @@ -13599,7 +13599,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20707, + "line": 20709, "backend": "cuda-hip", "fn": "getenv" } @@ -15057,7 +15057,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17243, + "line": 17245, "backend": "cuda-hip", "fn": "getenv" } @@ -15962,19 +15962,19 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17557, + "line": 17559, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 17597, + "line": 17599, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 18603, + "line": 18605, "backend": "cuda-hip", "fn": "getenv" }, @@ -16030,7 +16030,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17601, + "line": 17603, "backend": "cuda-hip", "fn": "getenv" }, @@ -16235,13 +16235,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18776, + "line": 18778, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21808, + "line": 21810, "backend": "cuda-hip", "fn": "getenv" }, @@ -23622,7 +23622,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18520, + "line": 18522, "backend": "cuda-hip", "fn": "getenv" }, @@ -26524,7 +26524,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18078, + "line": 18080, "backend": "cuda-hip", "fn": "getenv" } @@ -26561,7 +26561,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18104, + "line": 18106, "backend": "cuda-hip", "fn": "getenv" } @@ -26629,7 +26629,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18124, + "line": 18126, "backend": "cuda-hip", "fn": "getenv" } @@ -26662,7 +26662,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18342, + "line": 18344, "backend": "cuda-hip", "fn": "getenv" } @@ -26697,7 +26697,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18346, + "line": 18348, "backend": "cuda-hip", "fn": "getenv" } @@ -26777,7 +26777,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18338, + "line": 18340, "backend": "cuda-hip", "fn": "getenv" } @@ -26847,7 +26847,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19118, + "line": 19120, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27004,7 +27004,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18947, + "line": 18949, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27089,7 +27089,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17426, + "line": 17428, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27129,7 +27129,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18874, + "line": 18876, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27169,7 +27169,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19067, + "line": 19069, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27209,7 +27209,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19114, + "line": 19116, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27288,7 +27288,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19274, + "line": 19276, "backend": "cuda-hip", "fn": "pipe_dbg_env" } @@ -27322,7 +27322,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17429, + "line": 17431, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27362,7 +27362,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17422, + "line": 17424, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27402,7 +27402,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18931, + "line": 18933, "backend": "cuda-hip", "fn": "pipe_dbg_env" }, @@ -27447,7 +27447,7 @@ }, { "file": "src/program/generate.cpp", - "line": 15654, + "line": 15691, "backend": "cuda-hip", "fn": "getenv" } @@ -28417,7 +28417,7 @@ }, { "file": "src/program/generate.cpp", - "line": 17816, + "line": 17818, "backend": "cuda-hip", "fn": "getenv" } @@ -28716,7 +28716,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18085, + "line": 18087, "backend": "cuda-hip", "fn": "env_on" }, @@ -32214,7 +32214,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 19736, + "line": 19738, "backend": "cuda-hip", "fn": "getenv" } @@ -32603,7 +32603,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17636, + "line": 17638, "backend": "cuda-hip", "fn": "getenv" } @@ -32640,7 +32640,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17677, + "line": 17679, "backend": "cuda-hip", "fn": "getenv" }, @@ -34507,7 +34507,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18767, + "line": 18769, "backend": "cuda-hip", "fn": "getenv" } @@ -34540,7 +34540,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18770, + "line": 18772, "backend": "cuda-hip", "fn": "getenv" } @@ -35015,7 +35015,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14875, + "line": 14912, "backend": "cuda-hip", "fn": "getenv" } @@ -35371,7 +35371,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 17210, + "line": 17212, "backend": "cuda-hip", "fn": "getenv" }, @@ -35419,7 +35419,7 @@ }, { "file": "src/program/generate.cpp", - "line": 17183, + "line": 17185, "backend": "cuda-hip", "fn": "getenv" }, @@ -35577,13 +35577,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 14534, + "line": 14571, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21562, + "line": 21564, "backend": "cuda-hip", "fn": "getenv" } @@ -35627,7 +35627,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21610, + "line": 21612, "backend": "cuda-hip", "fn": "getenv" } @@ -35697,7 +35697,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20757, + "line": 20759, "backend": "cuda-hip", "fn": "getenv" } @@ -35976,13 +35976,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18714, + "line": 18716, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21565, + "line": 21567, "backend": "cuda-hip", "fn": "getenv" } @@ -36015,7 +36015,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18715, + "line": 18717, "backend": "cuda-hip", "fn": "getenv" } @@ -36048,7 +36048,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21550, + "line": 21552, "backend": "cuda-hip", "fn": "getenv" } @@ -36081,7 +36081,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21652, + "line": 21654, "backend": "cuda-hip", "fn": "getenv" } @@ -36504,7 +36504,7 @@ }, { "file": "src/program/generate.cpp", - "line": 18086, + "line": 18088, "backend": "cuda-hip", "fn": "env_on" } @@ -36903,7 +36903,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20728, + "line": 20730, "backend": "cuda-hip", "fn": "getenv" }, @@ -37127,7 +37127,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 22342, + "line": 22344, "backend": "hip", "fn": "getenv" } @@ -37569,7 +37569,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 20315, + "line": 20317, "backend": "cuda-hip", "fn": "getenv" }, @@ -37650,7 +37650,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20353, + "line": 20355, "backend": "cuda-hip", "fn": "getenv" }, @@ -37904,7 +37904,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18211, + "line": 18213, "backend": "cuda-hip", "fn": "getenv" } @@ -38024,7 +38024,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 18128, + "line": 18130, "backend": "cuda-hip", "fn": "getenv" } @@ -39040,7 +39040,7 @@ }, { "file": "src/program/generate.cpp", - "line": 20898, + "line": 20900, "backend": "cuda-hip", "fn": "getenv" }, @@ -39096,13 +39096,13 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 21407, + "line": 21409, "backend": "cuda-hip", "fn": "getenv" }, { "file": "src/program/generate.cpp", - "line": 21444, + "line": 21446, "backend": "cuda-hip", "fn": "getenv" }, @@ -40842,7 +40842,7 @@ "reads": [ { "file": "src/program/generate.cpp", - "line": 15936, + "line": 14518, "backend": "cuda-hip", "fn": "getenv" } diff --git a/include/strata/spec/draft_policy.hpp b/include/strata/spec/draft_policy.hpp index d180b644c4..882f4fa5cd 100644 --- a/include/strata/spec/draft_policy.hpp +++ b/include/strata/spec/draft_policy.hpp @@ -109,10 +109,16 @@ private: /// share <0..1> (optional: the CPU prompt share learned on this machine, src/prefill/prefill.cpp) /// pcie <0..1> (optional: the decode PCIe share PcieAuto settled on, src/program/generate.cpp) /// end -/// The real rounds of one size seen since the table was learned: n rounds, their sum in ms (each clamped to [kCalibLo, kCalibHi] x the learned cost). +/// The real rounds of one size seen since the table was learned: n rounds, their sum in ms (each clamped to [kCalibLo, kCalibHi] x the learned cost), and the +/// rounds themselves (up to kVals): the size's real price is their MEDIAN (a cold or stalled round, a first use, another process, moves a mean but not a median). +/// A file line from before the values ("cal b t n sum" without them) has nv = 0: its price is the mean as before. +/// cal [ ... ] struct CalAcc { + static constexpr int kVals = 16; int n = 0; double sum = 0.0; + int nv = 0; ///< how many of vals hold a round (== n when every round is kept) + std::array vals{}; }; struct CostFile { std::string key; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 8e85433760..459f70e2b2 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14508,6 +14508,43 @@ int main(int argc, char** argv) { strata::core::pin_reserve_release_hard(); // the load is over: nothing else needs the headroom strata::core::kfd_settle::settle_before_ready(); // integrated gfx11 under Linux: until the kernel has stopped moving the registered arena (nothing elsewhere) strata::core::manifest::instance().write("ready"); // STRATA_MANIFEST (a no-op unless it is set) + // ---- window warm-up (lane DRAFT-COSTS): the first run of a window width builds its graph / pipeline (srv118 CUDA: a capture; Metal: the first execution), so a + // width that the policy first picks inside a long request pays it there (M5 Max, IQ3_S: +60 ms on the first five-row lookup round, in the timed code request in 5 of 8 launches + // with a table, because the release and the live costs happen to pay it in request 1). One dummy window per allowed width 1..S, once, before the first request is read; it + // changes nothing a request can see: the windows write K/V cells 0..T-1 and the recurrent state of the session, and session_zero() below zeroes the session exactly as a request + // that reuses nothing does (the engine's state after session_init); no checkpoint, conversation entry, RNG draw, policy sample or statistic is touched (the policy's observe_* + // calls live in the decode loop); the expert cache may page in what the dummy token routes to (speed only). STRATA_WINDOW_WARM=0: off (research switch). + { + static const bool warm_off = [] { const char* v = std::getenv("STRATA_WINDOW_WARM"); return v != nullptr && v[0] == '0'; }(); + if (!warm_off && o.spec >= 2 && n_stages == 1 && o.batch <= 0) { + const Clock::time_point w0 = Clock::now(); + std::vector wtok((size_t) o.spec, 1), wout((size_t) o.spec + 1, 0); + std::string werr, wlist; + bool wok = true; + for (int t = 1; t <= o.spec && wok; ++t) { + if (!((lookup_size_mask(o) >> t) & 1u)) continue; + bool no_vram = false; + if (!ver.prepare(t, no_vram, werr)) { if (no_vram) continue; wok = false; break; } // CUDA / HIP: the graph now (a size that finds no VRAM is left to the runtime rule); Metal: nothing to do + const Clock::time_point t0 = Clock::now(); + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + wok = ver.run(t, wtok.data(), 0, win_pool_fn, win_pool_user, wout.data(), werr) && !drive.d.failed; + char wb[48]; + std::snprintf(wb, sizeof wb, "%s%d:%.0f", wlist.empty() ? "" : " ", t, + std::chrono::duration(Clock::now() - t0).count()); + wlist += wb; + } + strata::core::session_zero(ss, g, nullptr, main_cs); + cudaStreamSynchronize(main_stream); + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + std::fprintf(stderr, "strata serve: window warm-up: ms per width %s, total %.0f ms%s%s\n", wlist.c_str(), + std::chrono::duration(Clock::now() - w0).count(), wok ? "" : "; a window failed: ", + wok ? "" : werr.c_str()); + } + } g_gpu_pause_idle.idle(gpu_pause_now()); // AMD on Linux: the gap before the first request starts here (the start-up's own pauses are not a "between") std::printf("READY %lld stop hold holdb\n", (long long) o.max_context); // "stop": this engine honours STOP; "hold": GEN hold=N:ID; "holdb": the --batch slots end at the hold too (BDONE hold) std::fflush(stdout); @@ -15926,41 +15963,6 @@ int main(int argc, char** argv) { if (!pump(false)) return false; return pmtp_settle(); }; - // ---- window warm-up (lane DRAFT-COSTS): the first run of a window width builds its graph / pipeline (srv118 CUDA: a capture; Metal: the first execution), so a - // width that the policy first picks inside a long request pays it there (M5 Max, IQ3_S: +60 ms on the first five-row lookup round, in the timed code request in 5 of 8 launches - // with a table, because the release and the live costs happen to pay it in request 1). One dummy window per allowed width 1..S, once, before the first request is read; it - // changes nothing a request can see: the windows write K/V cells 0..T-1 and the recurrent state of the session, and session_zero() below zeroes the session exactly as a request - // that reuses nothing does (the engine's state after session_init); no checkpoint, conversation entry, RNG draw, policy sample or statistic is touched (the policy's observe_* - // calls live in the decode loop); the expert cache may page in what the dummy token routes to (speed only). STRATA_WINDOW_WARM=0: off (research switch). - { - static const bool warm_off = [] { const char* v = std::getenv("STRATA_WINDOW_WARM"); return v != nullptr && v[0] == '0'; }(); - if (!warm_off && S >= 2 && n_stages == 1 && !batch_on() && !piped) { - const Clock::time_point w0 = Clock::now(); - std::vector wtok((size_t) S, 1), wout((size_t) S + 1, 0); - std::string werr, wlist; - bool wok = true; - for (int t = 1; t <= S && wok; ++t) { - if (!policy.allowed(t)) continue; - const Clock::time_point t0 = Clock::now(); - drive.d.layers = 0; - drive.d.experts = 0; - drive.d.failed = false; - wok = ver.run(t, wtok.data(), 0, win_pool_fn, win_pool_user, wout.data(), werr) && !drive.d.failed; - char wb[48]; - std::snprintf(wb, sizeof wb, "%s%d:%.0f", wlist.empty() ? "" : " ", t, - std::chrono::duration(Clock::now() - t0).count()); - wlist += wb; - } - strata::core::session_zero(ss, g, nullptr, main_cs); - cudaStreamSynchronize(main_stream); - drive.d.layers = 0; - drive.d.experts = 0; - drive.d.failed = false; - std::fprintf(stderr, "strata serve: window warm-up: ms per width %s, total %.0f ms%s%s\n", wlist.c_str(), - std::chrono::duration(Clock::now() - w0).count(), wok ? "" : "; a window failed: ", - wok ? "" : werr.c_str()); - } - } for (;;) { line_drain_ms = 0.0; strata::core::manifest::instance().flush_if_dirty("request"); // STRATA_MANIFEST: what the last request added (a no-op when off) diff --git a/src/spec/draft_policy.cpp b/src/spec/draft_policy.cpp index d1706d93ae..48efeefc98 100644 --- a/src/spec/draft_policy.cpp +++ b/src/spec/draft_policy.cpp @@ -305,14 +305,31 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o continue; } if (line.rfind("cal ", 0) == 0) { - int cb = -1, ct = -1, cn = -1; + int cb = -1, ct = -1, cn = -1, used = 0; double cs = -1.0; - if (std::sscanf(line.c_str(), "cal %d %d %d %lf", &cb, &ct, &cn, &cs) != 4 || cb < 0 || cb >= CostLearner::kCtxBuckets || ct < 1 || ct > CostLearner::kMaxT + if (std::sscanf(line.c_str(), "cal %d %d %d %lf%n", &cb, &ct, &cn, &cs, &used) != 4 || cb < 0 || cb >= CostLearner::kCtxBuckets || ct < 1 || ct > CostLearner::kMaxT || cn < 0 || cn > 100000 || !(cs >= 0.0) || !(cs < 1e9)) { why = "a malformed calibration line"; return false; } - out.cal[(size_t) cb][(size_t) ct] = CalAcc{cn, cs}; + CalAcc ca; + ca.n = cn; + ca.sum = cs; + { // the rounds themselves (a line from before them: none, the mean decides as it did) + const char* p = line.c_str() + used; + int k = 0; + bool ok = true; + while (k < CalAcc::kVals) { + char* e = nullptr; + const double v = std::strtod(p, &e); + if (e == p) break; + if (!(v > 0.0) || !(v < 1e6)) { ok = false; break; } + ca.vals[(size_t) k++] = v; + p = e; + } + ca.nv = ok && k == cn && cn <= CalAcc::kVals ? k : 0; + } + out.cal[(size_t) cb][(size_t) ct] = ca; continue; } if (line.rfind("rc ", 0) == 0) { @@ -386,7 +403,13 @@ bool write_cost_file(const std::string& path, const CostFile& c, std::string& wh const CalAcc& a = c.cal[(size_t) k][(size_t) t]; if (a.n <= 0 || (c.real[(size_t) k] >> (t - 1) & 1u)) continue; std::snprintf(b, sizeof b, "%.4f", a.sum); - f << "cal " << k << " " << t << " " << a.n << " " << b << "\n"; + f << "cal " << k << " " << t << " " << a.n << " " << b; + if (a.nv == a.n) + for (int i = 0; i < a.nv; ++i) { + std::snprintf(b, sizeof b, "%.4f", (double) a.vals[(size_t) i]); + f << " " << b; + } + f << "\n"; } } if (c.cpu_share >= 0.0) { @@ -673,7 +696,16 @@ void DraftPolicy::apply_table() { if (real_[(size_t) k] >> (t - 1) & 1u) cost_[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t]; else cost_[(size_t) k][(size_t) t] = learned_[(size_t) k][(size_t) t] * (t >= 2 ? r : 1.0); } - for (int t = 2; t <= n; ++t) // more rows never cost less + // more rows never cost less. An inversion is repaired from the trusted side: a size that is only guessed (not real), or that sits below another real size, is + // LOWERED to the price of the next larger size first (a cold first-use round or a live value taken at take-over made it too high; raising every larger size to it, + // as a forward pass alone does, made one 20 ms 2-row price of the srv118 table the price of every size from 2 to 7 rows and the policy took 12-row windows); + // a real size above an unreached next size is left, and the forward pass then lifts that guess to it + for (int t = n - 1; t >= 1; --t) { + const bool real_t = real_[(size_t) k] >> (t - 1) & 1u, real_next = real_[(size_t) k] >> t & 1u; + if (cost_[(size_t) k][(size_t) t] > cost_[(size_t) k][(size_t) t + 1] && (!real_t || real_next)) + cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t + 1]; + } + for (int t = 2; t <= n; ++t) if (cost_[(size_t) k][(size_t) t] < cost_[(size_t) k][(size_t) t - 1]) cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t - 1]; } } @@ -772,6 +804,7 @@ void DraftPolicy::use_table() { } void DraftPolicy::calib_add(int bucket, int t, double ms, double age) { + static_assert(kCalibN <= CalAcc::kVals, "a size's rounds are all kept for the median"); if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > fixed_n_[(size_t) bucket]) return; if (real_[(size_t) bucket] >> (t - 1) & 1u) return; if (calib_fresh_only_ && age > CostLearner::kFreshS) return; // the table is what rounds of the first seconds of a busy run cost @@ -780,7 +813,9 @@ void DraftPolicy::calib_add(int bucket, int t, double ms, double age) { if (!(base > 0.0)) return; CalAcc& a = cal_[(size_t) bucket][(size_t) t]; if (a.n >= kCalibN) return; - a.sum += std::clamp(ms, kCalibLo * base, kCalibHi * base); // one stalled round moves the mean by at most (kCalibHi - 1) / kCalibN + const double r = std::clamp(ms, kCalibLo * base, kCalibHi * base); // one stalled round moves the mean by at most (kCalibHi - 1) / kCalibN + a.sum += r; + if (a.nv == a.n && a.n < CalAcc::kVals) a.vals[(size_t) a.nv++] = r; // the rounds are kept: the price is their median a.n += 1; calib_dirty_ = true; } @@ -797,7 +832,13 @@ bool DraftPolicy::calibrate(CostFile& cf, std::string& report) { if (real_[(size_t) k] >> (t - 1) & 1u) continue; CalAcc& a = cal_[(size_t) k][(size_t) t]; if (a.n < kCalibN) continue; - const double v = a.sum / a.n, base = learned_[(size_t) k][(size_t) t]; + double v = a.sum / a.n; // a file from before the kept rounds: the mean + if (a.nv == a.n && a.n > 0) { // the median of the rounds: a cold first use, a stall, another process move a mean, not a median + std::array s = a.vals; + std::sort(s.begin(), s.begin() + a.nv); + v = a.nv % 2 == 1 ? s[(size_t) a.nv / 2] : 0.5 * (s[(size_t) a.nv / 2 - 1] + s[(size_t) a.nv / 2]); + } + const double base = learned_[(size_t) k][(size_t) t]; if (!(base > 0.0) || (v >= kCalibOkLo * base && v <= kCalibOkHi * base)) { // no learned cost (passive): the clamped rounds are taken as they are if (base > 0.0) std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v); else std::snprintf(b, sizeof b, "%s%d rows real %.2f", report.empty() ? "" : ", ", t, v); diff --git a/src/spec/draft_policy_test.cpp b/src/spec/draft_policy_test.cpp index 7a86fec7df..3fe54645d4 100644 --- a/src/spec/draft_policy_test.cpp +++ b/src/spec/draft_policy_test.cpp @@ -544,6 +544,125 @@ int main() { check(g5.lookup && g5.t == 5 && g5.pad == 3, "pad: the next unmeasured size follows once one has its samples"); check(g.choose(1, 1, 3, 1).pad == 0, "pad: a pad_cap of one draft makes no filler"); } + { // DRAFT-COSTS-5: a real price is the MEDIAN of its 16 rounds; the monotone guard repairs an inversion from the trusted side + namespace fs = std::filesystem; + using strata::spec::CalAcc; + using strata::spec::CostFile; + using strata::spec::CostLearner; + using Cal = std::array, CostLearner::kCtxBuckets>; + using Rc = std::array, CostLearner::kCtxBuckets>; + using Real = std::array; + const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90}; + const Cal cal0{}; + const Rc rc0{}; + { // one cold round among 16 (the first use of a width): the real price is the median, a mean would be moved by it + DraftPolicy m(8); + m.set_fixed_costs(tab, 5, 0); + m.start_calibration(false, Real{}, cal0, rc0); + for (int i = 0; i < 15; ++i) m.observe(false, 2, 1, 0, 14.5); + m.observe(false, 2, 1, 0, 40.0); + CostFile cf; + std::string rep; + check(m.calibrate(cf, rep) && (cf.real[0] & 2u), "median: the 16th round marks the size real"); + check(std::fabs(cf.real_cost[0][2] - 14.5) < 1e-9, "median: one cold round among 16 does not move the real price"); + } + { // eight slow rounds in the first request, eight normal ones after: the median sits between (even count: mean of the two middle rounds) + DraftPolicy m(8); + m.set_fixed_costs(tab, 5, 0); + m.start_calibration(false, Real{}, cal0, rc0); + for (int i = 0; i < 8; ++i) m.observe(false, 2, 1, 0, 15.0); + for (int i = 0; i < 8; ++i) m.observe(false, 2, 1, 0, 14.0); + CostFile cf; + std::string rep; + check(m.calibrate(cf, rep) && std::fabs(cf.real_cost[0][2] - 14.5) < 1e-9, "median: sixteen rounds of two values: the mean of the two middle ones"); + } + { // the rounds survive the file (a start collects part of them, the next start the rest) and a file line without them still loads (mean as before) + const fs::path dir = fs::temp_directory_path() / ("strata-dpt-med-" + std::to_string((unsigned long long) (uintptr_t) &tab)); + const std::string path = (dir / "m.costs").string(); + CostFile c; + c.key = "k"; + c.tables[0] = {12.68, 14.30, 16.41}; + c.cal[0][2] = CalAcc{}; + c.cal[0][2].n = 3; + c.cal[0][2].sum = 43.5; + c.cal[0][2].nv = 3; + c.cal[0][2].vals = {14.5, 14.0, 15.0}; + c.cal[0][3].n = 2; // no rounds kept (a file of an older build): only the sum + c.cal[0][3].sum = 33.0; + std::string why; + check(strata::spec::write_cost_file(path, c, why), "median file: written"); + CostFile r; + check(strata::spec::read_cost_file(path, c.key, r, why), "median file: read back"); + check(r.cal[0][2].n == 3 && r.cal[0][2].nv == 3 && std::fabs((double) r.cal[0][2].vals[1] - 14.0) < 1e-6 && std::fabs(r.cal[0][2].sum - 43.5) < 1e-3, + "median file: the kept rounds come back with their count and sum"); + check(r.cal[0][3].n == 2 && r.cal[0][3].nv == 0 && std::fabs(r.cal[0][3].sum - 33.0) < 1e-3, "median file: a line without rounds keeps only n and sum (the mean decides)"); + std::error_code ec; + fs::remove_all(dir, ec); + } + { // fixture 1: the srv118 table as taken over (a real 2-row price of 20.08 ms, the sizes above it real or unreached): the outlier is lowered, 3-6 rows keep their prices + const double t12[12] = {7.928, 20.085, 9.577, 10.524, 12.136, 13.270, 19.223, 21.293, 23.659, 26.024, 28.390, 30.756}; + Real real0{}; + real0[0] = 63u; + Cal cal1{}; + Rc rc1{}; + const double rcv[7] = {0.0, 7.9276, 20.0847, 9.5771, 10.5245, 12.1355, 13.2695}; + for (int t = 1; t <= 6; ++t) rc1[0][(size_t) t] = rcv[t]; + DraftPolicy p(12); + p.set_fixed_costs(t12, 12, 0); + p.start_calibration(false, real0, cal1, rc1, 100); + bool mono = true; + for (int t = 2; t <= 12; ++t) mono = mono && p.cost_ms(t) >= p.cost_ms(t - 1) - 1e-12; + check(mono, "guard: the used table never costs less for more rows"); + check(std::fabs(p.cost_ms(2) - 9.5771) < 1e-9 && std::fabs(p.cost_ms(3) - 9.5771) < 1e-9 && std::fabs(p.cost_ms(4) - 10.5245) < 1e-9 && std::fabs(p.cost_ms(6) - 13.2695) < 1e-9, + "guard: the 20 ms 2-row outlier is lowered to the next real price, not raised into every larger size"); + check(std::fabs(p.cost_ms(1) - 7.9276) < 1e-9, "guard: the 1-row price is untouched"); + } + { // fixture 2: the Q2_0 table at take-over: 4 rows an unreached live value above the real 5 rows + const double q[5] = {12.966, 14.482, 17.042, 21.796, 21.361}; + Real real0{}; + real0[0] = 23u; // sizes 1, 2, 3, 5 + Cal cal1{}; + Rc rc1{}; + rc1[0][1] = 12.9665; + rc1[0][2] = 14.4821; + rc1[0][3] = 17.0419; + rc1[0][5] = 21.3610; + DraftPolicy p(8); + p.set_fixed_costs(q, 5, 0); + p.start_calibration(false, real0, cal1, rc1, 100); + check(std::fabs(p.cost_ms(4) - 21.3610) < 1e-9 && std::fabs(p.cost_ms(5) - 21.3610) < 1e-9 && std::fabs(p.cost_ms(3) - 17.0419) < 1e-9, + "guard: an unreached 4 rows above the real 5 rows is lowered to it"); + } + { // fixture 3: the IQ3_S table at take-over: 4 rows 28.31 (a live value) above the real 5 rows 25.00 + const double q[5] = {14.734, 16.967, 20.096, 28.312, 25.005}; + Real real0{}; + real0[0] = 23u; + Cal cal1{}; + Rc rc1{}; + rc1[0][1] = 14.7341; + rc1[0][2] = 16.9669; + rc1[0][3] = 20.0959; + rc1[0][5] = 25.0046; + DraftPolicy p(8); + p.set_fixed_costs(q, 5, 0); + p.start_calibration(false, real0, cal1, rc1, 100); + check(std::fabs(p.cost_ms(4) - 25.0046) < 1e-9 && std::fabs(p.cost_ms(5) - 25.0046) < 1e-9 && std::fabs(p.cost_ms(2) - 16.9669) < 1e-9, + "guard: IQ3_S 4 rows 28.31 is lowered to the real 5 rows 25.00"); + } + { // a real size above an unreached next size is not lowered by the guess: the guess is lifted to it + const double q[5] = {12.0, 14.0, 20.0, 15.0, 16.0}; + Real real0{}; + real0[0] = 4u; // size 3 real at 20.0 + Cal cal1{}; + Rc rc1{}; + rc1[0][3] = 20.0; + DraftPolicy p(8); + p.set_fixed_costs(q, 5, 0); + p.start_calibration(false, real0, cal1, rc1, 100); + check(std::fabs(p.cost_ms(3) - 20.0) < 1e-9 && p.cost_ms(4) >= 20.0 - 1e-9 && p.cost_ms(5) >= p.cost_ms(4) - 1e-12 && std::fabs(p.cost_ms(2) - 14.0) < 1e-9, + "guard: a real price is kept against a guessed larger size, which is lifted to it"); + } + } { // calibration against real rounds using strata::spec::CalAcc; using strata::spec::CostFile; @@ -722,7 +841,7 @@ int main() { "passive: real size 2 at its real cost, size 4 at its live cost, size 3 (never measured) at the policy's prior"); for (int i = 0; i < 17; ++i) b.observe(true, 4, 2, 0, 20.1); // the unreached size keeps collecting CostFile cb3 = cb2; - check(b.calibrate(cb3, rp) && (cb3.real[0] & 8u) && std::fabs(b.cost_ms(4) - (5 * 19.9 + 11 * 20.1) / 16.0) < 1e-6, "passive: after the take-over a size still collects and becomes real at 16 own rounds"); + check(b.calibrate(cb3, rp) && (cb3.real[0] & 8u) && std::fabs(b.cost_ms(4) - 20.1) < 1e-9, "passive: after the take-over a size still collects and becomes real at 16 own rounds (its price the median: 5 rounds of 19.9, 11 of 20.1)"); } // the file round trip: state, real, real cost, cal CostFile w; From 1b11a76e8ca96176d3f6c35fe02310dc61059d85 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 13 Nov 2026 11:31:54 +0100 Subject: [PATCH 17/17] draft-cost table: on by default on Metal only; CUDA and HIP keep live costs The taken-over table measured below live costs on CUDA (RTX PRO 5000, IQ3_S + MTP: code -1.5 %, chat -1.5 %, JSON +1.9 %, long -0.2 %, agent -0.5 %) and above them on Metal (M5 Max). serve/server.py now passes --draft-costs by default only on darwin; on other platforms the engine runs live costs exactly as without the flag. "draft_costs": true in a config turns the table on anywhere, false turns it off. Two tests in serve/test_server.py (DraftCosts). --- serve/server.py | 12 +++++++++++- serve/test_server.py | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/serve/server.py b/serve/server.py index a88106b6ea..07455848b8 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4061,7 +4061,17 @@ def learned_profile_args(cfg: dict, args: list[str]) -> list[str]: return args -DRAFT_COSTS_DEFAULT = True # repeatable output: on by default (owner decision); "draft_costs": false in a config turns it off +DRAFT_COSTS_DEFAULT_PLATFORMS = ("darwin",) # Metal: the taken-over table measured above live costs there (M5 Max: Q2_0 code +2.6 %, chat +2.4 %, JSON +0.2 %; IQ3_S +0.2 / +0.6 / +0.7 %) + + +def draft_costs_default(platform: str | None = None) -> bool: + """Repeatable output (owner decision) is the default only where the table was measured at or above live costs: Metal. On CUDA (RTX PRO 5000, IQ3_S: code + -1.5 %, chat -1.5 %, JSON +1.9 % against live costs) and HIP the engine keeps live costs, as an engine started without --draft-costs does. `"draft_costs": true` + in a config turns the table on anywhere (tests and A/Bs), `"draft_costs": false` turns it off.""" + return (platform or sys.platform) in DRAFT_COSTS_DEFAULT_PLATFORMS + + +DRAFT_COSTS_DEFAULT = draft_costs_default() # "draft_costs": true / false in a config overrides it _engine_texts: dict = {} diff --git a/serve/test_server.py b/serve/test_server.py index 131d46de3a..1fe7879dab 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -2564,6 +2564,25 @@ class DraftCosts(unittest.TestCase): self.assertEqual(server.draft_costs_args({"model_name": "m"}, list(args)), args) self.assertEqual(server.draft_costs_args({"model_name": "m"}, list(args), str(self.tmp / "missing")), args) + def test_default_is_on_only_on_metal(self): + # the taken-over table measured above live costs on Metal and below them on CUDA (l620, 11-13): live costs stay the default there and on HIP + self.assertTrue(server.draft_costs_default("darwin")) + for platform in ("linux", "win32", "cygwin", "freebsd14", "android"): + self.assertFalse(server.draft_costs_default(platform), platform) + self.assertEqual(server.DRAFT_COSTS_DEFAULT, sys.platform == "darwin") + + def test_table_off_by_default_gives_no_flag_unless_the_config_asks(self): + args = ["--native", "x", "--spec", "6"] + new = self.tmp / "new-engine" + new.write_bytes(b"\x7fELF strata --spec --serve --draft-costs --draft-costs-key") + with mock.patch.object(server, "DRAFT_COSTS_DEFAULT", False): # CUDA / HIP class + self.assertEqual(server.draft_costs_args({"model_name": "m"}, list(args), str(new)), args) + self.assertIn("--draft-costs", server.draft_costs_args({"model_name": "m", "draft_costs": True}, list(args), str(new))) # the test switch + self.assertEqual(server.draft_costs_args({"model_name": "m", "draft_costs": False}, list(args), str(new)), args) + with mock.patch.object(server, "DRAFT_COSTS_DEFAULT", True): # Metal class + self.assertIn("--draft-costs", server.draft_costs_args({"model_name": "m"}, list(args), str(new))) + self.assertEqual(server.draft_costs_args({"model_name": "m", "draft_costs": False}, list(args), str(new)), args) + def test_on_gives_a_file_in_the_redirected_folder(self): args = ["--native", "x", "--spec", "6"] got = server.draft_costs_args({"model_name": "qwen3.8-flash-next-iq3_s", "draft_costs": True}, list(args))