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++
Overlap streamed KV uploads with prefill computation
Moor Wuf1635c2174cd
diff --git a/docs/KV_PREFETCH.md b/docs/KV_PREFETCH.mdnew file mode 100644index 000000000..aecce544d--- /dev/null+++ b/docs/KV_PREFETCH.md@@ -0,0 +1,57 @@+# Overlap streamed KV uploads with prefill computation++## Why this helps++When long-context KV lives partly in system RAM, prefill uploads each attention+layer's cached prefix. Waiting for every upload on the compute stream leaves+the GPU idle.++This opt-in change starts the next attention layer's upload on a separate stream+while the current layer continues computing. It reuses the existing staging+pool; it does not allocate another KV buffer.++## Use and ordering++Set `STRATA_KV_PREFETCH=1` before starting the engine. It is off by default.+A release event protects the staging pool's last reader; a ready event orders+the next attention consumer. Early returns drain pending copies before the caller+can refill borrowed expert slots. Relayout and destruction also drain the stream.++## Validation environment++- Two modified RTX 3080 20 GB cards; CUDA SM86, CUDA 13.1, Linux.+- Intel Xeon E5-2686 v4 (18 cores / 36 threads), about 94 GiB usable RAM.+- PCIe 3.0, no GPU peer-to-peer access; 17 expert-pool workers.+- Qwen3.8-Flash-Next IQ3_S, 131,072-token context, INT8 KV,+ 32,768 resident KV cells.+- Medium thinking: 2,048-token reasoning cap, 8,192-token output cap.+- Physical GPU power limits stayed at 250 W and 280 W. No power increase.+- Historical performance tests used an isolated engine based on official+ v0.1.38 plus reviewed architectds/Strata changes (best, 05c0f36).+ This PR contains only our change, ported to official main (99f3dbd).+ The historical timings are NOT a measured speedup of this pure-upstream port.++## Historical benefit++ABBA comparison, two observations per arm, all 20 complete JSON checks passed:++| Cold input | Serial prefill | Overlapped prefill | Serial request | Overlapped request |+| --- | ---: | ---: | ---: | ---: |+| 8K | 5.013 s | 5.025 s | 6.727 s | 6.726 s |+| 32K | 16.989 s | 16.082 s | 18.468 s | 17.559 s |+| 64K | 32.604 s | 31.259 s | 34.354 s | 32.775 s |++Prefill time fell by 5.3% at 32K and 4.1% at 64K.+There was no useful 8K improvement and no decode speedup.+Profiling showed roughly 939 ms / 1,553 ms of serial KV-stage wait moving off+the critical path. The copies still execute; they are not eliminated.++## Validation and remaining work++- Linux compile/link against pure official main (99f3dbd) passed. No engine+ was started and no production settings were changed.+- No claim of a pure-upstream GPU speedup or bitwise numerical parity yet.+- The standalone historical prototype did not run the full vision/120K/cancel+ safety suite. Later combined builds did, but they do not validate this port.+- Keep draft until pure-upstream long-context, cancellation, and image-history+ tests pass. HIP and other GPUs are unvalidated.diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cppindex 9cc1e5d51..205716bd9 100644--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@ -608,6 +608,8 @@ struct Prefill::Impl {// KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout)strata::kernels::KvHostPools stage;int32_t* ident_table = nullptr;+ cudaStream_t kv_copy = nullptr;+ cudaEvent_t kv_released = nullptr, kv_ready = nullptr;// layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn)int device = -1;float* hand[2] = {};@@ -674,6 +676,7 @@ void Prefill::release() {if (!impl_) return;if (impl_->cs) cudaStreamSynchronize(impl_->cs);if (impl_->copy) cudaStreamSynchronize(impl_->copy);+ if (impl_->kv_copy) cudaStreamSynchronize(impl_->kv_copy);for (int i = 0; i < RING_MAX; ++i) {if (impl_->copied[i]) cudaEventDestroy(impl_->copied[i]);if (impl_->used[i]) cudaEventDestroy(impl_->used[i]);@@ -684,6 +687,9 @@ void Prefill::release() {if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty()) cudaFreeHost(impl_->ple_emb_host[b]);}if (impl_->copy) cudaStreamDestroy(impl_->copy);+ if (impl_->kv_copy) cudaStreamDestroy(impl_->kv_copy);+ if (impl_->kv_released) cudaEventDestroy(impl_->kv_released);+ if (impl_->kv_ready) cudaEventDestroy(impl_->kv_ready);if (impl_->grp_host) cudaFreeHost(impl_->grp_host);for (void* p : impl_->owned) cudaFree(p);}@@ -1011,7 +1017,8 @@ bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max);return false;}- if (cudaStreamSynchronize(m.cs) != cudaSuccess || cudaStreamSynchronize(m.copy) != cudaSuccess) {+ if (cudaStreamSynchronize(m.cs) != cudaSuccess || cudaStreamSynchronize(m.copy) != cudaSuccess ||+ (m.kv_copy && cudaStreamSynchronize(m.kv_copy) != cudaSuccess)) {err = "prefill: relayout: the stream failed";return false;}@@ -1637,6 +1644,22 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stristrata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;s.idx_dim = g.idx_key_dim;+ const char* kv_env = std::getenv("STRATA_KV_PREFETCH");+ const bool kv_prefetch = kv_env && std::atoi(kv_env) != 0;+ if (kv_prefetch) {+ if ((!m.kv_copy && cudaStreamCreateWithFlags(&m.kv_copy, cudaStreamNonBlocking) != cudaSuccess) ||+ (!m.kv_released && cudaEventCreateWithFlags(&m.kv_released, cudaEventDisableTiming) != cudaSuccess) ||+ (!m.kv_ready && cudaEventCreateWithFlags(&m.kv_ready, cudaEventDisableTiming) != cudaSuccess)) {+ err = "prefill: KV prefetch stream/events";+ return false;+ }+ }+ // An early return must drain DMA before the caller refills the borrowed expert slots.+ struct KvDrain {+ cudaStream_t stream;+ ~KvDrain() { if (stream) cudaStreamSynchronize(stream); }+ } kv_drain{kv_prefetch ? m.kv_copy : nullptr};+ int64_t kv_prefetches = 0;const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +(uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};@@ -1803,6 +1826,34 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::striint64_t qsa_index = 0, gdn_index = 0;for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;+ int64_t kv_pending = -1;+ auto kv_prefetch_after = [&](int64_t layer, int64_t ordinal) -> bool {+ if (!kv_prefetch || p0 <= 0) return true;+ for (int64_t l = layer; l < LE; ++l) {+ if (!core::is_qsa_layer(g, l)) continue;+ const core::QsaState& state = ss.qsa_states[ordinal];+ if (state.kv_mode != 1) { ++ordinal; continue; }+ // Reuse one KV pool only after its last attention reader completes. The next layer's+ // [0, p0) host prefix is immutable throughout this chunk; its new rows are appended later.+ if (cudaEventRecord(m.kv_released, cs) != cudaSuccess ||+ cudaStreamWaitEvent(m.kv_copy, m.kv_released, 0) != cudaSuccess) {+ err = "prefill: releasing KV staging pool";+ return false;+ }+ strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), state.host,+ core::qsa_kv_format(state), (p0 + s.page_size - 1) / s.page_size, s, m.kv_copy);+ if (cudaPeekAtLastError() != cudaSuccess ||+ cudaEventRecord(m.kv_ready, m.kv_copy) != cudaSuccess) {+ err = "prefill: enqueueing KV prefetch";+ return false;+ }+ kv_pending = ordinal;+ ++kv_prefetches;+ break;+ }+ return true;+ };+ if (!kv_prefetch_after(LB, qsa_index)) return false;// step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry// k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's// `used` event recorded), so the copy stream never waits on an event that is not queued yet@@ -2172,7 +2223,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::striconst bool staged = st.kv_mode == 1;if (staged) {pt.mark(kPfKvStage, cs);- strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,+ if (kv_pending == qsa_index) {+ if (cudaStreamWaitEvent(cs, m.kv_ready, 0) != cudaSuccess) {+ err = "prefill: waiting for KV prefetch";+ return false;+ }+ kv_pending = -1;+ } else strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host,core::qsa_kv_format(st),(p0 + s.page_size - 1) / s.page_size, s, m.cs);pt.mark(kPfQsa, cs);@@ -2371,6 +2428,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::strigate_attn(m.attn, m.Qf, m.attn_h, T, m.cs, ld_a);if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err, 0, ld_a)) return false;++qsa_index;+ if (!kv_prefetch_after(l + 1, qsa_index)) return false;} else {// ======================= MoE =======================const core::WeightRef *wr = need(v, "ffn_gate_inp.weight", err),@@ -3208,6 +3266,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::strierr = std::string("prefill: expert copy stream: ") + cudaGetErrorString(cst);return false;}+ if (kv_prefetch) {+ if (const cudaError_t cst = cudaStreamSynchronize(m.kv_copy); cst != cudaSuccess) {+ err = std::string("prefill: KV prefetch stream: ") + cudaGetErrorString(cst);+ return false;+ }+ std::fprintf(stderr, "strata KV prefetch: %lld layer prefixes, single existing staging pool\n",+ (long long) kv_prefetches);+ }stats_.ms_total += ms_since(t_start);if (pt.on) {pt.fold();