okami.mom/strata

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

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

main
13.0 KiB247 linesraw
1// src/kernels/spec_verify_parity.cpp - the GPU verifier of probabilistic draft acceptance (sample_tokens_spec) against
2// the host reference (include/strata/core/spec_prob.hpp), token for token.
3//
4// Random logits at three vocabulary sizes (one block, a few blocks, the engine's 248,320), windows of 2..8 rows,
5// chains with top_k / top_p / min_p / temperature and repetition penalties over a per-row history, drafts taken from
6// the row's own top tokens, outside them, and from q; q lists cut by a DIFFERENT chain than p's; n_q from 0 (every
7// row a point mass) to all rows.  The host computes p the sampler's way (penalties on the raw logits, top_k with
8// ties to the lowest index, top_p's cut in double, min_p in logit space, temperature), the Philox draws of the kernel
9// (u_pick = pos, u_accept = pos | 1<<62, u_resid = pos | 1<<63), and judges every row with spec_verify_row /
10// spec_sample.  Every out[t] must match, accepted or not.  Needs a GPU.
11#include "strata/core/spec_prob.hpp"
12#include "strata/kernels/sampler.hpp"
13
14#include <cuda_runtime.h>
15
16#include <algorithm>
17#include <cmath>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <random>
22#include <vector>
23
24using strata::core::SpecP;
25using strata::core::SpecQ;
26using strata::kernels::SamplerParams;
27
28namespace {
29
30void check(cudaError_t e, const char* what) {
31    if (e != cudaSuccess) {
32        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
33        std::exit(1);
34    }
35}
36
37float host_philox_uniform(uint64_t seed, uint64_t counter) {
38    uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32);
39    uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32);
40    for (int i = 0; i < 10; ++i) {
41        const uint32_t hi0 = (uint32_t) (((uint64_t) 0x9E3779B9u * c0) >> 32);
42        const uint32_t hi1 = (uint32_t) (((uint64_t) 0xBB67AE85u * c2) >> 32);
43        const uint32_t lo0 = 0x9E3779B9u * c0;
44        const uint32_t lo1 = 0xBB67AE85u * c2;
45        const uint32_t n0 = hi1 ^ c1 ^ (uint32_t) i;
46        const uint32_t n2 = hi0 ^ c3 ^ 0u;
47        c0 = n0; c1 = lo1; c2 = n2; c3 = lo0;
48    }
49    return (float) (c0 >> 8) * (1.0f / 16777216.0f);
50}
51
52struct PList {
53    std::vector<int32_t> id;
54    std::vector<double> p;
55    std::vector<float> pf;
56};
57
58// the sampler's chain over one row (penalties over `hist`), as sampled_reference in sampler_parity.cpp
59PList chain_list(const std::vector<float>& l, const std::vector<int>& hist, const SamplerParams& p) {
60    auto penal = [&](float logit, int count) {
61        if (count <= 0) return logit;
62        if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat;
63        logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
64        return logit;
65    };
66    const int nv = (int) l.size();
67    std::vector<float> s((size_t) nv);
68    for (int v = 0; v < nv; ++v) s[(size_t) v] = l[(size_t) v];
69    if (p.penalty_last_n > 0) {
70        std::vector<int> cnt((size_t) nv, 0);
71        const int h = (int) hist.size();
72        for (int i = std::max(0, h - p.penalty_last_n); i < h; ++i)
73            if (hist[(size_t) i] >= 0 && hist[(size_t) i] < nv) ++cnt[(size_t) hist[(size_t) i]];
74        for (int v = 0; v < nv; ++v) s[(size_t) v] = penal(s[(size_t) v], cnt[(size_t) v]);
75    }
76    const int k = std::min(nv, (p.top_k > 0 && p.top_k < 64) ? p.top_k : 64);
77    std::vector<int> idx((size_t) nv);
78    for (int i = 0; i < nv; ++i) idx[(size_t) i] = i;
79    std::partial_sort(idx.begin(), idx.begin() + k, idx.end(), [&](int a, int b) {
80        return s[(size_t) a] > s[(size_t) b] || (s[(size_t) a] == s[(size_t) b] && a < b);
81    });
82    std::vector<float> sl((size_t) k);
83    for (int i = 0; i < k; ++i) sl[(size_t) i] = s[(size_t) idx[(size_t) i]];
84    int n_keep = k;
85    if (p.top_p < 1.0f) {
86        double sum = 0.0;
87        for (int i = 0; i < k; ++i) sum += std::exp((double) sl[(size_t) i] - (double) sl[0]);
88        double cum = 0.0;
89        int cut = k;
90        for (int i = 0; i < k; ++i) {
91            cum += std::exp((double) sl[(size_t) i] - (double) sl[0]) / sum;
92            if (cum >= (double) p.top_p) { cut = i + 1; break; }
93        }
94        if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
95        n_keep = cut;
96    }
97    if (p.min_p > 0.0f) {
98        const float thresh = sl[0] + std::log(p.min_p);
99        for (int i = 0; i < n_keep; ++i)
100            if (sl[(size_t) i] < thresh) { n_keep = i; break; }
101    }
102    const float inv_t = 1.0f / p.temperature;
103    float smx = sl[0] * inv_t;
104    for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, sl[(size_t) i] * inv_t);
105    PList L;
106    double sum = 0.0;
107    std::vector<double> e((size_t) n_keep);
108    for (int i = 0; i < n_keep; ++i) {
109        e[(size_t) i] = std::exp((double) (sl[(size_t) i] * inv_t) - (double) smx);
110        sum += e[(size_t) i];
111    }
112    for (int i = 0; i < n_keep; ++i) {
113        L.id.push_back(idx[(size_t) i]);
114        L.p.push_back(e[(size_t) i] / sum);
115        L.pf.push_back((float) (e[(size_t) i] / sum));
116    }
117    return L;
118}
119
120}  // namespace
121
122int main(int argc, char** argv) {
123    (void) argc; (void) argv;
124    std::mt19937_64 g(777);
125    long long rows = 0, accepted = 0, rejected = 0, plain = 0, bad = 0, qrows_total = 0;
126    const int vocabs[] = {1000, 50000, 248320};
127    const int Ts[] = {2, 3, 5, 8};
128    const int kMaxT = 8;
129    float* d_logits = nullptr;
130    int* d_out = nullptr;
131    int32_t* d_hist = nullptr;
132    int32_t* d_dtok = nullptr;
133    int32_t* d_q = nullptr;
134    check(cudaMalloc((void**) &d_logits, (size_t) kMaxT * 248320 * sizeof(float)), "malloc logits");
135    check(cudaMalloc((void**) &d_out, kMaxT * sizeof(int)), "malloc out");
136    check(cudaMalloc((void**) &d_hist, (size_t) kMaxT * 64 * sizeof(int32_t)), "malloc hist");
137    check(cudaMalloc((void**) &d_dtok, kMaxT * sizeof(int32_t)), "malloc dtok");
138    check(cudaMalloc((void**) &d_q, (size_t) kMaxT * strata::core::kSpecQStride * sizeof(int32_t)), "malloc q");
139    for (int nv : vocabs) {
140        for (int T : Ts) {
141            for (int rep = 0; rep < 24; ++rep) {
142                SamplerParams p;
143                const int tk[] = {1, 5, 20, 64, 0};
144                const float tp[] = {1.0f, 0.95f, 0.5f};
145                const float mp[] = {0.0f, 0.05f, 0.1f};
146                const float tt[] = {0.3f, 0.7f, 1.0f, 1.5f};
147                p.top_k = tk[g() % 5];
148                p.top_p = tp[g() % 3];
149                p.min_p = mp[g() % 3];
150                p.temperature = tt[g() % 4];
151                p.seed = g();
152                p.counter = g() % 100000;
153                const bool pen = rep % 3 == 2;
154                if (pen) { p.penalty_last_n = 32; p.penalty_repeat = 1.2f; p.penalty_freq = 0.1f; p.penalty_present = 0.2f; }
155                std::normal_distribution<float> nd(0.0f, 2.5f);
156                std::vector<std::vector<float>> logits((size_t) T, std::vector<float>((size_t) nv));
157                std::vector<float> flat((size_t) T * nv);
158                for (int t = 0; t < T; ++t) {
159                    for (int v = 0; v < nv; ++v) logits[(size_t) t][(size_t) v] = nd(g);
160                    // a few clustered peaks, so top_p / min_p cut at interesting places
161                    for (int j = 0; j < 6; ++j) logits[(size_t) t][g() % nv] += 4.0f + (float) (g() % 100) / 25.0f;
162                    std::copy(logits[(size_t) t].begin(), logits[(size_t) t].end(), flat.begin() + (size_t) t * nv);
163                }
164                std::vector<int32_t> hist((size_t) T * 64, -1);
165                std::vector<std::vector<int>> rowhist((size_t) T);
166                if (pen)
167                    for (int t = 0; t < T; ++t) {
168                        for (int i = 0; i < 40; ++i) hist[(size_t) t * 64 + 24 + (size_t) i] = -1;
169                        rowhist[(size_t) t].clear();
170                        for (int i = 0; i < 32; ++i) {
171                            const int v = (int) (g() % 200);
172                            hist[(size_t) t * 64 + 32 + (size_t) i] = v;   // the last 32 slots
173                            rowhist[(size_t) t].push_back(v);
174                        }
175                    }
176                // host: p lists, q lists, drafts
177                std::vector<PList> P((size_t) T), Q((size_t) T);
178                const int n_q = (int) (g() % (T));   // 0 .. T-1 rows with a list
179                std::vector<int32_t> dtok((size_t) (T - 1), 0);
180                std::vector<int32_t> qbuf((size_t) T * strata::core::kSpecQStride, -1);
181                for (int t = 0; t < T; ++t) P[(size_t) t] = chain_list(logits[(size_t) t], rowhist[(size_t) t], p);
182                for (int t = 0; t < T - 1; ++t) {
183                    if (t < n_q) {
184                        // the drafter's own chain: a perturbed copy, its own top_k / top_p / temperature, no penalties
185                        std::vector<float> lq = logits[(size_t) t];
186                        for (float& x : lq) x += 0.7f * nd(g) / 2.5f;
187                        SamplerParams q;
188                        q.top_k = tk[g() % 5]; q.top_p = tp[g() % 3]; q.min_p = 0.0f; q.temperature = tt[g() % 4];
189                        Q[(size_t) t] = chain_list(lq, {}, q);
190                        int32_t* row = qbuf.data() + (size_t) t * strata::core::kSpecQStride;
191                        float* prow = (float*) (row + strata::core::kSpecQEntries);
192                        for (size_t i = 0; i < Q[(size_t) t].id.size(); ++i) { row[i] = Q[(size_t) t].id[i]; prow[i] = Q[(size_t) t].pf[i]; }
193                        // the draft: drawn from q
194                        const float u = (float) (g() >> 40) * (1.0f / 16777216.0f);
195                        double cum = 0.0;
196                        int32_t d = Q[(size_t) t].id.back();
197                        for (size_t i = 0; i < Q[(size_t) t].id.size(); ++i) { cum += Q[(size_t) t].p[i]; if ((double) u < cum) { d = Q[(size_t) t].id[i]; break; } }
198                        dtok[(size_t) t] = d;
199                    } else {
200                        const int r = (int) (g() % 10);
201                        const PList& L = P[(size_t) t];
202                        dtok[(size_t) t] = r < 6 ? L.id[g() % std::min<size_t>(L.id.size(), 5)] : (int32_t) (g() % nv);
203                    }
204                }
205                check(cudaMemcpy(d_logits, flat.data(), flat.size() * sizeof(float), cudaMemcpyHostToDevice), "up logits");
206                check(cudaMemcpy(d_hist, hist.data(), hist.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "up hist");
207                check(cudaMemcpy(d_dtok, dtok.data(), dtok.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "up dtok");
208                check(cudaMemcpy(d_q, qbuf.data(), qbuf.size() * sizeof(int32_t), cudaMemcpyHostToDevice), "up q");
209                const bool ran = strata::kernels::sample_tokens_spec(d_logits, T, nv, pen ? d_hist : nullptr, pen ? 64 : 0, p,
210                                                                     d_dtok, d_q, n_q, d_out, nullptr);
211                if (!ran) { std::printf("sample_tokens_spec did not run (nv %d T %d)\n", nv, T); return 1; }
212                check(cudaDeviceSynchronize(), "sync");
213                int out[kMaxT];
214                check(cudaMemcpy(out, d_out, (size_t) T * sizeof(int), cudaMemcpyDeviceToHost), "down");
215                for (int t = 0; t < T; ++t) {
216                    const uint64_t pos = p.counter + (uint64_t) t;
217                    const SpecP sp{P[(size_t) t].id.data(), P[(size_t) t].p.data(), (int) P[(size_t) t].id.size()};
218                    int32_t want;
219                    if (t == T - 1) {
220                        want = strata::core::spec_sample(sp, host_philox_uniform(p.seed, pos));
221                        ++plain;
222                    } else {
223                        SpecQ sq{nullptr, nullptr, -1};
224                        if (t < n_q) sq = SpecQ{Q[(size_t) t].id.data(), Q[(size_t) t].pf.data(), (int) Q[(size_t) t].id.size()};
225                        const auto r = strata::core::spec_verify_row(sp, dtok[(size_t) t], sq,
226                                                                     host_philox_uniform(p.seed, pos | strata::core::kSpecCtrAccept),
227                                                                     host_philox_uniform(p.seed, pos | strata::core::kSpecCtrResid));
228                        want = r.token;
229                        (r.accepted ? accepted : rejected) += 1;
230                        qrows_total += t < n_q;
231                    }
232                    ++rows;
233                    if (out[t] != want) {
234                        if (++bad <= 10)
235                            std::printf("MISMATCH nv %d T %d row %d: kernel %d host %d (draft %d, n_q %d, top_k %d top_p %.2f min_p %.2f temp %.1f%s)\n",
236                                        nv, T, t, out[t], want, t < T - 1 ? dtok[(size_t) t] : -1, n_q, p.top_k, p.top_p, p.min_p,
237                                        p.temperature, pen ? " penalties" : "");
238                    }
239                }
240            }
241        }
242    }
243    std::printf("spec_verify_parity: %lld rows (%lld drafts kept, %lld rejected, %lld plain last rows, %lld with a q list): %lld mismatches\n",
244                rows, accepted, rejected, plain, qrows_total, bad);
245    cudaFree(d_logits); cudaFree(d_out); cudaFree(d_hist); cudaFree(d_dtok); cudaFree(d_q);
246    return bad == 0 ? 0 : 1;
247}