diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index bb8fe2806..aff2e631d 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -11,7 +11,7 @@ A number or a word is set like any environment variable, for example `STRATA_KVA (`terminal/strata-.json`), which the server passes to the engine. The Strata project's Terminal writes it there with `strata launch --set NAME=value`. -## Switches you can turn on (347) +## Switches you can turn on (349) Off unless you set them. The last column says where each one is described. @@ -211,6 +211,8 @@ Off unless you set them. The last column says where each one is described. | `STRATA_PCIE_FRAC_DEFAULT` | on / off | NVIDIA and AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md), [DETAILS.md](DETAILS.md), [README.md](bench-results/2026-10-20-0.2.1-idle-gpu/README.md) | | `STRATA_PCIE_K_RULE` | text | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | | `STRATA_PCIE_MIN1` | number | NVIDIA and AMD | [README.md](bench-results/2026-10-11-community-rtx3090-5600x-arena-pin-by-need/README.md) | +| `STRATA_PEER_AUTONOMOUS` | number | NVIDIA and AMD | - | +| `STRATA_PEER_DIRECT_SIGNAL` | number | NVIDIA and AMD | - | | `STRATA_PEER_HEAD_SPLIT` | text | NVIDIA | [NVIDIA_V100.md](NVIDIA_V100.md) | | `STRATA_PEER_NO_P2P` | number | NVIDIA and AMD | [SECOND_GPU.md](SECOND_GPU.md) | | `STRATA_PENALTY_PROMPT` | on / off | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md) | diff --git a/engine/include/strata/core/expert_source.hpp b/engine/include/strata/core/expert_source.hpp index 66c13c797..aa260e84e 100644 --- a/engine/include/strata/core/expert_source.hpp +++ b/engine/include/strata/core/expert_source.hpp @@ -418,6 +418,8 @@ struct GpuPlanSink { int32_t cpu_jobs = 0; ///< host only: the distinct experts the pool computes for the layer just published float* hit_out_dev = nullptr; ///< device address of this group's hit_out buffer on the primary GPU (P2P peer scatter) bool device_hits_only = false; ///< STRATA_VERIFY_DEVICE_HITS=1: GPU built its own hit plan; host only marks kind[] + uint32_t want_flag = 0; ///< direct GPU-to-GPU: flag value to signal upon peer completion + bool peer_signals_flag = false; ///< direct GPU-to-GPU: set when peer GPU directly signals the flag over PCIe }; /// Verifier::set_pcie_balance: a verify window's costs, fitted to each layer's measured times (ms, least squares with diff --git a/engine/include/strata/core/peer_experts.hpp b/engine/include/strata/core/peer_experts.hpp index a21543687..d9a477c89 100644 --- a/engine/include/strata/core/peer_experts.hpp +++ b/engine/include/strata/core/peer_experts.hpp @@ -33,6 +33,15 @@ namespace strata::core { void set_peer_portable(bool on); bool peer_portable(); +struct PeerPlanDevice { + unsigned long long ptr[64]; + int32_t start[68]; + int32_t count[4]; + int32_t dst[64]; + int32_t tok[64]; + int32_t out_row[64]; +}; + class PeerExperts { public: PeerExperts() = default; @@ -64,7 +73,7 @@ class PeerExperts { /// 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); + std::string& err, float* out = nullptr, uint32_t want_flag = 0); /// 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); @@ -92,6 +101,13 @@ class PeerExperts { /// whether a launch given host rows writes them itself (STRATA_PEER_DIRECT, default on): then the caller need not /// zero a peer row at all, whether the launch has happened yet or not static bool direct_mode(); + void set_target_flag(volatile uint32_t* h_flag); + bool signaled_target_flag() const { return signaled_target_flag_; } + bool bind_verifier_buffers(int par, volatile uint32_t* h_seq, volatile uint32_t* h_flag, + const float* h_x, const int32_t* h_ids, float* h_ymiss); + bool launch_window(int par, int64_t lb, int64_t le, int T, int k, uint32_t want_flag_start, int G = 1); + bool autonomous() const { return autonomous_; } + void set_autonomous(bool on) { autonomous_ = on; } 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 @@ -131,7 +147,20 @@ class PeerExperts { volatile uint32_t* h_done_seq_ = nullptr; uint32_t* d_done_seq_ = nullptr; int* d_blocks_finished_ = nullptr; + volatile uint32_t* h_target_flag_ = nullptr; + uint32_t* d_target_flag_ = nullptr; + bool signaled_target_flag_ = false; uint32_t seq_ = 0; + bool autonomous_ = false; + uint32_t* d_seq_[2] = {nullptr, nullptr}; + uint32_t* d_target_flag_p_[2] = {nullptr, nullptr}; + const float* d_m_x_[2] = {nullptr, nullptr}; + const int32_t* d_m_ids_[2] = {nullptr, nullptr}; + float* d_m_ymiss_[2] = {nullptr, nullptr}; + int32_t* d_res_peer_ = nullptr; + unsigned long long* d_slot_off_peer_ = nullptr; + PeerPlanDevice* d_plans_ = nullptr; + int* d_blocks_finished_arr_ = nullptr; }; } // namespace strata::core diff --git a/engine/include/strata/core/verify.hpp b/engine/include/strata/core/verify.hpp index b142101ec..b8aa2fb01 100644 --- a/engine/include/strata/core/verify.hpp +++ b/engine/include/strata/core/verify.hpp @@ -43,6 +43,8 @@ namespace strata::core { +class PeerExperts; + /// 0.1.43 (STRATA_ADAPT_OVERLAP): the adaptive tier's copies still landing while a decode window runs. The window's /// residency tables are the baseline's (the swapped-in experts are resident from the window's first layer), but their /// bytes arrive layer by layer: `run` holds a layer's plan (the first thing that lets the GPU read the layer's expert @@ -100,6 +102,12 @@ class Verifier { Verifier(const Verifier&) = delete; Verifier& operator=(const Verifier&) = delete; void set_remote_expert_opt(RemoteExpertOpt* opt) { remote_opt_ = opt; } // before init/capture + uint32_t* h_seq() const { return h_seq_; } + float* h_x() const { return h_x_; } + int32_t* h_ids() const { return h_ids_; } + float* h_ymiss() const { return h_ymiss_; } + void set_peer(PeerExperts* peer, int parity = 0); + bool peer_autonomous() const { return peer_autonomous_; } /// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags. void diag(std::FILE* f) const; @@ -421,6 +429,7 @@ class Verifier { /// The GPU plan the pool writes each layer (VRAM hits + the PCIe share of the misses); give it to the /// dispatch (`ExpertDispatch::plan`) before the first `run`. GpuPlanSink* plan_sink() { return &sink_; } + uint32_t* h_flag() const { return h_flag_; } /// Plan v0.3 P6: split the window into two token groups and pipeline the CPU experts of one with the GPU work /// of the other (default on). Set before the first `run`. void set_split(bool on) { split_ = on; } @@ -771,6 +780,9 @@ class Verifier { std::function pre_launch_; // set_pre_launch int groups_[strata::kernels::kVerifyLongT + 1] = {}; float* h_ymiss_ = nullptr; float* m_ymiss_ = nullptr; // T * k * n_embd + PeerExperts* peer_ = nullptr; + int parity_ = 0; + bool peer_autonomous_ = false; // device void* arena_ = nullptr; diff --git a/engine/include/strata/kernels/elementwise.hpp b/engine/include/strata/kernels/elementwise.hpp index 9ca1c831a..734be4714 100644 --- a/engine/include/strata/kernels/elementwise.hpp +++ b/engine/include/strata/kernels/elementwise.hpp @@ -107,7 +107,16 @@ void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream); /// 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 scatter_rows_and_signal_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, - uint32_t* d_done_ptr, uint32_t val, int* d_blocks_finished, void* stream); + uint32_t* d_done_ptr, uint32_t val, int* d_blocks_finished, void* stream, + uint32_t* d_flag_ptr = nullptr, uint32_t flag_val = 0); +void scatter_rows_and_signal_fixed_f32(const float* src, float* dst, const int32_t* rows, + const int32_t* d_count, int64_t cap_entries, int64_t width, + int* d_blocks_finished, void* stream, + uint32_t* d_flag_ptr, uint32_t flag_val); +void peer_plan(const int32_t* ids, int n, int k, const int32_t* res, int n_expert, + const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, + unsigned long long* grp_ptr, int32_t* grp_start, int32_t* grp_count, + int32_t* grp_dst, int32_t* grp_tok, int32_t* grp_out_row, void* stream); void signal_stream_done(uint32_t* d_ptr, uint32_t val, 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/engine/include/strata/kernels/verify_kernels.hpp b/engine/include/strata/kernels/verify_kernels.hpp index 319c1322e..fd375a79a 100644 --- a/engine/include/strata/kernels/verify_kernels.hpp +++ b/engine/include/strata/kernels/verify_kernels.hpp @@ -138,7 +138,8 @@ void copy_rows_strided(float* dst, const float* src, int64_t rows, int64_t w, in /// left empty and *plan_err (mapped host memory) is set to 1, so the host sees it instead of running a stale plan. void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err = nullptr); + long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err = nullptr, + bool allow_partial = false); /// Partial-VRAM on-device hit plan (`STRATA_VERIFY_DEVICE_HITS=1`, `--pcie-frac 0`, CUDA / HIP): groups only the /// resident routed experts (`res_layer[e] >= 0`) in first-occurrence routing order into `plan` (`counts = {hit_groups, /// hit_entries, 0}`), matching `expert_pool_dispatch_multi` when `fetches == 0` without waiting on `m_flagA_`/`m_flagB_`. diff --git a/engine/src/core/expert_source.cpp b/engine/src/core/expert_source.cpp index 73e3bc3dd..7d4271d5f 100644 --- a/engine/src/core/expert_source.cpp +++ b/engine/src/core/expert_source.cpp @@ -5702,18 +5702,38 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 : (e >= 0 && e < d.n_expert && d.peer != nullptr && d.peer->has(d.layers, e)) ? 2 : -1; } } + static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); + // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN / + // STRATA_VERIFY_DEVICE_HITS's copy_or_zero_from_mapped copies every row, so there the host still zeroes them + static const bool device_plan = [] { + const char* p = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); + const char* h = std::getenv("STRATA_VERIFY_DEVICE_HITS"); + return (p != nullptr && std::atoi(p) != 0) || (h != nullptr && std::atoi(h) != 0); + }(); + const bool gpu_zeroes_hits = (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap && dec_batch && !device_plan); + bool any_cpu = false; + bool any_tail = false; + for (int64_t i = 0; i < n; ++i) { + if (kind[i] == -1) any_cpu = true; // -2: skipped (STRATA_ROUTE_TAIL_SKIP), host zeroes row below + else if (kind[i] == -2) any_tail = true; + } + const bool can_peer_signal = (!any_cpu && !any_tail && gpu_zeroes_hits && d.remote_count == 0 && d.plan != nullptr && d.plan->want_flag > 0); + const uint32_t peer_want = can_peer_signal ? d.plan->want_flag : 0; if (d.peer != nullptr) { // multi-GPU: start the second GPU's share before the CPU's own work std::string perr; float* peer_out = (d.plan != nullptr && d.peer->p2p() && d.plan->hit_out_dev != nullptr && d.peer->direct_mode()) ? d.plan->hit_out_dev : out; - if (!d.peer->launch(d.layers, x_f, ids, n_tok, k, kind, perr, peer_out)) { + if (!d.peer->launch(d.layers, x_f, ids, n_tok, k, kind, perr, peer_out, peer_want)) { 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.plan != nullptr && d.peer->signaled_target_flag()) { + d.plan->peer_signals_flag = true; + } } if (d.remote_count > 0) { static thread_local std::string remote_error; @@ -5724,18 +5744,6 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2; } } - static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); - // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN / - // STRATA_VERIFY_DEVICE_HITS's copy_or_zero_from_mapped copies every row, so there the host still zeroes them - static const bool device_plan = [] { - const char* p = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); - const char* h = std::getenv("STRATA_VERIFY_DEVICE_HITS"); - return (p != nullptr && std::atoi(p) != 0) || (h != nullptr && std::atoi(h) != 0); - }(); - const bool gpu_zeroes_hits = (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap && dec_batch && !device_plan); - bool any_cpu = false; - for (int64_t i = 0; i < n; ++i) - if (kind[i] == -1) { any_cpu = true; break; } // -2: skipped (STRATA_ROUTE_TAIL_SKIP), no work if (d.dres_check != nullptr && any_cpu) { // STRATA_ADAPT_CHECKRES bool published = false; for (int64_t i = 0; i < n && !published; ++i) diff --git a/engine/src/core/peer_experts.cpp b/engine/src/core/peer_experts.cpp index 1948d2538..dd918871d 100644 --- a/engine/src/core/peer_experts.cpp +++ b/engine/src/core/peer_experts.cpp @@ -8,6 +8,7 @@ #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/verify_kernels.hpp" #include "strata/kernels/window_limits.hpp" #include @@ -179,6 +180,10 @@ void PeerExperts::close() { if (d_gate_vals_) cudaFree(d_gate_vals_); if (h_gate_) cudaFreeHost((void*) h_gate_); if (h_done_seq_) cudaFreeHost((void*) h_done_seq_); + if (d_res_peer_) cudaFree(d_res_peer_); + if (d_slot_off_peer_) cudaFree(d_slot_off_peer_); + if (d_plans_) cudaFree(d_plans_); + if (d_blocks_finished_arr_) cudaFree(d_blocks_finished_arr_); if (refill_ev_) cudaEventDestroy(refill_ev_); if (stream_) cudaStreamDestroy(stream_); if (refill_) cudaStreamDestroy(refill_); @@ -192,6 +197,21 @@ void PeerExperts::close() { h_done_seq_ = nullptr; d_done_seq_ = nullptr; d_blocks_finished_ = nullptr; + d_res_peer_ = nullptr; + d_slot_off_peer_ = nullptr; + d_plans_ = nullptr; + d_blocks_finished_arr_ = nullptr; + for (int i = 0; i < 2; ++i) { + d_seq_[i] = nullptr; + d_target_flag_p_[i] = nullptr; + d_m_x_[i] = nullptr; + d_m_ids_[i] = nullptr; + d_m_ymiss_[i] = nullptr; + } + h_target_flag_ = nullptr; + d_target_flag_ = nullptr; + signaled_target_flag_ = false; + autonomous_ = false; seq_ = 0; stream_ = refill_ = nullptr; refill_ev_ = nullptr; @@ -331,6 +351,31 @@ bool PeerExperts::open(int device, const std::vector return false; } resident_ = (int64_t) pick.size(); + static const bool auto_env = [] { + const char* e = std::getenv("STRATA_PEER_AUTONOMOUS"); + return e != nullptr && std::atoi(e) != 0; + }(); + if (auto_env && direct_mode()) { + if (cudaMalloc((void**) &d_res_peer_, res_.size() * sizeof(int32_t)) == cudaSuccess) { + cudaMemcpy(d_res_peer_, res_.data(), res_.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + } + if (cache_.slot_offsets() != nullptr) { + size_t n_slots = (size_t) cache_.slots(); + if (cudaMalloc((void**) &d_slot_off_peer_, (n_slots + 1) * sizeof(unsigned long long)) == cudaSuccess) { + cudaMemcpy(d_slot_off_peer_, cache_.slot_offsets(), (n_slots + 1) * sizeof(unsigned long long), cudaMemcpyHostToDevice); + } + } + cudaMalloc((void**) &d_plans_, 256 * sizeof(PeerPlanDevice)); + cudaMalloc((void**) &d_blocks_finished_arr_, 256 * sizeof(int)); + cudaMemset(d_blocks_finished_arr_, 0, 256 * sizeof(int)); + autonomous_ = (d_res_peer_ != nullptr && d_plans_ != nullptr && d_blocks_finished_arr_ != nullptr); + } else { + autonomous_ = false; + } + if (auto_env) { + std::fprintf(stderr, "strata peer: autonomous mode %s (p2p=%d, direct=%d)\n", + autonomous_ ? "ENABLED" : "disabled", (int) p2p_, (int) direct_mode()); + } return true; } @@ -339,8 +384,111 @@ bool PeerExperts::direct_mode() { return v; } +void PeerExperts::set_target_flag(volatile uint32_t* h_flag) { + h_target_flag_ = h_flag; + d_target_flag_ = nullptr; + if (h_flag != nullptr && device_ >= 0) { + On on(device_); + cudaError_t e = cudaHostGetDevicePointer((void**) &d_target_flag_, (void*) h_flag, 0); + if (e != cudaSuccess) { + std::fprintf(stderr, "strata peer: cudaHostGetDevicePointer failed for target flag: %s\n", + cudaGetErrorString(e)); + (void) cudaGetLastError(); + d_target_flag_ = nullptr; + } else { + std::fprintf(stderr, "strata peer: direct hardware flag handoff enabled (d_target_flag_=%p)\n", + (void*) d_target_flag_); + } + } +} + +bool PeerExperts::bind_verifier_buffers(int par, volatile uint32_t* h_seq, volatile uint32_t* h_flag, + const float* h_x, const int32_t* h_ids, float* h_ymiss) { + if (device_ < 0 || par < 0 || par >= 2) return false; + On on(device_); + bool ok = true; + if (h_seq) ok &= (cudaHostGetDevicePointer((void**) &d_seq_[par], (void*) h_seq, 0) == cudaSuccess); + if (h_flag) ok &= (cudaHostGetDevicePointer((void**) &d_target_flag_p_[par], (void*) h_flag, 0) == cudaSuccess); + if (h_x) ok &= (cudaHostGetDevicePointer((void**) &d_m_x_[par], (void*) h_x, 0) == cudaSuccess); + if (h_ids) ok &= (cudaHostGetDevicePointer((void**) &d_m_ids_[par], (void*) h_ids, 0) == cudaSuccess); + if (h_ymiss) ok &= (cudaHostGetDevicePointer((void**) &d_m_ymiss_[par], (void*) h_ymiss, 0) == cudaSuccess); + if (!ok) { + (void) cudaGetLastError(); + std::fprintf(stderr, "strata peer: bind_verifier_buffers failed for par=%d\n", par); + return false; + } + if (par == 0 && d_target_flag_p_[0]) d_target_flag_ = d_target_flag_p_[0]; + return true; +} + +bool PeerExperts::launch_window(int par, int64_t lb, int64_t le, int T, int k, uint32_t want_flag_start, int G) { + if (device_ < 0 || par < 0 || par >= 2 || !autonomous_) return false; + uint32_t* const d_seq = d_seq_[par]; + uint32_t* const d_flag = d_target_flag_p_[par]; + const float* const d_x_m = d_m_x_[par]; + const int32_t* const d_ids_m = d_m_ids_[par]; + float* const d_ymiss_m = d_m_ymiss_[par]; + if (!d_seq || !d_flag || !d_x_m || !d_ids_m || !d_ymiss_m || !d_plans_ || !d_res_peer_) return false; + + if (G < 1) G = 1; + On on(device_); + const cudaStream_t s = stream_; + const auto& lay = strata::kernels::cpu::expert_layout(); + if (!lay.native) return false; + + const int64_t total_steps = (le - lb) * G; + for (int64_t step = 0; step < total_steps; ++step) { + const int64_t l = lb + step / G; + const int grp = (int) (step % G); + const uint32_t want = want_flag_start + (uint32_t) step; + const int tb = G == 2 ? (grp == 0 ? 0 : (T + 1) / 2) : 0; + const int te = G == 2 ? (grp == 0 ? (T + 1) / 2 : T) : T; + const int n = te - tb; + const int n_entries = n * k; + if (n_entries > CAP) return false; + + const auto& f = lay.fmt[(size_t) l]; + + strata::kernels::wait_flag_ge(d_seq, want, s); + + PeerPlanDevice* pl = d_plans_ + (step % 256); + strata::kernels::peer_plan( + d_ids_m + (size_t) tb * k, (int) n_entries, k, + d_res_peer_ + (size_t) l * (size_t) n_expert_, (int) n_expert_, + cache_.device_slot(0), d_slot_off_peer_, (long long) lay.blob_bytes(l), + pl->ptr, pl->start, pl->count, pl->dst, pl->tok, pl->out_row, s + ); + + const float* cur_x = d_x_m + (size_t) tb * H; + if (f.had_gu) { + strata::kernels::hadamard_rows(cur_x, d_x_, n, H, f.had_block, d_sx_, s); + strata::kernels::quantize_q8_1_rows(d_x_, n, H, d_q8_, s); + } else { + strata::kernels::quantize_q8_1_rows(cur_x, n, H, d_q8_, s); + } + + auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); + if (f.had_d) { L.had_block = f.had_block; L.d_signs = d_sh_; } + strata::kernels::native_expert_grouped( + L, pl->ptr, pl->start, pl->count, pl->dst, pl->tok, + CAP, CAP, d_q8_, d_scratch_, d_out_, s + ); + + strata::kernels::scatter_rows_and_signal_fixed_f32( + d_out_, d_ymiss_m + (size_t) tb * k * H, pl->out_row, pl->count + 1, (int) n_entries, H, + d_blocks_finished_arr_ + (step % 256), s, d_flag, want + ); + } + 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) { + const int32_t* kind, std::string& err, float* out, uint32_t want_flag) { + if (autonomous_) { + signaled_target_flag_ = true; + launched_direct_ = true; + return true; + } const bool direct = direct_mode() && out != nullptr; struct Timer { double& acc; @@ -348,6 +496,7 @@ bool PeerExperts::launch(int64_t layer, const float* x, const int32_t* ids, int6 ~Timer() { acc += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); } } timer{ms_launch}; launched_direct_ = false; + signaled_target_flag_ = false; launched_rows_ = 0; row_of_.clear(); const int64_t n = n_tok * k; @@ -404,12 +553,19 @@ bool PeerExperts::launch(int64_t layer, const float* x, const int32_t* ids, int6 return false; } ++seq_; + static const bool direct_signal_env = [] { + const char* e = std::getenv("STRATA_PEER_DIRECT_SIGNAL"); + return e != nullptr && std::atoi(e) != 0; + }(); + uint32_t* const flag_target = (direct && direct_signal_env && want_flag > 0) ? d_target_flag_ : nullptr; if (direct) { // the rows straight into the host `out` (zero-copy, coalesced float4 writes) try { - if (d_done_seq_ != nullptr && d_blocks_finished_ != nullptr) { - strata::kernels::scatter_rows_and_signal_f32(d_out_, out, dm->out_row, rows, H, d_done_seq_, seq_, d_blocks_finished_, s); + if (d_blocks_finished_ != nullptr) { + strata::kernels::scatter_rows_and_signal_f32(d_out_, out, dm->out_row, rows, H, d_done_seq_, seq_, + d_blocks_finished_, s, flag_target, want_flag); } else { strata::kernels::scatter_rows_f32(d_out_, out, dm->out_row, rows, H, s); + if (flag_target != nullptr) strata::kernels::signal_stream_done(flag_target, want_flag, s); if (d_done_seq_ != nullptr) strata::kernels::signal_stream_done(d_done_seq_, seq_, s); } } catch (const std::exception& e) { err = std::string("peer experts: scatter: ") + e.what(); return false; } @@ -419,12 +575,21 @@ bool PeerExperts::launch(int64_t layer, const float* x, const int32_t* ids, int6 return false; if (d_done_seq_ != nullptr) strata::kernels::signal_stream_done(d_done_seq_, seq_, s); } + if (flag_target != nullptr) { + signaled_target_flag_ = true; + } return true; } bool PeerExperts::finish(float* out, std::string& err) { + if (autonomous_) return true; if (launched_rows_ == 0) return true; ++launches; + if (signaled_target_flag_) { + signaled_target_flag_ = false; + launched_rows_ = 0; + return true; + } const auto t0 = std::chrono::steady_clock::now(); if (d_done_seq_ != nullptr) { const uint32_t target = seq_; @@ -569,6 +734,10 @@ void PeerExperts::apply_pending(bool wait) { else if (cudaEventQuery(refill_ev_) != cudaSuccess) return; } for (const auto& [i, slot] : pending_) res_[(size_t) i] = slot; + if (d_res_peer_) { + On on(device_); + cudaMemcpyAsync(d_res_peer_, res_.data(), res_.size() * sizeof(int32_t), cudaMemcpyHostToDevice, refill_); + } pending_.clear(); } diff --git a/engine/src/core/verify.cpp b/engine/src/core/verify.cpp index 200ee638d..4954a62d7 100644 --- a/engine/src/core/verify.cpp +++ b/engine/src/core/verify.cpp @@ -12,6 +12,7 @@ #include "strata/core/device_hits_plan.hpp" #include "strata/kernels/gfx_arch.hpp" #include "strata/core/verify.hpp" +#include "strata/core/peer_experts.hpp" #include "strata/core/pending_cuda_error.hpp" #include "strata/core/window_evict.hpp" #include "strata/core/expert_nibble.hpp" @@ -836,6 +837,25 @@ Verifier::~Verifier() { if (h) cudaFreeHost(h); } +void Verifier::set_peer(PeerExperts* peer, int parity) { + peer_ = peer; + parity_ = parity; + if (peer_ != nullptr && peer_->valid() && peer_->autonomous()) { + peer_autonomous_ = true; + if (!all_resident_ && !always_publish_) { + device_plan_ = true; + if (skip_ == nullptr && device_ >= 0) { + const OnDevice on_dev(device_); + if (cudaMalloc((void**) &skip_, 64) == cudaSuccess) { + cudaMemset(skip_, 0, 64); + } + } + } + } else { + peer_autonomous_ = false; + } +} + int Verifier::tap_total() const { int n = 0; if (g_ == nullptr) return 0; @@ -1411,6 +1431,26 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& err = "verify: the mixer branch's stream / events could not be created"; return false; } + if (peer_autonomous_) { + bool all_gpu_resident = true; + int64_t missing_count = 0; + for (int64_t l = lb_; l < le_; ++l) { + for (int64_t e = 0; e < g.n_expert; ++e) { + const bool on_gpu0 = (hits.h_res != nullptr && hits.h_res[l * g.n_expert + e] >= 0); + const bool on_peer = (peer_ != nullptr && peer_->has(l, e)); + if (!on_gpu0 && !on_peer) { + all_gpu_resident = false; + ++missing_count; + } + } + } + if (!all_gpu_resident) { + peer_autonomous_ = false; + if (peer_ != nullptr) peer_->set_autonomous(false); + std::fprintf(stderr, "strata peer: autonomous mode disabled: %lld experts are not resident on either GPU (host fallback required)\n", + (long long) missing_count); + } + } // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1 or // STRATA_VERIFY_DEVICE_HITS=1: bitwise exact, off by default unless arch defaults opt in). STRATA_VERIFY_DEVICE_HITS=1 // also plans every layer's resident hit groups on-device when --pcie-frac 0 (set_no_pcie_share), avoiding host flag spins. @@ -1418,7 +1458,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); if (v == nullptr) v = std::getenv("STRATA_VERIFY_DEVICE_HITS"); // (not with set_always_publish: the device table may lag the host's while windows are in flight) - device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi(v) != 0); + device_plan_ = !all_resident_ && !always_publish_ && ((v != nullptr && std::atoi(v) != 0) || peer_autonomous_); #if defined(STRATA_GPU_METAL) device_hits_ = false; #else @@ -2696,7 +2736,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, hits_.cache_base, slot_off_d_, (long long) hits_.blob, plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp, - (uint32_t) ((l - lb_) * G + grp + 1), cs); + (uint32_t) ((l - lb_) * G + grp + 1), cs, nullptr, peer_autonomous_); #if defined(STRATA_USE_HIP) if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, @@ -2905,7 +2945,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { note_prio_tail(sh_cs_, -1); cudaEventRecord(ev_join_, sh_cs_); } - if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros + if (device_plan_ && !peer_autonomous_) { // no CPU share when the device planned the group: its rows are zeros wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs); copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N, skip_ + grp, ring, cs); @@ -3236,6 +3276,25 @@ std::string Verifier::profile_report() { // (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has // marked some -1). Not: the doorbell graph, which asks the pool for what the device does not hold. void Verifier::refresh_ar() { + if (peer_autonomous_ && h_res_ != nullptr && g_ != nullptr) { + bool all_gpu_resident = true; + for (int64_t l = lb_; l < (le_ < 0 ? g_->n_layers : le_); ++l) { + for (int64_t e = 0; e < g_->n_expert; ++e) { + const bool on_gpu0 = h_res_[l * g_->n_expert + e] >= 0; + const bool on_peer = (peer_ != nullptr && peer_->has(l, e)); + if (!on_gpu0 && !on_peer) { + all_gpu_resident = false; + break; + } + } + if (!all_gpu_resident) break; + } + if (!all_gpu_resident) { + peer_autonomous_ = false; + if (peer_ != nullptr) peer_->set_autonomous(false); + std::fprintf(stderr, "strata peer: autonomous mode disabled dynamically: experts missing from both GPUs (host fallback required)\n"); + } + } if (!all_resident_ || h_res_ == nullptr || g_ == nullptr) return; const int64_t ne = g_->n_expert; const int32_t* r = h_res_ + lb_ * ne; @@ -3875,6 +3934,12 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } *(volatile uint32_t*) h_flag_ = 1; flag_raised = true; + } else if (!pre && peer_autonomous_ && do_ple) { + const Clock::time_point tp = Clock::now(); + if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false; + std::atomic_thread_fence(std::memory_order_seq_cst); + strata_store_fence(); + ms_host += ms_since(tp); } static const bool probe_on = env_on("STRATA_LAUNCH_PROBE"); static std::atomic probe_count{0}; @@ -3923,6 +3988,13 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } }); } + const int G_launch = groups_[T] > 0 ? groups_[T] : 1; + if (peer_ != nullptr && peer_->valid() && peer_autonomous_) { + if (!peer_->launch_window(parity_, lb_, le_, T, (int) ss_->k, 1, G_launch)) { + err = "verify: peer autonomous window launch failed"; + return false; + } + } launch_o.emplace(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_, device_, threaded_launch, [this] { (void) release_gpu_waits(5000); }); const cudaError_t le = launch_o->status(); @@ -3935,6 +4007,13 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } #else strata::dispatch::Stats::get().graph_launch(T, ar_on() ? 0 : 1); + const int G_launch = groups_[T] > 0 ? groups_[T] : 1; + if (peer_ != nullptr && peer_->valid() && peer_autonomous_) { + if (!peer_->launch_window(parity_, lb_, le_, T, (int) ss_->k, 1, G_launch)) { + err = "verify: peer autonomous window launch failed"; + return false; + } + } const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_); #endif trace_ev("LAUNCHED", -1, -1, (int64_t) le); @@ -3989,6 +4068,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } else { *flag = 1; } + } else if (peer_autonomous_) { + // PLE rows already gathered before graph and peer launch } else for (int64_t k = 0; k < steps; ++k) { const int64_t l = lb_ + k / G; @@ -4074,6 +4155,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, !adapt_gate_wait((int32_t) l, err)) return false; cur_layer_ = want - 1; set_plan_slot(grp); + sink_.want_flag = (k == 0 && do_ple) ? 0u : want; + sink_.peer_signals_flag = false; const int tb = gtb[grp], n = gte[grp] - gtb[grp]; progress_at("verify window: the CPU experts of layer", l); if (remote_opt_) remote_opt_->begin(h_w_ + (size_t) tb * ss.k, tb, n); @@ -4115,7 +4198,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, strata_store_fence(); ms_host += ms_since(tp); } - if (!(test_stall && k + 1 == steps)) *flag = want; + if (!(test_stall && k + 1 == steps)) { + if (!sink_.peer_signals_flag) *flag = want; + } if (h_bal_ != nullptr) bal_p_[(size_t) ((k / G) * 2 + grp)] = ms_since(b); ms_wait += std::chrono::duration(b - a).count(); ms_pool += ms_since(b); @@ -5993,6 +6078,18 @@ bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T); ms_host += ms_since(t0); strata::dispatch::Stats::get().graph_launch(T, ar_on() ? 0 : 1); + if (peer_autonomous_ && fl_ple_) { + if (!ss.ple.table->gather_batch(pl_ple_rows_.data(), (size_t) T, h_ple_, err)) return false; + std::atomic_thread_fence(std::memory_order_seq_cst); + strata_store_fence(); + fl_ple_ = false; + } + if (peer_ != nullptr && peer_->valid() && peer_autonomous_) { + if (!peer_->launch_window(parity_, lb_, le_, T, (int) ss.k, 1, G)) { + err = "verify: peer autonomous window launch failed"; + return false; + } + } const cudaError_t le = cudaGraphLaunch(exec_[sl][T], cs_); trace_ev("LAUNCHED", -1, -1, (int64_t) le); if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } @@ -6012,7 +6109,12 @@ int Verifier::service(PoolMultiFn pool, void* user, std::string& err) { // and the device switch (OnDevice: cudaGetDevice and two cudaSetDevice) made that a few driver calls each time: // 919 million passes before the host stalled inside one of those cudaSetDevice calls with both stages waiting // on it (0.1.41, Windows, an RTX 3060 + RTX 5070 Ti split). The same answer as the loop below gives. - if (!ar_on() && *(volatile uint32_t*) h_seq_ < (uint32_t) (fl_k_ + 1)) { + if (peer_autonomous_) { + if (!fl_ple_ && *(volatile uint32_t*) h_seq_ < (uint32_t) fl_total_) { + const double now = now_ms(); + if (now - fl_flush_ms_ <= 2.0 && now - fl_since_ms_ <= 20000.0) return 0; + } + } else if (!ar_on() && *(volatile uint32_t*) h_seq_ < (uint32_t) (fl_k_ + 1)) { const double now = now_ms(); if (now - fl_flush_ms_ <= 2.0 && now - fl_since_ms_ <= 20000.0) return 0; } @@ -6038,6 +6140,24 @@ int Verifier::service(PoolMultiFn pool, void* user, std::string& err) { progress_tick(); return 1; } + if (peer_autonomous_) { + if (fl_k_ == 0 && !gather_ple()) return -1; + if (*(volatile uint32_t*) h_seq_ < (uint32_t) fl_total_) { + const double now = now_ms(); + if (now - fl_flush_ms_ > 2.0) { + fl_flush_ms_ = now; + (void) cudaStreamQuery(cs_); + } + if (now - fl_since_ms_ > 20000.0) { + err = "verify: autonomous window timed out"; + return -1; + } + return 0; + } + fl_k_ = fl_total_; + progress_tick(); + return 1; + } const int G = groups_[T] > 0 ? groups_[T] : 1; const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; while (fl_k_ < fl_total_) { @@ -6068,6 +6188,8 @@ int Verifier::service(PoolMultiFn pool, void* user, std::string& err) { const int grp = (int) (fl_k_ % G); cur_layer_ = want - 1; set_plan_slot(grp); + sink_.want_flag = (fl_k_ == 0 && fl_ple_) ? 0u : want; + sink_.peer_signals_flag = false; const int tb = gtb[grp], n = gte[grp] - gtb[grp]; progress_at("verify window (pipelined): the CPU experts of layer", l); if (pool != nullptr) @@ -6089,7 +6211,7 @@ int Verifier::service(PoolMultiFn pool, void* user, std::string& err) { raise_flag_b_ordered(want); // behind any copy still queued from an earlier layer } if (fl_k_ == 0 && !gather_ple()) return -1; - *(volatile uint32_t*) h_flag_ = want; + if (!sink_.peer_signals_flag) *(volatile uint32_t*) h_flag_ = want; ++fl_k_; ms_pool += ms_since(b); fl_since_ms_ = fl_flush_ms_ = now_ms(); diff --git a/engine/src/kernels/cuda/elementwise.cu b/engine/src/kernels/cuda/elementwise.cu index 8adcc3d8e..6b83bd13c 100644 --- a/engine/src/kernels/cuda/elementwise.cu +++ b/engine/src/kernels/cuda/elementwise.cu @@ -269,26 +269,157 @@ __global__ void scatter_rows_kernel(const float4* __restrict__ src, float4* dst, } __global__ void scatter_rows_and_signal_kernel(const float4* __restrict__ src, float4* dst, const int32_t* __restrict__ rows, int64_t w4, uint32_t* __restrict__ done_ptr, uint32_t val, - int* __restrict__ d_blocks_finished) { + int* __restrict__ d_blocks_finished, + uint32_t* __restrict__ flag_ptr, uint32_t flag_val) { 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]; - if (done_ptr != nullptr) { + if (done_ptr != nullptr || flag_ptr != nullptr) { __syncthreads(); if (threadIdx.x == 0) { __threadfence_system(); if (atomicAdd(d_blocks_finished, 1) == (int) gridDim.x - 1) { *d_blocks_finished = 0; - *done_ptr = val; + __threadfence_system(); + if (flag_ptr != nullptr) *flag_ptr = flag_val; + if (done_ptr != nullptr) *done_ptr = val; + __threadfence_system(); } } } } +__global__ void scatter_rows_and_signal_fixed_kernel( + const float4* __restrict__ src, float4* dst, const int32_t* __restrict__ rows, + const int32_t* __restrict__ d_count, int64_t w4, + int* __restrict__ d_blocks_finished, + uint32_t* __restrict__ flag_ptr, uint32_t flag_val) { + const int64_t r = blockIdx.x; + const int total_rows = d_count != nullptr ? *d_count : (int) gridDim.x; + if (r < total_rows) { + 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]; + } + if (flag_ptr != nullptr) { + __syncthreads(); + if (threadIdx.x == 0) { + __threadfence_system(); + if (atomicAdd(d_blocks_finished, 1) == (int) gridDim.x - 1) { + *d_blocks_finished = 0; + __threadfence_system(); + *flag_ptr = flag_val; + __threadfence_system(); + } + } + } +} + +template +__global__ void __launch_bounds__(NT) peer_plan_kernel( + const int32_t* __restrict__ ids, int n, int k, + const int32_t* __restrict__ res, int n_expert, + const uint8_t* cache_base, const unsigned long long* slot_off, + long long blob, + unsigned long long* __restrict__ grp_ptr, + int32_t* __restrict__ grp_start, + int32_t* __restrict__ grp_count, + int32_t* __restrict__ grp_dst, + int32_t* __restrict__ grp_tok, + int32_t* __restrict__ grp_out_row) { + constexpr int NW = NT / 32; + __shared__ int32_t s_ids[NT]; + __shared__ int32_t s_slot[NT]; + __shared__ int32_t s_excl[NT]; + __shared__ int32_t s_wsum[NW]; + const int tid = threadIdx.x; + + int32_t eid = -1; + int32_t slot = -1; + if (tid < n) { + eid = ids[tid]; + s_ids[tid] = eid; + slot = (eid >= 0 && eid < n_expert) ? res[eid] : -1; + s_slot[tid] = slot; + } else { + s_ids[tid] = -1; + s_slot[tid] = -1; + } + __syncthreads(); + + int first_j = tid; + int rank_in_group = 0; + int count_same = 0; + if (tid < n && slot >= 0) { + for (int j = 0; j < n; ++j) { + if (s_slot[j] >= 0 && s_ids[j] == eid) { + if (j < first_j) first_j = j; + if (j < tid) ++rank_in_group; + ++count_same; + } + } + } + + const bool is_first = (tid < n && slot >= 0 && first_j == tid); + const int my_cnt = is_first ? count_same : 0; + const int my_pack = (my_cnt << 16) | (is_first ? 1 : 0); + const int lane = tid & 31; + const int warp = tid >> 5; + + int pref = my_pack; +#pragma unroll + for (int d = 1; d < 32; d <<= 1) { + const int up = __shfl_up_sync(0xffffffffu, pref, d); + if (lane >= d) pref += up; + } + s_excl[tid] = pref - my_pack; + if (lane == 31) s_wsum[warp] = pref; + __syncthreads(); + + if (is_first) { + int tot = s_excl[tid]; +#pragma unroll + for (int w = 0; w < NW; ++w) { + if (w < warp) tot += s_wsum[w]; + } + const int grp_idx = tot & 0xffff; + const int ent_start = tot >> 16; + grp_ptr[grp_idx] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob)); + grp_start[grp_idx] = ent_start; + } + + if (tid < n && slot >= 0) { + const int fj_warp = first_j >> 5; + int fj_tot = s_excl[first_j]; +#pragma unroll + for (int w = 0; w < NW; ++w) { + if (w < fj_warp) fj_tot += s_wsum[w]; + } + const int out_idx = (fj_tot >> 16) + rank_in_group; + grp_dst[out_idx] = out_idx; + grp_tok[out_idx] = tid / k; + grp_out_row[out_idx] = tid; + } + + if (tid == 0) { + int groups = 0, entries = 0; +#pragma unroll + for (int w = 0; w < NW; ++w) { + groups += (s_wsum[w] & 0xffff); + entries += (s_wsum[w] >> 16); + } + grp_start[groups] = entries; + grp_count[0] = groups; + grp_count[1] = entries; + grp_count[2] = 0; + grp_count[3] = 0; + } +} __global__ void signal_done_kernel(uint32_t* __restrict__ ptr, uint32_t val) { if (threadIdx.x == 0 && blockIdx.x == 0) { __threadfence_system(); *ptr = val; + __threadfence_system(); } } } // namespace @@ -306,14 +437,35 @@ void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t scatter_rows_kernel<<<(unsigned) n, 128, 0, (cudaStream_t) stream>>>((const float4*) src, (float4*) dst, rows, width / 4); } void scatter_rows_and_signal_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, - uint32_t* d_done_ptr, uint32_t val, int* d_blocks_finished, void* stream) { + uint32_t* d_done_ptr, uint32_t val, int* d_blocks_finished, void* stream, + uint32_t* d_flag_ptr, uint32_t flag_val) { if (n <= 0) return; if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) { std::fprintf(stderr, "scatter_rows_and_signal_f32: width must be a multiple of 4 and both pointers 16-byte aligned\n"); std::exit(1); } scatter_rows_and_signal_kernel<<<(unsigned) n, 128, 0, (cudaStream_t) stream>>>( - (const float4*) src, (float4*) dst, rows, width / 4, d_done_ptr, val, d_blocks_finished); + (const float4*) src, (float4*) dst, rows, width / 4, d_done_ptr, val, d_blocks_finished, d_flag_ptr, flag_val); +} +void scatter_rows_and_signal_fixed_f32(const float* src, float* dst, const int32_t* rows, + const int32_t* d_count, int64_t cap_entries, int64_t width, + int* d_blocks_finished, void* stream, + uint32_t* d_flag_ptr, uint32_t flag_val) { + if (cap_entries <= 0) return; + if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) { + std::fprintf(stderr, "scatter_rows_and_signal_fixed_f32: alignment error\n"); + std::exit(1); + } + scatter_rows_and_signal_fixed_kernel<<<(unsigned) cap_entries, 128, 0, (cudaStream_t) stream>>>( + (const float4*) src, (float4*) dst, rows, d_count, width / 4, d_blocks_finished, d_flag_ptr, flag_val); +} +void peer_plan(const int32_t* ids, int n, int k, const int32_t* res, int n_expert, + const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, + unsigned long long* grp_ptr, int32_t* grp_start, int32_t* grp_count, + int32_t* grp_dst, int32_t* grp_tok, int32_t* grp_out_row, void* stream) { + peer_plan_kernel<128><<<1, 128, 0, (cudaStream_t) stream>>>( + ids, n, k, res, n_expert, cache_base, slot_off, blob, + grp_ptr, grp_start, grp_count, grp_dst, grp_tok, grp_out_row); } 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) { @@ -359,9 +511,7 @@ __global__ void doorbell_publish_kernel(const float* __restrict__ x, const int32 __syncthreads(); if (threadIdx.x == 0) { *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; -#if defined(__HIPCC__) // #697: HIP only; on RDNA4 the volatile store alone can sit in L2 until the stream syncs __threadfence_system(); -#endif } } @@ -383,9 +533,7 @@ __global__ void doorbell_publish_res_kernel(const float* __restrict__ x, const i __syncthreads(); if (threadIdx.x == 0) { *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; -#if defined(__HIPCC__) // #697: HIP only; on RDNA4 the volatile store alone can sit in L2 until the stream syncs __threadfence_system(); -#endif } } diff --git a/engine/src/kernels/cuda/verify_kernels.cu b/engine/src/kernels/cuda/verify_kernels.cu index 07c7a1caf..9980f57fb 100644 --- a/engine/src/kernels/cuda/verify_kernels.cu +++ b/engine/src/kernels/cuda/verify_kernels.cu @@ -1493,7 +1493,7 @@ static_assert(kVerifyMaxT * 10 <= kResidentPlanMax, "resident_plan: one thread p // the parallel scan keeps one partial sum per warp in s_wsum[NT / 32] and packs (entries << 16 | groups) in an int static_assert(kResidentPlanMax <= 256 && kResidentPlanMax % 32 == 0, "resident_plan: at most 8 warps"); static_assert(kResidentPlanMax < 32768, "resident_plan: the packed entry count must stay below 2^15"); -template +template __global__ void __launch_bounds__(NT) resident_plan_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip, @@ -1513,16 +1513,20 @@ __global__ void __launch_bounds__(NT) resident_plan_kernel(const int32_t* __rest eid = ids[tid]; s_ids[tid] = eid; slot = (eid >= 0 && eid < n_expert) ? res[eid] : -1; - if (slot < 0) atomicOr(&s_bad, 1); + if constexpr (!AllowPartial) { + if (slot < 0) atomicOr(&s_bad, 1); + } } __syncthreads(); - if (s_bad) { - if (tid == 0 && skip != nullptr) *skip = 0; - if (tid == 0 && skip == nullptr) { // #871: the all-resident graph has no host plan to fall back on - pl[0] = 0; pl[1] = 0; pl[2] = 0; // an empty plan: no expert runs on a stale pointer - if (plan_err != nullptr) { *plan_err = 1; __threadfence_system(); } + if constexpr (!AllowPartial) { + if (s_bad) { + if (tid == 0 && skip != nullptr) *skip = 0; + if (tid == 0 && skip == nullptr) { // #871: the all-resident graph has no host plan to fall back on + pl[0] = 0; pl[1] = 0; pl[2] = 0; // an empty plan: no expert runs on a stale pointer + if (plan_err != nullptr) { *plan_err = 1; __threadfence_system(); } + } + return; } - return; } int first_j = tid; @@ -1573,7 +1577,7 @@ __global__ void __launch_bounds__(NT) resident_plan_kernel(const int32_t* __rest ptr[grp_idx] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob)); start[grp_idx] = ent_start; } - if (tid < n) { + if (tid < n && (!AllowPartial || slot >= 0)) { const int fj_warp = first_j >> 5; int fj_tot = s_excl[first_j]; #pragma unroll @@ -1585,18 +1589,17 @@ __global__ void __launch_bounds__(NT) resident_plan_kernel(const int32_t* __rest tok[out_idx] = tid / k; } if (tid == 0) { - int groups; - if constexpr (NW == 4) groups = (s_wsum[0] + s_wsum[1] + s_wsum[2] + s_wsum[3]) & 0xffff; // (the 128-thread kernel as it was) - else { - groups = 0; + int groups = 0, entries = 0; #pragma unroll - for (int w = 0; w < NW; ++w) groups += s_wsum[w]; - groups &= 0xffff; + for (int w = 0; w < NW; ++w) { + groups += (s_wsum[w] & 0xffff); + entries += (s_wsum[w] >> 16); } - start[groups] = n; - start2[0] = n; + const int final_entries = AllowPartial ? entries : n; + start[groups] = final_entries; + start2[0] = final_entries; counts[0] = groups; - counts[1] = n; + counts[1] = final_entries; counts[2] = 0; if (skip != nullptr) { __threadfence(); @@ -1833,18 +1836,34 @@ __global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile flo void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, - long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) { - if (n_entries > kResidentPlanNarrow) { // a 9..16-row window (kResidentPlanMax == 256 only in a wide build) - if (kResidentPlanMax > kResidentPlanNarrow && n_entries <= kResidentPlanMax) - resident_plan_kernel<<<1, kResidentPlanMax, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, - blob, plan, capx, skip, ring, plan_err); - else { - std::fprintf(stderr, "resident_plan: %d entries, at most %d\n", n_entries, kResidentPlanMax); - std::exit(1); + long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err, + bool allow_partial) { + if (allow_partial) { + if (n_entries > kResidentPlanNarrow) { + if (kResidentPlanMax > kResidentPlanNarrow && n_entries <= kResidentPlanMax) + resident_plan_kernel<<<1, kResidentPlanMax, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, + blob, plan, capx, skip, ring, plan_err); + else { + std::fprintf(stderr, "resident_plan: %d entries, at most %d\n", n_entries, kResidentPlanMax); + std::exit(1); + } + } else { + resident_plan_kernel<<<1, kResidentPlanNarrow, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, + blob, plan, capx, skip, ring, plan_err); } } else { - resident_plan_kernel<<<1, kResidentPlanNarrow, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, - blob, plan, capx, skip, ring, plan_err); + if (n_entries > kResidentPlanNarrow) { + if (kResidentPlanMax > kResidentPlanNarrow && n_entries <= kResidentPlanMax) + resident_plan_kernel<<<1, kResidentPlanMax, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, + blob, plan, capx, skip, ring, plan_err); + else { + std::fprintf(stderr, "resident_plan: %d entries, at most %d\n", n_entries, kResidentPlanMax); + std::exit(1); + } + } else { + resident_plan_kernel<<<1, kResidentPlanNarrow, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, + blob, plan, capx, skip, ring, plan_err); + } } check("resident_plan"); } diff --git a/engine/src/program/generate.cpp b/engine/src/program/generate.cpp index 977fa6c98..97ef0464b 100644 --- a/engine/src/program/generate.cpp +++ b/engine/src/program/generate.cpp @@ -13407,6 +13407,7 @@ int main(int argc, char** argv) { return 1; } } + if (peer.valid()) ver_b.set_peer(&peer, 1); if (!ver_b.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA0 (the first card): " "%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", err.c_str()); @@ -13422,6 +13423,7 @@ int main(int argc, char** argv) { if (use_df2) ver.set_taps(df2.tap_layers()); if (batch_df2) ver.set_batch_taps(true); #endif + if (peer.valid()) ver.set_peer(&peer, 0); if (!ver.init(wt, g, ss, vh, native_head.loaded() || prefill_head_alias_bound ? &native_head : nullptr, batch_max_t(), err) || (use_mtp && !prefill_head_alias_bound && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, @@ -13430,6 +13432,13 @@ int main(int argc, char** argv) { return 1; } if (prefill_head_alias_bound) mtp.set_window_R(ver.final_R_all()); + if (peer.valid()) { + peer.set_target_flag(ver.h_flag()); + peer.bind_verifier_buffers(0, ver.h_seq(), ver.h_flag(), ver.h_x(), ver.h_ids(), ver.h_ymiss()); + if (pipe) { + peer.bind_verifier_buffers(1, ver_b.h_seq(), ver_b.h_flag(), ver_b.h_x(), ver_b.h_ids(), ver_b.h_ymiss()); + } + } #if defined(STRATA_HAVE_DFLASH2) #if defined(STRATA_HAVE_DFLASH2) // DFlash2 prompt taps on a layer split. Every stage's prompt path taps the requested layers it runs into its own staging and hands them to its @@ -24402,11 +24411,16 @@ int main(int argc, char** argv) { #if defined(STRATA_HAVE_DFLASH2) if (use_df2) ver.set_taps(df2.tap_layers()); #endif + if (peer.valid()) ver.set_peer(&peer, 0); if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } const bool use_mtp = !o.mtp.empty(); + if (peer.valid()) { + peer.set_target_flag(ver.h_flag()); + peer.bind_verifier_buffers(0, ver.h_seq(), ver.h_flag(), ver.h_x(), ver.h_ids(), ver.h_ymiss()); + } if (use_mtp && !mtp.bind(wt, &native_head, ver.final_R_all(), err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1;