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++
STRATA_ADAPT_OVERLAP=1 (opt-in): the adaptive tier's copies land while the next decode window runs, a layer waits for its own copies
Niko12219ef4484248e7
diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hppindex 519fd43b5..96a297b28 100644--- a/include/strata/core/verify.hpp+++ b/include/strata/core/verify.hpp@@ -39,6 +39,18 @@namespace strata::core {+/// 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+/// slots) back until `landed >= layer` for a layer with a swap (`has[layer]`). Set `active` only around one window.+struct AdaptGate {+ struct Tick { AdaptGate* gate; int32_t layer; };+ std::atomic<int32_t> landed{-1}; ///< the highest layer whose swap copies have landed (n_layers: all of them)+ std::atomic<bool> active{false};+ std::vector<uint8_t> has; ///< per layer: a swap copies into this layer's slots+ std::vector<Tick> ticks; ///< host-function contexts, one per layer and the final one (stable storage)+};+class NativeHead;class RemoteExpertOpt;@@ -216,6 +228,14 @@ public:/// expert evicted on the host (the pool then computes it on the CPU) before the device table follows. Also turns/// the device-planned layers (E-6) off. Before `init`.void set_always_publish(bool on) { always_publish_ = on; }+ /// 0.1.43: the adaptive tier's overlap gate (see AdaptGate). Refused (false) with the device-planned layers (E-6),+ /// which never ask the host. The pointer must outlive the verifier's windows.+ bool set_adapt_gate(AdaptGate* g) {+ if (g != nullptr && device_plan_) return false;+ adapt_gate_ = g;+ return true;+ }+ double ms_gate = 0; ///< host time spent holding a layer's plan for the adaptive copies (decode timing prints it)cudaStream_t stream() const { return cs_; }int device() const { return device_; }/// Capture every window size and the commit graph now (a capture syncs the stream: never with a window in flight).@@ -321,6 +341,8 @@ private:// pipelined windows (pl_launch ...)cudaStream_t ext_stream_ = nullptr; ///< set_stream: the stage's shared stream (not destroyed here)bool always_publish_ = false;+ bool adapt_gate_wait(int32_t layer, std::string& err);+ AdaptGate* adapt_gate_ = nullptr; ///< 0.1.43: STRATA_ADAPT_OVERLAP's gate (null: off)void pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]);cudaEvent_t ev_done_ = nullptr, ev_commit_ = nullptr;unsigned long long* prof_pin_ = nullptr; ///< pinned host copy of the stamps (pipelined windows)diff --git a/src/core/verify.cpp b/src/core/verify.cppindex 3e9ec069a..c5e6a98be 100644--- a/src/core/verify.cpp+++ b/src/core/verify.cpp@@ -1969,6 +1969,24 @@ void Verifier::accumulate_profile(const unsigned long long* stamps) {++prof_windows_;}+// 0.1.43 (STRATA_ADAPT_OVERLAP): hold the host until the adaptive tier's copies up to `layer` have landed. The wait+// is a spin on an atomic the copy stream's host functions raise (no driver call here); 20 s is the window's own limit.+bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) {+ const Clock::time_point t0 = Clock::now();+ uint32_t spins = 0;+ while (adapt_gate_->landed.load(std::memory_order_acquire) < layer) {+ _mm_pause();+ if ((++spins & 1023u) != 0) continue;+ if (Clock::now() - t0 > std::chrono::seconds(20)) {+ err = "verify: the adaptive tier's copies for layer " + std::to_string(layer) + " never landed" ++ released_note(release_gpu_waits(5000));+ return false;+ }+ }+ ms_gate += ms_since(t0);+ return true;+}+bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out,std::string& err) {using namespace strata::kernels;@@ -2002,6 +2020,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,ms_host += ms_since(t0);VDBG("staged; launching\n");if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;+ // 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first+ if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() &&+ !adapt_gate_wait((int32_t) g.n_layers, err)) return false;const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_);trace_ev("LAUNCHED", -1, -1, (int64_t) le);if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }@@ -2065,6 +2086,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,const Clock::time_point b = Clock::now();if (g_trace) trace_ev("RANG", k, l, (int64_t) std::chrono::duration_cast<std::chrono::microseconds>(b - a).count());VDBG("layer %lld rang\n", (long long) l);+ if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && l >= 0 &&+ (size_t) l < adapt_gate_->has.size() && adapt_gate_->has[(size_t) l] != 0 &&+ !adapt_gate_wait((int32_t) l, err)) return false;cur_layer_ = want - 1;set_plan_slot(grp);const int tb = gtb[grp], n = gte[grp] - gtb[grp];diff --git a/src/program/generate.cpp b/src/program/generate.cppindex cb61a639f..c5cd3232d 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -1320,6 +1320,16 @@ int adapt_lag() {return v;}+/// 0.1.43 STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next decode window already runs. The window+/// sees the swapped-in experts as resident from its first layer, exactly as after #463's wait (so the tokens are the same+/// ones); what changes is only when the bytes arrive: the copies go in layer order and the verify window holds a layer's+/// plan back until that layer's copies have landed (AdaptGate in strata/core/verify.hpp). The ~10 ms a 96-swap round+/// took at the next window's start (PCIe 3.0 x16, Q2_0) is then hidden behind the window. Off by default.+bool adapt_overlap() {+ static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_OVERLAP"); return e && e[0] == '1'; }();+ return v;+}+/// --adapt-async: one background job at a time (the asynchronous adaptive tier's copies and memcpys). `post` hands/// it over, `idle` says whether it has finished; the owner never posts while a job runs.class JobThread {@@ -8121,6 +8131,36 @@ int main(int argc, char** argv) {std::vector<void*> pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landedcudaEvent_t adapt_ev = nullptr;cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming);+ // 0.1.43 STRATA_ADAPT_OVERLAP=1 (adapt_overlap above): the single-GPU, plain-RAM-arena decode loop only+ strata::core::AdaptGate agate;+ bool aflipped = false; // the pending swaps are in the tables and their copies may still be landing+ bool aov = false;+ int64_t aov_flips = 0;+ if (adapt_overlap()) {+ const char* why = multi_gpu || !stages.empty() ? "not on a layer split"+ : peer.valid() ? "not with --peer-device"+ : remote_opt ? "not with --remote-expert-opt"+ : o.adapt_async ? "not with --adapt-async"+ : o.pipeline_windows > 0 ? "not with --pipeline-windows"+ : src.complement_ready() ? "not with the resident RAM mode"+ : pin_blobs_on() ? "not with page-locked swap sources"+ : strata::core::dma_batch_mode() != 0 ? "not with STRATA_DMA_BATCH"+ : adapt_lag() != 1 || adapt_nowait() ? "not with STRATA_ADAPT_LAG / STRATA_ADAPT_NOWAIT"+ : drive.d.usage.empty() ? "the adaptive tier is off"+ : nullptr;+ if (why == nullptr) {+ agate.ticks.resize((size_t) g.n_layers + 1);+ for (int64_t l = 0; l <= g.n_layers; ++l) agate.ticks[(size_t) l] = {&agate, (int32_t) l};+ agate.has.assign((size_t) g.n_layers, 0);+ if (!ver.set_adapt_gate(&agate)) why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on";+ }+ aov = why == nullptr;+ if (aov)+ std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next window runs "+ "(same tokens, a layer waits for its own copies)\n");+ else+ std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", why);+ }// a layer split's later stages keep a copy of the residency table on their devices, and swap on their ownauto res_upload = [&]() {if (d_res != nullptr)@@ -8149,6 +8189,8 @@ int main(int argc, char** argv) {}pending.clear();pending_age = 0;+ agate.active.store(false, std::memory_order_release); // 0.1.43: the copies have landed (STRATA_ADAPT_OVERLAP)+ aflipped = false;res_upload();};// --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt)@@ -8181,6 +8223,12 @@ int main(int argc, char** argv) {}std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);+ if (aov) { // 0.1.43: the copies go in layer order and each layer's landing is told to the verify window+ std::stable_sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.layer < b.layer; });+ agate.landed.store(-1, std::memory_order_release);+ agate.has.assign((size_t) g.n_layers, 0);+ for (const Swap& s : swaps) agate.has[(size_t) s.layer] = 1;+ }// the copies back read the cache of the card that owns each layer (see resident_stage_swaps)auto home_of = [&](int64_t layer) -> SwapHome {const int stn = multi_gpu ? stage_of(layer) : 0;@@ -8250,6 +8298,16 @@ int main(int argc, char** argv) {host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhilesrcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back aheadpending.emplace_back((int32_t) in, slot); // resident once the copy has landed+ if (aov && (si + 1 == swaps.size() || swaps[si + 1].layer != s.layer) &&+ cudaLaunchHostFunc(adapt_stream, [](void* p) {+ auto* t = (strata::core::AdaptGate::Tick*) p;+ int32_t cur = t->gate->landed.load(std::memory_order_relaxed);+ while (cur < t->layer && !t->gate->landed.compare_exchange_weak(cur, t->layer, std::memory_order_release)) {}+ }, &agate.ticks[(size_t) s.layer]) != cudaSuccess) {+ (void) cudaGetLastError();+ cudaStreamSynchronize(adapt_stream); // no callback: wait here, the gate opens at once+ agate.landed.store((int32_t) g.n_layers, std::memory_order_release);+ }}if (!cp_dst.empty() && strata::core::copy_blobs(cp_dst.data(), cp_src.data(), cp_bytes.data(), cp_dst.size(),adapt_stream, dma_mode) != cudaSuccess) {@@ -11575,6 +11633,15 @@ int main(int argc, char** argv) {// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B)if (adapt_nowait()) apply_pending(false);+ else if (aov && !pending.empty() && !aflipped) {+ // 0.1.43 STRATA_ADAPT_OVERLAP: the tables take the swaps now, exactly where the wait would have ended;+ // the copies still landing are waited for per layer inside the window (AdaptGate)+ for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot;+ res_upload();+ aflipped = true;+ ++aov_flips;+ agate.active.store(true, std::memory_order_release);+ }else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true);if (!adapt_tick(false)) { // --adapt-async: the round in flight moves on a step when it canstd::printf("ERR an adaptive refill failed\n");@@ -11606,6 +11673,7 @@ int main(int argc, char** argv) {std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());return 1;}+ if (aflipped) apply_pending(true); // 0.1.43: every layer's copies were waited for in the window; the bookkeeping now// Diagnostics (as in generate): STRATA_DUMP_FIRST_LOGITS=<path> writes the logits of each request's first// window to <path>.<n>, so the prompt paths (a peer card's share, a split) can be compared by KLif (first_window) {@@ -11724,6 +11792,9 @@ int main(int argc, char** argv) {(d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w,(d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L),(d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L));+ if (aov)+ std::fprintf(stderr, "strata decode adapt overlap: %lld windows took swaps still landing, a layer waited %.2f ms in all so far\n",+ (long long) aov_flips, ver.ms_gate);for (int st = 0; st < n_stages; ++st) { // every stage's GPU profile, not only the first card'sconst std::string pr = stage_ver(st).profile_report();if (pr.empty()) continue;diff --git a/tools/h2d_bench.cu b/tools/h2d_bench.cunew file mode 100644index 000000000..7384b392a--- /dev/null+++ b/tools/h2d_bench.cu@@ -0,0 +1,82 @@+// 0.1.43 5.2: do two streams move host->device data faster than one (both copy engines)? And what does one layer's+// worth of expert-sized copies cost end to end (issue, copy, host function, sync)?+// nvcc -O2 -o h2d_bench tools/h2d_bench.cu && ./h2d_bench [device]+#include <cuda_runtime.h>+#include <algorithm>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <vector>++#define CK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { std::printf("%s:%d %s\n", __FILE__, __LINE__, cudaGetErrorString(e)); std::exit(1); } } while (0)+using Clock = std::chrono::steady_clock;+static double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }++int main(int argc, char** argv) {+ int dev = argc > 1 ? std::atoi(argv[1]) : 0;+ CK(cudaSetDevice(dev));+ cudaDeviceProp p;+ CK(cudaGetDeviceProperties(&p, dev));+ std::printf("%s asyncEngineCount=%d\n", p.name, p.asyncEngineCount);+ const size_t blob = 1382400; // a Q2_0 expert+ const size_t nb = 256; // blobs in the arena+ const size_t arena_bytes = nb * blob;+ uint8_t* host = nullptr;+ // like the engine's arena: plain pages registered with cudaHostRegister (PORTABLE)+ host = (uint8_t*) aligned_alloc(2 << 20, (arena_bytes + (2 << 20) - 1) / (2 << 20) * (2 << 20));+ for (size_t i = 0; i < arena_bytes; i += 4096) host[i] = (uint8_t) i;+ CK(cudaHostRegister(host, arena_bytes, cudaHostRegisterPortable));+ uint8_t* dbuf;+ CK(cudaMalloc(&dbuf, 2 * 64 * blob));+ cudaStream_t s[2];+ for (int i = 0; i < 2; ++i) CK(cudaStreamCreateWithFlags(&s[i], cudaStreamNonBlocking));++ // 1. throughput: N blobs, one stream vs two streams (alternate blobs)+ for (int nstreams = 1; nstreams <= 2; ++nstreams) {+ double best = 1e9;+ for (int rep = 0; rep < 7; ++rep) {+ auto t0 = Clock::now();+ for (size_t i = 0; i < nb; ++i) CK(cudaMemcpyAsync(dbuf + (i % 64) * blob, host + i * blob, blob, cudaMemcpyHostToDevice, s[i % nstreams]));+ for (int i = 0; i < nstreams; ++i) CK(cudaStreamSynchronize(s[i]));+ best = std::min(best, ms_since(t0));+ }+ std::printf("throughput %d stream(s): %.3f ms for %zu blobs = %.2f GB/s\n", nstreams, best, nb, arena_bytes / best / 1e6);+ }+ // 1b. the same with each stream copying one big contiguous range+ for (int nstreams = 1; nstreams <= 2; ++nstreams) {+ double best = 1e9;+ for (int rep = 0; rep < 7; ++rep) {+ auto t0 = Clock::now();+ size_t half = 64 * blob / nstreams;+ for (int i = 0; i < nstreams; ++i) CK(cudaMemcpyAsync(dbuf + i * half, host + i * half, half, cudaMemcpyHostToDevice, s[i]));+ for (int i = 0; i < nstreams; ++i) CK(cudaStreamSynchronize(s[i]));+ best = std::min(best, ms_since(t0));+ }+ std::printf("big range %d stream(s): %.3f ms for %zu bytes = %.2f GB/s\n", nstreams, best, 64 * blob, 64 * blob / best / 1e6);+ }+ // 2. per-layer latency: k blobs, then a host function, then wait for it (the engine's flag B)+ for (int k : {1, 2, 4, 8, 16}) {+ for (int nstreams = 1; nstreams <= 2; ++nstreams) {+ std::vector<double> v;+ for (int rep = 0; rep < 200; ++rep) {+ static volatile int flag;+ flag = 0;+ auto t0 = Clock::now();+ for (int i = 0; i < k; ++i) CK(cudaMemcpyAsync(dbuf + i * blob, host + ((rep * 13 + i * 7) % nb) * blob, blob, cudaMemcpyHostToDevice, s[i % nstreams]));+ if (nstreams == 2) {+ cudaEvent_t ev;+ CK(cudaEventCreateWithFlags(&ev, cudaEventDisableTiming));+ CK(cudaEventRecord(ev, s[1]));+ CK(cudaStreamWaitEvent(s[0], ev, 0));+ CK(cudaEventDestroy(ev));+ }+ CK(cudaLaunchHostFunc(s[0], [](void*) { flag = 1; }, nullptr));+ while (!flag) {}+ v.push_back(ms_since(t0));+ }+ std::sort(v.begin(), v.end());+ std::printf("layer of %2d blobs, %d stream(s): median %.3f ms min %.3f p90 %.3f (ideal at 11 GB/s %.3f)\n", k, nstreams, v[v.size() / 2], v[0], v[v.size() * 9 / 10], k * blob / 11e6);+ }+ }+ return 0;+}