okami.mom/strata

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

Niko1221Strata: Qwen3.8-Flash-Next on a 12-24 GB NVIDIA GPU + 64 GB RAM, one-click install01529aaa8

main
8.5 KiB169 linesraw
1// src/core/overlap_main.cpp - `strata-overlap`: does streaming an expert overlap with computing on it?
2//
3// THE ARCHITECTURE'S CENTRAL PREMISE.  Only (1 - h) of a token's expert weights are in VRAM, so the rest must
4// cross the bus while the GPU is working.  If the copy and the compute do not overlap, the per-token cost is
5// their SUM; if they do, it is their MAXIMUM.  L3 measured the stream at 4.07 ms/token (design h) and L5 the
6// matvec at 27.9 ms/token, so serial would be ~32 ms and overlapped ~28 - but those are the STEADY-STATE
7// numbers for a whole token; at one expert's granularity the ratio is completely different and that is what
8// decides how the loop must be built.
9//
10// Measured against a SERIAL baseline in the same process, because the interesting quantity is the ratio and
11// not the absolute figure - and L6 established that absolute figures on this machine move by 20%.
12#include "strata/core/pinned.hpp"
13#include "strata/kernels/s_gemv.hpp"
14
15#include <cuda_runtime.h>
16
17#include <chrono>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <fstream>
22#include <string>
23#include <vector>
24
25namespace {
26
27void check(cudaError_t e, const char* what) {
28    if (e != cudaSuccess) {
29        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
30        std::exit(1);
31    }
32}
33
34struct Timing {
35    double seconds = 0;
36    const char* name = "";
37};
38
39}  // namespace
40
41int main(int argc, char** argv) {
42    std::string path;
43    int experts = 64;
44    int threads_per_row = 32;
45    for (int i = 1; i < argc; ++i) {
46        const std::string a = argv[i];
47        auto val = [&]() -> const char* {
48            if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); }
49            return argv[++i];
50        };
51        if (a == "--file") path = val();
52        else if (a == "--experts") experts = std::atoi(val());
53        else if (a == "--tpr") threads_per_row = std::atoi(val());
54        else {
55            std::fprintf(stderr, "usage: strata-overlap --file experts.bin [--experts N] [--tpr N]\n");
56            return 2;
57        }
58    }
59    if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; }
60
61    // One ROLE's worth of S2 weights: gate is [n_embd 2560] x [ff 640] = 1,638,400 weights = 460,800 B of
62    // codes at 4 codes per byte, plus 40 scales per row.
63    const long long n_in = 2560, n_out = 640;
64    const uint64_t role_codes = (uint64_t) n_out * n_in / 4;
65    const uint64_t role_bytes = role_codes + (uint64_t) n_out * (n_in / 64) * 4;
66    std::printf("per role: %lld x %lld S2 weights, %.1f KB of planes\n", n_in, n_out, role_bytes / 1024.0);
67
68    // host side: `experts` blobs read into a pinned arena, and the S2 planes the GEMV will read
69    strata::core::PinnedArena arena((uint64_t) experts * role_codes);
70    if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; }
71    {
72        std::ifstream f(path, std::ios::binary);
73        if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; }
74        // take the first `experts` blobs' worth of CODE bytes, pretending each is a role's plane: the bytes
75        // are real Q2_0 codes, so the kernel decodes real data and no cache-friendly pattern is invented
76        for (int i = 0; i < experts; ++i) {
77            f.seekg((std::streamoff) i * 1382400);
78            f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes);
79            if ((uint64_t) f.gcount() != role_codes) {
80                std::fprintf(stderr, "short read on expert %d\n", i);
81                return 1;
82            }
83        }
84    }
85    std::printf("loaded %d role-sized planes into a %s arena\n", experts, arena.note.c_str());
86
87    // device side: double buffered codes, plus x / scales / y
88    uint8_t* d_codes[2] = {nullptr, nullptr};
89    for (int b = 0; b < 2; ++b) check(cudaMalloc(&d_codes[b], role_codes), "cudaMalloc codes");
90    uint16_t* d_x = nullptr;
91    float *d_scales = nullptr, *d_y = nullptr;
92    check(cudaMalloc(&d_x, n_in * sizeof(uint16_t)), "cudaMalloc x");
93    check(cudaMalloc(&d_scales, (size_t) n_out * (n_in / 64) * sizeof(float)), "cudaMalloc scales");
94    check(cudaMalloc(&d_y, n_out * sizeof(float)), "cudaMalloc y");
95    std::vector<uint16_t> hx((size_t) n_in, 0x3C00);
96    std::vector<float> hs((size_t) n_out * (size_t) (n_in / 64), 0.001f);
97    check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x");
98    check(cudaMemcpy(d_scales, hs.data(), hs.size() * sizeof(float), cudaMemcpyHostToDevice), "copy scales");
99
100    cudaStream_t s_copy{}, s_comp{};
101    check(cudaStreamCreate(&s_copy), "stream copy");
102    check(cudaStreamCreate(&s_comp), "stream compute");
103    const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false};
104
105    // ---- SERIAL: the same operations on the SAME stream, so the GPU runs them one after another ----
106    //
107    // NOT a sync-per-iteration loop.  The first version waited with `cudaStreamSynchronize` after every copy and
108    // measured 234.8 us/expert where a copy plus a GEMV is ~43 us: the baseline was dominated by the CPU
109    // round-trip, so the ratio of 0.095 mostly measured "with syncs" against "without syncs".  Putting both
110    // operations on one stream expresses the same dependency with NO CPU involvement and ONE sync at the end,
111    // which is what makes the comparison about overlap rather than about synchronisation.
112    check(cudaStreamSynchronize(0), "pre sync");
113    auto t0 = std::chrono::steady_clock::now();
114    for (int i = 0; i < experts; ++i) {
115        check(cudaMemcpyAsync(d_codes[0], arena.data() + (uint64_t) i * role_codes, role_codes,
116                              cudaMemcpyHostToDevice, 0),
117              "serial copy");
118        strata::kernels::s_gemv_split_async(d_x, d_codes[0], d_scales, nullptr, d_y, n_in, n_out, form,
119                                            threads_per_row, (void*) (cudaStream_t) 0);
120    }
121    check(cudaStreamSynchronize(0), "serial final sync");
122    const double serial = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
123
124    // ---- OVERLAPPED: copy the next one while computing on the current one ----
125    check(cudaStreamSynchronize(0), "pre sync 2");
126    cudaEvent_t ev[2];
127    for (int b = 0; b < 2; ++b) check(cudaEventCreateWithFlags(&ev[b], cudaEventDisableTiming), "event");
128    t0 = std::chrono::steady_clock::now();
129    check(cudaMemcpyAsync(d_codes[0], arena.data(), role_codes, cudaMemcpyHostToDevice, s_copy), "prologue");
130    check(cudaEventRecord(ev[0], s_copy), "prologue event");
131    for (int i = 0; i < experts; ++i) {
132        const int cur = i & 1, nxt = (i + 1) & 1;
133        if (i + 1 < experts) {
134            check(cudaMemcpyAsync(d_codes[nxt], arena.data() + (uint64_t) (i + 1) * role_codes, role_codes,
135                                  cudaMemcpyHostToDevice, s_copy),
136                  "overlap copy");
137            check(cudaEventRecord(ev[nxt], s_copy), "overlap event");
138        }
139        // the compute stream must not start row i until its codes have landed
140        check(cudaStreamWaitEvent(s_comp, ev[cur], 0), "wait");
141        // a hand-written launch so it goes on s_comp; `s_gemv` synchronises on the default stream
142        strata::kernels::s_gemv_split_async(d_x, d_codes[cur], d_scales, nullptr, d_y, n_in, n_out, form,
143                                            threads_per_row, (void*) s_comp);
144    }
145    check(cudaStreamSynchronize(s_comp), "final sync");
146    check(cudaStreamSynchronize(s_copy), "final sync 2");
147    const double overlap = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
148
149    std::printf("\n  serial     %8.3f ms for %d experts  (%.1f us/expert)\n", serial * 1000, experts,
150                serial * 1e6 / experts);
151    std::printf("  overlapped %8.3f ms for %d experts  (%.1f us/expert)\n", overlap * 1000, experts,
152                overlap * 1e6 / experts);
153    std::printf("  ratio      %.3f  (1.00 = no overlap at all, <1.00 = overlap)\n", overlap / serial);
154    std::printf("\nNOTE: the OVERLAPPED loop launches on `s_comp` without synchronising, so the copy and the\n"
155                "      compute really are concurrent; the serial loop waits after each step.  What this does NOT\n"
156                "      model is the CPU expert path, the router, or the fact that a real token has 1440 roles to\n"
157                "      stream rather than %d.\n", experts);
158
159    for (int b = 0; b < 2; ++b) {
160        cudaFree(d_codes[b]);
161        cudaEventDestroy(ev[b]);
162    }
163    cudaFree(d_x);
164    cudaFree(d_scales);
165    cudaFree(d_y);
166    cudaStreamDestroy(s_copy);
167    cudaStreamDestroy(s_comp);
168    return 0;
169}