okami.mom/strata

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

Niko1221Merge branch 'f-1402-d1' into f-14027dbd8c09f

main
14.0 KiB306 linesraw
1// src/kernels/pdl_parity.cpp - programmatic dependent launch (pdl.hpp) in a captured graph, tested bitwise.
2//
3//     build/pdl_parity [--replays N]
4//
5// WHAT IT CHECKS.  A chain shaped like the verify window's - quantize, multi-column MMVQ (a small-K and a large-K
6// format), BF16 multi-row GEMV, the shared Q8_1 buffer rewritten by the next quantization, a memcpy node, a fork onto a
7// second stream and a join - is captured twice: with pdl_scope() off (ordinary launches) and on.  Then:
8//   1. every output of the PDL graph is bitwise the ordinary graph's, over many replays; before each replay every
9//      intermediate is overwritten with NaN bytes, so a kernel that read its input before the kernel writing it had
10//      finished would see NaNs and fail;
11//   2. every programmatic edge of the PDL graph joins two kernel nodes, and every node with a programmatic in-edge
12//      has kernels only before it (the kernel after the memcpy must be an ordinary launch); with STRATA_DF_PDL=2 also
13//      no programmatic edge into a node with a second in-edge (the kernel after the join);
14//   3. power: where pdl_supported() (sm_90+ with code built for it) the PDL graph has programmatic edges, elsewhere
15//      it has none.
16// Also copy_rows_strided against the cudaMemcpy2DAsync it replaces in the verify window.  GPU, synthetic, no model.
17#include "strata/kernels/bf16_bits.hpp"
18#include "strata/kernels/bf16_gemv.hpp"
19#include "strata/kernels/native_mmvq.hpp"
20#include "strata/kernels/pdl.hpp"
21#include "strata/kernels/verify_kernels.hpp"
22
23#include <cuda_runtime.h>
24
25#include <cmath>
26#include <cstdint>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <map>
31#include <random>
32#include <string>
33#include <vector>
34
35namespace k = strata::kernels;
36
37namespace {
38
39int g_fail = 0;
40
41void ck(cudaError_t e, const char* what) {
42    if (e != cudaSuccess) {
43        std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e));
44        std::exit(2);
45    }
46}
47
48// The set-up fills and copies run on the legacy default stream, which does not order the non-blocking streams the
49// kernels run on, and may return before the device has finished them: each one is completed before it is used.
50template <typename T>
51T* dalloc(size_t n) {
52    T* p = nullptr;
53    ck(cudaMalloc(&p, n * sizeof(T)), "malloc");
54    ck(cudaMemset(p, 0, n * sizeof(T)), "memset");
55    ck(cudaDeviceSynchronize(), "memset sync");
56    return p;
57}
58
59// a normal fp16 in +-[2^-10, 2^-5) (mmvq_multi_parity's: finite scales keep every output finite)
60uint16_t sane_half(std::mt19937& rng) {
61    const uint32_t r = rng();
62    return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));
63}
64
65// random quantized weights with sane fp16 scales at byte 0 of each block (Q8_0: 34 bytes, IQ4_XS: 136 bytes)
66void* quant_weights(int type, int n_in, int n_out, int block_elems, int block_bytes, std::mt19937& rng) {
67    const size_t bytes = k::native_mmvq_weight_bytes(type, n_in, n_out);
68    std::vector<uint8_t> w(bytes);
69    for (auto& b : w) b = (uint8_t) (rng() & 0xff);
70    const size_t blocks = (size_t) n_out * (size_t) (n_in / block_elems);
71    if (blocks * (size_t) block_bytes != bytes) {
72        std::printf("type %d: %zu blocks of %d bytes are not the %zu weight bytes\n", type, blocks, block_bytes, bytes);
73        std::exit(2);
74    }
75    for (size_t i = 0; i < blocks; ++i) {
76        const uint16_t h = sane_half(rng);
77        std::memcpy(&w[i * (size_t) block_bytes], &h, 2);
78    }
79    void* d = nullptr;
80    ck(cudaMalloc(&d, bytes), "malloc w");
81    ck(cudaMemcpy(d, w.data(), bytes, cudaMemcpyHostToDevice), "copy w");
82    ck(cudaDeviceSynchronize(), "copy w sync");
83    return d;
84}
85
86uint16_t* bf16_weights(int n_in, int n_out, float scale, std::mt19937& rng) {
87    std::normal_distribution<float> nd(0.f, scale);
88    std::vector<uint16_t> w((size_t) n_in * n_out);
89    for (auto& v : w) v = k::bf16_from_f32(nd(rng));
90    uint16_t* d = dalloc<uint16_t>(w.size());
91    ck(cudaMemcpy(d, w.data(), w.size() * 2, cudaMemcpyHostToDevice), "copy bf16 w");
92    ck(cudaDeviceSynchronize(), "copy bf16 w sync");
93    return d;
94}
95
96constexpr int T = 4, N = 2560, NB = 6144;   // a window of 4 tokens, n_embd, a wide projection
97
98struct Bufs {
99    float *x0, *y1, *y2, *y3, *y4, *y5, *y5c, *y6, *y7, *y8;
100    uint8_t *q, *q2;
101};
102
103// The chain (one capture).  `side`/`ev*`: the fork and join, as the verify window's branches make them.
104void record(const Bufs& b, void* w_q8, void* w_iq4, uint16_t* w_b1, uint16_t* w_b2, cudaStream_t s, cudaStream_t side,
105            cudaEvent_t ev_fork, cudaEvent_t ev_join) {
106    k::native_quantize_q8_1(b.x0, b.q, N, T, s);                          // A
107    k::native_mmvq(8, w_q8, b.q, b.y1, N, N, T, s);                       // B  Q8_0, large K
108    k::native_quantize_q8_1(b.y1, b.q, N, T, s);                          // C  rewrites the q B read
109    k::native_mmvq(23, w_iq4, b.q, b.y2, N, NB, T, s);                    // D  IQ4_XS, small K
110    k::bf16_gemv_fp32_mmvf_multi(b.y2, NB, w_b1, b.y3, N, NB, N, T, s);  // E
111    ck(cudaMemcpyAsync(b.y4, b.y3, (size_t) T * N * 4, cudaMemcpyDeviceToDevice, s), "memcpy node");   // F
112    k::native_quantize_q8_1(b.y4, b.q, N, T, s);                          // G  after a memcpy: ordinary
113    k::native_mmvq(8, w_q8, b.q, b.y5, N, N, T, s);                       // H
114    ck(cudaEventRecord(ev_fork, s), "fork");
115    ck(cudaStreamWaitEvent(side, ev_fork, 0), "fork wait");
116    k::copy_rows_strided(b.y5c, b.y5, T, N, N, side);                     // side: an ordinary kernel after H
117    k::native_quantize_q8_1(b.y5c, b.q2, N, T, side);
118    k::native_mmvq(8, w_q8, b.q2, b.y6, N, N, T, side);
119    k::bf16_gemv_fp32_mmvf_multi(b.y5, N, w_b2, b.y7, N, N, N, T, s);    // main: beside the side branch
120    ck(cudaEventRecord(ev_join, side), "join");
121    ck(cudaStreamWaitEvent(s, ev_join, 0), "join wait");
122    k::bf16_gemv_fp32_mmvf_multi(b.y6, N, w_b2, b.y8, N, N, N, T, s);    // after the join: ordinary
123}
124
125cudaGraphExec_t capture(bool pdl, const Bufs& b, void* w_q8, void* w_iq4, uint16_t* w_b1, uint16_t* w_b2,
126                        cudaStream_t s, cudaStream_t side, cudaEvent_t ef, cudaEvent_t ej, size_t& prog, size_t& bad,
127                        size_t& multi, size_t& mixed) {
128    k::pdl_scope() = pdl;
129    ck(cudaStreamBeginCapture(s, cudaStreamCaptureModeThreadLocal), "begin capture");
130    record(b, w_q8, w_iq4, w_b1, w_b2, s, side, ef, ej);
131    cudaGraph_t g = nullptr;
132    ck(cudaStreamEndCapture(s, &g), "end capture");
133    k::pdl_scope() = false;
134    prog = bad = multi = mixed = 0;
135#if CUDART_VERSION >= 12030
136    size_t ne = 0;
137#if CUDART_VERSION >= 13000
138    ck(cudaGraphGetEdges(g, nullptr, nullptr, nullptr, &ne), "edges");
139#else
140    ck(cudaGraphGetEdges_v2(g, nullptr, nullptr, nullptr, &ne), "edges");
141#endif
142    std::vector<cudaGraphNode_t> from(ne), to(ne);
143    std::vector<cudaGraphEdgeData> ed(ne);
144#if CUDART_VERSION >= 13000
145    ck(cudaGraphGetEdges(g, from.data(), to.data(), ed.data(), &ne), "edges");
146#else
147    ck(cudaGraphGetEdges_v2(g, from.data(), to.data(), ed.data(), &ne), "edges");
148#endif
149    std::map<cudaGraphNode_t, int> in_edges, prog_in, nonkernel_in;
150    for (size_t i = 0; i < ne; ++i) {
151        ++in_edges[to[i]];
152        cudaGraphNodeType ta;
153        ck(cudaGraphNodeGetType(from[i], &ta), "node type");
154        if (ta != cudaGraphNodeTypeKernel) ++nonkernel_in[to[i]];
155        if (ed[i].type == cudaGraphDependencyTypeProgrammatic) ++prog_in[to[i]];
156    }
157    for (size_t i = 0; i < ne; ++i) {
158        if (ed[i].type != cudaGraphDependencyTypeProgrammatic) continue;
159        ++prog;
160        cudaGraphNodeType ta, tb;
161        ck(cudaGraphNodeGetType(from[i], &ta), "node type");
162        ck(cudaGraphNodeGetType(to[i], &tb), "node type");
163        if (ta != cudaGraphNodeTypeKernel || tb != cudaGraphNodeTypeKernel) ++bad;
164        if (in_edges[to[i]] != 1) ++multi;
165    }
166    for (const auto& kv : prog_in)
167        if (nonkernel_in[kv.first] != 0) ++mixed;
168#endif
169    cudaGraphExec_t ex = nullptr;
170    ck(cudaGraphInstantiate(&ex, g, 0), "instantiate");
171    ck(cudaGraphDestroy(g), "destroy graph");
172    return ex;
173}
174
175std::vector<uint32_t> read(const float* d, size_t n) {
176    std::vector<uint32_t> h(n);
177    ck(cudaMemcpy(h.data(), d, n * 4, cudaMemcpyDeviceToHost), "read");
178    return h;
179}
180
181void copy_rows_strided_check(cudaStream_t s) {
182    const int64_t rows = 3 * 32, w = 256, src_w = 512;   // a 3-token window's q heads: query half of each q/gate pair
183    std::mt19937 rng(7);
184    std::normal_distribution<float> nd(0.f, 1.f);
185    std::vector<float> src((size_t) rows * src_w);
186    for (auto& v : src) v = nd(rng);
187    float* ds = dalloc<float>(src.size());
188    float* da = dalloc<float>((size_t) rows * w);
189    float* db = dalloc<float>((size_t) rows * w);
190    ck(cudaMemcpy(ds, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "copy src");
191    ck(cudaDeviceSynchronize(), "copy src sync");
192    k::copy_rows_strided(da, ds, rows, w, src_w, s);
193    ck(cudaMemcpy2DAsync(db, (size_t) w * 4, ds, (size_t) src_w * 4, (size_t) w * 4, (size_t) rows,
194                         cudaMemcpyDeviceToDevice, s), "memcpy2d");
195    ck(cudaStreamSynchronize(s), "sync");
196    const auto a = read(da, (size_t) rows * w), b = read(db, (size_t) rows * w);
197    const bool ok = a == b;
198    std::printf("copy_rows_strided vs cudaMemcpy2DAsync (%lld rows of %lld of %lld): %s\n", (long long) rows,
199                (long long) w, (long long) src_w, ok ? "bitwise equal" : "DIFFERENT");
200    if (!ok) ++g_fail;
201    cudaFree(ds); cudaFree(da); cudaFree(db);
202}
203
204}  // namespace
205
206int main(int argc, char** argv) {
207    int replays = 200;
208    for (int i = 1; i < argc; ++i)
209        if (!std::strcmp(argv[i], "--replays") && i + 1 < argc) replays = std::atoi(argv[++i]);
210    int dev = 0;
211    cudaDeviceProp prop{};
212    ck(cudaGetDevice(&dev), "device");
213    ck(cudaGetDeviceProperties(&prop, dev), "props");
214    const bool supported = k::pdl_supported();
215    std::printf("pdl_parity: %s (sm_%d%d), pdl_supported() = %d\n", prop.name, prop.major, prop.minor, (int) supported);
216
217    cudaStream_t s = nullptr, side = nullptr;
218    cudaEvent_t ef = nullptr, ej = nullptr;
219    ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
220    ck(cudaStreamCreateWithFlags(&side, cudaStreamNonBlocking), "stream");
221    ck(cudaEventCreateWithFlags(&ef, cudaEventDisableTiming), "event");
222    ck(cudaEventCreateWithFlags(&ej, cudaEventDisableTiming), "event");
223
224    copy_rows_strided_check(s);
225
226    std::mt19937 rng(1234);
227    void* w_q8 = quant_weights(8, N, N, 32, 34, rng);
228    void* w_iq4 = quant_weights(23, N, NB, 256, 136, rng);
229    uint16_t* w_b1 = bf16_weights(NB, N, 0.02f, rng);
230    uint16_t* w_b2 = bf16_weights(N, N, 0.02f, rng);
231    Bufs b{};
232    b.x0 = dalloc<float>((size_t) T * N);
233    float** outs[] = {&b.y1, &b.y2, &b.y3, &b.y4, &b.y5, &b.y5c, &b.y6, &b.y7, &b.y8};
234    constexpr int NOUT = 9;
235    const size_t out_n[NOUT] = {(size_t) T * N, (size_t) T * NB, (size_t) T * N, (size_t) T * N, (size_t) T * N,
236                                (size_t) T * N, (size_t) T * N, (size_t) T * N, (size_t) T * N};
237    for (int i = 0; i < NOUT; ++i) *outs[i] = dalloc<float>(out_n[i]);
238    const size_t qbytes = k::native_q8_1_bytes(N, T);
239    b.q = dalloc<uint8_t>(qbytes);
240    b.q2 = dalloc<uint8_t>(qbytes);
241    {
242        std::normal_distribution<float> nd(0.f, 1.f);
243        std::vector<float> x((size_t) T * N);
244        for (auto& v : x) v = nd(rng);
245        ck(cudaMemcpy(b.x0, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x");
246        ck(cudaDeviceSynchronize(), "copy x sync");
247    }
248
249    size_t prog0, bad0, multi0, mixed0, prog1, bad1, multi1, mixed1;
250    cudaGraphExec_t plain = capture(false, b, w_q8, w_iq4, w_b1, w_b2, s, side, ef, ej, prog0, bad0, multi0, mixed0);
251    cudaGraphExec_t pdl = capture(true, b, w_q8, w_iq4, w_b1, w_b2, s, side, ef, ej, prog1, bad1, multi1, mixed1);
252    const char* mode = std::getenv("STRATA_DF_PDL");
253    const bool single = mode != nullptr && std::atoi(mode) == 2;
254    std::printf("graph edges: ordinary capture %zu programmatic; PDL capture %zu programmatic, %zu not kernel to kernel, "
255                "%zu nodes with a programmatic and a non-kernel in-edge, %zu into a node with other in-edges%s\n", prog0,
256                prog1, bad1, mixed1, multi1, single ? " (STRATA_DF_PDL=2: must be 0)" : "");
257    if (prog0 != 0 || bad1 != 0 || mixed1 != 0 || (single && multi1 != 0)) ++g_fail;
258#if CUDART_VERSION >= 12030
259    if (supported && prog1 == 0) {
260        std::printf("FAIL: PDL is supported here but the PDL capture has no programmatic edge (the test has no power)\n");
261        ++g_fail;
262    }
263    if (!supported && prog1 != 0) {
264        std::printf("FAIL: PDL is not supported here but the capture has programmatic edges\n");
265        ++g_fail;
266    }
267#endif
268
269    auto poison = [&]() {   // NaN bytes in every intermediate and output
270        for (int i = 0; i < NOUT; ++i) ck(cudaMemsetAsync(*outs[i], 0xff, out_n[i] * 4, s), "poison");
271        ck(cudaMemsetAsync(b.q, 0xff, qbytes, s), "poison");
272        ck(cudaMemsetAsync(b.q2, 0xff, qbytes, s), "poison");
273    };
274    poison();
275    ck(cudaGraphLaunch(plain, s), "launch plain");
276    ck(cudaStreamSynchronize(s), "sync plain");
277    std::vector<std::vector<uint32_t>> ref;
278    for (int i = 0; i < NOUT; ++i) ref.push_back(read(*outs[i], out_n[i]));
279    long long nonfinite = 0;
280    for (const auto& r : ref)
281        for (uint32_t v : r) {
282            float f;
283            std::memcpy(&f, &v, 4);
284            if (!std::isfinite(f)) ++nonfinite;
285        }
286    if (nonfinite) {
287        std::printf("FAIL: the ordinary graph left %lld non-finite outputs (the data has no power)\n", nonfinite);
288        ++g_fail;
289    }
290    int bad_replays = 0;
291    for (int r = 0; r < replays; ++r) {
292        poison();
293        ck(cudaGraphLaunch(pdl, s), "launch pdl");
294        ck(cudaStreamSynchronize(s), "sync pdl");
295        bool same = true;
296        for (int i = 0; i < NOUT && same; ++i) same = read(*outs[i], out_n[i]) == ref[(size_t) i];
297        if (!same) ++bad_replays;
298    }
299    std::printf("PDL graph vs ordinary graph over %d replays: %d differ\n", replays, bad_replays);
300    if (bad_replays) ++g_fail;
301
302    cudaGraphExecDestroy(plain);
303    cudaGraphExecDestroy(pdl);
304    std::printf("pdl_parity: %s\n", g_fail ? "FAIL" : "PASS");
305    return g_fail ? 1 : 0;
306}