okami.mom/strata

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

Niko1221Merge branch 'f-1402-p' into f-1402c954f5bd1

main
17.2 KiB368 linesraw
1// src/core/spec_prob_test.cpp - probabilistic draft acceptance (include/strata/core/spec_prob.hpp), no GPU.
2//
3// A reference rejection sampler on synthetic target distributions p and drafter distributions q over a 16-token
4// vocabulary; 2,000,000 trials per case.  Each trial draws a draft d from q, judges it with spec_verify_row and
5// records the token the row emits; a chi-square test (99.9% bound) compares the emitted histogram with p.  If
6// min(1, p/q) plus the residual preserved p only approximately the test would fail; two controls with a deliberately
7// wrong rule must fail it, which shows the test can tell.
8//
9// The cases: q = p; q = a point mass (the argmax draft, no list); q disjoint from p; q's support wider than p's; the
10// draft head's argmax outside p's support (p(d) = 0); a perturbed q.  The chains: top_k 1, 5, 64; top_p 0.5, 0.95;
11// min_p 0.1; temperature 0.3, 1.0, 1.5 - p and q each cut by their OWN chain (q never borrows p's cut), the sampler's
12// own arithmetic (top_p's cut in double over the top_k list, min_p in logit space, temperature after).
13// Then a two-token WINDOW over a tiny Markov model checks the JOINT of the first two tokens (a wrong residual shows
14// up in the pairs first), with a draft of depth 2 whose second row is conditioned on the first draft.
15// Truncation regressions: a point-mass row inside a window that also has q rows (a lookup chain's tail) behaves as
16// exact match (accept probability p(d)), and "no list" is never "q = 0".
17#include "strata/core/spec_prob.hpp"
18
19#include <algorithm>
20#include <cmath>
21#include <cstdio>
22#include <random>
23#include <vector>
24
25using namespace strata::core;
26
27namespace {
28
29constexpr int V = 16;
30int g_fail = 0;
31int g_cases = 0;
32
33struct Chain {
34    int top_k;
35    float top_p;
36    float min_p;
37    float temp;
38};
39
40struct List {
41    std::vector<int32_t> id;
42    std::vector<double> p;
43    std::vector<float> q;   // the same probabilities as float, a drafter's list
44};
45
46// the sampler's chain over logits (no penalties): top_k list in selection order, top_p cut in double on the raw
47// logits, min_p in logit space, temperature, normalise (sampled_probs_warp)
48List chain_list(const std::vector<float>& logit, const Chain& c) {
49    std::vector<int> ord(V);
50    for (int i = 0; i < V; ++i) ord[i] = i;
51    std::stable_sort(ord.begin(), ord.end(), [&](int a, int b) { return logit[a] > logit[b]; });
52    const int k = std::min(V, (c.top_k > 0 && c.top_k < 64) ? c.top_k : 64);
53    int n_keep = k;
54    const float mx = logit[ord[0]];
55    if (c.top_p < 1.0f) {
56        double sum = 0.0;
57        std::vector<double> e(k);
58        for (int i = 0; i < k; ++i) { e[i] = std::exp((double) logit[ord[i]] - (double) mx); sum += e[i]; }
59        double cum = 0.0;
60        int cut = k;
61        for (int i = 0; i < k; ++i) {
62            cum += e[i] / sum;
63            if (cum >= (double) c.top_p) { cut = i + 1; break; }
64        }
65        n_keep = std::max(cut, 1);
66    }
67    if (c.min_p > 0.0f) {
68        const float thresh = logit[ord[0]] + std::log(c.min_p);
69        for (int i = 0; i < n_keep; ++i)
70            if (logit[ord[i]] < thresh) { n_keep = i; break; }
71    }
72    const float inv_t = 1.0f / c.temp;
73    float smx = logit[ord[0]] * inv_t;
74    for (int i = 1; i < n_keep; ++i) smx = std::max(smx, logit[ord[i]] * inv_t);
75    List L;
76    double sum = 0.0;
77    for (int i = 0; i < n_keep; ++i) {
78        L.id.push_back(ord[i]);
79        L.p.push_back(std::exp((double) (logit[ord[i]] * inv_t) - (double) smx));
80        sum += L.p.back();
81    }
82    for (double& x : L.p) x /= sum;
83    for (double x : L.p) L.q.push_back((float) x);
84    return L;
85}
86
87float uni(std::mt19937_64& g) { return (float) (g() >> 40) * (1.0f / 16777216.0f); }
88
89int32_t draw(const List& L, float u) {   // the sampler's inverse-CDF pick
90    double cum = 0.0;
91    int32_t pick = L.id.back();
92    for (size_t i = 0; i < L.id.size(); ++i) {
93        cum += L.p[i];
94        if ((double) u < cum) { pick = L.id[i]; break; }
95    }
96    return pick;
97}
98
99// chi-square statistic of `count` against probabilities `prob` (cells with expectation < 5 are pooled), and the 99.9%
100// critical value for its degrees of freedom (Wilson-Hilferty)
101struct Chi { double stat; int df; double crit; };
102Chi chi_square(const std::vector<double>& count, const std::vector<double>& prob, double n) {
103    double stat = 0.0, pool_o = 0.0, pool_e = 0.0;
104    int cells = 0;
105    for (size_t i = 0; i < count.size(); ++i) {
106        const double e = prob[i] * n;
107        if (e < 5.0) { pool_o += count[i]; pool_e += e; continue; }
108        stat += (count[i] - e) * (count[i] - e) / e;
109        ++cells;
110    }
111    if (pool_e >= 5.0) { stat += (pool_o - pool_e) * (pool_o - pool_e) / pool_e; ++cells; }
112    else if (pool_o > pool_e + 6.0 * std::sqrt(pool_e) + 10.0) stat += 1e9;   // far more hits than the thin tail's expectation
113    const int df = std::max(1, cells - 1);
114    const double z = 3.0902;   // 99.9%
115    const double a = 2.0 / (9.0 * df);
116    const double crit = df * std::pow(1.0 - a + z * std::sqrt(a), 3.0);
117    return {stat, df, crit};
118}
119
120void report(const char* name, const Chi& c, bool expect_fail = false) {
121    ++g_cases;
122    const bool pass = c.stat <= c.crit;
123    const bool ok = expect_fail ? !pass : pass;
124    if (!ok) ++g_fail;
125    std::printf("  %-4s %-58s chi2 %9.1f  df %2d  bound %6.1f%s\n", ok ? "ok" : "FAIL", name, c.stat, c.df, c.crit,
126                expect_fail ? "  (control: must fail)" : "");
127}
128
129enum class Rule { Standard, AlwaysAccept, NoListMeansZeroQ };
130
131// one row: draw d from q, judge it
132int32_t one_trial(std::mt19937_64& g, const List& P, const List* Q, int32_t point_d, Rule rule, bool* accepted) {
133    const SpecP sp{P.id.data(), P.p.data(), (int) P.id.size()};
134    int32_t d;
135    SpecQ sq{nullptr, nullptr, -1};
136    if (Q != nullptr) {
137        d = draw(*Q, uni(g));
138        sq = SpecQ{Q->id.data(), Q->q.data(), (int) Q->id.size()};
139    } else {
140        d = point_d;
141    }
142    const float ua = uni(g), ur = uni(g);
143    SpecResult r = spec_verify_row(sp, d, sq, ua, ur);
144    if (rule == Rule::AlwaysAccept) r = {d, 1};
145    if (rule == Rule::NoListMeansZeroQ && Q == nullptr) r = {d, 0};   // "no q: q = 0": reject; (the residual is then p)
146    if (rule == Rule::NoListMeansZeroQ && Q == nullptr) r.token = draw(P, ur);
147    *accepted = r.accepted != 0;
148    return r.token;
149}
150
151struct Setup {
152    const char* name;
153    List P;
154    List Q;
155    bool point;     // q is a point mass at its argmax: no list
156    int32_t d_point;
157};
158
159void run_case(const Setup& S, int trials, std::mt19937_64& g, Rule rule, bool expect_fail, double* acc_rate) {
160    std::vector<double> cnt(V, 0.0), prob(V, 0.0);
161    for (size_t i = 0; i < S.P.id.size(); ++i) prob[(size_t) S.P.id[i]] = S.P.p[i];
162    long long acc = 0;
163    for (int t = 0; t < trials; ++t) {
164        bool a = false;
165        const int32_t tok = one_trial(g, S.P, S.point ? nullptr : &S.Q, S.d_point, rule, &a);
166        cnt[(size_t) tok] += 1.0;
167        acc += a;
168    }
169    // a token outside p's support must never be emitted
170    double outside = 0.0;
171    for (int i = 0; i < V; ++i)
172        if (prob[(size_t) i] == 0.0) outside += cnt[(size_t) i];
173    Chi c = chi_square(cnt, prob, (double) trials);
174    if (outside > 0.0) c.stat += 1e9;
175    if (acc_rate) *acc_rate = (double) acc / trials;
176    char nm[160];
177    std::snprintf(nm, sizeof nm, "%s (accept %.3f)", S.name, (double) acc / trials);
178    report(nm, c, expect_fail);
179}
180
181std::vector<float> rand_logits(std::mt19937_64& g, float spread) {
182    std::normal_distribution<float> nd(0.0f, spread);
183    std::vector<float> l(V);
184    for (float& x : l) x = nd(g);
185    return l;
186}
187
188}  // namespace
189
190int main() {
191    std::mt19937_64 g(20261006);
192    const int N = 2000000;
193    const std::vector<Chain> chains = {{64, 1.0f, 0.0f, 1.0f},  {1, 1.0f, 0.0f, 1.0f},   {5, 1.0f, 0.0f, 1.0f},
194                                       {64, 0.5f, 0.0f, 1.0f},  {64, 0.95f, 0.0f, 1.0f}, {20, 0.95f, 0.05f, 0.7f},
195                                       {64, 1.0f, 0.1f, 1.0f},  {64, 1.0f, 0.0f, 0.3f},  {64, 1.0f, 0.0f, 1.5f},
196                                       {8, 0.9f, 0.02f, 1.0f}};
197    std::printf("spec_prob_test: %d trials per case, 16-token vocabulary\n", N);
198    for (const Chain& c : chains) {
199        std::printf("chain top_k %d top_p %.2f min_p %.2f temp %.1f\n", c.top_k, c.top_p, c.min_p, c.temp);
200        const std::vector<float> lp = rand_logits(g, 2.0f);
201        const List P = chain_list(lp, c);
202        // q = p
203        run_case({"q = p", P, P, false, 0}, N, g, Rule::Standard, false, nullptr);
204        // a perturbed q (the typical drafter), cut by its own chain
205        std::vector<float> lq = lp;
206        std::normal_distribution<float> nd(0.0f, 0.8f);
207        for (float& x : lq) x += nd(g);
208        run_case({"perturbed q", P, chain_list(lq, c), false, 0}, N, g, Rule::Standard, false, nullptr);
209        // q a point mass at its argmax (no list: the argmax draft)
210        {
211            const List Qp = chain_list(lq, Chain{1, 1.0f, 0.0f, 1.0f});
212            run_case({"q = point mass (argmax draft, no list)", P, Qp, true, Qp.id[0]}, N, g, Rule::Standard, false,
213                     nullptr);
214        }
215        // q disjoint from p: the drafter's top tokens are the target's tail
216        {
217            std::vector<float> ld(V);
218            for (int i = 0; i < V; ++i) ld[i] = -lp[i];
219            run_case({"q disjoint from p (inverted logits)", P, chain_list(ld, c), false, 0}, N, g, Rule::Standard,
220                     false, nullptr);
221        }
222        // q's support wider than p's: p cut hard, q uncut
223        run_case({"q support wider than p's", P, chain_list(lq, Chain{64, 1.0f, 0.0f, 1.0f}), false, 0}, N, g,
224                 Rule::Standard, false, nullptr);
225        // the drafter's argmax is outside p's support: p(d) = 0 for the point-mass draft
226        {
227            const List Qp = chain_list(lq, Chain{1, 1.0f, 0.0f, 1.0f});
228            std::vector<float> lo = lp;
229            lo[(size_t) Qp.id[0]] = -50.0f;   // the target gives the drafter's favourite no mass
230            const List Po = chain_list(lo, c);
231            run_case({"p(argmax draft) = 0, point mass", Po, Qp, true, Qp.id[0]}, N, g, Rule::Standard, false, nullptr);
232        }
233    }
234    // controls: wrong rules must fail the test
235    {
236        std::printf("controls\n");
237        const Chain c{64, 0.95f, 0.0f, 1.0f};
238        const std::vector<float> lp = rand_logits(g, 2.0f);
239        std::vector<float> lq = lp;
240        std::normal_distribution<float> nd(0.0f, 1.0f);
241        for (float& x : lq) x += nd(g);
242        const List P = chain_list(lp, c);
243        run_case({"always accept the draft", P, chain_list(lq, c), false, 0}, 200000, g, Rule::AlwaysAccept, true,
244                 nullptr);
245        const List Qp = chain_list(lq, Chain{1, 1.0f, 0.0f, 1.0f});
246        const double pd = [&] { double v = 0; for (size_t i = 0; i < P.id.size(); ++i) if (P.id[i] == Qp.id[0]) v = P.p[i]; return v; }();
247        double acc_std = 0, acc_zero = 0;
248        run_case({"point mass, standard rule", P, Qp, true, Qp.id[0]}, 200000, g, Rule::Standard, false, &acc_std);
249        run_case({"point mass, 'no list = q 0' (rejects all: #29924)", P, Qp, true, Qp.id[0]}, 200000, g,
250                 Rule::NoListMeansZeroQ, false, &acc_zero);
251        ++g_cases;
252        const bool ok = std::fabs(acc_std - pd) < 0.01 && acc_zero == 0.0;
253        if (!ok) ++g_fail;
254        std::printf("  %-4s point-mass accept rate %.4f = p(d) %.4f; the q = 0 rule accepts %.4f\n", ok ? "ok" : "FAIL",
255                    acc_std, pd, acc_zero);
256    }
257
258    // ---- the JOINT of the first two tokens over a Markov model, drafts of depth 2.
259    // p0 over x0, p1(. | x0) over x1; the drafter q0, q1(. | d0) are perturbations; window = [d0, d1] verified by two
260    // rows, then the continuation: after an accepted row the next row's pick; after a reject the row's own residual
261    // token is x0 and the NEXT window starts from it (a plain sample of x1 from p1(. | x0)).
262    for (const Chain& c : std::vector<Chain>{{64, 1.0f, 0.0f, 1.0f}, {20, 0.95f, 0.05f, 0.7f}, {5, 0.5f, 0.0f, 1.5f}}) {
263        std::printf("joint (x0, x1) over a Markov model: top_k %d top_p %.2f min_p %.2f temp %.1f\n", c.top_k, c.top_p,
264                    c.min_p, c.temp);
265        std::vector<List> P1(V), Q1(V);
266        const std::vector<float> l0 = rand_logits(g, 1.5f);
267        std::vector<float> m0 = l0;
268        std::normal_distribution<float> nd(0.0f, 0.9f);
269        for (float& x : m0) x += nd(g);
270        const List P0 = chain_list(l0, c), Q0 = chain_list(m0, c);
271        for (int a = 0; a < V; ++a) {
272            const std::vector<float> l1 = rand_logits(g, 1.5f);
273            std::vector<float> m1 = l1;
274            for (float& x : m1) x += nd(g);
275            P1[(size_t) a] = chain_list(l1, c);
276            Q1[(size_t) a] = chain_list(m1, c);
277        }
278        std::vector<double> cnt((size_t) V * V, 0.0), prob((size_t) V * V, 0.0);
279        for (size_t i = 0; i < P0.id.size(); ++i)
280            for (size_t j = 0; j < P1[(size_t) P0.id[i]].id.size(); ++j)
281                prob[(size_t) P0.id[i] * V + (size_t) P1[(size_t) P0.id[i]].id[j]] = P0.p[i] * P1[(size_t) P0.id[i]].p[j];
282        long long acc_tokens = 0;
283        for (int t = 0; t < N; ++t) {
284            const int32_t d0 = draw(Q0, uni(g));
285            const int32_t d1 = draw(Q1[(size_t) d0], uni(g));
286            // row 0 judges d0 against p0
287            const SpecP s0{P0.id.data(), P0.p.data(), (int) P0.id.size()};
288            const SpecQ q0{Q0.id.data(), Q0.q.data(), (int) Q0.id.size()};
289            const float a0 = uni(g), r0 = uni(g);
290            const SpecResult r = spec_verify_row(s0, d0, q0, a0, r0);
291            const int32_t x0 = r.token;
292            int32_t x1;
293            if (r.accepted) {
294                // row 1 (conditioned on the window's d0 == x0) judges d1 against p1(. | d0)
295                const List& P = P1[(size_t) x0];
296                const SpecP s1{P.id.data(), P.p.data(), (int) P.id.size()};
297                const List& Q = Q1[(size_t) d0];
298                const SpecQ q1{Q.id.data(), Q.q.data(), (int) Q.id.size()};
299                const float a1 = uni(g), r1 = uni(g);
300                x1 = spec_verify_row(s1, d1, q1, a1, r1).token;
301                ++acc_tokens;
302            } else {
303                x1 = draw(P1[(size_t) x0], uni(g));   // the next window: row 0 of a fresh window, plain
304            }
305            cnt[(size_t) x0 * V + (size_t) x1] += 1.0;
306        }
307        char nm[96];
308        std::snprintf(nm, sizeof nm, "joint of 2 tokens (row-0 kept %.3f)", (double) acc_tokens / N);
309        report(nm, chi_square(cnt, prob, (double) N));
310    }
311
312    // ---- truncation regressions
313    {
314        std::printf("truncation regressions\n");
315        // a window of 3 drafts: rows 0 and 1 carry q lists, row 2 is a lookup chain's point-mass tail.  Row 2 must
316        // accept with probability p(d) (exact match), whatever the lists are, and a shortened draft (n_q smaller than
317        // the number of drafts: the tail now starts earlier) must not inherit an empty list as q = 0.
318        const Chain c{20, 0.95f, 0.0f, 0.7f};
319        const List P = chain_list(rand_logits(g, 2.0f), c);
320        const SpecP sp{P.id.data(), P.p.data(), (int) P.id.size()};
321        for (size_t pick : {0u, 1u, 3u}) {
322            const int32_t d = P.id[std::min(pick, P.id.size() - 1)];
323            long long acc = 0;
324            const int n = 400000;
325            for (int t = 0; t < n; ++t) acc += spec_verify_row(sp, d, SpecQ{nullptr, nullptr, -1}, uni(g), uni(g)).accepted;
326            double pd = 0;
327            for (size_t i = 0; i < P.id.size(); ++i) if (P.id[i] == d) pd = P.p[i];
328            ++g_cases;
329            const double rate = (double) acc / n, se = std::sqrt(pd * (1 - pd) / n);
330            const bool ok = std::fabs(rate - pd) < 4.5 * se + 1e-9;
331            if (!ok) ++g_fail;
332            std::printf("  %-4s point-mass row: accept %.4f vs p(d) %.4f (4.5 se %.4f)\n", ok ? "ok" : "FAIL", rate, pd,
333                        4.5 * se);
334        }
335        // a draft outside p's support (cut by top_p / top_k / min_p) is rejected and the replacement is in p's support
336        const int32_t outside = [&] {
337            for (int v = 0; v < V; ++v) {
338                bool in = false;
339                for (int32_t id : P.id) in = in || id == v;
340                if (!in) return v;
341            }
342            return -1;
343        }();
344        long long bad = 0;
345        for (int t = 0; t < 100000 && outside >= 0; ++t) {
346            const SpecResult r = spec_verify_row(sp, outside, SpecQ{nullptr, nullptr, -1}, uni(g), uni(g));
347            bad += r.accepted || r.token == outside;
348        }
349        ++g_cases;
350        if (bad != 0 || outside < 0) ++g_fail;
351        std::printf("  %-4s a draft outside top_k/top_p/min_p support is always rejected, replaced inside p (%lld bad)\n",
352                    (bad == 0 && outside >= 0) ? "ok" : "FAIL", bad);
353        // p == q everywhere: always accepted (min(1, p/q) = 1), never a 0 / 0
354        long long rej = 0;
355        const List Q = P;
356        const SpecQ sq{Q.id.data(), Q.q.data(), (int) Q.id.size()};
357        for (int t = 0; t < 200000; ++t) {
358            const int32_t d = draw(Q, uni(g));
359            rej += !spec_verify_row(sp, d, sq, uni(g), uni(g)).accepted;
360        }
361        ++g_cases;
362        if (rej != 0) ++g_fail;
363        std::printf("  %-4s p == q: every draft is accepted (%lld rejected)\n", rej == 0 ? "ok" : "FAIL", rej);
364    }
365
366    std::printf("spec_prob_test: %d cases, %d failed\n", g_cases, g_fail);
367    return g_fail == 0 ? 0 : 1;
368}