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
9.7 KiB197 linesraw
1// src/core/concurrent_main.cpp - do the CPU expert path and the GPU stream path actually run at once?
2//
3// L9 concluded that the two miss paths are INDEPENDENT RESOURCES - 42.55 GB/s of DRAM bandwidth for the CPU
4// expert kernel and 28.9 GB/s of PCIe for the stream - and that running them together would cover a token's
5// 552.7 MB of misses in 7.74 ms, which is what puts 100 tps inside reach on this Gen4 machine.
6//
7// THAT CLAIM HAS A HOLE.  An H2D copy from PINNED host memory READS HOST DRAM to do it, so the bus path is not
8// free of the resource the CPU path is bound by.  If the two contend, the combined rate is not 42.55 + 28.9 and
9// the 129 tok/s figure is optimistic; if they overlap cleanly, it stands.  This measures it three ways in one
10// process - CPU alone, GPU alone, both - because comparing two separately-measured rates is exactly the
11// inference that has been wrong twice already in this ledger (L2's dependency chain, L8's bus-only ceiling).
12//
13// The CPU side is a READ LOOP over the same pinned arena rather than the real VNNI kernel, and that is
14// deliberate: the question is whether the two paths contend for DRAM BANDWIDTH, and a read loop is a pure
15// measurement of that demand, with no compute that could mask it.
16#include "strata/core/pinned.hpp"
17#include "strata/kernels/s_gemv.hpp"
18
19#include <cuda_runtime.h>
20
21#include <atomic>
22#include <chrono>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <fstream>
27#include <string>
28#include <thread>
29#include <vector>
30
31namespace {
32
33void check(cudaError_t e, const char* what) {
34    if (e != cudaSuccess) {
35        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
36        std::exit(1);
37    }
38}
39
40// Volatile sink so the read loop cannot be optimised away; summed across threads and printed, so a compiler
41// that removed the loads would produce a suspiciously round zero rather than a plausible number.
42std::atomic<uint64_t> g_sink{0};
43
44struct Run {
45    double seconds = 0;
46    double cpu_gb = 0;      // GB/s read by the CPU threads
47    double gpu_experts = 0; // experts streamed and computed by the GPU
48};
49
50}  // namespace
51
52int main(int argc, char** argv) {
53    std::string path;
54    // 4096 planes = 2 GiB, which is 64x the 32 MB L3 on this CPU.  At 0.1 GiB the read loop measured 206 GB/s -
55    // that is CACHE bandwidth, not DRAM, and it would have answered the contention question with a number about
56    // a different resource entirely.
57    int experts = 4096;
58    int cpu_threads = 6;
59    int gpu_roles = 256;
60    for (int i = 1; i < argc; ++i) {
61        const std::string a = argv[i];
62        auto val = [&]() -> const char* {
63            if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); }
64            return argv[++i];
65        };
66        if (a == "--file") path = val();
67        else if (a == "--experts") experts = std::atoi(val());
68        else if (a == "--cpu-threads") cpu_threads = std::atoi(val());
69        else if (a == "--gpu-roles") gpu_roles = std::atoi(val());
70        else {
71            std::fprintf(stderr, "usage: strata-concurrent --file experts.bin [--experts N] "
72                                 "[--cpu-threads N] [--gpu-roles N]\n");
73            return 2;
74        }
75    }
76    if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; }
77
78    const long long n_in = 2560, n_out = 640;
79    const uint64_t role_codes = (uint64_t) n_out * n_in / 4;
80    const uint64_t plane_bytes = role_codes;      // the CPU loop reads the same planes
81
82    strata::core::PinnedArena arena((uint64_t) experts * role_codes);
83    if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; }
84    {
85        std::ifstream f(path, std::ios::binary);
86        if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; }
87        for (int i = 0; i < experts; ++i) {
88            f.seekg((std::streamoff) i * 1382400);
89            f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes);
90            if ((uint64_t) f.gcount() != role_codes) { std::fprintf(stderr, "short read\n"); return 1; }
91        }
92    }
93    std::printf("arena %.2f GiB pinned; %d CPU threads; %d GPU roles\n",
94                (double) arena.capacity / (1024.0 * 1024 * 1024), cpu_threads, gpu_roles);
95
96    uint8_t* d_codes = nullptr;
97    check(cudaMalloc(&d_codes, role_codes), "cudaMalloc codes");
98    uint16_t* d_x = nullptr;
99    float *d_scales = nullptr, *d_y = nullptr;
100    check(cudaMalloc(&d_x, n_in * sizeof(uint16_t)), "cudaMalloc x");
101    check(cudaMalloc(&d_scales, (size_t) n_out * (n_in / 64) * sizeof(float)), "cudaMalloc scales");
102    check(cudaMalloc(&d_y, n_out * sizeof(float)), "cudaMalloc y");
103    std::vector<uint16_t> hx((size_t) n_in, 0x3C00);
104    std::vector<float> hs((size_t) n_out * (size_t) (n_in / 64), 0.001f);
105    check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x");
106    check(cudaMemcpy(d_scales, hs.data(), hs.size() * sizeof(float), cudaMemcpyHostToDevice), "copy scales");
107    cudaStream_t s_copy{}, s_comp{};
108    check(cudaStreamCreate(&s_copy), "stream copy");
109    check(cudaStreamCreate(&s_comp), "stream compute");
110    const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false};
111
112    // The CPU loop: read the whole arena, Nthreads ways, and sum bytes so nothing is elided.
113    auto cpu_work = [&](std::atomic<bool>& stop, std::atomic<uint64_t>& bytes) {
114        uint64_t acc = 0, n = 0;
115        const uint8_t* p = arena.data();
116        while (!stop.load(std::memory_order_relaxed)) {
117            // touch one byte per 64 - a stride that defeats prefetch into a pure streaming read
118            for (uint64_t i = 0; i < plane_bytes * (uint64_t) experts; i += 64) acc += p[i];
119            n += plane_bytes * (uint64_t) experts;
120        }
121        bytes.fetch_add(n);
122        g_sink.fetch_add(acc);
123    };
124
125    // The GPU loop: stream each role plane on the copy stream while computing on the compute stream.
126    auto gpu_work = [&](int roles) {
127        cudaEvent_t ev[2];
128        for (int b = 0; b < 2; ++b) check(cudaEventCreateWithFlags(&ev[b], cudaEventDisableTiming), "event");
129        uint8_t* buf[2] = {d_codes, d_codes};      // one buffer is enough: the timing is what is measured
130        check(cudaMemcpyAsync(buf[0], arena.data(), role_codes, cudaMemcpyHostToDevice, s_copy), "prologue");
131        check(cudaEventRecord(ev[0], s_copy), "prologue event");
132        for (int i = 0; i < roles; ++i) {
133            const int cur = i & 1, nxt = (i + 1) & 1;
134            if (i + 1 < roles) {
135                check(cudaMemcpyAsync(buf[nxt], arena.data() + (uint64_t) ((i + 1) % experts) * role_codes,
136                                      role_codes, cudaMemcpyHostToDevice, s_copy),
137                      "copy");
138                check(cudaEventRecord(ev[nxt], s_copy), "event");
139            }
140            check(cudaStreamWaitEvent(s_comp, ev[cur], 0), "wait");
141            strata::kernels::s_gemv_split_async(d_x, buf[cur], d_scales, nullptr, d_y, n_in, n_out, form, 32,
142                                                (void*) s_comp);
143        }
144        check(cudaStreamSynchronize(s_comp), "sync comp");
145        check(cudaStreamSynchronize(s_copy), "sync copy");
146        for (int b = 0; b < 2; ++b) cudaEventDestroy(ev[b]);
147    };
148
149    auto run = [&](bool do_cpu, bool do_gpu, const char* name) {
150        std::atomic<bool> stop{false};
151        std::atomic<uint64_t> bytes{0};
152        std::vector<std::thread> cpu;
153        check(cudaStreamSynchronize(0), "pre");
154        const auto t0 = std::chrono::steady_clock::now();
155        if (do_cpu) for (int t = 0; t < cpu_threads; ++t) cpu.emplace_back(cpu_work, std::ref(stop), std::ref(bytes));
156        if (do_gpu) {
157            gpu_work(gpu_roles);
158        } else {
159            // CPU-only needs a REAL window.  The first version let t0..t1 span nothing when there was no GPU
160            // work, so the threads were stopped immediately and the run reported 0.000 s and 0.00 GB/s.
161            std::this_thread::sleep_for(std::chrono::milliseconds(3000));
162        }
163        const auto t1 = std::chrono::steady_clock::now();
164        stop = true;
165        for (auto& t : cpu) t.join();
166        Run r;
167        r.seconds = std::chrono::duration<double>(t1 - t0).count();
168        r.cpu_gb = (double) bytes.load() / 1e9 / r.seconds;
169        r.gpu_experts = do_gpu ? (double) gpu_roles / r.seconds : 0.0;
170        std::printf("  %-18s %7.3f s   CPU read %6.2f GB/s   GPU %7.1f roles/s\n", name, r.seconds, r.cpu_gb,
171                    r.gpu_experts);
172        return r;
173    };
174
175    std::printf("\n  mode                     wall   CPU read          GPU\n");
176    const Run cpu_only = run(true, false, "CPU only");
177    const Run gpu_only = run(false, true, "GPU only");
178    const Run both = run(true, true, "BOTH");
179
180    std::printf("\n  independence check (1.00 = perfectly shared, 0.00 = fully independent):\n");
181    const double cpu_interference = cpu_only.cpu_gb > 0 ? 1.0 - both.cpu_gb / cpu_only.cpu_gb : 0.0;
182    const double gpu_interference = gpu_only.gpu_experts > 0 ? 1.0 - both.gpu_experts / gpu_only.gpu_experts : 0.0;
183    std::printf("    CPU throughput lost when the GPU also runs : %5.1f%%\n", cpu_interference * 100);
184    std::printf("    GPU throughput lost when the CPU also runs : %5.1f%%\n", gpu_interference * 100);
185    std::printf("    combined vs the sum of the parts           : CPU %6.2f + GPU-equivalent vs %6.2f measured\n",
186                cpu_only.cpu_gb, both.cpu_gb);
187    std::printf("\n  NOTE: the CPU side is a READ LOOP, not the VNNI kernel - it measures DRAM DEMAND, which is the\n"
188                "        resource the question is about.  L9's 129 tok/s assumes these two do not contend.\n");
189
190    cudaFree(d_codes);
191    cudaFree(d_x);
192    cudaFree(d_scales);
193    cudaFree(d_y);
194    cudaStreamDestroy(s_copy);
195    cudaStreamDestroy(s_comp);
196    return 0;
197}