From f629fb04177375041b7e0769165b8740d993963e Mon Sep 17 00:00:00 2001 From: yi-sudo Date: Tue, 13 Oct 2026 13:14:37 +0800 Subject: [PATCH 01/14] Batch decode: one launch for all rows in QSA attention and GDN recurrence (opt-in) With --batch N the verify window ran QSA block scoring, top-k and decode attention as one launch per row, and the GDN recurrence (window and 1-row commit) as one launch per slot. At 4-8 live slots these serial launches are most of the window's cost beyond the expert reads. Two env switches, both off by default (off = the same launches as before): STRATA_BATCH_ATTN_ROWS=1 block scores, top-k and decode attention for all rows of the window in one launch each; every row reads its own slot's indexer keys and K/V pools (passed by value as kernel params, so the graph captured per row layout stays valid). A slot that streams KV (kv_mode 1) keeps the per-row path. STRATA_BATCH_GDN_GROUPS=1 GDN recurrence in the window and the 1-row commit for all slots in one launch (grid.y = slot group). Conv commits stay per slot. Same arithmetic per row: 4 concurrent temperature-0 prompts give the same bytes with and without the switches (--batch 4 and --batch 8). RTX PRO 6000 Blackwell, IQ3_S, all experts in VRAM, a0116b2, same day, total tok/s (docs/BATCHING.md has the table): --batch 4, 4 clients: 268.4 -> 311.7 --batch 8, 8 clients: 308.4 -> 374.8 (reserve 6144 MiB) Window: 4 rows 14.3 -> 12.2 ms, 8 rows 24.6 -> 19.9 ms. Built and run with CUDA 13.0 (sm_120) only. The .cu files are also in the HIP build, which was not built here (no ROCm). The SYCL port has its own copies of these files and is untouched. --- docs/BATCHING.md | 31 ++++++++++ include/strata/kernels/qsa_decode_attn.hpp | 12 ++++ include/strata/kernels/qsa_select.hpp | 10 ++++ include/strata/kernels/verify_kernels.hpp | 14 +++++ src/core/verify.cpp | 69 ++++++++++++++++++++++ src/kernels/cuda/qsa_decode_attn.cu | 40 ++++++++++++- src/kernels/cuda/qsa_select.cu | 26 ++++++-- src/kernels/cuda/verify_kernels.cu | 37 +++++++++++- 8 files changed, 233 insertions(+), 6 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 69e5e2f7..9f068ee3 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -262,6 +262,37 @@ tok/s, at 0.7 -> 358 tok/s. `--trim-stage-weights` alone raised the share of experts held in VRAM on that machine from 76-85 % to 84-100 % per card. +### One launch for all slots (opt-in) + +In a batch window, QSA block scoring, top-k and decode attention ran as one launch per row, and the GDN recurrence +(in the window and in the 1-row commit) as one launch per slot. Two switches run each of them as one launch for all +rows, every row still reading its own slot's indexer keys, K/V pools and GDN state (passed by value as kernel +params, so the graph captured per row layout stays valid): + +| Switch | What it does | +| --- | --- | +| `STRATA_BATCH_ATTN_ROWS=1` | block scores, top-k and decode attention of all the window's rows (up to 8) in one launch each. Not with KV streaming (a slot with `kv_mode` 1 keeps the per-row launches). | +| `STRATA_BATCH_GDN_GROUPS=1` | the GDN recurrence in the window, and the commit of 1-row groups, for all slots in one launch. The conv commits stay per slot. | + +Both are off by default; off, the engine runs the same launches as before. On, the arithmetic per row is the same: +4 concurrent prompts at temperature 0 gave the same bytes as without them, with `--batch 4` and `--batch 8`. + +One RTX PRO 6000 Blackwell (96 GB), IQ3_S, all 24,576 experts in VRAM, `--kv int8`, 262144 context, `--mtp`, +`--spec 4`, through the HTTP server: C different stories sent at once, 1024 tokens each, temperature 0.7, mean of +2 rounds, total tok/s (engine a0116b2, same day): + +| Concurrent | `--batch 4` | with both switches | `--batch 8` (reserve 6144 MiB) | with both switches | +| ---: | ---: | ---: | ---: | ---: | +| 1 | 179.2 | 179.4 | 186.6 | 179.7 | +| 2 | 204.1 | 218.7 | | | +| 3 | 243.2 | 276.6 | | | +| 4 | 268.4 | 311.7 | 267.7 | 311.6 | +| 6 | | | 297.7 | 354.8 | +| 8 | | | 308.4 | 374.8 | + +The window (`strata batch:` in the engine log) costs 14.3 ms for 4 rows and 24.6 ms for 8 rows without them, and +12.2 ms and 19.9 ms with them: about 1.7-1.9 ms per added row instead of 2.4 ms. + ## Together with conversation parking `--conversation-cache-mib N --conversation-cache-slots K` (DETAILS.md) works with the layer split too: a request diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp index 45c0f301..d2ecc49e 100644 --- a/include/strata/kernels/qsa_decode_attn.hpp +++ b/include/strata/kernels/qsa_decode_attn.hpp @@ -32,6 +32,13 @@ struct QsaAttnPools { const int32_t* page_table = nullptr; }; +/// Batch windows: every query's own K/V pools - query z reads p[z] (z < n). n = 0: the call's one `pools`. +inline constexpr int kAttnRowsMax = 8; +struct QsaAttnPoolsRows { + QsaAttnPools p[kAttnRowsMax]; + int n = 0; +}; + /// Scratch floats for `cap` selected cells: partial accumulators, maxima and sums. uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s); @@ -43,4 +50,9 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream); +/// qsa_decode_attn_batch for up to kAttnRowsMax queries of DIFFERENT sequences (batch slots), query z attending +/// over rows.p[z] - one launch instead of one per query, the same per-query arithmetic (bit-identical outputs). +void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream); + } // namespace strata::kernels diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp index c36d29cf..a371cf02 100644 --- a/include/strata/kernels/qsa_select.hpp +++ b/include/strata/kernels/qsa_select.hpp @@ -24,6 +24,16 @@ namespace strata::kernels { /// scores [nq, max_blocks]; q_idx [nq, idx_n_head, idx_dim] (normed and rotated); steps [nq, kStepCount]. +/// Batch windows: query q's own indexer keys - pooled[q], dead[q] (q < n <= 8). +struct QsaScoreRows { + const float* pooled[8] = {}; + const float* dead[8] = {}; + int n = 0; +}; +/// qsa_block_scores for up to 8 queries of DIFFERENT sequences in one launch (the multi kernel, per query its own +/// keys; the same arithmetic in the same order: bit-identical scores). +void qsa_block_scores_rows(const QsaScoreRows& rows, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream); void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks = -1); ///< perf-review C-1: > 0 launches only this many blocks (the diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 5b37cdf4..6f54e0bb 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -38,6 +38,20 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet /// The recurrence + output norm for T tokens (h = (T, conv_channels) as q|k|v, gate/beta (T, h_v), z/y /// (T, value_dim)). With `n_keep == nullptr` the state is read and NOT written (verify); otherwise the first /// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`. +/// Batch windows: up to 8 slot groups in one launch - group i is rows [first[i], first[i] + ntok[i]) of the +/// window's buffers, recurring over its own slot's state[i] (and committing keep[i] tokens when keep is given). +struct GdnGroups { + float* state[8] = {}; + const int32_t* keep[8] = {}; + int first[8] = {}; + int ntok[8] = {}; + int n = 0; +}; +/// gdn_step_norm_multi over several slots' groups at once (the generic kernel, grid.y = group; per group the +/// same arithmetic as one call each: bit-identical). `commit`: every group keeps *keep[i] tokens, no outputs used. +void gdn_step_norm_groups(const GdnGroups& groups, const float* h, int conv_channels, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, bool commit, + void* stream); void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, const int32_t* n_keep, void* stream, int t_out_begin = 0, void* xq_out = nullptr); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index a8791cc6..d7d50062 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1195,6 +1195,24 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { stamp(l, 5, grp); } // the recurrence from the untouched state over tokens [0, te); outputs only for this group's + static const bool gdn_groups_on = [] { // STRATA_BATCH_GDN_GROUPS=1, all slots in one launch + const char* v = std::getenv("STRATA_BATCH_GDN_GROUPS"); + return v != nullptr && std::atoi(v) != 0; + }(); + if (batch_rec_ && gdn_groups_on && te - tb <= 8) { + strata::kernels::GdnGroups gg; + for (int t = tb; t < te;) { + const int first = t; + while (t < te && brow_[t] == brow_[first]) ++t; + SessionState& sx = slot_ss(first); + gg.state[gg.n] = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats; + gg.first[gg.n] = first; + gg.ntok[gg.n] = t - first; + ++gg.n; + } + strata::kernels::gdn_step_norm_groups(gg, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, + y_, (int) HK, (int) HV, false, cs); + } else if (batch_rec_) { // each slot's recurrence over its own proposed-token group for (int t = tb; t < te;) { const int first = t; @@ -1399,6 +1417,35 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } } stamp(l, 10, grp); + // STRATA_BATCH_ATTN_ROWS=1: the window's rows in ONE launch per step - scores with each row's + // own indexer keys, the top-k over all rows (row-independent), attention with each row's own pools - + // instead of 3-4 one-row launches per row; the same per-row arithmetic. Not with KV streaming + // (qsa_kv_resolve has work per slot then). + static const bool attn_rows = [] { + const char* v = std::getenv("STRATA_BATCH_ATTN_ROWS"); + return v != nullptr && std::atoi(v) != 0; + }(); + bool rows_ok = batch_rec_ && attn_rows && te - tb <= strata::kernels::kAttnRowsMax; + for (int t = tb; rows_ok && t < te; ++t) rows_ok = slot_ss(t).qsa_states[qi].kv_mode != 1; + if (rows_ok) { + const int n_rows = te - tb; + strata::kernels::QsaScoreRows sr; + strata::kernels::QsaAttnPoolsRows pr; + sr.n = pr.n = n_rows; + for (int t = tb; t < te; ++t) { + const QsaState& sx = slot_ss(t).qsa_states[qi]; + sr.pooled[t - tb] = sx.idx_pooled; + sr.dead[t - tb] = sx.idx_dead; + pr.p[t - tb] = qsa_attn_pools(sx); + } + qsa_block_scores_rows(sr, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n_rows, max_blocks_, s, + scores_ + (size_t) tb * max_blocks_, cs); + qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n_rows, max_blocks_, cap_, + s, sel_ + (size_t) tb * cap_, cs); + qsa_decode_attn_batch_rows(qcur_ + tb * NH * HD, pr, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, + cap_, s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, + attn_ + tb * NH * HD, n_rows, cs); + } else if (batch_rec_) { // each row selects and attends over its own slot's K/V for (int t = tb; t < te; ++t) { const QsaState& sx = slot_ss(t).qsa_states[qi]; @@ -2815,6 +2862,15 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri if (!is_qsa_layer(g, l)) { const WeightRef* wnm = need(v, "ssm_norm.weight", err); if (!wnm) { ok = false; break; } + // STRATA_BATCH_GDN_GROUPS=1: one-row groups (no --batch-mtp proposals) commit their recurrence + // in one launch for all slots; the conv commits stay per slot + static const bool gdn_groups_on = [] { + const char* v = std::getenv("STRATA_BATCH_GDN_GROUPS"); + return v != nullptr && std::atoi(v) != 0; + }(); + bool one_row = S <= 8; + for (int t = 1; one_row && t < S; ++t) one_row = rows[t] != rows[t - 1]; + strata::kernels::GdnGroups gg; for (int t = 0; t < S;) { const int first = t; while (t < S && rows[t] == rows[first]) ++t; @@ -2824,6 +2880,14 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, (int) C, keep, cs_); + if (gdn_groups_on && one_row) { + gg.state[gg.n] = state; + gg.keep[gg.n] = keep; + gg.first[gg.n] = first; + gg.ntok[gg.n] = 1; + ++gg.n; + continue; + } gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV, beta_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV, @@ -2832,6 +2896,11 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri (int) HV, t - first, keep, cs_, t - first > 1 ? t - first : 0); // a 1-row group keeps the 0.1.39 kernel } + if (gg.n > 0) + gdn_step_norm_groups(gg, h_L_ + (size_t) gdn_index * MT * C, (int) C, + gate_L_ + (size_t) gdn_index * MT * HV, beta_L_ + (size_t) gdn_index * MT * HV, + z_, (const float*) wnm->data, EPS, y_dummy_, (int) g.ssm_k_heads, (int) HV, true, + cs_); ++gdn_index; } else { const WeightRef* wikn = need(v, "indexer.k_norm.weight", err); diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index bff0e420..9a0bc84d 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -122,7 +122,9 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest const int32_t* __restrict__ step, int n_kv_heads, int page_size, float scale, float* __restrict__ part_acc, float* __restrict__ part_m, float* __restrict__ part_l, - int n_chunks, int cap = 0, long long scratch_stride = 0) { + int n_chunks, int cap = 0, long long scratch_stride = 0, + QsaAttnPoolsRows prow = {}) { + if (prow.n > 0) p = prow.p[blockIdx.z]; // a batch window's query attends over its own slot's pools // batched form: query blockIdx.z, with its own q row, selection, step and scratch q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; ids += (size_t) blockIdx.z * (size_t) cap; @@ -710,6 +712,42 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 } } +void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return; + const QsaAttnPools& pools = rows.p[0]; + if (rows.n != n_q || n_q > kAttnRowsMax || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || + !scratch || !ids || !steps) { + std::fprintf(stderr, "qsa_decode_attn_batch_rows: unsupported geometry or missing buffers\n"); + std::exit(1); + } + const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; + float* part_l = part_m + (size_t) n_chunks * s.n_head; + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); + cudaStream_t st = (cudaStream_t) stream; + // the default kernel of qsa_decode_attn_batch on this target (no lane-cell, no pre-sm_75, no gfx906 variants) +#define STRATA_ATTN_ROWS(M) attn_chunk_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, \ + (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride, rows) + if (kv_mode == 3) STRATA_ATTN_ROWS(3); + else if (kv_mode == 2) STRATA_ATTN_ROWS(2); + else if (kv_mode == 1) STRATA_ATTN_ROWS(1); + else STRATA_ATTN_ROWS(0); +#undef STRATA_ATTN_ROWS + attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, + attn, stride); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn_batch_rows: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { const int64_t chunks = (cap + CHUNK - 1) / CHUNK; return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64; diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu index cb06396a..8d405680 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -821,7 +821,7 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co const float* __restrict__ q_idx, const int32_t* __restrict__ steps, int nq, int64_t max_blocks, float* __restrict__ out, - bool early_exit) { + bool early_exit, QsaScoreRows srow = {}) { __shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM]; __shared__ int64_t s_nkv[MQ], s_nbid[MQ]; if (!early_exit) @@ -844,12 +844,16 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co const int lane = threadIdx.x & 31; const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS; for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) { - const float4 kp = *reinterpret_cast(pooled + b * IDX_DIM + lane * 4); - const float4 kd = *reinterpret_cast(dead + lane * 4); + // srow.n > 0: each query reads its own sequence's keys; else one set of keys for every query + const bool own = srow.n > 0; + const float4 kp = own ? float4{} : *reinterpret_cast(pooled + b * IDX_DIM + lane * 4); + const float4 kd = own ? float4{} : *reinterpret_cast(dead + lane * 4); for (int qi = 0; qi < nq; ++qi) { const int64_t n_bid = s_nbid[qi]; if (b > n_bid) continue; - const float4 k4 = (b == n_bid) ? kd : kp; + const float4 k4 = !own ? ((b == n_bid) ? kd : kp) + : (b == n_bid) ? *reinterpret_cast(srow.dead[qi] + lane * 4) + : *reinterpret_cast(srow.pooled[qi] + b * IDX_DIM + lane * 4); const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4; float score = 0.0f; #pragma unroll @@ -1118,6 +1122,20 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores: %s\n", cudaGetErrorString(e)); std::exit(1); } } +void qsa_block_scores_rows(const QsaScoreRows& rows, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream) { + if (nq <= 0) return; + if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > MQ || rows.n != nq) { + std::fprintf(stderr, "qsa_block_scores_rows: unsupported geometry\n"); + std::exit(1); + } + static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }(); + block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(nullptr, nullptr, q_idx, steps, (int) nq, + max_blocks, scores, early, rows); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_rows: %s\n", cudaGetErrorString(e)); std::exit(1); } +} + bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { if (nq <= 0) return true; diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 39fdda2d..420ddf5c 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -291,7 +291,18 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re const float* __restrict__ gamma, float eps, float* __restrict__ y, int h_k, int h_v, int T, const int32_t* __restrict__ n_keep, int t_out_begin, - GdnQ81* __restrict__ xq) { + GdnQ81* __restrict__ xq, GdnGroups grp = {}) { + if (grp.n > 0) { // group blockIdx.y - its slot's state and its rows of the window's buffers + const int gi = blockIdx.y, f = grp.first[gi]; + state = grp.state[gi]; + hbuf += (size_t) f * C; + gate += (size_t) f * h_v; + beta += (size_t) f * h_v; + z += (size_t) f * S * h_v; + y += (size_t) f * S * h_v; + T = grp.ntok[gi]; + n_keep = grp.keep[gi]; + } __shared__ float sk[2][S], sq[2][S]; __shared__ float red_kv[RG][S]; __shared__ float red_o[RG][S]; @@ -1059,6 +1070,30 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet check("gdn_ab_multi"); } +void gdn_step_norm_groups(const GdnGroups& groups, const float* h, int conv_channels, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, bool commit, + void* stream) { + if (groups.n < 1 || groups.n > 8 || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k) { + std::fprintf(stderr, "gdn_step_norm_groups: invalid arguments\n"); + std::exit(1); + } + for (int i = 0; i < groups.n; ++i) + if (!groups.state[i] || groups.ntok[i] < 1 || groups.ntok[i] > kVerifyMaxT || (commit && !groups.keep[i])) { + std::fprintf(stderr, "gdn_step_norm_groups: invalid group %d\n", i); + std::exit(1); + } + const dim3 g1((unsigned) h_v, (unsigned) groups.n), b1(S, RG); + // the kernel gdn_step_norm_multi picks for these calls: a window's rows (all outputs, no keep) or a commit of + // one-row groups (keep, t_out_begin 0) + if (commit) + gdn_step_norm_multi_kernel<<>>( + nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups); + else + gdn_step_norm_multi_kernel<<>>( + nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups); + check("gdn_step_norm_groups"); +} + void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) { From a2de744653c30570fe5ad89f2ae7215d1251c383 Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:27:49 -0700 Subject: [PATCH 02/14] PleTable: a lock around its reader state, so two threads can use one table The prompt path gathers a chunk's PLE rows on its own thread and the batch windows gather theirs on the main thread, from the same table (ss.ple.table). Today they never overlap - a prompt run's read-ahead ends with the run, and the windows run between runs - but a prompt read beside running windows would race on the reader's tickets and the prefetch slots. Every public method that touches them now holds a recursive mutex (gather holds it across its issue and collect). Uncontended it is a few nanoseconds per call; nothing else changes. --- src/kernels/ngram.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp index 91de3705..b2086134 100644 --- a/src/kernels/ngram.cpp +++ b/src/kernels/ngram.cpp @@ -18,6 +18,7 @@ #endif #include #include +#include #include #include #include @@ -212,6 +213,8 @@ struct PleTable::Impl { strata::ngram::PleReader::Ticket ticket; bool pending = false; bool locked = false; + // the table is shared by the prompt path and the decode windows; they can use it at once (one on a worker thread) + std::recursive_mutex mu; uint32_t rows[PLE_N_HEADS] = {}; uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; static constexpr size_t kMaxPrefetch = 16; @@ -389,6 +392,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO } void PleTable::wait_prefetches() { + std::lock_guard lk(impl_->mu); if (impl_->n_prefetch == 0) return; std::string dummy; for (size_t i = 0; i < impl_->n_prefetch; ++i) (void) impl_->reader.collect(impl_->prefetch_tickets[i], dummy); @@ -396,6 +400,7 @@ void PleTable::wait_prefetches() { } void PleTable::prefetch_rows(const uint32_t* rows16) { + std::lock_guard lk(impl_->mu); if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { for (size_t i = 0; i < impl_->n_prefetch; ++i) if (std::memcmp(impl_->prefetch_keys[i], rows16, sizeof(uint32_t) * PLE_N_HEADS) == 0) return; @@ -444,6 +449,7 @@ uint64_t PleTable::rows() const { return impl_->n_rows; } uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } void PleTable::read_row(uint32_t row, float* out160) const { + std::lock_guard lk(impl_->mu); if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { uint8_t raw[PLE_ROW_BYTES_MAX]; std::string err; @@ -465,6 +471,7 @@ void PleTable::read_row(uint32_t row, float* out160) const { } bool PleTable::issue(const uint32_t* rows16) { + std::lock_guard lk(impl_->mu); wait_prefetches(); std::memcpy(impl_->rows, rows16, sizeof impl_->rows); if (impl_->mode == PleIo::Direct) { @@ -491,6 +498,7 @@ bool PleTable::issue(const uint32_t* rows16) { } bool PleTable::collect(float* out2560, std::string& err) { + std::lock_guard lk(impl_->mu); if (!impl_->pending) { err = "PleTable::collect without issue"; return false; } impl_->pending = false; if (impl_->mode == PleIo::Direct) { @@ -505,6 +513,7 @@ bool PleTable::collect(float* out2560, std::string& err) { } bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err) { + std::lock_guard lk(impl_->mu); if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; } const size_t n = n_tokens * (size_t) PLE_N_HEADS; if (impl_->mode == PleIo::Direct) { @@ -601,6 +610,7 @@ std::string PleTable::io_report() const { } void PleTable::gather(const uint32_t* rows16, float* out2560) const { + std::lock_guard lk(impl_->mu); // issue + collect as one if (impl_->mode == PleIo::Direct) { // `gather` stays const for its existing callers; the reader's state is the table's I/O state. PleTable* self = const_cast(this); From bc90e1acffdefb8383a73013ddfec892d5f1ee31 Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:23:17 -0700 Subject: [PATCH 03/14] batch-groups: read a prompt beside the decoding slots on a thread of its own (opt-in, experimental STRATA_PIPED_CONCURRENT) With a layer split and --batch-groups > 1 a prompt read is one sp.run, so every decoding slot stops for the whole read (#1906); #2050's pieces bound the stop but drain the pipeline at each piece. With STRATA_PIPED_CONCURRENT=1 the read runs on a worker thread while the main thread keeps the groups going through the pipeline (pump) and takes BSTOP and BYIELD meanwhile. The prompt's K/V goes to the main sessions and the slots' to their own; the windows' streams get the device's highest priority on CUDA (STRATA_PIPED_CONCURRENT_PRIO=0 keeps the default). - The slots' doorbells are served on a thread of their own that makes no CUDA call (Verifier::batch_serve, now batch_poll's per-layer service too, and set_external_serve). Two hangs found while building this, read from the stall dumps against the PDB, had #31's shape: the main thread waited for the driver's lock in cudaSetDevice while its holder waited for the GPU (a cudaFree in the drafter's prompt pass; cuBLASLt's lazy load of a GEMM module), and a window on that GPU waited for its doorbell. - MtpDrafter::reserve_prefill captures the drafter's prompt graphs and sizes its records before the read. - Prefill::stop_at_chunk: a BYIELD ends the run at its next chunk, also with no slot decoding; the pipeline is drained there and the part read gives way as #656 does. A read nobody waits for is not cut. - The reader is joined on every way out (an exception too). Off beside STRATA_PREFILL_HELP and STRATA_SPLIT_MTP_BATCH, which allocate during a read. --- include/strata/core/mtp.hpp | 4 + include/strata/core/verify.hpp | 18 ++- include/strata/prefill/prefill.hpp | 7 + src/core/mtp.cpp | 43 ++++-- src/core/verify.cpp | 88 ++++++++----- src/prefill/prefill.cpp | 7 + src/program/generate.cpp | 203 ++++++++++++++++++++++++----- 7 files changed, 296 insertions(+), 74 deletions(-) diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index d3c05a98..7216f015 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 a9dc19db..f04475dd 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 b_running_{false}; + std::atomic b_k_{0}; + int64_t b_steps_ = 0; + std::atomic ext_serve_{false}; std::chrono::steady_clock::time_point b_last_; int32_t b_out_[8] = {}; std::vector slot_sp_; diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index b4f100df..b5ddeff7 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 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 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 c36841c6..f75288ca 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 d7d50062..002b2d39 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(©_, cudaStreamNonBlocking) != cudaSuccess) { + if (!copy_made && make_stream(©_) != 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 2fa71c7c..228b5962 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 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 ba00f94d..3a5eb045 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 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(sp.chunk(), 1); + // BYIELD 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(C, o.short_read); + std::string ye; + const auto ty = Clock::now(); + std::vector 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(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 on{true}; + std::thread th; + std::function 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 done{false}; + std::atomic 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& 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 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(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(C, o.short_read); - std::string ye; - const auto ty = Clock::now(); - std::vector 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(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(Clock::now() - tq).count(); const auto td = Clock::now(); 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 04/14] 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; } From 6c5c382b9426432b22833f55fb92af2f4708fc8a 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 05/14] docs/BATCHING.md: reading beside the decoding slots, and what it measured The opt-in's section: how the read and the windows share the GPUs, the doorbell thread, the give-way at a chunk, where the mode is off. Measured against main (a0116b27) on 2x RTX 5090 in one window (main, this, this, main): the stops, the streams' rate during the reads with the same answers every run, the joining prompts' TTFT, a question during a read, the same randomised load on both, the doorbell thread's first wait as an A/B; 16 GB cards on each side; a weaker host as well in #1906's shape; the default path's check; text equality. tools/piped_read_join_bench.py, the client that measured it, is #2050's, unchanged (the same file as there). --- docs/BATCHING.md | 96 ++++++++++++++ tools/piped_read_join_bench.py | 226 +++++++++++++++++++++++++++++++++ 2 files changed, 322 insertions(+) create mode 100644 tools/piped_read_join_bench.py diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 9f068ee3..ee41b69c 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -141,6 +141,102 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske - Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`). - A client that disconnects stops its slot (`BSTOP`); the others go on. +## Reading a prompt beside pipelined groups (experimental, opt-in) + +With a layer split and `--batch-groups` above 1 a prompt is read in one run: every decoding slot stops until it is +read, however long it is (#1906). One GPU does not have this problem: there the slots decode between the prompt's +chunks for `STRATA_BATCH_DECODE_SHARE` x the chunk's time. + +`STRATA_PIPED_CONCURRENT=1` reads a prompt on a thread of its own while the slot groups keep decoding through the +pipeline, instead of stopping them: the prompt's chunks and the slots' windows run on the same GPUs at once, on their +own streams (the windows' at the device's highest priority on CUDA; `STRATA_PIPED_CONCURRENT_PRIO=0` keeps the default), +so the slots never wait for the read and the read is one run with no drain inside it. + +- The prompt's K/V goes to the main sessions and the slots' to their own, so they do not touch each other's state. The + n-gram (PLE) table both of them read is locked. The adaptive VRAM tier stands still during the read: its round lands + before the read and none starts while it runs. +- The VRAM expert slots the prompt path borrows are lent before the read and refilled after it, with nothing in flight; + in between the slots' windows compute those experts on the CPU. +- The slots' doorbells are served on a thread of their own during the read, which makes no CUDA call. A CUDA call can + wait for the driver's lock while its holder waits for the GPU - a free, or the module the first kernel of a new shape + loads - and a window on that GPU waits for its doorbell (issue #31's pattern: two such hangs were found and read from + the engine's stall dumps while this was built). The MTP drafter's prompt buffers and the prompt path's pinned upload + slots are sized before the read, so its thread allocates and frees nothing. Between windows the doorbell thread waits + for the next launch, which wakes it (a timed sleep is a whole timer tick on Windows, up to 15.6 ms). A window that + will not finish is still found (its graph ended with a layer still to ring, or no layer rang for 20 s), and the stall + watchdog stays on for the whole read. +- A waiting shorter request takes over at the read's next chunk (`BYIELD`), also when no slot decodes: the run ends + there, the pipeline is drained and the part read waits in a slot, as off the pipeline. A read nobody waits for is not cut. +- Off, said once, where the read's thread would allocate or free (`STRATA_PREFILL_HELP=1`, `STRATA_SPLIT_MTP_BATCH=1`), + where serving a doorbell makes a CUDA call (`--pcie-mode dma`, `STRATA_FS_SLOTS`, the helper caches + `--expert-cache-device1..3`), and with an expert source that hands out buffers it recycles (the GGUF in place, an + unbuffered source, `STRATA_IO_PREFETCH`): the experts come from the RAM arena or the mapped file. A prompt with + pictures is read the usual way. + +One log line per read (`strata batch: read N tokens on a thread of its own in X ms (concurrent, to Q of T); the slots +decoded R rows meanwhile (S rows/s; stage k: W windows, H ms host each)`). Built for CUDA and HIP (HIP keeps the default +stream priority, and is not run on a GPU here); SYCL does not have it. + +Measured on 2x RTX 5090 (Swift 1.5 IQ3_S, split 25, `--batch 6 --batch-groups 2`, resident experts, k8v4, 262K, +`--kv-resident 32768`, the engine-default decode share): main (`a0116b27`) against this mode, a fresh engine per arm in +the order main, this mode, this mode, main (`tools/piped_read_join_bench.py`; the fixed-prompt rows send the same four +stream prompts every run, so the streams' answers and work are the same): + +| | main | `STRATA_PIPED_CONCURRENT=1` | +| --- | ---: | ---: | +| 64K + 32K cold prompts beside four streams: longest stop of a stream | 11.9 s | 0.77-0.84 s | +| ... the streams' tokens meanwhile | 289-291 | 1,411-1,679 | +| ... the prompts' TTFT | 6.8 / 5.8-5.9 s | 8.1-8.2 / 8.2-8.3 s | +| the same with fixed stream prompts: the streams' rate while the prompts are read | 2-3 tok/s | 85-92 tok/s | +| ... the streams finish at | 26.1-27.1 s | 24.6-25.3 s | +| ... GPU utilization while the prompts are read | 75-86% | 85-91% | +| a one-line question 1 s into a cold 45K read, nothing decoding: its TTFT | 5.7-5.9 s | 1.9 s | +| ... and the 45K prompt's own TTFT | 6.2-6.4 s | 7.4-7.5 s | + +The joining prompts pay for the GPU time the streams now get. Over a whole run with the same work, the streams +finished 5-8% sooner (6.4% on average); with prompts that change from run to run (the bench's), the run's token rate +varies more than that between runs. Between windows the doorbell thread first slept 50 us, which is a whole timer +tick on Windows: the same build with `STRATA_TEST_BELL_SLEEP_US=50` gave the streams 64-67 tok/s during the reads +instead of 85-92. + +The same randomised load (`soak`: three streams, cold joins of 4-64K, short questions, follow-ups of earlier joins, +clients leaving mid-read and mid-answer; 5 minutes, the same seed) on main and in this mode: 167 and 180 requests +answered; the longest gap inside a stream 9.8 and 1.0 s (90th percentile 8.5 and 0.7 s); the joins' TTFT median 3.8 +and 4.6 s. A request that comes during a read still waits for it, unless its prompt is under half as long (`BYIELD`). + +A 16 GB card on each side (`--vram-reserve-mib 16600 --kv-resident 16384`, the same flags otherwise): + +| | main | this mode | +| --- | ---: | ---: | +| fixed stream prompts, 64K + 32K joining: the streams' rate while the prompts are read | 0.9 tok/s | 52.9 tok/s | +| ... the streams finish at | 70.6 s | 63.8 s | +| ... the prompts' TTFT | 9.5 / 10.1 s | 15.8 / 21.1 s | +| a one-line question 1 s into a cold 45K read: its TTFT | 7.3 s | 3.8 s | +| the 45K prompt read alone | 7.33 s | 7.25 s | + +A weaker host as well (16 GB cards, the experts from the mapped file, AVX2 expert kernels, 6 pool workers), in #1906's +shape (`--batch 2 --batch-groups 2`): one stream decoding while another's cold prompt is read: + +| cold prompt | main: the stream's longest stop / tok/s meanwhile / the prompt's TTFT | this mode | +| --- | ---: | ---: | +| 64K | 11.1 s / 2.4 / 10.9 s | 0.41 s / 25.7 / 11.7 s | +| 127K | 20.3 s / 1.5 / 19.9 s | 0.64 s / 32.7 / 20.7 s | + +So the cost is the joining prompt's: +4-7% beside one stream, +20-45% beside four on these cards, and +67-109% beside +four on 16 GB cards, where the streams' windows take a larger share of the GPU. + +**Checked:** with the variable unset this build gives main's tokens (six greedy answers' SHA-256 equal in two engine +starts each, `--prompt-cache 0 --adapt-swaps 0 --pcie-frac 0`) at main's speed. In this mode, 25 minutes of the +randomised load above (also on `--batch 2`): about 760 requests, 340 concurrent reads and 88 give-ways, with no hang, no +error and no stall report. + +**Text equality** (`batch_interleave_test.py --long 40000` with its exact settings, `--batch 4 --batch-groups 2`, no +conversation cache): this test is not reproducible run to run on this PC even for main (A differed from its solo tokens +at token 142 in one run of two). In this mode every request equaled its solo tokens in two runs of three - D giving way +at its first chunk (`YIELDED 2 2048`), E admitted meanwhile, D going on and A going back to the solo path included, +which main does not do on this path (D never gives way there); the third run had B off at token 74, a near tie that +flips on main as well. Greedy only; other GPU pairs, three or more stages and sampled decoding not measured. + ## The VRAM expert tier keeps adapting in batch windows Batch windows count which experts they route to, and every `--adapt-every` windows (default 4) the engine swaps the diff --git a/tools/piped_read_join_bench.py b/tools/piped_read_join_bench.py new file mode 100644 index 00000000..59ab8054 --- /dev/null +++ b/tools/piped_read_join_bench.py @@ -0,0 +1,226 @@ +"""Decoding streams while long cold prompts join: how smooth the streams stay, and what the joining prompt pays. + +Runs against a running `serve/server.py` (OpenAI API). N streams decode long greedy answers (thinking off); after a +delay one or two long cold prompts join. Every streamed token's arrival is timed on the client. Reported per scenario: + + joiner_ttft_s the joining prompt's time to first token + worst_max_gap_s the longest time any decoding stream received no token during the join window + mean_stalled_s per stream, the sum of gaps above 0.5 s during the window (mean over the streams) + stream_tokens_during_join tokens the decoding streams received from the first joiner's arrival to the last + joiner's first token + 1 s + aggregate_tok_s the streams' tokens / the run's wall time (throughput of the whole run) + +Two scenarios without decoding streams (#1504's test): `followup` reads a cold 45K prompt alone and sends a short +prompt 1 s later (followup_ttft_s: how long the short one waits behind the read; long_ttft_s: what the read pays); +`read_alone` is the same read without the follow-up (what the read costs by itself). + +The prompts are synthetic: the joiners are text from this repository's own files (src, include, serve, tools, docs), so +they route to most experts the way real code and tool output do; a joiner never repeats an earlier prompt (the +conversation cache would turn it into a warm read). `--determinism` instead sends fixed greedy prompts and prints the +SHA-256 of each answer (to compare two builds' output tokens). + + python tools/piped_read_join_bench.py --port 8080 --out join.json + python tools/piped_read_join_bench.py --port 8080 --scenarios two_joiners,followup --repeat 3 + python tools/piped_read_join_bench.py --port 8080 --determinism +""" +import argparse +import hashlib +import http.client +import json +import statistics +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +CODING = ["Write a Python function that parses an INI file into nested dicts, with tests. Explain each step.", + "Implement a thread-safe LRU cache in C++ with a short explanation of the design and its complexity.", + "Explain, with code, how to stream a large CSV file in Go and aggregate per-key statistics.", + "Write a TypeScript debounce and throttle pair with tests and explain where each one fits."] +DETERMINISM = ["Count from 1 to 40, comma separated.", "List the planets of the solar system in order, one per line.", + "Write the first 12 Fibonacci numbers.", "Explain in three sentences what a hash map is.", + 'Translate "good morning, how are you" into French, German and Spanish.', + "Write a haiku about compilers."] +# name -> the joins (delay s, size in K tokens) beside decoding streams, or (size, follow-up delay s) with none decoding +SCENARIOS = {"cold32k": [(6, 32)], "cold64k": [(6, 64)], "two_joiners": [(6, 64), (12, 32)], + "followup": (45, 1.0), "read_alone": (45, 0)} +_FILES = [] + + +def corpus(chars, offset): + """About `chars` characters of this repository's own files, from the `offset`-th file on (at most 60,000 each).""" + if not _FILES: + for sub, pat in (("src", "*.cpp"), ("src", "*.cu"), ("include", "*.hpp"), ("serve", "*.py"), ("tools", "*.py"), + ("docs", "*.md")): + _FILES.extend(sorted((ROOT / sub).rglob(pat))) + parts, n, i = [], 0, offset + while n < chars: + p = _FILES[i % len(_FILES)] + i += 1 + text = p.read_text(encoding="utf-8", errors="replace")[:60000] + parts.append("=== %s ===\n%s\n" % (p.relative_to(ROOT).as_posix(), text)) + n += len(parts[-1]) + return "".join(parts)[:chars] + + +def request(content, max_tokens, model): + """One streamed greedy chat request with thinking off.""" + return json.dumps({"model": model, "messages": [{"role": "user", "content": content}], "temperature": 0, + "max_tokens": max_tokens, "stream": True, "stream_options": {"include_usage": True}, + "chat_template_kwargs": {"enable_thinking": False}}).encode() + + +def stream(port, raw, timeout=1800): + """-> (token arrival times, text, usage, the time the request was sent)""" + c = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) + ts, text, usage = [], [], None + t0 = time.monotonic() + c.request("POST", "/v1/chat/completions", raw, {"Content-Type": "application/json", "Connection": "close"}) + r = c.getresponse() + if r.status != 200: + raise RuntimeError("HTTP %d" % r.status) + while True: + line = r.readline(1 << 20) + if not line: + break + if not line.startswith(b"data:"): + continue + data = line[5:].strip() + if data == b"[DONE]": + break + item = json.loads(data) + if item.get("usage"): + usage = item["usage"] + for ch in item.get("choices") or []: + d = (ch.get("delta") or {}).get("content") + if d: + ts.append(time.monotonic()) + text.append(d) + c.close() + return ts, "".join(text), usage or {}, t0 + + +def pct(v, p): + v = sorted(v) + return v[min(len(v) - 1, max(0, int(round(p / 100 * (len(v) - 1)))))] if v else 0 + + +def smooth(ts, lo, hi): + """One stream's arrivals in [lo, hi]: tokens, the longest and p99 gap, and the time in gaps above 0.5 s.""" + inside = [t for t in ts if lo <= t <= hi] + gaps = [b - a for a, b in zip(ts, ts[1:]) if b >= lo and a <= hi] + return {"tokens": len(inside), "max_gap_s": round(max(gaps or [0]), 3), "p99_gap_s": round(pct(gaps, 99), 3), + "stalled_s": round(sum(g for g in gaps if g > 0.5), 3)} + + +def scenario(port, model, name, n, joins, max_tokens, tag): + """`n` streams decode; each join (delay s, size in K tokens) then sends a cold prompt of this repository's text.""" + events, joined = {}, {} + + def decode(i): + content = "Stream %s-%s-%d. %s" % (tag, name, i, CODING[i % len(CODING)]) + events[i] = stream(port, request(content, max_tokens, model))[0] + + def join(k, delay, size): + time.sleep(delay) + text = corpus(int(size * 1024 * 3.3), 7 * size + k + 131 * len(name)) + content = "Join %s-%s-%d.\n%s\nName the file that defines the class above in one line." % (tag, name, k, text) + ts, _, usage, t0 = stream(port, request(content, 64, model)) + joined[k] = {"sent": t0, "first": ts[0] if ts else None, "usage": usage} + + t0 = time.monotonic() + threads = [threading.Thread(target=decode, args=(i,)) for i in range(n)] + threads += [threading.Thread(target=join, args=(k, d, size)) for k, (d, size) in enumerate(joins)] + for t in threads: + t.start() + for t in threads: + t.join() + lo = min(v["sent"] for v in joined.values()) + hi = max(v["first"] for v in joined.values()) + 1.0 + per = [smooth(ts, lo, hi) for _, ts in sorted(events.items())] + ends = [ts[-1] for ts in events.values() if ts] + joins_in_order = [v for _, v in sorted(joined.items())] + return {"joiner_ttft_s": [round(v["first"] - v["sent"], 3) for v in joins_in_order], + "joiner_prompt_tokens": [v["usage"].get("prompt_tokens") for v in joins_in_order], + "joiner_cached_tokens": [(v["usage"].get("prompt_tokens_details") or {}).get("cached_tokens") + for v in joins_in_order], + "worst_max_gap_s": max(p["max_gap_s"] for p in per), + "mean_stalled_s": round(statistics.mean(p["stalled_s"] for p in per), 3), + "stream_tokens_during_join": sum(p["tokens"] for p in per), + "aggregate_tok_s": round(sum(len(t) for t in events.values()) / (max(ends) - t0), 1), + "streams": per} + + +def alone(port, model, name, size, follow, tag): + """A cold prompt of `size` K tokens with nothing decoding; with `follow`, a short prompt `follow` s after it.""" + got = {} + + def long_read(): + text = corpus(int(size * 1024 * 3.3), 11 * size + 131 * len(name)) + content = "Read %s-%s.\n%s\nName the file that defines the class above in one line." % (tag, name, text) + ts, _, usage, t0 = stream(port, request(content, 64, model)) + got["long"] = (t0, ts[0] if ts else None, usage) + + def short(): + time.sleep(follow) + content = "Follow-up %s-%s: what is 17 x 23? Reply with the number only." % (tag, name) + ts, _, usage, t0 = stream(port, request(content, 16, model)) + got["short"] = (t0, ts[0] if ts else None, usage) + + threads = [threading.Thread(target=long_read)] + ([threading.Thread(target=short)] if follow else []) + for t in threads: + t.start() + for t in threads: + t.join() + out = {"long_ttft_s": round(got["long"][1] - got["long"][0], 3), + "long_prompt_tokens": got["long"][2].get("prompt_tokens")} + if follow: + out["followup_ttft_s"] = round(got["short"][1] - got["short"][0], 3) + out["followup_prompt_tokens"] = got["short"][2].get("prompt_tokens") + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--model", default=None, help="default: the server's own model id") + ap.add_argument("--streams", type=int, default=4) + ap.add_argument("--max-tokens", type=int, default=2048) + ap.add_argument("--scenarios", default="cold32k,cold64k,two_joiners", + help="comma-separated: " + ", ".join(SCENARIOS)) + ap.add_argument("--repeat", type=int, default=1, help="runs of each scenario (each with its own cold prompts)") + ap.add_argument("--out") + ap.add_argument("--determinism", action="store_true") + a = ap.parse_args() + tag = time.strftime("%H%M%S") + if a.model is None: + c = http.client.HTTPConnection("127.0.0.1", a.port, timeout=30) + c.request("GET", "/v1/models") + a.model = json.loads(c.getresponse().read())["data"][0]["id"] + c.close() + if a.determinism: + rows = [] + for p in DETERMINISM: + _, text, usage, _ = stream(a.port, request(p, 128, a.model)) + rows.append({"prompt_sha256": hashlib.sha256(p.encode()).hexdigest()[:12], + "answer_sha256": hashlib.sha256(text.encode()).hexdigest(), + "tokens": usage.get("completion_tokens")}) + print(json.dumps(rows, indent=1)) + return + out = {} + for rep in range(a.repeat): + for name in a.scenarios.split(","): + spec, run_tag = SCENARIOS[name], "%s.%d" % (tag, rep) + key = name if a.repeat == 1 else "%s#%d" % (name, rep + 1) + if isinstance(spec, tuple): + out[key] = alone(a.port, a.model, name, spec[0], spec[1], run_tag) + else: + out[key] = scenario(a.port, a.model, name, a.streams, spec, a.max_tokens, run_tag) + print(json.dumps({"scenario": key, **{k: v for k, v in out[key].items() if k != "streams"}}), flush=True) + time.sleep(3) + if a.out: + Path(a.out).write_text(json.dumps(out, indent=1)) + + +if __name__ == "__main__": + main() From 0d47295f5a4849dab3f5e1512cea27bc6427fbd1 Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:50:13 -0700 Subject: [PATCH 06/14] batch-groups: --remote-expert-opt without a helper cache does not keep the concurrent read off The flag works only through a helper cache (--expert-cache-device1..3), and on a plain layer split it is inert (MULTI_GPU.md, #1447), so the check looks at the helper caches themselves. #2275's rig runs a plain split with the flag set, and the mode would have stayed off there for a cache it does not have. --- include/strata/program/batch_read.hpp | 3 ++- src/program/generate.cpp | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/strata/program/batch_read.hpp b/include/strata/program/batch_read.hpp index d91afc1b..536e1cc3 100644 --- a/include/strata/program/batch_read.hpp +++ b/include/strata/program/batch_read.hpp @@ -33,7 +33,8 @@ struct ConcurrentReadSetup { 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 helper_caches = false; ///< --expert-cache-device1..3 (and --remote-expert-opt on them), a prompt source of + ///< its own; --remote-expert-opt alone is inert on a plain layer split 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 diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 80148f49..a54192ae 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -11664,7 +11664,8 @@ int main(int argc, char** argv) { 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; + // (--remote-expert-opt works only through a helper cache, so without one it does not count) + s.helper_caches = 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; From 073d079d27d229468456604a80eeac79bab301f7 Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:16:06 -0700 Subject: [PATCH 07/14] batch-groups: the concurrent read's threads do not share the host thread's core on Linux On Linux a thread inherits its creator's CPU mask, and the host thread is pinned to the one core the pool leaves it (aux_cpus.hpp). The read's thread and the doorbell thread were created from it, so they shared that core with the host thread that pumps the windows, and every window waited there for the doorbell of each layer: 6.1 rows/s during a read on 4x RTX 5080, 4 stages (blange48 on #2326). Windows places the host with CPU Sets, which new threads do not inherit, so it did not show there. Both threads now move off the host's core and the pool workers' CPUs (on an SMT machine with the default pool: the idle sibling threads; without such CPUs, every CPU but the host's), and the threads that already run on the host's CPU (the prompt path's copy threads, started by the first prompt) move the same way at a read. --aux-cpus places them all when it is on. STRATA_PIPED_CONCURRENT_UNPIN=0 keeps the inherited CPUs (an A/B). Measured on Linux (WSL2, Ubuntu 24.04, 2x RTX 5090, 4 streams, a cold 32K prompt; same binary, UNPIN=0 / default): the slots decoded 25.9 and 23.7 rows/s during the read with the threads kept on the host's CPU (76-81 threads there), and 75.6 and 62.8 with this change; with the n-gram table in RAM (WSL's disk reads it 7x slower than Windows) 110.7 rows/s, as on Windows (107.0). piped_read_join_bench.py (cold32k, followup, two_joiners; table in RAM, 2-3 runs each): 24-37 rows/s during the 30K+ reads kept on the host's CPU, 95-127 with this change, and 925-1,065 stream tokens during the cold 32K join against 454-484. On Windows, STRATA_TEST_CONC_ON_HOST_CPU=1 (a test) puts both threads on the host thread's CPU set first: 18.6 rows/s kept there, 105.4 with this change. --- include/strata/platform/aux_cpus.hpp | 64 ++++++++++++++++++++++++++++ src/program/generate.cpp | 54 ++++++++++++++++++++++- 2 files changed, 116 insertions(+), 2 deletions(-) diff --git a/include/strata/platform/aux_cpus.hpp b/include/strata/platform/aux_cpus.hpp index 3a560316..cd90e700 100644 --- a/include/strata/platform/aux_cpus.hpp +++ b/include/strata/platform/aux_cpus.hpp @@ -159,6 +159,7 @@ struct State { std::vector allowed; ///< the process's CPUs, snapshotted before any thread is pinned std::vector plan; ///< the aux CPUs (empty: nothing to do) std::vector workers; ///< the pool's CPUs: their threads are never touched + int host_cpu = -1; ///< the CPU the host thread is pinned to (-1: unknown) cpu_set_t target; std::set owned; ///< tids of pool workers and host threads std::map original; ///< tid -> the mask it had before this module moved it @@ -286,6 +287,66 @@ inline void set_enabled(bool on) { inline bool enabled() { return detail::state().enabled.load(std::memory_order_acquire); } +namespace detail { +/// The CPUs a thread that must not share the host's core runs on: every CPU the process may use but the host's and +/// the pool workers' (on an SMT machine with the default pool, the idle sibling threads); without such CPUs, every CPU +/// but the host's; failing that, every CPU. Caller holds `mu`. False when `configure` saw no CPUs. +inline bool off_host_target_locked(const State& s, cpu_set_t& out) { + if (s.allowed.empty()) return false; + auto build = [&](bool skip_workers) { + CPU_ZERO(&out); + int n = 0; + for (int c : s.allowed) { + if (c == s.host_cpu) continue; + if (skip_workers && std::find(s.workers.begin(), s.workers.end(), c) != s.workers.end()) continue; + CPU_SET(c, &out); + ++n; + } + return n; + }; + if (build(true) > 0 || build(false) > 0) return true; + CPU_ZERO(&out); + for (int c : s.allowed) CPU_SET(c, &out); + return true; +} +} // namespace detail + +/// Puts the calling thread off the host's core and off the pool workers' CPUs (see off_host_target_locked). A thread +/// the host creates inherits the host's single CPU; one that must not share that core (the concurrent prompt read's +/// thread and its doorbell thread, STRATA_PIPED_CONCURRENT) calls this first. False when nothing changed. +inline bool place_off_host() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + cpu_set_t to; + if (!detail::off_host_target_locked(s, to)) return false; + return sched_setaffinity(0, sizeof to, &to) == 0; +} + +/// Called on the host thread: every other thread that runs on exactly the host's CPUs (it inherited them: the prefill +/// copy threads started by the first prompt, a helper the host started) goes where place_off_host puts a thread. The +/// pool's workers and the host threads are never moved. Returns how many moved. +inline int release_host_inheritors() { + detail::State& s = detail::state(); + std::lock_guard lk(s.mu); + cpu_set_t host, all, to; + CPU_ZERO(&host); + CPU_ZERO(&all); + if (!detail::off_host_target_locked(s, to) || sched_getaffinity(0, sizeof host, &host) != 0) return 0; + for (int c : s.allowed) CPU_SET(c, &all); + if (detail::same_mask(host, all)) return 0; // the host is not pinned: nothing inherited a single core + detail::purge_locked(s); + const int self = detail::self_tid(); + int n = 0; + for (int tid : detail::task_ids()) { + if (tid == self || s.owned.find(tid) != s.owned.end()) continue; + cpu_set_t m; + CPU_ZERO(&m); + if (sched_getaffinity(tid, sizeof m, &m) != 0 || !detail::same_mask(m, host)) continue; + if (sched_setaffinity(tid, sizeof to, &to) == 0) ++n; + } + return n; +} + /// The aux CPUs of the plan ({} when there is none). inline std::vector plan() { detail::State& s = detail::state(); @@ -324,6 +385,7 @@ inline std::string set_topology(int host_cpu, const std::vector& worker_cpu : derive(allowed, host_cpu, worker_cpus); s.plan = plan; s.workers = worker_cpus; + s.host_cpu = host_cpu; CPU_ZERO(&s.target); for (int c : plan) CPU_SET(c, &s.target); s.have_plan.store(!plan.empty(), std::memory_order_release); @@ -353,6 +415,8 @@ inline void pin_current_thread() {} inline int restore() { return 0; } inline void set_enabled(bool) {} inline bool enabled() { return false; } +inline bool place_off_host() { return false; } // (a new thread does not inherit the host's CPU set here) +inline int release_host_inheritors() { return 0; } inline std::vector plan() { return {}; } inline std::string set_topology(int, const std::vector&) { return "strata aux cpus: not available on this system"; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a54192ae..d96ca97f 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -11684,6 +11684,56 @@ int main(int argc, char** argv) { 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"); + // where the read's thread and the doorbell thread run: on Linux a thread inherits its creator's + // CPUs, and the host thread is pinned to the one core the pool leaves it, so both would share that + // core with the host thread that pumps the windows - every window then waits its turn there for + // the doorbell of each layer (4x RTX 5080, 4 stages: 6 rows/s during a read). They move off the + // host's core and the pool workers' CPUs instead (--aux-cpus places them, when it is on). + // STRATA_PIPED_CONCURRENT_UNPIN=0 keeps the inherited CPUs (an A/B); STRATA_TEST_CONC_ON_HOST_CPU=1 + // (Windows, a test) puts them on the host thread's CPUs first, as Linux does. + static const bool conc_unpin = [] { + const char* v = std::getenv("STRATA_PIPED_CONCURRENT_UNPIN"); + return v == nullptr || std::atoi(v) != 0; + }(); +#if defined(_WIN32) + static const bool conc_on_host = std::getenv("STRATA_TEST_CONC_ON_HOST_CPU") != nullptr; + std::vector host_cpu_sets; + if (conc_on_host) { + const HANDLE self = GetCurrentThread(); + ULONG count = 0; + if (GetThreadSelectedCpuSets(self, nullptr, 0, &count) || + GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + host_cpu_sets.resize(count); + if (count && !GetThreadSelectedCpuSets(self, host_cpu_sets.data(), count, &count)) + host_cpu_sets.clear(); + } + static bool said = false; + if (!said) { + said = true; + std::fprintf(stderr, "strata batch: test: the read's and the doorbell threads start on the " + "host thread's %zu CPU set(s)%s\n", host_cpu_sets.size(), + conc_unpin ? ", then leave them (the fix)" + : " and stay there (as on Linux)"); + } + } +#endif + // the threads that already inherited the host's core (the prompt path's copy threads, started by + // the first prompt on the host thread) work during the read too: off that core as well (Linux) + if (conc_unpin && !strata::aux_cpus::enabled()) + if (const int moved = strata::aux_cpus::release_host_inheritors(); moved > 0) + std::fprintf(stderr, "strata batch: %d threads that ran on the host thread's core moved off " + "it, for reads beside the slots\n", moved); + auto conc_thread_cpus = [&] { + strata::aux_cpus::pin_current_thread(); +#if defined(_WIN32) + const HANDLE self = GetCurrentThread(); + if (conc_on_host && !host_cpu_sets.empty()) + SetThreadSelectedCpuSets(self, host_cpu_sets.data(), (ULONG) host_cpu_sets.size()); + if (conc_unpin && conc_on_host) SetThreadSelectedCpuSets(self, nullptr, 0); +#else + if (conc_unpin && !strata::aux_cpus::enabled()) (void) strata::aux_cpus::place_off_host(); +#endif + }; // 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 @@ -11710,7 +11760,7 @@ int main(int argc, char** argv) { bell_cv.notify_one(); }; bells.th = std::thread([&] { - strata::aux_cpus::pin_current_thread(); + conc_thread_cpus(); auto any_busy = [&] { for (int k = 0; k < n_pipe; ++k) if (stage_verifier(k).batch_busy()) return true; @@ -11762,7 +11812,7 @@ int main(int argc, char** argv) { 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(); + conc_thread_cpus(); 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) { From 5d6bf8d414c8fe3a62df37628942311a1bf26db3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 11:58:14 +0200 Subject: [PATCH 08/14] batch-groups: decode and give way between the pieces of a prompt read (#2050, opt-in STRATA_PIPED_READ_PIECE), on top of #2326's concurrent read Squash of SuperDistance's three commits of PR #2050 (decode between the pieces of a read on the pipelined groups, the piece lines counting the rows the slots decoded meanwhile, the stall watchdog staying on for a read in pieces), applied after #2326 here: the BYIELD give-way is #2326's give_way lambda, the concurrent block runs first and the piece path serves a read that STRATA_PIPED_CONCURRENT leaves to it (pictures, configurations where it is off). Co-authored-by: SuperDistance <43229543+SuperDistance@users.noreply.github.com> --- docs/BATCHING.md | 70 ++++++++++++++++++++- include/strata/program/batch_read.hpp | 31 ++++++++++ src/program/generate.cpp | 89 ++++++++++++++++++++++++++- tests/program/batch_read_test.cpp | 26 ++++++++ 4 files changed, 214 insertions(+), 2 deletions(-) diff --git a/docs/BATCHING.md b/docs/BATCHING.md index ee41b69c..63423864 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -237,6 +237,74 @@ at its first chunk (`YIELDED 2 2048`), E admitted meanwhile, D going on and A go which main does not do on this path (D never gives way there); the third run had B off at token 74, a near tie that flips on main as well. Greedy only; other GPU pairs, three or more stages and sampled decoding not measured. +## A prompt read beside pipelined groups (opt-in) + +With a layer split and `--batch-groups` above 1 a prompt is read in one run: every decoding slot stops until it is read, +however long it is, `STRATA_BATCH_DECODE_SHARE` does not apply and no `BYIELD` is taken (`batch_read_piece` returns 0 +for the pipelined groups; #1906). One GPU does not have this problem: there the slots decode between the prompt's chunks +for `STRATA_BATCH_DECODE_SHARE` x the chunk's time. These variables give the pipelined groups the same choice: + +- `STRATA_PIPED_READ_PIECE=N`: a prompt read on the pipelined groups goes in pieces of N tokens, rounded down to whole + chunks (at least one, at most 32), so a piece reads exactly the chunks a single run would, the two stages stay + overlapped inside it and only the piece's end drains the pipeline. Between two pieces the slot groups decode through + the pipeline for `STRATA_BATCH_DECODE_SHARE` x the piece's time, at most `STRATA_PIPED_DECODE_MAX_MS` and at least + `STRATA_PIPED_DECODE_MIN_MS`, and every group in flight finishes before the next piece, as before any prompt read. +- At a piece's end the pipeline is drained, so a waiting request with a prompt under half as long can take over there + (`BYIELD`, as between the chunks of a read off the pipeline): the part read waits in a slot and the read goes on from + it after the short request is in. The pieces are also taken when no slot decodes, for this reason (off the pipeline + the same read goes in `STRATA_BATCH_YIELD_CHUNKS` pieces then). +- A read that starts within a second (plus the decode budget) of the previous such read's end - prompts arriving back to + back - first gives the slots one decode budget (the same rule, from the previous read's last full piece); otherwise + the slots would stop for both reads. + +With the variables unset the read is one run as before. One log line per piece (`strata batch: piped read N tokens in X +ms (to Q of T)`, with `, then the slots decoded R rows in Y ms` when slots decode), per give-way (`the prompt read gives +way at Q of T tokens; slot S holds it`) and per lead-in (`a read right after a read: the slots decoded R rows in Y ms +first`). + +**What it trades.** Every piece ends by draining the pipeline, so a long read takes longer - also on an idle server, +since the pieces are what lets a short request in - and the decoding streams get tokens where they had none. It is a +latency choice, not a throughput gain: leave it off where throughput or the long prompt's own TTFT matters most, use it +where a stream that stops for several seconds, or a short question stuck behind a long read, is worse than a long prompt +that waits a little longer. + +Measured on 2x RTX 5090 (Swift 1.5 IQ3_S, `--layer-split 25 --trim-stage-weights --batch 6 --batch-groups 2 +--resident-experts`, k8v4 KV, 262K context, `--kv-resident 32768`, `STRATA_ARENA_PIN_GIB=24`, Windows 11; a CUDA 13.0 +sm_120 build of this change on 0.1.43, "release" = 0.1.43 built the same way; a fresh engine for every run, all from one +window, `tools/piped_read_join_bench.py`). Four streams decode greedy coding answers (thinking off, up to 2048 tokens) +when cold prompts of this repository's own source text join. "Longest stop": the longest time any stream received no +token, from the first prompt's arrival to the last one's first token + 1 s (client-side, SSE); "stream tokens": what the +four streams received in that window; "token rate": the streams' tokens over the run's wall time. + +Two cold prompts, 64K then 32K, arriving 6 s apart (`--scenarios two_joiners`; release and 32K pieces: median of 5 runs +each, interleaved; 16K pieces: one run): + +| arm | prompts' TTFT | longest stop of a stream | stream tokens | token rate | +| --- | ---: | ---: | ---: | ---: | +| release (one run per prompt) | 6.9 s / 6.1 s | 12.2 s | 289 | 173 tok/s | +| `PIECE=32768 DECODE_MAX_MS=400` | 8.1 s / 8.5 s | 4.2 s | 527 | 166 tok/s | +| `PIECE=16384 DECODE_MAX_MS=400` | 10.5 s / 12.0 s | 2.6 s | 793 | 154 tok/s | + +The longest stop was 12.16-12.23 s for the release in all five runs and 4.19-4.22 s for 32K pieces in four; in the fifth +the first 32K piece of the 64K prompt took 9.3 s instead of 3.95 s (one uninterrupted run before any slot decoded), +which made that run's stop 9.5 s. The token rate varied 169-180 tok/s (release) and 136-174 tok/s (32K) between runs. + +A short request behind a long read, nothing decoding (#1504's test, `--scenarios followup,read_alone --repeat 3`, median +of 3): a one-line question sent 1 s after a cold 45K prompt, and the same 45K prompt read alone: + +| arm | the question's TTFT | the 45K prompt's TTFT | the 45K prompt alone | +| --- | ---: | ---: | ---: | +| release | 5.4 s | 6.0 s | 5.7 s | +| `PIECE=32768 DECODE_MAX_MS=400` | 3.6 s | 7.3 s | 6.4 s | +| `PIECE=16384 DECODE_MAX_MS=400` | 1.8 s | 8.0 s | 7.1 s | + +With the variables unset this change ran as the release in the same window (the 45K read alone 5.66 vs 5.69 s, the two +joiners' longest stop 12.2 s on both) and gave the same SHA-256 for six greedy answers under `--prompt-cache 0 +--adapt-swaps 0 --pcie-frac 0`. For reference, one RTX 5090 (the same model and flags without the split, 6 slots) with +one cold 64K prompt joining four streams: `STRATA_BATCH_DECODE_SHARE=2.0` 2.4 s longest stop and 37.2 s TTFT, `=0` 14.0 +s and 13.8 s. Pieces of one chunk (`PIECE=8192`) cost the long prompt the most. Not measured: other GPU pairs, three or +more stages, HIP and SYCL (built for CUDA only), sampled decoding, prompts with pictures. + ## The VRAM expert tier keeps adapting in batch windows Batch windows count which experts they route to, and every `--adapt-every` windows (default 4) the engine swaps the @@ -405,7 +473,7 @@ tests the server's side with a scripted engine (no GPU). | Script | What it checks | | --- | --- | | `tools/batch_test.py` | the same prompts alone (`GEN`) and together in the batch slots (`BGEN`): every slot's greedy tokens equal its solo tokens; prints the aggregate rate. `--batch-groups` in `--extra` tests the pipeline, `--keys "temperature=0.7"` the sampled rows. | -| `tools/batch_interleave_test.py` | a long prompt read while two slots decode, a prompt that gives way (`BYIELD`) and goes on, and a next turn continued from its slot: each equal to its solo tokens. | +| `tools/batch_interleave_test.py` | a long prompt read while two slots decode, a prompt that gives way (`BYIELD`) and goes on, and a next turn continued from its slot: each equal to its solo tokens. On a two-stage layer split with pipelined groups add `--batch 4 --batch-groups 2` to `--extra` (its 3 slots do not divide into two groups) and set `STRATA_PIPED_READ_PIECE`; run it without a conversation cache, or step 4 restores the prompt instead of reading it. | | `tools/parking_test.py` | a follow-up to a conversation decodes the same tokens whether its state stayed live or came back from the parking cache (with a layer split: every stage's image). | | `tools/early_close_test.py` | a client that stops reading a streamed answer early (alone, and with a second request running) does not leave its tokens to the next request (server). | diff --git a/include/strata/program/batch_read.hpp b/include/strata/program/batch_read.hpp index 536e1cc3..65cd6a08 100644 --- a/include/strata/program/batch_read.hpp +++ b/include/strata/program/batch_read.hpp @@ -53,4 +53,35 @@ inline const char* concurrent_read_off(const ConcurrentReadSetup& s) { return nullptr; } +/// Tokens of the next piece of a prompt read on the pipelined slot groups (--batch-groups > 1 on a layer split, #1906), +/// or 0 for "the whole rest in one run" (the opt-in is off). +/// piece_tokens: STRATA_PIPED_READ_PIECE, rounded down to whole chunks (at least one, at most kPipedMaxChunks) +/// A piece is one pipelined run over its chunks, so the stages stay overlapped inside it and only its end drains the +/// pipeline. At a piece's end the decoding slots decode, and a waiting shorter request can take over (BYIELD), as +/// between the pieces of a read off the pipeline. +inline constexpr int64_t kPipedMaxChunks = 32; +inline int64_t piped_read_piece(int64_t piece_tokens, int64_t chunk) { + if (piece_tokens <= 0) return 0; + chunk = std::max(chunk, 1); + return std::clamp(piece_tokens / chunk, 1, kPipedMaxChunks) * chunk; +} + +/// The slots' decode time between two pieces: share x the piece's time (STRATA_BATCH_DECODE_SHARE, the rule the +/// one-GPU path uses between chunks), at most cap_ms (STRATA_PIPED_DECODE_MAX_MS; <= 0: no cap), at least floor_ms +/// (STRATA_PIPED_DECODE_MIN_MS). +inline double piped_decode_budget_ms(double piece_ms, double share, double cap_ms, double floor_ms) { + double b = std::max(0.0, share) * std::max(0.0, piece_ms); + if (cap_ms > 0.0) b = std::min(b, cap_ms); + return std::max(b, std::max(0.0, floor_ms)); +} + +/// Prompts arriving back to back: a piecewise read that starts within kPipedLeadInWindowMs + budget_ms of the +/// previous piecewise read's end first gives the slots one decode budget (otherwise they stop for both reads). +/// ms_since_prev_end: < 0 when there was no piecewise read yet +inline constexpr double kPipedLeadInWindowMs = 1000.0; +inline bool piped_read_lead_in(bool enabled, bool beside_slots, double ms_since_prev_end, double budget_ms) { + return enabled && beside_slots && ms_since_prev_end >= 0.0 && + ms_since_prev_end <= kPipedLeadInWindowMs + std::max(0.0, budget_ms); +} + } // namespace strata::program diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d96ca97f..f8b6de29 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -11898,12 +11898,79 @@ int main(int argc, char** argv) { } return true; } - const int64_t piece = strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, yield_chunks); + // Opt-in (#1906): on the pipelined slot groups a read goes in pieces of STRATA_PIPED_READ_PIECE tokens + // (whole chunks). A piece's end has the pipeline drained, so a waiting shorter request can take + // over there (BYIELD); with slots decoding, the groups then decode through the pipeline (pump) for + // STRATA_BATCH_DECODE_SHARE x the piece's time, capped / floored by STRATA_PIPED_DECODE_MAX_MS / + // _MIN_MS, and are drained (pipe_drain) before the next piece, as before any read. Unset: one run. + static const int64_t pr_piece = [] { + const char* v = std::getenv("STRATA_PIPED_READ_PIECE"); + return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 0; + }(); + static const double pr_cap = [] { + const char* v = std::getenv("STRATA_PIPED_DECODE_MAX_MS"); + return v != nullptr ? std::max(0.0, std::atof(v)) : 0.0; + }(); + static const double pr_floor = [] { + const char* v = std::getenv("STRATA_PIPED_DECODE_MIN_MS"); + return v != nullptr ? std::max(0.0, std::atof(v)) : 0.0; + }(); + const bool pr_on = piped && pr_piece > 0; + auto piece_now = [&]() -> int64_t { + return pr_on ? strata::program::piped_read_piece(pr_piece, C) + : strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, + yield_chunks); + }; + // the slots decode through the pipeline for budget_ms, drained before the next read + auto piped_decode = [&](double budget_ms, std::string& err) -> bool { + const auto td = Clock::now(); + in_prompt_read = true; + do { + if (!pump(true)) { + in_prompt_read = false; batch_fatal = true; err = "a pipelined batch window failed"; + return false; + } + } while (batch_on() && + std::chrono::duration(Clock::now() - td).count() < budget_ms); + if (!pipe_drain()) { + in_prompt_read = false; batch_fatal = true; err = "a pipelined batch window failed"; + return false; + } + in_prompt_read = false; + ++il_parts; + il_ms += std::chrono::duration(Clock::now() - td).count(); + return true; + }; + // prompts arriving back to back: one decode budget before a read that follows a piecewise read + static Clock::time_point pr_prev_end{}; + static bool pr_have_prev = false; + static double pr_prev_piece_ms = 0.0; // the previous read's last full piece + if (pr_on) { + const double lead = + pr_prev_piece_ms > 0.0 + ? strata::program::piped_decode_budget_ms(pr_prev_piece_ms, decode_share, pr_cap, pr_floor) + : (pr_cap > 0.0 ? pr_cap : std::max(pr_floor, 200.0)); + const double since = + pr_have_prev ? std::chrono::duration(Clock::now() - pr_prev_end).count() + : -1.0; + if (strata::program::piped_read_lead_in(true, batch_on(), since, lead)) { + const int64_t rows0 = pipe_rows; + const auto tl = Clock::now(); + if (!piped_decode(lead, e)) return false; + std::fprintf(stderr, "strata batch: a read right after a read: the slots decoded %lld rows in " + "%.0f ms first\n", (long long) (pipe_rows - rows0), + std::chrono::duration(Clock::now() - tl).count()); + } + } + int64_t piece = piece_now(); if (piece <= 0) return sp.run(ids.data() + a0, b0 - a0, a0, e); for (int64_t q = a0; q < b0;) { const int64_t r = std::min(b0, q + piece); const auto tq = Clock::now(); if (!sp.run(ids.data() + q, r - q, q, e)) return false; + const double piece_ms = std::chrono::duration(Clock::now() - tq).count(); + if (pr_on && r < b0) pr_prev_piece_ms = piece_ms; + const int64_t piece_tokens = r - q; q = r; if (q >= b0) continue; int ys = -1; @@ -11923,6 +11990,25 @@ int main(int argc, char** argv) { } } if (ys >= 0 && give_way(ys, q, e)) return false; + // (on the pipelined path a piece's end has the pipeline drained - nothing runs during a piece and + // every decode budget ends in pipe_drain - so the part read can give way there as off the pipeline) + if (pr_on) { // the pipelined pieces: the slots decode through the pipeline, then it is drained + if (!batch_on()) { + std::fprintf(stderr, "strata batch: piped read %lld tokens in %.0f ms (to %lld of %lld)\n", + (long long) piece_tokens, piece_ms, (long long) q, (long long) n); + continue; + } + const double budget = + strata::program::piped_decode_budget_ms(piece_ms, decode_share, pr_cap, pr_floor); + const int64_t rows0 = pipe_rows; + const auto td = Clock::now(); + if (!piped_decode(budget, e)) return false; + std::fprintf(stderr, "strata batch: piped read %lld tokens in %.0f ms (to %lld of %lld), " + "then the slots decoded %lld rows in %.0f ms\n", (long long) piece_tokens, + piece_ms, (long long) q, (long long) n, (long long) (pipe_rows - rows0), + std::chrono::duration(Clock::now() - td).count()); + continue; + } if (decode_share <= 0.0 || !batch_on()) continue; const double budget = decode_share * std::chrono::duration(Clock::now() - tq).count(); const auto td = Clock::now(); @@ -11939,6 +12025,7 @@ int main(int argc, char** argv) { std::fflush(stderr); } } + if (pr_on) { pr_prev_end = Clock::now(); pr_have_prev = true; } // for the next read's lead-in return true; }; apply_pending(true); diff --git a/tests/program/batch_read_test.cpp b/tests/program/batch_read_test.cpp index d22cf2e8..017065ef 100644 --- a/tests/program/batch_read_test.cpp +++ b/tests/program/batch_read_test.cpp @@ -8,6 +8,9 @@ using strata::program::batch_read_piece; using strata::program::concurrent_read_off; using strata::program::ConcurrentReadSetup; +using strata::program::piped_decode_budget_ms; +using strata::program::piped_read_lead_in; +using strata::program::piped_read_piece; static int fails = 0; #define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++fails; } } while (0) @@ -54,6 +57,29 @@ int main() { for (size_t j = i; j < std::size(each); ++j) s.*each[j] = true; CHECK(same(concurrent_read_off(s), named[i])); } + // piped_read_piece (#1906): off -> one run; whole chunks, at least one, at most 32 + CHECK(piped_read_piece(0, 8192) == 0); + CHECK(piped_read_piece(-5, 8192) == 0); + CHECK(piped_read_piece(32768, 8192) == 32768); + CHECK(piped_read_piece(20000, 8192) == 16384); // rounded down to whole chunks + CHECK(piped_read_piece(4096, 8192) == 8192); // never below one chunk + CHECK(piped_read_piece(1 << 30, 8192) == 32 * 8192); + CHECK(piped_read_piece(5000, 0) == 32); // chunk 0 guarded as 1 (and the cap applies) + for (int64_t c : {1024, 2048, 6144, 8192}) + for (int64_t p : {1, 1000, 9000, 50000, 300000}) CHECK(piped_read_piece(p, c) % c == 0); // the header's rule + // piped_decode_budget_ms: share x piece, capped, floored; negatives are 0 + CHECK(piped_decode_budget_ms(2000.0, 2.0, 400.0, 0.0) == 400.0); + CHECK(piped_decode_budget_ms(2000.0, 0.35, 3000.0, 0.0) == 700.0); + CHECK(piped_decode_budget_ms(2000.0, 0.0, 400.0, 150.0) == 150.0); + CHECK(piped_decode_budget_ms(2000.0, 2.0, 0.0, 0.0) == 4000.0); // no cap + CHECK(piped_decode_budget_ms(-5.0, -1.0, 400.0, -3.0) == 0.0); + // piped_read_lead_in: on, beside decoding slots, within 1000 ms + the budget of the previous piecewise read's end + CHECK(piped_read_lead_in(true, true, 0.0, 400.0)); + CHECK(piped_read_lead_in(true, true, 1400.0, 400.0)); + CHECK(!piped_read_lead_in(true, true, 1401.0, 400.0)); + CHECK(!piped_read_lead_in(true, true, -1.0, 400.0)); + CHECK(!piped_read_lead_in(false, true, 0.0, 400.0)); + CHECK(!piped_read_lead_in(true, false, 0.0, 400.0)); if (fails == 0) std::printf("batch_read_test: ok\n"); return fails == 0 ? 0 : 1; } From 56146c4c4906721d9a946707c3ca21b3da4b8f53 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 11:51:37 +0200 Subject: [PATCH 09/14] layer split: overlap the stages' hand-off (STRATA_SPLIT_OVERLAP=1, opt-in) Each verify window of a layer split runs its stages strictly in turn: stage 1 finishes, the host syncs its stream, then stages and launches stage 2's graph. Under HIP the sync and the graph launch both sit on the critical path of every window. With STRATA_SPLIT_OVERLAP=1 the hand-off carries a ready word (mapped, one per hand-off buffer): - the writing stage's graph ends with handoff_publish: the payload with volatile stores (RDNA keeps plain stores to mapped memory in L2), a system fence per thread, and the last block raises the flag; - the reading stage's graph starts with wait_flag_ge(flag, 1); - Verifier::run captures the next stage's window on this thread, then stages and launches it on a helper thread (prelaunch) while this thread serves its own layers; it then serves the next stage's layers directly and syncs the earlier stage once the chain is done; - release_gpu_waits also raises the hand-in flag; an early return after the prelaunch releases the next stage. Batch windows and --split-device 0 keep the serial order. Off by default. Measured on 2x RX 7900 XTX (ROCm, Linux), Swift 1.5 IQ3_XXS, 512-token greedy answers, median of 8: decode 53 -> 70.1 tok/s (code prompt), 45 -> 55.9 tok/s (prose prompt); greedy output byte-identical with the flag at 0 and 1; quiz 47/51 both ways. Not measured on NVIDIA. Split-overlap launch merged with 0.1.44 HostGraphLaunch (STRATA_VERIFY_ASYNC_LAUNCH): the launcher object is kept in an optional so an early-launched window has none. Co-authored-by: bsvinay --- docs/MULTI_GPU.md | 21 +++ include/strata/core/verify.hpp | 18 +++ include/strata/kernels/verify_kernels.hpp | 7 + src/core/verify.cpp | 164 ++++++++++++++++++---- src/kernels/cuda/verify_kernels.cu | 33 +++++ src/program/generate.cpp | 25 +++- 6 files changed, 237 insertions(+), 31 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 62a8a177..640d60ed 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -199,6 +199,27 @@ that overlap instead of one, a 32K one four instead of two. Same tokens; 2x / 3x 32K +18% / +21% / +29%, 64K +4% / +12% / +17%, 8K unchanged. `STRATA_SPLIT_CHUNK16K=1` keeps 16384.) Conversation checkpoints save and restore every card's state; the adaptive expert swaps copy into the card that owns the layer. +## Overlapped hand-off (`STRATA_SPLIT_OVERLAP=1`, opt-in) + +By default each verify window runs the stages one after another: the host syncs stage 1, then stages and launches +stage 2's graph, and so on. `STRATA_SPLIT_OVERLAP=1` (stages on different cards only) gives the hand-off a ready +flag: the earlier stage's GPU writes the hand-off with volatile stores and raises the flag (`handoff_publish`), the +next stage's graph is staged and launched on a helper thread while the earlier stage is still running and waits for +the flag on its GPU (`wait_flag_ge`), and the host goes straight from serving one stage's layers to the next, syncing +the earlier stage only once the chain is done. It takes one stream sync and one graph launch per window off the +critical path. Batch windows (several conversations) keep the serial order. + +Measured on 2x RX 7900 XTX (gfx1100, ROCm, Linux), Ryzen 9 9900X, 52 GB RAM, Swift 1.5 IQ3_XXS, 128K context, 8-bit +KV, layers 0-25 / 26-47; 512-token greedy answers, median of 8 runs: + +| | serial (default) | `STRATA_SPLIT_OVERLAP=1` | one card | +|---|---|---|---| +| decode, code prompt | 53 tok/s | 70.1 tok/s | ~70 tok/s | +| decode, prose prompt | 45 tok/s | 55.9 tok/s | ~68 tok/s | + +Greedy output is byte-identical with the flag at 0 and 1; the quiz set scored the same (47/51). Not measured on +NVIDIA yet, where a sync and a graph launch cost less. + ## Limits (for now) - **Works across cards** (bench/results/2026-09-29-layer-split-limits): diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 2539a33a..313ea4a7 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -170,6 +170,14 @@ public: void set_stage(int64_t layer_begin, int64_t layer_end, const float* handoff_in, float* handoff_out) { lb_ = layer_begin; le_ = layer_end; hand_in_ = handoff_in; hand_out_ = handoff_out; } + /// STRATA_SPLIT_OVERLAP=1 (opt-in; stages on DIFFERENT devices only): the hand-off carries a ready flag (one + /// mapped word per hand-off buffer: host and device addresses). The writing stage raises it from the GPU when + /// its hand-off is out (handoff_publish); the reading stage's window graph waits on it (wait_flag_ge) - so the + /// next stage's graph is launched while this stage is still running, and the host no longer syncs between the + /// stages. Null (the default): the old order - sync, then launch the next stage. Set before `init`. + void set_handoff_flags(uint32_t* in_host, uint32_t* in_dev, uint32_t* out_host, uint32_t* out_dev) { + hflag_in_h_ = in_host; hflag_in_d_ = in_dev; hflag_out_h_ = out_host; hflag_out_d_ = out_dev; + } /// The next stage: `run` and `commit` continue into it (its pool calls get `next_user`); sampling settings /// and `final_R` are the last stage's. void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; } @@ -433,6 +441,16 @@ private: int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last) const float* hand_in_ = nullptr; float* hand_out_ = nullptr; + uint32_t* hflag_in_h_ = nullptr; ///< set_handoff_flags: the incoming hand-off's ready word (host / device) + uint32_t* hflag_in_d_ = nullptr; + uint32_t* hflag_out_h_ = nullptr; ///< ... and the outgoing one's + uint32_t* hflag_out_d_ = nullptr; + uint32_t* hcount_d_ = nullptr; ///< handoff_publish's block counter (device memory) + int prelaunched_ = 0; ///< prelaunch ran for a window of this size: run skips staging + launch + /// The overlapped split: stage this window's inputs and launch its graph now (the graph waits on the hand-off + /// flag); `run` then only serves the host side. Called on a helper thread while the previous stage runs. + bool prelaunch(int T, const int32_t* tokens, int64_t pos0, std::string& err); + bool chain_overlap() const; ///< this stage hands off through a flag to a next stage that waits on it Verifier* next_ = nullptr; void* next_user_ = nullptr; bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 6f54e0bb..9669f53f 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -74,6 +74,13 @@ void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream); /// kernel costs ~2.4 us on a gfx1201 graph whatever it does. n <= 128 * k for any k (a strided loop). void wait_copy_i32_from_mapped(const uint32_t* flag, uint32_t value, int32_t* dst, const int32_t* src, int64_t n, void* stream); + +/// Layer split, overlapped hand-off (STRATA_SPLIT_OVERLAP): dst (mapped) = [a (na) | b (nb) | c (nc)] with volatile +/// stores, then the LAST block to finish raises *flag = 1 (mapped) after a system fence, so the next stage's GPU can +/// start (wait_flag_ge(flag, 1)) without the host syncing this stage first. `counter` is one device word, 0 between +/// calls (the last block resets it). Volatile because on RDNA a plain store to mapped memory can sit in the L2. +void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc, + uint32_t* counter, uint32_t* flag, void* stream); /// the GPU's %globaltimer (ns) into buf[i] (a one-thread kernel: the verify window's stage profiler). Inside a PDL /// stretch (pdl.hpp) the stamp passes the early launch on, so a profiled window keeps the chain it measures. void gpu_stamp(unsigned long long* buf, int i, void* stream); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 9fe22ecf..ed2a37f9 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -396,7 +397,7 @@ bool Verifier::release_gpu_waits(int timeout_ms) { // the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here // reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but // wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises. - for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_}) + for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_, hflag_in_h_}) // + an overlapped split's hand-off wait if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX; std::atomic_thread_fence(std::memory_order_seq_cst); _mm_sfence(); @@ -529,6 +530,7 @@ Verifier::~Verifier() { for (cudaEvent_t e : df_join_) if (e) cudaEventDestroy(e); if (arena_) cudaFree(arena_); + if (hcount_d_) cudaFree(hcount_d_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_}; for (void* h : hosts) @@ -713,6 +715,10 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& return false; } cudaMemset(arena_, 0, count.used); + if (hflag_out_d_ != nullptr && hcount_d_ == nullptr) { // the overlapped split's hand-off counter + if (cudaMalloc((void**) &hcount_d_, 64) != cudaSuccess) { err = "verify: hand-off counter allocation failed"; return false; } + cudaMemset(hcount_d_, 0, 64); + } if (g_trace && trace_h_ == nullptr) { // #649: the breadcrumbs, mapped so they read while the GPU hangs trace_n_ = (size_t) (g.n_layers + 1) * kProfPer * 2; if (!mapped(trace_n_ * 8, (void**) &trace_h_, (void**) &trace_m_)) { @@ -957,6 +963,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const int64_t HB = Verifier::handoff_floats(g); if (lb_ > 0) { const float* hin = hand_in_ + (size_t) hrow0 * HB; // the group's rows: [R][bo][inj] contiguous + // the overlapped split: this graph was launched before the previous stage finished - wait for its hand-off + if (hflag_in_d_ != nullptr && !batch_rec_) wait_flag_ge(hflag_in_d_, 1u, cs); copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs); copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs); copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs); @@ -1795,6 +1803,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } if (le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head float* hout = hand_out_ + (size_t) hrow0 * HB; + if (hflag_out_d_ != nullptr && !batch_rec_) { // the overlapped split: payload + the next stage's flag + handoff_publish(hout, R_, (int64_t) T * HC * N, bo_, (int64_t) T * N, inj2_, (int64_t) T * HC, hcount_d_, + hflag_out_d_, cs); + return true; + } copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs); copy_from_mapped(hout + (size_t) T * HC * N, bo_, (int64_t) T * N, cs); copy_from_mapped(hout + (size_t) T * (HC + 1) * N, inj2_, (int64_t) T * HC, cs); @@ -2225,7 +2238,10 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) { *(volatile uint32_t*) h_flag_ = 0; *(volatile uint32_t*) h_flagA_ = 0; *(volatile uint32_t*) h_flagB_ = 0; + // the overlapped split: the next stage's graph is launched after this, and must see THIS window's raise + if (hflag_out_h_ != nullptr) *(volatile uint32_t*) hflag_out_h_ = 0; std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); last_t_ = T; last_pos0_ = pos0; for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t]; @@ -2298,6 +2314,36 @@ bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) { return true; } +bool Verifier::chain_overlap() const { + return next_ != nullptr && hflag_out_h_ != nullptr && hflag_out_d_ != nullptr && hcount_d_ != nullptr && + next_->hflag_in_h_ == hflag_out_h_ && next_->device_ != device_ && !next_->ple_stage(); +} + +bool Verifier::prelaunch(int T, const int32_t* tokens, int64_t pos0, std::string& err) { + const OnDevice on_device(device_); + prelaunched_ = 0; + cudaGraphExec_t exec_t = ar_off_ ? exec_nr_[T] : exec_[T]; // #871: the variant the previous stage refreshed + if (T < 1 || T > max_t_ || exec_t == nullptr) { err = "verify: prelaunch before the window was captured"; return false; } + if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } + if (pos0 + T > ss_->qsa_states[ss_->qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } + const Clock::time_point t0 = Clock::now(); + stage_inputs(T, tokens, pos0); + if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); + std::atomic_thread_fence(std::memory_order_seq_cst); + trace_ev("WINDOW-PRE", -1, -1, pos0 * 16 + T); + ms_host += ms_since(t0); + if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; + // 0.1.43: the same gate run() applies before it launches (the adaptive tier's copies land first) + if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() && + !adapt_gate_wait((int32_t) g_->n_layers, err)) return false; + 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; } + (void) cudaStreamQuery(cs_); + prelaunched_ = T; + return true; +} + bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err) { #if defined(STRATA_GPU_METAL) @@ -2313,11 +2359,21 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const ModelGeometry& g = *g_; SessionState& ss = *ss_; if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } - refresh_ar(); + // the overlapped split launched this stage's window already: keep the graph variant (#871) chosen for it then, + // or this thread would serve the window as the other variant + const bool pre = prelaunched_ == T; + prelaunched_ = 0; + if (!pre) refresh_ar(); if (!capture(T, err) || !capture_commit(err)) return false; + const bool chain = chain_overlap(); + if (chain) { // capture the next stage's window here, on this thread, so the helper only stages and launches + const OnDevice on_next(next_->device_); + next_->refresh_ar(); // #871: the variant its prelaunch and its run() will both use + if (!next_->capture(T, err) || !next_->capture_commit(err)) return false; + } VDBG("captured; staging\n"); const Clock::time_point t0 = Clock::now(); - if (!staged_) stage_inputs(T, tokens, pos0); + if (!pre && !staged_) stage_inputs(T, tokens, pos0); staged_ = false; const bool do_ple = ss.ple.ready() && ple_stage(); uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS]; @@ -2330,35 +2386,64 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, ss.ple.table->prefetch_rows(ple_rows + t * PLE_N_HEADS); } } - 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", -1, -1, pos0 * 16 + T); - ms_host += ms_since(t0); - VDBG("staged; launching\n"); - if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; - // 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first - if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() && - !adapt_gate_wait((int32_t) g.n_layers, err)) return false; #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) - // A blocking instrumented launch cannot also serve the graph's CPU doorbells. - static const bool threaded_launch = [] { - const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH"); - return value != nullptr && value[0] == '1'; - }(); - HostGraphLaunch launch(ar_off_ ? exec_nr_[T] : exec_[T], cs_, device_, threaded_launch, - [this] { (void) release_gpu_waits(5000); }); - const cudaError_t le = launch.status(); -#else - const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_); + std::optional launch_o; // (not set when the previous stage launched this window already) #endif - trace_ev("LAUNCHED", -1, -1, (int64_t) le); - if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } + if (!pre) { + 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", -1, -1, pos0 * 16 + T); + ms_host += ms_since(t0); + VDBG("staged; launching\n"); + if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; + // 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first + if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() && + !adapt_gate_wait((int32_t) g.n_layers, err)) return false; #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) - (void) launch.query(); + // A blocking instrumented launch cannot also serve the graph's CPU doorbells. + static const bool threaded_launch = [] { + const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH"); + return value != nullptr && value[0] == '1'; + }(); + launch_o.emplace(ar_off_ ? exec_nr_[T] : exec_[T], cs_, device_, threaded_launch, + [this] { (void) release_gpu_waits(5000); }); + const cudaError_t le = launch_o->status(); #else - (void) cudaStreamQuery(cs_); + const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_); #endif - VDBG("launched\n"); + trace_ev("LAUNCHED", -1, -1, (int64_t) le); + if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + (void) launch_o->query(); +#else + (void) cudaStreamQuery(cs_); +#endif + VDBG("launched\n"); + } + // The overlapped split: the next stage's window is staged and launched on a helper thread while this thread + // serves this stage's layers; its graph waits on the GPU for this stage's hand-off flag. The guard joins the + // helper on every return, and on an early return (an error after the launch) releases the next stage's GPU + // waits so no spin kernel outlives the window (#267). + struct NextLaunch { + Verifier* next = nullptr; + std::thread th; + bool ok = true; + bool handed = false; + std::string err; + bool join(std::string& e) { + if (th.joinable()) th.join(); + if (!ok) e = err; + return ok; + } + ~NextLaunch() { + if (th.joinable()) th.join(); + if (next != nullptr && !handed) (void) next->release_gpu_waits(5000); + } + } nl; + if (chain) { + nl.next = next_; + nl.th = std::thread([&nl, T, tokens, pos0] { nl.ok = nl.next->prelaunch(T, tokens, pos0, nl.err); }); + } volatile uint32_t* const seq = h_seq_; volatile uint32_t* const flag = h_flag_; const int G = groups_[T] > 0 ? groups_[T] : 1; @@ -2392,7 +2477,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, if (now - last_flush > std::chrono::microseconds(2000)) { last_flush = now; #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) - const cudaError_t q = launch.query(); + const cudaError_t q = launch_o ? launch_o->query() : cudaStreamQuery(cs_); #else const cudaError_t q = cudaStreamQuery(cs_); #endif @@ -2407,7 +2492,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, if (now - a > std::chrono::seconds(20)) { // #267: the caller ends the engine; no spin kernel may outlive it #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) - trace_ev("TIMEOUT", k, l, (int64_t) launch.query()); + trace_ev("TIMEOUT", k, l, (int64_t) (launch_o ? launch_o->query() : cudaStreamQuery(cs_))); #else trace_ev("TIMEOUT", k, l, (int64_t) cudaStreamQuery(cs_)); #endif @@ -2469,6 +2554,25 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, ms_pool += ms_since(b); } // (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own) + if (chain) { + // The overlapped split: no host sync between the stages. The next stage's GPU starts on this stage's flag; + // this thread goes straight to serving the next stage's layers, and syncs this stage once the chain is done. + if (!nl.join(err)) return false; + nl.handed = true; + ++windows; + const bool ok = next_->run(T, tokens, pos0, pool, next_user_, out, err); + const OnDevice back(device_); + const cudaError_t se = cudaStreamSynchronize(cs_); + if (copy_used_) { + cudaStreamSynchronize(copy_); + copy_used_ = false; + } + if (!ok) return false; + if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } + commit_pending_ = false; + if (prof_on_ && G == 1) collect_profile(); + return true; + } progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T); // #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall // watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no @@ -2476,7 +2580,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, // itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver // beside the expert workers). #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) - const cudaError_t launch_result = launch.finish(); + const cudaError_t launch_result = launch_o ? launch_o->finish() : cudaSuccess; if (launch_result != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(launch_result); return false; diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 420ddf5c..75c6f3d3 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -1156,8 +1156,41 @@ __global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t valu while (*flag < value) strata_spin_pause(); __threadfence_system(); } + +__global__ void handoff_publish_kernel(float* dst, const float* __restrict__ a, int64_t na, const float* __restrict__ b, + int64_t nb, const float* __restrict__ c, int64_t nc, uint32_t* counter, + uint32_t* flag) { + const int64_t n = na + nb + nc; + volatile float* const out = dst; + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) + out[i] = i < na ? a[i] : i < na + nb ? b[i - na] : c[i - na - nb]; + __threadfence_system(); // this thread's stores reach host memory before the block counts itself done + __syncthreads(); + if (threadIdx.x == 0) { + const uint32_t prev = atomicAdd(counter, 1u); + if (prev == gridDim.x - 1) { // every block's payload is out: raise the next stage's flag + *(volatile uint32_t*) counter = 0u; + __threadfence_system(); + *(volatile uint32_t*) flag = 1u; + __threadfence_system(); + } + } +} } // namespace +void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc, + uint32_t* counter, uint32_t* flag, void* stream) { + const int64_t n = na + nb + nc; + if (n <= 0 || dst == nullptr || counter == nullptr || flag == nullptr) { + std::fprintf(stderr, "handoff_publish: invalid arguments\n"); + std::exit(1); + } + const int64_t nb256 = (n + 255) / 256; + const int blocks = (int) (nb256 < 64 ? nb256 : 64); + handoff_publish_kernel<<>>(dst, a, na, b, nb, c, nc, counter, flag); + check("handoff_publish"); +} + namespace { // one thread per window entry: up to kVerifyMaxT tokens x 10 routed experts (80), so 128 (#646 had 64: a window of // 7+ tokens lost its last entries) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index f8b6de29..b64155f4 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -7833,11 +7833,33 @@ int main(int argc, char** argv) { } std::memset(hh, 0, hb); } + // STRATA_SPLIT_OVERLAP=1 (opt-in; measured on 2x RX 7900 XTX only): a ready word per hand-off, raised by the + // writing stage's GPU, so the next stage's window is launched early and the host never syncs between + // stages (Verifier::set_handoff_flags). Not for --split-device 0 (both stages on one GPU). + const bool overlap = !split_same && [] { + const char* v = std::getenv("STRATA_SPLIT_OVERLAP"); + return v != nullptr && std::atoi(v) != 0; + }(); + std::vector hflag_h((size_t) n_stages - 1, nullptr), hflag_d((size_t) n_stages - 1, nullptr); + if (overlap) + for (size_t i = 0; i < hflag_h.size(); ++i) { + if (cudaHostAlloc((void**) &hflag_h[i], 64, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || + cudaHostGetDevicePointer((void**) &hflag_d[i], hflag_h[i], 0) != cudaSuccess) { + std::fprintf(stderr, "strata serve: the layer-split hand-off flag allocation failed\n"); + return 1; + } + std::memset(hflag_h[i], 0, 64); + } split_drive.base = &drive; split_drive.n = n_stages; for (int st = 0; st < n_stages; ++st) { stage_ver(st).set_stage(st == 0 ? 0 : split_at[(size_t) st - 1], st + 1 < n_stages ? split_at[(size_t) st] : -1, st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr); + if (overlap) + stage_ver(st).set_handoff_flags(st == 0 ? nullptr : hflag_h[(size_t) st - 1], + st == 0 ? nullptr : hflag_d[(size_t) st - 1], + st + 1 < n_stages ? hflag_h[(size_t) st] : nullptr, + st + 1 < n_stages ? hflag_d[(size_t) st] : nullptr); split_drive.end[st] = st + 1 < n_stages ? split_at[(size_t) st] : g.n_layers; split_drive.cache_base[st] = drive.d.cache_base; split_drive.cache_slot_off[st] = drive.d.cache_slot_off; @@ -7877,7 +7899,8 @@ int main(int argc, char** argv) { for (int st = 1; st < n_stages; ++st) plan_s += ", " + std::to_string(split_at[(size_t) st - 1]) + "-" + std::to_string(split_drive.end[st] - 1) + " (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")"; - std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str()); + std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window%s\n", plan_s.c_str(), + overlap ? " (overlapped: STRATA_SPLIT_OVERLAP=1)" : ""); } // --pipeline-windows: the odd windows' verifiers and their hand-off (initialized before `ver`, which stays the // watchdog's verifier), and the drafter's own row buffer, which either parity's rows are copied into From 2443c9225c1a779b2b5a05ea4475cd5f6b9e15d3 Mon Sep 17 00:00:00 2001 From: bsvinay Date: Tue, 6 Oct 2026 08:21:45 +0530 Subject: [PATCH 10/14] layer split overlap: bound the GPU-side hand-off wait (STRATA_SPLIT_WAIT_MS) Review on #936 (justxiami): the reading stage's wait_flag_ge spun with no bound, so a lost publish would leave that stream spinning. - wait_handoff: the reading stage's graph now waits with a bound (default 30 s, STRATA_SPLIT_WAIT_MS, 0 = unbounded, GPU clock as in gpu_stamp). On timeout it sets a mapped error word and returns, so the graph completes; the host checks the word after the window and fails it with an error that names the setting, instead of using a stale hand-off. - The host's per-layer wait (20 s, #267) still normally ends a stalled window first; release_gpu_waits already raises the hand-in flag. - Test hook STRATA_TEST_HANDOFF_DROP=N: the first stage's N-th window withholds its flag (a lost publish), to exercise both paths. Only active with STRATA_SPLIT_OVERLAP=1; the default path is unchanged. --- docs/MULTI_GPU.md | 7 ++++ include/strata/core/verify.hpp | 5 +++ include/strata/kernels/verify_kernels.hpp | 6 ++- src/core/verify.cpp | 40 +++++++++++++++++-- src/kernels/cuda/verify_kernels.cu | 47 ++++++++++++++++++++--- 5 files changed, 96 insertions(+), 9 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 640d60ed..0ee03e2e 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -220,6 +220,13 @@ KV, layers 0-25 / 26-47; 512-token greedy answers, median of 8 runs: Greedy output is byte-identical with the flag at 0 and 1; the quiz set scored the same (47/51). Not measured on NVIDIA yet, where a sync and a graph launch cost less. +The reading stage's wait for the flag is bounded on the GPU: `STRATA_SPLIT_WAIT_MS` (default 30000, 0 = no bound). +If the flag does not arrive in time, the wait marks an error word and returns, the window's graph completes, and the +host fails that window with an error naming the setting (the server then restarts the engine) instead of using a +stale hand-off. Normally the host's own per-layer wait (20 s, #267) ends a stalled window first and releases every +GPU wait, the hand-off's included. Test hook: `STRATA_TEST_HANDOFF_DROP=N` withholds the flag in the first stage's +N-th window, as if the publish were lost. + ## Limits (for now) - **Works across cards** (bench/results/2026-09-29-layer-split-limits): diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 313ea4a7..358aacd5 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -446,6 +446,11 @@ private: uint32_t* hflag_out_h_ = nullptr; ///< ... and the outgoing one's uint32_t* hflag_out_d_ = nullptr; uint32_t* hcount_d_ = nullptr; ///< handoff_publish's block counter (device memory) + uint32_t* herr_h_ = nullptr; ///< the bounded hand-off wait gave up (mapped; the reading stage's) + uint32_t* herr_d_ = nullptr; + uint32_t* hdrop_h_ = nullptr; ///< STRATA_TEST_HANDOFF_DROP: the writing stage withholds its flag (mapped) + uint32_t* hdrop_d_ = nullptr; + bool handoff_failed(std::string& err) const; ///< the bounded hand-off wait timed out in the last window int prelaunched_ = 0; ///< prelaunch ran for a window of this size: run skips staging + launch /// The overlapped split: stage this window's inputs and launch its graph now (the graph waits on the hand-off /// flag); `run` then only serves the host side. Called on a helper thread while the previous stage runs. diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 9669f53f..dab7c9fe 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -79,8 +79,12 @@ void wait_copy_i32_from_mapped(const uint32_t* flag, uint32_t value, int32_t* ds /// stores, then the LAST block to finish raises *flag = 1 (mapped) after a system fence, so the next stage's GPU can /// start (wait_flag_ge(flag, 1)) without the host syncing this stage first. `counter` is one device word, 0 between /// calls (the last block resets it). Volatile because on RDNA a plain store to mapped memory can sit in the L2. +/// `drop` (mapped, may be null): a test hook - nonzero leaves the flag down, as if the publish were lost. void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc, - uint32_t* counter, uint32_t* flag, void* stream); + uint32_t* counter, uint32_t* flag, void* stream, const uint32_t* drop = nullptr); +/// The reading stage's hand-off wait, bounded: spin until *flag >= value, or after timeout_ns (0: no bound) set +/// *err = 1 (mapped) and return, so the window's graph completes and the host fails the window cleanly. +void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream); /// the GPU's %globaltimer (ns) into buf[i] (a one-thread kernel: the verify window's stage profiler). Inside a PDL /// stretch (pdl.hpp) the stamp passes the early launch on, so a profiled window keeps the chain it measures. void gpu_stamp(unsigned long long* buf, int i, void* stream); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index ed2a37f9..2aaa6dba 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -389,6 +389,19 @@ const int64_t g_test_stall = [] { const char* e = std::getenv("STRATA_TEST_VERIFY_STALL"); return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0; }(); +// The overlapped split's hand-off wait on the GPU is bounded: STRATA_SPLIT_WAIT_MS (default 30000, 0 = no bound). +// The host's own per-layer wait (20 s, #267) normally ends a stalled window first; this bound is the backstop for +// a host that is gone (a killed process must not leave a kernel spinning on its card). +const unsigned long long g_split_wait_ns = [] { + const char* e = std::getenv("STRATA_SPLIT_WAIT_MS"); + return (unsigned long long) (e != nullptr ? std::atoll(e) : 30000) * 1000000ull; +}(); +// test hook: STRATA_TEST_HANDOFF_DROP=N - the writing stage's N-th window (1-based) leaves its hand-off flag down, as +// if the publish were lost; the reading stage's bounded wait (or the host's) must then end the window cleanly. +const int64_t g_test_drop = [] { + const char* e = std::getenv("STRATA_TEST_HANDOFF_DROP"); + return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0; +}(); } // namespace bool Verifier::release_gpu_waits(int timeout_ms) { @@ -532,7 +545,7 @@ Verifier::~Verifier() { if (arena_) cudaFree(arena_); if (hcount_d_) cudaFree(hcount_d_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, - h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_}; + h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -718,7 +731,10 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& if (hflag_out_d_ != nullptr && hcount_d_ == nullptr) { // the overlapped split's hand-off counter if (cudaMalloc((void**) &hcount_d_, 64) != cudaSuccess) { err = "verify: hand-off counter allocation failed"; return false; } cudaMemset(hcount_d_, 0, 64); + if (!mapped(64, (void**) &hdrop_h_, (void**) &hdrop_d_)) { err = "verify: hand-off test word allocation failed"; return false; } } + if (hflag_in_d_ != nullptr && herr_h_ == nullptr && + !mapped(64, (void**) &herr_h_, (void**) &herr_d_)) { err = "verify: hand-off error word allocation failed"; return false; } if (g_trace && trace_h_ == nullptr) { // #649: the breadcrumbs, mapped so they read while the GPU hangs trace_n_ = (size_t) (g.n_layers + 1) * kProfPer * 2; if (!mapped(trace_n_ * 8, (void**) &trace_h_, (void**) &trace_m_)) { @@ -964,7 +980,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (lb_ > 0) { const float* hin = hand_in_ + (size_t) hrow0 * HB; // the group's rows: [R][bo][inj] contiguous // the overlapped split: this graph was launched before the previous stage finished - wait for its hand-off - if (hflag_in_d_ != nullptr && !batch_rec_) wait_flag_ge(hflag_in_d_, 1u, cs); + if (hflag_in_d_ != nullptr && !batch_rec_) wait_handoff(hflag_in_d_, 1u, herr_d_, g_split_wait_ns, cs); copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs); copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs); copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs); @@ -1805,7 +1821,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { float* hout = hand_out_ + (size_t) hrow0 * HB; if (hflag_out_d_ != nullptr && !batch_rec_) { // the overlapped split: payload + the next stage's flag handoff_publish(hout, R_, (int64_t) T * HC * N, bo_, (int64_t) T * N, inj2_, (int64_t) T * HC, hcount_d_, - hflag_out_d_, cs); + hflag_out_d_, cs, hdrop_d_); return true; } copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs); @@ -2240,6 +2256,8 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) { *(volatile uint32_t*) h_flagB_ = 0; // the overlapped split: the next stage's graph is launched after this, and must see THIS window's raise if (hflag_out_h_ != nullptr) *(volatile uint32_t*) hflag_out_h_ = 0; + if (herr_h_ != nullptr) *(volatile uint32_t*) herr_h_ = 0; + if (hdrop_h_ != nullptr) *(volatile uint32_t*) hdrop_h_ = (g_test_drop > 0 && windows + 1 == g_test_drop) ? 1u : 0u; std::atomic_thread_fence(std::memory_order_seq_cst); _mm_sfence(); last_t_ = T; @@ -2314,6 +2332,15 @@ bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) { return true; } +bool Verifier::handoff_failed(std::string& err) const { + if (herr_h_ == nullptr || *(const volatile uint32_t*) herr_h_ == 0) return false; + err = "verify: layer split: the hand-off into layer " + std::to_string(lb_) + " did not arrive within " + + std::to_string(g_split_wait_ns / 1000000ull) + " ms (STRATA_SPLIT_WAIT_MS); the window was not used. " + "STRATA_SPLIT_OVERLAP=0 runs the serial order"; + trace_ev("HANDOFF-TIMEOUT", -1, lb_, (int64_t) (g_split_wait_ns / 1000000ull)); + return true; +} + bool Verifier::chain_overlap() const { return next_ != nullptr && hflag_out_h_ != nullptr && hflag_out_d_ != nullptr && hcount_d_ != nullptr && next_->hflag_in_h_ == hflag_out_h_ && next_->device_ != device_ && !next_->ple_stage(); @@ -2569,6 +2596,12 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } if (!ok) return false; if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } + if (handoff_failed(err)) return false; // a middle stage of three or more: its own hand-in + if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871, as below + *(volatile uint32_t*) h_plan_err_ = 0; + err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)"; + return false; + } commit_pending_ = false; if (prof_on_ && G == 1) collect_profile(); return true; @@ -2590,6 +2623,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, const cudaError_t se = cudaStreamSynchronize(cs_); trace_ev("SYNCED", -1, -1, (int64_t) se); if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } + if (handoff_failed(err)) return false; // a stale hand-off: nothing of this window is used if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871: refresh_ar saw the table whole *(volatile uint32_t*) h_plan_err_ = 0; err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)"; diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 75c6f3d3..0928c731 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -1157,9 +1157,39 @@ __global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t valu __threadfence_system(); } +// the GPU's clock in ns (the same sources as gpu_stamp_kernel) +__device__ __forceinline__ unsigned long long strata_now_ns() { + unsigned long long t; +#if defined(STRATA_HIP_GFX906) + t = wall_clock64() * 40ull; +#elif defined(__HIPCC__) + t = wall_clock64() * 10ull; +#else + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); +#endif + return t; +} + +// the overlapped split's hand-off wait, bounded: spin until *flag >= value, or give up after timeout_ns (0: never), +// marking *err = 1 (mapped) so the host fails the window instead of using a stale hand-off. The window's later +// kernels still run (on whatever the hand-off buffer holds) so the graph completes and no stream is left hanging. +__global__ void wait_handoff_kernel(const volatile uint32_t* flag, uint32_t value, uint32_t* err, + unsigned long long timeout_ns) { + const unsigned long long t0 = timeout_ns ? strata_now_ns() : 0ull; + while (*flag < value) { + strata_spin_pause(); + if (timeout_ns && strata_now_ns() - t0 > timeout_ns) { + *(volatile uint32_t*) err = 1u; + __threadfence_system(); + return; + } + } + __threadfence_system(); +} + __global__ void handoff_publish_kernel(float* dst, const float* __restrict__ a, int64_t na, const float* __restrict__ b, int64_t nb, const float* __restrict__ c, int64_t nc, uint32_t* counter, - uint32_t* flag) { + uint32_t* flag, const volatile uint32_t* drop) { const int64_t n = na + nb + nc; volatile float* const out = dst; for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) @@ -1171,15 +1201,22 @@ __global__ void handoff_publish_kernel(float* dst, const float* __restrict__ a, if (prev == gridDim.x - 1) { // every block's payload is out: raise the next stage's flag *(volatile uint32_t*) counter = 0u; __threadfence_system(); - *(volatile uint32_t*) flag = 1u; - __threadfence_system(); + if (drop == nullptr || *drop == 0u) { // test hook (STRATA_TEST_HANDOFF_DROP): a lost publish + *(volatile uint32_t*) flag = 1u; + __threadfence_system(); + } } } } } // namespace +void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream) { + wait_handoff_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, err, timeout_ns); + check("wait_handoff"); +} + void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc, - uint32_t* counter, uint32_t* flag, void* stream) { + uint32_t* counter, uint32_t* flag, void* stream, const uint32_t* drop) { const int64_t n = na + nb + nc; if (n <= 0 || dst == nullptr || counter == nullptr || flag == nullptr) { std::fprintf(stderr, "handoff_publish: invalid arguments\n"); @@ -1187,7 +1224,7 @@ void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int } const int64_t nb256 = (n + 255) / 256; const int blocks = (int) (nb256 < 64 ? nb256 : 64); - handoff_publish_kernel<<>>(dst, a, na, b, nb, c, nc, counter, flag); + handoff_publish_kernel<<>>(dst, a, na, b, nb, c, nc, counter, flag, drop); check("handoff_publish"); } From 090b8e9f13a8bd37cb96d10cb21ae4f8d941c387 Mon Sep 17 00:00:00 2001 From: bsvinay Date: Tue, 6 Oct 2026 09:49:55 +0530 Subject: [PATCH 11/14] layer split overlap: the hand-off publish reads the test word only with STRATA_TEST_HANDOFF_DROP set Without the hook the window graph passes no word, so the publish kernel does no extra read of mapped memory per window. --- src/core/verify.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 2aaa6dba..5bdc1093 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1821,7 +1821,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { float* hout = hand_out_ + (size_t) hrow0 * HB; if (hflag_out_d_ != nullptr && !batch_rec_) { // the overlapped split: payload + the next stage's flag handoff_publish(hout, R_, (int64_t) T * HC * N, bo_, (int64_t) T * N, inj2_, (int64_t) T * HC, hcount_d_, - hflag_out_d_, cs, hdrop_d_); + hflag_out_d_, cs, g_test_drop > 0 ? hdrop_d_ : nullptr); // the test word only with the hook on return true; } copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs); From cbc1578a2f86f6b41395f32e85383292dd0bc83c Mon Sep 17 00:00:00 2001 From: bsvinay Date: Tue, 6 Oct 2026 13:03:44 +0530 Subject: [PATCH 12/14] layer split overlap: off beside --pipeline-windows (#859) --pipeline-windows runs its own overlapped decode loop with its own hand-offs, so STRATA_SPLIT_OVERLAP now switches itself off when it is set (one log line says so). Rebased onto main 1735d64: the early launch of the next stage keeps #871's graph variant (the next stage's refresh_ar() runs before its capture and prelaunch, and not again in its run() when it was prelaunched), resets the plan error word like run()'s launch, and the chain path checks that word after its sync as well. --- docs/MULTI_GPU.md | 2 +- src/program/generate.cpp | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 0ee03e2e..7cc0cc55 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -207,7 +207,7 @@ flag: the earlier stage's GPU writes the hand-off with volatile stores and raise next stage's graph is staged and launched on a helper thread while the earlier stage is still running and waits for the flag on its GPU (`wait_flag_ge`), and the host goes straight from serving one stage's layers to the next, syncing the earlier stage only once the chain is done. It takes one stream sync and one graph launch per window off the -critical path. Batch windows (several conversations) keep the serial order. +critical path. Batch windows (several conversations) keep the serial order. It is off beside `--pipeline-windows`, whose loop overlaps the stages its own way. Measured on 2x RX 7900 XTX (gfx1100, ROCm, Linux), Ryzen 9 9900X, 52 GB RAM, Swift 1.5 IQ3_XXS, 128K context, 8-bit KV, layers 0-25 / 26-47; 512-token greedy answers, median of 8 runs: diff --git a/src/program/generate.cpp b/src/program/generate.cpp index b64155f4..f766e8da 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -7836,10 +7836,15 @@ int main(int argc, char** argv) { // STRATA_SPLIT_OVERLAP=1 (opt-in; measured on 2x RX 7900 XTX only): a ready word per hand-off, raised by the // writing stage's GPU, so the next stage's window is launched early and the host never syncs between // stages (Verifier::set_handoff_flags). Not for --split-device 0 (both stages on one GPU). - const bool overlap = !split_same && [] { + const bool overlap_asked = [] { const char* v = std::getenv("STRATA_SPLIT_OVERLAP"); return v != nullptr && std::atoi(v) != 0; }(); + // --pipeline-windows (#859) runs its own overlapped loop with its own hand-offs: the two do not mix + const bool overlap = overlap_asked && !split_same && o.pipeline_windows == 0; + if (overlap_asked && o.pipeline_windows > 0) + std::fprintf(stderr, "strata serve: STRATA_SPLIT_OVERLAP is off beside --pipeline-windows %d " + "(that loop overlaps the stages itself)\n", o.pipeline_windows); std::vector hflag_h((size_t) n_stages - 1, nullptr), hflag_d((size_t) n_stages - 1, nullptr); if (overlap) for (size_t i = 0; i < hflag_h.size(); ++i) { From 739bc9488157ed1e98808ac050d2cb851110cf43 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 12:05:28 +0200 Subject: [PATCH 13/14] tests: batch_rows_parity, #2234's one-launch kernels against the per-row launches (scores, decode attention, GDN window and commit), bitwise --- CMakeLists.txt | 5 + src/kernels/batch_rows_parity.cpp | 254 ++++++++++++++++++++++++++++++ 2 files changed, 259 insertions(+) create mode 100644 src/kernels/batch_rows_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e28abd9b..913f65ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1068,6 +1068,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(verify_batch_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(verify_batch_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME verify_batch_parity COMMAND verify_batch_parity) + # #2234: the batch window's one-launch-for-all-rows kernels vs the per-row launches, bitwise (GPU, synthetic) + add_executable(batch_rows_parity src/kernels/batch_rows_parity.cpp) + target_include_directories(batch_rows_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(batch_rows_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME batch_rows_parity COMMAND batch_rows_parity) add_executable(cvec_parity src/kernels/cvec_parity.cpp) target_include_directories(cvec_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(cvec_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/src/kernels/batch_rows_parity.cpp b/src/kernels/batch_rows_parity.cpp new file mode 100644 index 00000000..07875735 --- /dev/null +++ b/src/kernels/batch_rows_parity.cpp @@ -0,0 +1,254 @@ +// src/kernels/batch_rows_parity.cpp - the batch window's one-launch-for-all-rows kernels (#2234, STRATA_BATCH_ATTN_ROWS / +// STRATA_BATCH_GDN_GROUPS) against the per-row launches they replace, bitwise (GPU, synthetic, no model). +// +// 1. qsa_block_scores_rows == qsa_block_scores, one call per row, each row with its OWN indexer keys; +// 2. qsa_decode_attn_batch_rows == qsa_decode_attn_batch, one call per row, each row over its OWN K/V pools +// (int8 codes + scales, and fp16); +// 3. gdn_step_norm_groups == gdn_step_norm_multi, one call per slot group, in the window (all outputs, the state +// untouched) and in the 1-row commit (the state written after `keep` tokens). +// Every case compares with memcmp, not a tolerance. Usage: batch_rows_parity +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_select.hpp" +#include "strata/kernels/verify_kernels.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* up(const std::vector& h) { + T* d = nullptr; + ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc"); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +template std::vector down(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download"); + return h; +} +uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast(&h); } + +int bad = 0; +void report(const char* what, bool same) { + std::printf(" %-64s %s\n", what, same ? "bitwise" : "*** DIFFERS ***"); + if (!same) ++bad; +} + +// ---- 1. the block scores ---- +void scores_case(int rows) { + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t max_blocks = 3000; + std::mt19937 rng(11 + rows); + std::normal_distribution nd(0.f, 1.f); + k::QsaScoreRows sr; + sr.n = rows; + std::vector pooled(rows), dead(rows); + std::vector q((size_t) rows * s.idx_n_head * s.idx_dim); + for (auto& x : q) x = nd(rng); + std::vector steps((size_t) rows * k::kStepCount); + for (int r = 0; r < rows; ++r) { + std::vector p((size_t) max_blocks * s.idx_dim), d((size_t) s.idx_dim); + for (auto& x : p) x = nd(rng); + for (auto& x : d) x = nd(rng); + pooled[r] = up(p); + dead[r] = up(d); + sr.pooled[r] = pooled[r]; + sr.dead[r] = dead[r]; + const int64_t pos = 700 + 997 * r + (r % 3) * 5; // different lengths, and an incomplete block at the tail + steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) pos; + steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) (pos + 1); + steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block); + steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s); + } + const float* d_q = up(q); + const int32_t* d_steps = up(steps); + float *d_rows = nullptr, *d_ref = nullptr; + const size_t n = (size_t) rows * max_blocks; + ck(cudaMalloc(&d_rows, n * 4), "malloc"); + ck(cudaMalloc(&d_ref, n * 4), "malloc"); + ck(cudaMemset(d_rows, 0, n * 4), "memset"); + ck(cudaMemset(d_ref, 0, n * 4), "memset"); + k::qsa_block_scores_rows(sr, d_q, d_steps, rows, max_blocks, s, d_rows, nullptr); + for (int r = 0; r < rows; ++r) + k::qsa_block_scores(pooled[r], dead[r], d_q + (size_t) r * s.idx_n_head * s.idx_dim, d_steps + (size_t) r * k::kStepCount, 1, + max_blocks, s, d_ref + (size_t) r * max_blocks, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + const std::vector a = down(d_rows, n), b = down(d_ref, n); + char name[96]; + std::snprintf(name, sizeof name, "qsa_block_scores_rows, %d rows (own keys each)", rows); + report(name, std::memcmp(a.data(), b.data(), n * 4) == 0); +} + +// ---- 2. the decode attention ---- +void attn_case(int rows, bool int8) { + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size; + const int64_t ctx_max = 5000, pages = (ctx_max + PS - 1) / PS, prow = pages * NKV * PS; + const int64_t cap = k::qsa_selection_width(ctx_max, s); + std::mt19937 rng(23 + rows + int8); + std::normal_distribution nd(0.f, 1.f); + std::uniform_int_distribution code(-127, 127); + std::uniform_real_distribution sc(0.005f, 0.03f); + k::QsaAttnPoolsRows pr; + pr.n = rows; + std::vector q((size_t) rows * NH * HD); + for (auto& x : q) x = nd(rng) * 2.0f; + std::vector ids((size_t) rows * cap, 0), steps((size_t) rows * k::kStepCount, 0); + for (int r = 0; r < rows; ++r) { + k::QsaAttnPools& pl = pr.p[r]; + if (int8) { + std::vector kq((size_t) prow * HD), vq((size_t) prow * HD); + std::vector ks((size_t) prow * (HD / 64)), vs(ks.size()); + for (auto& x : kq) x = (int8_t) code(rng); + for (auto& x : vq) x = (int8_t) code(rng); + for (auto& x : ks) x = f2h(sc(rng)); + for (auto& x : vs) x = f2h(sc(rng)); + pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); + } else { + std::vector kh((size_t) prow * HD), vh(kh.size()); + for (auto& x : kh) x = f2h(nd(rng) * 1.5f); + for (auto& x : vh) x = f2h(nd(rng)); + pl.k_pool = up(kh); pl.v_pool = up(vh); + } + std::vector table(pages); + for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i; + std::shuffle(table.begin(), table.end(), rng); // each row's pool has its own page order + pl.page_table = up(table); + const int64_t nkv = 900 + 641 * r + (r % 2) * 3; + const int64_t w = k::qsa_selection_width(nkv, s); + std::vector all((size_t) nkv); + for (int64_t c = 0; c < nkv; ++c) all[c] = (int32_t) c; + std::shuffle(all.begin(), all.end(), rng); + std::sort(all.begin(), all.begin() + w); + std::copy(all.begin(), all.begin() + w, ids.begin() + (size_t) r * cap); + steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) (nkv - 1); + steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) nkv; + steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) (nkv / s.idx_block); + steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) w; + } + const float* d_q = up(q); + const int32_t* d_ids = up(ids); + const int32_t* d_steps = up(steps); + const int64_t scr = (int64_t) k::qsa_decode_attn_scratch_floats(cap, s); + float *scratch = nullptr, *d_rows = nullptr, *d_ref = nullptr; + ck(cudaMalloc(&scratch, (size_t) rows * scr * 4), "malloc"); + const size_t n = (size_t) rows * NH * HD; + ck(cudaMalloc(&d_rows, n * 4), "malloc"); + ck(cudaMalloc(&d_ref, n * 4), "malloc"); + ck(cudaMemset(d_rows, 0, n * 4), "memset"); + ck(cudaMemset(d_ref, 0, n * 4), "memset"); + k::qsa_decode_attn_batch_rows(d_q, pr, d_ids, d_steps, cap, s, scratch, d_rows, rows, nullptr); + for (int r = 0; r < rows; ++r) + k::qsa_decode_attn_batch(d_q + (size_t) r * NH * HD, pr.p[r], d_ids + (size_t) r * cap, d_steps + (size_t) r * k::kStepCount, cap, + s, scratch + (size_t) r * scr, d_ref + (size_t) r * NH * HD, 1, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + const std::vector a = down(d_rows, n), b = down(d_ref, n); + char name[96]; + std::snprintf(name, sizeof name, "qsa_decode_attn_batch_rows, %d rows, %s pools (own pools each)", rows, int8 ? "int8" : "fp16"); + report(name, std::memcmp(a.data(), b.data(), n * 4) == 0); +} + +// ---- 3. the GDN recurrence ---- +void gdn_case(const std::vector& ntok, bool commit) { + const int S = 128, h_k = 16, h_v = 48; // the artifact's geometry + const int qk = S * h_k, C = 2 * qk + S * h_v, vd = S * h_v; + const float eps = 1e-6f; + int T = 0; + for (int n : ntok) T += n; + const int G = (int) ntok.size(); + std::mt19937 rng(31 + T * 7 + G + commit); + std::normal_distribution nd(0.f, 1.f); + std::vector h((size_t) T * C), gate((size_t) T * h_v), beta((size_t) T * h_v), z((size_t) T * vd), gamma(S); + for (auto& v : h) v = nd(rng) * 0.1f; + for (auto& v : gate) v = -(0.5f + 3.0f * (float) (rng() % 100) / 100.0f); + for (auto& v : beta) v = (float) (rng() % 100) / 100.0f; + for (auto& v : z) v = nd(rng); + for (auto& v : gamma) v = 1.0f + 0.1f * nd(rng); + const size_t st_n = (size_t) S * h_v * S; + std::vector> st0(G); + std::vector st_g(G), st_r(G); + std::vector keep(G); + k::GdnGroups gg; + gg.n = G; + int first = 0; + for (int i = 0; i < G; ++i) { + st0[i].resize(st_n); + for (auto& v : st0[i]) v = nd(rng) * 0.1f; + st_g[i] = up(st0[i]); + st_r[i] = up(st0[i]); + const int32_t kp = commit ? ntok[i] : 0; // a commit group keeps all of its rows here + keep[i] = up(std::vector{kp}); + gg.state[i] = st_g[i]; + gg.keep[i] = commit ? keep[i] : nullptr; + gg.first[i] = first; + gg.ntok[i] = ntok[i]; + first += ntok[i]; + } + const float* d_h = up(h); + const float* d_gate = up(gate); + const float* d_beta = up(beta); + const float* d_z = up(z); + const float* d_gm = up(gamma); + float *d_y = nullptr, *d_yr = nullptr; + ck(cudaMalloc(&d_y, (size_t) T * vd * 4), "malloc"); + ck(cudaMalloc(&d_yr, (size_t) T * vd * 4), "malloc"); + ck(cudaMemset(d_y, 0, (size_t) T * vd * 4), "memset"); + ck(cudaMemset(d_yr, 0, (size_t) T * vd * 4), "memset"); + k::gdn_step_norm_groups(gg, d_h, C, d_gate, d_beta, d_z, d_gm, eps, d_y, h_k, h_v, commit, nullptr); + for (int i = 0; i < G; ++i) { + const int f = gg.first[i]; + // the engine's per-slot call: a window group runs its rows with all outputs; a commit group (1 row) keeps them + k::gdn_step_norm_multi(st_r[i], d_h + (size_t) f * C, C, d_gate + (size_t) f * h_v, d_beta + (size_t) f * h_v, + d_z + (size_t) f * vd, d_gm, eps, d_yr + (size_t) f * vd, h_k, h_v, ntok[i], + commit ? keep[i] : nullptr, nullptr, 0); + } + ck(cudaDeviceSynchronize(), "sync"); + bool same = true; + for (int i = 0; i < G; ++i) { + const std::vector a = down(st_g[i], st_n), b = down(st_r[i], st_n); + same = same && std::memcmp(a.data(), b.data(), st_n * 4) == 0; + if (!commit) same = same && std::memcmp(a.data(), st0[i].data(), st_n * 4) == 0; // a window leaves the state alone + } + if (!commit) { + const std::vector a = down(d_y, (size_t) T * vd), b = down(d_yr, (size_t) T * vd); + same = same && std::memcmp(a.data(), b.data(), a.size() * 4) == 0; + } + char name[96], rows[64] = ""; + for (int i = 0; i < G && i < 8; ++i) std::snprintf(rows + std::strlen(rows), sizeof rows - std::strlen(rows), "%s%d", i ? "," : "", ntok[i]); + std::snprintf(name, sizeof name, "gdn_step_norm_groups %s, groups of %s rows", commit ? "commit" : "window", rows); + report(name, same); +} +} // namespace + +int main() { + std::printf("batch rows parity (#2234 kernels against the per-row launches)\n"); + for (int r : {1, 2, 4, 8}) scores_case(r); + for (int r : {1, 3, 8}) { + attn_case(r, true); + attn_case(r, false); + } + gdn_case({1}, false); + gdn_case({1, 1, 1, 1}, false); + gdn_case({2, 2, 2, 2}, false); + gdn_case({1, 3, 2, 1, 1}, false); + gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, false); + gdn_case({1}, true); + gdn_case({1, 1, 1, 1}, true); + gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, true); + std::printf("%s\n", bad ? "batch_rows_parity: FAILED" : "batch_rows_parity: ok"); + return bad ? 1 : 0; +} From f755a06d7c833e189cd3e27a608773e1b8bc1b86 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 14 Oct 2026 21:38:26 +0200 Subject: [PATCH 14/14] #2234 follow-up: the rows attention runs the default kernel's body from its own kernel (the default kernel's signature, and the pre-sm_75 / HIP function-pointer selections, stay as they were: HIP did not build); per-row calls where the per-row path runs a variant (lane-cell, pre-sm_75, gfx906) batch_rows_parity also checks the one top-k launch over all rows against one call per row. --- src/kernels/batch_rows_parity.cpp | 20 +++++++++ src/kernels/cuda/qsa_decode_attn.cu | 66 +++++++++++++++++++++++------ 2 files changed, 74 insertions(+), 12 deletions(-) diff --git a/src/kernels/batch_rows_parity.cpp b/src/kernels/batch_rows_parity.cpp index 07875735..51a0554f 100644 --- a/src/kernels/batch_rows_parity.cpp +++ b/src/kernels/batch_rows_parity.cpp @@ -91,6 +91,26 @@ void scores_case(int rows) { char name[96]; std::snprintf(name, sizeof name, "qsa_block_scores_rows, %d rows (own keys each)", rows); report(name, std::memcmp(a.data(), b.data(), n * 4) == 0); + // the window selects with one top-k launch over all rows (row-independent) where the per-row path ran one per row + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s); + int32_t *i_rows = nullptr, *i_ref = nullptr; + ck(cudaMalloc(&i_rows, (size_t) rows * cap * 4), "malloc"); + ck(cudaMalloc(&i_ref, (size_t) rows * cap * 4), "malloc"); + ck(cudaMemset(i_rows, 0, (size_t) rows * cap * 4), "memset"); + ck(cudaMemset(i_ref, 0, (size_t) rows * cap * 4), "memset"); + k::qsa_block_topk(d_ref, d_steps, rows, max_blocks, cap, s, i_rows, nullptr); + for (int r = 0; r < rows; ++r) + k::qsa_block_topk(d_ref + (size_t) r * max_blocks, d_steps + (size_t) r * k::kStepCount, 1, max_blocks, cap, s, + i_ref + (size_t) r * cap, nullptr); + ck(cudaDeviceSynchronize(), "sync"); + const std::vector ta = down(i_rows, (size_t) rows * cap), tb = down(i_ref, (size_t) rows * cap); + bool tsame = true; + for (int r = 0; r < rows; ++r) { + const int64_t w = steps[(size_t) r * k::kStepCount + k::kStepWidth]; + tsame = tsame && std::memcmp(ta.data() + (size_t) r * cap, tb.data() + (size_t) r * cap, (size_t) w * 4) == 0; + } + std::snprintf(name, sizeof name, "qsa_block_topk over %d rows == one call per row", rows); + report(name, tsame); } // ---- 2. the decode attention ---- diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index 9a0bc84d..ca8a9d4b 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -116,15 +116,15 @@ __device__ __forceinline__ int reduce12_head_of_lane(int lane) { return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1); } -template -__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, - const int32_t* __restrict__ ids, - const int32_t* __restrict__ step, int n_kv_heads, - int page_size, float scale, float* __restrict__ part_acc, - float* __restrict__ part_m, float* __restrict__ part_l, - int n_chunks, int cap = 0, long long scratch_stride = 0, - QsaAttnPoolsRows prow = {}) { - if (prow.n > 0) p = prow.p[blockIdx.z]; // a batch window's query attends over its own slot's pools +// (the body is a device function so the batch window's rows kernel below can run it over each query's own pools without +// the default kernel's signature, or the function-pointer types the pre-sm_75 / HIP selections build, changing) +template +__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, const int32_t* __restrict__ step, + int n_kv_heads, int page_size, float scale, + float* __restrict__ part_acc, float* __restrict__ part_m, + float* __restrict__ part_l, int n_chunks, int cap, + long long scratch_stride) { // batched form: query blockIdx.z, with its own q row, selection, step and scratch q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; ids += (size_t) blockIdx.z * (size_t) cap; @@ -283,6 +283,32 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h]; } +template +__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int n_kv_heads, + int page_size, float scale, float* __restrict__ part_acc, + float* __restrict__ part_m, float* __restrict__ part_l, + int n_chunks, int cap = 0, long long scratch_stride = 0) { + attn_chunk_body(q, p, ids, step, n_kv_heads, page_size, scale, part_acc, + part_m, part_l, n_chunks, cap, scratch_stride); +} + +// Batch windows: query blockIdx.z attends over its own slot's pools (rows.p[z]); the default kernel otherwise. +template +__global__ void __launch_bounds__(THREADS) attn_chunk_rows_kernel(const float* __restrict__ q, QsaAttnPoolsRows rows, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int n_kv_heads, + int page_size, float scale, + float* __restrict__ part_acc, + float* __restrict__ part_m, + float* __restrict__ part_l, int n_chunks, int cap, + long long scratch_stride) { + attn_chunk_body(q, rows.p[blockIdx.z], ids, step, n_kv_heads, page_size, scale, + part_acc, part_m, part_l, n_chunks, cap, scratch_stride); +} + + // PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel // above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It // uses more registers (80 vs 38 on sm_70), so on CUDA it runs on cards below sm_75 only, and exists only in the @@ -731,9 +757,25 @@ void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, co const float scale = 1.0f / sqrtf((float) HD); const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); cudaStream_t st = (cudaStream_t) stream; - // the default kernel of qsa_decode_attn_batch on this target (no lane-cell, no pre-sm_75, no gfx906 variants) -#define STRATA_ATTN_ROWS(M) attn_chunk_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, \ - (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride, rows) + // The plain kernel is what qsa_decode_attn_batch runs unless one of its variants is on (lane-cell scoring, the + // pre-sm_75 / gfx103x kernel, the gfx906 swizzle): there each row goes through that call, one launch per row. + static const bool lane_cell_rows = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); + bool per_row = lane_cell_rows; +#if defined(STRATA_ATTN_PRE75_BUILT) + per_row = per_row || pre75_attn(); +#endif +#if defined(STRATA_HIP_GFX906) + per_row = true; +#endif + if (per_row) { + for (int64_t r = 0; r < n_q; ++r) + qsa_decode_attn_batch(q + (size_t) r * s.n_head * HD, rows.p[r], ids + (size_t) r * cap, + steps + (size_t) r * kStepCount, cap, s, scratch + (size_t) r * stride, + attn + (size_t) r * s.n_head * HD, 1, stream); + return; + } +#define STRATA_ATTN_ROWS(M) attn_chunk_rows_kernel<<>>(q, rows, ids, steps, (int) s.n_head_kv, \ + (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride) if (kv_mode == 3) STRATA_ATTN_ROWS(3); else if (kv_mode == 2) STRATA_ATTN_ROWS(2); else if (kv_mode == 1) STRATA_ATTN_ROWS(1);