Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
multi-GPU: a second GPU as an opt-in expert-cache tier (--peer-device N)
Andy58f852f10026
diff --git a/CMakeLists.txt b/CMakeLists.txtindex e25587c42..3ffd79329 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -349,7 +349,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)# about arithmetic, and this one knows the ORDER the arithmetic happens in.add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cppsrc/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp- src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp)+ src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp)target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target})if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp")diff --git a/docs/SECOND_GPU.md b/docs/SECOND_GPU.mdindex 0ce94e7aa..a9311bb19 100644--- a/docs/SECOND_GPU.md+++ b/docs/SECOND_GPU.md@@ -83,3 +83,41 @@ short decode requests.The existing warning about the CUDA0 expert-cache GPU hit path still applies:its outputs diverge from cache-off runs. Treat performance as experimentaluntil the generated tokens have been validated.++## Peer tier (`--peer-device`)++`--peer-device N` puts a second adaptive expert cache on CUDA device N. It+takes the ranked pairs CUDA0's cache does not hold, as many as fit. The peer+computes the rows of its own experts, for decode windows and for prompt+chunks; the activations and the results cross NVLink or another P2P path. The+tier adapts while the server runs, like the primary cache. It is an+alternative to the CUDA1-3 caches above, not a third tier beside them.++- `--peer-device N` (default off): enable the tier on CUDA device N (N >= 1).+- `--peer-reserve-mib M` (default 600): leave M MiB free on the peer card; the+ cache takes what remains. The prompt-path buffers need this headroom.+- `--peer-slots N` (default 0): cap the tier at N experts; 0 = as many as fit.+- `--peer-adapt-swaps N` (default -1): swaps per adaptive round on the peer;+ -1 uses the primary's `--adapt-swaps`.+- `--peer-prefill-rows N` (default -1): the share of each prompt chunk's rows+ the peer computes; -1 is half of chunk x top-k, 0 keeps prompt rows on the+ primary.++`--peer-device` requires `--expert-profile` and an enabled expert cache, and+the device must be visible; it refuses otherwise. `--expert-cache-device1`+and the peer both fill CUDA1 with an expert cache; the code does not refuse+the pair, but the two tiers then hold the same card twice and should not be+combined. A layer split (`--layer-split`) is a different second-GPU mode; the+combination is not refused and not tested.++Without `--peer-device` the binary is unchanged; its output is byte-identical+to the release. With `--peer-device` and the same expert set split across the+two cards, the generated tokens are byte-identical to the single-GPU run under+the exactness gate.++With a peer the prompt path keeps the MMQ path; the fused int8 prompt path is+not yet combined with the peer's rows. Mapped host buffers gain+`cudaHostAllocPortable` only with a peer, since only then does a second+context write them. The tier size is manual for now (`--peer-reserve-mib`,+`--peer-slots`); automatic sizing on small cards wants the buffer lending of+#216 and is a follow-up.diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hppindex fe079de87..4c4d12f56 100644--- a/include/strata/core/expert_source.hpp+++ b/include/strata/core/expert_source.hpp@@ -43,6 +43,7 @@ struct ExpertLayout;namespace strata::core {+class PeerExperts; // multi-GPU: the second GPU's expert tier (peer_experts.hpp)class RemoteExperts;struct LoadStats;@@ -336,6 +337,9 @@ struct ExpertDispatch {std::vector<float> usage;int64_t multi_misses = 0; ///< distinct (layer, expert) pairs the CPU computed in verify windowsint64_t multi_entries = 0; ///< routed (token, expert) entries the CPU served in verify windows+ /// Multi-GPU: the second GPU's tier. Its experts are computed there instead of on the CPU (kind 2).+ PeerExperts* peer = nullptr;+ int64_t peer_entries = 0; ///< routed entries the peer served in verify windows/// Set when `dispatch` could not produce an answer. The loop itself has no error channel, so this is/// where a source failure surfaces: the driver checks it after `session_loop` returns rather than the/// engine computing from a half-filled `parts`.diff --git a/include/strata/core/peer_experts.hpp b/include/strata/core/peer_experts.hppnew file mode 100644index 000000000..a6e3766a9--- /dev/null+++ b/include/strata/core/peer_experts.hpp@@ -0,0 +1,106 @@+// include/strata/core/peer_experts.hpp - multi-GPU: a second expert tier on another GPU.+//+// The primary GPU (device 0) keeps everything it had: the dense weights, the KV cache, the MTP layer, its own+// adaptive expert tier and the captured verify graph. This class adds an expert tier on a SECOND card. From+// the verify graph's point of view nothing changes: for each layer the pool thread decides which routed experts+// the primary computes (its VRAM tier, the PCIe share), and every remaining expert is a "CPU row" the graph reads+// from mapped host memory after the pool raises its flag. The peer takes the rows whose experts it holds: the+// pool thread launches them on the peer right after publishing the primary's plan, the CPU computes the rest at+// the same time, and the peer's rows are written into the same mapped rows before the pool returns.+//+// The peer computes with the SAME kernels as the primary's hit path (q8_1 activations + native_expert_grouped),+// from the same activation values, so an expert gives bit-identical rows on either card.+//+// The tier follows the conversation like the primary's: `adapt` swaps the most-routed experts that neither card+// holds into the peer's least-used slots (per layer, so a slot keeps its layer's blob size).+#pragma once++#include "strata/core/expert_cache.hpp"+#include "strata/core/expert_source.hpp"++#include <cuda_runtime.h>++#include <cstdint>+#include <string>+#include <utility>+#include <vector>++namespace strata::core {++/// multi-GPU: set once at startup when a peer device is configured (--peer-device N). The mapped host buffers+/// the peer card writes into are then allocated with cudaHostAllocPortable; without a peer the flag stays off.+void set_peer_portable(bool on);+bool peer_portable();++class PeerExperts {+public:+ PeerExperts() = default;+ ~PeerExperts();+ PeerExperts(const PeerExperts&) = delete;+ PeerExperts& operator=(const PeerExperts&) = delete;++ /// Opens the tier on `device`: fills it with the first pairs of `ranked` that `primary` does not hold, as many+ /// as fit in the card's free memory minus `reserve_mib` (`max_slots` > 0 caps the count).+ bool open(int device, const std::vector<std::pair<int32_t, int32_t>>& ranked, const ExpertCache& primary,+ ExpertSource& src, int64_t n_layers, int64_t n_expert, int reserve_mib, int64_t max_slots,+ std::string& err);+ void close();+ bool valid() const { return device_ >= 0; }+ int device() const { return device_; }++ /// Whether the peer holds (layer, expert) right now.+ bool has(int64_t layer, int64_t expert) const { return res_[(size_t) (layer * n_expert_ + expert)] >= 0; }++ /// The device address of (layer, expert)'s blob on the peer, or null when it is not resident.+ const uint8_t* slot_ptr(int64_t layer, int64_t expert) {+ const int32_t sl = res_[(size_t) (layer * n_expert_ + expert)];+ return sl >= 0 ? cache_.device_slot(sl) : nullptr;+ }+ /// Whether the primary (device 0) and the peer can read each other's memory directly (NVLink / PCIe P2P).+ bool p2p() const { return p2p_; }++ /// Starts the peer's share of one layer: the entries i with kind[i] == 2 (x: n_tok rows of n_embd floats).+ /// multi-GPU: with `out` (pinned, portable host rows) the peer writes its rows straight into+ /// out[entry] with a scatter kernel (no D2H copy + host memcpy in finish); STRATA_PEER_DIRECT=0: the old way.+ bool launch(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, int64_t k, const int32_t* kind,+ std::string& err, float* out = nullptr);+ /// Waits for the launched share and writes its rows into `out` (row i = entry i, n_embd floats).+ bool finish(float* out, std::string& err);++ /// Adaptive tier: swap up to `max_swaps` experts routed at least twice that neither the primary (`res0`, slot+ /// or -1) nor the peer holds into the peer's least-used slots. Copies run on the peer's refill stream; a+ /// swapped-in expert becomes resident at `apply_pending`. Call only between verify windows.+ bool adapt(const float* usage, const int32_t* res0, int max_swaps, std::string& err);+ void apply_pending(bool wait);++ int64_t resident() const { return resident_; }+ /// the last launch writes its rows into the host rows itself (the caller must not touch them)+ bool launched_direct() const { return launched_direct_; }+ double gib() const { return cache_.gib(); }+ int64_t entries() const { return entries_; } ///< routed entries the peer computed+ int64_t experts() const { return experts_; } ///< distinct (layer, expert) the peer computed+ int64_t swaps() const { return swaps_; }+ double ms_wait = 0; ///< host time spent in finish() waiting for the peer++private:+ int device_ = -1;+ bool p2p_ = false;+ int64_t n_layers_ = 0, n_expert_ = 0;+ ExpertCache cache_;+ ExpertSource* src_ = nullptr;+ std::vector<int32_t> res_; ///< [n_layers * n_expert] -> peer slot or -1+ std::vector<std::pair<int32_t, int32_t>> pending_; ///< (residency index, slot) once the copies land+ int64_t resident_ = 0, entries_ = 0, experts_ = 0, swaps_ = 0;+ cudaStream_t stream_ = nullptr, refill_ = nullptr;+ cudaEvent_t refill_ev_ = nullptr;+ float* h_x_ = nullptr; float* d_x_ = nullptr; // n_tok x n_embd+ float* h_out_ = nullptr; float* d_out_ = nullptr; // compact rows+ void* h_meta_ = nullptr; void* d_meta_ = nullptr; // groups: ptr | start | dst | tok | count+ uint8_t* d_q8_ = nullptr;+ void* d_scratch_ = nullptr;+ std::vector<int32_t> row_of_; ///< compact row -> original entry+ int64_t launched_rows_ = 0;+ bool launched_direct_ = false;+};++} // namespace strata::corediff --git a/include/strata/kernels/elementwise.hpp b/include/strata/kernels/elementwise.hppindex 0136176c4..02501beb6 100644--- a/include/strata/kernels/elementwise.hpp+++ b/include/strata/kernels/elementwise.hpp@@ -104,6 +104,8 @@ void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream);void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream);/// `rows` rows of `width` floats from mapped memory, except the rows listed in hit_rows[0, *count) (device),/// which are written +0.0 instead (a verify window's GPU-computed entries: the pool leaves zeros there).+/// multi-GPU: dst[rows[r] * width ..] = src[r * width ..] for r < n (float4; dst may be mapped host memory).+void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, void* stream);void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows,const int32_t* count, void* stream);diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hppindex da225d3b4..038e0dd95 100644--- a/include/strata/prefill/prefill.hpp+++ b/include/strata/prefill/prefill.hpp@@ -21,6 +21,8 @@#include <memory>#include <string>+namespace strata::core { class PeerExperts; }+namespace strata::prefill {struct PrefillStats {@@ -86,6 +88,11 @@ public:const PrefillStats& stats() const { return stats_; }+ /// multi-GPU: the experts the peer GPU holds are computed THERE for every prompt chunk (up to `cap_rows` routed+ /// rows per layer; the rest of the peer's experts are read by this GPU over P2P). Allocates the peer's buffers for+ /// chunks of up to init's `chunk` tokens. Needs P2P between the two cards.+ bool set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& err);+/// Plan v0.3 P6: called after every chunk with the chunk's final multi-stream residual rows (device,/// T x hc*n_embd, valid until the next chunk) and the chunk's first position; the MTP draft layer builds its/// K/V from them. The prefill stream is synchronized before the call.diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cppindex 26c3edf9f..c64909f54 100644--- a/src/core/expert_source.cpp+++ b/src/core/expert_source.cpp@@ -1,6 +1,7 @@// src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract.#include "strata/core/expert_source.hpp"#include "strata/core/remote_experts.hpp"+#include "strata/core/peer_experts.hpp"#include "strata/kernels/cpu/expert_layout.hpp"#include "strata/artifact/gguf_reader.hpp"@@ -1899,7 +1900,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32if (first_of[i] == i) {distinct[nd++] = i;const int32_t e = ids[i];- if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0) ++nmiss;+ if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 &&+ !(d.peer != nullptr && d.peer->has(d.layers, e))) ++nmiss;}}const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers);@@ -1919,6 +1921,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32kd = 0;ptr = (unsigned long long) (d.cache_base + (d.cache_slot_off ? (size_t) d.cache_slot_off[slot]: (size_t) slot * (size_t) d.cache_blob));+ } else if (d.peer != nullptr && d.peer->has(d.layers, e)) {+ kd = 2; // multi-GPU: the second GPU computes it} else {if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) {const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr;@@ -1973,7 +1977,18 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32for (int64_t i = 0; i < n; ++i) {const int32_t e = ids[i];kind[i] = (e >= 0 && e < d.n_expert && d.host_res != nullptr &&- d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0 : -1;+ d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0+ : (e >= 0 && e < d.n_expert && d.peer != nullptr && d.peer->has(d.layers, e)) ? 2 : -1;+ }+ }+ if (d.peer != nullptr) { // multi-GPU: start the second GPU's share before the CPU's own work+ std::string perr;+ if (!d.peer->launch(d.layers, x_f, ids, n_tok, k, kind, perr, out)) {+ std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);+ d.failed = true;+ d.fail = "the peer GPU's experts could not be launched";+ d.fail_layer = d.layers;+ return;}}if (d.remote_count > 0) {@@ -2016,9 +2031,12 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32d.fail_expert = e;return;}- if (kind[i] >= 0) { // CUDA0, PCIe, or a remote result staged into this row below+ if (kind[i] >= 0) { // CUDA0, PCIe, or a remote/peer result staged into this row belowif (kind[i] == 0) ++d.cache_hits;- std::memset(row, 0, (size_t) H * sizeof(float));+ else if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries;+ // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it+ if (!(kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()))+ std::memset(row, 0, (size_t) H * sizeof(float));continue;}++d.cache_refused;@@ -2056,6 +2074,16 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;}}+ if (d.peer != nullptr) { // multi-GPU: the second GPU's rows, into the same mapped rows+ std::string perr;+ if (!d.peer->finish(out, perr)) {+ std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);+ d.failed = true;+ d.fail = "the peer GPU's experts failed";+ d.fail_layer = d.layers;+ return;+ }+ }const auto c4 = std::chrono::steady_clock::now();pt("ran");auto ms = [](auto a, auto b) { return std::chrono::duration<double, std::milli>(b - a).count(); };diff --git a/src/core/mtp.cpp b/src/core/mtp.cppindex f35165e03..a53cc60a4 100644--- a/src/core/mtp.cpp+++ b/src/core/mtp.cpp@@ -4,6 +4,7 @@#include "strata/core/on_device.hpp"#include "strata/core/native_head.hpp"+#include "strata/core/peer_experts.hpp"#include "strata/kernels/bf16_gemv.hpp"#include "strata/kernels/cpu/expert.hpp"#include "strata/kernels/elementwise.hpp"@@ -56,7 +57,7 @@ struct Bump {};bool mapped(size_t bytes, void** h, void** d) {- if (cudaHostAlloc(h, bytes, cudaHostAllocMapped) != cudaSuccess) return false;+ if (cudaHostAlloc(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false;std::memset(*h, 0, bytes);return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;}diff --git a/src/core/peer_experts.cpp b/src/core/peer_experts.cppnew file mode 100644index 000000000..bf6284a62--- /dev/null+++ b/src/core/peer_experts.cpp@@ -0,0 +1,325 @@+// src/core/peer_experts.cpp - see include/strata/core/peer_experts.hpp.+#include "strata/core/peer_experts.hpp"++#include "strata/kernels/cpu/expert_layout.hpp"+#include "strata/kernels/elementwise.hpp"+#include "strata/kernels/iq_kernels.hpp"+#include "strata/kernels/quantize_act.hpp"+#include "strata/kernels/s2_expert_grouped.hpp"++#include <algorithm>+#include <chrono>+#include <cstdio>+#include <cstring>+#include <cstdlib>+#include <stdexcept>++namespace strata::core {++static bool g_peer_portable = false;+void set_peer_portable(bool on) { g_peer_portable = on; }+bool peer_portable() { return g_peer_portable; }++namespace {++constexpr int64_t H = strata::kernels::cpu::H;+constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10; // entries per layer: MAXT tokens x top-10++struct Meta { // one block, uploaded with one copy per layer+ unsigned long long ptr[CAP];+ int32_t start[CAP + 1];+ int32_t dst[CAP];+ int32_t tok[CAP];+ int32_t count[4]; // [0] groups, [1] entries+ int32_t out_row[CAP]; // multi-GPU: compact row -> entry row in the host `out`+};++/// Switches the calling thread to `dev` and back. The engine's own thread lives on device 0.+struct On {+ int prev = 0;+ explicit On(int dev) { cudaGetDevice(&prev); if (prev != dev) cudaSetDevice(dev); }+ ~On() { int cur = 0; cudaGetDevice(&cur); if (cur != prev) cudaSetDevice(prev); }+};++bool ck(cudaError_t e, const char* what, std::string& err) {+ if (e == cudaSuccess) return true;+ err = std::string("peer experts: ") + what + ": " + cudaGetErrorString(e);+ return false;+}++} // namespace++PeerExperts::~PeerExperts() { close(); }++void PeerExperts::close() {+ if (device_ < 0) return;+ {+ On on(device_);+ if (stream_) cudaStreamSynchronize(stream_);+ if (refill_) cudaStreamSynchronize(refill_);+ cache_.close();+ if (d_x_) cudaFree(d_x_);+ if (d_out_) cudaFree(d_out_);+ if (d_meta_) cudaFree(d_meta_);+ if (d_q8_) cudaFree(d_q8_);+ if (d_scratch_) cudaFree(d_scratch_);+ if (h_x_) cudaFreeHost(h_x_);+ if (h_out_) cudaFreeHost(h_out_);+ if (h_meta_) cudaFreeHost(h_meta_);+ if (refill_ev_) cudaEventDestroy(refill_ev_);+ if (stream_) cudaStreamDestroy(stream_);+ if (refill_) cudaStreamDestroy(refill_);+ }+ d_x_ = d_out_ = h_x_ = h_out_ = nullptr;+ d_meta_ = h_meta_ = d_scratch_ = nullptr;+ d_q8_ = nullptr;+ stream_ = refill_ = nullptr;+ refill_ev_ = nullptr;+ device_ = -1;+}++bool PeerExperts::open(int device, const std::vector<std::pair<int32_t, int32_t>>& ranked, const ExpertCache& primary,+ ExpertSource& src, int64_t n_layers, int64_t n_expert, int reserve_mib, int64_t max_slots,+ std::string& err) {+ close();+ int count = 0;+ if (!ck(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err)) return false;+ if (device < 1 || device >= count) {+ err = "peer experts: CUDA device " + std::to_string(device) + " is not visible (" + std::to_string(count) ++ " devices; set CUDA_VISIBLE_DEVICES)";+ return false;+ }+ const auto& lay = strata::kernels::cpu::expert_layout();+ n_layers_ = n_layers;+ n_expert_ = n_expert;+ src_ = &src;+ res_.assign((size_t) (n_layers * n_expert), kNotResident);+ { // direct access both ways (NVLink or another P2P path): the prompt path copies activations and results over it+ int a = 0, b = 0;+ cudaDeviceCanAccessPeer(&a, 0, device);+ cudaDeviceCanAccessPeer(&b, device, 0);+ p2p_ = a && b;+ if (p2p_) {+ On on0(0);+ cudaError_t e0 = cudaDeviceEnablePeerAccess(device, 0);+ if (e0 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e0 = cudaSuccess; }+ On on1(device);+ cudaError_t e1 = cudaDeviceEnablePeerAccess(0, 0);+ if (e1 == cudaErrorPeerAccessAlreadyEnabled) { cudaGetLastError(); e1 = cudaSuccess; }+ p2p_ = e0 == cudaSuccess && e1 == cudaSuccess;+ }+ }+ On on(device);+ device_ = device;+ // scratch first, so the slots take what is really left+ int64_t ff = strata::kernels::cpu::FF;+ if (lay.native)+ for (const auto& f : lay.fmt) ff = std::max<int64_t>(ff, f.n_ff);+ const size_t scratch = std::max<size_t>((size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, ff),+ strata::kernels::native_expert_scratch_bytes(CAP, ff));+ const bool alloc_ok =+ ck(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err) &&+ ck(cudaStreamCreateWithFlags(&refill_, cudaStreamNonBlocking), "refill stream", err) &&+ ck(cudaEventCreateWithFlags(&refill_ev_, cudaEventDisableTiming), "event", err) &&+ ck(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "input staging", err) &&+ ck(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "result staging", err) &&+ ck(cudaHostAlloc(&h_meta_, sizeof(Meta), cudaHostAllocPortable | cudaHostAllocMapped), "plan staging", err) &&+ ck(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err) &&+ ck(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err) &&+ ck(cudaMalloc(&d_meta_, sizeof(Meta)), "plan", err) &&+ ck(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activations", err) &&+ ck(cudaMalloc(&d_scratch_, scratch), "scratch", err);+ if (!alloc_ok) { close(); return false; }++ // the pairs the primary does not hold, in rank order, as many as fit+ size_t free_b = 0, total_b = 0;+ if (!ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo", err)) { close(); return false; }+ const uint64_t reserve = (uint64_t) std::max(reserve_mib, 128) << 20;+ const uint64_t budget = free_b > reserve ? free_b - reserve : 0;+ std::vector<std::pair<int32_t, int32_t>> pick;+ std::vector<int64_t> sizes;+ uint64_t used = 0;+ for (const auto& pr : ranked) {+ if (primary.slot_of(pr.first, pr.second) >= 0) continue;+ const uint64_t b = lay.blob_bytes(pr.first);+ const uint64_t b256 = lay.native ? (b + 255) / 256 * 256 : lay.max_blob;+ if (used + b256 > budget) break;+ if (max_slots > 0 && (int64_t) pick.size() >= max_slots) break;+ used += b256;+ pick.push_back(pr);+ sizes.push_back((int64_t) b);+ }+ if (pick.empty()) { err = "peer experts: no room or no expert left for the peer"; close(); return false; }+ const bool opened = lay.native ? cache_.open_sized(sizes, n_layers, n_expert, err)+ : cache_.open((int64_t) pick.size(), n_layers, n_expert, (int64_t) lay.max_blob, err);+ if (!opened) { err = "peer experts: " + err; close(); return false; }+ // open() zeroes the arena with cudaMemset on the legacy stream, which is not ordered against the non-blocking+ // refill stream: wait for it, or the zeroing can land on top of the fills+ if (!ck(cudaDeviceSynchronize(), "arena zeroing", err)) { close(); return false; }+ for (const auto& pr : pick) {+ const int32_t slot = cache_.admit(pr.first, pr.second);+ const uint8_t* b = src.blob(pr.first, pr.second);+ if (slot < 0 || b == nullptr || !cache_.fill_slot(slot, b, refill_, err, (int64_t) lay.blob_bytes(pr.first))) {+ err = "peer experts: fill failed: " + err;+ close();+ return false;+ }+ res_[(size_t) (pr.first * n_expert + pr.second)] = slot;+ }+ if (!ck(cudaStreamSynchronize(refill_), "fill", err)) { close(); return false; }+ const auto& f0 = pick.front();+ if (!cache_.verify_slot(res_[(size_t) (f0.first * n_expert + f0.second)], src.blob(f0.first, f0.second), err,+ (int64_t) lay.blob_bytes(f0.first))) {+ err = "peer experts: " + err;+ close();+ return false;+ }+ resident_ = (int64_t) pick.size();+ return true;+}++bool PeerExperts::launch(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, int64_t k,+ const int32_t* kind, std::string& err, float* out) {+ static const bool direct_env = [] { const char* v = std::getenv("STRATA_PEER_DIRECT"); return v == nullptr || std::atoi(v) != 0; }();+ const bool direct = direct_env && out != nullptr;+ launched_direct_ = false;+ launched_rows_ = 0;+ row_of_.clear();+ const int64_t n = n_tok * k;+ if (n > CAP) { err = "peer experts: window too large"; return false; }+ Meta& m = *(Meta*) h_meta_;+ int groups = 0, rows = 0;+ // distinct experts in routing order; each one's entries become compact rows+ for (int64_t i = 0; i < n; ++i) {+ if (kind[i] != 2) continue;+ bool seen = false;+ for (int64_t j = 0; j < i; ++j)+ if (kind[j] == 2 && ids[j] == ids[i]) { seen = true; break; }+ if (seen) continue;+ const int32_t slot = res_[(size_t) (layer * n_expert_ + ids[i])];+ if (slot < 0) { err = "peer experts: an entry was planned for the peer but is not resident"; return false; }+ m.ptr[groups] = (unsigned long long) cache_.device_slot(slot);+ m.start[groups] = rows;+ for (int64_t j = i; j < n; ++j)+ if (kind[j] == 2 && ids[j] == ids[i]) {+ m.dst[rows] = rows;+ m.tok[rows] = (int32_t) (j / k);+ m.out_row[rows] = (int32_t) j;+ row_of_.push_back((int32_t) j);+ ++rows;+ }+ ++groups;+ ++experts_;+ }+ if (groups == 0) return true;+ m.start[groups] = rows;+ m.count[0] = groups;+ m.count[1] = rows;+ entries_ += rows;+ launched_rows_ = rows;+ // direct: x is the verifier's pinned (portable) doorbell row block - copied from where it is+ if (!direct) std::memcpy(h_x_, x, (size_t) (n_tok * H) * sizeof(float));+ On on(device_);+ const cudaStream_t s = stream_;+ if (!ck(cudaMemcpyAsync(d_x_, direct ? x : h_x_, (size_t) (n_tok * H) * sizeof(float), cudaMemcpyHostToDevice, s), "input", err) ||+ !ck(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(Meta), cudaMemcpyHostToDevice, s), "plan", err))+ return false;+ Meta* dm = (Meta*) d_meta_;+ const auto& lay = strata::kernels::cpu::expert_layout();+ if (lay.native) {+ strata::kernels::quantize_q8_1_rows(d_x_, n_tok, H, d_q8_, s);+ const auto& f = lay.fmt[(size_t) layer];+ const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);+ strata::kernels::native_expert_grouped(L, dm->ptr, dm->start, dm->count, dm->dst, dm->tok, groups, rows, d_q8_,+ d_scratch_, d_out_, s);+ } else {+ err = "peer experts: only native packs are supported";+ return false;+ }+ if (direct) { // the rows straight into the host `out` (zero-copy, coalesced float4 writes)+ try {+ strata::kernels::scatter_rows_f32(d_out_, out, dm->out_row, rows, H, s);+ } catch (const std::exception& e) { err = std::string("peer experts: scatter: ") + e.what(); return false; }+ launched_direct_ = true;+ return true;+ }+ return ck(cudaMemcpyAsync(h_out_, d_out_, (size_t) rows * H * sizeof(float), cudaMemcpyDeviceToHost, s),+ "results", err);+}++bool PeerExperts::finish(float* out, std::string& err) {+ if (launched_rows_ == 0) return true;+ const auto t0 = std::chrono::steady_clock::now();+ {+ On on(device_);+ // spin on the stream (a blocking sync would sleep the pool thread and wake it late)+ cudaError_t e;+ while ((e = cudaStreamQuery(stream_)) == cudaErrorNotReady) {+ }+ if (!ck(e, "finish", err)) return false;+ }+ ms_wait += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();+ if (launched_direct_) { launched_rows_ = 0; return true; }+ for (size_t r = 0; r < row_of_.size(); ++r)+ std::memcpy(out + (size_t) row_of_[r] * H, h_out_ + r * H, (size_t) H * sizeof(float));+ launched_rows_ = 0;+ return true;+}++bool PeerExperts::adapt(const float* usage, const int32_t* res0, int max_swaps, std::string& err) {+ if (!pending_.empty() || max_swaps <= 0) return true;+ const auto& lay = strata::kernels::cpu::expert_layout();+ struct Swap { float gain; int32_t layer, in, out; };+ std::vector<Swap> swaps;+ std::vector<std::pair<float, int32_t>> cand, vict;+ for (int64_t l = 0; l < n_layers_; ++l) {+ cand.clear();+ vict.clear();+ const float* u = usage + l * n_expert_;+ const int32_t* r0 = res0 + l * n_expert_;+ const int32_t* r1 = res_.data() + l * n_expert_;+ for (int32_t e = 0; e < (int32_t) n_expert_; ++e) {+ if (r1[e] >= 0) vict.emplace_back(u[e], e);+ else if (r0[e] < 0 && u[e] >= 2.0f) cand.emplace_back(u[e], e);+ }+ if (cand.empty() || vict.empty()) continue;+ std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; });+ const size_t nc = std::min(cand.size(), vict.size());+ std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(),+ [](auto& a, auto& b) { return a.first < b.first; });+ for (size_t i = 0; i < nc; ++i) {+ if (cand[i].first < vict[i].first + 1.5f) break;+ swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second});+ }+ }+ if (swaps.empty()) return true;+ std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });+ if ((int) swaps.size() > max_swaps) swaps.resize((size_t) max_swaps);+ On on(device_);+ for (const Swap& s : swaps) {+ const size_t in = (size_t) (s.layer * n_expert_ + s.in), out = (size_t) (s.layer * n_expert_ + s.out);+ const int32_t slot = res_[out];+ const uint8_t* b = src_->blob(s.layer, s.in);+ if (slot < 0 || b == nullptr) continue;+ if (!ck(cudaMemcpyAsync(cache_.device_slot(slot), b, (size_t) lay.blob_bytes(s.layer), cudaMemcpyHostToDevice,+ refill_), "refill", err))+ return false;+ res_[out] = kNotResident; // evicted now: the CPU computes it meanwhile+ pending_.emplace_back((int32_t) in, slot);+ ++swaps_;+ }+ return ck(cudaEventRecord(refill_ev_, refill_), "refill event", err);+}++void PeerExperts::apply_pending(bool wait) {+ if (pending_.empty()) return;+ {+ On on(device_);+ if (wait) cudaEventSynchronize(refill_ev_);+ else if (cudaEventQuery(refill_ev_) != cudaSuccess) return;+ }+ for (const auto& [i, slot] : pending_) res_[(size_t) i] = slot;+ pending_.clear();+}++} // namespace strata::corediff --git a/src/core/verify.cpp b/src/core/verify.cppindex f682edba3..ade718a0f 100644--- a/src/core/verify.cpp+++ b/src/core/verify.cpp@@ -6,6 +6,7 @@#include "strata/core/native_head.hpp"#include "strata/core/on_device.hpp"+#include "strata/core/peer_experts.hpp"#include "strata/kernels/iq_kernels.hpp"#include "strata/kernels/cpu/expert_layout.hpp"#include "strata/kernels/bf16_gemv.hpp"@@ -69,7 +70,7 @@ struct Bump {};bool mapped(size_t bytes, void** h, void** d) {- if (cudaHostAlloc(h, bytes, cudaHostAllocMapped) != cudaSuccess) return false;+ if (cudaHostAlloc(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false; // multi-GPU: portable only with a peer - the peer card writes its rows into themstd::memset(*h, 0, bytes);return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;}diff --git a/src/kernels/cuda/elementwise.cu b/src/kernels/cuda/elementwise.cuindex 22d022e92..26cf66faa 100644--- a/src/kernels/cuda/elementwise.cu+++ b/src/kernels/cuda/elementwise.cu@@ -251,6 +251,23 @@ __global__ void copy_rows_from_mapped_kernel(float4* __restrict__ dst, const volfor (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = const_cast<const float4*>(sr)[i];}}+namespace {+__global__ void scatter_rows_kernel(const float4* __restrict__ src, float4* dst, const int32_t* __restrict__ rows,+ int64_t w4) {+ const int64_t r = blockIdx.x;+ const float4* s = src + r * w4;+ float4* d = dst + (int64_t) rows[r] * w4;+ for (int64_t i = threadIdx.x; i < w4; i += blockDim.x) d[i] = s[i];+}+} // namespace+void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, void* stream) {+ if (n <= 0) return;+ if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) {+ std::fprintf(stderr, "scatter_rows_f32: width must be a multiple of 4 and both pointers 16-byte aligned\n");+ std::exit(1);+ }+ scatter_rows_kernel<<<(unsigned) n, 128, 0, (cudaStream_t) stream>>>((const float4*) src, (float4*) dst, rows, width / 4);+}void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows,const int32_t* count, void* stream) {if (rows <= 0) return;diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cppindex ad831d004..edbc47c56 100644--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@ -26,6 +26,7 @@#include "strata/prefill/moe_fused.hpp"#include "strata/prefill/moe_fused_iq.hpp"#include "strata/prefill/moe_mmq.hpp"+#include "strata/core/peer_experts.hpp"#include "strata/prefill/kernels.hpp"#include <cuda_runtime.h>@@ -119,6 +120,7 @@ int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_over// take any of its layers: IQ2_XS, 4K / 32K, their first version at 384 slots -3% / -6% against MMQ, at 512 +8% / 0%.inline bool fused_ring() {if (!fused::enabled()) return false;+ if (core::peer_portable()) return false; // multi-GPU: --peer-device keeps the MMQ path and its buffer sizesconst strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();if (!lay.native) return true;static const bool any = [&lay] {@@ -331,6 +333,81 @@ struct Stager {}};+// multi-GPU: the peer GPU's share of a prompt chunk's experts. Per MoE layer the primary copies its normed+// activations over P2P, the peer quantizes the rows routed to the experts it holds, runs the same MMQ products the+// primary would (gathered from its own slots), and copies the result rows back into the primary's Dm rows - the rows+// are laid out local-first, so the peer's are one contiguous block at the end.+struct PeerPrefill {+ core::PeerExperts* peer = nullptr;+ int dev = -1;+ int64_t cap_rows = 0, T_max = 0;+ cudaStream_t s = nullptr;+ cudaEvent_t ev_in = nullptr; // on the primary: the activations and the row tables are ready+ cudaEvent_t ev_done = nullptr; // on the peer: its rows have landed in the primary's Dm+ // multi-GPU: the result rows go back group by group on a second stream while the next group computes+ cudaStream_t s_out = nullptr;+ static constexpr int kGrpEv = NE / 16 + 2;+ cudaEvent_t ev_grp[kGrpEv] = {};+ bool out_pending = false; // s_out may still read Dm (the next layer's products wait for it)+ bool out_pipe = true;+ // multi-GPU COMPACT: the peer's per-row buffers hold one GROUP's rows instead of the layer's (a group+ // = up to 16 experts and at most G rows), the result rows double-buffered: ~0.9 GB -> ~0.26 GB on the helper+ // card at 8192-token chunks, and no row cap (every peer-held expert's rows go to the peer).+ // STRATA_PF_PEER_COMPACT=0: the layer-sized buffers (the A/B).+ bool compact = true;+ int64_t G = 0;+ void *Xq_g = nullptr, *Hq_g = nullptr;+ float *GU_g = nullptr, *H_g = nullptr, *Dm_b[2] = {};+ cudaEvent_t ev_dm[2] = {};+ bool dm_live[2] = {};+ std::vector<std::pair<size_t, size_t>> groups;+ // multi-GPU PEER STREAMING: a share of the experts the primary would stream over ITS PCIe link in a+ // big chunk is streamed by the peer over its own link instead (into its own ring) and computed there - it halves+ // the primary's copy load and moves expert work to the card that idles through most of the MoE half.+ // STRATA_PF_PEER_STREAM = the share (0 = off), STRATA_PF_PEER_RING = its ring slots.+ double ps_frac = 0.0;+ int RP = 0;+ std::vector<uint8_t*> pstage;+ std::vector<cudaEvent_t> pcopied, pused;+ std::vector<char> plive;+ cudaStream_t s_cp = nullptr;+ struct PsEntry { int32_t l, e; const uint8_t* blob; };+ std::vector<PsEntry> pseq; // this chunk's peer-streamed experts, layer by layer in id order+ std::vector<size_t> pseq_start;+ std::vector<char> ps_flag; // [layer * NE + e]: streamed by the peer in this chunk+ size_t p_issued = 0, pk = 0;+ int64_t ps_experts = 0;+ float *mixed = nullptr, *GU = nullptr, *H = nullptr, *Dm = nullptr;+ void *Xq = nullptr, *Hq = nullptr;+ int32_t *src = nullptr, *bounds = nullptr, *ident = nullptr;+ uint8_t *grp_gu = nullptr, *grp_d = nullptr;+ std::unique_ptr<mmq::Context> ctx;+ std::vector<int32_t> bounds_host;+ std::vector<void*> owned;+ int64_t layers = 0, experts = 0, rows = 0, over_cap = 0; // stats+ ~PeerPrefill() {+ if (dev < 0) return;+ int prev = 0;+ cudaGetDevice(&prev);+ cudaSetDevice(dev);+ if (s) cudaStreamSynchronize(s);+ ctx.reset();+ for (void* p : owned) cudaFree(p);+ if (ev_done) cudaEventDestroy(ev_done);+ if (s_out) cudaStreamSynchronize(s_out);+ for (cudaEvent_t e : ev_grp) if (e) cudaEventDestroy(e);+ for (cudaEvent_t e : ev_dm) if (e) cudaEventDestroy(e);+ if (s_cp) cudaStreamSynchronize(s_cp);+ for (cudaEvent_t e : pcopied) if (e) cudaEventDestroy(e);+ for (cudaEvent_t e : pused) if (e) cudaEventDestroy(e);+ if (s_cp) cudaStreamDestroy(s_cp);+ if (s_out) cudaStreamDestroy(s_out);+ if (s) cudaStreamDestroy(s);+ cudaSetDevice(prev);+ if (ev_in) cudaEventDestroy(ev_in);+ }+};+struct Prefill::Impl {const core::WeightTable* wt = nullptr;const core::ModelGeometry* g = nullptr;@@ -414,6 +491,7 @@ struct Prefill::Impl {// C-4: the chunk's token ids on the device, for one batched embedding gatherint32_t* tok_dev = nullptr;std::vector<int32_t> tok_host;+ std::unique_ptr<PeerPrefill> pp; // multi-GPU: the peer GPU's expert share (set_peer)};namespace {@@ -642,7 +720,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, com.grp_host = m.grp_dev = nullptr;m.grp_n = m.grp_tk = 0;void *h = nullptr, *d = nullptr;- if (cudaHostAlloc(&h, need * 4, cudaHostAllocMapped) == cudaSuccess &&+ if (cudaHostAlloc(&h, need * 4, cudaHostAllocMapped | (core::peer_portable() ? cudaHostAllocPortable : 0)) == cudaSuccess &&cudaHostGetDevicePointer(&d, h, 0) == cudaSuccess) {m.grp_host = (int32_t*) h;m.grp_dev = (int32_t*) d;@@ -969,6 +1047,104 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t(long long) B, ms_idle, ms_since(tl0), ms_since(t0));return true;}+bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& err) {+ Impl& m = *impl_;+ if (peer == nullptr || !peer->valid()) { m.pp.reset(); return true; }+ if (!peer->p2p()) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; }+ if (!mmq_plan().any) { err = "prefill peer: needs the MMQ prompt path"; return false; }+ auto pp = std::make_unique<PeerPrefill>();+ pp->peer = peer;+ pp->T_max = m.T_max;+ pp->cap_rows = std::max<int64_t>(1, std::min<int64_t>(cap_rows, m.T_max * K));+ const int64_t R = pp->cap_rows;+ const MmqPlan& mp = mmq_plan();+ if (cudaEventCreateWithFlags(&pp->ev_in, cudaEventDisableTiming) != cudaSuccess) { err = "prefill peer: event"; return false; }+ int prev = 0;+ cudaGetDevice(&prev);+ pp->dev = peer->device();+ cudaSetDevice(pp->dev);+ bool ok = cudaStreamCreateWithFlags(&pp->s, cudaStreamNonBlocking) == cudaSuccess &&+ cudaEventCreateWithFlags(&pp->ev_done, cudaEventDisableTiming) == cudaSuccess;+ {+ const char* v = std::getenv("STRATA_PF_PEER_OUT_PIPE"); // =0: one copy after the last group (the A/B)+ pp->out_pipe = (v == nullptr || std::atoi(v) != 0) || pp->compact; // compact always pipes+ }+ if (ok && pp->out_pipe) {+ ok = cudaStreamCreateWithFlags(&pp->s_out, cudaStreamNonBlocking) == cudaSuccess;+ for (int i = 0; ok && i < PeerPrefill::kGrpEv; ++i)+ ok = cudaEventCreateWithFlags(&pp->ev_grp[i], cudaEventDisableTiming) == cudaSuccess;+ }+ auto take = [&](size_t bytes) -> void* {+ void* p = nullptr;+ if (!ok || cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; return nullptr; }+ pp->owned.push_back(p);+ return p;+ };+ pp->mixed = (float*) take((size_t) m.T_max * N * 4);+ {+ const char* v = std::getenv("STRATA_PF_PEER_COMPACT");+ pp->compact = v == nullptr || std::atoi(v) != 0;+ }+ if (pp->compact) {+ pp->cap_rows = m.T_max * K; // no row cap: only the row tables grow with it+ pp->G = m.T_max; // one expert never has more rows than the chunk has tokens+ const int64_t Gr = pp->G;+ pp->Xq_g = take(mmq::q8_bytes(Gr, N));+ pp->Hq_g = take(mmq::q8_bytes(Gr, 640));+ pp->GU_g = (float*) take((size_t) Gr * 1280 * 4);+ pp->H_g = (float*) take((size_t) Gr * 640 * 4);+ pp->Dm_b[0] = (float*) take((size_t) Gr * N * 4);+ pp->Dm_b[1] = (float*) take((size_t) Gr * N * 4);+ for (int b = 0; b < 2 && ok; ++b) ok = cudaEventCreateWithFlags(&pp->ev_dm[b], cudaEventDisableTiming) == cudaSuccess;+ const char* fs = std::getenv("STRATA_PF_PEER_STREAM");+ pp->ps_frac = fs ? std::atof(fs) : 0.35; // measured: 0.25-0.5 all ~1950-1970 at 32K, 0.35 best+ if (pp->ps_frac > 0.0 && !mp.fallback && m.T_max >= stream_all_min()) {+ pp->RP = 48;+ if (const char* pr = std::getenv("STRATA_PF_PEER_RING"); pr != nullptr) pp->RP = std::atoi(pr);+ pp->pstage.assign((size_t) pp->RP, nullptr);+ pp->pcopied.assign((size_t) pp->RP, nullptr);+ pp->pused.assign((size_t) pp->RP, nullptr);+ pp->plive.assign((size_t) pp->RP, 0);+ ok = ok && cudaStreamCreateWithFlags(&pp->s_cp, cudaStreamNonBlocking) == cudaSuccess;+ for (int i = 0; ok && i < pp->RP; ++i) {+ pp->pstage[(size_t) i] = (uint8_t*) take((size_t) MAXBLOB());+ ok = ok && cudaEventCreateWithFlags(&pp->pcopied[(size_t) i], cudaEventDisableTiming) == cudaSuccess &&+ cudaEventCreateWithFlags(&pp->pused[(size_t) i], cudaEventDisableTiming) == cudaSuccess;+ }+ } else {+ pp->ps_frac = 0.0;+ }+ } else {+ pp->Xq = take(mmq::q8_bytes(R, N));+ pp->Hq = take(mmq::q8_bytes(R, 640));+ pp->GU = (float*) take((size_t) R * 1280 * 4);+ pp->H = (float*) take((size_t) R * 640 * 4);+ pp->Dm = (float*) take((size_t) R * N * 4);+ }+ const int64_t Rt = pp->cap_rows;+ pp->src = (int32_t*) take((size_t) Rt * 4);+ pp->ident = (int32_t*) take((size_t) Rt * 4);+ pp->bounds = (int32_t*) take((size_t) (2 * (NE + NE / MMQ_GROUP + 2)) * 4);+ pp->grp_gu = (uint8_t*) take(MMQ_GROUP * mp.gu_max + MMQ_TAIL);+ pp->grp_d = (uint8_t*) take(MMQ_GROUP * mp.d_max + MMQ_TAIL);+ if (ok) {+ pp->ctx = std::make_unique<mmq::Context>();+ mmq::iota(pp->ident, pp->cap_rows, pp->s);+ ok = cudaStreamSynchronize(pp->s) == cudaSuccess;+ }+ size_t fb = 0, tb = 0;+ cudaMemGetInfo(&fb, &tb);+ cudaSetDevice(prev);+ if (!ok) { err = "prefill peer: the peer's buffers do not fit (raise --peer-reserve-mib or lower --peer-prefill-rows)"; return false; }+ std::fprintf(stderr, "strata prefill: peer GPU %d computes its experts' rows of each prompt chunk (up to %lld rows per "+ "layer%s); %zu MiB left free on it\n", pp->dev, (long long) pp->cap_rows,+ pp->compact ? (pp->ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string((int) (pp->ps_frac * 100 + 0.5)) ++ "% of the primary's streamed experts through a " + std::to_string(pp->RP) + "-slot ring").c_str()+ : ", compact group buffers") : "", fb >> 20);+ m.pp = std::move(pp);+ return true;+}+void Prefill::set_pinned_share(double share) { g_pinned_share = share; }void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; }double Prefill::pinned_share() { return g_pinned_share; }@@ -1078,6 +1254,47 @@ struct PfTimer {for (cudaEvent_t e : ev) cudaEventDestroy(e);}};+// multi-GPU: the peer's own timeline (STRATA_PREFILL_TIMING): marks on the peer stream, folded with the primary's+enum PePhase { kPeIdle, kPeMoeIn, kPeMoeGemm, kPeMoeOut, kPeCount };+const char* const kPeNames[kPeCount] = {"idle", "moe in", "moe gemm", "moe out"};+struct PeTimer {+ bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr;+ int dev = -1;+ std::vector<cudaEvent_t> ev;+ std::vector<int> ph;+ size_t used = 0;+ double ms[kPeCount] = {};+ void mark(int phase, cudaStream_t s) { // the peer device is current+ if (!on) return;+ if (used == ev.size()) {+ cudaEvent_t e = nullptr;+ cudaEventCreate(&e);+ ev.push_back(e);+ ph.push_back(0);+ }+ ph[used] = phase;+ cudaEventRecord(ev[used], s);+ ++used;+ }+ void fold() { // every mark has completed+ if (!on || used < 2) return;+ for (size_t i = 0; i + 1 < used; ++i) {+ float t = 0.0f;+ if (cudaEventElapsedTime(&t, ev[i], ev[i + 1]) == cudaSuccess) ms[ph[i]] += t;+ }+ std::swap(ev[0], ev[used - 1]);+ std::swap(ph[0], ph[used - 1]);+ used = 1;+ }+ ~PeTimer() {+ if (dev < 0) return;+ int prev = 0;+ cudaGetDevice(&prev);+ cudaSetDevice(dev);+ for (cudaEvent_t e : ev) cudaEventDestroy(e);+ cudaSetDevice(prev);+ }+};} // namespacebool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {@@ -1101,6 +1318,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e(uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};PfTimer pt;+ PeTimer pe;+ if (m.pp) pe.dev = m.pp->dev; else pe.on = false;const cudaStream_t cs = (cudaStream_t) m.cs;// the MMQ row table lives in the borrowed cache slots, which the refill after a prompt overwrites with experts:// write it again for every prompt (a layout is reused as long as the chunk and the slots are the same)@@ -1248,6 +1467,31 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e// `used` event recorded), so the copy stream never waits on an event that is not queued yetconst strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout();const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr;+ const bool ps_on = stream_all && m.pp && m.pp->ps_frac > 0.0;+ if (m.pp && !ps_on) m.pp->ps_flag.clear();+ // multi-GPU: the peer's ring - issue its copies up to `limit` / give entries back (the peer device is current)+ auto p_issue_until = [&](size_t limit) {+ PeerPrefill& P = *m.pp;+ limit = std::min(limit, P.pseq.size());+ while (P.p_issued < limit) {+ const PeerPrefill::PsEntry& en = P.pseq[P.p_issued];+ const size_t sl = P.p_issued % (size_t) P.RP;+ if (P.plive[sl]) cudaStreamWaitEvent(P.s_cp, P.pused[sl], 0);+ cudaMemcpyAsync(P.pstage[sl], en.blob, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(en.l),+ cudaMemcpyHostToDevice, P.s_cp);+ cudaEventRecord(P.pcopied[sl], P.s_cp);+ P.plive[sl] = 1;+ ++P.p_issued;+ }+ };+ auto p_release_to = [&](int64_t l, int32_t e_stop, cudaStream_t ps) {+ PeerPrefill& P = *m.pp;+ while (P.pk < P.pseq_start[(size_t) l + 1] && P.pseq[P.pk].e < e_stop) {+ cudaEventRecord(P.pused[P.pk % (size_t) P.RP], ps);+ ++P.pk;+ p_issue_until(P.pk + (size_t) P.RP);+ }+ };struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; };std::vector<StreamEntry> seq;std::vector<size_t> seq_start;@@ -1255,10 +1499,19 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& eif (stream_all) {seq_start.assign((size_t) g.n_layers + 1, 0);std::vector<Stager::Job> js;+ if (ps_on) {+ m.pp->pseq.clear();+ m.pp->pseq_start.assign((size_t) g.n_layers + 1, 0);+ m.pp->ps_flag.assign((size_t) g.n_layers * m.g->n_expert, 0);+ m.pp->p_issued = m.pp->pk = 0;+ }+ double ps_acc = 0.0;for (int64_t l = LB; l < LE; ++l) {seq_start[(size_t) l] = seq.size();+ if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();for (int32_t e = 0; e < m.g->n_expert; ++e) {if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;+ if (m.pp && m.pp->peer->has(l, e)) continue; // multi-GPU: computed on (or read from) the peerint job = -1;const uint8_t* b = nullptr;if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer@@ -1267,6 +1520,15 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e} else {b = m.src->blob(l, e);if (!b) { err = "prefill: expert source has no blob"; return false; }+ if (ps_on && m.src->pinned(l, e)) { // multi-GPU: every ps_frac-th one goes to the peer's ring+ ps_acc += m.pp->ps_frac;+ if (ps_acc >= 1.0) {+ ps_acc -= 1.0;+ m.pp->pseq.push_back({(int32_t) l, e, b});+ m.pp->ps_flag[(size_t) l * m.g->n_expert + e] = 1;+ continue;+ }+ }if (!m.src->pinned(l, e)) {job = (int) js.size();js.push_back({b, (size_t) lay0.blob_bytes(l)});@@ -1275,7 +1537,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& eseq.push_back({(int32_t) l, e, b, job});}}- for (int64_t l = LE; l <= g.n_layers; ++l) seq_start[(size_t) l] = seq.size();+ for (int64_t l = LE; l <= g.n_layers; ++l) {+ seq_start[(size_t) l] = seq.size();+ if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();+ }m.stager->start(std::move(js));}struct StagerDone {@@ -1364,6 +1629,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& eif (threaded_issue) a_consumed.store(upto, std::memory_order_release);else issue_until(upto + (size_t) m.ring);};+ if (ps_on) {+ int pd = 0;+ cudaGetDevice(&pd);+ cudaSetDevice(m.pp->dev);+ p_issue_until((size_t) m.pp->RP);+ cudaSetDevice(pd);+ }host_setup_ms += ms_since(tsetup);bool normed = false; // F-2: the previous half's write already normed R for this half (grs, xn16)for (int64_t l = LB; l < LE; ++l) {@@ -1697,9 +1969,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& econst bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42;const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;- const bool fused_nat = use_mmq && stream_all && lay.native && fused::native_supported(mmq_gt, mmq_dt);- const bool fused_l = (use_mmq && stream_all && !lay.native && fused::enabled()) || fused_nat;+ const bool fused_nat = use_mmq && stream_all && !m.pp && lay.native && fused::native_supported(mmq_gt, mmq_dt);+ const bool fused_l = (use_mmq && stream_all && !m.pp && !lay.native && fused::enabled()) || fused_nat;size_t n_order = 0; // the routed experts (the debug report; unknown when fused)+ bool peer_now = false; // multi-GPU: the peer computed rows of this layer (MMQ path only)if (fused_l) {if (static bool said = false; !said) {said = true;@@ -1771,14 +2044,47 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& eelse cudaMemcpyAsync(m.ids_host.data(), m.ids, (size_t) T * K * 4, cudaMemcpyDeviceToHost, m.cs);cudaStreamSynchronize(m.cs);pt.fold();+ if (pe.on) { // the peer's marks so far are done: the primary waited for its last rows+ int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd);+ }std::fill(m.cnt.begin(), m.cnt.end(), 0);for (int64_t i = 0; i < T * K; ++i) {const int32_t e = ids_h[(size_t) i];if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; }++m.cnt[(size_t) e];}- m.off[0] = 0;- for (int64_t e = 0; e < m.g->n_expert; ++e) m.off[(size_t) e + 1] = m.off[(size_t) e] + m.cnt[(size_t) e];+ // multi-GPU: the rows of the experts the peer computes go last, as one block [rows_local, T*K)+ const bool pre_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];+ std::vector<char> on_peer;+ int64_t rows_local = T * K, rows_peer = 0;+ if (m.pp && pre_mmq) {+ on_peer.assign((size_t) m.g->n_expert, 0);+ for (int32_t e = 0; e < m.g->n_expert; ++e) {+ const int32_t c = m.cnt[(size_t) e];+ if (c > 0 && !m.pp->ps_flag.empty() && m.pp->ps_flag[(size_t) l * m.g->n_expert + e]) { // peer-streamed+ on_peer[(size_t) e] = 2;+ rows_peer += c;+ continue;+ }+ if (c == 0 || (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) ||+ !m.pp->peer->has(l, e))+ continue;+ if (rows_peer + c > m.pp->cap_rows) { ++m.pp->over_cap; continue; }+ on_peer[(size_t) e] = 1;+ rows_peer += c;+ }+ rows_local = T * K - rows_peer;+ }+ {+ int32_t r = 0;+ for (int32_t e = 0; e < m.g->n_expert; ++e)+ if (on_peer.empty() || !on_peer[(size_t) e]) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; }+ // the peer's rows in order_peer's order (peer-held, then peer-streamed): its groups need them contiguous+ for (int kind = 1; kind <= 2 && !on_peer.empty(); ++kind)+ for (int32_t e = 0; e < m.g->n_expert; ++e)+ if (on_peer[(size_t) e] == kind) { m.off[(size_t) e] = r; r += m.cnt[(size_t) e]; }+ m.off[(size_t) m.g->n_expert] = r;+ }std::vector<int32_t> fill(m.off.begin(), m.off.end() - 1);for (int64_t i = 0; i < T * K; ++i) {const int32_t e = ids_h[(size_t) i];@@ -1794,8 +2100,12 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& ecudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);}// the experts, in id order: resident ones from VRAM, the others through the staging ring- std::vector<int32_t> order;- for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);+ std::vector<int32_t> order, order_peer;+ for (int32_t e = 0; e < m.g->n_expert; ++e)+ if (m.cnt[(size_t) e] > 0 && (on_peer.empty() || on_peer[(size_t) e] != 2))+ (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e);+ for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e) // the peer-streamed ones last:+ if (on_peer[(size_t) e] == 2) order_peer.push_back(e); // their copies get the most timen_order = order.size();const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;@@ -1808,7 +2118,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& econst size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]];- m.bounds_host[n] = (int32_t) (T * K);+ m.bounds_host[n] = (int32_t) rows_local;for (size_t g = 0; g < ng; ++g)for (size_t i = 0; i <= MMQ_GROUP; ++i)m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] =@@ -1824,6 +2134,182 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e} else {gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);}+ // multi-GPU: the peer's share, enqueued before the primary's own experts so both cards work at once+ peer_now = use_mmq && !order_peer.empty();+ if (peer_now) {+ PeerPrefill& P = *m.pp;+ cudaEventRecord(P.ev_in, m.cs);+ int prevd = 0;+ cudaGetDevice(&prevd);+ cudaSetDevice(P.dev);+ const cudaStream_t ps = P.s;+ cudaStreamWaitEvent(ps, P.ev_in, 0);+ if (P.out_pending) { cudaStreamWaitEvent(ps, P.ev_done, 0); P.out_pending = false; }+ pe.mark(kPeMoeIn, ps);+ cudaMemcpyPeerAsync(P.mixed, P.dev, m.mixed, prevd, (size_t) T * N * 4, ps);+ cudaMemcpyAsync(P.src, src_h + rows_local, // multi-GPU: the mapped table when on+ (size_t) rows_peer * 4, cudaMemcpyHostToDevice, ps);+ const size_t n = order_peer.size();+ if (P.compact) {+ // groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows+ P.groups.clear();+ {+ size_t g0 = 0;+ int64_t gr = 0;+ for (size_t j = 0; j < n; ++j) {+ const int64_t c = m.cnt[(size_t) order_peer[j]];+ if (j > g0 && (j - g0 == (size_t) MMQ_GROUP || gr + c > P.G)) { P.groups.push_back({g0, j}); g0 = j; gr = 0; }+ gr += c;+ }+ if (n > g0) P.groups.push_back({g0, n});+ }+ const size_t ng = P.groups.size();+ P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));+ for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) rows_local;+ P.bounds_host[n] = (int32_t) rows_peer;+ for (size_t g2 = 0; g2 < ng; ++g2)+ for (size_t i = 0; i <= MMQ_GROUP; ++i)+ P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =+ P.bounds_host[std::min(P.groups[g2].second, P.groups[g2].first + i)] -+ P.bounds_host[P.groups[g2].first];+ cudaMemcpyAsync(P.bounds, P.bounds_host.data(), P.bounds_host.size() * 4, cudaMemcpyHostToDevice, ps);+ pe.mark(kPeMoeGemm, ps);+ const auto& f = lay.fmt[(size_t) l];+ for (size_t g2 = 0; g2 < ng; ++g2) {+ const size_t j0 = P.groups[g2].first, j1 = P.groups[g2].second;+ const int ngx = (int) (j1 - j0);+ int64_t maxr = 0;+ for (size_t j = j0; j < j1; ++j) {+ const int32_t e = order_peer[j];+ maxr = std::max<int64_t>(maxr, m.cnt[(size_t) e]);+ const uint8_t* bd = nullptr;+ int psl = -1;+ if (on_peer[(size_t) e] == 2) { // from the peer's ring+ p_release_to(l, e, ps);+ if (P.pk >= P.pseq_start[(size_t) l + 1] || P.pseq[P.pk].e != e) {+ err = "prefill: a peer-streamed expert is not next in the peer's ring";+ cudaSetDevice(prevd);+ return false;+ }+ psl = (int) (P.pk % (size_t) P.RP);+ cudaStreamWaitEvent(ps, P.pcopied[(size_t) psl], 0);+ bd = P.pstage[(size_t) psl];+ ++P.ps_experts;+ } else {+ bd = P.peer->slot_ptr(l, e);+ }+ const size_t q = j - j0;+ if (lay.native)+ mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db,+ P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);+ else+ mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);+ if (psl >= 0) { // the slot is free once gathered+ cudaEventRecord(P.pused[(size_t) psl], ps);+ ++P.pk;+ p_issue_until(P.pk + (size_t) P.RP);+ }+ }+ const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j1] - r0;+ if (nr <= 0) continue;+ const int32_t* rel = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);+ cudaMemsetAsync(P.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, ps);+ cudaMemsetAsync(P.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, ps);+ mmq::quantize(P.mixed, P.src + r0, P.Xq_g, mmq_gt, N, N, nr, ps);+ mmq::Product gu;+ gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;+ gu.n = ngx; gu.xq = P.Xq_g; gu.bounds = rel; gu.ids = P.ident;+ gu.total_rows = nr; gu.max_rows = maxr; gu.dst = P.GU_g; gu.ld_dst = 1280;+ P.ctx->run(gu, ps);+ mmq::swiglu(P.GU_g, P.H_g, nr, 640, !lay.native, ps);+ mmq::quantize(P.H_g, nullptr, P.Hq_g, mmq_dt, 640, 640, nr, ps);+ const int b = (int) (g2 & 1);+ if (P.dm_live[b]) cudaStreamWaitEvent(ps, P.ev_dm[b], 0); // its last rows have left+ mmq::Product dn;+ dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;+ dn.n = ngx; dn.xq = P.Hq_g; dn.bounds = rel;+ dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm_b[b];+ dn.ld_dst = N;+ P.ctx->run(dn, ps);+ cudaEventRecord(P.ev_grp[g2 % PeerPrefill::kGrpEv], ps);+ cudaStreamWaitEvent(P.s_out, P.ev_grp[g2 % PeerPrefill::kGrpEv], 0);+ cudaMemcpyPeerAsync(m.Dm + (size_t) (rows_local + r0) * N, prevd, P.Dm_b[b], P.dev,+ (size_t) nr * N * 4, P.s_out);+ cudaEventRecord(P.ev_dm[b], P.s_out);+ P.dm_live[b] = true;+ }+ } else {+ const size_t ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;+ P.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));+ for (size_t j = 0; j < n; ++j) P.bounds_host[j] = m.off[(size_t) order_peer[j]] - (int32_t) rows_local;+ P.bounds_host[n] = (int32_t) rows_peer;+ for (size_t g2 = 0; g2 < ng; ++g2)+ for (size_t i = 0; i <= MMQ_GROUP; ++i)+ P.bounds_host[n + 1 + g2 * (MMQ_GROUP + 1) + i] =+ P.bounds_host[std::min(n, g2 * MMQ_GROUP + i)] - P.bounds_host[g2 * MMQ_GROUP];+ cudaMemcpyAsync(P.bounds, P.bounds_host.data(), P.bounds_host.size() * 4, cudaMemcpyHostToDevice, ps);+ mmq::quantize(P.mixed, P.src, P.Xq, mmq_gt, N, N, rows_peer, ps);+ pe.mark(kPeMoeGemm, ps);+ const auto& f = lay.fmt[(size_t) l];+ for (size_t j = 0; j < n; ++j) {+ const int32_t e = order_peer[j];+ const uint8_t* bd = P.peer->slot_ptr(l, e);+ const size_t q = j % MMQ_GROUP;+ if (lay.native)+ mmq::gather_native(bd, bd + f.up_off, mmq_gub / 2, bd + f.down_off, mmq_db,+ P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);+ else+ mmq::gather_strata_q2(bd, P.grp_gu + q * mmq_gub, P.grp_d + q * mmq_db, ps);+ if (q + 1 < MMQ_GROUP && j + 1 < n) continue;+ const size_t j0 = j - q, g2 = j0 / MMQ_GROUP;+ const int ngx = (int) (q + 1);+ const int64_t r0 = P.bounds_host[j0], nr = P.bounds_host[j + 1] - r0;+ int64_t maxr = 0;+ for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order_peer[i]]);+ cudaMemsetAsync(P.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, ps);+ cudaMemsetAsync(P.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, ps);+ mmq::Product gu;+ gu.w = P.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub;+ gu.n = ngx; gu.xq = P.Xq; gu.bounds = P.bounds + j0; gu.ids = P.ident;+ gu.total_rows = rows_peer; gu.max_rows = maxr; gu.dst = P.GU; gu.ld_dst = 1280;+ P.ctx->run(gu, ps);+ mmq::swiglu(P.GU + r0 * 1280, P.H + r0 * 640, nr, 640, !lay.native, ps);+ mmq::quantize(P.H + r0 * 640, nullptr, P.Hq, mmq_dt, 640, 640, nr, ps);+ mmq::Product dn;+ dn.w = P.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db;+ dn.n = ngx; dn.xq = P.Hq; dn.bounds = P.bounds + n + 1 + g2 * (MMQ_GROUP + 1);+ dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm + r0 * N;+ dn.ld_dst = N;+ P.ctx->run(dn, ps);+ if (P.out_pipe && nr > 0) { // this group's rows go back while the next group computes+ cudaEventRecord(P.ev_grp[g2], ps);+ cudaStreamWaitEvent(P.s_out, P.ev_grp[g2], 0);+ cudaMemcpyPeerAsync(m.Dm + (size_t) (rows_local + r0) * N, prevd, P.Dm + (size_t) r0 * N,+ P.dev, (size_t) nr * N * 4, P.s_out);+ }+ }+ }+ pe.mark(kPeMoeOut, ps);+ if (P.out_pipe) {+ cudaEventRecord(P.ev_done, P.s_out);+ P.out_pending = true;+ } else {+ cudaMemcpyPeerAsync(m.Dm + (size_t) rows_local * N, prevd, P.Dm, P.dev, (size_t) rows_peer * N * 4, ps);+ cudaEventRecord(P.ev_done, ps);+ }+ pe.mark(kPeIdle, ps);+ cudaSetDevice(prevd);+ ++P.layers;+ P.experts += (int64_t) n;+ P.rows += rows_peer;+ }+ if (ps_on) { // multi-GPU: this layer's peer-ring entries the routing did not pick give their slots back+ int pd = 0;+ cudaGetDevice(&pd);+ cudaSetDevice(m.pp->dev);+ p_release_to(l, (int32_t) m.g->n_expert, m.pp->s);+ cudaSetDevice(pd);+ }// Stage ahead: the copy stream moves blobs host -> device while the compute stream works.int stage_next = 0;std::vector<int> stage_of(order.size(), -1);@@ -2032,8 +2518,12 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& econsumed = ++k;if (!group_gather || gg_nslots == 0) give_back(consumed); // its group was gathered} else {+ const bool r0 = m.host_res && m.cache && m.host_res[(size_t) l * NE + e] >= 0;+ const uint8_t* bp = r0 ? m.cache->device_slot(m.host_res[(size_t) l * NE + e])+ : (m.pp ? m.pp->peer->slot_ptr(l, e) : nullptr); // over the cap: P2P+ if (bp == nullptr) { err = "prefill: an expert is neither resident, streamed nor on the peer"; return false; }++stats_.experts_resident;- if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;+ if (!compute(j, bp, -1)) return false;if (group_gather && gg_nslots == 0) give_back(consumed);}}@@ -2041,6 +2531,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e}}pt.mark(kPfCombine, cs);+ if (peer_now) cudaStreamWaitEvent(m.cs, m.pp->ev_done, 0); // multi-GPU: the peer's rows are in Dmmoe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs);// debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite valuesif (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {@@ -2190,6 +2681,21 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& estd::fprintf(stderr, "strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, ""waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, ""PLE %.0f ms\n", host_setup_ms, host_sync_ms, host_chunk_ms, stats_.ms_ple);+ if (pe.on) {+ int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd);+ std::string pl;+ for (int i = 0; i < kPeCount; ++i) {+ std::snprintf(b, sizeof b, " %s %.0f", kPeNames[i], pe.ms[i]);+ pl += b;+ }+ std::fprintf(stderr, "strata prefill timing (peer GPU, ms):%s; MoE layers %lld, rows/layer %.0f of %lld cap, experts/layer %.0f, "+ "over the cap %lld\n", pl.c_str(), (long long) m.pp->layers,+ m.pp->layers ? (double) m.pp->rows / m.pp->layers : 0.0, (long long) m.pp->cap_rows,+ m.pp->layers ? (double) m.pp->experts / m.pp->layers : 0.0, (long long) m.pp->over_cap);+ if (m.pp->ps_frac > 0.0)+ std::fprintf(stderr, "strata prefill timing: peer-streamed experts %lld (%.0f per MoE layer)\n",+ (long long) m.pp->ps_experts, m.pp->layers ? (double) m.pp->ps_experts / m.pp->layers : 0.0);+ }}if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // debug: the GDN states as the prompt path leaves themcudaStreamSynchronize(m.cs);diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 05f88d8e4..942ddce1e 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -23,6 +23,7 @@#include "strata/core/pinned.hpp"#include "strata/core/remote_experts.hpp"#include "strata/core/on_device.hpp"+#include "strata/core/peer_experts.hpp"#include "strata/core/layer.hpp"#include "strata/core/layout.hpp"#include "strata/core/session.hpp"@@ -296,6 +297,16 @@ struct Options {/// to them. Measured at 256 slots: **1781 of 60000 = 2.97%**, against **21.4%** for 8 slots per layer and/// **70.4%** for 64, from `Memory/cache_allocation.py` on the same run's routing. Off by default.bool expert_cache_per_layer = false;+ /// Multi-GPU: a second expert tier on CUDA device `peer_device` (-1 = off), `peer_reserve_mib` left free+ /// there, `peer_slots` caps its size (0 = as many as fit), `peer_adapt_swaps` per adaptive round+ /// (-1 = adapt_swaps).+ int peer_device = -1;+ int peer_reserve_mib = 600;+ int64_t peer_slots = 0;+ int peer_adapt_swaps = -1;+ /// the prompt path's rows per layer the peer computes: -1 = half of chunk x top-k, 0 = the prompt path stays on+ /// the primary+ int64_t peer_prefill_rows = -1;/// The PLE gather's prefetch, as an A/B arm. The gather measured 2.10-2.61 ms/token because its sixteen/// row reads are sixteen SEPARATE page faults into a 26.8 GB mapping; see `ple_prefetch_enable`.bool no_ple_prefetch = false;@@ -1266,6 +1277,11 @@ int main(int argc, char** argv) {else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps"));else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true;else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true;+ else if (a == "--peer-device") o.peer_device = std::atoi(next("--peer-device"));+ else if (a == "--peer-reserve-mib") o.peer_reserve_mib = std::atoi(next("--peer-reserve-mib"));+ else if (a == "--peer-slots") o.peer_slots = std::atoll(next("--peer-slots"));+ else if (a == "--peer-adapt-swaps") o.peer_adapt_swaps = std::atoi(next("--peer-adapt-swaps"));+ else if (a == "--peer-prefill-rows") o.peer_prefill_rows = std::atoll(next("--peer-prefill-rows"));else if (a == "--no-hit-poke") o.no_hit_poke = true;else if (a == "--expert-profile") o.expert_profile = next("--expert-profile");else if (a == "--expert-profile-save") o.expert_profile_save = next("--expert-profile-save");@@ -1315,6 +1331,7 @@ int main(int argc, char** argv) {}}strata::core::set_coupled_draft(o.coupled_draft);+ strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation)if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0))std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n",o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0");@@ -2319,6 +2336,36 @@ int main(int argc, char** argv) {// file). `--expert-cache 0` used to take the count the profile was built for; the profile now ranks// every pair (issue #46: a card that holds more than the old 8,000 used to stop there), so it means auto.if (o.expert_cache == 0) o.expert_cache = -1;+ // Multi-GPU: STRATA_PEER_HOT=<f> gives the peer card a share f of the HOT pairs, so both cards+ // compute routed experts every layer (the primary alone did ~25 of ~30 per layer-window). Of the first+ // STRATA_PEER_HOT_AT (default 8700, ~ the primary's slots) ranks, every pair with floor((r+1)f) > floor(rf)+ // moves to just after that point: the primary fills past them, the peer (which takes what the primary does+ // not hold, in order) gets them first.+ if (o.peer_device >= 1) { // default 0.45 (measured: 0.3-0.6 all better than 0; 0 = off, e.g. for the gate)+ const char* ph = std::getenv("STRATA_PEER_HOT");+ const double f = ph ? std::atof(ph) : 0.45;+ const char* pa = std::getenv("STRATA_PEER_HOT_AT");+ const size_t at = std::min(profile.size(), (size_t) (pa ? std::atoll(pa) : 8700));+ if (f > 0.0 && f < 1.0 && at > 0) {+ std::vector<std::pair<int32_t, int32_t>> keep, moved;+ for (size_t r = 0; r < at; ++r) {+ const bool to_peer = (int64_t) ((double) (r + 1) * f) > (int64_t) ((double) r * f);+ (to_peer ? moved : keep).push_back(profile[r]);+ }+ const size_t n_moved = moved.size();+ // the primary's share continues with the ranks after `at` until it is full; then the moved ones+ std::vector<std::pair<int32_t, int32_t>> out;+ out.reserve(profile.size());+ out.insert(out.end(), keep.begin(), keep.end());+ const size_t fill = std::min(profile.size(), at + n_moved); // what the primary still takes+ out.insert(out.end(), profile.begin() + (long) at, profile.begin() + (long) fill);+ out.insert(out.end(), moved.begin(), moved.end());+ out.insert(out.end(), profile.begin() + (long) fill, profile.end());+ profile.swap(out);+ std::fprintf(stderr, "strata generate: STRATA_PEER_HOT %.2f: %zu of the first %zu ranked pairs moved "+ "behind rank %zu (the peer's)\n", f, n_moved, at, fill);+ }+ }std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n",o.expert_profile.c_str(), profile.size(), (long long) pslots);}@@ -3106,9 +3153,29 @@ int main(int argc, char** argv) {}}+ // ---- Multi-GPU: the second GPU's expert tier, filled with the ranked pairs the primary does not hold+ strata::core::PeerExperts peer;+ if (o.peer_device >= 1) {+ if (profile.empty() || srcp == nullptr || o.expert_cache <= 0) {+ std::fprintf(stderr, "strata generate: --peer-device needs --expert-profile and the expert cache\n");+ return 1;+ }+ const auto tp0 = Clock::now();+ if (!peer.open(o.peer_device, profile, xcache, *srcp, g.n_layers, g.n_expert, o.peer_reserve_mib, o.peer_slots,+ err)) {+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());+ return 1;+ }+ std::fprintf(stderr, "strata generate: peer GPU %d: %lld experts, %.2f GiB (filled in %.1f s); with the primary's "+ "%lld that is %lld of %lld on the GPUs\n", o.peer_device, (long long) peer.resident(), peer.gib(),+ std::chrono::duration<double>(Clock::now() - tp0).count(), (long long) xcache.slots(),+ (long long) (peer.resident() + xcache.slots()), (long long) (g.n_layers * g.n_expert));+ }+Drive drive;for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r];+ drive.d.peer = peer.valid() ? &peer : nullptr;drive.d.hit_cpu_order = o.expert_cache_cpu_order;drive.d.split_rows = !o.no_split_rows;drive.d.pool = &pool;@@ -4230,6 +4297,13 @@ int main(int argc, char** argv) {"context, or read prompts in smaller chunks (--prefill 512)\n");return 1;}+ if (peer.valid() && o.peer_prefill_rows != 0) {+ const int64_t rows = o.peer_prefill_rows > 0 ? o.peer_prefill_rows : o.prefill_chunk * K / 2;+ if (!sp.set_peer(&peer, rows, err)) {+ std::fprintf(stderr, "strata serve: %s - the prompt path stays on the primary GPU\n", err.c_str());+ err.clear();+ }+ }mem_mark("the head and the prompt path");// #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an// S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache):@@ -4604,6 +4678,7 @@ int main(int argc, char** argv) {}};auto apply_pending = [&](bool wait) {+ if (peer.valid()) peer.apply_pending(wait);if (pending.empty()) return;if (wait) cudaEventSynchronize(adapt_ev);else if (cudaEventQuery(adapt_ev) != cudaSuccess) return;@@ -4630,7 +4705,7 @@ int main(int argc, char** argv) {const float* u = drive.d.usage.data() + l * g.n_expert;const int32_t* r = host_res.data() + l * g.n_expert;for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {- if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); }+ if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e))) cand.emplace_back(u[e], e); }else vict.emplace_back(u[e], e);}if (cand.empty() || vict.empty()) continue;@@ -4675,6 +4750,16 @@ int main(int argc, char** argv) {// decays: the sum is proportional to the routing itself) - only with --expert-profile-save, else `heat`// is emptyfor (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i];+ if (peer.valid()) { // multi-GPU: the peer takes the next most-routed CPU misses+ std::vector<int32_t> r0 = host_res;+ for (const auto& [i, slot] : pending) r0[(size_t) i] = slot; // swapped into the primary already+ std::string perr;+ if (!peer.adapt(drive.d.usage.data(), r0.data(),+ o.peer_adapt_swaps >= 0 ? o.peer_adapt_swaps : o.adapt_swaps, perr)) {+ std::fprintf(stderr, "strata serve: %s\n", perr.c_str());+ return false;+ }+ }for (float& v : drive.d.usage) v *= o.adapt_decay;return true;};