okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
12.9 KiB272 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#define DPCT_PROFILING_ENABLED
17#include <sycl/sycl.hpp>
18#include <dpct/dpct.hpp>
19#include "strata/core/pinned.hpp"
20#include "strata/kernels/s_gemv.hpp"
21
22#include <atomic>
23#include <chrono>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <fstream>
28#include <string>
29#include <thread>
30#include <vector>
31
32namespace {
33
34void check(dpct::err0 e, const char *what) {
35}
36
37// Volatile sink so the read loop cannot be optimised away; summed across threads and printed, so a compiler
38// that removed the loads would produce a suspiciously round zero rather than a plausible number.
39std::atomic<uint64_t> g_sink{0};
40
41struct Run {
42    double seconds = 0;
43    double cpu_gb = 0;      // GB/s read by the CPU threads
44    double gpu_experts = 0; // experts streamed and computed by the GPU
45};
46
47}  // namespace
48
49int main(int argc, char** argv) {
50    std::string path;
51    // 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 -
52    // that is CACHE bandwidth, not DRAM, and it would have answered the contention question with a number about
53    // a different resource entirely.
54    int experts = 4096;
55    int cpu_threads = 6;
56    int gpu_roles = 256;
57    for (int i = 1; i < argc; ++i) {
58        const std::string a = argv[i];
59        auto val = [&]() -> const char* {
60            if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); }
61            return argv[++i];
62        };
63        if (a == "--file") path = val();
64        else if (a == "--experts") experts = std::atoi(val());
65        else if (a == "--cpu-threads") cpu_threads = std::atoi(val());
66        else if (a == "--gpu-roles") gpu_roles = std::atoi(val());
67        else {
68            std::fprintf(stderr, "usage: strata-concurrent --file experts.bin [--experts N] "
69                                 "[--cpu-threads N] [--gpu-roles N]\n");
70            return 2;
71        }
72    }
73    if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; }
74
75    const long long n_in = 2560, n_out = 640;
76    const uint64_t role_codes = (uint64_t) n_out * n_in / 4;
77    const uint64_t plane_bytes = role_codes;      // the CPU loop reads the same planes
78
79    strata::core::PinnedArena arena((uint64_t) experts * role_codes);
80    if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; }
81    {
82        std::ifstream f(path, std::ios::binary);
83        if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; }
84        for (int i = 0; i < experts; ++i) {
85            f.seekg((std::streamoff) i * 1382400);
86            f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes);
87            if ((uint64_t) f.gcount() != role_codes) { std::fprintf(stderr, "short read\n"); return 1; }
88        }
89    }
90    std::printf("arena %.2f GiB pinned; %d CPU threads; %d GPU roles\n",
91                (double) arena.capacity / (1024.0 * 1024 * 1024), cpu_threads, gpu_roles);
92
93    uint8_t* d_codes = nullptr;
94    check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(
95                               role_codes, dpct::get_in_order_queue())),
96          "cudaMalloc codes");
97    uint16_t* d_x = nullptr;
98    float *d_scales = nullptr, *d_y = nullptr;
99    check(DPCT_CHECK_ERROR(
100              d_x = (uint16_t *)sycl::malloc_device(
101                  n_in * sizeof(uint16_t), dpct::get_in_order_queue())),
102          "cudaMalloc x");
103    check(DPCT_CHECK_ERROR(d_scales = (float *)sycl::malloc_device(
104                               (size_t)n_out * (n_in / 64) * sizeof(float),
105                               dpct::get_in_order_queue())),
106          "cudaMalloc scales");
107    check(DPCT_CHECK_ERROR(
108              d_y = (float *)sycl::malloc_device(n_out * sizeof(float),
109                                                 dpct::get_in_order_queue())),
110          "cudaMalloc y");
111    std::vector<uint16_t> hx((size_t) n_in, 0x3C00);
112    std::vector<float> hs((size_t) n_out * (size_t) (n_in / 64), 0.001f);
113    /*
114    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
115    the original code the source host memory is pageable memory. If the memory
116    is not pageable, call wait() on event return by memcpy API to ensure
117    synchronization behavior.
118    */
119    check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
120              d_x, hx.data(), hx.size() * sizeof(uint16_t)).wait()),
121          "copy x");
122    /*
123    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
124    the original code the source host memory is pageable memory. If the memory
125    is not pageable, call wait() on event return by memcpy API to ensure
126    synchronization behavior.
127    */
128    check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
129              d_scales, hs.data(), hs.size() * sizeof(float)).wait()),
130          "copy scales");
131    dpct::queue_ptr s_copy{}, s_comp{};
132    check(DPCT_CHECK_ERROR(s_copy =
133                               dpct::get_current_device().create_queue(true)),
134          "stream copy");
135    check(DPCT_CHECK_ERROR(s_comp =
136                               dpct::get_current_device().create_queue(true)),
137          "stream compute");
138    const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false};
139
140    // The CPU loop: read the whole arena, Nthreads ways, and sum bytes so nothing is elided.
141    auto cpu_work = [&](std::atomic<bool>& stop, std::atomic<uint64_t>& bytes) {
142        uint64_t acc = 0, n = 0;
143        const uint8_t* p = arena.data();
144        while (!stop.load(std::memory_order_relaxed)) {
145            // touch one byte per 64 - a stride that defeats prefetch into a pure streaming read
146            for (uint64_t i = 0; i < plane_bytes * (uint64_t) experts; i += 64) acc += p[i];
147            n += plane_bytes * (uint64_t) experts;
148        }
149        bytes.fetch_add(n);
150        g_sink.fetch_add(acc);
151    };
152
153    // The GPU loop: stream each role plane on the copy stream while computing on the compute stream.
154    auto gpu_work = [&](int roles) {
155        try {
156    dpct::event_ptr ev[2];
157        for (int b = 0; b < 2; ++b)
158            check(DPCT_CHECK_ERROR(ev[b] = new sycl::event()), "event");
159        uint8_t* buf[2] = {d_codes, d_codes};      // one buffer is enough: the timing is what is measured
160        /*
161        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
162        While the origin API might be synchronous, it depends on the type of
163        operand memory, so you may need to call wait() on event return by memcpy
164        API to ensure synchronization behavior.
165        */
166        check(
167            DPCT_CHECK_ERROR(s_copy->memcpy(buf[0], arena.data(), role_codes)),
168            "prologue");
169        /*
170        DPCT1024: The original code returned the error code that was further
171        consumed by the program logic. This original code was replaced with 0.
172        You may need to rewrite the program logic consuming the error code.
173        */
174        check(DPCT_CHECK_ERROR(dpct::sync_barrier(ev[0], s_copy)),
175              "prologue event");
176        for (int i = 0; i < roles; ++i) {
177            const int cur = i & 1, nxt = (i + 1) & 1;
178            if (i + 1 < roles) {
179                /*
180                DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
181                API. While the origin API might be synchronous, it depends on
182                the type of operand memory, so you may need to call wait() on
183                event return by memcpy API to ensure synchronization behavior.
184                */
185                check(DPCT_CHECK_ERROR(s_copy->memcpy(
186                          buf[nxt],
187                          arena.data() +
188                              (uint64_t)((i + 1) % experts) * role_codes,
189                          role_codes)),
190                      "copy");
191                /*
192                DPCT1024: The original code returned the error code that was
193                further consumed by the program logic. This original code was
194                replaced with 0. You may need to rewrite the program logic
195                consuming the error code.
196                */
197                check(DPCT_CHECK_ERROR(dpct::sync_barrier(ev[nxt], s_copy)),
198                      "event");
199            }
200            check(
201                DPCT_CHECK_ERROR(s_comp->ext_oneapi_submit_barrier({*ev[cur]})),
202                "wait");
203            strata::kernels::s_gemv_split_async(d_x, buf[cur], d_scales, nullptr, d_y, n_in, n_out, form, 32,
204                                                (void*) s_comp);
205        }
206        check(DPCT_CHECK_ERROR(s_comp->wait()), "sync comp");
207        check(DPCT_CHECK_ERROR(s_copy->wait()), "sync copy");
208        for (int b = 0; b < 2; ++b) dpct::destroy_event(ev[b]);
209    }
210    catch (sycl::exception const &exc) {
211      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
212                << ", line:" << __LINE__ << std::endl;
213      std::exit(1);
214    }
215    };
216
217    auto run = [&](bool do_cpu, bool do_gpu, const char *name) {
218        try {
219    std::atomic<bool> stop{false};
220        std::atomic<uint64_t> bytes{0};
221        std::vector<std::thread> cpu;
222        check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().wait()), "pre");
223        const auto t0 = std::chrono::steady_clock::now();
224        if (do_cpu) for (int t = 0; t < cpu_threads; ++t) cpu.emplace_back(cpu_work, std::ref(stop), std::ref(bytes));
225        if (do_gpu) {
226            gpu_work(gpu_roles);
227        } else {
228            // CPU-only needs a REAL window.  The first version let t0..t1 span nothing when there was no GPU
229            // work, so the threads were stopped immediately and the run reported 0.000 s and 0.00 GB/s.
230            std::this_thread::sleep_for(std::chrono::milliseconds(3000));
231        }
232        const auto t1 = std::chrono::steady_clock::now();
233        stop = true;
234        for (auto& t : cpu) t.join();
235        Run r;
236        r.seconds = std::chrono::duration<double>(t1 - t0).count();
237        r.cpu_gb = (double) bytes.load() / 1e9 / r.seconds;
238        r.gpu_experts = do_gpu ? (double) gpu_roles / r.seconds : 0.0;
239        std::printf("  %-18s %7.3f s   CPU read %6.2f GB/s   GPU %7.1f roles/s\n", name, r.seconds, r.cpu_gb,
240                    r.gpu_experts);
241        return r;
242    }
243    catch (sycl::exception const &exc) {
244      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
245                << ", line:" << __LINE__ << std::endl;
246      std::exit(1);
247    }
248    };
249
250    std::printf("\n  mode                     wall   CPU read          GPU\n");
251    const Run cpu_only = run(true, false, "CPU only");
252    const Run gpu_only = run(false, true, "GPU only");
253    const Run both = run(true, true, "BOTH");
254
255    std::printf("\n  independence check (1.00 = perfectly shared, 0.00 = fully independent):\n");
256    const double cpu_interference = cpu_only.cpu_gb > 0 ? 1.0 - both.cpu_gb / cpu_only.cpu_gb : 0.0;
257    const double gpu_interference = gpu_only.gpu_experts > 0 ? 1.0 - both.gpu_experts / gpu_only.gpu_experts : 0.0;
258    std::printf("    CPU throughput lost when the GPU also runs : %5.1f%%\n", cpu_interference * 100);
259    std::printf("    GPU throughput lost when the CPU also runs : %5.1f%%\n", gpu_interference * 100);
260    std::printf("    combined vs the sum of the parts           : CPU %6.2f + GPU-equivalent vs %6.2f measured\n",
261                cpu_only.cpu_gb, both.cpu_gb);
262    std::printf("\n  NOTE: the CPU side is a READ LOOP, not the VNNI kernel - it measures DRAM DEMAND, which is the\n"
263                "        resource the question is about.  L9's 129 tok/s assumes these two do not contend.\n");
264
265    sycl::free(d_codes, dpct::get_in_order_queue());
266    sycl::free(d_x, dpct::get_in_order_queue());
267    sycl::free(d_scales, dpct::get_in_order_queue());
268    sycl::free(d_y, dpct::get_in_order_queue());
269    dpct::get_current_device().destroy_queue(s_copy);
270    dpct::get_current_device().destroy_queue(s_comp);
271    return 0;
272}