okami.mom/strata

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

waveringanareject unsupported latent experts in the peer cache7961f0837

main
22.9 KiB475 linesraw
1// src/core/peer_experts.cpp - see include/strata/core/peer_experts.hpp.
2#include "strata/core/peer_experts.hpp"
3
4#include "strata/core/device.hpp"   // primary_device() (STRATA_PRIMARY_DEVICE)
5#include "strata/kernels/cpu/expert_layout.hpp"
6#include "strata/kernels/cpu/hadamard.hpp"
7#include "strata/kernels/elementwise.hpp"
8#include "strata/kernels/iq_kernels.hpp"
9#include "strata/kernels/quantize_act.hpp"
10#include "strata/kernels/s2_expert_grouped.hpp"
11#include "strata/kernels/window_limits.hpp"
12
13#include <algorithm>
14#include <chrono>
15#include <cstdio>
16#include <cstring>
17#include <cstdlib>
18#include <stdexcept>
19#include <vector>
20
21namespace strata::core {
22
23static bool g_peer_portable = false;
24void set_peer_portable(bool on) { g_peer_portable = on; }
25bool peer_portable() { return g_peer_portable; }
26
27namespace {
28
29constexpr int64_t H = strata::kernels::cpu::H;
30constexpr int64_t CAP = strata::kernels::kWindowMaxT * 10;   // entries per layer: a window's rows x top-10
31
32struct Meta {                           // one block, uploaded with one copy per layer
33    unsigned long long ptr[CAP];
34    int32_t start[CAP + 1];
35    int32_t dst[CAP];
36    int32_t tok[CAP];
37    int32_t count[4];                   // [0] groups, [1] entries
38    int32_t out_row[CAP];               // multi-GPU: compact row -> entry row in the host `out`
39};
40
41/// Switches the calling thread to `dev` and back.  The engine's own thread lives on device 0.
42struct On {
43    int prev = 0;
44    explicit On(int dev) { cudaGetDevice(&prev); if (prev != dev) cudaSetDevice(dev); }
45    ~On() { int cur = 0; cudaGetDevice(&cur); if (cur != prev) cudaSetDevice(prev); }
46};
47
48/// #2666: `cudaDeviceCanAccessPeer` said yes and `cudaDeviceEnablePeerAccess` succeeded, and on a pair of GPUs behind a host bridge
49/// (2x RTX A4000, "PHB" in nvidia-smi topo) `cudaMemcpyPeerAsync` then returned success having moved nothing: the peer's input rows
50/// were zeros and the rows it sent back never arrived, so the first prompt's MoE output was garbage and the logits NaN.  Without
51/// peer access enabled the same copies are right (the driver stages them).  So the pair is asked once, with a small copy each way,
52/// whether the direct path really carries data.  true = both ways exact (or nothing could be tested: the old trust is kept).
53bool p2p_copies_data(int device) {
54    constexpr size_t kN = 1 << 14;   // floats
55    std::vector<float> h(kN), back(kN);
56    for (size_t i = 0; i < kN; ++i) h[i] = 1.0f + (float) ((i * 2654435761u) % 4093u);
57    float* d[2] = {nullptr, nullptr};
58    const int dev[2] = {0, device};
59    bool ok = true, tested = true;
60    for (int k = 0; k < 2 && tested; ++k) {
61        On on(dev[k]);
62        if (cudaMalloc((void**) &d[k], kN * 4) != cudaSuccess) { cudaGetLastError(); tested = false; }
63    }
64    for (int dir = 0; dir < 2 && tested && ok; ++dir) {   // 0: device 0 -> peer, 1: peer -> device 0
65        const int from = dir == 0 ? 0 : 1, to = 1 - from;
66        {
67            On on(dev[from]);
68            if (cudaMemcpy(d[from], h.data(), kN * 4, cudaMemcpyHostToDevice) != cudaSuccess) { tested = false; break; }
69        }
70        {
71            On on(dev[to]);
72            if (cudaMemset(d[to], 0, kN * 4) != cudaSuccess) { tested = false; break; }
73        }
74        if (cudaMemcpyPeer(d[to], dev[to], d[from], dev[from], kN * 4) != cudaSuccess) { tested = false; break; }
75        {
76            On on(dev[to]);
77            if (cudaMemcpy(back.data(), d[to], kN * 4, cudaMemcpyDeviceToHost) != cudaSuccess) { tested = false; break; }
78        }
79        ok = std::memcmp(back.data(), h.data(), kN * 4) == 0;
80    }
81    for (int k = 0; k < 2; ++k)
82        if (d[k] != nullptr) { On on(dev[k]); cudaFree(d[k]); }
83    if (!tested) { cudaGetLastError(); return true; }
84    return ok;
85}
86
87bool ck(cudaError_t e, const char* what, std::string& err) {
88    if (e == cudaSuccess) return true;
89    err = std::string("peer experts: ") + what + ": " + cudaGetErrorString(e);
90    return false;
91}
92
93}  // namespace
94
95PeerExperts::~PeerExperts() { close(); }
96
97void PeerExperts::close() {
98    if (device_ < 0) return;
99    {
100        On on(device_);
101        if (stream_) cudaStreamSynchronize(stream_);
102        if (refill_) cudaStreamSynchronize(refill_);
103        cache_.close();
104        if (d_x_) cudaFree(d_x_);
105        if (d_out_) cudaFree(d_out_);
106        if (d_meta_) cudaFree(d_meta_);
107        if (d_q8_) cudaFree(d_q8_);
108        if (d_scratch_) cudaFree(d_scratch_);
109        if (h_x_) cudaFreeHost(h_x_);
110        if (h_out_) cudaFreeHost(h_out_);
111        if (h_meta_) cudaFreeHost(h_meta_);
112        if (d_gate_vals_) cudaFree(d_gate_vals_);
113        if (h_gate_) cudaFreeHost((void*) h_gate_);
114        if (refill_ev_) cudaEventDestroy(refill_ev_);
115        if (stream_) cudaStreamDestroy(stream_);
116        if (refill_) cudaStreamDestroy(refill_);
117    }
118    d_x_ = d_out_ = h_x_ = h_out_ = nullptr;
119    d_meta_ = h_meta_ = d_scratch_ = nullptr;
120    d_q8_ = nullptr;
121    d_sx_ = d_sh_ = nullptr;
122    d_gate_vals_ = nullptr;
123    h_gate_ = nullptr;
124    stream_ = refill_ = nullptr;
125    refill_ev_ = nullptr;
126    device_ = -1;
127}
128
129bool PeerExperts::open(int device, const std::vector<std::pair<int32_t, int32_t>>& ranked, const ExpertCache& primary,
130                       ExpertSource& src, int64_t n_layers, int64_t n_expert, int reserve_mib, int64_t max_slots,
131                       std::string& err) {
132    close();
133    int count = 0;
134    if (!ck(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err)) return false;
135    if (device < 1 || device >= count) {
136        err = "peer experts: CUDA device " + std::to_string(device) + " is not visible (" + std::to_string(count) +
137              " devices; set CUDA_VISIBLE_DEVICES)";
138        return false;
139    }
140    const auto& lay = strata::kernels::cpu::expert_layout();
141    if (lay.native && std::any_of(lay.fmt.begin(), lay.fmt.end(), [](const auto& f) { return f.n_embd != H; })) {
142        err = "peer experts: latent projections are not supported; use --layer-split";
143        return false;
144    }
145    n_layers_ = n_layers;
146    n_expert_ = n_expert;
147    src_ = &src;
148    res_.assign((size_t) (n_layers * n_expert), kNotResident);
149    {   // direct access both ways (NVLink or another P2P path): the prompt path copies activations and results over it
150        int a = 0, b = 0;
151        cudaDeviceCanAccessPeer(&a, primary_device(), device);
152        cudaDeviceCanAccessPeer(&b, device, primary_device());
153        if (const char* np = std::getenv("STRATA_PEER_NO_P2P"); np != nullptr && std::atoi(np) != 0) a = 0;   // test knob: pretend the pair has no P2P
154        p2p_ = a && b;
155        if (p2p_) {
156            On on0(primary_device());
157            cudaError_t e0 = cudaDeviceEnablePeerAccess(device, 0);
158            if (e0 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e0 = cudaSuccess; }
159            On on1(device);
160            cudaError_t e1 = cudaDeviceEnablePeerAccess(primary_device(), 0);
161            if (e1 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e1 = cudaSuccess; }
162            p2p_ = e0 == cudaSuccess && e1 == cudaSuccess;
163            // recommend, never force: the direct path is used only if a test copy each way arrives exact (#2666)
164            if (p2p_ && !p2p_copies_data(device)) {
165                std::fprintf(stderr, "strata: peer GPU %d: peer access is enabled but a test copy between the two GPUs arrived wrong "
166                                     "(a host bridge between them, no real P2P): the prompt path takes the host route instead "
167                                     "(STRATA_PEER_NO_P2P=1 does that by hand)\n", device);
168                { On q0(0); cudaDeviceDisablePeerAccess(device); cudaGetLastError(); }
169                { On q1(device); cudaDeviceDisablePeerAccess(0); cudaGetLastError(); }
170                p2p_ = false;
171            }
172        }
173    }
174    On on(device);
175    device_ = device;
176    // scratch first, so the slots take what is really left
177    int64_t ff = strata::kernels::cpu::FF;
178    if (lay.native)
179        for (const auto& f : lay.fmt) ff = std::max<int64_t>(ff, f.n_ff);
180    const size_t scratch = std::max<size_t>((size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, ff),
181                                            strata::kernels::native_expert_scratch_bytes(CAP, ff));
182    const bool alloc_ok =
183        ck(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err) &&
184        ck(cudaStreamCreateWithFlags(&refill_, cudaStreamNonBlocking), "refill stream", err) &&
185        ck(cudaEventCreateWithFlags(&refill_ev_, cudaEventDisableTiming), "event", err) &&
186        ck(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "input staging", err) &&
187        ck(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "result staging", err) &&
188        ck(cudaHostAlloc(&h_meta_, sizeof(Meta), cudaHostAllocPortable | cudaHostAllocMapped), "plan staging", err) &&
189        ck(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err) &&
190        ck(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err) &&
191        ck(cudaMalloc(&d_meta_, sizeof(Meta)), "plan", err) &&
192        ck(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activations", err) &&
193        ck(cudaMalloc(&d_scratch_, scratch), "scratch", err);
194    if (!alloc_ok) { close(); return false; }
195    if (strata::kernels::cpu::hadamard_spec().any()) {   // APR: this device's copies of the sign vectors
196        d_sx_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) H), (int) H);
197        d_sh_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) ff), (int) ff);
198    }
199
200    // the pairs the primary does not hold, in rank order, as many as fit
201    size_t free_b = 0, total_b = 0;
202    if (!ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo", err)) { close(); return false; }
203    const uint64_t reserve = (uint64_t) std::max(reserve_mib, 128) << 20;
204    const uint64_t budget = free_b > reserve ? free_b - reserve : 0;
205    std::vector<std::pair<int32_t, int32_t>> pick;
206    std::vector<int64_t> sizes;
207    uint64_t used = 0;
208    for (const auto& pr : ranked) {
209        if (primary.slot_of(pr.first, pr.second) >= 0) continue;
210        const uint64_t b = lay.blob_bytes(pr.first);
211        const uint64_t b256 = lay.native ? (b + 255) / 256 * 256 : lay.max_blob;
212        if (used + b256 > budget) break;
213        if (max_slots > 0 && (int64_t) pick.size() >= max_slots) break;
214        used += b256;
215        pick.push_back(pr);
216        sizes.push_back((int64_t) b);
217    }
218    if (pick.empty()) { err = "peer experts: no room or no expert left for the peer"; close(); return false; }
219    const bool opened = lay.native ? cache_.open_sized(sizes, n_layers, n_expert, err)
220                                   : cache_.open((int64_t) pick.size(), n_layers, n_expert, (int64_t) lay.max_blob, err);
221    if (!opened) { err = "peer experts: " + err; close(); return false; }
222    // open() zeroes the arena with cudaMemset on the legacy stream, which is not ordered against the non-blocking
223    // refill stream: wait for it, or the zeroing can land on top of the fills
224    if (!ck(cudaDeviceSynchronize(), "arena zeroing", err)) { close(); return false; }
225    // mapped reads: advise the next kAhead pairs so their reads overlap
226    constexpr size_t kAhead = 256;
227    const bool advise = src.advise_pairs(pick.data(), (int64_t) std::min(kAhead, pick.size()));
228    for (size_t i = 0; i < pick.size(); ++i) {
229        const auto& pr = pick[i];
230        if (advise && i + kAhead < pick.size()) (void) src.advise_pairs(&pick[i + kAhead], 1);
231        const int32_t slot = cache_.admit(pr.first, pr.second);
232        const uint8_t* b = src.blob(pr.first, pr.second);
233        if (slot < 0 || b == nullptr || !cache_.fill_slot(slot, b, refill_, err, (int64_t) lay.blob_bytes(pr.first))) {
234            err = "peer experts: fill failed: " + err;
235            close();
236            return false;
237        }
238        src.note_async_read(b, refill_);   // #1237
239        res_[(size_t) (pr.first * n_expert + pr.second)] = slot;
240    }
241    if (!ck(cudaStreamSynchronize(refill_), "fill", err)) { close(); return false; }
242    const auto& f0 = pick.front();
243    if (!cache_.verify_slot(res_[(size_t) (f0.first * n_expert + f0.second)], src.blob(f0.first, f0.second), err,
244                            (int64_t) lay.blob_bytes(f0.first))) {
245        err = "peer experts: " + err;
246        close();
247        return false;
248    }
249    resident_ = (int64_t) pick.size();
250    return true;
251}
252
253bool PeerExperts::direct_mode() {
254    static const bool v = [] { const char* e = std::getenv("STRATA_PEER_DIRECT"); return e == nullptr || std::atoi(e) != 0; }();
255    return v;
256}
257
258bool PeerExperts::launch(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, int64_t k,
259                         const int32_t* kind, std::string& err, float* out) {
260    const bool direct = direct_mode() && out != nullptr;
261    struct Timer {
262        double& acc;
263        std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
264        ~Timer() { acc += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); }
265    } timer{ms_launch};
266    launched_direct_ = false;
267    launched_rows_ = 0;
268    row_of_.clear();
269    const int64_t n = n_tok * k;
270    if (n > CAP) { err = "peer experts: window too large"; return false; }
271    Meta& m = *(Meta*) h_meta_;
272    int groups = 0, rows = 0;
273    // distinct experts in routing order; each one's entries become compact rows
274    for (int64_t i = 0; i < n; ++i) {
275        if (kind[i] != 2) continue;
276        bool seen = false;
277        for (int64_t j = 0; j < i; ++j)
278            if (kind[j] == 2 && ids[j] == ids[i]) { seen = true; break; }
279        if (seen) continue;
280        const int32_t slot = res_[(size_t) (layer * n_expert_ + ids[i])];
281        if (slot < 0) { err = "peer experts: an entry was planned for the peer but is not resident"; return false; }
282        m.ptr[groups] = (unsigned long long) cache_.device_slot(slot);
283        m.start[groups] = rows;
284        for (int64_t j = i; j < n; ++j)
285            if (kind[j] == 2 && ids[j] == ids[i]) {
286                m.dst[rows] = rows;
287                m.tok[rows] = (int32_t) (j / k);
288                m.out_row[rows] = (int32_t) j;
289                row_of_.push_back((int32_t) j);
290                ++rows;
291            }
292        ++groups;
293        ++experts_;
294    }
295    if (groups == 0) return true;
296    m.start[groups] = rows;
297    m.count[0] = groups;
298    m.count[1] = rows;
299    entries_ += rows;
300    launched_rows_ = rows;
301    // direct: x is the verifier's pinned (portable) doorbell row block - copied from where it is
302    if (!direct) std::memcpy(h_x_, x, (size_t) (n_tok * H) * sizeof(float));
303    On on(device_);
304    const cudaStream_t s = stream_;
305    if (!ck(cudaMemcpyAsync(d_x_, direct ? x : h_x_, (size_t) (n_tok * H) * sizeof(float), cudaMemcpyHostToDevice, s), "input", err) ||
306        !ck(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(Meta), cudaMemcpyHostToDevice, s), "plan", err))
307        return false;
308    Meta* dm = (Meta*) d_meta_;
309    const auto& lay = strata::kernels::cpu::expert_layout();
310    if (lay.native) {
311        const auto& f = lay.fmt[(size_t) layer];
312        // APR: Hadamard-folded gate/up take H (s * x); d_x_ is this device's private copy, rotated in place
313        if (f.had_gu) strata::kernels::hadamard_rows(d_x_, d_x_, n_tok, H, f.had_block, d_sx_, s);
314        strata::kernels::quantize_q8_1_rows(d_x_, n_tok, H, d_q8_, s);
315        auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);
316        if (f.had_d) { L.had_block = f.had_block; L.d_signs = d_sh_; }
317        strata::kernels::native_expert_grouped(L, dm->ptr, dm->start, dm->count, dm->dst, dm->tok, groups, rows, d_q8_,
318                                               d_scratch_, d_out_, s);
319    } else {
320        err = "peer experts: only native packs are supported";
321        return false;
322    }
323    if (direct) {   // the rows straight into the host `out` (zero-copy, coalesced float4 writes)
324        try {
325            strata::kernels::scatter_rows_f32(d_out_, out, dm->out_row, rows, H, s);
326        } catch (const std::exception& e) { err = std::string("peer experts: scatter: ") + e.what(); return false; }
327        launched_direct_ = true;
328        return true;
329    }
330    return ck(cudaMemcpyAsync(h_out_, d_out_, (size_t) rows * H * sizeof(float), cudaMemcpyDeviceToHost, s),
331              "results", err);
332}
333
334bool PeerExperts::finish(float* out, std::string& err) {
335    if (launched_rows_ == 0) return true;
336    ++launches;
337    const auto t0 = std::chrono::steady_clock::now();
338    {
339        On on(device_);
340        // spin on the stream (a blocking sync would sleep the pool thread and wake it late)
341        cudaError_t e;
342        while ((e = cudaStreamQuery(stream_)) == cudaErrorNotReady) {
343        }
344        if (!ck(e, "finish", err)) return false;
345    }
346    ms_wait += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
347    if (launched_direct_) { launched_rows_ = 0; return true; }
348    for (size_t r = 0; r < row_of_.size(); ++r)
349        std::memcpy(out + (size_t) row_of_[r] * H, h_out_ + r * H, (size_t) H * sizeof(float));
350    launched_rows_ = 0;
351    return true;
352}
353
354bool PeerExperts::adapt(const float* usage, const int32_t* res0, int max_swaps, std::string& err) {
355    if (!pending_.empty() || max_swaps <= 0) return true;
356    const auto& lay = strata::kernels::cpu::expert_layout();
357    struct Swap { float gain; int32_t layer, in, out; };
358    std::vector<Swap> swaps;
359    std::vector<std::pair<float, int32_t>> cand, vict;
360    for (int64_t l = 0; l < n_layers_; ++l) {
361        cand.clear();
362        vict.clear();
363        const float* u = usage + l * n_expert_;
364        const int32_t* r0 = res0 + l * n_expert_;
365        const int32_t* r1 = res_.data() + l * n_expert_;
366        for (int32_t e = 0; e < (int32_t) n_expert_; ++e) {
367            if (r1[e] >= 0) vict.emplace_back(u[e], e);
368            else if (r0[e] < 0 && u[e] >= 2.0f) cand.emplace_back(u[e], e);
369        }
370        if (cand.empty() || vict.empty()) continue;
371        std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; });
372        const size_t nc = std::min(cand.size(), vict.size());
373        std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(),
374                          [](auto& a, auto& b) { return a.first < b.first; });
375        for (size_t i = 0; i < nc; ++i) {
376            if (cand[i].first < vict[i].first + 1.5f) break;
377            swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second});
378        }
379    }
380    if (swaps.empty()) return true;
381    std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });
382    if ((int) swaps.size() > max_swaps) swaps.resize((size_t) max_swaps);
383    const bool gated = gate_landed_ != nullptr;
384    if (gated) {   // the copies go in layer order and each layer's landing raises the gate's counter
385        std::stable_sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.layer < b.layer; });
386        gate_landed_->store(-1, std::memory_order_release);
387        if (h_gate_ != nullptr) *h_gate_ = -1;
388        gate_has_->assign((size_t) n_layers_, 0);
389        *gate_last_ = -1;
390    }
391    On on(device_);
392    int32_t issued_layer = -1;   // the layer whose copies are on the stream and not yet ticked
393    auto tick = [&](int32_t layer) -> bool {
394        if ((h_gate_ != nullptr
395                 ? cudaMemcpyAsync((void*) h_gate_, d_gate_vals_ + layer, 4, cudaMemcpyDeviceToHost, refill_)
396                 : cudaLaunchHostFunc(refill_, [](void* p) {
397                auto* t = (Tick*) p;
398                int32_t cur = t->counter->load(std::memory_order_relaxed);
399                while (cur < t->layer && !t->counter->compare_exchange_weak(cur, t->layer, std::memory_order_release)) {}
400            }, &ticks_[(size_t) layer])) == cudaSuccess)
401            return true;
402        (void) cudaGetLastError();
403        cudaStreamSynchronize(refill_);   // no callback: wait here, the gate opens at once
404        gate_landed_->store((int32_t) n_layers_, std::memory_order_release);
405        return false;
406    };
407    for (const Swap& s : swaps) {
408        const size_t in = (size_t) (s.layer * n_expert_ + s.in), out = (size_t) (s.layer * n_expert_ + s.out);
409        const int32_t slot = res_[out];
410        const uint8_t* b = src_->blob(s.layer, s.in);
411        if (slot < 0 || b == nullptr) continue;
412        if (gated && issued_layer >= 0 && issued_layer != s.layer) tick(issued_layer);
413        if (!ck(cudaMemcpyAsync(cache_.device_slot(slot), b, (size_t) lay.blob_bytes(s.layer), cudaMemcpyHostToDevice,
414                                refill_), "refill", err))
415            return false;
416        if (gated) {
417            (*gate_has_)[(size_t) s.layer] = 1;
418            *gate_last_ = std::max(*gate_last_, s.layer);
419            issued_layer = s.layer;
420        }
421        res_[out] = kNotResident;              // evicted now: the CPU computes it meanwhile
422        pending_.emplace_back((int32_t) in, slot);
423        ++swaps_;
424    }
425    if (gated && issued_layer >= 0) tick(issued_layer);
426    if (!ck(cudaEventRecord(refill_ev_, refill_), "refill event", err)) return false;
427    // #2188: hand the copies and their landing signals to the GPU now (WDDM batches a stream's work until a driver
428    // call flushes it, and the verify window only spins on the pinned int; Linux submits at once: a no-op)
429    if (gated && h_gate_ != nullptr && issued_layer >= 0) (void) cudaStreamQuery(refill_);
430    return true;
431}
432
433volatile int32_t* PeerExperts::set_overlap_gate(std::atomic<int32_t>* landed, std::vector<uint8_t>* has, int32_t* last,
434                                                bool copy_signal) {
435    gate_landed_ = landed;
436    gate_has_ = has;
437    gate_last_ = last;
438    ticks_.resize((size_t) n_layers_);
439    for (int64_t l = 0; l < n_layers_; ++l) ticks_[(size_t) l] = {landed, (int32_t) l};
440    if (copy_signal && h_gate_ == nullptr) {
441        On on(device_);
442        std::vector<int32_t> iota((size_t) n_layers_);
443        for (size_t i = 0; i < iota.size(); ++i) iota[i] = (int32_t) i;
444        int32_t* vals = nullptr;
445        void* hp = nullptr;
446        if (cudaMalloc((void**) &vals, iota.size() * 4) == cudaSuccess &&
447            cudaMemcpy(vals, iota.data(), iota.size() * 4, cudaMemcpyHostToDevice) == cudaSuccess &&
448            cudaHostAlloc(&hp, 64, cudaHostAllocPortable) == cudaSuccess) {
449            *(volatile int32_t*) hp = -1;
450            d_gate_vals_ = vals;
451            h_gate_ = (volatile int32_t*) hp;
452        } else {   // host functions then
453            (void) cudaGetLastError();
454            if (vals) cudaFree(vals);
455        }
456    }
457    return h_gate_;
458}
459
460void PeerExperts::flip_pending() {
461    for (const auto& [i, slot] : pending_) res_[(size_t) i] = slot;
462}
463
464void PeerExperts::apply_pending(bool wait) {
465    if (pending_.empty()) return;
466    {
467        On on(device_);
468        if (wait) cudaEventSynchronize(refill_ev_);
469        else if (cudaEventQuery(refill_ev_) != cudaSuccess) return;
470    }
471    for (const auto& [i, slot] : pending_) res_[(size_t) i] = slot;
472    pending_.clear();
473}
474
475}  // namespace strata::core