okami.mom/strata

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

Niko1221Merge f-kv-default: with KV streaming on NVIDIA cards, the prompt's new K/V cells reach the host copy by one DMA copy per array6aae30348

main
11.6 KiB216 linesraw
1// src/prefill/kv_host_dma_parity.cpp - the prompt path's K/V append under KV streaming, both ways (GPU, synthetic, no model):
2//   (a) the append kernel writes the host copy itself (STRATA_KV_HOST_DMA=0),
3//   (b) the append writes the staging pool and the VRAM slots only, then kv_unstage_to_host copies the chunk's blocks
4//       from the staging pool to the host copy by DMA on the same stream (the CUDA default, core/kv_host_dma.hpp).
5// Per format (fp16, int8 + scales, q4_0) a 4,048-cell context is appended in four chunks whose starts are not block
6// aligned (0, 999, 1000, 3045; one chunk of a single cell), each chunk staged from the host copy first as the prompt
7// path does. After every chunk, before any host-side wait on the append's stream, a reader on ANOTHER stream that waits
8// for an event recorded right after the append reads the host copy back; then the host copies, the read-backs and the
9// VRAM slot pools of (a) and (b) must be byte-equal over every cell written so far. The staging pools start as junk,
10// the host copies as zeros, so a block that was not copied, or a copy that ran before its append, shows up.
11//
12//   kv_host_dma_parity [--device N]     exit 0: every case equal; 1: a difference; 77: no GPU
13#include "strata/kernels/kv_q4.hpp"
14#include "strata/kernels/kv_q8.hpp"
15#include "strata/kernels/kv_stream.hpp"
16#include "strata/kernels/qsa.hpp"
17#include "strata/kernels/qsa_decode_attn.hpp"
18#include "strata/prefill/kernels.hpp"
19
20#include <cuda_runtime.h>
21
22#include <algorithm>
23#include <cstdint>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <random>
28#include <string>
29#include <vector>
30
31namespace k = strata::kernels;
32
33namespace {
34bool ck(cudaError_t e, const char* what) {
35    if (e != cudaSuccess) {
36        std::fprintf(stderr, "kv_host_dma_parity: %s: %s\n", what, cudaGetErrorString(e));
37        return false;
38    }
39    return true;
40}
41
42// One array of a pool: bytes per (cell, head) row.
43struct Arr {
44    size_t row = 0;
45};
46
47struct Pools {          // one set of arrays (fp16: 2, int8: 4, q4: 2), each [n_pages][2][page_size] rows
48    std::vector<uint8_t*> a;
49};
50
51k::KvHostPools as_host(const Pools& p, int fmt) {
52    k::KvHostPools h;
53    if (fmt == k::kKvF16) { h.k_pool = (uint16_t*) p.a[0]; h.v_pool = (uint16_t*) p.a[1]; }
54    else if (fmt == k::kKvInt8) { h.k_q = (int8_t*) p.a[0]; h.v_q = (int8_t*) p.a[1]; h.k_scale = (uint16_t*) p.a[2]; h.v_scale = (uint16_t*) p.a[3]; }
55    else { h.k_q4 = p.a[0]; h.v_q4 = p.a[1]; }
56    return h;
57}
58
59k::QsaAttnPools as_attn(const Pools& p, int fmt) {
60    const k::KvHostPools h = as_host(p, fmt);
61    k::QsaAttnPools q;
62    q.k_pool = h.k_pool; q.v_pool = h.v_pool; q.k_q = h.k_q; q.v_q = h.v_q; q.k_scale = h.k_scale; q.v_scale = h.v_scale;
63    q.k_q4 = h.k_q4; q.v_q4 = h.v_q4;
64    return q;
65}
66
67std::vector<Arr> arrays_of(int fmt, const k::QsaShapes& s) {
68    if (fmt == k::kKvF16) return {{(size_t) s.head_dim * 2}, {(size_t) s.head_dim * 2}};
69    if (fmt == k::kKvInt8) {
70        const size_t sc = (size_t) (s.head_dim / k::KV_Q8_GROUP) * 2;
71        return {{(size_t) s.head_dim}, {(size_t) s.head_dim}, {sc}, {sc}};
72    }
73    const size_t q4 = (size_t) k::kv_q4_bytes_per_head((int) s.head_dim);
74    return {{q4}, {q4}};
75}
76
77const char* fmt_name(int fmt) { return fmt == k::kKvF16 ? "fp16" : fmt == k::kKvInt8 ? "int8" : "q4_0"; }
78
79int run_format(int fmt) {
80    k::QsaShapes s = k::qsa_real_shapes();
81    const int64_t ps = s.page_size, nkv = s.n_head_kv, hd = s.head_dim;
82    const int64_t n_cells = 4096, n_pages = n_cells / ps, rows = n_pages * nkv * ps;
83    const std::vector<Arr> arrs = arrays_of(fmt, s);
84    const int na = (int) arrs.size();
85    // the VRAM slots: one slot per resident page; about a third of the pages are not resident (-1)
86    std::mt19937 rng(1234u + (unsigned) fmt);
87    std::vector<int32_t> table((size_t) n_pages);
88    {
89        std::vector<int32_t> perm((size_t) n_pages);
90        for (int64_t i = 0; i < n_pages; ++i) perm[(size_t) i] = (int32_t) i;
91        std::shuffle(perm.begin(), perm.end(), rng);
92        for (int64_t i = 0; i < n_pages; ++i) table[(size_t) i] = (rng() % 3 == 0) ? -1 : perm[(size_t) i];
93    }
94    int32_t* d_table = nullptr;
95    if (!ck(cudaMalloc(&d_table, table.size() * 4), "table") ||
96        !ck(cudaMemcpy(d_table, table.data(), table.size() * 4, cudaMemcpyHostToDevice), "table up")) return 2;
97    // per path (0 = kernel stores, 1 = DMA): host copy (pinned, mapped), staging pool, slot pool, read-back buffer
98    Pools host[2], host_dev[2], stage[2], slots[2], back[2];
99    for (int w = 0; w < 2; ++w) {
100        for (int i = 0; i < na; ++i) {
101            const size_t bytes = (size_t) rows * arrs[(size_t) i].row;
102            uint8_t *h = nullptr, *hd_ptr = nullptr, *st = nullptr, *sl = nullptr, *bk = nullptr;
103            if (!ck(cudaHostAlloc((void**) &h, bytes, cudaHostAllocMapped | cudaHostAllocPortable), "host copy") ||
104                !ck(cudaHostGetDevicePointer((void**) &hd_ptr, h, 0), "host device pointer") ||
105                !ck(cudaMalloc(&st, bytes), "stage") || !ck(cudaMalloc(&sl, bytes), "slots") || !ck(cudaMalloc(&bk, bytes), "back"))
106                return 2;
107            std::memset(h, 0, bytes);
108            ck(cudaMemset(st, 0xA5, bytes), "stage junk");
109            ck(cudaMemset(sl, 0x5A, bytes), "slots junk");
110            ck(cudaMemset(bk, 0x00, bytes), "back zero");
111            host[w].a.push_back(h); host_dev[w].a.push_back(hd_ptr); stage[w].a.push_back(st); slots[w].a.push_back(sl);
112            back[w].a.push_back(bk);
113        }
114    }
115    cudaStream_t cs = nullptr, rd = nullptr;
116    cudaEvent_t ev = nullptr;
117    if (!ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream") ||
118        !ck(cudaStreamCreateWithFlags(&rd, cudaStreamNonBlocking), "reader stream") ||
119        !ck(cudaEventCreateWithFlags(&ev, cudaEventDisableTiming), "event")) return 2;
120    const int64_t chunks[4][2] = {{0, 999}, {999, 1}, {1000, 2045}, {3045, 1003}};
121    std::normal_distribution<float> nd(0.0f, 1.0f);
122    float *dK = nullptr, *dV = nullptr;
123    if (!ck(cudaMalloc(&dK, (size_t) 2045 * nkv * hd * 4), "K") || !ck(cudaMalloc(&dV, (size_t) 2045 * nkv * hd * 4), "V")) return 2;
124    int bad = 0;
125    for (const auto& c : chunks) {
126        const int64_t p0 = c[0], T = c[1], end = p0 + T;
127        std::vector<float> K((size_t) (T * nkv * hd)), V(K.size());
128        for (auto& x : K) x = nd(rng) * 3.0f;
129        for (auto& x : V) x = nd(rng) * 3.0f;
130        ck(cudaMemcpy(dK, K.data(), K.size() * 4, cudaMemcpyHostToDevice), "K up");
131        ck(cudaMemcpy(dV, V.data(), V.size() * 4, cudaMemcpyHostToDevice), "V up");
132        // the uploads and the junk fills run on the legacy stream, which the two non-blocking streams do not wait for
133        if (!ck(cudaDeviceSynchronize(), "uploads")) return 2;
134        for (int w = 0; w < 2; ++w) {
135            const k::KvHostPools hp = as_host(host_dev[w], fmt), sp = as_host(stage[w], fmt), lp = as_host(slots[w], fmt);
136            // the prompt path: this layer's cells [0, p0) from the host copy into the staging pool first
137            k::kv_stage_from_host(as_attn(stage[w], fmt), hp, fmt, (p0 + ps - 1) / ps, s, cs);
138            const k::KvHostPools* host_w = w == 0 ? &hp : nullptr;
139            if (fmt == k::kKvQ4)
140                k::kv_append_q4(lp.k_q4, lp.v_q4, d_table, p0, T, dK, dV, s, cs, host_w, &sp);
141            else
142                strata::prefill::kv_append(dK, dV, T, p0, d_table, ps, fmt == k::kKvF16 ? lp.k_pool : nullptr,
143                                           fmt == k::kKvF16 ? lp.v_pool : nullptr, lp.k_q, lp.v_q, lp.k_scale, lp.v_scale,
144                                           cs, host_w, &sp);
145            if (w == 1) k::kv_unstage_to_host(as_attn(stage[w], fmt), hp, fmt, p0 / ps, (end + ps - 1) / ps, s, cs);
146            // a reader on another stream, ordered only by an event recorded right after the append's calls
147            ck(cudaEventRecord(ev, cs), "event record");
148            ck(cudaStreamWaitEvent(rd, ev, 0), "reader wait");
149            for (int i = 0; i < na; ++i) {
150                const size_t bytes = (size_t) ((end + ps - 1) / ps) * nkv * ps * arrs[(size_t) i].row;
151                ck(cudaMemcpyAsync(back[w].a[(size_t) i], host_dev[w].a[(size_t) i], bytes, cudaMemcpyDefault, rd), "read back");
152            }
153            if (!ck(cudaStreamSynchronize(rd), "reader sync")) return 2;
154        }
155        if (!ck(cudaDeviceSynchronize(), "sync") || !ck(cudaGetLastError(), "kernels")) return 2;
156        // compare every written cell: host copies (host side), read-backs, and the whole slot pools
157        std::vector<uint8_t> b0, b1;
158        for (int i = 0; i < na; ++i) {
159            const size_t rb = arrs[(size_t) i].row, bytes = (size_t) rows * rb;
160            b0.resize(bytes); b1.resize(bytes);
161            ck(cudaMemcpy(b0.data(), back[0].a[(size_t) i], bytes, cudaMemcpyDeviceToHost), "back0");
162            ck(cudaMemcpy(b1.data(), back[1].a[(size_t) i], bytes, cudaMemcpyDeviceToHost), "back1");
163            int64_t d_host = 0, d_back = 0, d_zero = 0;
164            for (int64_t pos = 0; pos < end; ++pos)
165                for (int64_t h = 0; h < nkv; ++h) {
166                    const size_t r = (size_t) (((pos / ps) * nkv + h) * ps + pos % ps) * rb;
167                    if (std::memcmp(host[0].a[(size_t) i] + r, host[1].a[(size_t) i] + r, rb) != 0) ++d_host;
168                    if (std::memcmp(b0.data() + r, b1.data() + r, rb) != 0) ++d_back;
169                    if (std::memcmp(b0.data() + r, host[0].a[(size_t) i] + r, rb) != 0) ++d_back;
170                    bool zero = true;   // a written row of a nonzero input is never all zero: catches a missing copy
171                    for (size_t j = 0; j < rb; ++j) zero = zero && host[1].a[(size_t) i][r + j] == 0;
172                    if (zero) ++d_zero;
173                }
174            ck(cudaMemcpy(b0.data(), slots[0].a[(size_t) i], bytes, cudaMemcpyDeviceToHost), "slots0");
175            ck(cudaMemcpy(b1.data(), slots[1].a[(size_t) i], bytes, cudaMemcpyDeviceToHost), "slots1");
176            const bool slots_eq = std::memcmp(b0.data(), b1.data(), bytes) == 0;
177            const bool ok = d_host == 0 && d_back == 0 && d_zero == 0 && slots_eq;
178            std::printf("%s chunk p0 %lld T %lld array %d: host rows differing %lld, read-back rows differing %lld, "
179                        "all-zero rows %lld, slot pools %s: %s\n", fmt_name(fmt), (long long) p0, (long long) T, i,
180                        (long long) d_host, (long long) d_back, (long long) d_zero, slots_eq ? "equal" : "DIFFER",
181                        ok ? "ok" : "FAIL");
182            if (!ok) ++bad;
183        }
184    }
185    cudaFree(dK); cudaFree(dV); cudaFree(d_table);
186    for (int w = 0; w < 2; ++w)
187        for (int i = 0; i < na; ++i) {
188            cudaFreeHost(host[w].a[(size_t) i]); cudaFree(stage[w].a[(size_t) i]); cudaFree(slots[w].a[(size_t) i]);
189            cudaFree(back[w].a[(size_t) i]);
190        }
191    cudaEventDestroy(ev); cudaStreamDestroy(cs); cudaStreamDestroy(rd);
192    return bad == 0 ? 0 : 1;
193}
194}  // namespace
195
196int main(int argc, char** argv) {
197    int dev = 0;
198    for (int i = 1; i + 1 < argc; ++i)
199        if (std::string(argv[i]) == "--device") dev = std::atoi(argv[i + 1]);
200    int n = 0;
201    if (cudaGetDeviceCount(&n) != cudaSuccess || n <= dev) {
202        std::printf("kv_host_dma_parity: no GPU: skipped\n");
203        return 77;
204    }
205    if (!ck(cudaSetDevice(dev), "device")) return 2;
206    cudaDeviceProp p{};
207    cudaGetDeviceProperties(&p, dev);
208    std::printf("kv_host_dma_parity: device %d %s (sm_%d%d)\n", dev, p.name, p.major, p.minor);
209    int rc = 0;
210    for (int fmt : {(int) k::kKvF16, (int) k::kKvInt8, (int) k::kKvQ4}) {
211        const int r = run_format(fmt);
212        if (r != 0) rc = r > rc ? r : rc;
213    }
214    std::printf("kv_host_dma_parity: %s\n", rc == 0 ? "ok (both ways byte-equal)" : "FAILED");
215    return rc;
216}