From 34b726e09051ee17b419e8f761db7ceeba3a3d8c Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:23:32 -0700 Subject: [PATCH] batch-groups: the concurrent read allocates nothing on its threads, keeps its checks and the watchdog, and waits on a launch From a review of the concurrent read: - With external serving batch_poll still finds a window that will not finish (its graph ended or failed with a layer to ring, or no layer rang for 20 s): the served count is read before the stream query and the ring count after it, at most one query a millisecond; the last ring's time is an atomic. batch_serve reads a window's row count after its served count, so a window launched while the doorbell thread was descheduled is not served with the last one's rows. - #1996's pinned upload rings (0.1.43.1) grew a slot at its first larger upload, a pinned free and allocation on the read's thread: the drafter's records and the prompt path's routing tables reserve their slots before the read (PinnedRing::reserve, Prefill::reserve_uploads). - Off, said once, where serving a doorbell makes a CUDA call (--pcie-mode dma, STRATA_FS_SLOTS, the helper caches) or the expert source recycles the buffers it hands out (the GGUF in place, unbuffered, STRATA_IO_PREFETCH); a prompt with pictures is read the usual way. The expert sources' read counters are atomics. The check is a pure function, concurrent_read_off (batch_read.hpp), with a test in batch_read_test. - pump's all-idle branch turned the stall watchdog off when the last slot finished mid-read; it stays on while a prompt is read until the request ends. - Between windows the doorbell thread slept 50 us, a whole timer tick on Windows (up to 15.6 ms): it now waits on a condition each launch notifies (STRATA_TEST_BELL_SLEEP_US=N, a test, restores the sleep for an A/B). With nothing decoding the main thread waits for the read's end or a line instead of sleeping. A pool failure the doorbell thread set is reported before pump clears the flag for the next window. - The read's log line ends with the slots' rate and, per stage, its windows and the host time that set each up. The priority stream's cudaGetLastError runs only under the opt-in. --- include/strata/core/expert_source.hpp | 13 ++- include/strata/core/pinned_ring.hpp | 35 ++++++ include/strata/core/verify.hpp | 11 +- include/strata/prefill/prefill.hpp | 5 + include/strata/program/batch_read.hpp | 25 +++++ src/core/expert_source.cpp | 4 +- src/core/mtp.cpp | 8 +- src/core/verify.cpp | 63 ++++++++--- src/prefill/prefill.cpp | 16 +++ src/program/generate.cpp | 147 ++++++++++++++++++++++---- tests/program/batch_read_test.cpp | 29 ++++- 11 files changed, 307 insertions(+), 49 deletions(-) diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index cf517690..327067f6 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -721,7 +721,7 @@ public: /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only /// interesting once Phase 3 makes it not so. - int64_t reads() const override { return reads_; } + int64_t reads() const override { return reads_.load(std::memory_order_relaxed); } // ---- the Linux I/O path of the mapped file tier (STRATA_IO_PREFETCH=1, opt in; no effect on Windows) // @@ -735,6 +735,9 @@ public: // The bytes are the same bytes, so the output is the same. `threads` = I/O threads (0: default 4). void set_io_prefetch(bool on, int threads); bool io_prefetch() const { return io_pf_; } + /// blob() hands out stage buffers it recycles (the GGUF in place, an unbuffered source, the I/O read-ahead): one + /// thread at a time (STRATA_PIPED_CONCURRENT is off with such a source) + bool stages_blobs() const { return staged(); } /// Counts the cached / uncached bytes of every blob read from the files (mincore, page-granular). Free with /// io_prefetch; otherwise opt in with STRATA_IO_STATS=1 (the check costs a few microseconds per blob). void set_io_stats(bool on) { io_stats_ = on || io_pf_; } @@ -891,7 +894,7 @@ private: uint64_t xstage_blob_ = 0; int64_t exchanges_ = 0; std::atomic file_reads_{0}; - int64_t reads_ = 0; + std::atomic reads_{0}; ///< (a counter only; two threads can read blobs at once) #if defined(_WIN32) void* file_ = nullptr; void* mapping_ = nullptr; @@ -939,9 +942,9 @@ public: int64_t blobs() const { return blobs_; } const uint8_t* blob(int64_t layer, int64_t expert) override; /// `blob` without the read counter: a pure pointer into the arena, safe from another thread (the async adaptive - /// tier's job thread, which must not touch the non-atomic `reads_`) + /// tier's job thread) const uint8_t* blob_at(int64_t layer, int64_t expert) const; - int64_t reads() const { return reads_; } + int64_t reads() const { return reads_.load(std::memory_order_relaxed); } bool pinned(int64_t layer, int64_t expert) const override; const uint8_t* device_alias(int64_t layer, int64_t expert) const override; /// Prefix pinning: the old rule (device_alias(layer, 0)); pin by need: at least one pinned range in the layer. @@ -985,7 +988,7 @@ private: const uint8_t* base_ = nullptr; int64_t blobs_ = 0; int64_t n_expert_ = 0; - int64_t reads_ = 0; + std::atomic reads_{0}; ///< (a counter only; two threads can read blobs at once) std::string note_; std::string ram_warning_; double gib_per_s_ = 0.0; diff --git a/include/strata/core/pinned_ring.hpp b/include/strata/core/pinned_ring.hpp index 7b74a24f..6e3757a7 100644 --- a/include/strata/core/pinned_ring.hpp +++ b/include/strata/core/pinned_ring.hpp @@ -113,6 +113,41 @@ public: return e; } + // Every slot holds at least `bytes` from here on: grown now, by a caller that must not allocate later (a pinned + // allocation or free takes the driver's lock and can wait for the device: STRATA_PIPED_CONCURRENT grows the rings + // before a read whose windows run beside it). On the device that is current, as acquire(). False: a slot could + // not be had (its uploads then grow it, or go up from the caller's memory, as before). + bool reserve(size_t bytes) { + if (bytes == 0 || pageable_forced()) return true; + int cur = -1; + if (cudaGetDevice(&cur) != cudaSuccess) { cudaGetLastError(); return false; } + if (dev_ < 0) dev_ = cur; + if (cur != dev_) return false; + for (Slot& sl : slots_) { + if (sl.cap >= bytes && sl.ev != nullptr) continue; + if (sl.pending) { + sl.pending = false; + if (cudaEventSynchronize(sl.ev) != cudaSuccess) { cudaGetLastError(); return false; } + } + if (sl.cap < bytes) { + if (sl.p) { cudaFreeHost(sl.p); sl.p = nullptr; sl.cap = 0; } + const size_t cap = bytes < kMinCap ? kMinCap : bytes; + if (cudaHostAlloc(&sl.p, cap, cudaHostAllocPortable) != cudaSuccess) { + cudaGetLastError(); + sl.p = nullptr; + return false; + } + sl.cap = cap; + } + if (sl.ev == nullptr && cudaEventCreateWithFlags(&sl.ev, cudaEventDisableTiming) != cudaSuccess) { + cudaGetLastError(); + sl.ev = nullptr; + return false; + } + } + return true; + } + void release() { for (Slot& sl : slots_) { if (sl.pending && sl.ev) cudaEventSynchronize(sl.ev); diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index f04475dd..2539a33a 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -354,7 +354,16 @@ private: std::atomic b_k_{0}; int64_t b_steps_ = 0; std::atomic ext_serve_{false}; - std::chrono::steady_clock::time_point b_last_; + // when a layer was last served (steady clock ticks): the serving thread writes it, batch_poll's checks read it + std::atomic b_last_{0}; + void ring_now() { + b_last_.store((int64_t) std::chrono::steady_clock::now().time_since_epoch().count(), std::memory_order_release); + } + std::chrono::steady_clock::time_point last_ring() const { + return std::chrono::steady_clock::time_point( + std::chrono::steady_clock::duration(b_last_.load(std::memory_order_acquire))); + } + std::chrono::steady_clock::time_point ext_checked_{}; ///< batch_poll's last check with external serving int32_t b_out_[8] = {}; std::vector slot_sp_; bool sample_rows(int S, std::string& err); ///< the sampled slots' rows of the last batch window diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index b5ddeff7..11d1560d 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -154,6 +154,11 @@ public: /// (STRATA_PIPED_CONCURRENT) gives way to a waiting shorter request there. std::function stop_at_chunk; int64_t stopped_at() const { return stopped_at_; } + /// Grows this stage's (and the later stages') pinned upload slots to what a text chunk of `T` tokens uploads, so + /// a run of such chunks allocates no pinned memory (STRATA_PIPED_CONCURRENT: an allocation or free on the read's + /// thread takes the driver's lock). Before the run, with nothing of this path in flight. False: a slot could + /// not be had (it then grows at first use, as before). + bool reserve_uploads(int64_t T); /// 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. diff --git a/include/strata/program/batch_read.hpp b/include/strata/program/batch_read.hpp index c9036138..d91afc1b 100644 --- a/include/strata/program/batch_read.hpp +++ b/include/strata/program/batch_read.hpp @@ -27,4 +27,29 @@ inline int64_t batch_read_piece(bool batch, bool piped, bool layer_split, bool b return chunks_per_piece > 0 ? chunk * chunks_per_piece : 0; } +/// What a configuration has that keeps the concurrent read (STRATA_PIPED_CONCURRENT=1) off. +struct ConcurrentReadSetup { + bool prefill_help = false; ///< STRATA_PREFILL_HELP: the idle stage's help allocates on the read's thread + bool split_mtp_batch = false; ///< STRATA_SPLIT_MTP_BATCH: the batched draft K/V frees there (a free waits) + bool fs_slots = false; ///< STRATA_FS_SLOTS (Foresight swap space): serving a doorbell makes a CUDA call + bool pcie_dma = false; ///< --pcie-mode dma: the same (its copies) + bool helper_caches = false; ///< --expert-cache-device1..3, a remote expert source, a prompt source of its own + bool staged_source = false; ///< the GGUF source stages its blobs (in place, unbuffered, STRATA_IO_PREFETCH): + ///< it recycles the buffers it hands out, one thread at a time + bool other_source = false; ///< an expert source that is neither the GGUF source nor the arena +}; + +/// Why the concurrent read stays off with `s` (the first reason, for the log line), or nullptr when it can run. +inline const char* concurrent_read_off(const ConcurrentReadSetup& s) { + if (s.prefill_help) return "STRATA_PREFILL_HELP"; + if (s.split_mtp_batch) return "STRATA_SPLIT_MTP_BATCH"; + if (s.fs_slots) return "STRATA_FS_SLOTS"; + if (s.pcie_dma) return "--pcie-mode dma"; + if (s.helper_caches) return "the helper caches (--expert-cache-device1..3)"; + if (s.staged_source) + return "an expert source that stages its blobs (the GGUF in place, unbuffered, STRATA_IO_PREFETCH)"; + if (s.other_source) return "this expert source"; + return nullptr; +} + } // namespace strata::program diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 4878c111..6547a2f1 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -3495,7 +3495,7 @@ const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) { } if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed); } - if (result != nullptr) ++reads_; + if (result != nullptr) reads_.fetch_add(1, std::memory_order_relaxed); return result; } @@ -4895,7 +4895,7 @@ const uint8_t* ArenaExpertSource::blob(int64_t layer, int64_t expert) { if (layer < 0 || expert < 0 || expert >= n_expert_) return nullptr; const int64_t idx = layer * n_expert_ + expert; if (idx < 0 || idx >= blobs_) return nullptr; - ++reads_; + reads_.fetch_add(1, std::memory_order_relaxed); // Pointer arithmetic into resident memory. No fault, no copy, no mapping - which is the entire point of // this class over `FileExpertSource`. return base_ + arena_off(layer, expert); diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index f75288ca..3894b8ad 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -1390,7 +1390,13 @@ bool MtpDrafter::reserve_prefill(int64_t n, std::string& err) { } 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 (n <= 0) return true; + // the records' pinned upload slots too (#1996's ring grows a slot at its first larger upload: a pinned free and + // allocation, which take the driver's lock) + if (!pf_ring_.reserve((size_t) (n * per_row) * sizeof(int32_t))) + std::fprintf(stderr, "strata mtp: the prompt records' pinned upload slots could not be reserved (they grow at " + "first use)\n"); + if (pf_cap_ >= n * per_row) return true; if (pf_dev_) cudaFree(pf_dev_); pf_dev_ = nullptr; pf_cap_ = 0; diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 002b2d39..9fe22ecf 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -759,10 +759,12 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& 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(); + if (hi) { + if (cudaDeviceGetStreamPriorityRange(&lo, &top) == cudaSuccess && + cudaStreamCreateWithPriority(s, cudaStreamNonBlocking, top) == cudaSuccess) + return cudaSuccess; + cudaGetLastError(); // (only the failed priority call's error: the default path clears nothing) + } #endif return cudaStreamCreateWithFlags(s, cudaStreamNonBlocking); }; @@ -3285,7 +3287,7 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_ } b_k_ = 0; b_steps_ = le_ - lb_; - b_last_ = Clock::now(); + ring_now(); b_running_.store(true, std::memory_order_release); // last: an external server reads the rest after it return true; } @@ -3293,7 +3295,6 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_ 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, // 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. @@ -3302,14 +3303,20 @@ int Verifier::batch_serve(PoolMultiFn pool, void* user) { _mm_sfence(); *h_flag_ = 1; } - while (!ar_on() && b_k_ < b_steps_) { - const uint32_t want = (uint32_t) (b_k_ + 1); + for (;;) { + // the window's row count is read after the served-layer count: with external serving the window this call + // began on can have finished and the next one been launched meanwhile, and batch_launch writes its rows + // (stage_batch) before it resets b_k_, so a count that is the new window's comes with the new rows + const int64_t k = b_k_.load(std::memory_order_acquire); + if (ar_on() || k >= b_steps_) break; + const uint32_t want = (uint32_t) (k + 1); if (*seq < want) return 0; + const int S = last_t_; const Clock::time_point b = Clock::now(); cur_layer_ = want - 1; set_plan_slot(0); if (remote_opt_) remote_opt_->begin(h_w_, 0, S); - if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + b_k_); + if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + k); if (remote_opt_) remote_opt_->end(); progress_tick(); std::atomic_thread_fence(std::memory_order_seq_cst); @@ -3326,7 +3333,7 @@ int Verifier::batch_serve(PoolMultiFn pool, void* user) { } *(volatile uint32_t*) h_flag_ = want; ms_pool += ms_since(b); - b_last_ = Clock::now(); + ring_now(); b_k_.fetch_add(1, std::memory_order_release); } return 1; @@ -3334,17 +3341,41 @@ int Verifier::batch_serve(PoolMultiFn pool, void* user) { 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; + // set_external_serve: another thread serves the doorbells (batch_serve) and this one only checks for a window that + // will not finish, as below: its graph ended (or failed) with a layer still to ring, or no layer rang for 20 s. + // The stream query can wait for the driver's lock while a read's call holds it; the doorbells go on meanwhile. + // The served count is read before the query and the ring count after it: a layer served in between rang first. + if (ext_serve_.load(std::memory_order_acquire) && !ar_on()) { + const int64_t k = b_k_.load(std::memory_order_acquire); + if (k < b_steps_) { + const auto now = Clock::now(); + if (now - last_ring() <= std::chrono::milliseconds(2) || now - ext_checked_ < std::chrono::milliseconds(1)) + return 0; + ext_checked_ = now; // (at most one query a millisecond: pump calls this in a loop) + const OnDevice on_device(device_); + const cudaError_t q = cudaStreamQuery(cs_); + if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < (uint32_t) (k + 1)) { + err = "verify batch: layer " + std::to_string(lb_ + k) + " never rang (" + + (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; + b_running_ = false; + return -1; + } + if (now - last_ring() > std::chrono::seconds(20)) { + err = "verify batch: timed out at layer " + std::to_string(lb_ + k) + + released_note(release_gpu_waits(5000)); + b_running_ = false; + return -1; + } + 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)) { + if (now - last_ring() > 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 (" + @@ -3352,7 +3383,7 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) { b_running_ = false; return -1; } - if (now - b_last_ > std::chrono::seconds(20)) { + if (now - last_ring() > 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; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 228b5962..bab1ff33 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -4342,6 +4342,22 @@ bool Prefill::drain_pipeline(std::string& err) { return ok; } +bool Prefill::reserve_uploads(int64_t T) { + bool ok = true; + if (impl_ != nullptr && T > 0) { + Impl& m = *impl_; + const core::OnDevice on_device(m.device); // (the ring is the device's that is current at its first use) + // a text chunk's largest pageable uploads through the ring: the routing tables (and their ids down, T x K + // each); the PLE rows when they could not be pinned (T x N). A picture's rows are not covered. + size_t bytes = (size_t) (T * K) * sizeof(int32_t); + if (!m.ple_pageable[0].empty() || !m.ple_pageable[1].empty()) + bytes = std::max(bytes, (size_t) (T * N) * sizeof(float)); + ok = m.up_ring.reserve(bytes); + } + if (next_ != nullptr) ok = next_->reserve_uploads(T) && ok; + return ok; +} + bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { #if defined(STRATA_GPU_METAL) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 3a5eb045..80148f49 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -10193,6 +10193,13 @@ int main(int argc, char** argv) { for (int t = 0; t < GS; ++t) if (bs[(size_t) (gi * GS + t)].active) return true; return false; }; + // STRATA_PIPED_CONCURRENT (read_part): while a prompt is read on a thread of its own, the slots' doorbells are + // served on another (conc_serving); between windows that thread waits on bell_cv and a launch wakes it (a + // timed sleep is a whole timer tick on Windows, up to 15.6 ms, and the window's first layer would wait for it) + bool conc_serving = false; + std::mutex bell_mu; + std::condition_variable bell_cv; + std::atomic bell_waiting{false}; // one turn: serve every running stage, hand finished groups on, start what can start auto pump = [&](bool may_start) -> bool { ++pipe_tick; @@ -10283,6 +10290,12 @@ int main(int argc, char** argv) { } G.inflight = true; G.stage = 0; + // (with the doorbells on their own thread, a failure it set for a window that left this stage is + // not cleared unseen) + if (conc_serving && drive.d.failed) { + std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); + return false; + } drive.d.failed = false; apply_pending(false); } @@ -10293,6 +10306,13 @@ int main(int argc, char** argv) { return false; } stage_group[(size_t) k] = pick; + if (conc_serving) { // the doorbell thread may be waiting between windows: the launch above is seen + std::atomic_thread_fence(std::memory_order_seq_cst); + if (bell_waiting.load(std::memory_order_relaxed)) { + std::lock_guard lk(bell_mu); + bell_cv.notify_one(); + } + } } if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; } if (!pipe_inflight() && !batch_on() && bt_windows > 0) { // all idle: the timing line, as batch_step @@ -10305,7 +10325,9 @@ int main(int argc, char** argv) { if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str()); } bt_windows = bt_rows = 0; - strata::core::progress().busy.store(false); + // (not while a prompt is read in a request: its windows ran beside it, and the watchdog stays on for + // the rest of the read, STRATA_PIPED_CONCURRENT; the request's end turns it off) + if (!in_prompt_read) strata::core::progress().busy.store(false); } return true; }; @@ -11624,23 +11646,43 @@ int main(int argc, char** argv) { // 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 = [] { + // Not where a read's thread allocates or frees (the idle stage's help, STRATA_PREFILL_HELP; the batched + // draft K/V, STRATA_SPLIT_MTP_BATCH: a free waits for the device), where serving a doorbell makes a + // CUDA call (--pcie-mode dma, the Foresight swap space STRATA_FS_SLOTS, the helper caches), and where + // the expert source recycles the buffers it hands out (the GGUF in place, an unbuffered source, the + // I/O read-ahead: one thread at a time). Pictures are read the usual way (their rows go up through + // pinned slots of a size known only then). + 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; - } + auto env_on = [](const char* k) { + const char* x = std::getenv(k); + return x != nullptr && std::atoi(x) != 0; + }; + strata::program::ConcurrentReadSetup s; + s.prefill_help = env_on("STRATA_PREFILL_HELP"); + s.split_mtp_batch = env_on("STRATA_SPLIT_MTP_BATCH"); + s.fs_slots = env_on("STRATA_FS_SLOTS"); + s.pcie_dma = o.pcie_mode == "dma"; + s.helper_caches = o.remote_expert_opt || prefill_src != srcp; + for (int r = 0; r < 3; ++r) s.helper_caches |= o.expert_cache_remote[(size_t) r] > 0; + s.staged_source = srcp == &src && src.stages_blobs(); + s.other_source = srcp != &src && srcp != &arena_src; + if (const char* why = strata::program::concurrent_read_off(s)) { + std::fprintf(stderr, "strata batch: STRATA_PIPED_CONCURRENT is off beside %s\n", why); + 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 (piped && pr_conc && req_imgs.empty()) { // (with no slot decoding it only watches for a BYIELD) + // the drafter's prompt pass captures its graphs and grows its records at first use, and the + // prompt path's pinned upload slots grow at their first larger upload: done here, with nothing in + // flight (on the reader's thread a capture, an allocation or a free takes the driver's lock and + // can wait for the device, #31) if (use_mtp && !mtp.reserve_prefill(C, e)) return false; + if (!sp.reserve_uploads(C)) + std::fprintf(stderr, "strata batch: the prompt path's pinned upload slots could not be " + "reserved (they grow at first use)\n"); // 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 @@ -11648,17 +11690,31 @@ int main(int argc, char** argv) { struct Doorbells { std::atomic on{true}; std::thread th; - std::function off; + std::function wake, off; ~Doorbells() { on.store(false, std::memory_order_release); + if (wake) wake(); 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); }; + conc_serving = true; + bells.off = [&] { + for (int k = 0; k < n_pipe; ++k) stage_verifier(k).set_external_serve(false); + conc_serving = false; + }; + bells.wake = [&] { + std::lock_guard lk(bell_mu); + bell_cv.notify_one(); + }; bells.th = std::thread([&] { strata::aux_cpus::pin_current_thread(); + auto any_busy = [&] { + for (int k = 0; k < n_pipe; ++k) + if (stage_verifier(k).batch_busy()) return true; + return false; + }; while (bells.on.load(std::memory_order_acquire)) { bool busy = false; for (int k = 0; k < n_pipe; ++k) { @@ -11668,12 +11724,36 @@ int main(int argc, char** argv) { vk.batch_serve(win_pool_fn, win_pool_user); } } - if (!busy) std::this_thread::sleep_for(std::chrono::microseconds(50)); + if (busy) continue; + // STRATA_TEST_BELL_SLEEP_US=N (a test, an A/B of the wait below): sleep N us instead, as + // the first form of this thread did (a whole timer tick on Windows) + static const int test_sleep_us = [] { + const char* t = std::getenv("STRATA_TEST_BELL_SLEEP_US"); + return t != nullptr ? std::max(0, std::atoi(t)) : 0; + }(); + if (test_sleep_us > 0) { + std::this_thread::sleep_for(std::chrono::microseconds(test_sleep_us)); + continue; + } + // no window in flight: wait for pump's next launch (it notifies when this is set; the + // fences pair the flag with batch_launch's running flag, so one of the two sides sees the + // other), or for the end of the read + std::unique_lock lk(bell_mu); + bell_waiting.store(true, std::memory_order_relaxed); + std::atomic_thread_fence(std::memory_order_seq_cst); + bell_cv.wait_for(lk, std::chrono::milliseconds(2), + [&] { return !bells.on.load(std::memory_order_acquire) || any_busy(); }); + bell_waiting.store(false, std::memory_order_relaxed); } }); for (int64_t q0 = a0; q0 < b0;) { const auto tc = Clock::now(); const int64_t rows0 = pipe_rows; + // per stage, for the read's log line: its windows and the host time that set them up (the + // PLE gather included, which waits while the prompt holds the table) - both this thread's + std::vector> st0((size_t) n_pipe); + for (int k = 0; k < n_pipe; ++k) + st0[(size_t) k] = {stage_verifier(k).windows, stage_verifier(k).ms_host}; std::atomic done{false}; std::atomic want_yield{-1}; bool read_ok = true; @@ -11692,6 +11772,8 @@ int main(int argc, char** argv) { read_err = "the prompt read failed"; } done.store(true, std::memory_order_release); + { std::lock_guard lk(in_mu); } // (the loop below may be waiting on in_cv) + in_cv.notify_all(); }); struct ReadEnd { // on every way out of this round (an exception too): the reader joined first std::thread& t; @@ -11704,12 +11786,17 @@ int main(int argc, char** argv) { } } read_end{reader, sp.stop_at_chunk, in_prompt_read}; bool pump_ok = true; + size_t seen = 0; // in_lines' length after the last look: a line that comes wakes the wait 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)); + const bool decoding = pump_ok && (batch_on() || pipe_inflight()); + if (decoding) pump_ok = pump(true); + std::unique_lock lk(in_mu); + if (!decoding) // nothing to pump: until the read ends or a line comes (both notify) + in_cv.wait_for(lk, std::chrono::milliseconds(2), [&] { + return done.load(std::memory_order_acquire) || in_lines.size() != seen; + }); // a BSTOP that came meanwhile ends its slot at its next window; a BYIELD ends the read at // its next chunk - std::lock_guard 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); @@ -11722,6 +11809,7 @@ int main(int argc, char** argv) { ++it; } } + seen = in_lines.size(); } reader.join(); // (a failed window leaves the read to finish: it is not stopped mid-run) sp.stop_at_chunk = nullptr; @@ -11732,11 +11820,24 @@ int main(int argc, char** argv) { return false; } const int64_t q = read_ok && sp.stopped_at() >= 0 ? q0 + sp.stopped_at() : b0; + const double read_ms = std::chrono::duration(Clock::now() - tc).count(); + std::string per; + for (int k = 0; k < n_pipe; ++k) { + const auto& v = stage_verifier(k); + const int64_t w = v.windows - st0[(size_t) k].first; + char b[96]; + const double host = w > 0 ? (v.ms_host - st0[(size_t) k].second) / (double) w : 0.0; + std::snprintf(b, sizeof b, "%sstage %d: %lld windows, %.1f ms host each", k ? "; " : "", + k + 1, (long long) w, host); + per += b; + } 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(Clock::now() - tc).count(), - (long long) q, (long long) n, (long long) (pipe_rows - rows0)); + "(concurrent, to %lld of %lld); the slots decoded %lld rows meanwhile " + "(%.1f rows/s; %s)\n", + (long long) (q - q0), read_ms, (long long) q, (long long) n, + (long long) (pipe_rows - rows0), + read_ms > 0.0 ? 1000.0 * (double) (pipe_rows - rows0) / read_ms : 0.0, + per.c_str()); if (!read_ok) { e = read_err; return false; diff --git a/tests/program/batch_read_test.cpp b/tests/program/batch_read_test.cpp index d9842381..d22cf2e8 100644 --- a/tests/program/batch_read_test.cpp +++ b/tests/program/batch_read_test.cpp @@ -1,9 +1,13 @@ -// batch_read_piece: the pieces of a --batch prompt read (synthetic: no model, no GPU). +// batch_read.hpp: the pieces of a --batch prompt read, where the concurrent read runs (synthetic: no model, no GPU). #include "strata/program/batch_read.hpp" #include +#include +#include using strata::program::batch_read_piece; +using strata::program::concurrent_read_off; +using strata::program::ConcurrentReadSetup; static int fails = 0; #define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++fails; } } while (0) @@ -27,6 +31,29 @@ int main() { // a piece is always a multiple of the chunk for (int64_t c : {256, 1000, 2048, 4096}) for (int64_t k : {1, 3, 8, 16}) CHECK(batch_read_piece(true, false, true, false, c, k) % c == 0); + // concurrent_read_off (STRATA_PIPED_CONCURRENT): runs with nothing set; each setting alone keeps it off, named + CHECK(concurrent_read_off({}) == nullptr); + bool ConcurrentReadSetup::*const each[] = { + &ConcurrentReadSetup::prefill_help, &ConcurrentReadSetup::split_mtp_batch, &ConcurrentReadSetup::fs_slots, + &ConcurrentReadSetup::pcie_dma, &ConcurrentReadSetup::helper_caches, &ConcurrentReadSetup::staged_source, + &ConcurrentReadSetup::other_source}; + const char* named[std::size(each)] = {}; + auto same = [](const char* a, const char* b) { return a != nullptr && b != nullptr && std::strcmp(a, b) == 0; }; + for (size_t i = 0; i < std::size(each); ++i) { + ConcurrentReadSetup s; + s.*each[i] = true; + named[i] = concurrent_read_off(s); + CHECK(named[i] != nullptr); + for (size_t j = 0; j < i; ++j) CHECK(!same(named[i], named[j])); // a reason of its own + } + CHECK(same(named[0], "STRATA_PREFILL_HELP")); + CHECK(same(named[3], "--pcie-mode dma")); + // with several, the first in the struct's order is named + for (size_t i = 0; i < std::size(each); ++i) { + ConcurrentReadSetup s; + for (size_t j = i; j < std::size(each); ++j) s.*each[j] = true; + CHECK(same(concurrent_read_off(s), named[i])); + } if (fails == 0) std::printf("batch_read_test: ok\n"); return fails == 0 ? 0 : 1; }