diff --git a/CMakeLists.txt b/CMakeLists.txt index 012d46c8..4e81f9a3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1134,6 +1134,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/docs/BATCHING.md b/docs/BATCHING.md index 44769a78..cbb534e4 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -188,6 +188,170 @@ 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. + +## 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 @@ -309,6 +473,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 @@ -325,7 +520,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/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 352a5f63..6d2c8dc9 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -215,6 +215,34 @@ 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. 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: + +| | 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. + +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/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/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/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 a3d5fa7f..f4d98251 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -178,6 +178,14 @@ public: /// Is the zero-doorbell graph the one a batch window would run now (every expert of the stage in VRAM by the host /// table)? Looks at the table, as each window does. (STRATA_ADMIT_MERGE_FIRST's gate.) bool ar_live() { refresh_ar(); return ar_on(); } + /// 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; } @@ -225,7 +233,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. @@ -349,10 +364,22 @@ 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; - std::chrono::steady_clock::time_point b_last_; + // 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}; + // 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 @@ -423,6 +450,21 @@ private: int handoff_rows_ = 0; ///< set_handoff_rows (0: kVerifyMaxT) 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) + 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. + 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/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp index 3270d8b6..e782035d 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); @@ -68,5 +75,9 @@ void qsa_decode_attn_chunks_only(const float* q, const QsaAttnPools& pools, cons void* stream); void qsa_decode_attn_merge_only(const int32_t* steps, int64_t cap, const QsaShapes& s, const float* scratch, float* attn, int64_t n_q, int v2, 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 5d1331fe..e8beacce 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..dab7c9fe 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); @@ -60,6 +74,17 @@ 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. +/// `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, 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/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/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 9b2893fa..197dc25f 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -154,6 +154,17 @@ 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_; } + /// 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. @@ -206,6 +217,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) /// STRATA_HANDOFF_PIPE: the previous stage's per-piece "landed in hand_in_" events (cudaEvent_t[hand_pieces_], diff --git a/include/strata/program/batch_read.hpp b/include/strata/program/batch_read.hpp index c9036138..65cd6a08 100644 --- a/include/strata/program/batch_read.hpp +++ b/include/strata/program/batch_read.hpp @@ -27,4 +27,61 @@ 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 (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 +}; + +/// 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; +} + +/// 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/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 fb254d35..68be4420 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -1372,6 +1372,46 @@ 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) 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; + 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) @@ -1393,14 +1433,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 8c945c4e..6c1c1e3e 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -58,6 +58,7 @@ #include #include #include +#include #include #include #include @@ -412,6 +413,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) { @@ -420,7 +434,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(); @@ -557,8 +571,9 @@ 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_}; + h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -741,6 +756,13 @@ 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 (!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_)) { @@ -777,6 +799,25 @@ 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) { + 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); + }; 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 @@ -790,13 +831,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; } @@ -989,6 +1030,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_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); @@ -1279,6 +1322,24 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { } } // 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; @@ -1553,6 +1614,35 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { bool streamed = false; // a streamed KV cache keeps the per-row resolve-then-attend order if (batch_rec_ && g_qsa_slots) for (int t = tb; t < te; ++t) streamed = streamed || slot_ss(t).qsa_states[qi].kv_mode == 1; + // 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_ && g_qsa_slots && !streamed) { // the rows' block scores, top-k and attention, up to 8 rows per launch. The rows only read // their slots' keys and K/V here and write their own scores/sel/scratch/attn rows, so running @@ -1927,6 +2017,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, 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); 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); @@ -2357,7 +2452,12 @@ 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; + 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; last_pos0_ = pos0; for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t]; @@ -2430,6 +2530,45 @@ 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(); +} + +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) @@ -2445,11 +2584,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]; @@ -2462,35 +2611,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; @@ -2524,7 +2702,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 @@ -2539,7 +2717,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 @@ -2601,6 +2779,31 @@ 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; } + 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; + } 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 @@ -2608,7 +2811,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; @@ -2618,6 +2821,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)"; @@ -3014,6 +3218,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; @@ -3023,6 +3236,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, @@ -3031,6 +3252,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); @@ -3399,52 +3625,38 @@ 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(); + ring_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(); *h_flag_ = 1; } - 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; - } + 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); @@ -3461,8 +3673,64 @@ 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_; + ring_now(); + 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) 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 - 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 (" + + (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_ + 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/kernels/batch_rows_parity.cpp b/src/kernels/batch_rows_parity.cpp new file mode 100644 index 00000000..51a0554f --- /dev/null +++ b/src/kernels/batch_rows_parity.cpp @@ -0,0 +1,274 @@ +// 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); + // 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 ---- +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; +} diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu index fe1ee65e..062ef664 100644 --- a/src/kernels/cuda/qsa_decode_attn.cu +++ b/src/kernels/cuda/qsa_decode_attn.cu @@ -117,6 +117,8 @@ __device__ __forceinline__ int reduce12_head_of_lane(int lane) { } // The chunk kernel's body; `p` is the query's KV pools (the call's one set, or blockIdx.z's slot's set). +// (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, @@ -309,6 +311,20 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_slots_kernel(const float* 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 @@ -966,6 +982,58 @@ bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const return true; } +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 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); + else STRATA_ATTN_ROWS(0); +#undef STRATA_ATTN_ROWS + launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head, + (unsigned) n_q, st); + 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 39db4f65..02e6c750 100644 --- a/src/kernels/cuda/qsa_select.cu +++ b/src/kernels/cuda/qsa_select.cu @@ -835,7 +835,8 @@ __device__ __forceinline__ void block_scores_multi_body(const float* __restrict_ const float* __restrict__ dead, const float* __restrict__ q_idx, const int32_t* __restrict__ steps, int nq, int64_t max_blocks, - float* __restrict__ out, bool early_exit) { + float* __restrict__ out, bool early_exit, + const QsaScoreRows& srow) { __shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM]; __shared__ int64_t s_nkv[MQ], s_nbid[MQ]; if (!early_exit) @@ -858,12 +859,16 @@ __device__ __forceinline__ void block_scores_multi_body(const float* __restrict_ 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 @@ -887,8 +892,8 @@ __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) { - block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit); + bool early_exit, QsaScoreRows srow = {}) { + block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit, srow); } // Queries of different slots, each with its own indexer keys: blockIdx.y is the query, and its CTAs run exactly the @@ -910,7 +915,8 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_slots_kernel(Sc for (unsigned i = 1; i < MQ; ++i) if (z == i) { pooled = keys.pooled[i]; dead = keys.dead[i]; } block_scores_multi_body(pooled, dead, q_idx + (size_t) z * IDX_HEADS * IDX_DIM, - steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit); + steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit, + QsaScoreRows{}); } // QSAROWS (docs/QSAROWS.md, STRATA_QSA_ROWS=1): block_scores_multi_kernel's work for NQ <= 4 queries with less issue @@ -1284,6 +1290,20 @@ bool qsa_block_scores_rows(const float* pooled, const float* dead, const float* return true; } +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..0928c731 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) { @@ -1121,8 +1156,78 @@ __global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t valu while (*flag < value) strata_spin_pause(); __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, 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) + 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(); + 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, 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"); + 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, drop); + 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/kernels/ngram.cpp b/src/kernels/ngram.cpp index 1fd7a3a5..2892e059 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) { @@ -605,6 +614,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); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 49ea499c..3f840921 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -2352,8 +2352,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 @@ -4642,6 +4649,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 ed20bbd0..09bdef8e 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8270,12 +8270,39 @@ 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_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) { + 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 (hrows > strata::kernels::kVerifyMaxT) stage_ver(st).set_handoff_rows(hrows); + 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; @@ -8316,7 +8343,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 @@ -10384,6 +10412,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; @@ -10793,6 +10822,13 @@ int main(int argc, char** argv) { double line_drain_ms = 0.0, adm_drain_ms = 0.0; const char* rows_wait = nullptr; // what the next rows are timed from (rows_wait_t) Clock::time_point rows_wait_t{}; + // 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; @@ -10832,6 +10868,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; @@ -10887,6 +10924,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); } @@ -10897,6 +10940,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 @@ -10909,7 +10959,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; }; @@ -12276,12 +12328,376 @@ 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); - const int64_t piece = strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, yield_chunks); + // 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 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; + 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"; + // (--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; + 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 && 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"); + // 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 + // 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 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); + 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([&] { + conc_thread_cpus(); + 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) { + auto& vk = stage_verifier(k); + if (vk.batch_busy()) { + busy = true; + vk.batch_serve(win_pool_fn, win_pool_user); + } + } + 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; + std::string read_err; + in_prompt_read = true; + sp.stop_at_chunk = [&] { return want_yield.load(std::memory_order_acquire) >= 0; }; + std::thread reader([&] { + 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) { + 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); + { 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; + 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; + 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)) { + 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 + 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; + } + } + 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; + 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; + 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 " + "(%.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; + } + 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; + } + // 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; @@ -12300,38 +12716,25 @@ 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 (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; } - 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()); + 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(); @@ -12349,6 +12752,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 d9842381..017065ef 100644 --- a/tests/program/batch_read_test.cpp +++ b/tests/program/batch_read_test.cpp @@ -1,9 +1,16 @@ -// 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; +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) @@ -27,6 +34,52 @@ 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])); + } + // 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; } 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()