okami.mom/strata

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

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

main
11.6 KiB239 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#define DPCT_PROFILING_ENABLED
13#include <sycl/sycl.hpp>
14#include <dpct/dpct.hpp>
15#include "strata/core/pinned.hpp"
16#include "strata/kernels/s_gemv.hpp"
17
18#include <chrono>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <fstream>
23#include <string>
24#include <vector>
25
26namespace {
27
28void check(dpct::err0 e, const char *what) {
29}
30
31struct Timing {
32    double seconds = 0;
33    const char* name = "";
34};
35
36}  // namespace
37
38int main(int argc, char** argv) {
39    std::string path;
40    int experts = 64;
41    int threads_per_row = 32;
42    for (int i = 1; i < argc; ++i) {
43        const std::string a = argv[i];
44        auto val = [&]() -> const char* {
45            if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); }
46            return argv[++i];
47        };
48        if (a == "--file") path = val();
49        else if (a == "--experts") experts = std::atoi(val());
50        else if (a == "--tpr") threads_per_row = std::atoi(val());
51        else {
52            std::fprintf(stderr, "usage: strata-overlap --file experts.bin [--experts N] [--tpr N]\n");
53            return 2;
54        }
55    }
56    if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; }
57
58    // One ROLE's worth of S2 weights: gate is [n_embd 2560] x [ff 640] = 1,638,400 weights = 460,800 B of
59    // codes at 4 codes per byte, plus 40 scales per row.
60    const long long n_in = 2560, n_out = 640;
61    const uint64_t role_codes = (uint64_t) n_out * n_in / 4;
62    const uint64_t role_bytes = role_codes + (uint64_t) n_out * (n_in / 64) * 4;
63    std::printf("per role: %lld x %lld S2 weights, %.1f KB of planes\n", n_in, n_out, role_bytes / 1024.0);
64
65    // host side: `experts` blobs read into a pinned arena, and the S2 planes the GEMV will read
66    strata::core::PinnedArena arena((uint64_t) experts * role_codes);
67    if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; }
68    {
69        std::ifstream f(path, std::ios::binary);
70        if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; }
71        // take the first `experts` blobs' worth of CODE bytes, pretending each is a role's plane: the bytes
72        // are real Q2_0 codes, so the kernel decodes real data and no cache-friendly pattern is invented
73        for (int i = 0; i < experts; ++i) {
74            f.seekg((std::streamoff) i * 1382400);
75            f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes);
76            if ((uint64_t) f.gcount() != role_codes) {
77                std::fprintf(stderr, "short read on expert %d\n", i);
78                return 1;
79            }
80        }
81    }
82    std::printf("loaded %d role-sized planes into a %s arena\n", experts, arena.note.c_str());
83
84    // device side: double buffered codes, plus x / scales / y
85    uint8_t* d_codes[2] = {nullptr, nullptr};
86    for (int b = 0; b < 2; ++b)
87        check(DPCT_CHECK_ERROR(d_codes[b] = (uint8_t *)sycl::malloc_device(
88                                   role_codes, dpct::get_in_order_queue())),
89              "cudaMalloc codes");
90    uint16_t* d_x = nullptr;
91    float *d_scales = nullptr, *d_y = nullptr;
92    check(DPCT_CHECK_ERROR(
93              d_x = (uint16_t *)sycl::malloc_device(
94                  n_in * sizeof(uint16_t), dpct::get_in_order_queue())),
95          "cudaMalloc x");
96    check(DPCT_CHECK_ERROR(d_scales = (float *)sycl::malloc_device(
97                               (size_t)n_out * (n_in / 64) * sizeof(float),
98                               dpct::get_in_order_queue())),
99          "cudaMalloc scales");
100    check(DPCT_CHECK_ERROR(
101              d_y = (float *)sycl::malloc_device(n_out * sizeof(float),
102                                                 dpct::get_in_order_queue())),
103          "cudaMalloc y");
104    std::vector<uint16_t> hx((size_t) n_in, 0x3C00);
105    std::vector<float> hs((size_t) n_out * (size_t) (n_in / 64), 0.001f);
106    /*
107    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
108    the original code the source host memory is pageable memory. If the memory
109    is not pageable, call wait() on event return by memcpy API to ensure
110    synchronization behavior.
111    */
112    check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
113              d_x, hx.data(), hx.size() * sizeof(uint16_t)).wait()),
114          "copy x");
115    /*
116    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
117    the original code the source host memory is pageable memory. If the memory
118    is not pageable, call wait() on event return by memcpy API to ensure
119    synchronization behavior.
120    */
121    check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
122              d_scales, hs.data(), hs.size() * sizeof(float)).wait()),
123          "copy scales");
124
125    dpct::queue_ptr s_copy{}, s_comp{};
126    check(DPCT_CHECK_ERROR(s_copy =
127                               dpct::get_current_device().create_queue(true)),
128          "stream copy");
129    check(DPCT_CHECK_ERROR(s_comp =
130                               dpct::get_current_device().create_queue(true)),
131          "stream compute");
132    const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false};
133
134    // ---- SERIAL: the same operations on the SAME stream, so the GPU runs them one after another ----
135    //
136    // NOT a sync-per-iteration loop.  The first version waited with `cudaStreamSynchronize` after every copy and
137    // measured 234.8 us/expert where a copy plus a GEMV is ~43 us: the baseline was dominated by the CPU
138    // round-trip, so the ratio of 0.095 mostly measured "with syncs" against "without syncs".  Putting both
139    // operations on one stream expresses the same dependency with NO CPU involvement and ONE sync at the end,
140    // which is what makes the comparison about overlap rather than about synchronisation.
141    check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().wait()), "pre sync");
142    auto t0 = std::chrono::steady_clock::now();
143    for (int i = 0; i < experts; ++i) {
144        /*
145        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
146        While the origin API might be synchronous, it depends on the type of
147        operand memory, so you may need to call wait() on event return by memcpy
148        API to ensure synchronization behavior.
149        */
150        check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
151                  d_codes[0], arena.data() + (uint64_t)i * role_codes,
152                  role_codes).wait()),
153              "serial copy");
154        strata::kernels::s_gemv_split_async(
155            d_x, d_codes[0], d_scales, nullptr, d_y, n_in, n_out, form,
156            threads_per_row,
157            (void *)(dpct::queue_ptr)&dpct::get_in_order_queue());
158    }
159    check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().wait()),
160          "serial final sync");
161    const double serial = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
162
163    // ---- OVERLAPPED: copy the next one while computing on the current one ----
164    check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().wait()), "pre sync 2");
165    dpct::event_ptr ev[2];
166    for (int b = 0; b < 2; ++b)
167        check(DPCT_CHECK_ERROR(ev[b] = new sycl::event()), "event");
168    t0 = std::chrono::steady_clock::now();
169    /*
170    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
171    the origin API might be synchronous, it depends on the type of operand
172    memory, so you may need to call wait() on event return by memcpy API to
173    ensure synchronization behavior.
174    */
175    check(
176        DPCT_CHECK_ERROR(s_copy->memcpy(d_codes[0], arena.data(), role_codes)),
177        "prologue");
178    /*
179    DPCT1024: The original code returned the error code that was further
180    consumed by the program logic. This original code was replaced with 0. You
181    may need to rewrite the program logic consuming the error code.
182    */
183    check(DPCT_CHECK_ERROR(dpct::sync_barrier(ev[0], s_copy)),
184          "prologue event");
185    for (int i = 0; i < experts; ++i) {
186        const int cur = i & 1, nxt = (i + 1) & 1;
187        if (i + 1 < experts) {
188            /*
189            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
190            API. While the origin API might be synchronous, it depends on the
191            type of operand memory, so you may need to call wait() on event
192            return by memcpy API to ensure synchronization behavior.
193            */
194            check(
195                DPCT_CHECK_ERROR(s_copy->memcpy(
196                    d_codes[nxt], arena.data() + (uint64_t)(i + 1) * role_codes,
197                    role_codes)),
198                "overlap copy");
199            /*
200            DPCT1024: The original code returned the error code that was
201            further consumed by the program logic. This original code was
202            replaced with 0. You may need to rewrite the program logic consuming
203            the error code.
204            */
205            check(DPCT_CHECK_ERROR(dpct::sync_barrier(ev[nxt], s_copy)),
206                  "overlap event");
207        }
208        // the compute stream must not start row i until its codes have landed
209        check(DPCT_CHECK_ERROR(s_comp->ext_oneapi_submit_barrier({*ev[cur]})),
210              "wait");
211        // a hand-written launch so it goes on s_comp; `s_gemv` synchronises on the default stream
212        strata::kernels::s_gemv_split_async(d_x, d_codes[cur], d_scales, nullptr, d_y, n_in, n_out, form,
213                                            threads_per_row, (void*) s_comp);
214    }
215    check(DPCT_CHECK_ERROR(s_comp->wait()), "final sync");
216    check(DPCT_CHECK_ERROR(s_copy->wait()), "final sync 2");
217    const double overlap = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
218
219    std::printf("\n  serial     %8.3f ms for %d experts  (%.1f us/expert)\n", serial * 1000, experts,
220                serial * 1e6 / experts);
221    std::printf("  overlapped %8.3f ms for %d experts  (%.1f us/expert)\n", overlap * 1000, experts,
222                overlap * 1e6 / experts);
223    std::printf("  ratio      %.3f  (1.00 = no overlap at all, <1.00 = overlap)\n", overlap / serial);
224    std::printf("\nNOTE: the OVERLAPPED loop launches on `s_comp` without synchronising, so the copy and the\n"
225                "      compute really are concurrent; the serial loop waits after each step.  What this does NOT\n"
226                "      model is the CPU expert path, the router, or the fact that a real token has 1440 roles to\n"
227                "      stream rather than %d.\n", experts);
228
229    for (int b = 0; b < 2; ++b) {
230        sycl::free(d_codes[b], dpct::get_in_order_queue());
231        dpct::destroy_event(ev[b]);
232    }
233    sycl::free(d_x, dpct::get_in_order_queue());
234    sycl::free(d_scales, dpct::get_in_order_queue());
235    sycl::free(d_y, dpct::get_in_order_queue());
236    dpct::get_current_device().destroy_queue(s_copy);
237    dpct::get_current_device().destroy_queue(s_comp);
238    return 0;
239}