Layer split: pipelined verify windows (--pipeline-windows, opt-in)

With a split the two cards take turns on every verify window: stage 0 runs its
layers and hands off, then waits while stage 1 runs the rest, the head and the
draft. The batch pipeline (--batch-groups) overlaps different conversations;
one conversation's decode stayed serial.

--pipeline-windows 2 runs window K+1 on stage 0 while stage 1 verifies window
K. The guess for K+1 comes from the MTP chain, launched as soon as K's verdict
is known and teacher-forced through K+1's drafts: if K is accepted as guessed,
K+1 is already half done; if not, stage 0 restores its GDN state from a
snapshot, replays K's commit with the real count, and K+1 is rebuilt from the
real tokens. --pipeline-windows 1 overlaps only the prompt's short reads
through the windows (--short-read). Default 0: nothing changes.

What it adds:
- Verifier: a non-blocking form of run()/commit() (capture_all, pl_launch,
  prestage, service, done, pl_finish, pl_commit_async), the batch pipeline's
  batch_launch/batch_poll pattern for one sequence. The window, its staging,
  the PLE gather at layer 0, the zero-doorbell graph's flag, the #267 release
  on a timeout and the commit graph are run()'s. Two verifiers per stage (one
  per window parity) share one stream of their card (set_stream) and each
  pair has its own hand-off.
- set_always_publish: the pipelined verifiers copy the token rows to the host
  at every layer, because the adaptive tier now marks experts evicted on the
  host while windows are in flight, before the device residency table follows.
- MtpDrafter: chain_launch (the round and its steps back to back, an event
  after each output, the first steps fed the in-flight window's drafts by a
  one-thread forcing kernel), prefill without a host sync, 8 rows with 2, the
  drafter's stream at the highest priority (CUDA only).
- the adaptive tier beside the pipeline: evictions are marked first, then the
  refill copies wait (on the tier's thread) for every window in flight; the
  RAM side of a swap (exchange, release, unpin) waits for the windows that may
  still pull the incoming experts over PCIe.
- an agreement gate: a speculative window is launched only when the chain's
  estimate says it is likely kept (STRATA_PIPELINE_THETA, default 0.2); a
  window known to be wrong gets empty plans for its remaining layers; a lookup
  window's continuation becomes the speculative window behind it.
- VRAM: 160 MiB more kept out of each card's cache for the second verifier,
  and the two GDN snapshots on the first card.
- off, with one log line saying why, for anything it does not support: --batch
  slots, --peer-device, the helper caches, three or more stages, a split on
  one GPU, no drafter. Requests with repetition penalties or coupled draft
  sampling decode serially. Nothing is in flight outside the two pipelined
  loops, so checkpoints, parking and the serial paths are unchanged.

Measured: Swift 1.5 IQ3_XXS at 160K (q4_0 KV, the stock draft layer), RTX 4060
Ti (layers 0-19) + RTX 5080 (20-47), i9-14900KF, 32 GB of RAM, the resident
RAM mode on the split (#848); greedy, 500 tokens, two interleaved pairs of
three rounds, decode tok/s, serial -> pipelined: Python code 90.4 -> 103.1,
C code 76.6 -> 81.6, English prose 63.0 -> 71.1, Italian prose 41.6 -> 46.3,
a copy-heavy edit (a 5 KB file back with a rename) 90.5 -> 117.9; mean
72.4 -> 84.0 (+16%). With the experts read through the OS file cache
(--mmap-experts on that PC) the file reads dominate and it measured no faster.

Correctness: with STRATA_IQ_MT_MIN=1 --pcie-frac 0 --adapt-every 0 the
greedy text is identical to the serial loop's when both have the same expert
caches (4/4 prompts, 500 tokens; the serial run given the pipeline's reserve
through --vram-reserve-mib). The same text with STRATA_PIPELINE_THETA=2 (no
speculative window), STRATA_PIPELINE_FORCE_MISS=1 (every speculative window
wrong, rolled back) with and without DOOM_SKIP, PRESTAGE=0 and
SNAP_OVERLAP=0. Against a run without the flag a few experts move from a card
to the CPU (the pipeline's VRAM), which rounds them differently, so a near-tie
can flip. With the adaptive tier on: 22 varied requests at temperature 0.6
(thinking on and off, five languages, code), and 11 more with
STRATA_PIPELINE_FORCE_MISS=2, gave no degenerate answer, no stall.

The watchdog prints the pipelined loop's state when it fires;
STRATA_PIPELINE_TRACE=<file> writes a timeline.
This commit is contained in:
Francesco Albano authored and Niko1221 committed 2026-10-05 13:19:38 +02:00
1 parent 8ba583fec2
commit bfa532e97c
6 files changed
+1384 -27

No files matched your search

+39
View File
@@ -191,6 +191,45 @@ The Coder on an RTX 5080 + RTX 3090 (Ryzen 9 9950X3D), 32K context; details in
3090 pair slower (68 / 90 tok/s decode): every extra card costs its own round per window.
- More cards pay off when the model's routed experts do not fit the faster ones.
## One conversation with both cards busy (`--pipeline-windows`, opt-in)
With a split the cards take turns on a verify window: the first card runs its layers and hands off, then waits while
the last card runs the rest, the head and the draft. `--pipeline-windows 2` lets the first card start the **next**
window while the last card still verifies this one. The next window is a guess: that this window is accepted whole
and that its bonus token is the one the draft layer predicts (the draft layer is run on through the drafts of the
window in flight). When the guess holds, half of the next window is already done; when it does not, the first card
puts its state back (a copy of its recurrent state taken while the window ran) and the next window is built from the
real tokens. A guessed window is only started when the draft layer's estimate says it is likely to be kept. Windows
copied from earlier context (`--suffix-draft`) are guessed past as well, which is where edits that copy text gain
most. `--pipeline-windows 1` overlaps only the short prompt reads that go through the verify windows
(`--short-read`).
Two cards, exactly two stages, `--serve`. In the config:
```
"args": [ ..., "--pipeline-windows", "2" ],
"layer_split": "20"
```
- **Cost**: a second verify window on each card, 160 MiB more kept out of each card's expert cache, plus two copies
of the first card's recurrent state (about 3 MiB per GDN layer it runs) on the first card with `2`.
- **Same text**: the last card only ever runs windows that are verified, and every window row computes what it
would in any other window, so the tokens are the serial loop's. With `STRATA_IQ_MT_MIN=1 --pcie-frac 0
--adapt-every 0` the greedy output is identical bit for bit to the serial loop's with the same expert caches. The pipeline keeps
its VRAM out of the caches, so against a run without the flag a few experts move from a card to the CPU, which
rounds them differently, and a near-tie can flip (a serial run given the same caches through `--vram-reserve-mib`
matches it exactly).
- **Off, with one line in the log saying why**, with `--batch` slots, `--peer-device`, the helper caches
(`--expert-cache-device1..3`, `--remote-expert-opt`), a split into three or more stages or onto one GPU
(`--split-device 0`), or no draft layer. A request with repetition penalties (`penalty_last_n`) or coupled
draft sampling decodes serially.
- **Measured** (Swift 1.5 IQ3_XXS, 160K context, q4_0 KV, the stock draft layer, RTX 4060 Ti (layers 0-19) +
RTX 5080 (20-47), i9-14900KF, 32 GB of RAM with the resident RAM mode on the split (#848); greedy, 500 tokens, two
interleaved pairs of three rounds, decode tok/s): Python code 90.4 -> 103.1, C code 76.6 -> 81.6, English prose
63.0 -> 71.1, Italian prose 41.6 -> 46.3, a copy-heavy edit (a 5 KB file back with a rename) 90.5 -> 117.9; mean
72.4 -> 84.0 (+16%). It pays when the windows are GPU-bound: with the experts read through the OS file cache
(`--mmap-experts` on that 32 GB PC) the file reads dominate and it measured no faster.
## Several conversations at once
With a layer split, `--batch N --batch-groups G --trim-stage-weights` decodes several conversations together and
+3
View File
@@ -487,6 +487,9 @@ public:
uint8_t* exchange_buffer(int64_t q) const;
/// Requires `has_resident(layer, in)`, `!has_resident(layer, out)` and `exchange_buffer(q)` holding out's blob.
bool stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q);
/// --pipeline-windows: size the exchange table now, so a `stage_exchange` on the adaptive tier's thread never
/// reallocates it under a concurrent `blob` (the pool reads it while windows are in flight).
void prepare_overrides() { if (override_.empty()) override_.assign((size_t) blobs_, nullptr); }
/// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied.
int64_t commit_exchanges();
/// `commit_exchanges` in two halves, for the asynchronous adaptive tier (--adapt-async): `commit_copies` moves
+2
View File
@@ -39,6 +39,8 @@ inline std::atomic<DiagFn>& release_gpu_fn() { static std::atomic<DiagFn> f{null
inline void release_gpu_waits(std::FILE* f) {
if (auto fn = release_gpu_fn().load()) fn(f);
}
/// --pipeline-windows: the pipelined loop's windows and the drafter's chain (set while that loop runs)
inline std::atomic<DiagFn>& diag_pipeline_fn() { static std::atomic<DiagFn> f{nullptr}; return f; }
inline Progress& progress() {
static Progress p;
+52
View File
@@ -185,6 +185,45 @@ public:
/// false with `err` when it failed. Free when nothing is pending.
bool wait_commit(std::string& err);
// ---- PIPELINED WINDOWS (--pipeline-windows, a layer split on two GPUs). One conversation's windows with the
// stages overlapped: stage 0 runs window K+1 while stage 1 still runs window K. The same window as `run`, driven
// without blocking the host, so one host thread keeps a window in flight on each stage (the batch pipeline's
// pattern, batch_launch / batch_poll, for one sequence with drafts). Two verifiers per stage (one per window
// parity) share the stage's stream and each has its own hand-off. `pl_launch` stages and launches (it never
// captures: `capture_all` first, with nothing in flight), `service` serves the layers whose doorbells have rung
// and returns at once, `done` polls the window's completion, `pl_finish` reads the picks, `pl_commit_async`
// queues the commit. Nothing chains to `next_`: the caller drives every stage.
/// The compute stream to use instead of a private one (the two verifiers of one stage share it). Before `init`.
void set_stream(cudaStream_t s) { ext_stream_ = s; }
/// Every layer copies the token rows to the host (doorbell_publish), not only the layers with a routed expert
/// outside the VRAM tier by the device's residency table: with windows in flight the adaptive tier marks an
/// expert evicted on the host (the pool then computes it on the CPU) before the device table follows. Also turns
/// the device-planned layers (E-6) off. Before `init`.
void set_always_publish(bool on) { always_publish_ = on; }
cudaStream_t stream() const { return cs_; }
int device() const { return device_; }
/// Capture every window size and the commit graph now (a capture syncs the stream: never with a window in flight).
bool capture_all(std::string& err);
bool pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string& err);
/// Stage a window ahead of its launch (positions, and the PLE rows from `ple_prev` = the two tokens before the
/// window as they WILL be, their pages prefetched). A later `pl_launch` of the same window (T, pos0, tokens, and
/// `ss.ple_prev` equal to `ple_prev` by then) skips the staging; anything else stages again.
bool prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err);
/// 1: every layer served; 0: the GPU has not reached the next layer yet; -1: an error (`err`).
int service(PoolMultiFn pool, void* user, std::string& err);
bool in_flight() const { return fl_active_; }
/// The window's graph (and its profile copy) completed; false while it runs. An error sets `err`.
bool done(std::string& err);
/// After `done`: the profile, the last stage's host sampling and picks (`out` may be null on an earlier stage).
bool pl_finish(int32_t* out, std::string& err);
/// The commit without a host sync; `ss.ple_prev` advances now (host side). A second call for the same window
/// (after its state was restored) replays it with another count.
bool pl_commit_async(int n_keep, std::string& err);
/// Fold another verifier's counters and GPU profile into this one's (the two verifiers of one stage report once).
void absorb_stats(Verifier& o);
/// The watchdog's line for a pipelined verifier: in flight, layers served, the GPU's ring and flags, its events.
void diag_pipelined(std::FILE* f, const char* name) const;
/// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head -
/// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the
/// distribution at pos0 + t, targets[t] is the token at pos0 + t + 1, extra_logprob is the log-probability of
@@ -257,6 +296,19 @@ private:
int64_t last_pos_b_[8] = {};
bool capture_batch(const int* rows, int S, int hbase, std::string& err);
void collect_profile(); ///< STRATA_VERIFY_PROFILE: add the last window's stamps to prof_sum_
void accumulate_profile(const unsigned long long* stamps); ///< one window's stamps (host copy) into prof_sum_
// pipelined windows (pl_launch ...)
cudaStream_t ext_stream_ = nullptr; ///< set_stream: the stage's shared stream (not destroyed here)
bool always_publish_ = false;
void pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]);
cudaEvent_t ev_done_ = nullptr, ev_commit_ = nullptr;
unsigned long long* prof_pin_ = nullptr; ///< pinned host copy of the stamps (pipelined windows)
bool fl_active_ = false, fl_prof_ = false, fl_ple_ = false, commit_live_ = false, pl_prestaged_ = false;
int fl_T_ = 0;
int64_t fl_k_ = 0, fl_total_ = 0;
double fl_since_ms_ = 0, fl_flush_ms_ = 0, fl_launch_ms_ = 0;
int32_t pl_prev_[2] = {-1, -1};
std::vector<uint32_t> pl_ple_rows_; ///< the window's PLE rows (T x PLE_N_HEADS), gathered when layer 0 is served
bool capture_commit_batch(const int* rows, int S, int hbase, std::string& err);
bool stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, std::string& err);
strata::kernels::SamplerParams sampling_ = [] {
+307 -10
View File
@@ -287,10 +287,13 @@ Verifier::~Verifier() {
if (kv.second) cudaGraphExecDestroy(kv.second);
if (arena_b_) cudaFree(arena_b_);
if (h_commitb_) cudaFreeHost(h_commitb_);
if (cs_) cudaStreamDestroy(cs_);
if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_); // set_stream: the stage's stream, shared, not ours
if (sh_cs_) cudaStreamDestroy(sh_cs_);
if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); }
if (commit_done_) cudaEventDestroy(commit_done_);
if (ev_done_) cudaEventDestroy(ev_done_);
if (ev_commit_) cudaEventDestroy(ev_commit_);
if (prof_pin_) cudaFreeHost(prof_pin_);
if (ev_fork_) cudaEventDestroy(ev_fork_);
if (ev_join_) cudaEventDestroy(ev_join_);
if (arena_) cudaFree(arena_);
@@ -480,8 +483,9 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
err = "verify: copy stream create failed";
return false;
}
if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess ||
cudaStreamCreateWithFlags(&sh_cs_, cudaStreamNonBlocking) != cudaSuccess) {
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) {
err = "verify: stream create failed";
return false;
}
@@ -517,7 +521,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
// exact, but neutral on RIBPC 1-2 GPUs: off by default)
{
const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN");
device_plan_ = !all_resident_ && (v != nullptr && std::atoi(v) != 0);
// (not with set_always_publish: the device table may lag the host's while windows are in flight)
device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi(v) != 0);
}
if (all_resident_ || device_plan_) {
bool ok2 = true;
@@ -962,7 +967,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs);
else
#endif
if (remote_opt_) // #578: the helper GPUs reduce with the routing weights - publish them
// #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows
// whatever the device's residency table says (pipelined windows)
if (remote_opt_ || always_publish_)
doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);
else {
@@ -1386,10 +1393,14 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) {
}
void Verifier::collect_profile() {
const ModelGeometry& g = *g_;
cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost);
accumulate_profile(prof_h_.data());
}
void Verifier::accumulate_profile(const unsigned long long* stamps) {
const ModelGeometry& g = *g_;
const int64_t L = g.n_layers;
auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; };
auto at = [&](int64_t l, int i) { return stamps[(size_t) (l * kProfPer + i)]; };
// D8: the derived columns below read stamps the hc-read kernels write themselves or the next
// layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns -
// which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now
@@ -1397,7 +1408,8 @@ void Verifier::collect_profile() {
const auto gap = [](unsigned long long to, unsigned long long from) {
return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0;
};
for (int64_t l = 0; l < L; ++l) {
// only this stage's layers [lb_, le_) are ever stamped (a layer split); the head only on the last stage
for (int64_t l = lb_; l < le_; ++l) {
const int kind = is_qsa_layer(g, l) ? 1 : 0;
unsigned long long prev = at(l, 0);
for (int i = 1; i <= 24; ++i) {
@@ -1406,7 +1418,7 @@ void Verifier::collect_profile() {
prof_sum_[kind][i] += (double) (x - prev);
prev = x;
}
if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24));
if (l + 1 < le_) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24));
const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28));
if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice
prof_sum_[kind][27] += dn; // hc-read0: norm
@@ -1415,7 +1427,7 @@ void Verifier::collect_profile() {
prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split)
}
}
prof_sum_[0][26] += gap(at(L, 1), at(L, 0));
if (le_ == L) prof_sum_[0][26] += gap(at(L, 1), at(L, 0));
++prof_windows_;
}
@@ -2317,4 +2329,289 @@ bool Verifier::copy_logits(int t, float* host) const {
cudaMemcpyDeviceToHost) == cudaSuccess;
}
// ================================ PIPELINED WINDOWS (see verify.hpp) ================================
//
// The window is run()'s, step for step: the same graph, the same staging, the same per-layer service (the PLE rows
// gathered while layer 0 is served, the zero-doorbell graph's one flag), the same commit graph. Only the waits are
// split up: the host polls instead of spinning, so it can serve the other stage's window in between.
namespace {
double now_ms() { return std::chrono::duration<double, std::milli>(Clock::now().time_since_epoch()).count(); }
} // namespace
void Verifier::diag_pipelined(std::FILE* f, const char* name) const {
auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
auto ev = [](cudaEvent_t e) {
if (e == nullptr) return "none";
const cudaError_t q = cudaEventQuery(e);
return q == cudaSuccess ? "done" : q == cudaErrorNotReady ? "PENDING" : "error";
};
std::fprintf(f, " %s: %s T=%d pos %lld served %lld/%lld; GPU rang %u, flags served %u A %u B %u; window event %s, "
"commit event %s (commit launched %d)\n", name, fl_active_ ? "IN FLIGHT" : "idle", last_t_,
(long long) last_pos0_, (long long) fl_k_, (long long) fl_total_, rd(h_seq_), rd(h_flag_), rd(h_flagA_),
rd(h_flagB_), ev(ev_done_), ev(ev_commit_), (int) commit_live_);
}
bool Verifier::capture_all(std::string& err) {
const OnDevice on_device(device_);
if (g_ == nullptr) { err = "verify: capture_all before init"; return false; }
if (remote_opt_ != nullptr) { err = "verify: pipelined windows do not serve --remote-expert-opt"; return false; }
if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
for (int T = 1; T <= max_t_; ++T)
if (!capture(T, err)) return false;
if (!capture_commit(err)) return false;
if ((ev_done_ == nullptr && cudaEventCreateWithFlags(&ev_done_, cudaEventDisableTiming) != cudaSuccess) ||
(ev_commit_ == nullptr && cudaEventCreateWithFlags(&ev_commit_, cudaEventDisableTiming) != cudaSuccess)) {
err = "verify: event create failed";
return false;
}
if (prof_on_ && prof_pin_ == nullptr &&
cudaHostAlloc((void**) &prof_pin_, prof_h_.size() * 8, cudaHostAllocDefault) != cudaSuccess) {
prof_pin_ = nullptr; // the pipelined windows go unprofiled
cudaGetLastError();
}
pl_ple_rows_.assign((size_t) strata::kernels::kVerifyMaxT * strata::kernels::PLE_N_HEADS, 0u);
return true;
}
// The host staging of a pipelined window: run()'s (stage_inputs), and its PLE rows from `ple_prev` with their pages
// prefetched (they are gathered into the mapped rows when layer 0 is served, as run() does).
void Verifier::pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]) {
using namespace strata::kernels;
stage_inputs(T, tokens, pos0);
staged_ = false; // a later run() stages its own window
SessionState& ss = *ss_;
fl_ple_ = ss.ple.ready() && ple_stage();
if (fl_ple_) {
int32_t prev[2] = {ple_prev[0], ple_prev[1]};
for (int t = 0; t < T; ++t) {
ngram_rows(&tokens[t], prev, 1, ss.ple.consts, pl_ple_rows_.data() + t * PLE_N_HEADS);
prev[0] = prev[1];
prev[1] = tokens[t];
ss.ple.table->prefetch_rows(pl_ple_rows_.data() + t * PLE_N_HEADS);
}
}
pl_prev_[0] = ple_prev[0];
pl_prev_[1] = ple_prev[1];
}
bool Verifier::prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err) {
if (fl_active_) { err = "verify: a window is in flight on this verifier"; return false; }
if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
if (pl_ple_rows_.empty()) { err = "verify: pipelined window not prepared (capture_all)"; return false; }
const Clock::time_point t0 = Clock::now();
pl_stage(T, tokens, pos0, ple_prev);
pl_prestaged_ = true;
ms_host += ms_since(t0);
return true;
}
bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string& err) {
const OnDevice on_device(device_);
if (fl_active_) { err = "verify: a window is already in flight on this verifier"; return false; }
if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
SessionState& ss = *ss_;
if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
if (exec_[T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) {
err = "verify: pipelined window not prepared (capture_all)";
return false;
}
const Clock::time_point t0 = Clock::now();
last_batch_ = false;
bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0;
for (int t = 0; staged && t < T; ++t) staged = last_tokens_[t] == tokens[t];
if (staged && ss.ple.ready() && ple_stage())
staged = pl_prev_[0] == ss.ple_prev[0] && pl_prev_[1] == ss.ple_prev[1];
pl_prestaged_ = false;
if (!staged) pl_stage(T, tokens, pos0, ss.ple_prev);
const int G = groups_[T] > 0 ? groups_[T] : 1;
fl_T_ = T;
fl_k_ = 0;
fl_total_ = (le_ - lb_) * G;
fl_prof_ = prof_on_ && G == 1 && prof_pin_ != nullptr;
if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs only
std::atomic_thread_fence(std::memory_order_seq_cst);
trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T);
ms_host += ms_since(t0);
const cudaError_t le = cudaGraphLaunch(exec_[T], cs_);
trace_ev("LAUNCHED", -1, -1, (int64_t) le);
if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
if (fl_prof_) cudaMemcpyAsync(prof_pin_, prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost, cs_);
if (cudaEventRecord(ev_done_, cs_) != cudaSuccess) { err = "verify: event record failed"; return false; }
(void) cudaStreamQuery(cs_); // WDDM: submit now
fl_active_ = true;
fl_since_ms_ = fl_flush_ms_ = fl_launch_ms_ = now_ms();
return true;
}
int Verifier::service(PoolMultiFn pool, void* user, std::string& err) {
if (!fl_active_) return 1;
if (fl_k_ >= fl_total_) return 1;
const OnDevice on_device(device_);
const ModelGeometry& g = *g_;
SessionState& ss = *ss_;
const int T = fl_T_;
// the PLE rows into the mapped staging (layer 1's pre() copies them once flag 1 is up), as run() does at k == 0
auto gather_ple = [&]() -> bool {
if (!fl_ple_) return true;
const Clock::time_point tp = Clock::now();
if (!ss.ple.table->gather_batch(pl_ple_rows_.data(), (size_t) T, h_ple_, err)) return false;
std::atomic_thread_fence(std::memory_order_seq_cst);
_mm_sfence();
ms_host += ms_since(tp);
return true;
};
if (all_resident_) { // the zero-doorbell graph never rings: it waits only for flag 1 (stage 0's PLE rows)
if (!gather_ple()) return -1;
*(volatile uint32_t*) h_flag_ = 1;
fl_k_ = fl_total_;
progress_tick();
return 1;
}
const int G = groups_[T] > 0 ? groups_[T] : 1;
const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
while (fl_k_ < fl_total_) {
const int64_t l = lb_ + fl_k_ / G;
const uint32_t want = (uint32_t) (fl_k_ + 1);
if (*(volatile uint32_t*) h_seq_ < want) {
const double now = now_ms();
if (now - fl_flush_ms_ > 2.0) { // flush WDDM and notice a dead graph, as run() does
fl_flush_ms_ = now;
const cudaError_t q = cudaEventQuery(ev_done_);
if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < want) {
trace_ev("NEVER-RANG", fl_k_, l, (int64_t) q);
err = "verify: layer " + std::to_string(l) + " never rang (" +
(q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
return -1;
}
(void) cudaStreamQuery(cs_);
}
if (now - fl_since_ms_ > 20000.0) { // #267: no spin kernel may outlive the engine
trace_ev("TIMEOUT", fl_k_, l, 0);
err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
return -1;
}
return 0;
}
const Clock::time_point b = Clock::now();
ms_wait += now_ms() - fl_since_ms_;
const int grp = (int) (fl_k_ % G);
cur_layer_ = want - 1;
set_plan_slot(grp);
const int tb = gtb[grp], n = gte[grp] - gtb[grp];
progress_at("verify window (pipelined): 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);
if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", fl_k_, l,
(int64_t) ms_since(b));
progress_tick();
std::atomic_thread_fence(std::memory_order_seq_cst);
_mm_sfence();
if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one
sink_.counts[0] = 0;
sink_.counts[1] = 0;
sink_.counts[2] = 0;
sink_.start[0] = 0;
sink_.start2[0] = 0;
std::atomic_thread_fence(std::memory_order_seq_cst);
*(volatile uint32_t*) h_flagA_ = want;
raise_flag(h_flagB_, want);
}
if (fl_k_ == 0 && !gather_ple()) return -1;
*(volatile uint32_t*) h_flag_ = want;
++fl_k_;
ms_pool += ms_since(b);
fl_since_ms_ = fl_flush_ms_ = now_ms();
}
return 1;
}
bool Verifier::done(std::string& err) {
if (!fl_active_ || fl_k_ < fl_total_) return false;
const OnDevice on_device(device_);
const cudaError_t q = cudaEventQuery(ev_done_);
if (q == cudaErrorNotReady) {
const double now = now_ms();
if (now - fl_flush_ms_ > 2.0) { fl_flush_ms_ = now; (void) cudaStreamQuery(cs_); }
if (now - fl_since_ms_ > 20000.0) { // every layer served, and the graph still runs: #267 as above
err = "verify: the window never finished" + released_note(release_gpu_waits(5000));
}
return false;
}
if (q != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(q); return false; }
if (copy_used_) { // no host function of this window may raise flag B in the next one
if (cudaStreamQuery(copy_) == cudaErrorNotReady) return false;
copy_used_ = false;
}
return true;
}
bool Verifier::pl_finish(int32_t* out, std::string& err) {
using namespace strata::kernels;
const OnDevice on_device(device_);
const ModelGeometry& g = *g_;
fl_active_ = false;
if (fl_prof_) accumulate_profile(prof_pin_);
++windows;
trace_ev("DONE (pipelined)", -1, -1, (int64_t) (now_ms() - fl_launch_ms_));
if (le_ < g.n_layers) return true; // an earlier stage: the hand-off is written
const int T = fl_T_;
const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;
if (head_sampling_ && (sampled || hist_d_ != nullptr)) { // run()'s host-side sampling, Philox(seed, pos0 + t)
SamplerParams sp = sampling_;
sp.counter = (uint64_t) last_pos0_;
sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
if (cudaStreamSynchronize(cs_) != cudaSuccess) {
err = "verify: the head sampling failed";
return false;
}
}
if (out != nullptr)
for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
progress_beat();
return true;
}
bool Verifier::pl_commit_async(int n_keep, std::string& err) {
const OnDevice on_device(device_);
if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }
if (commit_exec_ == nullptr || ev_commit_ == nullptr) { err = "verify: pipelined commit not prepared"; return false; }
const Clock::time_point t0 = Clock::now();
if (commit_live_) { // its graph reads the words below when it starts: the previous one has (a window ago)
cudaError_t q;
while ((q = cudaEventQuery(ev_commit_)) == cudaErrorNotReady) _mm_pause();
if (q != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(q); return false; }
}
h_commit_[0] = n_keep;
h_commit_[1] = n_keep - 1;
for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;
std::atomic_thread_fence(std::memory_order_seq_cst);
const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_);
if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; }
if (cudaEventRecord(ev_commit_, cs_) != cudaSuccess) { err = "verify: event record failed"; return false; }
(void) cudaStreamQuery(cs_);
commit_live_ = true;
if (ple_stage())
for (int t = 0; t < n_keep; ++t) {
ss_->ple_prev[0] = ss_->ple_prev[1];
ss_->ple_prev[1] = last_tokens_[t];
}
ms_commit += ms_since(t0);
return true;
}
void Verifier::absorb_stats(Verifier& o) {
ms_wait += o.ms_wait; ms_pool += o.ms_pool; ms_host += o.ms_host; ms_commit += o.ms_commit;
windows += o.windows;
o.ms_wait = o.ms_pool = o.ms_host = o.ms_commit = 0;
o.windows = 0;
for (int k = 0; k < 2; ++k)
for (int i = 0; i < kProfPer; ++i) { prof_sum_[k][i] += o.prof_sum_[k][i]; o.prof_sum_[k][i] = 0; }
prof_windows_ += o.prof_windows_;
o.prof_windows_ = 0;
}
} // namespace strata::core
+981 -17
View File
File diff suppressed because it is too large. Load diff