okami.mom/strata

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

Niko1221Merge f-q4-geometry (fc1c4e429): the model shape is fixed at build time (-DSTRATA_GEOMETRY / -DSTRATA_GEOMETRY_FILE); the default Flash-Next build is unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 path-string offsets only, SYCL 22/22 checksums, Metal 10/10 tokens, CUDA 130/130 tokens); Qwen4 test shapes q4_lite/q4_mid/q4_big pass logits gate 2 on CUDA (Qwen4 prep)4dad59ab3

main
24.5 KiB501 linesraw
1#include "strata/core/remote_experts.hpp"
2#include "strata/core/device.hpp"   // primary_device() (STRATA_PRIMARY_DEVICE)
3#include "strata/core/remote_expert_opt.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#include "strata/kernels/window_limits.hpp"
11
12#include <algorithm>
13#include <chrono>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17
18namespace strata::core {
19namespace {
20constexpr int64_t H = strata::kernels::cpu::H;
21constexpr int64_t FF = strata::kernels::cpu::FF;
22constexpr int64_t CAP = strata::kernels::kWindowMaxT * 10;   // a window's rows x top-10
23
24// Small enough to copy as one pinned buffer per layer. The kernels read the
25// individual arrays through pointers into the same device allocation.
26struct RemoteMeta {
27    unsigned long long ptr[CAP];
28    int32_t start[CAP + 1];
29    int32_t dst[CAP];
30    int32_t tok[CAP];
31    int32_t count;
32};
33
34struct DeviceScope {
35    int previous = -1;
36    bool ok = false;
37    cudaError_t status = cudaSuccess;
38    const char* failed_step = nullptr;
39    explicit DeviceScope(int device) {
40        status = cudaGetDevice(&previous);
41        if (status != cudaSuccess) {
42            previous = -1;
43            failed_step = "cudaGetDevice";
44            return;
45        }
46        status = cudaSetDevice(device);
47        if (status != cudaSuccess) {
48            failed_step = "cudaSetDevice";
49            return;
50        }
51        ok = true;
52    }
53    ~DeviceScope() { if (previous >= 0) cudaSetDevice(previous); }
54    std::string error(int device) const {
55        return std::string("CUDA") + std::to_string(device) + " experts: " +
56               (failed_step ? failed_step : "device switch") +
57               "(" + std::to_string(device) + ") failed: " + cudaGetErrorString(status) +
58               " (CUDA error " + std::to_string((int) status) + ")";
59    }
60};
61
62bool check(cudaError_t result, const char* what, std::string& err, int device) {
63    if (result == cudaSuccess) return true;
64    err = "CUDA" + std::to_string(device) + " experts: " + what + ": " + cudaGetErrorString(result);
65    return false;
66}
67} // namespace
68
69RemoteExperts::~RemoteExperts() { close(); }
70
71bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) {
72    int count = 0;
73    if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false;
74    if (device < 0 || device >= count) {
75        err = "CUDA" + std::to_string(device) + " experts: CUDA device is not visible";
76        return false;
77    }
78    if (device == primary_device()) {   // the primary may be any visible ordinal; the helper cannot be it
79        err = "CUDA" + std::to_string(device) + " experts: the helper cannot be the primary device "
80                                                 "(STRATA_PRIMARY_DEVICE)";
81        return false;
82    }
83    // The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up
84    // costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows).  Only possible
85    // before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default.
86#if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL)
87    const char* spin = std::getenv("STRATA_REMOTE_SPIN");
88    if (!(spin && spin[0] == '0')) cudaInitDevice(device, cudaDeviceScheduleSpin | cudaDeviceMapHost, 0);
89    cudaGetLastError();
90#endif
91    // HIP has no cudaInitDevice equivalent; retain its default scheduling policy.
92    DeviceScope scope(device);
93    if (!scope.ok) { err = scope.error(device); return false; }
94    size_t free_bytes = 0, total_bytes = 0;
95    if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "preflight free memory", err, device)) return false;
96    free_gib = (double) free_bytes / 1073741824.0;
97    return true;
98}
99
100void RemoteExperts::close() {
101    if (device_ < 0) return;
102    DeviceScope scope(device_);
103    if (scope.ok) {
104        if (stream_) cudaStreamSynchronize(stream_);
105        if (read_stream_) cudaStreamSynchronize(read_stream_);
106        cache_.close();
107        if (d_x_) cudaFree(d_x_);
108        if (d_out_) cudaFree(d_out_);
109        if (d_q8_) cudaFree(d_q8_);
110        if (d_scales_) cudaFree(d_scales_);
111        if (d_xr_) cudaFree(d_xr_);
112        if (d_scratch_) cudaFree(d_scratch_);
113        if (d_meta_) cudaFree(d_meta_);
114        if (h_x_) cudaFreeHost(h_x_);
115        if (h_out_) cudaFreeHost(h_out_);
116        if (h_meta_) cudaFreeHost(h_meta_);
117        if (stream_) cudaStreamDestroy(stream_);
118        if (read_stream_) cudaStreamDestroy(read_stream_);
119    }
120    device_ = -1;
121    stream_ = nullptr;
122    read_stream_ = nullptr;
123    h_x_ = h_out_ = d_x_ = d_out_ = nullptr;
124    h_meta_ = d_meta_ = nullptr;
125    d_q8_ = nullptr;
126    d_scales_ = nullptr;
127    d_xr_ = nullptr;
128    d_sx_ = d_sh_ = nullptr;
129    d_scratch_ = nullptr;
130    d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr;
131    d_ptr_ = nullptr;
132    original_row_.clear();
133    layers_present_.clear();
134}
135
136bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts,
137                         const std::vector<std::pair<int32_t, int32_t>>& ranked,
138                         const ExpertCache& primary, ExpertSource& source,
139                         std::vector<uint8_t>& claimed, std::string& err, bool auto_size) {
140    close();
141    int count = 0;
142    if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false;
143    if (device < 0 || device >= count || slots <= 0 || ranked.empty() ||
144        layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts ||
145        device == primary_device()) {   // the helper cannot be the primary device (any visible ordinal)
146        err = "CUDA" + std::to_string(device) + " experts: need the device, ranked experts and positive slot count";
147        return false;
148    }
149    DeviceScope scope(device);
150    if (!scope.ok) { err = scope.error(device); return false; }
151    device_ = device;
152    n_expert_ = experts;
153    const auto& lay = strata::kernels::cpu::expert_layout();
154    size_t free_bytes = 0, total_bytes = 0;
155    if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "free memory", err, device)) { close(); return false; }
156    uint64_t needed = 0;
157    std::vector<std::pair<int32_t, int32_t>> selected;
158    selected.reserve((size_t) std::min<int64_t>(slots, layers * experts));
159    std::vector<uint8_t> picked(claimed.size(), 0);
160    for (const auto& pair : ranked) {
161        if (pair.first < 0 || pair.first >= layers || pair.second < 0 || pair.second >= experts) continue;
162        const size_t index = (size_t) pair.first * (size_t) experts + (size_t) pair.second;
163        if (primary.slot_of(pair.first, pair.second) < 0 && !claimed[index] && !picked[index]) {
164            const uint64_t bytes = lay.native ? (lay.blob_bytes(pair.first) + 255) / 256 * 256 : lay.max_blob;
165            if (auto_size && needed + bytes + (512ull << 20) > free_bytes) break;
166            selected.push_back(pair);
167            needed += bytes;
168            picked[index] = 1;
169            if ((int) selected.size() >= slots) break;
170        }
171    }
172    if (selected.empty()) {
173        err = "CUDA" + std::to_string(device) + (auto_size ? " experts: no unclaimed expert fits with 512 MiB free"
174                                                          : " experts: no unclaimed experts remain");
175        close(); return false;
176    }
177    std::vector<int64_t> sizes;
178    if (lay.native) {
179        sizes.reserve(selected.size());
180        for (const auto& pair : selected) sizes.push_back((int64_t) lay.blob_bytes(pair.first));
181    }
182    // Leave room for the CUDA context, staging and later driver allocations, especially under WDDM.
183    if (needed + (512ull << 20) > free_bytes) {
184        err = "CUDA" + std::to_string(device) + " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string(device);
185        close(); return false;
186    }
187    const bool cache_ok = lay.native ? cache_.open_sized(sizes, layers, experts, err)
188                                     : cache_.open((int64_t) selected.size(), layers, experts,
189                                                   (int64_t) lay.max_blob, err);
190    if (!cache_ok) { err = "CUDA" + std::to_string(device) + " experts: " + err; close(); return false; }
191    for (const auto& pair : selected) {
192        const int32_t slot = cache_.admit(pair.first, pair.second);
193        const uint8_t* blob = source.blob(pair.first, pair.second);
194        if (slot < 0 || !blob || !cache_.fill_slot_blocking(slot, blob, err, (int64_t) lay.blob_bytes(pair.first))) {
195            err = "CUDA" + std::to_string(device) + " experts: " +
196                  (err.empty() ? "cache fill failed" : err);
197            close(); return false;
198        }
199    }
200    const auto& first = selected.front();
201    if (!cache_.verify_slot(cache_.slot_of(first.first, first.second), source.blob(first.first, first.second),
202                            err, (int64_t) lay.blob_bytes(first.first))) {
203        err = "CUDA" + std::to_string(device) + " experts: " + err;
204        close(); return false;
205    }
206
207    const size_t scratch = std::max<size_t>(
208        (size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, FF),
209        strata::kernels::native_expert_scratch_bytes(CAP, FF));
210    const size_t meta_bytes = sizeof(RemoteMeta) + (remote_opt_ ? remote_opt_->metadata_bytes() : 0);
211    const bool allocated =
212        check(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err, device) &&
213        check(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "input staging", err, device) &&
214        check(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "result staging", err, device) &&
215        check(cudaHostAlloc(&h_meta_, meta_bytes, cudaHostAllocPortable), "metadata staging", err, device) &&
216        check(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err, device) &&
217        check(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err, device) &&
218        check(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activation", err, device) &&
219        check(cudaMalloc((void**) &d_scales_, (size_t) CAP * (H / 32) * sizeof(float)), "activation scales", err, device) &&
220        check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) &&
221        check(cudaMalloc(&d_meta_, meta_bytes), "group metadata", err, device) &&
222        (!strata::kernels::cpu::hadamard_spec().any() ||
223         check(cudaMalloc((void**) &d_xr_, (size_t) CAP * H * sizeof(float)), "rotated input", err, device));
224    if (!allocated) { close(); return false; }
225    if (!check(cudaStreamCreateWithFlags(&read_stream_, cudaStreamNonBlocking), "cache read stream", err, device)) {
226        close();
227        return false;
228    }
229    if (strata::kernels::cpu::hadamard_spec().any()) {   // APR: this device's copies of the sign vectors
230        d_sx_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) H), (int) H);
231        d_sh_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) FF), (int) FF);
232    }
233    // Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers
234    // directly - two copies fewer per layer, each of which is a PCIe round trip.  STRATA_REMOTE_ZEROCOPY=0 copies.
235    const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY");
236    zero_copy_ = !(zc && zc[0] == '0') &&
237                 cudaHostGetDevicePointer((void**) &z_x_, h_x_, 0) == cudaSuccess &&
238                 cudaHostGetDevicePointer((void**) &z_out_, h_out_, 0) == cudaSuccess;
239    cudaGetLastError();
240    auto* meta = (RemoteMeta*) d_meta_;
241    d_ptr_ = meta->ptr;
242    d_start_ = meta->start;
243    d_dst_ = meta->dst;
244    d_tok_ = meta->tok;
245    d_count_ = &meta->count;
246    owned_.resize(CAP);
247    layers_present_.assign((size_t) layers, 0);
248    group_of_.resize(CAP);
249    group_id_.reserve(CAP);
250    ptr_.reserve(CAP);
251    start_.reserve(CAP + 1);
252    dst_.reserve(CAP);
253    tok_.reserve(CAP);
254    original_row_.reserve(CAP);
255    computed_ = 0;
256    launched_layers_ = 0;
257    returned_bytes_ = full_row_bytes_ = 0;
258    for (const auto& pair : selected) {
259        layers_present_[(size_t) pair.first] = 1;
260        claimed[(size_t) pair.first * (size_t) experts + (size_t) pair.second] = 1;
261    }
262    return true;
263}
264
265bool RemoteExperts::begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok,
266                          int64_t k, const int32_t* kind, const int32_t* primary_res,
267                          std::string& err) {
268    // cumulative host time in here (staging and launches), reported per request by the driver
269    struct Timer { double& acc; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
270        ~Timer() { acc += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); } } timer{ms_begin_};
271    const int64_t n = n_tok * k;
272    if (n <= 0 || n > CAP || n_tok > strata::kernels::kWindowMaxT || k != (int) strata::core::kCompiledGeometry.n_expert_used || layer < 0 ||
273        (size_t) layer >= layers_present_.size() || device_ < 0) {
274        err = "CUDA" + std::to_string(device_) + " experts: invalid layer, routing width or window size";
275        return false;
276    }
277    std::fill(owned_.begin(), owned_.begin() + n, 0);
278    group_id_.clear(); ptr_.clear(); start_.clear(); dst_.clear(); tok_.clear(); original_row_.clear();
279    if (!layers_present_[(size_t) layer]) return true;
280    std::fill(group_of_.begin(), group_of_.begin() + n, -1);
281    for (int64_t i = 0; i < n; ++i) {
282        const int32_t e = ids[i];
283        if ((kind && kind[i] != -1) || e < 0 || e >= n_expert_ ||
284            (primary_res && primary_res[(size_t) layer * (size_t) n_expert_ + (size_t) e] >= 0)) continue;
285        const int32_t slot = cache_.slot_of(layer, e);
286        if (slot < 0) continue;
287        owned_[(size_t) i] = 1;
288        int32_t group = -1;
289        for (size_t g = 0; g < group_id_.size(); ++g)
290            if (group_id_[g] == e) { group = (int32_t) g; break; }
291        if (group < 0) {
292            group = (int32_t) group_id_.size();
293            group_id_.push_back(e);
294            ptr_.push_back((unsigned long long) cache_.device_slot(slot));
295        }
296        group_of_[(size_t) i] = group;
297        ++computed_;
298    }
299    if (group_id_.empty()) return true;
300    for (size_t g = 0; g < group_id_.size(); ++g) {
301        start_.push_back((int32_t) dst_.size());
302        for (int64_t i = 0; i < n; ++i) if (group_of_[(size_t) i] == (int32_t) g) {
303            // The grouped kernels read the activation from `tok`, so their
304            // output row can instead be packed densely for the USB4 return.
305            original_row_.push_back((int32_t) i);
306            dst_.push_back((int32_t) dst_.size());
307            tok_.push_back((int32_t) (i / k));
308        }
309    }
310    start_.push_back((int32_t) dst_.size());
311    // Private pinned buffers survive until this GPU has consumed them. The CPU
312    // pool can write other output rows without a cross-device race.
313    std::memcpy(h_x_, x, (size_t) n_tok * H * sizeof(float));
314    auto* meta = (RemoteMeta*) h_meta_;
315    std::memcpy(meta->ptr, ptr_.data(), ptr_.size() * sizeof(ptr_[0]));
316    std::memcpy(meta->start, start_.data(), start_.size() * sizeof(start_[0]));
317    std::memcpy(meta->dst, dst_.data(), dst_.size() * sizeof(dst_[0]));
318    std::memcpy(meta->tok, tok_.data(), tok_.size() * sizeof(tok_[0]));
319    meta->count = (int32_t) group_id_.size();
320    const bool reduce = remote_opt_ && remote_opt_->active();
321    if (reduce) remote_opt_->prepare(*this, meta + 1);
322    DeviceScope scope(device_);
323    if (!scope.ok) { err = scope.error(device_); return false; }
324    groups_ = (int32_t) group_id_.size();
325    const cudaStream_t s = stream_;
326    const bool staged =
327        (zero_copy_ || check(cudaMemcpyAsync(d_x_, h_x_, (size_t) n_tok * H * sizeof(float), cudaMemcpyHostToDevice, s), "copy input", err, device_)) &&
328        check(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(RemoteMeta) + (reduce ? remote_opt_->metadata_bytes() : 0),
329                              cudaMemcpyHostToDevice, s), "copy group metadata", err, device_);
330    if (!staged) return false;
331    const auto& lay = strata::kernels::cpu::expert_layout();
332    if (lay.native) {
333        const auto& fmt = lay.fmt[(size_t) layer];
334        const float* xe = zero_copy_ ? z_x_ : d_x_;
335        if (fmt.had_gu) {   // APR: Hadamard-folded gate/up take H (s * x)
336            strata::kernels::hadamard_rows(xe, d_xr_, n_tok, H, fmt.had_block, d_sx_, s);
337            xe = d_xr_;
338        }
339        strata::kernels::quantize_q8_1_rows(xe, n_tok, H, d_q8_, s);
340        auto L = strata::kernels::native_expert_layout(fmt.gu_type, fmt.d_type, fmt.n_embd, fmt.n_ff);
341        if (fmt.had_d) { L.had_block = fmt.had_block; L.d_signs = d_sh_; }
342        strata::kernels::native_expert_grouped(L, d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
343                                               groups_, (int64_t) dst_.size(), d_q8_, d_scratch_, zero_copy_ && !reduce ? z_out_ : d_out_, s);
344    } else {
345        strata::kernels::quantize_q8_0_scaled(zero_copy_ ? z_x_ : d_x_, d_q8_, d_scales_, n_tok * H, s);
346        strata::kernels::moe_grouped_s2_window(d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
347                                               groups_, (int64_t) dst_.size(), d_q8_, d_scales_, d_scratch_, zero_copy_ && !reduce ? z_out_ : d_out_, s,
348                                               (int) n_tok);
349    }
350    const uint64_t compact_bytes = (uint64_t) (reduce ? n_tok : dst_.size()) * H * sizeof(float);
351    if (reduce) {
352        if (!remote_opt_->reduce(*this, (RemoteMeta*) d_meta_ + 1, err)) return false;
353    } else if (!zero_copy_ && !check(cudaMemcpyAsync(h_out_, d_out_, (size_t) compact_bytes, cudaMemcpyDeviceToHost, s),
354               "copy results", err, device_)) return false;
355    ++launched_layers_;
356    returned_bytes_ += compact_bytes;
357    full_row_bytes_ += (uint64_t) n * H * sizeof(float);
358    return true;
359}
360
361bool RemoteExperts::finish(float* out, std::string& err) {
362    if (group_id_.empty()) return true;
363    DeviceScope scope(device_);
364    if (!scope.ok) { err = scope.error(device_); return false; }
365    const auto w0 = std::chrono::steady_clock::now();
366    // Spin on the stream like PeerExperts::finish instead of the blocking sync: the layer waits for this helper
367    // on the CPU pool's critical path, and a blocking sync's wake-up costs more than the helper's small batch
368    // takes - on HIP especially, where the CUDA branch's cudaInitDevice(ScheduleSpin) does not exist and the
369    // device keeps its default policy.  STRATA_REMOTE_SPIN=0 keeps the blocking sync (the same switch the CUDA
370    // branch reads).
371#if defined(STRATA_USE_HIP)   // HIP only: the CUDA branch's cudaInitDevice(ScheduleSpin) already makes the sync spin
372    static const bool spin = [] {
373        const char* v = std::getenv("STRATA_REMOTE_SPIN");
374        return !(v != nullptr && v[0] == '0');
375    }();
376    if (spin) {
377        cudaError_t e;
378        while ((e = cudaStreamQuery(stream_)) == cudaErrorNotReady) {
379        }
380        if (!check(e, "finish", err, device_)) return false;
381    } else if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) {
382        return false;
383    }
384#else
385    if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) return false;
386#endif
387    ms_wait_ += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - w0).count();
388    if (remote_opt_ && remote_opt_->active()) { remote_opt_->accumulate(*this); return true; }
389    for (size_t i = 0; i < original_row_.size(); ++i)
390        std::memcpy(out + (size_t) original_row_[i] * H, h_out_ + i * H, (size_t) H * sizeof(float));
391    return true;
392}
393
394bool RemoteExperts::copy_cached_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst,
395                                      size_t n, uint8_t* hit, std::string& err) {
396    std::fill(hit, hit + n, 0);
397    if (device_ < 0 || read_stream_ == nullptr || n == 0) return true;
398    const auto& lay = strata::kernels::cpu::expert_layout();
399    DeviceScope scope(device_);
400    if (!scope.ok) { err = scope.error(device_); return false; }
401    std::lock_guard<std::mutex> lock(read_mu_);
402    bool queued = false;
403    for (size_t i = 0; i < n; ++i) {
404        if (dst[i] == nullptr) continue;
405        const int32_t slot = cache_.slot_of(layers[i], experts[i]);
406        if (slot < 0) continue;
407        const size_t bytes = (size_t) lay.blob_bytes(layers[i]);
408        if (!check(cudaMemcpyAsync(dst[i], cache_.device_slot(slot), bytes, cudaMemcpyDeviceToHost, read_stream_),
409                   "cache read", err, device_)) {
410            // Nothing may still be writing a caller's buffer when this returns.  If the drain succeeds, the
411            // hits queued before the failure are complete and the caller may keep them; if it does not,
412            // forget every hit and let the caller refill all of them from its fallback.
413            if (cudaStreamSynchronize(read_stream_) != cudaSuccess) std::fill(hit, hit + n, 0);
414            return false;
415        }
416        hit[i] = 1;
417        queued = true;
418    }
419    if (queued && !check(cudaStreamSynchronize(read_stream_), "cache read wait", err, device_)) {
420        std::fill(hit, hit + n, 0);   // a failed wait means no copied buffer may be trusted
421        return false;
422    }
423    return true;
424}
425
426bool RemotePrefillSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
427    if (dst != nullptr && from_helper(layer, expert)) {
428        const int32_t l = (int32_t) layer, e = (int32_t) expert;
429        uint8_t* d = dst;
430        std::string err;
431        for (RemoteExperts* h : helpers_) {
432            uint8_t got = 0;
433            const bool ok = h->copy_cached_blobs(&l, &e, &d, 1, &got, err);
434            if (got) {
435                helper_blobs_.fetch_add(1, std::memory_order_relaxed);
436                helper_bytes_.fetch_add(strata::kernels::cpu::expert_layout().blob_bytes(layer),
437                                        std::memory_order_relaxed);
438                return true;
439            }
440            if (!ok) break;
441        }
442        warn(err);
443    }
444    return fallback_.copy_blob(layer, expert, dst);
445}
446
447bool RemotePrefillSource::copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) {
448    if (helpers_.empty() || n == 0) return fallback_.copy_blobs(layers, experts, dst, n);
449    thread_local std::vector<int32_t> hl, he;
450    thread_local std::vector<uint8_t*> hd;
451    thread_local std::vector<size_t> idx;
452    thread_local std::vector<uint8_t> got;
453    thread_local std::vector<uint8_t> served;
454    thread_local std::vector<int32_t> ml, me;
455    thread_local std::vector<uint8_t*> md;
456    thread_local std::vector<int> which;
457    which.assign(n, -1);
458    served.assign(n, 0);
459    for (size_t i = 0; i < n; ++i) {
460        if (dst[i] == nullptr) continue;
461        for (size_t k = 0; k < helpers_.size(); ++k)
462            if (helpers_[k]->holds(layers[i], experts[i])) { which[i] = (int) k; break; }
463    }
464    // One stream batch per helper, so several hits pay one wait; the misses go to the file source in one
465    // call, which keeps its own batched-read merging for them.
466    uint64_t blobs = 0, bytes = 0;
467    const auto& lay = strata::kernels::cpu::expert_layout();
468    for (size_t k = 0; k < helpers_.size(); ++k) {
469        hl.clear(); he.clear(); hd.clear(); idx.clear();
470        for (size_t i = 0; i < n; ++i)
471            if (which[i] == (int) k) {
472                hl.push_back(layers[i]); he.push_back(experts[i]); hd.push_back(dst[i]); idx.push_back(i);
473            }
474        if (hl.empty()) continue;
475        got.assign(hl.size(), 0);
476        std::string err;
477        if (!helpers_[k]->copy_cached_blobs(hl.data(), he.data(), hd.data(), hl.size(), got.data(), err)) warn(err);
478        for (size_t j = 0; j < got.size(); ++j)
479            if (got[j]) {
480                served[idx[j]] = 1;
481                ++blobs;
482                bytes += lay.blob_bytes(hl[j]);
483            }
484    }
485    if (blobs != 0) {
486        helper_blobs_.fetch_add(blobs, std::memory_order_relaxed);
487        helper_bytes_.fetch_add(bytes, std::memory_order_relaxed);
488    }
489    ml.clear(); me.clear(); md.clear();
490    for (size_t i = 0; i < n; ++i)
491        if (!served[i]) { ml.push_back(layers[i]); me.push_back(experts[i]); md.push_back(dst[i]); }
492    if (ml.empty()) return true;
493    return fallback_.copy_blobs(ml.data(), me.data(), md.data(), ml.size());
494}
495
496void RemotePrefillSource::warn(const std::string& err) {
497    if (err.empty() || warned_.exchange(true)) return;
498    std::fprintf(stderr, "prefill: a helper cache read failed (%s); the file source fills that blob instead\n",
499                 err.c_str());
500}
501} // namespace strata::core