Skip to content

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++

engine: fix a race in the CPU expert pool, and never hang silently again (issue #29, engine 0.1.12)

Niko12219ffd6c94618c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1acade5e7..84882d090 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -550,6 +550,10 @@ if(STRATA_BUILD_TESTS)
add_executable(pool_test src/kernels/cpu/pool_test.cpp)
target_link_libraries(pool_test PRIVATE strata_kernels_cpu)
add_test(NAME pool_test COMMAND pool_test --selftest WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
+ # issue #29: tiny batches with sleeping workers, as on a big-VRAM card; a hang fails it
+ add_executable(pool_stress src/kernels/cpu/pool_stress.cpp)
+ target_link_libraries(pool_stress PRIVATE strata_kernels_cpu)
+ add_test(NAME pool_stress COMMAND pool_stress 20)
endif()
if(STRATA_BUILD_TESTS)
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 9e821ce4b..0d62337a5 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -381,6 +381,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`.
| A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). |
| Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). |
| A request never finishes: "reading the prompt", GPU "100%" at low power | The GPU ran out of VRAM (engines before 0.1.9 could end with ~30 MiB free at large contexts). Run `START-HERE.bat` once to get engine 0.1.9 or newer; the log then says `... MiB of VRAM free with everything loaded` (a few hundred) and names the `--vram-reserve-mib` to add if it is low. |
+| Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving for 2 minutes ends with an error instead of hanging: the log says `no progress for 120 s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. (`STRATA_WATCHDOG_S` sets the 120 s; 0 turns it off.) |
| Anything else | The engine log is `strata-<model>.log` in this folder. |
---
diff --git a/include/strata/core/progress.hpp b/include/strata/core/progress.hpp
new file mode 100644
index 000000000..5b27a5336
--- /dev/null
+++ b/include/strata/core/progress.hpp
@@ -0,0 +1,35 @@
+// include/strata/core/progress.hpp - issue #29: whether a request is still moving, and where it is.
+//
+// The engine's host loop and the GPU wait on each other through flags; a protocol bug there does not crash, it
+// spins forever (the GPU "100%", one CPU core busy, no tokens). `--serve` runs a watchdog thread over this: a
+// request whose heartbeat stops for `STRATA_WATCHDOG_S` seconds (default 120; 0 = off) ends the engine with the
+// stage it was stuck in, and the server starts it again instead of hanging. Tokens, prompt chunks and verify
+// windows beat; the stage is two relaxed stores per layer, which the token path does not notice.
+#pragma once
+
+#include <atomic>
+#include <cstdint>
+
+namespace strata::core {
+
+struct Progress {
+ std::atomic<uint64_t> beats{0};
+ std::atomic<bool> busy{false};
+ std::atomic<const char*> where{"idle"};
+ std::atomic<int64_t> detail{-1};
+};
+
+inline Progress& progress() {
+ static Progress p;
+ return p;
+}
+
+inline void progress_at(const char* where, int64_t detail = -1) {
+ Progress& p = progress();
+ p.where.store(where, std::memory_order_relaxed);
+ p.detail.store(detail, std::memory_order_relaxed);
+}
+
+inline void progress_beat() { progress().beats.fetch_add(1, std::memory_order_relaxed); }
+
+} // namespace strata::core
diff --git a/include/strata/kernels/cpu/pool.hpp b/include/strata/kernels/cpu/pool.hpp
index 314c65be2..a74246a90 100644
--- a/include/strata/kernels/cpu/pool.hpp
+++ b/include/strata/kernels/cpu/pool.hpp
@@ -14,9 +14,17 @@
// THE COMPLETION PROTOCOL, because this is where a pool usually goes wrong. `run()` waits for `done == n`
// AND for every worker to PARK. Waiting only for `done` is not enough: a worker can still be inside the
// drain loop after its last `done` increment, and the host resetting `head` underneath it would let that
-// worker claim a job from the NEXT batch before the next batch has been published. The
-// `done`-then-`parked` pair makes the handover unambiguous, and the second wait costs a few hundred cycles
-// against a layer that takes milliseconds.
+// worker claim a job from the NEXT batch before the next batch has been published.
+//
+// **AND `parked` IS NOT ENOUGH EITHER (issue #29).** A worker that went to sleep (after `kSpinBeforeSleep`) is
+// still counted as parked when it wakes, so for a moment after it has seen a new epoch the host believes it is
+// idle. On a card with most experts in VRAM the workers sleep in the middle of a request, tiny batches finish
+// before a sleeper is awake, and that moment comes round constantly: a late worker could claim from the NEXT
+// batch while the host was still writing it, run a job twice, or add to `done` after the host had reset it -
+// and `done != n` then never ended, with the GPU waiting on the pool forever. So every claim carries its
+// batch: `head` is one 64-bit word `epoch | njobs | index`, a claim is a CAS that only succeeds for the epoch
+// the worker woke for, and a late worker's claim simply fails. A claim that succeeds belongs to the current
+// batch, whose description the host cannot change until that job's `done` has landed.
#pragma once
#include "strata/kernels/cpu/expert.hpp"
@@ -142,14 +150,26 @@ public:
/// **A PARKED WORKER SPINS FOR THIS LONG, THEN SLEEPS.** The park is a `_mm_pause` spin because a layer's
/// batches are microseconds apart and a wake-up from the OS costs more than that. But a spin that never ends
/// keeps every worker's core at 100% while the engine waits for a request - issue #4, "CPU 50% even when
- /// doing nothing" (7 of the 5700X's 16 threads). Inside a request the gaps between batches are far below
- /// this, so the token path still never sleeps; between requests the workers block on `sleep_cv_`.
+ /// doing nothing" (7 of the 5700X's 16 threads). Between requests the workers block on `sleep_cv_`. NOT only
+ /// between requests: with most experts in VRAM (a 24 GB card) many layers have no CPU work, so the workers
+ /// also sleep mid-request - which the claim protocol above must survive (issue #29).
+ /// `STRATA_POOL_SPIN_US` overrides it (a test knob: a short spin makes the workers sleep constantly).
static constexpr std::chrono::milliseconds kSpinBeforeSleep{20};
+ /// A pool wait that sees no completion for this long is a bug; the engine stops with a message instead of
+ /// spinning forever, and the server starts it again (issue #29).
+ static constexpr std::chrono::seconds kStall{60};
private:
void worker(int id);
- void drain(int id, ExpertScratch& scratch);
+ void drain(int id, ExpertScratch& scratch, uint32_t epoch);
void run_phase(int mode, int n_tasks);
+ /// Claim the next job of batch `epoch`, or -1 (that batch is exhausted, or it is not the current one).
+ int claim(uint32_t epoch);
+ /// Publish the batch whose description the caller has just written: reset `done`, then `head`, then the epoch.
+ uint32_t begin_batch(int n);
+ /// The host's waits, bounded by `kStall`.
+ void wait_parked(const char* what);
+ void wait_done(int n);
/// Bump `epoch_`, and wake the workers that went to sleep. Every publish goes through here.
void publish();
@@ -176,7 +196,7 @@ private:
//
// The counter was diagnostic only - `pauses()` was read in one place, to print a number nothing branched on
// - so it is deleted rather than amortised. `alignas(64)` then stops the remaining four sharing.
- alignas(64) std::atomic<uint32_t> head_{0};
+ alignas(64) std::atomic<uint64_t> head_{0}; // epoch << 32 | njobs << 16 | next index (issue #29)
alignas(64) std::atomic<uint32_t> done_{0};
alignas(64) std::atomic<uint32_t> parked_{0};
alignas(64) std::atomic<uint32_t> epoch_{0};
@@ -186,6 +206,7 @@ private:
alignas(64) std::atomic<uint32_t> sleepers_{0};
std::mutex sleep_mu_;
std::condition_variable sleep_cv_;
+ std::chrono::microseconds spin_before_sleep_{kSpinBeforeSleep};
std::vector<std::thread> threads_;
std::vector<ExpertScratch> scratch_; // one per worker: no allocation, no false sharing of the hot data
// run_split state: mode 0 = whole experts, 1 = gate/up row parts, 2 = down row parts
diff --git a/serve/server.py b/serve/server.py
index 175125ef8..1951d9984 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -123,6 +123,24 @@ class StrataEngine:
self.ended = True # its output closed: it is gone, even before the OS says so
self.lines.put(None)
+ def death_note(self) -> str:
+ """Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM."""
+ tail = ""
+ try:
+ with open(self.log_path, "rb") as f:
+ f.seek(0, 2)
+ f.seek(max(0, f.tell() - 4096))
+ tail = f.read().decode("utf-8", "replace")
+ except (OSError, TypeError):
+ pass
+ for line in reversed(tail.splitlines()):
+ if "issue #29" in line:
+ return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log "
+ "line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.")
+ return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | "
+ "grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a "
+ "smaller model (Q2_0 / IQ2_XS).")
+
def alive(self) -> bool:
return not getattr(self, "ended", False) and self.proc.poll() is None
@@ -633,10 +651,9 @@ class Service:
finish = "cancel"
except EngineDied as e:
finish = "error"
- print(f"[strata] {e}. The usual cause is running out of RAM: Linux then ends the biggest program "
- "(check: sudo dmesg | grep -i -E 'killed process|out of memory'); Windows slows down instead. "
- "Close other programs or use a smaller model (Q2_0 / IQ2_XS). The next request starts the engine "
- f"again.{' Its log: ' + self.engine.log_path if getattr(self.engine, 'log_path', None) else ''}",
+ note = self.engine.death_note() if hasattr(self.engine, "death_note") else ""
+ print(f"[strata] {e}. {note} The next request starts the engine again."
+ f"{' Its log: ' + self.engine.log_path if getattr(self.engine, 'log_path', None) else ''}",
flush=True)
raise
finally:
diff --git a/setup.py b/setup.py
index d737b33d4..d78c1f7f2 100644
--- a/setup.py
+++ b/setup.py
@@ -56,7 +56,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip"
# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages
CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"]
MIN_DRIVER = 580 # CUDA 13.0
-MIN_ENGINE = (0, 1, 10) # INFO arena_mib: the start-up RAM warning (issue #27), v0.1.10
+MIN_ENGINE = (0, 1, 12) # the expert-pool race and the serve watchdog (issue #29), v0.1.12
PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"]
MODELS = {
diff --git a/src/core/session.cpp b/src/core/session.cpp
index cf0bbde2f..7578ad32e 100644
--- a/src/core/session.cpp
+++ b/src/core/session.cpp
@@ -1,5 +1,6 @@
// src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer.
#include "strata/core/session.hpp"
+#include "strata/core/progress.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/elementwise.hpp"
@@ -888,6 +889,7 @@ bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, Se
const auto t0 = Clock::now();
auto last_flush = t0;
uint32_t spins = 0;
+ progress_at("token: waiting for the GPU to reach layer", l);
while (*seq < want) {
STRATA_SPIN_PAUSE();
if ((++spins & 1023u) != 0) continue;
@@ -909,6 +911,7 @@ bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, Se
}
}
const auto t1 = Clock::now();
+ progress_at("token: the CPU experts of layer", l);
if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, s.k, y_miss_host);
std::atomic_thread_fence(std::memory_order_seq_cst);
_mm_sfence();
@@ -917,8 +920,11 @@ bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, Se
tg.ms_wait += std::chrono::duration<double, std::milli>(t1 - t0).count();
tg.ms_pool += std::chrono::duration<double, std::milli>(t2 - t1).count();
}
+ progress_at("token: waiting for the GPU to finish the token");
const cudaError_t se = cudaStreamSynchronize(cs);
if (se != cudaSuccess) { err = std::string("session_run_token: ") + cudaGetErrorString(se); return false; }
+ progress_at("decode");
+ progress_beat();
return true;
}
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
index 6762d11a3..39bb06ecb 100644
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -28,6 +28,7 @@
#include "strata/kernels/rope.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
#include "strata/kernels/sampler.hpp"
+#include "strata/core/progress.hpp"
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/verify_kernels.hpp"
@@ -772,6 +773,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
const Clock::time_point a = Clock::now();
auto last_flush = a;
uint32_t spins = 0;
+ progress_at("verify window: waiting for the GPU to reach layer", l);
while (*seq < want) {
_mm_pause();
if ((++spins & 1023u) != 0) continue;
@@ -792,6 +794,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
cur_layer_ = want - 1;
set_plan_slot(grp);
const int tb = gtb[grp], n = gte[grp] - gtb[grp];
+ progress_at("verify window: the CPU experts of layer", l);
if (pool != nullptr)
pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k,
h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);
@@ -812,8 +815,10 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
ms_wait += std::chrono::duration<double, std::milli>(b - a).count();
ms_pool += ms_since(b);
}
+ progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T);
const cudaError_t se = cudaStreamSynchronize(cs_);
if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
+ progress_at("verify window: waiting for the expert copies", (int64_t) T);
cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one
// ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's
// own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to
@@ -832,6 +837,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
VDBG("window done\n");
++windows;
+ progress_at("decode");
+ progress_beat();
return true;
}
diff --git a/src/kernels/cpu/pool.cpp b/src/kernels/cpu/pool.cpp
index 7b87c5ca1..d6a386204 100644
--- a/src/kernels/cpu/pool.cpp
+++ b/src/kernels/cpu/pool.cpp
@@ -8,6 +8,7 @@
#include <immintrin.h>
#include <cstdio>
+#include <cstdlib>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
@@ -19,6 +20,12 @@
namespace strata::kernels::cpu {
+namespace {
+constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) {
+ return ((uint64_t) epoch << 32) | ((uint64_t) n << 16) | (uint64_t) i;
+}
+} // namespace
+
std::vector<int> physical_cores(bool skip_first) {
std::vector<int> cores;
#if defined(_WIN32)
@@ -109,6 +116,8 @@ void restore_thread_affinity(long long previous) {
}
ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works) : host_works_(host_works) {
+ if (const char* e = std::getenv("STRATA_POOL_SPIN_US")) // a test knob; see kSpinBeforeSleep
+ spin_before_sleep_ = std::chrono::microseconds((std::max)(0, std::atoi(e)));
const std::vector<int> cores = physical_cores(true);
n_ = n_workers > 0 ? n_workers : (int) cores.size();
if (n_ < 1) n_ = 1;
@@ -170,7 +179,7 @@ void ExpertPool::worker(int id) {
if (stop_.load(std::memory_order_relaxed)) return;
_mm_pause();
if ((++spins & 1023u) != 0) continue;
- if (std::chrono::steady_clock::now() - parked_at < kSpinBeforeSleep) continue;
+ if (std::chrono::steady_clock::now() - parked_at < spin_before_sleep_) continue;
std::unique_lock<std::mutex> lk(sleep_mu_);
sleepers_.fetch_add(1, std::memory_order_seq_cst);
sleep_cv_.wait(lk, [&] {
@@ -179,21 +188,87 @@ void ExpertPool::worker(int id) {
sleepers_.fetch_sub(1, std::memory_order_relaxed);
}
if (stop_.load(std::memory_order_acquire)) return;
- seen = epoch_.load(std::memory_order_relaxed);
+ // acquire: the batch this epoch published (`head`, and the description before it) is visible from here
+ seen = epoch_.load(std::memory_order_acquire);
parked_.fetch_sub(1, std::memory_order_acq_rel); // leaving the park
// Drain: one claim per iteration, so a slow worker takes fewer experts and a fast one takes more.
- // Every job is the same size (all experts are 1,382,400 bytes), so there is nothing to schedule.
- drain(id, scratch_[(size_t) id]);
+ // Every job is the same size (all experts are 1,382,400 bytes), so there is nothing to schedule. Only
+ // this epoch's jobs: if the host has already moved on, the claims fail and the worker parks again.
+ drain(id, scratch_[(size_t) id], seen);
parked_.fetch_add(1, std::memory_order_acq_rel); // back at the park
}
}
-void ExpertPool::drain(int id, ExpertScratch& scratch) {
+int ExpertPool::claim(uint32_t epoch) {
+ uint64_t h = head_.load(std::memory_order_acquire);
+ for (;;) {
+ if ((uint32_t) (h >> 32) != epoch) return -1; // not the batch this thread woke for
+ const uint32_t n = (uint32_t) (h >> 16) & 0xffffu, i = (uint32_t) h & 0xffffu;
+ if (i >= n) return -1; // exhausted
+ if (head_.compare_exchange_weak(h, h + 1, std::memory_order_acq_rel, std::memory_order_acquire))
+ return (int) i;
+ }
+}
+
+uint32_t ExpertPool::begin_batch(int n) {
+ if (n < 0 || n > 0xffff) {
+ std::fprintf(stderr, "strata: expert pool batch of %d jobs is out of range\n", n);
+ std::abort();
+ }
+ // Every job of the previous batch has completed (`wait_done`), and a claim of it can no longer succeed, so
+ // nothing adds to `done` until this batch's first claim - which the release below orders after the reset.
+ done_.store(0, std::memory_order_relaxed);
+ const uint32_t e = epoch_.load(std::memory_order_relaxed) + 1; // only the host bumps the epoch
+ head_.store(pack_head(e, (uint32_t) n, 0), std::memory_order_release);
+ publish();
+ return e;
+}
+
+void ExpertPool::wait_parked(const char* what) {
+ uint32_t spins = 0;
+ std::chrono::steady_clock::time_point t0{};
+ while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) {
+ _mm_pause();
+ if ((++spins & 1023u) != 0) continue;
+ const auto now = std::chrono::steady_clock::now();
+ if (spins == 1024u) t0 = now;
+ else if (now - t0 > kStall) {
+ std::fprintf(stderr, "strata: the CPU expert pool stalled %s (%u of %d workers parked) - stopping the engine "
+ "so the server can start it again (issue #29)\n",
+ what, parked_.load(), n_);
+ std::fflush(stderr);
+ std::abort();
+ }
+ }
+}
+
+void ExpertPool::wait_done(int n) {
+ uint32_t spins = 0, seen = 0;
+ std::chrono::steady_clock::time_point t0{};
+ for (;;) {
+ const uint32_t d = done_.load(std::memory_order_acquire);
+ if (d >= (uint32_t) n) return; // `>=`: never a wait that an overshoot outlives
+ _mm_pause();
+ if ((++spins & 1023u) != 0) continue;
+ const auto now = std::chrono::steady_clock::now();
+ if (spins == 1024u || d != seen) { t0 = now; seen = d; } // progress restarts the clock
+ else if (now - t0 > kStall) {
+ std::fprintf(stderr, "strata: the CPU expert pool stalled: %u of %d jobs done, %u of %d workers parked - "
+ "stopping the engine so the server can start it again (issue #29)\n",
+ d, n, parked_.load(), n_);
+ std::fflush(stderr);
+ std::abort();
+ }
+ }
+}
+
+void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) {
(void) id;
for (;;) {
- const uint32_t i = head_.fetch_add(1, std::memory_order_relaxed);
- if (i >= (uint32_t) njobs_) break;
+ const int ci = claim(epoch);
+ if (ci < 0) break;
+ const uint32_t i = (uint32_t) ci;
if (mode_ == 0) {
const ExpertJob& j = jobs_[i];
s2_expert_vnni_q(j.blob, *j.act, j.out, scratch);
@@ -267,15 +342,13 @@ void ExpertPool::drain(int id, ExpertScratch& scratch) {
}
void ExpertPool::run_phase(int mode, int n_tasks) {
- while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) _mm_pause();
+ wait_parked("before a phase");
mode_ = mode;
njobs_ = n_tasks;
- head_.store(0, std::memory_order_relaxed);
- done_.store(0, std::memory_order_relaxed);
- publish();
- if (host_works_) drain(-1, host_scratch_);
- while (done_.load(std::memory_order_acquire) != (uint32_t) n_tasks) _mm_pause();
- while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) _mm_pause();
+ const uint32_t e = begin_batch(n_tasks);
+ if (host_works_) drain(-1, host_scratch_, e);
+ wait_done(n_tasks);
+ wait_parked("after a phase");
}
void ExpertPool::run_split(ExpertJob* jobs, int n) {
@@ -376,14 +449,12 @@ void ExpertPool::run(ExpertJob* jobs, int n) {
// THE THREE PHASES ARE TIMED SEPARATELY. They were one number, which cannot distinguish a pool that is
// slow at the WORK from one that is slow at the SYNCHRONISATION - and those need opposite fixes.
const auto t_a = std::chrono::steady_clock::now();
- while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) _mm_pause();
+ wait_parked("before a batch");
const auto t_b = std::chrono::steady_clock::now();
jobs_ = jobs;
njobs_ = n;
mode_ = 0;
- head_.store(0, std::memory_order_relaxed);
- done_.store(0, std::memory_order_relaxed);
- publish(); // a release (seq_cst): jobs_/njobs_ are visible before the bump
+ const uint32_t e = begin_batch(n); // done, then head (release), then the epoch: the batch is described first
// ---- **THE HOST DRAINS TOO (R2.2), INSTEAD OF SPINNING ON `done_`.**
//
@@ -401,19 +472,19 @@ void ExpertPool::run(ExpertJob* jobs, int n) {
// device after `run()` returns, so the write must be published, not merely performed.
if (host_works_) {
for (;;) {
- const uint32_t i = head_.fetch_add(1, std::memory_order_relaxed);
- if (i >= (uint32_t) n) break;
- const ExpertJob& j = jobs_[i];
+ const int ci = claim(e);
+ if (ci < 0) break;
+ const ExpertJob& j = jobs_[ci];
s2_expert_vnni_q(j.blob, *j.act, j.out, host_scratch_);
done_.fetch_add(1, std::memory_order_release);
}
}
- while (done_.load(std::memory_order_acquire) != (uint32_t) n) _mm_pause();
+ wait_done(n);
// And park again, so the next `run` starts from a known state. See the header for why `done` alone is
// not enough.
const auto t_c = std::chrono::steady_clock::now();
- while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) _mm_pause();
+ wait_parked("after a batch");
const auto t_d = std::chrono::steady_clock::now();
ms_wait_park_ += std::chrono::duration<double, std::milli>(t_b - t_a).count();
diff --git a/src/kernels/cpu/pool_stress.cpp b/src/kernels/cpu/pool_stress.cpp
new file mode 100644
index 000000000..2c9fca544
--- /dev/null
+++ b/src/kernels/cpu/pool_stress.cpp
@@ -0,0 +1,99 @@
+// src/kernels/cpu/pool_stress.cpp - issue #29: the expert pool under the load a big-VRAM card gives it.
+//
+// With most experts resident on the GPU, many layers hand the pool nothing, the workers go to sleep in the middle
+// of a request, and the next tiny batch (one or two experts) is often finished by the host and the awake workers
+// before a sleeper has even woken. That late wake-up is what the park/claim protocol has to survive. This drives
+// hundreds of thousands of such batches - 0-4 jobs, run() and run_split(), with pauses long enough for the workers
+// to sleep - and checks that every batch returns, with every job's output written. A watchdog thread turns a
+// hang into a failure instead of a frozen test.
+//
+// pool_stress [seconds] (default 20)
+#include "strata/kernels/cpu/pool.hpp"
+#include "strata/kernels/cpu/expert.hpp"
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <random>
+#include <thread>
+#include <vector>
+
+namespace cpu = strata::kernels::cpu;
+
+int main(int argc, char** argv) {
+ const double seconds = argc > 1 ? std::atof(argv[1]) : 20.0;
+ const cpu::CpuFeatures feat = cpu::cpu_features();
+ if (!feat.usable()) {
+ std::printf("CPU lacks %s: pool_stress SKIPPED\n", feat.reason());
+ return 0;
+ }
+ constexpr int NJ = 4;
+ std::vector<std::vector<uint8_t>> blobs(NJ, std::vector<uint8_t>(cpu::BLOB, 0));
+ std::vector<float> x(cpu::H, 0.25f);
+ cpu::ActQ act;
+ cpu::act_quant_q8_1(x.data(), cpu::H, act);
+ std::vector<float> out((size_t) NJ * cpu::H);
+ std::vector<cpu::ExpertJob> jobs(NJ);
+ for (int e = 0; e < NJ; ++e) {
+ jobs[(size_t) e].blob = blobs[(size_t) e].data();
+ jobs[(size_t) e].act = &act;
+ jobs[(size_t) e].out = out.data() + (size_t) e * cpu::H;
+ jobs[(size_t) e].slot = e;
+ }
+
+ cpu::ExpertPool pool;
+ std::printf("pool_stress: %d workers + host, %.0f s\n", pool.workers(), seconds);
+
+ // the watchdog: a batch that does not return within 10 s is a hang
+ std::atomic<long long> beat{0};
+ std::atomic<bool> finished{false};
+ std::thread dog([&] {
+ long long last = -1;
+ auto since = std::chrono::steady_clock::now();
+ while (!finished.load()) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(200));
+ const long long b = beat.load();
+ const auto now = std::chrono::steady_clock::now();
+ if (b != last) { last = b; since = now; continue; }
+ if (now - since > std::chrono::seconds(10)) {
+ std::printf("\npool_stress: HANG - batch %lld has not returned for 10 s\n", b);
+ std::fflush(stdout);
+ std::_Exit(3);
+ }
+ }
+ });
+
+ std::mt19937 rng(29);
+ const float SENTINEL = -1.2345e33f;
+ long long batches = 0, sleeps = 0, missed = 0;
+ const auto t0 = std::chrono::steady_clock::now();
+ while (std::chrono::steady_clock::now() - t0 < std::chrono::duration<double>(seconds)) {
+ // now and then a gap long enough for every worker to go to sleep (the pool sleeps after 20 ms)
+ if (rng() % 64 == 0) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(21 + (int) (rng() % 10)));
+ ++sleeps;
+ } else if (rng() % 4 == 0) {
+ std::this_thread::sleep_for(std::chrono::microseconds(rng() % 300));
+ }
+ const int n = (int) (rng() % (NJ + 1));
+ for (int e = 0; e < n; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL);
+ if (rng() % 2) pool.run(jobs.data(), n);
+ else pool.run_split(jobs.data(), n);
+ for (int e = 0; e < n; ++e)
+ if (jobs[(size_t) e].out[0] == SENTINEL || jobs[(size_t) e].out[cpu::H - 1] == SENTINEL) ++missed;
+ beat.fetch_add(1);
+ ++batches;
+ }
+ finished.store(true);
+ dog.join();
+ std::printf("pool_stress: %lld batches (%lld after the workers slept), %lld jobs not run\n", batches, sleeps,
+ missed);
+ if (missed) {
+ std::printf("pool_stress: FAILED\n");
+ return 1;
+ }
+ std::printf("pool_stress OK\n");
+ return 0;
+}
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 15df9e543..da5d138bb 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -45,6 +45,7 @@
#include "strata/spec/draft_policy.hpp"
#include "strata/spec/suffix_drafter.hpp"
#include "strata/kernels/cvec.hpp"
+#include "strata/core/progress.hpp"
#ifndef NOMINMAX
#define NOMINMAX // gguf_reader.hpp includes windows.h
#endif
@@ -2200,6 +2201,8 @@ int main(int argc, char** argv) {
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - pp_t0).count();
std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) pp_total, ms,
ms > 0.0 ? 1000.0 * (double) (done - pp_from) / ms : 0.0);
+ strata::core::progress_at("reading the prompt (batched), done up to token", done);
+ strata::core::progress_beat();
std::fflush(stdout);
if (o.prompt_cache_every > 0 && done >= pp_next_check) {
if (!checkpoint_at(done)) { e = "saving a conversation checkpoint failed"; return false; }
@@ -2335,6 +2338,31 @@ int main(int argc, char** argv) {
o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(),
(long long) (strata::kernels::cpu::expert_layout().total >> 20));
}
+ // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on
+ // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the
+ // GPU spinning forever. STRATA_WATCHDOG_S=0 turns it off.
+ {
+ const char* ws = std::getenv("STRATA_WATCHDOG_S");
+ const int limit = ws ? std::atoi(ws) : 120;
+ if (limit > 0)
+ std::thread([limit] {
+ strata::core::Progress& p = strata::core::progress();
+ uint64_t last = p.beats.load();
+ auto since = std::chrono::steady_clock::now();
+ for (;;) {
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ const auto now = std::chrono::steady_clock::now();
+ const uint64_t b = p.beats.load();
+ if (!p.busy.load() || b != last) { last = b; since = now; continue; }
+ if (now - since < std::chrono::seconds(limit)) continue;
+ std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s %lld) - stopping "
+ "the engine so the server starts it again (issue #29)\n",
+ limit, p.where.load(), (long long) p.detail.load());
+ std::fflush(stderr);
+ std::abort();
+ }
+ }).detach();
+ }
std::printf("READY %lld stop\n", (long long) o.max_context); // "stop": this engine honours STOP
std::fflush(stdout);
std::string line;
@@ -2354,6 +2382,11 @@ int main(int argc, char** argv) {
std::vector<const float*> row_ptr;
while (next_line(line)) {
if (line == "QUIT") break;
+ // the watchdog watches a request from here until this iteration ends, whichever way it ends
+ struct BusyScope {
+ BusyScope() { strata::core::progress().busy.store(true); strata::core::progress_at("request"); }
+ ~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); }
+ } busy_scope;
stop_req.store(false); // a STOP that arrived between requests is stale
const bool geni = line.rfind("GENI ", 0) == 0;
if (!geni && line.rfind("GEN ", 0) != 0) {
@@ -2573,6 +2606,7 @@ int main(int argc, char** argv) {
pp_t0 = r0;
pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every;
std::printf("RESUME %lld\n", (long long) resume); // before reading: this many prompt tokens are reused
+ strata::core::progress_at("reading the prompt, from token", read_from);
std::fflush(stdout);
// A SHORT PART OF THE PROMPT - the new message of a chat that continues from a checkpoint, the assistant
// header - goes through the verify windows, S tokens at a time, as decode reads them. The batched path
@@ -2612,6 +2646,7 @@ int main(int argc, char** argv) {
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - pp_t0).count();
std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms,
ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0);
+ strata::core::progress_beat();
std::fflush(stdout);
return true;
};
@@ -2795,6 +2830,7 @@ int main(int argc, char** argv) {
bool eos = false;
for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) {
std::printf("T %d\n", (int) outv[(size_t) i]);
+ strata::core::progress_beat();
++produced_n;
if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);
eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();