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

batch-groups: read a prompt beside the decoding slots on a thread of its own (opt-in, experimental STRATA_PIPED_CONCURRENT)

SuperDistancebc90e1acffde
diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp
index d3c05a982..7216f015a 100644
--- a/include/strata/core/mtp.hpp
+++ b/include/strata/core/mtp.hpp
@@ -92,6 +92,10 @@ public:
/// --pipeline-windows: capture the prefill graphs and size its input records for windows of up to max_t rows now,
/// so a later prefill(sync = false) of a window neither captures nor allocates (both wait for the device).
bool prepare_prefill(std::string& err);
+ /// A prompt read beside running batch windows (STRATA_PIPED_CONCURRENT): the prompt pass's graphs captured and its
+ /// input records sized for chunks of up to n rows now, with nothing in flight. On the read's thread a capture or
+ /// a free waits for the device, whose windows wait for the main thread's doorbell service (#31).
+ bool reserve_prefill(int64_t n, std::string& err);
cudaStream_t stream() const { return cs_; }
/// One round: catch-up over T cells from `p` (rows = the window's final residuals, `tokens` = the window's
diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp
index a9dc19dbd..f04475ddb 100644
--- a/include/strata/core/verify.hpp
+++ b/include/strata/core/verify.hpp
@@ -217,7 +217,14 @@ public:
/// 1 = this stage's window and commit are done (the last stage's picks are in batch_out), 0 = still running,
/// -1 = an error (err). Serves every layer that has rung so far.
int batch_poll(PoolMultiFn pool, void* user, std::string& err);
- bool batch_busy() const { return b_running_; }
+ bool batch_busy() const { return b_running_.load(std::memory_order_acquire); }
+ /// Serves the layers of this stage's window that have rung (the CPU pool and the flags), with no CUDA call: 1 once
+ /// every layer is served (or the window raises no host doorbells), 0 while one is still to ring. batch_poll
+ /// calls it, unless set_external_serve(true) moved it to a thread of its own (STRATA_PIPED_CONCURRENT: a CUDA
+ /// call can wait for the driver's lock while another thread holds it waiting for the GPU, whose window waits
+ /// for its doorbell, #31); batch_poll then makes no CUDA call before every layer is served.
+ int batch_serve(PoolMultiFn pool, void* user);
+ void set_external_serve(bool on) { ext_serve_.store(on, std::memory_order_release); }
/// A slot's sampling (temperature / top_p / top_k / min_p / seed; penalties are not applied in batch windows):
/// its row is drawn again on the last stage with Philox(seed, position), as a solo window draws it. Greedy by
/// default. Set on the first stage, it reaches the last.
@@ -341,9 +348,12 @@ private:
for (int t = 0; t < S; ++t) k.push_back(rows[t]);
return k;
}
- // batch_launch / batch_poll
- bool b_running_ = false;
- int64_t b_k_ = 0, b_steps_ = 0;
+ // batch_launch / batch_poll (with external serving, batch_serve runs on another thread: running and the served
+ // layer count are atomics, set by batch_launch before running)
+ std::atomic<bool> b_running_{false};
+ std::atomic<int64_t> b_k_{0};
+ int64_t b_steps_ = 0;
+ std::atomic<bool> ext_serve_{false};
std::chrono::steady_clock::time_point b_last_;
int32_t b_out_[8] = {};
std::vector<strata::kernels::SamplerParams> slot_sp_;
diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp
index b4f100df0..b5ddeff70 100644
--- a/include/strata/prefill/prefill.hpp
+++ b/include/strata/prefill/prefill.hpp
@@ -148,6 +148,12 @@ public:
/// Checked before every chunk: true stops the prompt early (`run` returns false with err "cancelled").
std::function<bool()> should_stop;
+ /// The first stage only, checked before every chunk but the first: true ends the run there as if the prompt
+ /// ended there. `run` returns true once every stage has read the tokens before that chunk, and `stopped_at()`
+ /// says how many of the run's tokens that is (-1 when the run read them all). A read beside the batch slots
+ /// (STRATA_PIPED_CONCURRENT) gives way to a waiting shorter request there.
+ std::function<bool()> stop_at_chunk;
+ int64_t stopped_at() const { return stopped_at_; }
/// The vision path: HOST rows (n_embd floats) indexed by absolute position, read in place of the token
/// embedding where non-null (an image's <|image_pad|> cells). Null (default): every position embeds its token.
@@ -200,6 +206,7 @@ private:
Prefill* next_ = nullptr;
Prefill* helper_ = nullptr; ///< set_stage_helper
bool single_chunk_ = false; ///< a later stage: the prompt is one chunk (set by the stage before)
+ int64_t stopped_at_ = -1; ///< stop_at_chunk ended the last run after this many tokens (-1: it read all)
bool bind_stage_helper(int64_t T); // binds the helper's buffers for a one-chunk prompt of T tokens
const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned)
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
index c36841c6c..f75288ca7 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -1368,6 +1368,40 @@ bool MtpDrafter::prepare_prefill(std::string& err) {
return true;
}
+// STRATA_MTP_PREFILL_SYNC: the prompt pass's per-group loop (see MtpDrafter::prefill); HIP's default
+static bool prefill_per_group_sync() {
+ static const bool v = [] {
+ if (const char* e = std::getenv("STRATA_MTP_PREFILL_SYNC")) return std::atoi(e) != 0;
+#if defined(STRATA_USE_HIP)
+ return true;
+#else
+ return false;
+#endif
+ }();
+ return v;
+}
+
+bool MtpDrafter::reserve_prefill(int64_t n, std::string& err) {
+ const OnDevice on_device(device_);
+ if (prefill_per_group_sync()) {
+ for (int T = 1; T <= max_t_; ++T)
+ if (!capture_prefill(T, err)) return false;
+ return true;
+ }
+ if (!prepare_prefill(err)) return false;
+ const int64_t per_row = 1 + 4 + g_->n_head;
+ if (n <= 0 || pf_cap_ >= n * per_row) return true;
+ if (pf_dev_) cudaFree(pf_dev_);
+ pf_dev_ = nullptr;
+ pf_cap_ = 0;
+ if (cudaMalloc((void**) &pf_dev_, (size_t) (n * per_row) * sizeof(int32_t)) != cudaSuccess) {
+ err = "mtp prefill: the input records do not fit";
+ return false;
+ }
+ pf_cap_ = n * per_row;
+ return true;
+}
+
bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err,
bool sync) {
#if defined(STRATA_GPU_METAL)
@@ -1389,14 +1423,7 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_
// in hipGraphLaunch or the final sync until the watchdog ends the engine. R9700, full IQ3_XXS, --kv-resident
// 32768, mixed load (chats, 32K and 7K prompts, deep follow-ups): E-4 hung in the first round on 2 of 2 tries,
// the old loop ran 30 of 30 rounds clean, prompt speed unchanged.
- static const bool per_group_sync = [] {
- if (const char* v = std::getenv("STRATA_MTP_PREFILL_SYNC")) return std::atoi(v) != 0;
-#if defined(STRATA_USE_HIP)
- return true;
-#else
- return false;
-#endif
- }();
+ const bool per_group_sync = prefill_per_group_sync();
const int64_t NHp = g_->n_head, per_row = 1 + 4 + NHp;
if (!per_group_sync && n > 0) {
if (pf_cap_ < n * per_row) {
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
index d7d500620..002b2d39a 100644
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -749,6 +749,23 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
sink_.staging = (unsigned long long) staging_;
sink_.staging_cap = kStagingBlobs;
(void) TS;
+ // STRATA_PIPED_CONCURRENT=1 (opt-in): a prompt can run on the same GPU while the batch windows run, so the windows'
+ // streams get the device's highest priority (HIP: the default priority, as the drafter's)
+ auto make_stream = [](cudaStream_t* s) -> cudaError_t {
+#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
+ static const bool hi = [] { // (STRATA_PIPED_CONCURRENT_PRIO=0: the default priority)
+ const char* v = std::getenv("STRATA_PIPED_CONCURRENT");
+ const char* p = std::getenv("STRATA_PIPED_CONCURRENT_PRIO");
+ return v != nullptr && std::atoi(v) != 0 && (p == nullptr || std::atoi(p) != 0);
+ }();
+ int lo = 0, top = 0;
+ if (hi && cudaDeviceGetStreamPriorityRange(&lo, &top) == cudaSuccess &&
+ cudaStreamCreateWithPriority(s, cudaStreamNonBlocking, top) == cudaSuccess)
+ return cudaSuccess;
+ cudaGetLastError();
+#endif
+ return cudaStreamCreateWithFlags(s, cudaStreamNonBlocking);
+ };
bool copy_made = false;
#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
// engine-latency, STRATA_COPY_HIP_PRIO=1 (opt-in): the copy stream at high priority, so it gets a hardware queue of
@@ -762,13 +779,13 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
(void) cudaGetLastError();
}
#endif
- if (!copy_made && cudaStreamCreateWithFlags(&copy_, cudaStreamNonBlocking) != cudaSuccess) {
+ if (!copy_made && make_stream(&copy_) != cudaSuccess) {
err = "verify: copy stream create failed";
return false;
}
if (ext_stream_ != nullptr) cs_ = ext_stream_; // set_stream (pipelined windows): the stage's shared stream
- else if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) cs_ = nullptr;
- if (cs_ == nullptr || cudaStreamCreateWithFlags(&sh_cs_, cudaStreamNonBlocking) != cudaSuccess) {
+ else if (make_stream(&cs_) != cudaSuccess) cs_ = nullptr;
+ if (cs_ == nullptr || make_stream(&sh_cs_) != cudaSuccess) {
err = "verify: stream create failed";
return false;
}
@@ -3266,22 +3283,20 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_
sx.ple_prev[0] = sx.ple_prev[1];
sx.ple_prev[1] = tokens[t];
}
- b_running_ = true;
b_k_ = 0;
b_steps_ = le_ - lb_;
b_last_ = Clock::now();
+ b_running_.store(true, std::memory_order_release); // last: an external server reads the rest after it
return true;
}
-int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
- if (!b_running_) return 1;
- const OnDevice on_device(device_);
+int Verifier::batch_serve(PoolMultiFn pool, void* user) {
+ if (!b_running_.load(std::memory_order_acquire)) return 1;
volatile uint32_t* const seq = h_seq_;
const int S = last_t_;
// #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer,
- // so the poll is just "has the graph finished" - except the PLE flag, which the graph's first wait reads and
- // only the host can raise (the same raise run_slot_rows makes). Per-window (ar_on): with a loan in flight the
- // doorbell graph needs the per-layer service below.
+ // except the PLE flag, which the graph's first wait reads and only the host can raise (the same raise
+ // run_slot_rows makes). Per-window (ar_on): with a loan in flight the doorbell graph needs the per-layer service.
if (ar_on() && ss_->ple.ready() && ple_stage()) {
std::atomic_thread_fence(std::memory_order_seq_cst);
_mm_sfence();
@@ -3289,24 +3304,7 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
}
while (!ar_on() && b_k_ < b_steps_) {
const uint32_t want = (uint32_t) (b_k_ + 1);
- if (*seq < want) {
- const auto now = Clock::now();
- if (now - b_last_ > std::chrono::milliseconds(2)) {
- const cudaError_t q = cudaStreamQuery(cs_);
- if (q != cudaErrorNotReady && *seq < want) {
- err = "verify batch: layer " + std::to_string(lb_ + b_k_) + " never rang (" +
- (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
- b_running_ = false;
- return -1;
- }
- if (now - b_last_ > std::chrono::seconds(20)) {
- err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) + released_note(release_gpu_waits(5000));
- b_running_ = false;
- return -1;
- }
- }
- return 0;
- }
+ if (*seq < want) return 0;
const Clock::time_point b = Clock::now();
cur_layer_ = want - 1;
set_plan_slot(0);
@@ -3329,7 +3327,39 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
*(volatile uint32_t*) h_flag_ = want;
ms_pool += ms_since(b);
b_last_ = Clock::now();
- ++b_k_;
+ b_k_.fetch_add(1, std::memory_order_release);
+ }
+ return 1;
+}
+
+int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
+ if (!b_running_) return 1;
+ // set_external_serve: another thread serves the doorbells (batch_serve); no CUDA call here until it has served
+ // every layer, so this thread never holds up a doorbell however long a CUDA call of its own waits
+ if (ext_serve_.load(std::memory_order_acquire) && !ar_on() && b_k_.load(std::memory_order_acquire) < b_steps_)
+ return 0;
+ const OnDevice on_device(device_);
+ const int S = last_t_;
+ // the layers that have rung so far (batch_serve); with one still to ring: did the graph finish without it, or
+ // has it waited too long?
+ if (!batch_serve(pool, user)) {
+ const auto now = Clock::now();
+ if (now - b_last_ > std::chrono::milliseconds(2)) {
+ const cudaError_t q = cudaStreamQuery(cs_);
+ if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < (uint32_t) (b_k_ + 1)) {
+ err = "verify batch: layer " + std::to_string(lb_ + b_k_) + " never rang (" +
+ (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
+ b_running_ = false;
+ return -1;
+ }
+ if (now - b_last_ > std::chrono::seconds(20)) {
+ err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) +
+ released_note(release_gpu_waits(5000));
+ b_running_ = false;
+ return -1;
+ }
+ }
+ return 0;
}
const cudaError_t q = cudaStreamQuery(cs_);
if (q == cudaErrorNotReady) return 0;
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
index 2fa71c7ce..228b59624 100644
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@ -2175,8 +2175,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
std::future<bool> ple_next; // declared after everything it reads: an early return waits for it
int ple_buf = 0;
+ if (hand_in_ == nullptr) stopped_at_ = -1;
for (int64_t c0 = 0; c0 < n; c0 += m.T) {
if (should_stop && should_stop()) { err = "cancelled"; return false; }
+ // the first stage: end the run before this chunk (every chunk before it is handed on; the caller's drain
+ // waits for the later stages to read them)
+ if (c0 > 0 && hand_in_ == nullptr && stop_at_chunk && stop_at_chunk()) {
+ stopped_at_ = c0;
+ break;
+ }
if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); }
const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0;
core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index ba00f94d7..3a5eb045a 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -9840,6 +9840,7 @@ int main(int argc, char** argv) {
double bt_wait0 = 0, bt_pool0 = 0;
int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0;
int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0, bt_accepted = 0; // bt_accepted: --batch-mtp proposals taken
+ int64_t pipe_rows = 0; // the pipelined groups' rows, never reset (bt_rows restarts when the slots go idle)
// per stage (0 = CUDA0's verifier): the GPU-reach wait and pool time when the timed windows began; and the routed
// (token, expert) entries the CPU and the PCIe share had served by then (bt_hits0 holds the VRAM entries)
std::vector<double> bt_stage_wait0, bt_stage_pool0;
@@ -10231,6 +10232,7 @@ int main(int argc, char** argv) {
std::printf("BT %d %d\n", gi * GS + t, (int) y);
++sl.produced;
++bt_rows;
+ ++pipe_rows;
const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
: sl.p + 2 > o.max_context ? "length" : nullptr;
@@ -11577,6 +11579,173 @@ int main(int argc, char** argv) {
return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 8;
}();
const int64_t C = std::max<int64_t>(sp.chunk(), 1);
+ // BYIELD <ys> with the read stopped at q (nothing in flight): the part read waits in slot ys and the
+ // read ends with e = "yield" (true); false when it cannot give way there (the read goes on). Only
+ // where the rest is read the same way after it (more than a chunk and more than a short read left),
+ // text only, and into a slot that is not decoding.
+ auto give_way = [&](int ys, int64_t q, std::string& err) -> bool {
+ const bool can = ys < (int) bs.size() && !bs[(size_t) ys].active &&
+ (admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 &&
+ b0 - q > std::max<int64_t>(C, o.short_read);
+ std::string ye;
+ const auto ty = Clock::now();
+ std::vector<int32_t> pre(ids.begin(), ids.begin() + q);
+ if (can && copy_to_slot(ys, pre, ye)) {
+ BSlot& sl = bs[(size_t) ys];
+ sl = BSlot{};
+ sl.ids = std::move(pre);
+ sl.cached = true;
+ sl.partial = true;
+ sl.partial_from0 = read_from == 0 || resumed_from0;
+ sl.cvec = cvec_cached;
+ for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this read
+ if ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(),
+ [](int32_t x, int64_t y) { return (int64_t) x == y; }))
+ sl.checks.push_back(c);
+ yielded_at = q;
+ yielded_slot = ys;
+ std::fprintf(stderr, "strata batch: the prompt read gives way at %lld of %lld tokens; slot %d "
+ "holds it (copied in %.1f ms)\n", (long long) q, (long long) n, ys,
+ std::chrono::duration<double, std::milli>(Clock::now() - ty).count());
+ err = "yield";
+ return true;
+ }
+ if (can) bs[(size_t) ys].cached = false; // half written
+ std::fprintf(stderr, "strata batch: BYIELD %d not taken at %lld of %lld%s%s\n", ys, (long long) q,
+ (long long) n, ye.empty() ? "" : ": ", ye.c_str());
+ return false;
+ };
+ // Opt-in, experimental: STRATA_PIPED_CONCURRENT=1 reads the prompt on a thread of its own while
+ // this thread keeps the slot groups decoding through the pipeline (pump), so they never stop for it
+ // and the read has no drain inside it. The prompt and the windows use their own streams and memory
+ // (the prompt's K/V goes to the main sessions, the slots' to theirs; the PLE table is locked), and
+ // the adaptive tier stands still (its round landed before the read). The slots the prompt borrowed
+ // were lent before this read with nothing in flight and are refilled after it, so the windows see
+ // them missing and compute those experts on the CPU, as between pieces. A BYIELD ends the run at
+ // its next chunk (Prefill::stop_at_chunk): the pipeline is drained there and the part read gives
+ // way as below, or the read goes on from there.
+ // Not beside the opt-in paths that allocate or free during a read (the idle stage's help,
+ // STRATA_PREFILL_HELP; the batched draft K/V, STRATA_SPLIT_MTP_BATCH): a free waits for the device.
+ static const bool pr_conc = [] {
+ const char* v = std::getenv("STRATA_PIPED_CONCURRENT");
+ if (v == nullptr || std::atoi(v) == 0) return false;
+ for (const char* k : {"STRATA_PREFILL_HELP", "STRATA_SPLIT_MTP_BATCH"})
+ if (const char* x = std::getenv(k); x != nullptr && std::atoi(x) != 0) {
+ std::fprintf(stderr, "strata batch: STRATA_PIPED_CONCURRENT is off beside %s=1\n", k);
+ return false;
+ }
+ return true;
+ }();
+ if (piped && pr_conc) { // (with no slot decoding it only watches for a BYIELD meanwhile)
+ // the drafter's prompt pass captures its graphs and grows its records at first use: done here,
+ // with nothing in flight (on the reader's thread a capture or a free would wait for the windows,
+ // which wait for this thread to serve their doorbells, #31)
+ if (use_mtp && !mtp.reserve_prefill(C, e)) return false;
+ // the slots' doorbells are served on a thread of their own for the read, which makes no CUDA
+ // call: a call here or on the read's threads can wait for the driver's lock while its holder
+ // waits for the GPU (a free; a module the first kernel of a shape loads), and a window on that
+ // GPU waits for its doorbell (#31). Ends (and hands the service back to pump) on every exit.
+ struct Doorbells {
+ std::atomic<bool> on{true};
+ std::thread th;
+ std::function<void()> off;
+ ~Doorbells() {
+ on.store(false, std::memory_order_release);
+ if (th.joinable()) th.join();
+ if (off) off();
+ }
+ } bells;
+ for (int k = 0; k < n_pipe; ++k) stage_verifier(k).set_external_serve(true);
+ bells.off = [&] { for (int k = 0; k < n_pipe; ++k) stage_verifier(k).set_external_serve(false); };
+ bells.th = std::thread([&] {
+ strata::aux_cpus::pin_current_thread();
+ while (bells.on.load(std::memory_order_acquire)) {
+ bool busy = false;
+ for (int k = 0; k < n_pipe; ++k) {
+ auto& vk = stage_verifier(k);
+ if (vk.batch_busy()) {
+ busy = true;
+ vk.batch_serve(win_pool_fn, win_pool_user);
+ }
+ }
+ if (!busy) std::this_thread::sleep_for(std::chrono::microseconds(50));
+ }
+ });
+ for (int64_t q0 = a0; q0 < b0;) {
+ const auto tc = Clock::now();
+ const int64_t rows0 = pipe_rows;
+ std::atomic<bool> done{false};
+ std::atomic<int> want_yield{-1};
+ bool read_ok = true;
+ std::string read_err;
+ in_prompt_read = true;
+ sp.stop_at_chunk = [&] { return want_yield.load(std::memory_order_acquire) >= 0; };
+ std::thread reader([&] {
+ strata::aux_cpus::pin_current_thread();
+ try { // (an exception leaving a std::thread ends the process: a failed read instead)
+ read_ok = sp.run(ids.data() + q0, b0 - q0, q0, read_err);
+ } catch (const std::exception& x) {
+ read_ok = false;
+ read_err = std::string("the prompt read failed: ") + x.what();
+ } catch (...) {
+ read_ok = false;
+ read_err = "the prompt read failed";
+ }
+ done.store(true, std::memory_order_release);
+ });
+ struct ReadEnd { // on every way out of this round (an exception too): the reader joined first
+ std::thread& t;
+ std::function<bool()>& hook;
+ bool& reading;
+ ~ReadEnd() {
+ if (t.joinable()) t.join();
+ hook = nullptr;
+ reading = false;
+ }
+ } read_end{reader, sp.stop_at_chunk, in_prompt_read};
+ bool pump_ok = true;
+ while (!done.load(std::memory_order_acquire)) {
+ if (pump_ok && (batch_on() || pipe_inflight())) pump_ok = pump(true);
+ else std::this_thread::sleep_for(std::chrono::microseconds(200));
+ // a BSTOP that came meanwhile ends its slot at its next window; a BYIELD ends the read at
+ // its next chunk
+ std::lock_guard<std::mutex> lk(in_mu);
+ for (auto it = in_lines.begin(); it != in_lines.end();) {
+ if (it->rfind("BSTOP ", 0) == 0) {
+ const int b = std::atoi(it->c_str() + 6);
+ if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true;
+ it = in_lines.erase(it);
+ } else if (it->rfind("BYIELD ", 0) == 0 && want_yield.load() < 0) {
+ want_yield.store(std::atoi(it->c_str() + 7), std::memory_order_release);
+ it = in_lines.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ }
+ reader.join(); // (a failed window leaves the read to finish: it is not stopped mid-run)
+ sp.stop_at_chunk = nullptr;
+ in_prompt_read = false;
+ if (!pump_ok || !pipe_drain()) {
+ batch_fatal = true;
+ e = "a pipelined batch window failed";
+ return false;
+ }
+ const int64_t q = read_ok && sp.stopped_at() >= 0 ? q0 + sp.stopped_at() : b0;
+ std::fprintf(stderr, "strata batch: read %lld tokens on a thread of its own in %.0f ms "
+ "(concurrent, to %lld of %lld); the slots decoded %lld rows meanwhile\n",
+ (long long) (q - q0),
+ std::chrono::duration<double, std::milli>(Clock::now() - tc).count(),
+ (long long) q, (long long) n, (long long) (pipe_rows - rows0));
+ if (!read_ok) {
+ e = read_err;
+ return false;
+ }
+ if (q < b0 && give_way(want_yield.load(), q, e)) return false;
+ q0 = q; // done, or the give-way was not taken there: the rest goes on the same way
+ }
+ return true;
+ }
const int64_t piece = strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, yield_chunks);
if (piece <= 0) return sp.run(ids.data() + a0, b0 - a0, a0, e);
for (int64_t q = a0; q < b0;) {
@@ -11601,39 +11770,7 @@ int main(int argc, char** argv) {
}
}
}
- if (ys >= 0) {
- // only where the rest is read the same way after it (more than a chunk and more than a short
- // read left), text only, and into a slot that is not decoding
- const bool can = ys < (int) bs.size() && !bs[(size_t) ys].active &&
- (admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 &&
- b0 - q > std::max<int64_t>(C, o.short_read);
- std::string ye;
- const auto ty = Clock::now();
- std::vector<int32_t> pre(ids.begin(), ids.begin() + q);
- if (can && copy_to_slot(ys, pre, ye)) {
- BSlot& sl = bs[(size_t) ys];
- sl = BSlot{};
- sl.ids = std::move(pre);
- sl.cached = true;
- sl.partial = true;
- sl.partial_from0 = read_from == 0 || resumed_from0;
- sl.cvec = cvec_cached;
- for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this read
- if ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(),
- [](int32_t x, int64_t y) { return (int64_t) x == y; }))
- sl.checks.push_back(c);
- yielded_at = q;
- yielded_slot = ys;
- std::fprintf(stderr, "strata batch: the prompt read gives way at %lld of %lld tokens; slot %d "
- "holds it (copied in %.1f ms)\n", (long long) q, (long long) n, ys,
- std::chrono::duration<double, std::milli>(Clock::now() - ty).count());
- e = "yield";
- return false;
- }
- if (can) bs[(size_t) ys].cached = false; // half written
- std::fprintf(stderr, "strata batch: BYIELD %d not taken at %lld of %lld%s%s\n", ys, (long long) q,
- (long long) n, ye.empty() ? "" : ": ", ye.c_str());
- }
+ if (ys >= 0 && give_way(ys, q, e)) return false;
if (decode_share <= 0.0 || !batch_on()) continue;
const double budget = decode_share * std::chrono::duration<double, std::milli>(Clock::now() - tq).count();
const auto td = Clock::now();