okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-dc-learn-fix fc66df986 into the batch 16 candidate (draft-cost table learning fix)aad676f43

main
47.9 KiB1057 linesraw
1// src/spec/draft_policy.cpp - see include/strata/spec/draft_policy.hpp.
2#include "strata/spec/draft_policy.hpp"
3
4#include <algorithm>
5#include <cmath>
6#include <cstdio>
7#include <cstdlib>
8#include <filesystem>
9#include <fstream>
10
11namespace strata::spec {
12namespace {
13
14// The shape of a round's cost by window size, relative to one token, used only for sizes not measured yet (the
15// measured round times replace it). Between the RTX 5070's measured curves: +10 ms per token with every missed expert
16// on the CPU (bench/results/2026-09-27-spec/window-cost), flatter with the default CPU/DMA split.
17// (sizes 9-16, above the measured curves: +0.4 a token)
18constexpr double kShape[DraftPolicy::kMaxT + 1] = {0.0, 1.0, 1.35, 1.7, 2.05, 2.45, 2.85, 3.25, 3.6,
19                                                   4.0, 4.4, 4.8, 5.2, 5.6, 6.0, 6.4, 6.8};
20constexpr double kCostAlpha = 0.1;    // EMA weight of a new round time
21constexpr double kTokAlpha = 0.05;    // EMA weight of a new MTP window outcome
22constexpr double kCalDecay = 0.995;   // the MTP probability -> acceptance table fades slowly
23constexpr double kDecay = 0.97;       // lookup counts: older windows fade
24// Before a bucket has data: the longer the match, the likelier its continuation (llama.cpp's lookup decoding gates
25// on the same thing); worth 4 observations, so a few real windows override it
26constexpr double kPriorQ[DraftPolicy::kBuckets] = {0.75, 0.88, 0.93, 0.96};
27constexpr double kPriorN = 4.0;
28constexpr int kProbes = 3;       // a lookup window size is tried this often before its guessed cost can veto it
29// A size not measured for this many rounds is tried again when a confident lookup could use it: its cost was set in
30// one stretch (a prompt's cache refill, say) and, priced high, it would never be measured again (#1252)
31constexpr double kStaleRounds = 300.0;
32
33// STRATA_SPEC_FIXED=1 and STRATA_SPEC_FIXED_TABLE="T1,T2,.." (round ms of windows of 1, 2, .. rows): an expert's fixed table for every
34// context bucket, read once per process (the measured table of --draft-costs is the normal source).
35struct FixedEnv {
36    bool on = false;
37    double ms[DraftPolicy::kMaxT] = {};
38    int n = 0;
39};
40const FixedEnv& fixed_env() {
41    static const FixedEnv cfg = [] {
42        FixedEnv c;
43        const char* e = std::getenv("STRATA_SPEC_FIXED");
44        c.on = e != nullptr && e[0] == '1';
45        if (const char* tab = std::getenv("STRATA_SPEC_FIXED_TABLE"); c.on && tab != nullptr && tab[0] != '\0') {
46            for (const char* q = tab; *q != '\0' && c.n < DraftPolicy::kMaxT;) {
47                c.ms[c.n++] = std::atof(q);
48                while (*q != '\0' && *q != ',') ++q;
49                if (*q == ',') ++q;
50            }
51        }
52        return c;
53    }();
54    return cfg;
55}
56
57double trimmed_mean(std::vector<float> v) {
58    std::sort(v.begin(), v.end());
59    const size_t k = (size_t) ((double) v.size() * CostLearner::kTrim);
60    double s = 0.0;
61    size_t n = 0;
62    for (size_t i = k; i + k < v.size(); ++i, ++n) s += v[i];
63    if (n == 0) {
64        for (const float x : v) s += x;
65        n = v.size();
66    }
67    return n > 0 ? s / (double) n : 0.0;
68}
69
70double median_of(std::vector<float> v) {
71    if (v.empty()) return 0.0;
72    std::nth_element(v.begin(), v.begin() + (std::ptrdiff_t) (v.size() / 2), v.end());
73    return v[v.size() / 2];
74}
75
76}  // namespace
77
78// ---------------------------------------------------------------------------------------------------- CostLearner
79
80static_assert(CostLearner::kMaxT == DraftPolicy::kMaxT && CostLearner::kCtxBuckets == DraftPolicy::kCtxBuckets, "one table shape");
81
82void CostLearner::add(int bucket, int t, double ms, double busy_age_s) {
83    if (!(ms > 0.0) || !std::isfinite(ms)) return;
84    bucket = std::clamp(bucket, 0, kCtxBuckets - 1);
85    t = std::clamp(t, 1, kMaxT);
86    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
87    ++(late ? late_ : rounds_);
88    auto& v = (late ? late_s_ : s_)[(size_t) bucket][(size_t) t];
89    if ((int) v.size() < kKeep) v.push_back((float) ms);
90}
91
92void CostLearner::reset() {
93    for (auto& b : s_)
94        for (auto& v : b) v.clear();
95    for (auto& b : late_s_)
96        for (auto& v : b) v.clear();
97    rounds_ = 0;
98    late_ = 0;
99}
100
101bool CostLearner::state_effect(int bucket, int min_n) const {
102    if (bucket < 0 || bucket >= kCtxBuckets) return false;
103    const int need = std::max(1, min_n);
104    for (int t = 1; t <= kMaxT; ++t) {
105        const auto& f = s_[(size_t) bucket][(size_t) t];
106        const auto& l = late_s_[(size_t) bucket][(size_t) t];
107        if ((int) f.size() < need || (int) l.size() < need) continue;
108        const double tf = trimmed_mean(f), tl = trimmed_mean(l);
109        if (tf > 0.0 && std::fabs(tl - tf) / tf > kStateTol) return true;
110    }
111    return false;
112}
113
114std::array<std::vector<float>, CostLearner::kMaxT + 1> CostLearner::sets(int bucket, bool pooled) const {
115    std::array<std::vector<float>, kMaxT + 1> out;
116    for (int t = 1; t <= kMaxT; ++t) {
117        out[(size_t) t] = s_[(size_t) bucket][(size_t) t];
118        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());
119    }
120    return out;
121}
122
123bool CostLearner::state_known(int bucket, int min_n) const {
124    if (bucket < 0 || bucket >= kCtxBuckets) return false;
125    const int need = std::max(1, min_n);
126    for (int t = 1; t <= kMaxT; ++t)
127        if ((int) s_[(size_t) bucket][(size_t) t].size() >= need && (int) late_s_[(size_t) bucket][(size_t) t].size() >= need) return true;
128    return false;
129}
130
131int CostLearner::usable(int bucket, int t, int min_n) const {
132    if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > kMaxT) return 0;
133    int n = (int) s_[(size_t) bucket][(size_t) t].size();
134    if (!state_effect(bucket, min_n)) n += (int) late_s_[(size_t) bucket][(size_t) t].size();
135    return n;
136}
137
138int CostLearner::samples(int bucket, int t) const {
139    if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > kMaxT) return 0;
140    return (int) s_[(size_t) bucket][(size_t) t].size();
141}
142
143std::vector<double> CostLearner::table(int bucket, int min_n, int upto) const {
144    std::vector<double> out;
145    if (bucket < 0 || bucket >= kCtxBuckets) return out;
146    const std::array<std::vector<float>, kMaxT + 1> b = sets(bucket, !state_effect(bucket, min_n));
147    int top = 0;
148    std::array<double, kMaxT + 1> got{};
149    std::vector<int> seen;   // the measured sizes (min_n samples), ascending; a rough one (kWeakN samples) joins when it is accepted below
150    for (int t = 1; t <= kMaxT; ++t) {
151        if (!b[(size_t) t].empty()) top = t;
152        if ((int) b[(size_t) t].size() >= std::max(1, min_n)) {
153            got[(size_t) t] = trimmed_mean(b[(size_t) t]);
154            seen.push_back(t);
155        }
156    }
157    if (top == 0 || seen.empty()) return out;
158    top = std::max(top, std::min(upto, kMaxT));
159    // 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
160    // steeper of the last segment's slope and the slope over all measured sizes (never flatter than the measured trend)
161    const auto fill = [&](int t) {
162        int lo = 0, hi = 0;
163        for (const int u : seen) {
164            if (u < t) lo = u;
165            if (u > t && hi == 0) hi = u;
166        }
167        if (lo > 0 && hi > 0) return got[(size_t) lo] + (got[(size_t) hi] - got[(size_t) lo]) * (t - lo) / (double) (hi - lo);
168        if (hi > 0) return got[(size_t) hi] * kShape[t] / kShape[hi];
169        if (seen.size() < 2) return got[(size_t) lo] * kShape[t] / kShape[lo];
170        const int u2 = seen.back(), u1 = seen[seen.size() - 2], u0 = seen.front();
171        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)});
172        return got[(size_t) u2] + slope * (t - u2);
173    };
174    for (int t = 1; t <= top; ++t) {
175        if (got[(size_t) t] > 0.0) {
176            out.push_back(got[(size_t) t]);
177            continue;
178        }
179        double v = fill(t);
180        const int n = (int) b[(size_t) t].size();
181        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)
182            std::vector<float> s = b[(size_t) t];
183            std::sort(s.begin(), s.end());
184            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]);
185            if (med >= v && med <= kWeakMax * v) {
186                v = med;
187                got[(size_t) t] = med;
188                seen.insert(std::upper_bound(seen.begin(), seen.end(), t), t);
189            }
190        }
191        out.push_back(v);
192    }
193    for (size_t i = 1; i < out.size(); ++i) out[i] = std::max(out[i], out[i - 1]);   // more rows never cost less
194    return out;
195}
196
197CostLearner::Verdict CostLearner::check(int64_t min_rounds, int min_n) const {
198    Verdict v;
199    char b[160];
200    bool any = false, every_bucket_ok = true, effect = false;
201    for (int k = 0; k < kCtxBuckets; ++k) {
202        bool has = false, measured = false;
203        double prev_ms = 0.0;
204        int prev_t = 0;
205        const bool eff = state_effect(k, min_n);
206        effect = effect || eff;
207        const std::array<std::vector<float>, kMaxT + 1> use = sets(k, !eff);
208        for (int t = 1; t <= kMaxT; ++t) {
209            const auto& s = use[(size_t) t];
210            has = has || !s.empty();
211            if ((int) s.size() < std::max(1, min_n)) continue;
212            measured = true;
213            const double tm = trimmed_mean(s);
214            if (prev_t > 0 && tm < prev_ms * (1.0 - kOrderSlack) && v.why.empty()) {
215                std::snprintf(b, sizeof b, "bucket %d: T%d %.2f ms below T%d %.2f ms", k, t, tm, prev_t, prev_ms);
216                v.disturbed = true;
217                v.why = b;
218            }
219            prev_ms = tm;
220            prev_t = t;
221            if ((int) s.size() < 2 * std::max(1, min_n)) continue;
222            const size_t h = s.size() / 2;
223            const double a = trimmed_mean(std::vector<float>(s.begin(), s.begin() + (std::ptrdiff_t) h));
224            const double c = trimmed_mean(std::vector<float>(s.begin() + (std::ptrdiff_t) h, s.end()));
225            if (a > 0.0 && std::fabs(c - a) / a > kDriftMax && v.why.empty()) {
226                std::snprintf(b, sizeof b, "bucket %d: T%d first half %.2f ms, second half %.2f ms", k, t, a, c);
227                v.disturbed = true;
228                v.why = b;
229            }
230            const double med = median_of(s);
231            size_t spikes = 0;
232            for (const float x : s) spikes += x > 2.0 * med ? 1 : 0;
233            if ((double) spikes > kSpikeMax * (double) s.size() && v.why.empty()) {
234                std::snprintf(b, sizeof b, "bucket %d: T%d %zu of %zu rounds above twice the median %.2f ms", k, t, spikes, s.size(), med);
235                v.disturbed = true;
236                v.why = b;
237            }
238        }
239        any = any || measured;
240        if (has && !measured) every_bucket_ok = false;
241    }
242    // 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
243    // seconds), kFallbackFactor x the quota in rounds of any age when the fresh ones are at least 1 / kFallbackShare of the quota
244    const bool enough = effect ? (rounds_ >= min_rounds || (rounds_ + late_ >= kFallbackFactor * min_rounds && rounds_ * kFallbackShare >= min_rounds))
245                               : rounds_ + late_ >= min_rounds;
246    v.ready = enough && any && every_bucket_ok;
247    return v;
248}
249
250// ---------------------------------------------------------------------------------------------------- the table file
251
252namespace {
253constexpr 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
254// the path as UTF-8 (the server passes it so); on Windows a plain std::string would be read in the ANSI code page
255std::filesystem::path utf8_path(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }
256std::string one_line(std::string s) {
257    for (char& c : s)
258        if (c == '\n' || c == '\r') c = ' ';
259    return s;
260}
261}  // namespace
262
263bool read_cost_file(const std::string& path, const std::string& key, CostFile& out, std::string& why) {
264    out = CostFile{};
265    std::ifstream f(utf8_path(path), std::ios::binary);
266    if (!f) { why = "no table file yet"; return false; }
267    std::string line;
268    if (!std::getline(f, line) || line != kCostFileHead) { why = "not a table file of this format"; return false; }
269    if (!std::getline(f, line) || line.rfind("key ", 0) != 0) { why = "the file has no key"; return false; }
270    if (line.substr(4) != one_line(key)) { why = "learned on another machine or with other settings"; return false; }
271    bool ended = false, any = false;
272    while (std::getline(f, line)) {
273        if (line == "end") { ended = true; break; }
274        if (line.rfind("share ", 0) == 0) {
275            char* e = nullptr;
276            const double s = std::strtod(line.c_str() + 6, &e);
277            if (e == line.c_str() + 6 || *e != '\0' || !(s >= 0.0) || !(s <= 1.0)) { why = "a malformed share"; return false; }
278            out.cpu_share = s;
279            continue;
280        }
281        if (line.rfind("pcie ", 0) == 0) {
282            char* e = nullptr;
283            const double s = std::strtod(line.c_str() + 5, &e);
284            if (e == line.c_str() + 5 || *e != '\0' || !(s >= 0.0) || !(s <= 1.0)) { why = "a malformed PCIe share"; return false; }
285            out.pcie_frac = s;
286            continue;
287        }
288        if (line.rfind("state ", 0) == 0) {   // calibration lines (DraftPolicy::start_calibration); a file without them has no calibration done
289            if (line != "state 0" && line != "state 1") { why = "a malformed state"; return false; }
290            out.state_effect = line == "state 1";
291            continue;
292        }
293        if (line == "fresh 1") { out.fresh = true; continue; }
294        if (line.rfind("reqs ", 0) == 0) {
295            int rq = -1;
296            if (std::sscanf(line.c_str(), "reqs %d", &rq) != 1 || rq < 0 || rq > 1000000) { why = "a malformed request count"; return false; }
297            out.reqs = rq;
298            continue;
299        }
300        if (line.rfind("real ", 0) == 0) {
301            int rb = -1;
302            unsigned m = 0;
303            if (std::sscanf(line.c_str(), "real %d %u", &rb, &m) != 2 || rb < 0 || rb >= CostLearner::kCtxBuckets) { why = "a malformed real mark"; return false; }
304            out.real[(size_t) rb] = m;
305            continue;
306        }
307        if (line.rfind("cal ", 0) == 0) {
308            int cb = -1, ct = -1, cn = -1, used = 0;
309            double cs = -1.0;
310            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
311                || cn < 0 || cn > 100000 || !(cs >= 0.0) || !(cs < 1e9)) {
312                why = "a malformed calibration line";
313                return false;
314            }
315            CalAcc ca;
316            ca.n = cn;
317            ca.sum = cs;
318            {   // the rounds themselves (a line from before them: none, the mean decides as it did)
319                const char* p = line.c_str() + used;
320                int k = 0;
321                bool ok = true;
322                while (k < CalAcc::kVals) {
323                    char* e = nullptr;
324                    const double v = std::strtod(p, &e);
325                    if (e == p) break;
326                    if (!(v > 0.0) || !(v < 1e6)) { ok = false; break; }
327                    ca.vals[(size_t) k++] = v;
328                    p = e;
329                }
330                ca.nv = ok && k == cn && cn <= CalAcc::kVals ? k : 0;
331            }
332            out.cal[(size_t) cb][(size_t) ct] = ca;
333            continue;
334        }
335        if (line.rfind("rc ", 0) == 0) {
336            int rb = -1, rt = -1;
337            double rv = -1.0;
338            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)) {
339                why = "a malformed real cost";
340                return false;
341            }
342            out.real_cost[(size_t) rb][(size_t) rt] = rv;
343            continue;
344        }
345        int b = -1, used = 0;
346        if (std::sscanf(line.c_str(), "bucket %d %n", &b, &used) < 1 || used == 0 || b < 0 || b >= CostLearner::kCtxBuckets) {
347            why = "a malformed line";
348            return false;
349        }
350        std::vector<double> v;
351        const char* q = line.c_str() + used;
352        while (*q != '\0') {
353            char* e = nullptr;
354            const double x = std::strtod(q, &e);
355            if (e == q || !(x > 0.0) || !(x < 1e5)) { why = "a malformed table"; return false; }
356            v.push_back(x);
357            q = e;
358            if (*q == ',') ++q;
359            else if (*q != '\0') { why = "a malformed table"; return false; }
360        }
361        if (v.empty() || (int) v.size() > CostLearner::kMaxT) { why = "a table of the wrong length"; return false; }
362        out.tables[(size_t) b] = std::move(v);
363        any = true;
364    }
365    if (!ended || (!any && !out.fresh) || (any && out.fresh)) { why = "the file is cut short"; return false; }
366    out.key = key;
367    return true;
368}
369
370bool write_cost_file(const std::string& path, const CostFile& c, std::string& why) {
371    namespace fs = std::filesystem;
372    std::error_code ec;
373    const fs::path p = utf8_path(path);
374    if (p.has_parent_path()) fs::create_directories(p.parent_path(), ec);
375    if (ec) { why = "could not make the folder (" + ec.message() + ")"; return false; }
376    fs::path tmp = p;
377    tmp += ".tmp";
378    {
379        std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
380        if (!f) { why = "could not write the file"; return false; }
381        f << kCostFileHead << "\nkey " << one_line(c.key) << "\n";
382        char b[32];
383        for (int k = 0; k < CostLearner::kCtxBuckets; ++k) {
384            if (c.tables[(size_t) k].empty()) continue;
385            f << "bucket " << k << " ";
386            for (size_t i = 0; i < c.tables[(size_t) k].size(); ++i) {
387                std::snprintf(b, sizeof b, "%s%.3f", i ? "," : "", c.tables[(size_t) k][i]);
388                f << b;
389            }
390            f << "\n";
391        }
392        if (c.state_effect) f << "state 1\n";
393        if (c.reqs > 0) f << "reqs " << c.reqs << "\n";
394        if (c.fresh) f << "fresh 1\n";
395        for (int k = 0; k < CostLearner::kCtxBuckets; ++k) {
396            if (c.real[(size_t) k] != 0u) f << "real " << k << " " << c.real[(size_t) k] << "\n";
397            for (int t = 1; t <= CostLearner::kMaxT; ++t)
398                if ((c.real[(size_t) k] >> (t - 1) & 1u) && c.real_cost[(size_t) k][(size_t) t] > 0.0) {
399                    std::snprintf(b, sizeof b, "%.4f", c.real_cost[(size_t) k][(size_t) t]);
400                    f << "rc " << k << " " << t << " " << b << "\n";
401                }
402            for (int t = 1; t <= CostLearner::kMaxT; ++t) {
403                const CalAcc& a = c.cal[(size_t) k][(size_t) t];
404                if (a.n <= 0 || (c.real[(size_t) k] >> (t - 1) & 1u)) continue;
405                std::snprintf(b, sizeof b, "%.4f", a.sum);
406                f << "cal " << k << " " << t << " " << a.n << " " << b;
407                if (a.nv == a.n)
408                    for (int i = 0; i < a.nv; ++i) {
409                        std::snprintf(b, sizeof b, "%.4f", (double) a.vals[(size_t) i]);
410                        f << " " << b;
411                    }
412                f << "\n";
413            }
414        }
415        if (c.cpu_share >= 0.0) {
416            std::snprintf(b, sizeof b, "share %.3f\n", std::min(c.cpu_share, 1.0));
417            f << b;
418        }
419        if (c.pcie_frac >= 0.0) {
420            std::snprintf(b, sizeof b, "pcie %.3f\n", std::min(c.pcie_frac, 1.0));
421            f << b;
422        }
423        f << "end\n";
424        f.flush();
425        if (!f) { why = "could not write the file"; fs::remove(tmp, ec); return false; }
426    }
427    fs::rename(tmp, p, ec);   // replaces an older file whole (MoveFileEx with REPLACE_EXISTING on Windows)
428    if (ec) { why = "could not replace the file (" + ec.message() + ")"; fs::remove(tmp, ec); return false; }
429    return true;
430}
431
432void mark_learned_real(CostFile& cf) {
433    for (int k = 0; k < CostLearner::kCtxBuckets; ++k) {
434        std::vector<double>& tab = cf.tables[(size_t) k];
435        for (size_t i = 0; i < tab.size(); ++i) {
436            const double v = std::round(tab[i] * 1000.0) / 1000.0;
437            if (!(v > 0.0)) continue;   // never for a valid table; the size then stays not real (held, as before)
438            tab[i] = v;
439            cf.real[(size_t) k] |= 1u << i;
440            cf.real_cost[(size_t) k][i + 1] = v;
441        }
442    }
443}
444
445// ---------------------------------------------------------------------------------------------------- DraftPolicy
446
447DraftPolicy::DraftPolicy(int max_t, double margin)
448    : max_t_(std::clamp(max_t, 1, kMaxT)), margin_(margin) {
449    const FixedEnv& f = fixed_env();
450    if (f.on)
451        for (int k = 0; k < kCtxBuckets; ++k) set_fixed_costs(f.n > 0 ? f.ms : nullptr, f.n, k);
452}
453
454void DraftPolicy::set_fixed_costs(const double* ms, int n, int bucket) {
455    if (!fixed_ && !live_saved_) {   // the live costs at this point: start_calibration() may hand them back
456        live_cost_ = cost_;
457        live_n_ = cost_n_;
458        live_saved_ = true;
459    }
460    fixed_ = true;
461    held_table_ = false;
462    held_.clear();
463    if (ms == nullptr || n <= 0) return;
464    bucket = std::clamp(bucket, 0, kCtxBuckets - 1);
465    fixed_n_[(size_t) bucket] = std::min(n, kMaxT);
466    for (int t = 1; t <= kMaxT; ++t) {   // the table replaces what was measured; sizes past its end scale from it (cost_ms)
467        const bool in = t <= n && ms[t - 1] > 0.0;
468        cost_[bucket][t] = in ? ms[t - 1] : 0.0;
469        cost_n_[bucket][t] = in ? 1e6 : 0.0;
470        learned_[(size_t) bucket][(size_t) t] = cost_[bucket][t];
471    }
472}
473
474void DraftPolicy::set_sizes(unsigned mask) { sizes_ = mask | 2u; }
475
476void DraftPolicy::disable(int t) {
477    if (t > 1 && t <= kMaxT) sizes_ &= ~(1u << t);
478}
479
480int DraftPolicy::fit(int t) const {
481    for (t = std::min(t, max_t_); t > 1; --t)
482        if (allowed(t)) return t;
483    return 1;
484}
485
486int DraftPolicy::bucket(int match) {
487    return match < 6 ? 0 : match < 12 ? 1 : match < 24 ? 2 : 3;
488}
489
490double DraftPolicy::lookup_rate(int match) const {
491    const int b = bucket(match);
492    return (ok_[b] + kPriorN * kPriorQ[b]) / (ok_[b] + bad_[b] + kPriorN);
493}
494
495double DraftPolicy::cost_ms(int t) const {
496    t = std::clamp(t, 1, kMaxT);
497    if (cost_n_[bk_][t] > 0) return cost_[bk_][t];
498    // scale from the measured sizes, weighting each by how often it was seen
499    double num = 0.0, den = 0.0;
500    for (int u = 1; u <= kMaxT; ++u)
501        if (cost_n_[bk_][u] > 0) {
502            const double w = std::min(cost_n_[bk_][u], 20.0);
503            num += w * cost_[bk_][u] * kShape[t] / kShape[u];
504            den += w;
505        }
506    return den > 0 ? num / den : kShape[t];
507}
508
509double DraftPolicy::clamp_sample(int t, double ms) const {
510    if (!robust_) return ms;
511    const double known = cost_ms(t);           // the measured value, or the scaled guess from the other widths
512    if (cost_n_[bk_][t] == 0) {
513        // the first use of a width captures its graph: that round says nothing about its cost, the guess from the other widths stands in
514        for (int u = 1; u <= kMaxT; ++u)
515            if (cost_n_[bk_][u] > 0) return known;
516        return ms;
517    }
518    return std::min(ms, 2.0 * known);
519}
520
521void DraftPolicy::seed_costs(const double* ms, int n, double weight, int bucket) {
522    bucket = std::clamp(bucket, 0, kCtxBuckets - 1);
523    for (int t = 1; t <= std::min(n, kMaxT); ++t)
524        if (ms[t - 1] > 0.0 && cost_n_[bucket][t] == 0) {
525            cost_[bucket][t] = ms[t - 1];
526            cost_n_[bucket][t] = weight;
527        }
528}
529
530void DraftPolicy::set_context(long long pos) {
531    if (!robust_) return;
532    const int nb = pos < 6000 ? 0 : pos < 24000 ? 1 : 2;
533    if (nb == bk_) return;
534    bool has = false;
535    for (int t = 1; t <= kMaxT; ++t) has = has || cost_n_[nb][t] > 0;
536    if (!has) {   // nothing measured at this length yet: the nearest bucket that has data is the prior (one sample's worth)
537        for (int d = 1; d < kCtxBuckets && !has; ++d)
538            for (const int src : {nb - d, nb + d}) {
539                if (src < 0 || src >= kCtxBuckets || has) continue;
540                for (int t = 1; t <= kMaxT; ++t)
541                    if (cost_n_[src][t] > 0) {
542                        cost_[nb][t] = cost_[src][t];
543                        cost_n_[nb][t] = 1.0;
544                        last_[nb][t] = rounds_;
545                        has = true;
546                    }
547            }
548    }
549    bk_ = nb;
550}
551
552std::string DraftPolicy::cost_table_text() const {
553    std::string out;
554    char b[64];
555    for (int k = 0; k < kCtxBuckets; ++k) {
556        bool any = false;
557        for (int t = 1; t <= kMaxT; ++t) any = any || cost_n_[k][t] > 0;
558        if (!any) continue;
559        out += (out.empty() ? "" : " | ");
560        out += k == 0 ? "ctx<6K:" : k == 1 ? "ctx<24K:" : "ctx>=24K:";
561        for (int t = 1; t <= kMaxT; ++t)
562            if (cost_n_[k][t] > 0) {
563                std::snprintf(b, sizeof b, " T%d:%.2f(n=%.0f)", t, cost_[k][t], cost_n_[k][t]);
564                out += b;
565            }
566    }
567    return out;
568}
569
570bool DraftPolicy::stale(int t) const { return !fixed_ && cost_n_[bk_][t] > 0 && rounds_ - last_[bk_][t] > kStaleRounds; }
571
572double DraftPolicy::mtp_tokens(int t) const {
573    if (mtp_n_[t] > 0) return mtp_tok_[t];
574    return 1.0 + 0.7 * (t - 1);       // before any MTP window of this size: a typical acceptance
575}
576
577DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match, int pad_cap) const {
578    Pick p;
579    p.t = std::clamp(t_mtp, 1, max_t_);
580    if (lookup_k <= 0) return p;
581    if (learning_ && !fixed_) {   // a learning stretch measures the sizes it has too few rounds of, when a proposal is long enough for one
582        const int s = explore_size(lookup_k, pad_cap);
583        if (s > 0) {
584            p.lookup = true;
585            p.t = s;
586            p.pad = std::max(0, s - 1 - lookup_k);
587            return p;
588        }
589    }
590    const double base = mtp_tokens(p.t) / cost_ms(p.t);
591    const double q = lookup_rate(match);
592    double e = 1.0, qi = 1.0, best = 0.0;
593    int best_t = 0;
594    for (int k = 1; k <= std::min(lookup_k, max_t_ - 1); ++k) {
595        qi *= q;
596        e += qi;
597        if (!allowed(k + 1)) continue;
598        const double r = e / cost_ms(k + 1);
599        if (r > best) { best = r; best_t = k + 1; }
600    }
601    const int t_full = fit(std::min(lookup_k, max_t_ - 1) + 1);
602    if (best_t > 0 && best > base * (1.0 + margin_)) {
603        p.lookup = true;
604        p.t = best_t;
605        // a wider size whose cost has gone stale is re-measured, so one slow stretch cannot price it out for good
606        if (best_t < t_full && q >= 0.85 && stale(t_full)) p.t = t_full;
607        return p;
608    }
609    // a guessed cost can keep the policy from ever measuring a size: the first few times a confident lookup would
610    // need a size not measured yet, it is tried (verification keeps the output; only the one round's speed is at stake)
611    if (!fixed_ && t_full > p.t && t_full > 1 && (cost_n_[bk_][t_full] - delayed_n_[bk_][t_full] + tried_[bk_][t_full] < kProbes || stale(t_full)) && q >= 0.85) {
612        p.lookup = true;
613        p.t = t_full;
614    }
615    return p;
616}
617
618bool DraftPolicy::explore_ok() const {
619    const double age = busy_age_ < 0.0 ? 0.0 : busy_age_;
620    if (age <= CostLearner::kFreshS) return true;     // a fresh round: it counts on every machine
621    return learner_.state_known(bk_, 20) && !learner_.state_effect(bk_, 20);   // a late round counts only where the stretch has shown no state effect
622}
623
624int DraftPolicy::explore_next(int reach, int skip) const {
625    if (learner_.rounds() + learner_.late_rounds() < kExploreAfter || forced_total_ >= kExploreBudget || !explore_ok()) return 0;
626    for (int s = 2; s <= std::min(reach, max_t_); ++s) {
627        if (s == skip || !allowed(s) || forced_[(size_t) s] >= kExplorePerSize || learner_.usable(bk_, s, 20) >= kExploreN) continue;
628        ++forced_[(size_t) s];
629        ++forced_total_;
630        return s;
631    }
632    return 0;
633}
634
635int DraftPolicy::explore_size(int lookup_k, int pad_cap) const {
636    return explore_next(std::max(lookup_k, pad_cap) + 1, 0);
637}
638
639int DraftPolicy::explore_lookup(int cap) const {
640    if (!learning_ || fixed_) return 0;
641    return explore_next(cap, 0);
642}
643
644int DraftPolicy::explore_window(int t, int cap) const {
645    if (!learning_ || fixed_) return 0;
646    return explore_next(cap, t);
647}
648
649void DraftPolicy::observe_forced(int t, double round_ms) {
650    t = std::clamp(t, 1, kMaxT);
651    if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_);
652    if (round_ms > 0 && !fixed_) {
653        round_ms = clamp_sample(t, round_ms);
654        const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha;
655        cost_[bk_][t] = cost_n_[bk_][t] > 0 ? (1.0 - alpha) * cost_[bk_][t] + alpha * round_ms : round_ms;
656        cost_n_[bk_][t] += 1.0;
657        last_[bk_][t] = rounds_;
658    }
659    rounds_ += 1.0;
660}
661
662void DraftPolicy::reset_learning() {
663    learner_.reset();
664    forced_total_ = 0;
665    forced_.fill(0);
666}
667
668void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) {
669    t = std::clamp(t, 1, kMaxT);
670    if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_);
671    if (calib_on_ && round_ms > 0) calib_add(bk_, t, round_ms, busy_age_);
672    if (round_ms > 0 && !fixed_) {
673        round_ms = clamp_sample(t, round_ms);
674        const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha;   // a running mean for the first samples
675        cost_[bk_][t] = cost_n_[bk_][t] > 0 ? (1.0 - alpha) * cost_[bk_][t] + alpha * round_ms : round_ms;
676        cost_n_[bk_][t] += 1.0;
677        last_[bk_][t] = rounds_;
678    }
679    rounds_ += 1.0;
680    if (lookup) {
681        const int b = bucket(match);
682        ok_[b] = kDecay * ok_[b] + accepted;
683        bad_[b] = kDecay * bad_[b] + (accepted < t - 1 ? 1.0 : 0.0);
684    } else {
685        const double got = accepted + 1.0;
686        mtp_tok_[t] = mtp_n_[t] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t] + kTokAlpha * got : got;
687        mtp_n_[t] += 1.0;
688    }
689}
690
691// ---- calibration of a fixed table against real requests (see the header)
692
693void DraftPolicy::apply_table() {
694    if (!fixed_) return;   // a held table: cost_ is the live cost, not touched
695    for (int k = 0; k < kCtxBuckets; ++k) {
696        const int n = fixed_n_[(size_t) k];
697        if (n <= 0) continue;
698        // 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
699        // 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
700        double sum = 0.0;
701        int cnt = 0;
702        for (int t = 2; t <= n; ++t)
703            if ((real_[(size_t) k] >> (t - 1) & 1u) && learned_[(size_t) k][(size_t) t] > 0.0) {
704                sum += real_cost_[(size_t) k][(size_t) t] / learned_[(size_t) k][(size_t) t];
705                ++cnt;
706            }
707        const double r = cnt > 0 ? sum / cnt : 1.0;
708        for (int t = 1; t <= n; ++t) {
709            if (real_[(size_t) k] >> (t - 1) & 1u) cost_[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t];
710            else cost_[(size_t) k][(size_t) t] = learned_[(size_t) k][(size_t) t] * (t >= 2 ? r : 1.0);
711        }
712        // 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
713        // 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,
714        // 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);
715        // a real size above an unreached next size is left, and the forward pass then lifts that guess to it
716        for (int t = n - 1; t >= 1; --t) {
717            const bool real_t = real_[(size_t) k] >> (t - 1) & 1u, real_next = real_[(size_t) k] >> t & 1u;
718            if (cost_[(size_t) k][(size_t) t] > cost_[(size_t) k][(size_t) t + 1] && (!real_t || real_next))
719                cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t + 1];
720        }
721        for (int t = 2; t <= n; ++t)
722            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];
723    }
724}
725
726void DraftPolicy::start_calibration(bool state_effect, const std::array<unsigned, kCtxBuckets>& real,
727                                    const std::array<std::array<CalAcc, kMaxT + 1>, kCtxBuckets>& cal,
728                                    const std::array<std::array<double, kMaxT + 1>, kCtxBuckets>& real_cost, int reqs) {
729    reqs_ = std::max(reqs, 0);
730    calib_fresh_only_ = state_effect;
731    real_ = real;
732    cal_ = cal;
733    real_cost_ = real_cost;
734    for (int k = 0; k < kCtxBuckets; ++k)   // a mark without a cost (a damaged file) is no mark
735        for (int t = 1; t <= kMaxT; ++t)
736            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));
737    apply_table();
738    calib_dirty_ = false;
739    calib_on_ = false;
740    for (int k = 0; k < kCtxBuckets; ++k) {
741        const int n = fixed_n_[(size_t) k];
742        for (int t = 1; t <= n; ++t)
743            if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true;
744    }
745    // not calibrated: live costs decide, as without a table, until kCalibReqs requests have collected real rounds (a size real requests do not reach
746    // would hold the table back for good)
747    if (calib_on_ && reqs_ < kCalibReqs && fixed_ && live_saved_) hold_table();
748}
749
750void DraftPolicy::start_passive(const CostFile& cf, int n) {
751    passive_ = true;
752    calib_fresh_only_ = true;   // see the header: only the first seconds of a busy run count, no detection of a load-time effect
753    real_ = {};
754    real_[0] = cf.real[0];
755    cal_ = {};
756    cal_[0] = cf.cal[0];
757    real_cost_ = {};
758    real_cost_[0] = cf.real_cost[0];
759    learned_ = {};
760    fixed_n_ = {};
761    fixed_n_[0] = std::clamp(n, 1, kMaxT);
762    for (int t = 1; t <= kMaxT; ++t)   // a mark without a cost (a damaged file) is no mark; a size past the table length is none
763        if ((real_[0] >> (t - 1) & 1u) && (!(real_cost_[0][(size_t) t] > 0.0) || t > fixed_n_[0])) real_[0] &= ~(1u << (t - 1));
764    reqs_ = std::max(cf.reqs, 0);
765    held_table_ = true;
766    fixed_ = false;
767    calib_on_ = true;
768    calib_dirty_ = false;
769}
770
771void DraftPolicy::take_over_passive() {
772    const int bk_was = bk_;
773    for (int k = 0; k < kCtxBuckets; ++k) {
774        const int n = fixed_n_[(size_t) k];
775        for (int t = 1; t <= n; ++t) {
776            double v;
777            if (real_[(size_t) k] >> (t - 1) & 1u) v = real_cost_[(size_t) k][(size_t) t];   // a real size: its own cost
778            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
779            else {
780                bk_ = k;
781                v = cost_ms(t);   // never measured: the policy's own prior, as without a table
782                bk_ = bk_was;
783            }
784            if (!(v > 0.0)) v = t > 1 ? learned_[(size_t) k][(size_t) t - 1] : 1.0;
785            learned_[(size_t) k][(size_t) t] = v;
786        }
787    }
788    passive_ = false;
789}
790
791void DraftPolicy::hold_table() {
792    for (int k = 0; k < kCtxBuckets; ++k) {
793        if (fixed_n_[(size_t) k] <= 0) continue;
794        cost_[(size_t) k] = live_cost_[(size_t) k];
795        cost_n_[(size_t) k] = live_n_[(size_t) k];
796    }
797    fixed_ = false;
798    held_table_ = true;
799    held_.clear();
800}
801
802void DraftPolicy::use_table() {
803    fixed_ = true;
804    apply_table();   // every size is real: its real cost
805    for (int k = 0; k < kCtxBuckets; ++k) {
806        const int n = fixed_n_[(size_t) k];
807        if (n <= 0) continue;
808        for (int t = 1; t <= kMaxT; ++t) {
809            const bool in = t <= n && cost_[(size_t) k][(size_t) t] > 0.0;
810            if (!in) cost_[(size_t) k][(size_t) t] = 0.0;
811            cost_n_[(size_t) k][(size_t) t] = in ? 1e6 : 0.0;
812        }
813    }
814    fixed_ = true;
815    held_table_ = false;
816    held_.clear();
817}
818
819void DraftPolicy::calib_add(int bucket, int t, double ms, double age) {
820    static_assert(kCalibN <= CalAcc::kVals, "a size's rounds are all kept for the median");
821    if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > fixed_n_[(size_t) bucket]) return;
822    if (real_[(size_t) bucket] >> (t - 1) & 1u) return;
823    if (calib_fresh_only_ && age > CostLearner::kFreshS) return;   // the table is what rounds of the first seconds of a busy run cost
824    double base = learned_[(size_t) bucket][(size_t) t];
825    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
826    if (!(base > 0.0)) return;
827    CalAcc& a = cal_[(size_t) bucket][(size_t) t];
828    if (a.n >= kCalibN) return;
829    const double r = std::clamp(ms, kCalibLo * base, kCalibHi * base);   // one stalled round moves the mean by at most (kCalibHi - 1) / kCalibN
830    a.sum += r;
831    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
832    a.n += 1;
833    calib_dirty_ = true;
834}
835
836bool DraftPolicy::calibrate(CostFile& cf, std::string& report) {
837    report.clear();
838    if (!calib_on_ && !calib_dirty_) return false;
839    if (held_table_) ++reqs_;   // a request that ran while the table is held back
840    char b[96];
841    bool changed = calib_dirty_ || held_table_, replaced = false;   // a held table: the request count changed
842    for (int k = 0; k < kCtxBuckets; ++k) {
843        const int n = fixed_n_[(size_t) k];
844        for (int t = 1; t <= n; ++t) {
845            if (real_[(size_t) k] >> (t - 1) & 1u) continue;
846            CalAcc& a = cal_[(size_t) k][(size_t) t];
847            if (a.n < kCalibN) continue;
848            double v = a.sum / a.n;   // a file from before the kept rounds: the mean
849            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
850                std::array<double, CalAcc::kVals> s = a.vals;
851                std::sort(s.begin(), s.begin() + a.nv);
852                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]);
853            }
854            const double base = learned_[(size_t) k][(size_t) t];
855            if (!(base > 0.0) || (v >= kCalibOkLo * base && v <= kCalibOkHi * base)) {   // no learned cost (passive): the clamped rounds are taken as they are
856                if (base > 0.0) std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v);
857                else std::snprintf(b, sizeof b, "%s%d rows real %.2f", report.empty() ? "" : ", ", t, v);
858                report += b;
859                real_cost_[(size_t) k][(size_t) t] = v;
860                real_[(size_t) k] |= 1u << (t - 1);
861                replaced = true;
862            }
863            a = CalAcc{};   // replaced, or disturbed (rounds dropped, collected again)
864        }
865    }
866    if (replaced && fixed_) {   // the table is in use with sizes that were not reached: their scaled costs follow the real sizes
867        std::array<std::array<double, kMaxT + 1>, kCtxBuckets> before = cost_;
868        apply_table();
869        for (int k = 0; k < kCtxBuckets; ++k)
870            for (int t = 1; t <= fixed_n_[(size_t) k]; ++t)
871                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) {
872                    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]);
873                    report += b;
874                }
875    }
876    for (int k = 0; k < kCtxBuckets; ++k) {
877        const int n = fixed_n_[(size_t) k];
878        if (n <= 0) continue;
879        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
880        cf.real[(size_t) k] = real_[(size_t) k];
881        for (int t = 0; t <= kMaxT; ++t) {
882            cf.cal[(size_t) k][(size_t) t] = cal_[(size_t) k][(size_t) t];
883            cf.real_cost[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t];
884        }
885    }
886    cf.state_effect = calib_fresh_only_;
887    cf.reqs = reqs_;
888    cf.fresh = passive_;
889    calib_dirty_ = false;
890    calib_on_ = false;
891    for (int k = 0; k < kCtxBuckets; ++k)
892        for (int t = 1; t <= fixed_n_[(size_t) k]; ++t)
893            if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true;
894    // the last size is calibrated, or kCalibReqs requests have not reached the rest: the table decides from the next round on
895    if (held_table_ && (!calib_on_ || reqs_ >= kCalibReqs)) {
896        if (passive_) {
897            take_over_passive();
898            for (int k = 0; k < kCtxBuckets; ++k) {
899                const int n = fixed_n_[(size_t) k];
900                if (n > 0) cf.tables[(size_t) k].assign(learned_[(size_t) k].begin() + 1, learned_[(size_t) k].begin() + 1 + n);
901            }
902            cf.fresh = false;
903            changed = true;
904        }
905        use_table();
906        if (calib_on_) report += std::string(report.empty() ? "" : ", ") + "table in use, sizes real requests did not reach keep a scaled learned cost";
907    }
908    return changed || replaced;
909}
910
911void DraftPolicy::observe_committed(bool lookup, int t, int accepted, int match) {
912    t = std::clamp(t, 1, kMaxT);
913    rounds_ += 1.0;
914    if (lookup) {
915        tried_[bk_][t] += 1.0;
916        last_[bk_][t] = rounds_;   // tried now: not stale within this generation
917        const int b = bucket(match);
918        ok_[b] = kDecay * ok_[b] + accepted;
919        bad_[b] = kDecay * bad_[b] + (accepted < t - 1 ? 1.0 : 0.0);
920    } else {
921        const double got = accepted + 1.0;
922        mtp_tok_[t] = mtp_n_[t] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t] + kTokAlpha * got : got;
923        mtp_n_[t] += 1.0;
924    }
925}
926
927void DraftPolicy::defer_cost(int64_t end, int t, double round_ms) {
928    if (round_ms > 0 && (learning_ || calib_on_ || !fixed_)) held_.push_back({end, bk_, std::clamp(t, 1, kMaxT), round_ms, busy_age_});
929}
930
931void DraftPolicy::apply_costs(int64_t committed) {
932    size_t n = 0;
933    const int bucket_now = bk_;
934    for (; n < held_.size() && held_[n].end < committed; ++n) {
935        const HeldCost& h = held_[n];
936        if (learning_) learner_.add(h.bucket, h.t, h.ms, h.age);
937        if (calib_on_) calib_add(h.bucket, h.t, h.ms, h.age);
938        if (fixed_) continue;
939        bk_ = h.bucket;   // observe()'s update, in the bucket the round ran in
940        const double ms = clamp_sample(h.t, h.ms);
941        const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][h.t] + 1.0)) : kCostAlpha;
942        cost_[bk_][h.t] = cost_n_[bk_][h.t] > 0 ? (1.0 - alpha) * cost_[bk_][h.t] + alpha * ms : ms;
943        cost_n_[bk_][h.t] += 1.0;
944        delayed_n_[bk_][h.t] += 1.0;   // a round already counted by observe_committed
945        last_[bk_][h.t] = rounds_;
946    }
947    bk_ = bucket_now;
948    held_.erase(held_.begin(), held_.begin() + (std::ptrdiff_t) n);
949}
950
951namespace {
952int p_bucket(double p) {
953    const int b = (int) (p * 8.0);
954    return b < 0 ? 0 : b > 7 ? 7 : b;
955}
956}  // namespace
957
958// Until a bucket has data a draft is as likely to hold as the MTP says (worth kPriorN observations); measured
959// acceptance of the MTP chain is not the same as its own softmax (code and thinking text are over-confident).
960double DraftPolicy::draft_rate(double p) const {
961    const int b = p_bucket(p);
962    const double centre = std::clamp(p, 0.0, 1.0);
963    return (pa_ok_[b] + kPriorN * centre) / (pa_n_[b] + kPriorN);
964}
965
966void DraftPolicy::observe_probs(const float* p, int n, int accepted) {
967    // draft j was reached when the drafts before it held; it held when j < accepted
968    for (int j = 0; j < n && j <= accepted; ++j) {
969        const int b = p_bucket(p[j]);
970        pa_ok_[b] = kCalDecay * pa_ok_[b] + (j < accepted ? 1.0 : 0.0);
971        pa_n_[b] = kCalDecay * pa_n_[b] + 1.0;
972    }
973}
974
975bool DraftPolicy::keep_draft(ChainState& st, int idx, float p, int cap) const {
976    cap = std::clamp(cap, 1, max_t_);
977    if (idx == 0) {
978        st = ChainState{};
979        st.best_v = 1.0 / cost_ms(1);
980    }
981    const double a = draft_rate(p);
982    st.q *= a;
983    st.e += st.q;
984    const int rows = idx + 2;
985    if (rows <= cap) {
986        const double v = st.e / cost_ms(rows);
987        if (v > st.best_v * (1.0 + margin_ / 3.0)) {
988            st.best_v = v;
989            st.best_rows = rows;
990        }
991        // a width not measured yet is tried a few times when the chain is likely to hold that far
992        if (!fixed_ && cost_n_[bk_][rows] < kProbes && st.q >= 0.15) st.best_rows = rows;
993    }
994    st.kept = st.best_rows - 1;
995    if (rows + 1 > cap) return false;                       // no row left for another draft
996    // one or two more drafts, each as likely to hold as this one did, could they beat the best width so far?
997    const double v1 = (st.e + st.q * a) / cost_ms(rows + 1);
998    const double v2 = rows + 2 <= cap ? (st.e + st.q * a + st.q * a * a) / cost_ms(rows + 2) : 0.0;
999    return std::max(v1, v2) > st.best_v * (1.0 + margin_ / 3.0) || (!fixed_ && cost_n_[bk_][rows + 1] < kProbes && st.q * a >= 0.15);
1000}
1001
1002double DraftPolicy::chain_rate(int match) const {
1003    // prior: a chained draft is a lookup continuing the MTP's drafts - weaker evidence than a plain match of that length
1004    constexpr double kChainPrior[kBuckets] = {0.45, 0.65, 0.8, 0.9};
1005    const int b = bucket(match);
1006    return (cok_[b] + kPriorN * kChainPrior[b]) / (cok_[b] + cbad_[b] + kPriorN);
1007}
1008
1009int DraftPolicy::chain(int t_mtp, double p_mtp, int k_avail, int match) const {
1010    t_mtp = std::clamp(t_mtp, 1, max_t_);
1011    const int kmax = std::min(k_avail, max_t_ - t_mtp);
1012    if (kmax <= 0) return 0;
1013    const double e0 = mtp_tokens(t_mtp), base = e0 / cost_ms(t_mtp), c = chain_rate(match);
1014    p_mtp = std::clamp(p_mtp, 0.0, 1.0);
1015    double gain = 0.0, ci = 1.0, best = 0.0;
1016    int best_k = 0;
1017    for (int k = 1; k <= kmax; ++k) {
1018        ci *= c;
1019        gain += ci;
1020        if (!allowed(t_mtp + k)) continue;
1021        const double r = (e0 + p_mtp * gain) / cost_ms(t_mtp + k);
1022        if (r > best) { best = r; best_k = k; }
1023    }
1024    const int t_full = fit(t_mtp + kmax), k_full = t_full - t_mtp;
1025    if (best_k > 0 && best > base * (1.0 + margin_)) {
1026        // As choose(): a profitable shorter chain must not keep a stale full size from being measured again.
1027        if (best_k < k_full && p_mtp * c >= 0.6 && stale(t_full)) return k_full;
1028        return best_k;
1029    }
1030    // as choose(): a size whose cost is only guessed is tried a few times when the continuation looks likely
1031    if (!fixed_ && k_full > 0 && (cost_n_[bk_][t_full] < kProbes || stale(t_full)) && p_mtp * c >= 0.6) return k_full;
1032    return 0;
1033}
1034
1035void DraftPolicy::observe_chain(int t_mtp, int k, int accepted, int match, double round_ms) {
1036    const int t = std::clamp(t_mtp + k, 1, kMaxT);
1037    if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_);
1038    if (round_ms > 0 && !fixed_) {
1039        round_ms = clamp_sample(t, round_ms);
1040        const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha;   // a running mean for the first samples
1041        cost_[bk_][t] = cost_n_[bk_][t] > 0 ? (1.0 - alpha) * cost_[bk_][t] + alpha * round_ms : round_ms;
1042        cost_n_[bk_][t] += 1.0;
1043        last_[bk_][t] = rounds_;
1044    }
1045    rounds_ += 1.0;
1046    // the MTP part is an ordinary MTP window as far as its own drafts go
1047    const int mtp_acc = std::min(accepted, t_mtp - 1);
1048    const double got = mtp_acc + 1.0;
1049    mtp_tok_[t_mtp] = mtp_n_[t_mtp] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t_mtp] + kTokAlpha * got : got;
1050    mtp_n_[t_mtp] += 1.0;
1051    if (accepted < t_mtp - 1) return;   // the chain was never reached: it says nothing about the lookup
1052    const int b = bucket(match), ok = accepted - (t_mtp - 1);
1053    cok_[b] = kDecay * cok_[b] + ok;
1054    cbad_[b] = kDecay * cbad_[b] + (ok < k ? 1.0 : 0.0);
1055}
1056
1057}  // namespace strata::spec