okami.mom/strata

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

Niko1221Merge f-q4-sycl (41717f29c): the Intel Arc (SYCL) engine follows the compiled geometry, so q4_lite/q4_mid/q4_big build; default build unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 string offsets only, Metal 85/85 objects, SYCL 22/22 checksums); A750 gate 2 q4_lite 0.00021 vs floor 0.00017; one conflict with f-clean-6-0 in sycl/src/prefill/prefill.cpp resolved as tested by Q4-SYMERGE (Qwen4 prep)db137d917

main
21.7 KiB482 linesraw
1#include <sycl/sycl.hpp>
2#include <dpct/dpct.hpp>
3#include "strata/core/remote_experts.hpp"
4
5#include "strata/kernels/cpu/expert_layout.hpp"
6#include "strata/kernels/cpu/hadamard.hpp"
7#include "strata/kernels/iq_kernels.hpp"
8#include "strata/kernels/quantize_act.hpp"
9#include "strata/kernels/s2_expert_grouped.hpp"
10
11#include <algorithm>
12#include <chrono>
13#include <cstdlib>
14#include <cstring>
15
16namespace strata::core {
17namespace {
18constexpr int64_t H = strata::kernels::cpu::H;
19constexpr int64_t FF = strata::kernels::cpu::FF;
20constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10;
21
22// Small enough to copy as one pinned buffer per layer. The kernels read the
23// individual arrays through pointers into the same device allocation.
24struct RemoteMeta {
25    unsigned long long ptr[CAP];
26    int32_t start[CAP + 1];
27    int32_t dst[CAP];
28    int32_t tok[CAP];
29    int32_t count;
30};
31
32struct DeviceScope {
33    int previous = -1;
34    bool ok = false;
35    dpct::err0 status = 0;
36    const char* failed_step = nullptr;
37    explicit DeviceScope(int device) {
38        status = DPCT_CHECK_ERROR(previous = dpct::get_current_device_id());
39        if (status != 0) {
40            previous = -1;
41            failed_step = "cudaGetDevice";
42            return;
43        }
44        /*
45        DPCT1093: The "device" device may be not the one intended for use.
46        Adjust the selected device if needed.
47        */
48        status = DPCT_CHECK_ERROR(dpct::select_device(device));
49        if (status != 0) {
50            failed_step = "cudaSetDevice";
51            return;
52        }
53        ok = true;
54    }
55    /*
56    DPCT1093: The "previous" device may be not the one intended for use.
57    Adjust the selected device if needed.
58    */
59    ~DeviceScope() { if (previous >= 0) dpct::select_device(previous); }
60    std::string error(int device) const {
61        return std::string("CUDA") + std::to_string(device) +
62               " experts: " + (failed_step ? failed_step : "device switch") +
63               /*
64               DPCT1009: SYCL reports errors using exceptions and does not
65               use error codes. Please replace the "get_error_string_dummy(...)"
66               with a real error-handling function.
67               */
68               "(" +
69               std::to_string(device) +
70               ") failed: " + dpct::get_error_string_dummy(status) +
71               " (CUDA error " + std::to_string((int)status) + ")";
72    }
73};
74
75bool check(dpct::err0 result, const char *what, std::string &err, int device) {
76    if (result == 0) return true;
77    /*
78    DPCT1009: SYCL reports errors using exceptions and does not use error
79    codes. Please replace the "get_error_string_dummy(...)" with a real
80    error-handling function.
81    */
82    err = "CUDA" + std::to_string(device) + " experts: " + what + ": " +
83          dpct::get_error_string_dummy(result);
84    return false;
85}
86} // namespace
87
88RemoteExperts::~RemoteExperts() { close(); }
89
90bool RemoteExperts::preflight(int device, double &free_gib,
91                              std::string &err) try {
92    int count = 0;
93    if (!check(DPCT_CHECK_ERROR(count = dpct::device_count()),
94               "cudaGetDeviceCount", err, device)) return false;
95    if (device < 1 || device >= count) {
96        err = "CUDA" + std::to_string(device) + " experts: CUDA device is not visible";
97        return false;
98    }
99    // The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up
100    // costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows).  Only possible
101    // before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default.
102    const char* spin = std::getenv("STRATA_REMOTE_SPIN");
103    /*
104    DPCT1007: Migration of cudaInitDevice is not supported.
105    */
106    (void) spin;   // SYCL: no cudaInitDevice scheduling flags; the runtime picks its own wait policy
107    /*
108    DPCT1026: The call to cudaGetLastError was removed because this
109    functionality is redundant in SYCL.
110    */
111    DeviceScope scope(device);
112    if (!scope.ok) { err = scope.error(device); return false; }
113    size_t free_bytes = 0, total_bytes = 0;
114    /*
115    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for
116    device information which may not be supported by all compilers or runtimes.
117    You may need to adjust the code.
118    */
119    if (!check(DPCT_CHECK_ERROR(dpct::get_current_device().get_memory_info(
120                   free_bytes, total_bytes)),
121               "preflight free memory", err, device)) return false;
122    free_gib = (double) free_bytes / 1073741824.0;
123    return true;
124}
125catch (sycl::exception const &exc) {
126  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
127            << ", line:" << __LINE__ << std::endl;
128  std::exit(1);
129}
130
131void RemoteExperts::close() {
132    if (device_ < 0) return;
133    DeviceScope scope(device_);
134    if (scope.ok) {
135        if (stream_) stream_->wait();
136        cache_.close();
137        if (d_x_) sycl::free(d_x_, dpct::get_in_order_queue());
138        if (d_out_) sycl::free(d_out_, dpct::get_in_order_queue());
139        if (d_q8_) sycl::free(d_q8_, dpct::get_in_order_queue());
140        if (d_scales_) sycl::free(d_scales_, dpct::get_in_order_queue());
141        if (d_scratch_) sycl::free(d_scratch_, dpct::get_in_order_queue());
142        if (d_meta_) sycl::free(d_meta_, dpct::get_in_order_queue());
143        if (h_x_) sycl::free(h_x_, dpct::get_in_order_queue());
144        if (h_out_) sycl::free(h_out_, dpct::get_in_order_queue());
145        if (h_meta_) sycl::free(h_meta_, dpct::get_in_order_queue());
146        if (stream_) dpct::get_current_device().destroy_queue(stream_);
147    }
148    device_ = -1;
149    stream_ = &dpct::get_in_order_queue();
150    h_x_ = h_out_ = d_x_ = d_out_ = nullptr;
151    h_meta_ = d_meta_ = nullptr;
152    d_q8_ = nullptr;
153    d_scales_ = nullptr;
154    d_scratch_ = nullptr;
155    d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr;
156    d_ptr_ = nullptr;
157    original_row_.clear();
158    layers_present_.clear();
159}
160
161bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts,
162                         const std::vector<std::pair<int32_t, int32_t>> &ranked,
163                         const ExpertCache &primary, ExpertSource &source,
164                         std::vector<uint8_t> &claimed, std::string &err, bool /*auto_size*/) try {
165    close();
166    if (strata::kernels::cpu::hadamard_spec().any()) {   // APR: this helper does not rotate the expert input yet (SYCL)
167        err = "second-GPU experts: Hadamard-folded (Gyro) experts are not supported on a second Intel GPU yet";
168        return false;
169    }
170    int count = 0;
171    if (!check(DPCT_CHECK_ERROR(count = dpct::device_count()),
172               "cudaGetDeviceCount", err, device)) return false;
173    if (device < 1 || device >= count || slots <= 0 || ranked.empty() ||
174        layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts) {
175        err = "CUDA" + std::to_string(device) + " experts: need the device, ranked experts and positive slot count";
176        return false;
177    }
178    DeviceScope scope(device);
179    if (!scope.ok) { err = scope.error(device); return false; }
180    device_ = device;
181    n_expert_ = experts;
182    const auto& lay = strata::kernels::cpu::expert_layout();
183    std::vector<std::pair<int32_t, int32_t>> selected;
184    selected.reserve((size_t) slots);
185    std::vector<uint8_t> picked(claimed.size(), 0);
186    for (const auto& pair : ranked) {
187        if (pair.first < 0 || pair.first >= layers || pair.second < 0 || pair.second >= experts) continue;
188        const size_t index = (size_t) pair.first * (size_t) experts + (size_t) pair.second;
189        if (primary.slot_of(pair.first, pair.second) < 0 && !claimed[index] && !picked[index]) {
190            selected.push_back(pair);
191            picked[index] = 1;
192            if ((int) selected.size() >= slots) break;
193        }
194    }
195    if (selected.empty()) { err = "CUDA" + std::to_string(device) + " experts: no unclaimed experts remain"; close(); return false; }
196    std::vector<int64_t> sizes;
197    if (lay.native) {
198        sizes.reserve(selected.size());
199        for (const auto& pair : selected) sizes.push_back((int64_t) lay.blob_bytes(pair.first));
200    }
201    size_t free_bytes = 0, total_bytes = 0;
202    /*
203    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for
204    device information which may not be supported by all compilers or runtimes.
205    You may need to adjust the code.
206    */
207    if (!check(DPCT_CHECK_ERROR(dpct::get_current_device().get_memory_info(
208                   free_bytes, total_bytes)),
209               "free memory", err, device)) {
210        close(); return false;
211    }
212    uint64_t needed = 0;
213    for (const auto& pair : selected)
214        needed += lay.native ? (lay.blob_bytes(pair.first) + 255) / 256 * 256 : lay.max_blob;
215    // Leave room for the CUDA context, staging and later driver allocations, especially under WDDM.
216    if (needed + (512ull << 20) > free_bytes) {
217        err = "CUDA" + std::to_string(device) + " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string(device);
218        close(); return false;
219    }
220    const bool cache_ok = lay.native ? cache_.open_sized(sizes, layers, experts, err)
221                                     : cache_.open((int64_t) selected.size(), layers, experts,
222                                                   (int64_t) lay.max_blob, err);
223    if (!cache_ok) { err = "CUDA" + std::to_string(device) + " experts: " + err; close(); return false; }
224    for (const auto& pair : selected) {
225        const int32_t slot = cache_.admit(pair.first, pair.second);
226        const uint8_t* blob = source.blob(pair.first, pair.second);
227        if (slot < 0 || !blob || !cache_.fill_slot_blocking(slot, blob, err, (int64_t) lay.blob_bytes(pair.first))) {
228            err = "CUDA" + std::to_string(device) + " experts: " +
229                  (err.empty() ? "cache fill failed" : err);
230            close(); return false;
231        }
232    }
233    const auto& first = selected.front();
234    if (!cache_.verify_slot(cache_.slot_of(first.first, first.second), source.blob(first.first, first.second),
235                            err, (int64_t) lay.blob_bytes(first.first))) {
236        err = "CUDA" + std::to_string(device) + " experts: " + err;
237        close(); return false;
238    }
239
240    const size_t scratch = std::max<size_t>(
241        (size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, FF),
242        strata::kernels::native_expert_scratch_bytes(CAP, FF));
243    const bool allocated =
244        /*
245        DPCT1025: The SYCL queue is created ignoring the flag and priority
246        options.
247        */
248        check(DPCT_CHECK_ERROR(
249                  stream_ = dpct::get_current_device().create_queue(true)),
250              "stream", err, device) &&
251        /*
252        DPCT1048: The original value cudaHostAllocPortable is not meaningful
253        in the migrated code and was removed or replaced with 0. You may need to
254        check the migrated code.
255        */
256        /*
257        DPCT1048: The original value cudaHostAllocMapped is not meaningful in
258        the migrated code and was removed or replaced with 0. You may need to
259        check the migrated code.
260        */
261        check(
262            DPCT_CHECK_ERROR(h_x_ = sycl::malloc_host<float>(
263                                 (size_t)CAP * H, dpct::get_in_order_queue())),
264            "input staging", err, device) &&
265        /*
266        DPCT1048: The original value cudaHostAllocPortable is not meaningful
267        in the migrated code and was removed or replaced with 0. You may need to
268        check the migrated code.
269        */
270        /*
271        DPCT1048: The original value cudaHostAllocMapped is not meaningful in
272        the migrated code and was removed or replaced with 0. You may need to
273        check the migrated code.
274        */
275        check(
276            DPCT_CHECK_ERROR(h_out_ = sycl::malloc_host<float>(
277                                 (size_t)CAP * H, dpct::get_in_order_queue())),
278            "result staging", err, device) &&
279        /*
280        DPCT1048: The original value cudaHostAllocPortable is not meaningful
281        in the migrated code and was removed or replaced with 0. You may need to
282        check the migrated code.
283        */
284        check(DPCT_CHECK_ERROR(
285                  h_meta_ = (void *)sycl::malloc_host(
286                      sizeof(RemoteMeta), dpct::get_in_order_queue())),
287              "metadata staging", err, device) &&
288        check(
289            DPCT_CHECK_ERROR(d_x_ = sycl::malloc_device<float>(
290                                 (size_t)CAP * H, dpct::get_in_order_queue())),
291            "input", err, device) &&
292        check(
293            DPCT_CHECK_ERROR(d_out_ = sycl::malloc_device<float>(
294                                 (size_t)CAP * H, dpct::get_in_order_queue())),
295            "result", err, device) &&
296        check(DPCT_CHECK_ERROR(
297                  d_q8_ = (uint8_t *)sycl::malloc_device(
298                      (size_t)CAP * (H / 32) * 36, dpct::get_in_order_queue())),
299              "activation", err, device) &&
300        check(DPCT_CHECK_ERROR(
301                  d_scales_ = sycl::malloc_device<float>(
302                      (size_t)CAP * (H / 32), dpct::get_in_order_queue())),
303              "activation scales", err, device) &&
304        check(DPCT_CHECK_ERROR(d_scratch_ = (void *)sycl::malloc_device(
305                                   scratch, dpct::get_in_order_queue())),
306              "scratch", err, device) &&
307        check(DPCT_CHECK_ERROR(
308                  d_meta_ = (void *)sycl::malloc_device(
309                      sizeof(RemoteMeta), dpct::get_in_order_queue())),
310              "group metadata", err, device);
311    if (!allocated) { close(); return false; }
312    // Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers
313    // directly - two copies fewer per layer, each of which is a PCIe round trip.  STRATA_REMOTE_ZEROCOPY=0 copies.
314    const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY");
315    zero_copy_ = !(zc && zc[0] == '0') &&
316                 DPCT_CHECK_ERROR(*(void **)&z_x_ = (float *)h_x_) == 0 &&
317                 DPCT_CHECK_ERROR(*(void **)&z_out_ = (float *)h_out_) == 0;
318    /*
319    DPCT1026: The call to cudaGetLastError was removed because this
320    functionality is redundant in SYCL.
321    */
322    auto *meta = (RemoteMeta *)d_meta_;
323    d_ptr_ = meta->ptr;
324    d_start_ = meta->start;
325    d_dst_ = meta->dst;
326    d_tok_ = meta->tok;
327    d_count_ = &meta->count;
328    owned_.resize(CAP);
329    layers_present_.assign((size_t) layers, 0);
330    group_of_.resize(CAP);
331    group_id_.reserve(CAP);
332    ptr_.reserve(CAP);
333    start_.reserve(CAP + 1);
334    dst_.reserve(CAP);
335    tok_.reserve(CAP);
336    original_row_.reserve(CAP);
337    computed_ = 0;
338    launched_layers_ = 0;
339    returned_bytes_ = full_row_bytes_ = 0;
340    for (const auto& pair : selected) {
341        layers_present_[(size_t) pair.first] = 1;
342        claimed[(size_t) pair.first * (size_t) experts + (size_t) pair.second] = 1;
343    }
344    return true;
345}
346catch (sycl::exception const &exc) {
347  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
348            << ", line:" << __LINE__ << std::endl;
349  std::exit(1);
350}
351
352bool RemoteExperts::begin(int64_t layer, const float *x, const int32_t *ids,
353                          int64_t n_tok, int64_t k, const int32_t *kind,
354                          const int32_t *primary_res, std::string &err) try {
355    // cumulative host time in here (staging and launches), reported per request by the driver
356    struct Timer { double& acc; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
357        ~Timer() { acc += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); } } timer{ms_begin_};
358    const int64_t n = n_tok * k;
359    if (n <= 0 || n > CAP || n_tok > strata::kernels::cpu::MAXT || k != (int) strata::core::kCompiledGeometry.n_expert_used || layer < 0 ||
360        (size_t) layer >= layers_present_.size() || device_ < 0) {
361        err = "CUDA" + std::to_string(device_) + " experts: invalid layer, routing width or window size";
362        return false;
363    }
364    std::fill(owned_.begin(), owned_.begin() + n, 0);
365    group_id_.clear(); ptr_.clear(); start_.clear(); dst_.clear(); tok_.clear(); original_row_.clear();
366    if (!layers_present_[(size_t) layer]) return true;
367    std::fill(group_of_.begin(), group_of_.begin() + n, -1);
368    for (int64_t i = 0; i < n; ++i) {
369        const int32_t e = ids[i];
370        if ((kind && kind[i] != -1) || e < 0 || e >= n_expert_ ||
371            (primary_res && primary_res[(size_t) layer * (size_t) n_expert_ + (size_t) e] >= 0)) continue;
372        const int32_t slot = cache_.slot_of(layer, e);
373        if (slot < 0) continue;
374        owned_[(size_t) i] = 1;
375        int32_t group = -1;
376        for (size_t g = 0; g < group_id_.size(); ++g)
377            if (group_id_[g] == e) { group = (int32_t) g; break; }
378        if (group < 0) {
379            group = (int32_t) group_id_.size();
380            group_id_.push_back(e);
381            ptr_.push_back((unsigned long long) cache_.device_slot(slot));
382        }
383        group_of_[(size_t) i] = group;
384        ++computed_;
385    }
386    if (group_id_.empty()) return true;
387    for (size_t g = 0; g < group_id_.size(); ++g) {
388        start_.push_back((int32_t) dst_.size());
389        for (int64_t i = 0; i < n; ++i) if (group_of_[(size_t) i] == (int32_t) g) {
390            // The grouped kernels read the activation from `tok`, so their
391            // output row can instead be packed densely for the USB4 return.
392            original_row_.push_back((int32_t) i);
393            dst_.push_back((int32_t) dst_.size());
394            tok_.push_back((int32_t) (i / k));
395        }
396    }
397    start_.push_back((int32_t) dst_.size());
398    // Private pinned buffers survive until this GPU has consumed them. The CPU
399    // pool can write other output rows without a cross-device race.
400    std::memcpy(h_x_, x, (size_t) n_tok * H * sizeof(float));
401    auto* meta = (RemoteMeta*) h_meta_;
402    std::memcpy(meta->ptr, ptr_.data(), ptr_.size() * sizeof(ptr_[0]));
403    std::memcpy(meta->start, start_.data(), start_.size() * sizeof(start_[0]));
404    std::memcpy(meta->dst, dst_.data(), dst_.size() * sizeof(dst_[0]));
405    std::memcpy(meta->tok, tok_.data(), tok_.size() * sizeof(tok_[0]));
406    meta->count = (int32_t) group_id_.size();
407    DeviceScope scope(device_);
408    if (!scope.ok) { err = scope.error(device_); return false; }
409    groups_ = (int32_t) group_id_.size();
410    const dpct::queue_ptr s = stream_;
411    const bool staged =
412        /*
413        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
414        While the origin API might be synchronous, it depends on the type of
415        operand memory, so you may need to call wait() on event return by memcpy
416        API to ensure synchronization behavior.
417        */
418        (zero_copy_ ||
419         check(DPCT_CHECK_ERROR(
420                   s->memcpy(d_x_, h_x_, (size_t)n_tok * H * sizeof(float))),
421               "copy input", err, device_)) &&
422        /*
423        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
424        While the origin API might be synchronous, it depends on the type of
425        operand memory, so you may need to call wait() on event return by memcpy
426        API to ensure synchronization behavior.
427        */
428        check(DPCT_CHECK_ERROR(s->memcpy(d_meta_, h_meta_, sizeof(RemoteMeta))),
429              "copy group metadata", err, device_);
430    if (!staged) return false;
431    const auto& lay = strata::kernels::cpu::expert_layout();
432    if (lay.native) {
433        strata::kernels::quantize_q8_1_rows(zero_copy_ ? z_x_ : d_x_, n_tok, H, d_q8_, s);
434        const auto& fmt = lay.fmt[(size_t) layer];
435        auto L = strata::kernels::native_expert_layout(fmt.gu_type, fmt.d_type, fmt.n_embd, fmt.n_ff);
436        strata::kernels::native_expert_grouped(L, d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
437                                               groups_, (int64_t) dst_.size(), d_q8_, d_scratch_, zero_copy_ ? z_out_ : d_out_, s);
438    } else {
439        strata::kernels::quantize_q8_0_scaled(zero_copy_ ? z_x_ : d_x_, d_q8_, d_scales_, n_tok * H, s);
440        strata::kernels::moe_grouped_s2(d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
441                                        groups_, (int64_t) dst_.size(), d_q8_, d_scales_, d_scratch_, zero_copy_ ? z_out_ : d_out_, s);
442    }
443    const uint64_t compact_bytes = (uint64_t) dst_.size() * H * sizeof(float);
444    /*
445    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
446    the origin API might be synchronous, it depends on the type of operand
447    memory, so you may need to call wait() on event return by memcpy API to
448    ensure synchronization behavior.
449    */
450    if (!zero_copy_ && !check(DPCT_CHECK_ERROR(s->memcpy(
451                                  h_out_, d_out_, (size_t)compact_bytes)),
452                              "copy results", err, device_)) return false;
453    ++launched_layers_;
454    returned_bytes_ += compact_bytes;
455    full_row_bytes_ += (uint64_t) n * H * sizeof(float);
456    return true;
457}
458catch (sycl::exception const &exc) {
459  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
460            << ", line:" << __LINE__ << std::endl;
461  std::exit(1);
462}
463
464bool RemoteExperts::finish(float *out, std::string &err) try {
465    if (group_id_.empty()) return true;
466    DeviceScope scope(device_);
467    if (!scope.ok) { err = scope.error(device_); return false; }
468    const auto w0 = std::chrono::steady_clock::now();
469    if (!check(DPCT_CHECK_ERROR(stream_->wait()), "finish", err,
470               device_)) return false;
471    ms_wait_ += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - w0).count();
472    for (size_t i = 0; i < original_row_.size(); ++i)
473        std::memcpy(out + (size_t) original_row_[i] * H, h_out_ + i * H, (size_t) H * sizeof(float));
474    return true;
475}
476catch (sycl::exception const &exc) {
477  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
478            << ", line:" << __LINE__ << std::endl;
479  std::exit(1);
480}
481
482} // namespace strata::core