Compare commits

...
60 Commits
Author SHA1 Message Date
Niko1221 283fc353e4 D-1: the tensor-core prompt attention only on sm_80+ (the experimental sm_75 build compiles again)
Its MMA and cp.async need sm_80: an sm_75 build stopped with ptxas errors. They now compile to a trap below
sm_80, and qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs there. RTX 30/40/50:
the same code (parity unchanged: vs FP64 3.17e-6).
2026-09-29 11:26:54 +02:00
Niko1221 c43a308fed Engine 0.1.22: faster prompts, multi-GPU without flags; setup requires it 2026-09-29 11:04:51 +02:00
Niko1221 0f44fb492d Monitor: every card of a layer split (issue #112)
The GPU, VRAM, temperature and power cards read all the cards the model runs on: their total (VRAM, power, PCIe
traffic), mean (load) or hottest (temperature), with each card's own reading underneath; the GPU name lists them.
One card: unchanged.
2026-09-29 10:44:12 +02:00
Niko1221 68072d30d4 D-4: refill the prompt path's lent cache slots with queued copies and one wait
The same copies on the same (legacy) stream, but queued instead of waited on one by one: the same bytes, ordered the
same against earlier work. Q2_0 on a 5070 (1,782 slots): 162 -> 96 ms per prompt, 4K and 32K outputs identical.
The rest (publishing slots in the background while decode starts) would hide the last ~2% of the time to first
token on a 4K prompt; not done. STRATA_REFILL_BLOCKING=1 keeps the old loop.
2026-09-29 10:43:11 +02:00
Niko1221 4fb14bf923 prefill timing: KV staging on its own line ("kv stage")
D-3 measurement: Q2_0, 128K prompt with KV streaming, 5070: staging 1,331 ms of 81.3 s (1.6%); staging only the
selected union could save part of that, so D-3 is not done. The same prompt: 1,144 tok/s on 0.1.21, 1,596 on this
branch (+39.5%), time to first token 115.7 -> 83.4 s.
2026-09-29 10:33:39 +02:00
Niko1221 bba62249d5 setup: a card that cannot be used names both ways that work (--gpus 0,2, or one card: --gpu 0 or --gpu 2) 2026-09-29 10:18:09 +02:00
Niko1221 0be1ee9df3 setup: compile with Visual Studio 2019/2022, not a newer one installed next to it
vswhere -latest picked Visual Studio 2026 (version 18) on a PC that also has 2022, and CUDA 13.1's nvcc stops with
"unsupported Microsoft Visual Studio version". Now only 2019/2022 are looked for; with only a newer one, the 2022
Build Tools are installed as when none is there.
2026-09-29 10:09:52 +02:00
Niko1221 548007f874 setup: several GPUs without typing - a table of the cards, the choice asked, "not supported" said plainly
Several users could pick one GPU but not two. Now START-HERE.bat / setup.sh:
  * lists every NVIDIA card with "can be used" or why not (older than the RTX 30 series; under 8 GB to share a model);
  * asks, when two or more cards can share the model, which to use - the two best together recommended (newest
    generation first), every combination and each single card offered; --yes takes the recommendation;
  * asks once, at the next start of a model installed on one card, whether to use both from now on (kept);
  * --gpus 0,2 / --gpus all / --gpu 0,2 at a start saves the cards for that model; --gpu N is for that start only;
  * a card that cannot be used (or is gone) stops with its reason and the command that works instead.
The engine gets code for every chosen card (a local build compiles all their generations; the ready-made one is
checked against each), the context is recommended from the smallest card, and --calibrate measures the split.
2026-09-29 09:56:16 +02:00
Niko1221 cc02cdef73 Merge mg/limits: images, control vectors, KV streaming, helper GPUs and mid-prompt checkpoints across GPUs 2026-09-29 09:52:37 +02:00
Niko1221 732a3f4c92 D-1: the prompt path's QSA attention on tensor cores
One block per (query, KV head) walks its selected cells in chunks of 32 with an online softmax (no split-K
scratch, no merge kernel). q.k and p.v are FP16 MMAs with FP32 accumulation; int8 codes enter exactly, their
scales in FP32; q and p are split into hi + lo halves after an exact power-of-two prescale, so the result keeps
FP32-level accuracy. Int8 KV: each warp owns one 64-dim scale group and gathers its own K/V slices with
double-buffered cp.async. FP16 KV: the first version. Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the old kernel.

qsa_prompt_attn_parity (5070, synthetic): vs FP64 3.2e-6 (old kernel 2.5e-6); int8 4.0x faster (26.6 -> 6.6 ms per
2,048-query chunk at 32K), fp16 1.45x. Q2_0, 32K prompt: attention 5,216 -> 1,318 ms, prompt 1,386 -> 1,646 tok/s
(+18.8%). Not bitwise: the model amplifies any FP32-level change (v1 vs v2 of this kernel, same accuracy, another
summation order, differ as much as old vs new: residual rel L2 mean 0.060 vs 0.061). Needles 8K/16K/32K x 5 depths:
15/15 with both kernels.

Also STRATA_SEL_OVERLAP (debug): how many of the cells 16-query tiles read compared to one query at a time.
2026-09-29 09:48:42 +02:00
Niko1221 06bee97f7e setup: --gpus on an installed model splits it across those cards; --gpu 0,2 means --gpus 0,2
A user reported that he could pick a GPU but not two. With v0.1.21 (reproduced on a 5080 + 2080 Ti + 3090 PC):
  * START-HERE.bat --gpus 0,2 on an installed model started it on GPU 0 alone: --gpus was saved only with --setup,
    and the start passed its first card as --gpu, which overrides the saved choice;
  * START-HERE.bat --gpu 0,2 stopped with "argument --gpu: invalid int value";
  * an update unzipped next to a layer-split install stopped at step 1: "there is no GPU [0, 2]".
Now the first two start across both cards (the server gets --gpu 0,2 and splits the layers, auto), and an update
sets itself up across the same cards with the saved layer split.  --gpu N still runs one card.
2026-09-29 09:48:30 +02:00
Niko1221 0aa72eabe1 E-6: the device plan opt-in (STRATA_VERIFY_DEVICE_PLAN=1)
Exact on RIBPC (5080 alone and 5080+3090, device plan off/on 10/10 identical), but decode and prompt speed
within noise (1 GPU story 86.7 -> 84.5, code 103.3 -> 102.0 tok/s; 2 GPUs 81.5 -> 82.4, 113.9 -> 109.9).
2026-09-29 09:09:00 +02:00
Niko1221 b5347e3666 D-2: the prompt path's GDN recurrence split over value columns, the output norm in its own kernel
One 512-thread block per head (48 blocks) walked the chunk. The value columns' recurrences are
independent; only the per-token output norm couples a head's columns. Now 4 blocks of 32 columns per
head (192 blocks, 128 threads per __syncthreads), and a parallel norm kernel with the same warp sums.
Per column the same arithmetic in the same order: residual dumps and continuations byte-identical to
0.1.21 (4K, 20K). Q2_0 32K, back to back: GDN 5118 -> 4264 ms, prompt 1258 -> 1308 tok/s.
STRATA_GDN_REC_HEADS=1: the per-head kernel. (A chunked delta-rule kernel - not bitwise - is the
larger step left.)
2026-09-29 09:05:02 +02:00
Niko1221 1c58de5ab2 E-6: a verify layer whose routed experts are all in VRAM needs nothing from the host
After routing, one thread checks the group's entries against the device residency table; when all
are resident it writes the plan the host pool would (same layout, same order) and marks the ring.
The layer's waits on the host (plan, PCIe share, CPU share) then return at once and the CPU rows
are zeros; the host still runs its loop, off the GPU's critical path. STRATA_VERIFY_DEVICE_PLAN=0: off.
2026-09-29 08:56:02 +02:00
Niko1221 459a1d15e6 E-4 (prompt side): the draft layer's pass over a prompt chunk without a host sync per group
A group of <= --spec rows was staged in mapped memory and synced before the next: ~5,500 host round
trips on a 32K prompt. The rows' token / step / position records are now uploaded once per call and
each group is device copies plus a graph on the one stream, one sync at the end (a graph variant
without the mapped staging). The same work in the same order: continuations byte-identical to 0.1.21
(4K, 20K). Q2_0 32K: the draft layer's share 1091 -> 905 ms; prompt 1213 (Phase B) -> 1387 tok/s with
Phase C and D-5. STRATA_MTP_PREFILL_SYNC=1 keeps the old loop.
2026-09-29 08:45:41 +02:00
Niko1221 7d0f3fe79e Layer split limits: docs/MULTI_GPU.md and bench/results/2026-09-29-layer-split-limits 2026-09-29 08:44:35 +02:00
Niko1221 8baae07184 D-5: the prompt path's expert stream is issued by its own host thread
The thread that launches a chunk's kernels also issued the expert copies, and waited there for
the host copies of the unpinned blobs (the arena part Windows would not pin): the GPU idled - the
'wait copy' and 'dequant' time of the i-quant prompts. A per-chunk issuer thread now walks the
stream: the same copies in the same order into the same slots, a slot refilled only after the
compute stream recorded it free. STRATA_PREFILL_ISSUER=0 keeps the inline issue.
IQ3_S 32K prompt: 1143 -> 1213 tok/s, 'wait copy' 15.2% -> 7.5%. Exact: residual dumps and
continuations byte-identical to 0.1.21 at 20K (IQ3_S, IQ3_XXS: +16% prompt tok/s with Phase C).
The stager's ring and threads are tunable (STRATA_STAGER_RING / _THREADS); the defaults stay
(more copy threads were slower: 816 tok/s at 6).
2026-09-29 08:41:08 +02:00
Niko1221 24d4013c87 E-2: prefetch the i-quant expert rows ahead of the AVX-512 decode; an opt-in gather decode
Measured on a Ryzen 5 7600 (IQ3_S, 4K context, CLI decode timeline, outputs identical):
gate/up 37.1 -> 36.5 ms/round with a 2 KB prefetch; the gather decode (same results) is 3-5%
slower than the scalar lookups, so it is opt-in (STRATA_IQ_GATHER=1). More pool threads (SMT)
do not help: the pool reads its rows at ~30 GB/s, near DDR5's practical rate through 4 KB pages
- memory-bound, so decode speed now comes from VRAM hits (E-1) rather than CPU kernels.
2026-09-29 07:59:37 +02:00
Niko1221 07b107403a C-3: the prompt path's GDN short conv tiled over tokens
The 4-tap conv reads inputs, not its own outputs, so 64-token tiles are independent: 160x the
threads of the per-channel walk. Same per-element expression (identical bits: residual dumps and
continuations byte-identical to 0.1.21, also with 1001-token chunks). STRATA_GDN_CONV_SERIAL=1: the walk.
2026-09-29 07:32:59 +02:00
Niko1221 0c26102af4 C-1, C-2: the prompt path's QSA select grid reaches only the active blocks; the indexer appends a chunk at once
- C-1: the block-score grid spans the batch's largest n_bid + 1 blocks instead of the context's
  capacity (the blocks past a query's n_bid returned at once). The graphed decode paths keep the
  capacity grid.
- C-2: the indexer's appends of a chunk in three launches (the first cell's spare, one CTA per
  completed block, the tail) instead of one launch per token and QSA layer (24K per 2048-token chunk).
  The end state is the sequential one's: the same arithmetic per block, only the batch's last block
  writes the spare after it. STRATA_INDEXER_PER_TOKEN=1 keeps the old loop.
Exact: residual dumps and continuations byte-identical to 0.1.21 (4K, 20K, and 5K read in chunks of
1001 so blocks straddle chunks). Coder prompt tok/s with C-4: 4K 1063 -> 1255 (+18%), 20K 1216 -> 1373 (+13%).
2026-09-29 07:29:06 +02:00
Niko1221 0311c91377 Layer split: an explicit --expert-cache leaves room for the prompt path; --mmap-experts says it needs a canonical pack 2026-09-29 07:28:29 +02:00
Niko1221 dfe61b1ca0 C-4: the prompt's embedding in one gather, and the n-gram table read by several threads
- One batched gather per chunk instead of a launch per token (same arithmetic: identical bits).
- The prompt path's 'embed+steps' time was mostly the host reading the n-gram (PLE) rows from the SSD
  with the GPU idle: one thread issued every 90-byte read (~12 us of kernel time each, ~80K reads/s).
  DirectFile now only queues a read; a pool issues them (4 threads on Windows, overlapped; 16 blocking
  O_DIRECT preads on Linux, which read them one at a time before - perf-review F-2). STRATA_IO_THREADS.
  Q2_0 4K prompt: PLE 591 -> 291 ms, 941 -> 1010 tok/s.
- STRATA_PREFILL_TIMING also prints the host's share (chunk setup, the per-chunk callback).
Exactness: the prompt path's final residuals (STRATA_PREFILL_DUMP_R) and the continuation are
byte-identical to 0.1.21 at 4K and 20K tokens, IQ and S2 embedding tables.
2026-09-29 07:23:09 +02:00
Niko1221 d22177c610 Layer split: mid-prompt checkpoints (--prompt-cache-every) with the pipelined prompt path
Each stage saves its own part of a checkpoint when it has read the chunk that reaches the
position (Prefill::on_stage_chunk, its state synchronized at that chunk's end), by the same
rule the last stage uses; the last stage puts the parts together in on_chunk. They were off
across GPUs because the first stage is a chunk ahead when the last one reports.
2026-09-29 07:18:20 +02:00
Niko1221 9baff31592 Layer split: images, control vectors, KV streaming, --mmap-experts and the helper GPUs across GPUs
- the image-position (mrope) table and the control vector's tables are per device: every
  stage's rope and steering kernels read their own device's copy; picture rows go through
  the split prompt path (stage 0 embeds them, the later stages take the hand-off)
- KV streaming: each stage's session already streams its own pinned KV copy; no longer forced off
- --mmap-experts: allowed (no pinned arena: every miss the CPU computes, prompts copy on the host)
- --expert-cache-remote with a split: the helpers run on the visible GPUs no stage runs on and
  hold only experts no stage's cache holds
2026-09-29 07:16:53 +02:00
Niko1221 82c6464c92 F-1: the streaming detokenizer decodes each token's bytes incrementally (constant time per token)
It re-decoded every generated id per token: 2 ms per token after 8K tokens, 4 ms after 16K.
Now 0.0005 ms at any length; the text is the same (serve/test_detok.py checks it against the
old algorithm on real and random token streams), and a complete character is no longer held
back behind an incomplete one.
2026-09-29 06:56:26 +02:00
Niko1221 6e1a7be257 Engine 0.1.21: one model across two or three GPUs (layer split, experimental); setup requires it 2026-09-29 06:14:43 +02:00
Niko1221 6f1a24defb Layer split: measured results (bench/results/2026-09-29-layer-split) and the recommendations in docs/MULTI_GPU.md 2026-09-29 01:17:30 +02:00
Niko1221 641c62a0e9 Layer split auto: a cost model of the decode window (per-layer time from SMs x clock, missed routed mass)
Fitted on the 5080 + 3090 K sweep (18-32): it picks K=26, the measured best (prompt +18-20%
over the 5080 alone), and gives a slow third card (2080 Ti) a single layer.
2026-09-29 01:00:24 +02:00
Niko1221 52bccfe914 fused_gr: cap the shared-memory opt-in at the card's limit (Turing: 64 KB) 2026-09-29 00:34:46 +02:00
Niko1221 8d09be6051 Layer split: STRATA_SPLIT_TIMING (per-stage host time per window); docs/MULTI_GPU.md 2026-09-29 00:30:16 +02:00
Niko1221 c8b10915aa QSA scorer: an FP32 fallback for Turing (the experimental sm_75 build, a layer-split stage on a 2080 Ti) 2026-09-29 00:14:23 +02:00
Niko1221 500eb977a9 Multi-GPU in the config: "gpu": [0, 2] (setup --gpus 0,2) runs the layer split across the cards
The server sets CUDA_VISIBLE_DEVICES to the list and adds --layer-split ("layer_split" in the
config, auto by default); the Monitor reads the first (main) card.
2026-09-29 00:12:05 +02:00
Niko1221 3d5d96ddce Layer split: keep the 8 GiB pin limit across GPUs (WDDM), report a failed free-memory read 2026-09-29 00:08:55 +02:00
Niko1221 a2d13aa5b3 Layer split: N stages, the batched prompt path, checkpoints, swaps and PCIe per stage, auto placement
--layer-split K1[,K2..]|auto with --split-device D1[,D2..]: each later stage runs its layer
range on its own GPU (weights, session, cache, verify window, prompt path). The prompt path
hands each chunk's rows to the next stage, which reads it on a thread while the previous
stage reads the next chunk. Checkpoints carry every stage's session state; adaptive swaps
copy into the layer's own cache; each GPU probes its own PCIe share. "auto" scores every
placement (up to 3 GPUs) by the profile-weighted pairs each cache would hold.

STRATA_EXPERIMENTAL_SM75: lets CMake build for a Turing card (the 2080 Ti A/B).
2026-09-28 23:56:30 +02:00
Niko1221 4572b8f221 Layer split v1 (step 4): the second stage on its own GPU
--split-device D (default: the second visible GPU) runs layers [K, n) on device D with
its own copy of the dense weights, session, head, drafter and an expert cache filled
from the profile's pairs of its layers. Verifier and MtpDrafter switch to the device
they were made on (OnDevice), the pool wrapper swaps the stage's cache pointers, the
penalty history lives with the head, and the s2 LUT is per device.

v1 switches off what does not cross devices yet: checkpoints, adaptive swaps, the PCIe
share and the batched prompt path (prompts read through the verify windows).
2026-09-28 23:37:29 +02:00
Niko1221 45266e06fc Layer split v1 (step 1-2): a verify window can run a range of layers and hand its residual to the next stage
--layer-split K runs layers [0, K) and [K, n_layers) as two verify stages on the same device (sharing weights,
session and expert cache). The hand-off carries R, the last layer's pending write and inject, so the next stage
folds it in exactly as the unsplit window does. The GPU shared-memory opt-ins are now per device.
2026-09-28 23:11:45 +02:00
Niko1221 962beb84e3 multi-GPU: the helper spins instead of sleeping, and reads/writes its staging zero-copy
Each layer waits for the helper GPU on the CPU pool's critical path. Measured on RIBPC (Windows): ~0.3 ms
per round trip, more than the fast CPU needs for the same experts. The helper's context is created with
cudaDeviceScheduleSpin (STRATA_REMOTE_SPIN=0: the default), and its input/compact-output staging is mapped:
the kernels read and write it directly, two copies fewer per layer (STRATA_REMOTE_ZEROCOPY=0: copies).
2026-09-28 22:52:21 +02:00
Niko1221 4cd2461849 multi-GPU: time the helper GPU's staging/launch and wait per request 2026-09-28 22:47:06 +02:00
Niko1221 7dbe2bf85b PCIe probe: below 4 GB/s (x1 links) the PCIe share is 0 - every miss goes to the CPU pool 2026-09-28 22:42:40 +02:00
Niko1221 6cd274f03a CMake: STRATA_BUILD_TESTS=ON works without the unpublished tests/ tree 2026-09-28 22:42:25 +02:00
Daerdaal 109a209e53 Add optional multi-GPU expert caches and compact transfers 2026-09-28 22:05:16 +02:00
Niko1221andcode-martin bcd62942f1 Engine 0.1.20: a checkpoint at the end of the system prompt (PR #65 on top of #62); setup requires it
A prompt read from token 0 is also checkpointed at its first turn boundary when that is 2,048 tokens or
more (--prompt-cache-root N, 0 = off). It becomes the chain's root, which #62's retention policy pins,
so a new chat of the same client reads only what follows the system prompt and tools. Without it, #62's
root existed only for system prompts past --prompt-cache-every (16K).

Co-Authored-By: code-martin <[email protected]>
2026-09-28 19:17:28 +02:00
Niko1221 93c6ba5d78 Merge PR #62 (j-luwierski): the conversation cache keeps its shared prefix; the rest rotates LRU 2026-09-28 19:16:34 +02:00
Niko1221 1838ead7e2 PR #67 follow-up: name type 42 (Q2_0); its tests run from the repo root and on Windows (no symlinks, open memmaps) 2026-09-28 19:15:31 +02:00
Niko1221 f827ddd1c4 Merge PR #67 (acrogenesis): OrcaRouter IQ3_XXS with explicit BF16 compatibility packing 2026-09-28 19:15:09 +02:00
Niko1221 85118e318d PR #44 follow-up: keep the default from 20 GB/s up, probe native packs only, the share is read by SMs 2026-09-28 19:14:46 +02:00
Niko1221 fdf8a6249f Merge PR #44 (pipeob0): generate: probe the real host->device bandwidth for the PCIe share 2026-09-28 19:14:23 +02:00
Niko1221andMIDHAT NASHAR 3e1145d2f3 serve: report the engine's own version (INFO engine=) over BUILD.json's (from PR #41, midhatn)
Co-Authored-By: MIDHAT NASHAR <[email protected]>
2026-09-28 19:14:23 +02:00
Niko1221 f086119902 PR #63 follow-up: move the unpacked llama.cpp to third_party/llama.cpp itself, retrying a locked move 2026-09-28 19:14:09 +02:00
Niko1221 be4be48935 Merge PR #63 (alfirus): Windows PermissionError in get_llama_cpp() 2026-09-28 19:13:45 +02:00
Niko1221 763d57ddf8 PR #69 follow-up: '(hits / lookups)' in the log; what the hit rate counts (not the PCIe share) 2026-09-28 19:13:40 +02:00
Niko1221 cb708580a5 Merge PR #69 (code-martin): telemetry: per-request decode expert cache hit rate in DONE and web mo 2026-09-28 19:13:21 +02:00
Niko1221 5a60f99cc0 Merge PR #64 (pipeob0): parity tool: count a new-kernel mismatch as a failure, not just print 2026-09-28 19:13:21 +02:00
pipeob0 7a375041d1 parity tool: count a new-kernel mismatch as a failure, not just print it
The gate/up row and IQ4_NL down comparisons printed their distance from ggml's vec_dot without affecting the exit code, so a kernel that silently diverged still reported 0 failures. Gate both at 1e-5 (measured 3e-8 and 1e-7, so 100x headroom). Verified: 0 failures at 1e-5, and with the threshold dropped to 1e-9 the gate fires on every layer.

Also corrects the comment above the gate/up dispatch: STRATA_NO_IQ512 drops an AVX-512 CPU to the AVX-2 kernel, not to ggml; ggml's vec_dot needs both switches set.
2026-09-28 18:34:44 +02:00
code-martin 51fce4c83e telemetry: per-request decode expert cache hit rate in DONE and web monitor
- Reset cache hits/lookups baseline at start of autoregressive decode to exclude prefill distortion
- Append req_hits and req_look to engine DONE line and log decode hit rate to stderr
- Parse decode hit metrics in server.py and record hit_rate per request in history
- Add Hit rate column to Recent requests table in web monitor
2026-09-28 18:59:58 +03:00
acrogenesis 6c812b2c51 Merge upstream Strata 0.1.18 while preserving Orca compatibility
Bring in 45 upstream commits through f32577e. Update the split-GGUF test fixture with router geometry required by upstream's dynamic expert counts. Preserve the Orca BF16 conversion and native PLE compatibility paths.

Validation: Release CUDA build for sm_120; 8 packing tests; 23 server tests; sampler, gated residual, and KV streaming GPU parity checks.
2026-09-28 08:52:08 -06:00
Alfir b45c40be6a Fix Windows PermissionError in get_llama_cpp() by using shutil.move instead of pathlib.replace 2026-09-28 22:40:36 +08:00
Jakub Luwierski 5f8ad8284e serve: the conversation cache keeps its shared prefix; the rest rotates LRU
The retained checkpoints are always a prefix chain - the request loop drops
any checkpoint that is not a prefix of the current prompt, because its
positional cells are gone (the KV cache is one arena, one branch of history
at a time).  A radix cache's tree collapsed onto the one branch the session
can hold, and the chain's root is the node a radix cache keeps while its
leaves rotate: in practice the end of the system prompt, which every new
chat of the same client mounts through.

First-in-first-out kept that node only by accident of being first: after
prompt_cache newer checkpoints it was gone, and the next chat re-read the
whole prefix at prefill speed (~30 s per 30K tokens).  Now the root is
pinned while the budget allows root and leaf apart (cap >= 2; below that
the old behaviour stands), the rest rotates by least recent use, and a
mount re-dates the checkpoint it mounted through.

The policy is one pure function (conv_cache.hpp) with its scenarios in
conv_cache_test.cpp; checkpoint_save/restore and the state format are
untouched, so STRATA_CKPT_REREAD's token-for-token guarantee holds.
2026-09-28 16:27:51 +02:00
pipeob0 f4820f507d generate: probe the real host->device bandwidth for the PCIe share
pcie_frac's defaults (0.55 native / 0.2 canonical) were measured on a PCIe 4.0 x16 link.
A x8 card in a x8 slot carries about half of that, and the copy engine's share then waits
for DMA that arrived late.  Probe the H2D bandwidth once at startup the way the engine uses
it (DMA reads from pinned host memory) and scale the default by it: an RTX 5060 Ti at x8
probes 14.1 GB/s -> pcie_frac 0.29 instead of 0.55.  --pcie-frac still wins when given, and
a machine that cannot run the probe keeps the current default.
2026-09-28 09:53:34 +02:00
acrogenesis b9da8e7bde Support Orca IQ3_XXS with explicit BF16 compatibility packing 2026-09-27 14:10:52 -06:00
108 changed files with 9945 additions and 283 deletions

No files matched your search

+19 -4
View File
@@ -8,7 +8,7 @@
# written against sm_120 (RTX 5000 / Blackwell) and silently building for an older arch would produce a
# binary that runs and is wrong about its own performance, which is the worst of both outcomes.
cmake_minimum_required(VERSION 3.24)
project(strata VERSION 0.1.19 LANGUAGES CXX)
project(strata VERSION 0.1.22 LANGUAGES CXX)
add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}")
# issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can
# be read back to the exact source line
@@ -56,7 +56,7 @@ if(STRATA_ENABLE_CUDA)
if(_base STREQUAL "native" OR _base STREQUAL "all" OR _base STREQUAL "all-major")
continue()
endif()
if(_base LESS 80)
if(_base LESS 80 AND NOT STRATA_EXPERIMENTAL_SM75) # the A/B of a Turing card as a layer-split stage
message(FATAL_ERROR
"Strata needs an NVIDIA GPU of compute capability 8.0 or newer (RTX 30 / 40 / 50 series), but "
"CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'.")
@@ -189,6 +189,7 @@ if(STRATA_ENABLE_CUDA)
src/kernels/cuda/fused_gr.cu
src/kernels/cuda/cvec.cu
src/kernels/cuda/qsa_decode_attn.cu
src/kernels/cuda/qsa_prompt_attn.cu
src/kernels/cuda/fused_gdn.cu
src/kernels/cuda/dequant_bf16.cu
src/kernels/cuda/qsa_select.cu
@@ -198,6 +199,13 @@ if(STRATA_ENABLE_CUDA)
src/ngram/ple_reader.cpp
src/platform/direct_file.cpp)
target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact)
# perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with
# the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON
if(STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN)
add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp)
target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart)
endif()
# plan v0.3 P6: llama.cpp's block layouts and codebook grids for the i-quant formats (MIT, third_party/ggml)
target_include_directories(strata_kernels PRIVATE third_party/ggml)
# Match the pinned llama.cpp CUDA arithmetic contract for this adapter only.
@@ -245,7 +253,7 @@ if(STRATA_ENABLE_CUDA)
# already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third
# library is the honest shape of the dependency graph: core knows about devices and weights, kernels know
# about arithmetic, and this one knows the ORDER the arithmetic happens in.
add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp
add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp
src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp)
target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu CUDA::cudart)
@@ -455,6 +463,10 @@ if(STRATA_BUILD_TESTS)
add_executable(draft_policy_test src/spec/draft_policy_test.cpp)
target_link_libraries(draft_policy_test PRIVATE strata_spec)
add_test(NAME draft_policy_test COMMAND draft_policy_test)
# the serve loop's conversation-cache retention policy (header-only, no library to link)
add_executable(conv_cache_test src/program/conv_cache_test.cpp)
target_include_directories(conv_cache_test PRIVATE include)
add_test(NAME conv_cache_test COMMAND conv_cache_test)
endif()
add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp
@@ -592,5 +604,8 @@ endif()
if(STRATA_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
# the unit tests above build from src/; the tests/ tree (model-level checks) is not part of the published repo
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt)
add_subdirectory(tests)
endif()
endif()
+10
View File
@@ -42,6 +42,13 @@ A card with more VRAM is faster, because more of the model fits on the GPU: an R
Every PC is different: `START-HERE.bat --calibrate` measures a few engine settings on yours and keeps the fastest
(about 5-10 minutes; on the PC above it made the Coder 7% faster).
**Two or three NVIDIA cards?** Just run `START-HERE.bat`: it lists your cards, says which ones Strata can use, and
asks whether to share the model across them (recommended when two can). An install made on one card asks once at
its next start. Or choose yourself: `START-HERE.bat --gpus 0,2` (both, remembered), `--gpus all`, or `--gpu 0` (one
card, this start only). Each card keeps the experts of its own layers, and prompts flow through the cards in a
pipeline: on an RTX 5080 + RTX 3090 prompts were read 18-20% faster than on the 5080 alone, decoding on par.
Every card must be an RTX 30 series or newer with 8 GB or more. See [docs/MULTI_GPU.md](docs/MULTI_GPU.md).
## Which model should I pick?
**The size** (the same model, compressed more or less):
@@ -74,6 +81,9 @@ lower the RAM needed.
Not sure? Take **IQ2_XS** - or the **Coder** if you mainly write code, or have 32-48 GB of RAM. You can add another
one later with `SETUP.bat` (the same as `START-HERE.bat --setup`; on Linux `./setup.sh --setup`).
For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](docs/ORCA.md).
It needs an explicit packing conversion and is not an installer menu option.
## Install
**You need:** an NVIDIA RTX 30, 40 or 50 card with 12 GB of VRAM or more, enough RAM for the size you pick (above),
@@ -0,0 +1,59 @@
# Layer split: the features that were off across GPUs (2026-09-29)
**Setup:**
- **Rig:** RIBPC. RTX 5080 16 GB (CUDA0) + RTX 3090 24 GB; RTX 2080 Ti 22 GB as a helper card. Ryzen 9 9950X3D,
62 GB RAM, Windows 11.
- **Model:** the Coder (IQ1_M native pack).
- **Build:** branch `mg/limits`, sm_75 + sm_86 + sm_120.
- **Correctness runs:** `rib_norepeat.py`, with a fixed cache, no swaps, no PCIe share and no suffix drafts where two
runs are compared byte for byte.
- **Speed runs:** `rib_pp.py`.
- Raw results are in `data/`.
## Correctness
| Check | Result |
|---|---|
| One GPU, this branch vs the 0.1.21-equivalent run (fixed cache) | 10/10 byte-identical |
| Speed projection (control vector), one GPU vs the split on the same GPU (K=24) | 10/10 byte-identical |
| KV streaming (128K context, 32K resident), one GPU vs the split on the same GPU | 10/10 byte-identical |
| Images, one GPU vs the split on the same GPU (three questions about a test picture) | identical answers |
| Speed projection / KV streaming / plain, 5080 + 3090 (K=24): no-repeat under presence 100, the 144 sanity case | all pass, 0 repeats |
| The vector acts across GPUs: 5080 + 3090 with vs without the vector | 8 of 10 answers differ (as on one GPU: 7 of 10) |
| Images, 5080 + 3090 (K=24): "What color is the circle?" / "What number?" / describe | "Red" / "42" / "A red circle, the number 42, and a blue square are displayed on a white background" |
| Mid-prompt checkpoint (every 16,384 tokens): a 19.5K prompt, then another sharing its first 18,600 tokens | one GPU and 5080 + 3090: reused 16,384, answer right |
| 5080 + 3090 (K=30) + a 2080 Ti helper holding 3,000 experts | all pass |
| `--mmap-experts` with the Coder (a native pack) | a clear start-up error: it needs a canonical pack's `experts.bin` (with or without a split) |
Across GPUs the text is not byte-identical to one GPU: experts that one card leaves to the CPU run on a GPU in the
split, and the two round differently.
## Speed
| Run | Prompt 16K / 28K / 60K tok/s | Decode story / code tok/s | Hits |
|---|---|---|---|
| KV streaming (128K), 5080 alone | 1,487 / 1,801 / 1,837 | 66.6 / 74.0 | 59-71% |
| KV streaming (128K), 5080 + 3090 auto | 1,685 / 1,957 / 1,968 | 75.8 / 97.0 | 96-97% |
| Speed projection, 5080 + 3090 auto | 1,813 / 2,053 / - | 77.0 / 103.6 | 96-97% |
| 5080 + 3090 (K=30), no helper | - | 62.5 / 85.2 | |
| 5080 + 3090 (K=30) + 2080 Ti helper | - | 43.0 / 63.7 | |
**The helper card makes it slower,** as it did without a split (bench/results/2026-09-29-layer-split). Its per-layer
round trip costs more than the CPU pool needs for the few experts it would take over. It stays supported: the
helpers take the visible GPUs no stage runs on and hold only experts no stage's cache holds. But it isn't
recommended.
## What changed
- **Per-device tables:** the image-position (mrope) table and the control vector's tables are now kept per device;
every stage's rope and steering kernels read their own device's copy. `cvec_set_enabled` switches the vector on
every device.
- **KV streaming:** each stage's session streams its own KV host copy (pinned, portable). The split no longer forces
it off.
- **Mid-prompt checkpoints:** `Prefill::on_stage_chunk` lets each stage save its part of a checkpoint when it has
read the chunk. The last stage assembles the parts: the earlier ones are a chunk ahead by then.
- **Helpers (`--expert-cache-remote`) with a split:** they take the visible devices after the stages, skip every
pair a stage's cache holds, and preflight and open on those devices.
- **Explicit `--expert-cache` with a split:** it is capped so CUDA0 keeps room for the prompt path's own buffers.
Without the cap, the first prompt failed with "device buffers ... do not fit".
- **`--mmap-experts`:** refused at start for a native pack, with the reason.
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 102,
"drafts_offered": 166,
"tok_s": 66.7,
"text": "The wind didn\u2019t just howl; it screamed. It tore through the iron gallery of the Blackwood Point Light, rattling the glass panes like a prisoner testing the bars of a cell.\n\nElias Thorne was not a man who feared the dark. He was a man who feared the silence.\n\nFor forty years, he had lived in the shadow of the Fresnel lens, a rotating eye of glass and brass that swept the Atlantic with a beam of pure, unyielding light. His job was simple: keep the light burning. Keep the logbook current. Keep the foghorn sounding when the mist rolled in, thick as wool.\n\nBut Elias knew something else. He knew that the light was not just for ships. It was for the lost.\n\nIt was November 14th, 1982. The storm was a Category 5, a monster that had swallowed the horizon. The waves were mountains of black water, crashing against the granite"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 134,
"drafts_offered": 180,
"tok_s": 80.8,
"text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 72.5,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 74.6,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 104,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 92,
"tok_s": 45.4,
"text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 72,
"repeats": 0,
"drafts_accepted": 15,
"drafts_offered": 70,
"tok_s": 46.1,
"text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds on an open sore skin\u2014like a wound left unhealed by time. Elias knew this rhythm better than he remembered his own name<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 26,
"drafts_offered": 76,
"tok_s": 49.3,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to break its rhythm against stone that refused be broken by anything less than God himself had forged into being willing and able withstand eternity\u2019s cruelty without complaint or mercy from start finish until now forevermore if any such concept even existed within human comprehension let alone divine authority which we all knew did not exist but wished it would because wishful thinking is always easier to imagine hopelessly impossible truths as probable lies than vice versa.\n\nElias Thorne was eighty-three years old today, exactly one hundred and forty-seven days since his last heart attack had been logged by Dr Armitage who himself retired seven months ago after receiving a subpoena from the county clerk indicating he might have overstayed professional courtesy boundaries"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 94,
"repeats": 0,
"drafts_accepted": 27,
"drafts_offered": 56,
"tok_s": 46.7,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nBoar \nRabbit \nSquirrel <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 62.4,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 37,
"drafts_offered": 148,
"tok_s": 56.4,
"text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration by humans throughout human civilization; or perhaps more specifically in modern times refers often used metaphorically for economic trends like stock market fluctuations (\"sea change\"). However given your request likely intends an academic-style comprehensive overview covering both natural science aspects AND cultural significance through time periods\u2014especially since this kind question appears frequently on exams asking students write essays discussing evolution from primordial origins up present-day impacts including environmental changes due climate crisis etc.\u2014I will craft such broad yet structured piece combining geology + anthropology/ecological impact together while maintaining coherent flow suitable high-level educational context without overly technical jargon but still accurate enough scientifically grounded facts where appropriate within reasonable scope limits typical school assignments expect (~80\u201312% word count range implied implicitly though not stated explicitly here we aim moderate length ~65 words? Wait no user said \u201clong\u201d so probably >3k+ characters minimum safe bet around 7-9 paragraphs total approximating maybe close-to-full-page standard double-spaced equivalent which translates roughly \u22654K chars safely acceptable). Let me proceed accordingly ensuring clarity structure intro body conclusion style formal tone neutral informative balanced perspective acknowledging uncertainties if any minor ones exist e.g exact dates vary depending sources hence use hedging language sparingly only when necessary avoid overclaiming certainty especially regarding speculative theories vs established consensus knowledge base current mainstream understanding circa early-mid"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 102,
"drafts_offered": 166,
"tok_s": 67.1,
"text": "The wind didn\u2019t just howl; it screamed. It tore through the iron gallery of the Blackwood Point Light, rattling the glass panes like a prisoner testing the bars of a cell.\n\nElias Thorne was not a man who feared the dark. He was a man who feared the silence.\n\nFor forty years, he had lived in the shadow of the Fresnel lens, a rotating eye of glass and brass that swept the Atlantic with a beam of pure, unyielding light. His job was simple: keep the light burning. Keep the logbook current. Keep the foghorn sounding when the mist rolled in, thick as wool.\n\nBut Elias knew something else. He knew that the light was not just for ships. It was for the lost.\n\nIt was November 14th, 1982. The storm was a Category 5, a monster that had swallowed the horizon. The waves were mountains of black water, crashing against the granite"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 134,
"drafts_offered": 180,
"tok_s": 81.0,
"text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 62.4,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 73.4,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 104,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 92,
"tok_s": 43.5,
"text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 72,
"repeats": 0,
"drafts_accepted": 15,
"drafts_offered": 70,
"tok_s": 46.1,
"text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds on an open sore skin\u2014like a wound left unhealed by time. Elias knew this rhythm better than he remembered his own name<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 26,
"drafts_offered": 76,
"tok_s": 48.9,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to break its rhythm against stone that refused be broken by anything less than God himself had forged into being willing and able withstand eternity\u2019s cruelty without complaint or mercy from start finish until now forevermore if any such concept even existed within human comprehension let alone divine authority which we all knew did not exist but wished it would because wishful thinking is always easier to imagine hopelessly impossible truths as probable lies than vice versa.\n\nElias Thorne was eighty-three years old today, exactly one hundred and forty-seven days since his last heart attack had been logged by Dr Armitage who himself retired seven months ago after receiving a subpoena from the county clerk indicating he might have overstayed professional courtesy boundaries"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 94,
"repeats": 0,
"drafts_accepted": 27,
"drafts_offered": 56,
"tok_s": 46.8,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nBoar \nRabbit \nSquirrel <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 63.1,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 37,
"drafts_offered": 148,
"tok_s": 56.6,
"text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration by humans throughout human civilization; or perhaps more specifically in modern times refers often used metaphorically for economic trends like stock market fluctuations (\"sea change\"). However given your request likely intends an academic-style comprehensive overview covering both natural science aspects AND cultural significance through time periods\u2014especially since this kind question appears frequently on exams asking students write essays discussing evolution from primordial origins up present-day impacts including environmental changes due climate crisis etc.\u2014I will craft such broad yet structured piece combining geology + anthropology/ecological impact together while maintaining coherent flow suitable high-level educational context without overly technical jargon but still accurate enough scientifically grounded facts where appropriate within reasonable scope limits typical school assignments expect (~80\u201312% word count range implied implicitly though not stated explicitly here we aim moderate length ~65 words? Wait no user said \u201clong\u201d so probably >3k+ characters minimum safe bet around 7-9 paragraphs total approximating maybe close-to-full-page standard double-spaced equivalent which translates roughly \u22654K chars safely acceptable). Let me proceed accordingly ensuring clarity structure intro body conclusion style formal tone neutral informative balanced perspective acknowledging uncertainties if any minor ones exist e.g exact dates vary depending sources hence use hedging language sparingly only when necessary avoid overclaiming certainty especially regarding speculative theories vs established consensus knowledge base current mainstream understanding circa early-mid"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 85,
"drafts_offered": 172,
"tok_s": 36.6,
"text": "The wind didn\u2019t just howl; it screamed. It tore through the gaps in the iron railing of the Lantern Room, carrying the scent of brine and rotting kelp. Elias pulled his woolen collar up to his chin, his fingers numb and clumsy inside thick leather gloves.\n\nHe was the last man on the island. The automated systems had failed three winters ago, a glitch in the solar-powered backup that no engineer had been able to fix before the supply boat stopped coming. Now, it was just him, the light, and the sea.\n\nElias climbed the spiral stairs, his boots heavy with salt spray. The iron steps groaned under his weight, a sound that seemed to mock the storm outside. He reached the top, the glass walls vibrating with the force of the gale. Outside, the world was a blur of black and white. The ocean was invisible; it was only a presence, a weight pressing against the stone foundation of the tower.\n\nHe"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 136,
"drafts_offered": 173,
"tok_s": 96.8,
"text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 88.7,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 94.1,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 104,
"repeats": 0,
"drafts_accepted": 30,
"drafts_offered": 96,
"tok_s": 55.9,
"text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 114,
"tok_s": 55.4,
"text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds at this one\u2019s age: forty-three winters since its construction. My name was Elias Thorne\u2014no middle initial\u2014and I kept no logbook for visitors because there were none; only ships passed by, their hulls cutting through the black water as if they too feared what lay beneath it more than above or beside them in fog so thick that even my own reflection vanished from sight when looked upon directly.\n\nI climbed each morning not to greet dawn but check whether light still lived within me\u2014the bulb\u2019s heart had failed twice before, once during a storm named *Harrow*,"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 110,
"tok_s": 52.2,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to hold onto until I died.\u201d said Elias Thorne as he adjusted his collar against November\u2019s bite.** He was not merely complaining of cold weather but articulating a poetic metaphor: that even after death (metaphorically), there would be no relief from this relentless gale.\n\nElias had been the last human keeper on any significant stretch coast since automation became standard practice, yet here he stood , stubbornly refusing to let technology replace his vigilance . His cottage perched atop a crumbling granite foundation was more than just shelter; it housed centuries of handwritten logs detailing every ship\u2019s name and cargo load that passed within sight.\n\nOn most nights Elias tended the light mechanically\u2014"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 91,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 69,
"tok_s": 58.7,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippopotamus \nRhinoceros \nLeopard \nCheetah \nPanther \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nDog \nCat<|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 12,
"repeats": 0,
"drafts_accepted": 4,
"drafts_offered": 17,
"tok_s": 60.3,
"text": "1 2,3456789<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 41,
"drafts_offered": 168,
"tok_s": 59.9,
"text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration histories (\"history at/over/across/on/in/of/to/from/toward/off by means around above below through under upon alongside against among between within without throughout despite during after before since until while when where who whom whose which what how why whether\"), or perhaps even metaphorical interpretations involving human interaction with water bodies over time periods like ages eras epochs generations centuries decades years months days hours minutes seconds moments instants times occasions instances events episodes incidents occurrences situations circumstances conditions states phases stages steps processes procedures sequences series chains cycles loops repetitions iterations continuations progressions developments evolutions transformations changes alterations modifications adjustments corrections revisions amendments updates upgrades improvements enhancements refinements optimizations perfecting completing finishing concluding ending terminating ceasing stopping halting pausing resuming continuing proceeding advancing progressing moving shifting translating rotating reflecting mirroring flipping turning twisting bending curving arches spirals helix coils twists turns rotations reflections mirrors flips inversions reversings reversion backtracking retracing reversing undo redo do again repeat repeats repeated repeatedly repetition repetitive repetitiveness repete repeater repeatingly recurrent recurrence recurring recurs recur recurred recursion recursive recursively recurse recessed recessionary regress regression regressed retrograde reverse reversed reversal revert reverted reverberate resonated echo echoed echoing echoes echolocation sonar radar radio telecommunication communication communications communicate communicated communicating communicative comms comm chatter chat chats chatting chatted talk talks talked"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 88,
"drafts_offered": 171,
"tok_s": 62.5,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from broken glass and rusted iron, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, ensuring the rotation was smooth, silent, and precise. *Tick. Tick. Tick.* The sound was the heartbeat of the coast."
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 135,
"drafts_offered": 184,
"tok_s": 85.2,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 78.1,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 80.5,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 59,
"repeats": 0,
"drafts_accepted": 13,
"drafts_offered": 48,
"tok_s": 46.6,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \n\nCat \nCheetah \n\nChimpanzee \nClam \n\n\nCrocodile \n\n\n\nDolphin \n\n\n\n\nDonkey <|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 30,
"drafts_offered": 101,
"tok_s": 51.3,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots smelled faintly brine and old coffee as he climbed spiral stairs worn smooth by decades feet his hands were calloused from gripping iron railings that had been polished to a dull shine\n\nElias was not merely keeping light alive; He kept order intact. Every night, at precisely 18:07 hours local time\u2014adjusted for leap seconds and magnetic drift\u2014he wound the clockwork mechanism inside brass housing behind Fresnel lens This wasn\u2019t vanity It\u2019s necessity The rotation speed must remain constant or ships lose their bearing in fog where compasses fail\n\nHe spoke softly to himself while working, murmuring numbers aloud because silence made him"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 67,
"repeats": 0,
"drafts_accepted": 14,
"drafts_offered": 68,
"tok_s": 41.2,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, like he had no mouth to hold back its fury anymore that night.\u201d Elara pulled her wool coat tighter around herself as she climbed spiral staircase of **Blackrock Lighthouse**. Her boots were slick with salt spray from previous days.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 91,
"repeats": 0,
"drafts_accepted": 26,
"drafts_offered": 54,
"tok_s": 48.8,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nJaguar \nBear \nWolf \nFox \nDog \nCat \nMouse \nRat \nSquirrel \nDeer \n\nAntelope \n\nBuffalo \n\n\nBison \n\n\n\nElk \n\n\n\n\nMoose <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 11,
"tok_s": 68.8,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 32,
"drafts_offered": 107,
"tok_s": 52.3,
"text": "The ocean is not merely water; it has been, and remains to this day one giant storybook that weaves together geology with biology as wellas human culture into an epic narrative spanning billions years from its earliest beginnings in primordial times through modern-day ecological crises The vast expanse covers more than seventy percent Earth\u2019s surface area making up nearly all life support systems on our planet yet despite being so large humans have only explored less five thousand square kilometers out total 361 million km\u00b2 which means over ninety-nine point nine eight six per cent unexplored territory This makes oceans arguably larger unknown territories compared space exploration where NASA estimates they\u2019ve mapped roughly ten billion stars versus current marine surveys covering just two hundred fifty-six species documented globally against estimated millions undiscovered organisms including deep-sea creatures like anglerfish or vampire squid whose existence was first recorded centuries ago but still remain poorly understood due extreme pressures depths exceeding eleven miles below Pacific Trenches Mariana located near Guam island chain reaching maximum depth known today at approximately thirty-seven feet under pressure equivalent atmospheric levels causing structural collapse if unprotected by specialized vessels capable handling such conditions without failure mechanisms designed specifically for submersible operations operating within these zones require titanium hulls rated withstand forces greater gravity acting upon objects falling vertically downward acceleration rates calculated using Newtonian physics principles applied universally across gravitational fields regardless medium density variations present throughout different layers stratosphere troposphere mesospheres thermoclines etceterally speaking however when discussing aquatic environments instead air masses replace gases dissolved oxygen nitrogen arg"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 94,
"drafts_offered": 169,
"tok_s": 43.0,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a small, drafty cottage that smelled perpetually of kerosene and damp wood.\n\nFor decades, Elias had tended the great Fresnel lens, polishing the glass prisms until they gleamed like diamonds, winding the clockwork mechanism that turned the beam, and trimming the wick of the oil lamp. It was a job of patience, of precision, of silence. The light was his charge. The sea was his neighbor.\n\nBut this morning, the sea was not his neighbor. It was his enemy.\n\nThe storm had been forecasted for three days, but it had arrived in one. The barometric pressure had dropped so sharply that Elias\u2019s ears popped."
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 136,
"drafts_offered": 178,
"tok_s": 63.7,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 56.8,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 57.7,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 94,
"repeats": 0,
"drafts_accepted": 24,
"drafts_offered": 49,
"tok_s": 43.3,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nHippopotamus \nRhinoceros \nCheetah \nLeopard \nJaguar \nPuma \nWolf \nFox \nBear \nDeer \nElk \nMoose \nAntelope \nBison \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nDog \nCat \nRabbit \nMouse \nHamster \nGuinea Pig<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 35,
"drafts_offered": 108,
"tok_s": 41.4,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots smelled faintly brine and old coffee as he climbed spiral stairs worn smooth by decades feet his hands were calloused from gripping iron railings that had been polished to a dull shine.\n\nElias wasn\u2019t just keeping light; was guarding silence the beam swept across black water every seven seconds cutting through fog so thick it swallowed sound entirely for three nights straight no ships answered its signal not even fishing trawlers seeking shelter they\u2019d long abandoned this stretch of coast where currents shifted unpredictably pulling debris from sunken wrecks into tangled heaps that snagged anchors and tore hulls open like wounds.\n\nHe remembered the last time someone had"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 59,
"repeats": 0,
"drafts_accepted": 11,
"drafts_offered": 46,
"tok_s": 33.7,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, trying to pry them apart like loose planks of weathered oak outside your own mouth again and then you are going away from home is fine but for now let me write a proper story.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 60,
"repeats": 0,
"drafts_accepted": 17,
"drafts_offered": 48,
"tok_s": 43.2,
"text": "Aardvark \nAntelope allonax (Oryx) \u2013 *Note: Using standard names for clarity* \n\nLet me provide a clean list of exactly **1** animal name on each single physical text file/terminal output stream with no other characters except the newline (\\n).<|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 11,
"tok_s": 48.9,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 27,
"drafts_offered": 105,
"tok_s": 40.2,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element\u2014it became civilization itself through its capacity as both barrier (to land) but also conduit between lands\u2014and thus gave rise directly from being part nature\u2019s own evolutionary engine into becoming humanity's greatest historical actor across all time scales since first emergence until now present-day future projections still ongoing today within our current era context window limits allowed here by system constraints set above threshold levels required before output generation begins below line break marker inserted immediately after final punctuation mark ending entire preceding paragraph block structure defined earlier during initial drafting phase prior execution stage completed successfully without errors detected internally via internal validation routines executed automatically upon completion cycle termination signal received end-of-file condition triggered correctly according standard protocol specifications followed strictly adhered-to throughout process flow control logic implemented using structured programming constructs compatible with target runtime environment configuration parameters specified herein explicitly declared beforehand at top-level scope declaration section located near beginning source code file header comments included inline documentation style guidelines observed consistently applied uniformly everywhere else similarly formatted sections appearing later down document body text area scrolling vertically downward directionally aligned left margin justified right edge wrapped around fixed-width column boundaries determined dynamically based available screen real estate measured pixel-per-unit scaling factor adjusted responsively depending viewport dimensions reported back client-side rendering pipeline components responsible"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 94,
"drafts_offered": 167,
"tok_s": 62.7,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to hold the chaos of the ocean at bay. The beam swept out, a blade of pure, concentrated light cutting through the rain and sleet, illuminating the jagged teeth of the reef below.\n\n"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 136,
"drafts_offered": 179,
"tok_s": 81.3,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 71.0,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 71.9,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 61,
"repeats": 0,
"drafts_accepted": 18,
"drafts_offered": 52,
"tok_s": 47.9,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFalcon <|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 122,
"tok_s": 47.4,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach his post at dawn every morning for thirty years. His name was written on a brass plaque by door: **Elias Thorne**.\n\nHe wasn\u2019t just keeping light; He kept time, weathered hands gripping the cold iron railing until knuckles turned white against frostbite and windburn that never healed fully because they were always there waiting to be felt again when he stepped outside into storm or calm alike. The lens above him was a Fresnel giant\u2019s eye made of hand-ground crystal prisms each one polished daily with chamois cloth soaked in whale"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 65,
"repeats": 0,
"drafts_accepted": 11,
"drafts_offered": 58,
"tok_s": 42.6,
"text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they slammed against their hinges every night for eleven months of winter and summer alike.\u201d I had never seen calm water here\u2014only gray churning seas that swallowed ships smaller than themselves<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 101,
"repeats": 0,
"drafts_accepted": 32,
"drafts_offered": 53,
"tok_s": 49.4,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nHyena \nJackal \nAntelope \nBison \nElk \nCaribou \nLlama \nAlpace <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 12,
"tok_s": 64.7,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 52,
"drafts_offered": 148,
"tok_s": 49.9,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by hundreds millions years yet continues shaping every aspect from climate regulation through evolutionary biology down even into modern industrial logistics today's global supply chains depend upon them directly indirectly via atmospheric pressure systems weather patterns migration routes food webs carbon cycles oxygen generation thermal buffering tidal forces salinity gradients depth stratification light attenuation currents circulation gyres upwelling zones thermoclines halothermics bathymetric features continental shelves abyssal plains trenching ridges volcanic arcs island formations atoll structures seamounts submarine canons canyon walls cliff faces overhang ledge platforms reef flats fore-reef back-lagoon inner-shelf outer-slope drop-offs pinnacle pinnacles spires columns arches tunnels caves grottos swim-through passages chimney vents blowholes fissures cracks crevices joints faults fractures breaks gaps holes openings void spaces hollow chambers cavernous interiors subterranean networks underground rivers lakes pools springs wells shaft pits sinks drains sewers pipes conduits tubes channels gutters ditches furrows grooves rills runnels streams brooks rivulets creeks tributaries branches forks splits divergences con"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 94,
"drafts_offered": 167,
"tok_s": 49.2,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to hold the chaos of the ocean at bay. The beam swept out, a blade of pure, concentrated light cutting through the rain and sleet, illuminating the jagged teeth of the reef below.\n\n"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 136,
"drafts_offered": 179,
"tok_s": 76.2,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 73.1,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 73.4,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 61,
"repeats": 0,
"drafts_accepted": 18,
"drafts_offered": 52,
"tok_s": 47.1,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFalcon <|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 122,
"tok_s": 47.0,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach his post at dawn every morning for thirty years. His name was written on a brass plaque by door: **Elias Thorne**.\n\nHe wasn\u2019t just keeping light; He kept time, weathered hands gripping the cold iron railing until knuckles turned white against frostbite and windburn that never healed fully because they were always there waiting to be felt again when he stepped outside into storm or calm alike. The lens above him was a Fresnel giant\u2019s eye made of hand-ground crystal prisms each one polished daily with chamois cloth soaked in whale"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 65,
"repeats": 0,
"drafts_accepted": 11,
"drafts_offered": 58,
"tok_s": 42.3,
"text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they slammed against their hinges every night for eleven months of winter and summer alike.\u201d I had never seen calm water here\u2014only gray churning seas that swallowed ships smaller than themselves<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 101,
"repeats": 0,
"drafts_accepted": 32,
"drafts_offered": 53,
"tok_s": 50.0,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nHyena \nJackal \nAntelope \nBison \nElk \nCaribou \nLlama \nAlpace <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 12,
"tok_s": 64.6,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 52,
"drafts_offered": 148,
"tok_s": 49.8,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by hundreds millions years yet continues shaping every aspect from climate regulation through evolutionary biology down even into modern industrial logistics today's global supply chains depend upon them directly indirectly via atmospheric pressure systems weather patterns migration routes food webs carbon cycles oxygen generation thermal buffering tidal forces salinity gradients depth stratification light attenuation currents circulation gyres upwelling zones thermoclines halothermics bathymetric features continental shelves abyssal plains trenching ridges volcanic arcs island formations atoll structures seamounts submarine canons canyon walls cliff faces overhang ledge platforms reef flats fore-reef back-lagoon inner-shelf outer-slope drop-offs pinnacle pinnacles spires columns arches tunnels caves grottos swim-through passages chimney vents blowholes fissures cracks crevices joints faults fractures breaks gaps holes openings void spaces hollow chambers cavernous interiors subterranean networks underground rivers lakes pools springs wells shaft pits sinks drains sewers pipes conduits tubes channels gutters ditches furrows grooves rills runnels streams brooks rivulets creeks tributaries branches forks splits divergences con"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 97,
"drafts_offered": 176,
"tok_s": 73.0,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was the last of the line, the only man left on the jagged spine of Widow\u2019s Rock. For forty years, he had tended the light. For forty years, he had listened to the ocean\u2019s endless, hungry whisper.\n\nTonight was different. The storm wasn\u2019t just a storm; it was a *tempest*. The waves didn\u2019t crash; they *shattered*. They threw themselves against the granite base of the lighthouse with the force of a battering ram, sending tremors up through the soles of Elias\u2019s boots.\n\nHe climbed the spiral stairs, one hundred and twelve steps of iron and rust. His hand, calloused and scarred from decades of polishing the brass railing, found the familiar groove in the metal. He didn\u2019t look up. He didn\u2019t look down. He looked *forward*."
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 135,
"drafts_offered": 176,
"tok_s": 102.5,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 90.9,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 91.7,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 118,
"repeats": 0,
"drafts_accepted": 38,
"drafts_offered": 103,
"tok_s": 62.8,
"text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 58,
"repeats": 0,
"drafts_accepted": 9,
"drafts_offered": 63,
"tok_s": 50.4,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty jail cell below sea level three hundred feet down to where Elias kept his boots dry and ready for emergencies when he had no time even think about changing them.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 140,
"repeats": 0,
"drafts_accepted": 22,
"drafts_offered": 90,
"tok_s": 50.1,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, demanding entry into every crack and crevice of Stone Harbor Lighthous eKeepers have always been solitary figures against isolation\u2019s greatest adversary: time itself Elias Thorne knew this intimately. For thirty years he had kept watch over one hundred thousand ships each night scanning for lights that might signal disaster or hope\n\nHis job was simple but deadly serious He checked weather logs every day without fail The foghorn echoed through the tower three times before dawn Each morning at 4:02 AM Elias would climb eighty-two steps to reach his office where coffee cooled beside a single candle flickering in drafts from below<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 96,
"repeats": 0,
"drafts_accepted": 31,
"drafts_offered": 69,
"tok_s": 58.9,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nPanther \nCougar \nBear \nWolf \nFox \nDeer \nElk \nMoose \nBison \nBuffalo \nAntelope \nCamel \nDonkey \nGoat \nSheep \nCow \nPig \nHorse <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 71.2,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 37,
"drafts_offered": 119,
"tok_s": 61.3,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth\u2019s surface.\u201d \u2014 *This quote by Rachel Carson serves as an apt introduction.* The story we tell today begins with that first drop falling into primordial pools billions years ago\u2014but what follows next? What happens when those drops become oceans themselves\u2014when they begin moving across continents carrying sediment from mountains down rivers until finally reaching their final resting place at last\u2014the deep abyssal plains where sunlight cannot reach nor pressure crushes everything else alive there below depths greater than six kilometers beneath waves crashing against shores above them all around world forever changing shape over time due plate tectonics shifting landmass slowly apart together again repeatedly throughout geological epochs spanning hundreds millions or even thousands million+ yrs since formation early Hadean era through Archeozoic eons onward present Holocene epoch still ongoing now right here under current conditions observed via satellites monitoring global climate patterns affecting currents temperatures salinity levels biodiversity distribution human impacts altering ecosystems directly indirectly causing extinction events locally globally recently historically prehistorically anciently mythologically culturally spiritually philosoph scientifically mathematically physically chem biol geo astro cosmological sociopolitical economic environmental ecological evolutionary genetic linguistic literary artistic musical cinematic theatrical photographic journalistic digital analog virtual real tangible intangible metaphysical ontosemantic semiotic symbolic allegorical narrative descriptive analytical interpretive evaluative critical reflective introspective contemplatory ponderous thoughtful considerate attentive observant perceptive insightful intelligent knowledgeable informed educated literati learned skilled capable"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 87,
"drafts_offered": 170,
"tok_s": 71.4,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and green.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, listening for the faint, rhythmic *tick-tick-tick* that signaled the rotation was true. If the rhythm faltered, ships"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 136,
"drafts_offered": 178,
"tok_s": 104.1,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 90.1,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 94.8,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 76,
"repeats": 0,
"drafts_accepted": 20,
"drafts_offered": 64,
"tok_s": 61.6,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \nButterfly \nCamel \nCat \nCaterpillar \n\nCentipede \n\nChameleon \n\nCheetah \n\nChicken \n\nCricket \n\nCrocodile \n\n\nDolphin \n\n\n\nDonkey \n\n\n\n\nDragon<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 21,
"drafts_offered": 90,
"tok_s": 59.2,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty jail cell below sea level to above cloud height at once\u2014no matter how high you climbed or deep into its foundations down through rock and saltwater. It was November again when Elias first noticed that his logbook had begun recording entries he hadn\u2019t written yet: *Storm surge expected Tuesday, but the sky is clear.*\n\nHe stopped writing for a moment to listen\u2014not with ears alone\u2014but by pressing both palms flat against cold iron walls where condensation formed in slow spirals like fingerprints left behind after touching something invisible. The metal hummed faintly beneath his skin as if remembering old storms long past their dates on paper calendars torn from newspapers dated three years ahead of today"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 17,
"drafts_offered": 63,
"tok_s": 52.6,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, trying to get inside where he had spent thirty years refusing entry except for family and friends like him who were old enough too know better than young men ever could be again about what safety meant. It was November 2014 when Elias Thorne first stepped onto that spiral staircase with only one boot on because his other foot hurt after walking from the harbor office all morning long before anyone else thought he needed shoes off there for work even if nobody saw them do it but everyone knew why so they did not ask him anymore once this happened already twice last winter near same season now here again today too soon then tomorrow maybe never will come back unless someone sends message tonight via radio signal code Morse dot dash pattern"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 94,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 60,
"tok_s": 58.8,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nKangaroo \nPanda \nKoala \nCheetah \nWolf \nFox \nBear \nMonkey \nDolphin \nWhale \nShark \nOctopus \nJellyfish \nCrab \nSpider \nRabbit \nCat \nDog \nHorse \nCow \nSheep \nGoat \nChicken \nRooster \nTurkey \nEagle \nFalcon <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 71.8,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 52,
"drafts_offered": 148,
"tok_s": 61.8,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\u201d \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \u201cthe Sea\u201d or \"Ocean\" (terms often used interchangeably but distinct geographically) was never just an element within our planet\u2019s geography\u2014it became its engine itself\u2014a living system whose evolution shaped everything else around us from climate patterns down through evolutionary biology right up into modern civilization's economic structures cultural identities political boundaries ecological systems scientific understanding technological capabilities philosophical frameworks psychological experiences artistic expressions literary metaphors cinematic narratives musical compositions architectural designs urban planning strategies agricultural practices industrial processes medical discoveries legal precedents educational curricula religious traditions spiritual beliefs mythological stories folkloric tales poetic verses dramatic scripts visual arts photographic images digital media social networks behavioral norms emotional responses cognitive models decision-making algorithms predictive analytics statistical probabilities probabilistic reasoning causal inference counterfactual thinking hypothetical scenarios normative ethics deontal logic modal semantics temporal dynamics spatial relations topographical features hydrological cycles meteor phenomena atmospheric chemistry geological formations tectonic shifts volcanic eruptions seismic events tsunamis hurricanes cyclones monsoons typhoons droughts floods storms winds currents waves swells breakers surf foam spray mist fog rain snow ice glaciers berg floes drift pack-ice brine salinity pH alkalines acidity hardness softness temperature pressure depth light darkness color hue saturation brightness contrast luminance chroma tone value shade tint reflection"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 88,
"drafts_offered": 187,
"tok_s": 58.7,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 135,
"drafts_offered": 179,
"tok_s": 80.7,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 71.8,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 73.0,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 61,
"repeats": 0,
"drafts_accepted": 19,
"drafts_offered": 49,
"tok_s": 49.1,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 80,
"repeats": 0,
"drafts_accepted": 6,
"drafts_offered": 52,
"tok_s": 46.2,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 17,
"drafts_offered": 83,
"tok_s": 43.9,
"text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 62,
"repeats": 0,
"drafts_accepted": 18,
"drafts_offered": 31,
"tok_s": 49.1,
"text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 62.7,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 47,
"drafts_offered": 153,
"tok_s": 52.2,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules"
}
]
@@ -0,0 +1,84 @@
{
"label": "lim-cv-pp-x2",
"extra": [
"--layer-split",
"auto",
"--control-vector-scaled",
"C:\\Users\\ribbon\\strata-test\\Strata\\data\\experimental-speed-projection\\Qwen3.8-Flash-Next-experimental-speed-projection.gguf:1.0",
"--control-vector-layer-range",
"4",
"44",
"--cvec-mode",
"project",
"--cvec-dir",
"per-layer"
],
"gpus": "0,2",
"needles": [
{
"tokens": 15925,
"prompt_ms": 8783.1,
"pp_tok_s": 1813.1,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27474,
"prompt_ms": 13379.7,
"pp_tok_s": 2053.4,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3652.4,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 246.8,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 77.0,
"reps": [
77.0
],
"hit_rate": 0.9718150054476462,
"text": "The wind didn\u2019t just howl; it screamed. It tore through the gaps in the iron railing of the Lantern Room, carrying the scent of brine and rotting kelp. Elias pulled his woolen collar up to his chin, his fingers numb and clumsy inside thick leather gloves.\n\nHe was the last man on the island. The automated systems had failed three winters ago, a glitch in the solar panel array that no engineer had been able to fix before the supply boat stopped running. Now, it was just him, the light, and the sea.\n\nElias climbed the spiral stairs, his boots heavy with salt spray. The iron steps groaned under his weight, a sound that seemed to mock the storm outside. He reached the top, the glass walls vibrating with the force of the gale.\n\nInside the lantern room, the great Fresnel lens sat like a dormant eye. It was cold, dark, and waiting.\n\nElias moved to the control panel. His"
},
{
"name": "code",
"tok_s": 103.6,
"reps": [
103.6
],
"hit_rate": 0.957731667226356,
"text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False"
}
],
"stage_timing": [],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts",
"strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts",
"strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 3479 slots, 6.22 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-21",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 91.6% (5554 hits / 6062 lookups)",
"strata serve: decode expert cache hit rate: 95.3% (3592 hits / 3771 lookups)",
"strata serve: decode expert cache hit rate: 96.5% (3650 hits / 3782 lookups)",
"strata serve: decode expert cache hit rate: 96.3% (25027 hits / 25980 lookups)",
"strata serve: decode expert cache hit rate: 96.5% (3201 hits / 3318 lookups)",
"strata serve: decode expert cache hit rate: 97.2% (129334 hits / 133085 lookups)",
"strata serve: decode expert cache hit rate: 95.8% (108375 hits / 113158 lookups)"
]
}
@@ -0,0 +1,76 @@
{
"label": "lim-kv-pp-single",
"extra": [
"--max-context",
"131072",
"--kv-resident",
"32768"
],
"gpus": "0",
"needles": [
{
"tokens": 15925,
"prompt_ms": 10706.3,
"pp_tok_s": 1487.4,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27474,
"prompt_ms": 15256.7,
"pp_tok_s": 1800.8,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 59725,
"prompt_ms": 32515.5,
"pp_tok_s": 1836.8,
"found": true,
"answer": "falcon-174<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4006.4,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 276.2,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 66.6,
"reps": [
66.6
],
"hit_rate": 0.7101864314556545,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to sync with his own heartbeat. He had been doing this for forty years. His hands were mapped with scars from rope burns and broken glass, his eyes permanently squinted against the glare of the bulb."
},
{
"name": "code",
"tok_s": 74.0,
"reps": [
74.0
],
"hit_rate": 0.5873783774988882,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [],
"engine_lines": [
"strata generate: expert cache auto: 8.99 GiB free, 700 MiB reserved -> 3349 slots",
"strata generate: expert cache 2434 slots, 4.67 GiB of VRAM; policy is",
"strata serve: the prompt path borrows 1944 cache slots (3.72 GiB)",
"strata serve: decode expert cache hit rate: 41.8% (1746 hits / 4176 lookups)",
"strata serve: decode expert cache hit rate: 50.4% (1512 hits / 3000 lookups)",
"strata serve: decode expert cache hit rate: 54.9% (1689 hits / 3077 lookups)",
"strata serve: decode expert cache hit rate: 60.3% (1938 hits / 3213 lookups)",
"strata serve: decode expert cache hit rate: 58.3% (11146 hits / 19121 lookups)",
"strata serve: decode expert cache hit rate: 66.1% (2201 hits / 3331 lookups)",
"strata serve: decode expert cache hit rate: 71.0% (74397 hits / 104757 lookups)",
"strata serve: decode expert cache hit rate: 58.7% (54151 hits / 92191 lookups)"
]
}
@@ -0,0 +1,87 @@
{
"label": "lim-kv-pp-x2",
"extra": [
"--max-context",
"131072",
"--kv-resident",
"32768",
"--layer-split",
"auto"
],
"gpus": "0,2",
"needles": [
{
"tokens": 15925,
"prompt_ms": 9452.6,
"pp_tok_s": 1684.7,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27474,
"prompt_ms": 14042.4,
"pp_tok_s": 1956.5,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 59725,
"prompt_ms": 30345.9,
"pp_tok_s": 1968.1,
"found": true,
"answer": "falcon-174<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3806.1,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 245.6,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 75.8,
"reps": [
75.8
],
"hit_rate": 0.9698055042592483,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He stood before the great Fresnel lens, a cathedral of glass and brass that caught the light of the single, powerful bulb and fractured it into a thousand beams.\n\nHe checked the clock. 11:42 PM. The rotation was smooth, silent, a hypnotic sweep that painted the darkness with a slow, rhythmic pulse. *Flash. Dark. Flash. Dark.*\n\nE"
},
{
"name": "code",
"tok_s": 97.0,
"reps": [
97.0
],
"hit_rate": 0.9562207324057541,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 17.96 GiB free",
"strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.13 GiB for experts",
"strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 13.98 GiB for experts",
"strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11199 of 12288 profiled pairs (~99.7% of the routed mass)",
"strata generate: expert cache auto: 10.30 GiB free, 700 MiB reserved -> 3277 slots",
"strata generate: expert cache 3409 slots, 6.09 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-21",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 91.3% (5098 hits / 5585 lookups)",
"strata serve: decode expert cache hit rate: 94.7% (4000 hits / 4225 lookups)",
"strata serve: decode expert cache hit rate: 96.5% (4095 hits / 4245 lookups)",
"strata serve: decode expert cache hit rate: 97.8% (4183 hits / 4278 lookups)",
"strata serve: decode expert cache hit rate: 96.2% (27177 hits / 28250 lookups)",
"strata serve: decode expert cache hit rate: 97.6% (4177 hits / 4281 lookups)",
"strata serve: decode expert cache hit rate: 97.0% (130241 hits / 134296 lookups)",
"strata serve: decode expert cache hit rate: 95.6% (113534 hits / 118732 lookups)"
]
}
@@ -0,0 +1,24 @@
{
"answers": {
"single": [
" Red",
"42",
"A red circle, the number 42, and a blue square are arranged on a white background."
],
"same24": [
" Red",
"42",
"A red circle, the number 42, and a blue square are arranged on a white background."
],
"x2": [
" Red",
"42",
"A red circle, the number 42, and a blue square are displayed on a white background."
]
},
"correct": {
"single": true,
"same24": true,
"x2": true
}
}
@@ -0,0 +1,84 @@
# Layer split across GPUs (2026-09-29)
**Rig (a community member's PC, "RIBPC"):**
- Ryzen 9 9950X3D, 62 GB DDR5, Windows 11, CUDA 13.1.
- RTX 5080 16 GB (x16), RTX 3090 24 GB (x4 gen4, ~6 GB/s), RTX 2080 Ti 22 GB (x4 gen3, Turing sm_75; the
experimental `STRATA_EXPERIMENTAL_SM75` build).
**Model:** the Coder (GSQ-RCO IQ1_M, 48 layers x 256 experts = 12,288 expert pairs, ~23 GB of experts), 32K
context, int8 KV, `--prefill auto`, `--spec 4`. It is the only model that fits the rig's RAM and disk.
**Tools:** `rib_pp.py` (needle prompts at 2.7K/8K/16K/28K tokens with a code word at 50% depth, a 2-turn chat that
must reuse its checkpoint, greedy decode of a story and a code prompt) and `rib_norepeat.py` (the Phase A
no-repeat and sanity cases). Raw results are in `data/`.
## Correctness
| Check | Result |
|---|---|
| This branch vs the 0.1.20 release, one GPU (5080), fixed cache, all 10 cases | **10/10 byte-identical** |
| This branch, one GPU vs the split on the same GPU (K=24, `--split-device 0`) | **10/10 byte-identical**: the hand-off is exact |
| 5080 + 3090 (auto) and 5080 + 2080 Ti + 3090 (auto): no-repeat under presence 100 (greedy and sampled), 144 sanity | all pass, 0 repeats |
| Needles at 2.7K-28K tokens, every configuration | all found |
| 2-turn chat (the checkpoint restored on every GPU) | reused 6,631-6,632 of 6,660 tokens, answer right |
Across GPUs the text is not byte-identical to one GPU: experts the CPU computed on one card run on a GPU in the split,
and they round differently (the same effect as `--expert-cache`, bench/results/2026-09-27-cache-parity).
## Speed
**Prompt tok/s** at 16K / 28K tokens, and **decode tok/s** for story / code (greedy; three repeats averaged
in the K sweep):
| Configuration | Split | Prompt 16K | Prompt 28K | Decode story | Decode code | Decode hits |
|---|---|---|---|---|---|---|
| 0.1.20, 5080 alone | - | 2,045 | 2,005 | 83.2 | 88.2 | 70-84% |
| this branch, 5080 alone | - | 2,017 | 1,974 | 83.1 | 88.0 | 70-84% |
| this branch, 5080 alone, 3 repeats (adaptive swaps learn the prompt) | - | 1,726 | 1,970 | 86.7 | 105.2 | 91-92% |
| 3090 alone | - | 1,253 | 1,211 | 71.7 | 92.9 | 86-93% |
| 5080 + 3090 | K=18 | 1,547 | 1,694 | 77.2 | 103.8 | 99.9% |
| 5080 + 3090 | K=22 | 1,840 | 2,074 | 80.2 | 106.4 | 99.8% |
| 5080 + 3090 | K=24 | 1,978 | 2,258 | 83.5 | 109.5 | 99.5% |
| **5080 + 3090** | **K=26** | **2,039** | **2,357** | **83.8** | **109.7** | 99.3% |
| 5080 + 3090 | K=28 | 2,011 | 2,287 | 83.5 | 112.5 | 99.0% |
| 5080 + 3090 | K=30 | 1,935 | 2,218 | 81.1 | 109.6 | 98% |
| 5080 + 3090 | K=32 | 1,818 | 2,063 | 83.0 | 108.7 | 98% |
| 5080 + 3090 | auto (K=22) | 2,037 | 2,073 | 79.5 | 108.9 | 99.7% |
| 3090 + 5080 | auto (K=30) | 1,672 | 1,876 | 90.3 | 105.1 | 99.4% |
| 5080 + 2080 Ti + 3090 | auto (22, 23) | 1,687 | 1,847 | 67.6 | 89.6 | 99.7% |
| 5080 + 3090 + 2080 Ti | first auto (12, 33) | 1,148 | 1,144 | 51.9 | 69.7 | 100% |
| 5080 + 2080 Ti | first auto | 914 | 906 | 45.5 | 58.0 | 97% |
What decides it:
- **The best two-GPU split for the Coder is K=26-28.** Prompts run +18-20% over the 5080 alone at 16-28K;
decode is on par for story and +4-7% for code.
- **Residency saturates quickly: the per-layer GPU speed decides.** From K=18 up, both caches hold 98-100% of
the routed experts. Moving layers to the faster card is what helps: the 3090 costs 0.50 ms per layer per
window, the 5080 0.33 (`STRATA_SPLIT_TIMING`, the "wait for the GPU" per stage).
- **Decode is bounded by that GPU time.** One 5080 with its cache adapted spends 16.3 ms waiting for its GPU and
5.5 ms in the CPU pool per window. The split removes the pool (0.8-1.0 ms) but adds the slower card's layers:
7.9 + 12.1 ms at K=24. The per-layer GPU half (kernels plus the host round trip that publishes each layer's
expert plan) is the next thing to cut, for one GPU as well (perf-review-plan E-6).
- **A third, slower card costs more than it holds.** The 2080 Ti's one-layer stage took 3.1 ms per window.
For a model that already fits two cards, leave it out. It pays only when the two faster cards cannot hold most
of the routed experts (a bigger model; not testable on this rig's 62 GB of RAM).
- **Prompt chunk:** 1024 instead of 2048 frees ~0.7 GB per card, but prompts read 7-12% slower.
## Auto placement
`--layer-split auto` predicts one decode window's time for every placement (every placement up to three GPUs) and
keeps the fastest:
- **per-layer time** from SMs x clock (0.33 ms for an RTX 5080);
- **cache contents:** each card's layers' profiled pairs, hottest first, as the fill does;
- **routed mass** of rank r taken as (r+1)^-1.2 (fits the sweep's hit rates within 0.1-1%);
- **missed mass** costing 190 ms per unit (fitted to the sweep's best K; `STRATA_SPLIT_MISS_MS` overrides).
It picked K=22 on the 5080 + 3090: within 0-12% of the best fixed split on prompts and on par on decode. It gives
a slow third card a single layer.
## Reproduce
On a rig: the `strata-remote` tools, then `rib_matrix.bat`, `rib_ksweep.bat`, `rib_validate.bat` (in the dev
notes, not in this repository).
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 88,
"drafts_offered": 193,
"tok_s": 74.6,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, gripped the iron railing as he ascended the final flight of steps to the lantern room.\n\nBelow him, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t flip a switch. He didn\u2019t press a button. He reached for the heavy brass lever that had worn smooth by his palm over the years. With a grunt that matched the strain of his aging muscles, he pulled it down.\n\n*Clunk.*\n\nThe"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 136,
"drafts_offered": 181,
"tok_s": 105.5,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 85.8,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 94.3,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 118,
"repeats": 0,
"drafts_accepted": 37,
"drafts_offered": 105,
"tok_s": 67.9,
"text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 147,
"repeats": 0,
"drafts_accepted": 26,
"drafts_offered": 103,
"tok_s": 63.2,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to that date and time for context because you asked me about a lighthouse keeper but gave no specifics beyond \u201cshort story,\u201d so let\u2019s set it: isolated coastal station off the Oregon coast during winter storm season, 1987.\n\nMy name is Elias Vane (I made this fictional; real keepers often kept journals signed with initials only), and I\u2019m writing from memory because my logbook got waterlogged when a rogue wave breached lower storage room at dawn\u2014so here\u2019s what happened:<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 109,
"repeats": 0,
"drafts_accepted": 13,
"drafts_offered": 56,
"tok_s": 54.1,
"text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they settled into silence with every storm break out of three hundred days here being storms that broke something else again but mostly kept me warm because I burned coal and wood whenever we had any left over from last winter when even then if you\u2019re lucky enough to get through it all without freezing yourself so hard your own thoughts become ice too\n\nBut Elias knew better than anyone: fear was useful only until dawn<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 92,
"repeats": 0,
"drafts_accepted": 26,
"drafts_offered": 48,
"tok_s": 64.7,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nPanther \nJaguar \nBison \nElk \nDeer \nFox \nWolf \nBear \nLlama \nDonkey \nGoat \nSheep \nCow \nPig \nRabbit \nCat \nDog<|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 14,
"tok_s": 71.7,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 53,
"drafts_offered": 134,
"tok_s": 66.1,
"text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story we tell ourselves through our relationship** between landmasses separated by vast expansiveness that defines both isolation from other worlds (and thus their own unique evolutionary paths) as well than connection across them via currents wind patterns tides depth pressure temperature salinity biodiversity geology climate change economic trade routes ecological systems cultural exchange political boundaries scientific discovery technological advancement environmental degradation conservation efforts maritime archaeography historical cartographic evolution legal frameworks international law enforcement mechanisms insurance liability regimes regulatory compliance standards safety protocols navigation aids communication networks emergency response strategies search-and-rescue operations salvage rights ownership disputes heritage protection zones sustainable harvesting practices aquaculture development infrastructure engineering projects coastal management policies urban planning regulations zoning ordinances building codes architectural design guidelines aesthetic considerations functional requirements accessibility provisions energy efficiency measures thermal insulation techniques moisture control methods ventilation optimization lighting solutions acoustic soundproofing structural integrity assessments seismic resistance evaluations flood mitigation plans storm surge barriers levee construction seawall reinforcement breakwater installation harbor dredging channel maintenance buoy placement lighthouse automation radar monitoring sonar mapping bathymetric surveys hydrographic charts nautical almanacs tide tables current predictions weather forecasts marine meteorological models satellite imagery remote sensing data assimilation numerical simulations computational fluid dynamics finite element analysis partial differential equations tensor calculus linear algebra probability theory statistics stochastic processes Markov chains Bayesian inference machine learning artificial neural network deep convolutional recurrent transformer attention heads generative adversarial diffusion transformers large language model tokenization"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 88,
"drafts_offered": 193,
"tok_s": 68.2,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, gripped the iron railing as he ascended the final flight of steps to the lantern room.\n\nBelow him, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t flip a switch. He didn\u2019t press a button. He reached for the heavy brass lever that had worn smooth by his palm over the years. With a grunt that matched the strain of his aging muscles, he pulled it down.\n\n*Clunk.*\n\nThe"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 136,
"drafts_offered": 181,
"tok_s": 99.4,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 74.5,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 76.3,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 118,
"repeats": 0,
"drafts_accepted": 37,
"drafts_offered": 105,
"tok_s": 65.2,
"text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 147,
"repeats": 0,
"drafts_accepted": 26,
"drafts_offered": 103,
"tok_s": 45.7,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to that date and time for context because you asked me about a lighthouse keeper but gave no specifics beyond \u201cshort story,\u201d so let\u2019s set it: isolated coastal station off the Oregon coast during winter storm season, 1987.\n\nMy name is Elias Vane (I made this fictional; real keepers often kept journals signed with initials only), and I\u2019m writing from memory because my logbook got waterlogged when a rogue wave breached lower storage room at dawn\u2014so here\u2019s what happened:<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 109,
"repeats": 0,
"drafts_accepted": 13,
"drafts_offered": 56,
"tok_s": 42.1,
"text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they settled into silence with every storm break out of three hundred days here being storms that broke something else again but mostly kept me warm because I burned coal and wood whenever we had any left over from last winter when even then if you\u2019re lucky enough to get through it all without freezing yourself so hard your own thoughts become ice too\n\nBut Elias knew better than anyone: fear was useful only until dawn<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 92,
"repeats": 0,
"drafts_accepted": 26,
"drafts_offered": 48,
"tok_s": 43.9,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nPanther \nJaguar \nBison \nElk \nDeer \nFox \nWolf \nBear \nLlama \nDonkey \nGoat \nSheep \nCow \nPig \nRabbit \nCat \nDog<|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 14,
"tok_s": 61.4,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 53,
"drafts_offered": 134,
"tok_s": 51.9,
"text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story we tell ourselves through our relationship** between landmasses separated by vast expansiveness that defines both isolation from other worlds (and thus their own unique evolutionary paths) as well than connection across them via currents wind patterns tides depth pressure temperature salinity biodiversity geology climate change economic trade routes ecological systems cultural exchange political boundaries scientific discovery technological advancement environmental degradation conservation efforts maritime archaeography historical cartographic evolution legal frameworks international law enforcement mechanisms insurance liability regimes regulatory compliance standards safety protocols navigation aids communication networks emergency response strategies search-and-rescue operations salvage rights ownership disputes heritage protection zones sustainable harvesting practices aquaculture development infrastructure engineering projects coastal management policies urban planning regulations zoning ordinances building codes architectural design guidelines aesthetic considerations functional requirements accessibility provisions energy efficiency measures thermal insulation techniques moisture control methods ventilation optimization lighting solutions acoustic soundproofing structural integrity assessments seismic resistance evaluations flood mitigation plans storm surge barriers levee construction seawall reinforcement breakwater installation harbor dredging channel maintenance buoy placement lighthouse automation radar monitoring sonar mapping bathymetric surveys hydrographic charts nautical almanacs tide tables current predictions weather forecasts marine meteorological models satellite imagery remote sensing data assimilation numerical simulations computational fluid dynamics finite element analysis partial differential equations tensor calculus linear algebra probability theory statistics stochastic processes Markov chains Bayesian inference machine learning artificial neural network deep convolutional recurrent transformer attention heads generative adversarial diffusion transformers large language model tokenization"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 91,
"drafts_offered": 190,
"tok_s": 74.0,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, knew every bolt, every lever, and every creak in the iron bones of the tower.\n\nFor forty years, Elias had been the guardian of the Point. Not just of the light, but of the silence between the waves.\n\nIt was November. The sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that shook the floorboards beneath Elias\u2019s boots.\n\nHe climbed the stairs. One hundred and twelve steps. He counted them by feel, his left hand trailing along the cold iron railing. At the top, the air was"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 137,
"drafts_offered": 178,
"tok_s": 103.4,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 91.1,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 70.7,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 118,
"repeats": 0,
"drafts_accepted": 38,
"drafts_offered": 108,
"tok_s": 65.4,
"text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 57,
"repeats": 0,
"drafts_accepted": 11,
"drafts_offered": 61,
"tok_s": 57.1,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach top room where his world began again.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 58,
"repeats": 0,
"drafts_accepted": 14,
"drafts_offered": 54,
"tok_s": 52.9,
"text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in stone and steel, carrying with them spray from three miles out into churning black water that no longer resembled an ocean so much as abyssal chaos waiting for its prey to surface beneath waves of salt.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 59,
"repeats": 0,
"drafts_accepted": 11,
"drafts_offered": 47,
"tok_s": 51.7,
"text": "Lion \nTiger \n\nElephant\\nGiraffe\\Zebra\\rHippopotamus\\tRhinoceros\\vCrocodile\\fAlligator\\bSnake\\aSpider\\u2615CoffeeCup\u2615\ufe0fTeaTime\ud83d\udc09DragonFishWhaleDolph<|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 12,
"tok_s": 73.5,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 43,
"drafts_offered": 126,
"tok_s": 63.4,
"text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story told by waves**. It serves as both witness (through sedimentary layers)and participant( through currents that carry messages across continents). Its \"history\" spans geological epochs where life first emerged from primordial pools into complex ecosystems today\u2014and cultural histories shaped entirely around its roleas connector between distant lands or barrier separating them forever depending on perspective taken at different times throughout millennia since ancient civilizations began building boats outof logs carved using stone tools until modern container ships carrying billions tons cargo daily cross Atlantic routes once navigated onlyby stars alone under moonlight during nights when sailors feared monsters lurking beneath hulls made fragile against storms they could barely predict even now despite advanced meteorology systems developed over past century after industrial revolution transformed maritime trade patterns globally due economic pressures driving demand for faster logistics chains linking factories producing electronics manufactured inside cities located far inland near rivers feeding estuaries opening directly onto open seas connected via canals engineered centuries ago like Suez Canal built originallyfor military purposes later adapted commercial use post-World War II era reshaping global supply networks dramatically because geopolitical shifts altered which ports remained accessible politically versus physically blocked temporarily then reopened permanently following treaty agreements signed among nations agreeing upon shared responsibilities regarding environmental stewardship including coral reef restoration efforts funded jointly international organizations coordinating scientific research conducted aboard vessels specifically designed deep-sea exploration equipped robotic submersibles capable descending trenches deeper than any previous technology allowed"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 98,
"drafts_offered": 166,
"tok_s": 54.4,
"text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth."
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 137,
"drafts_offered": 163,
"tok_s": 70.7,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 56.7,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 57.6,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 59,
"repeats": 0,
"drafts_accepted": 13,
"drafts_offered": 47,
"tok_s": 39.7,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \n\nCat \nCheetah \n\nChimpanzee \nClam \n\n\nCrocodile \n\n\n\nDolphin \n\n\n\n\nDonkey <|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 57,
"repeats": 0,
"drafts_accepted": 12,
"drafts_offered": 58,
"tok_s": 39.9,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach topmost gallery where his world began.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 30,
"drafts_offered": 111,
"tok_s": 34.7,
"text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his stone cottage like an angry ghost trying to get inside, yet finding no door left unlocked because Elias never let one stay that way for more than three seconds after entering or leaving during storm season. He had been doing this since 1987\u2014since before he even knew why\u2014and now it was muscle memory so deep into his bones and fingers\u2019 calloused skin texture patterns worn thin by years of gripping the same iron railing at midnight watch that if you asked him what time exactly, down to quarter-hour increments when fog rolled in thick enough where light beams bent around itself like old rope coiling tight on a winch drum spooling out slowly from below deck floor level storage locker number seven under stairs leading"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 96,
"repeats": 0,
"drafts_accepted": 31,
"drafts_offered": 48,
"tok_s": 42.3,
"text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nChimpanzee \nGorilla \nOrangetutan \nAntelope \nBison \nElk <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 43.0,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 29,
"drafts_offered": 127,
"tok_s": 37.6,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\u201d \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \u201cthe Sea\u201d or \"Ocean\" (terms often used interchangeably but distinct geographically) was never just an element within our planet\u2019s geography\u2014it became its engine itself\u2014a living system whose existence predates humanity by billions years yet continues shaping us today through climate regulation oxygen production food supply trade routes cultural identity ecological resilience economic development political boundaries scientific discovery technological innovation environmental crisis conservation efforts historical memory philosophical reflection poetic metaphor musical composition cinematic storytelling literary narrative visual art architectural inspiration culinary tradition spiritual symbolism psychological influence sociological transformation educational foundation medical necessity agricultural dependency industrial revolution urban planning infrastructural engineering legal framework regulatory policy international cooperation global governance planetary stewardship existential risk mitigation sustainable practice ethical consideration moral imperative social justice democratic participation civic engagement public health community welfare individual responsibility personal accountability collective action shared experience common understanding mutual respect reciprocal trust collaborative effort cooperative endeavor joint venture unified mission integrated strategy coordinated plan synchronized schedule aligned timeline concurrent execution simultaneous operation parallel processing sequential progression iterative refinement recursive improvement continuous adaptation dynamic adjustment flexible response adaptive behavior responsive conduct proactive initiative anticipatory foresight predictive modeling probabilistic assessment statistical analysis empirical observation experimental verification theoretical hypothesis conceptual abstraction logical deduction rational inference critical evaluation analytical reasoning systematic investigation methodical inquiry structured exploration comprehensive examination detailed scrutiny meticulous inspection thorough review exhaustive audit complete survey full census total enumeration absolute"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 88,
"drafts_offered": 187,
"tok_s": 59.2,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 135,
"drafts_offered": 179,
"tok_s": 81.6,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 74.9,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 74.3,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 61,
"repeats": 0,
"drafts_accepted": 19,
"drafts_offered": 49,
"tok_s": 49.6,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 80,
"repeats": 0,
"drafts_accepted": 6,
"drafts_offered": 52,
"tok_s": 44.9,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 17,
"drafts_offered": 83,
"tok_s": 44.1,
"text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 62,
"repeats": 0,
"drafts_accepted": 18,
"drafts_offered": 31,
"tok_s": 49.5,
"text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 65.2,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 47,
"drafts_offered": 153,
"tok_s": 52.5,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 88,
"drafts_offered": 187,
"tok_s": 58.4,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 135,
"drafts_offered": 179,
"tok_s": 80.6,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 75.2,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 74.2,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 61,
"repeats": 0,
"drafts_accepted": 19,
"drafts_offered": 49,
"tok_s": 48.5,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 80,
"repeats": 0,
"drafts_accepted": 6,
"drafts_offered": 52,
"tok_s": 46.4,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 17,
"drafts_offered": 83,
"tok_s": 43.3,
"text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 62,
"repeats": 0,
"drafts_accepted": 18,
"drafts_offered": 31,
"tok_s": 49.8,
"text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 62.5,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 47,
"drafts_offered": 153,
"tok_s": 52.6,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules"
}
]
@@ -0,0 +1,92 @@
[
{
"name": "greedy story 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 88,
"drafts_offered": 187,
"tok_s": 58.4,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed"
},
{
"name": "greedy code 200",
"tokens": 200,
"repeats": 0,
"drafts_accepted": 135,
"drafts_offered": 179,
"tok_s": 80.5,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
},
{
"name": "greedy sanity",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 74.5,
"text": "144<|im_end|>"
},
{
"name": "greedy, no penalty (sanity)",
"tokens": 4,
"repeats": 0,
"drafts_accepted": 3,
"drafts_offered": 3,
"tok_s": 76.8,
"text": "144<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64",
"tokens": 61,
"repeats": 0,
"drafts_accepted": 19,
"drafts_offered": 49,
"tok_s": 49.6,
"text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>"
},
{
"name": "greedy presence=100 last_n=64 story",
"tokens": 80,
"repeats": 0,
"drafts_accepted": 6,
"drafts_offered": 52,
"tok_s": 46.7,
"text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>"
},
{
"name": "sampled presence=100 last_n=64 seed 3",
"tokens": 160,
"repeats": 0,
"drafts_accepted": 17,
"drafts_offered": 83,
"tok_s": 44.3,
"text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving"
},
{
"name": "sampled presence=100 last_n=64 seed 11",
"tokens": 62,
"repeats": 0,
"drafts_accepted": 18,
"drafts_offered": 31,
"tok_s": 50.0,
"text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>"
},
{
"name": "greedy frequency=100 last_n=16",
"tokens": 11,
"repeats": 0,
"drafts_accepted": 5,
"drafts_offered": 13,
"tok_s": 62.0,
"text": "1 to 50, separated by commas:<|im_end|>"
},
{
"name": "greedy presence=100 last_n=4096 (8-row windows)",
"tokens": 300,
"repeats": 0,
"drafts_accepted": 47,
"drafts_offered": 153,
"tok_s": 52.1,
"text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules"
}
]
@@ -0,0 +1,72 @@
{
"label": "dev-3090",
"extra": [],
"gpus": "2",
"needles": [
{
"tokens": 2726,
"prompt_ms": 3424.8,
"pp_tok_s": 796.0,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 8617.9,
"pp_tok_s": 972.3,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 12820.1,
"pp_tok_s": 1253.2,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 22901.1,
"pp_tok_s": 1211.4,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 5657.8,
"turn2_tokens": 6660,
"reused": 6631,
"turn2_ms": 238.7,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 71.7,
"hit_rate": 0.9266798230257504,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, punctuated by whitecaps that looked like teeth.\n\nHe climbed the spiral stairs, his knees protesting with every step. The iron rungs were cold, slick with condensation that had leaked through the hairline cracks in the masonry. At the top, the lantern room hummed with the low, steady thrum of the rotating lens. It was a sound Elias had learned to sleep with, a heartbeat of the house.\n\nHe checked the clock. 11:42 PM. The light swept across the water, a slow, hypnotic arc. *Flash. Darkness. Flash. Darkness.*\n\nFor a moment, the beam caught something that wasn\u2019t water. A shape"
},
{
"name": "code",
"tok_s": 92.9,
"hit_rate": 0.8636411400016346,
"text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header row\n and values from the corresponding row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n```<|im_end|>"
}
],
"engine_lines": [
"strata generate: expert cache auto: 17.31 GiB free, 700 MiB reserved -> 6704 slots",
"strata generate: expert cache 8730 slots, 16.62 GiB of VRAM; policy is",
"strata serve: the prompt path borrows 2315 cache slots (4.42 GiB)",
"strata serve: decode expert cache hit rate: 86.6% (4986 hits / 5756 lookups)",
"strata serve: decode expert cache hit rate: 87.1% (3757 hits / 4315 lookups)",
"strata serve: decode expert cache hit rate: 88.7% (3827 hits / 4314 lookups)",
"strata serve: decode expert cache hit rate: 92.1% (3975 hits / 4318 lookups)",
"strata serve: decode expert cache hit rate: 95.5% (4124 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 94.3% (25793 hits / 27360 lookups)",
"strata serve: decode expert cache hit rate: 94.6% (4088 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 92.7% (116454 hits / 125668 lookups)",
"strata serve: decode expert cache hit rate: 86.4% (73970 hits / 85649 lookups)"
]
}
@@ -0,0 +1,72 @@
{
"label": "dev-5080",
"extra": [],
"gpus": "0",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2129.8,
"pp_tok_s": 1279.9,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 5057.2,
"pp_tok_s": 1656.8,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 7964.7,
"pp_tok_s": 2017.2,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 14053.6,
"pp_tok_s": 1974.1,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3366.4,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 197.3,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 83.1,
"hit_rate": 0.8418683557684931,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow"
},
{
"name": "code",
"tok_s": 88.0,
"hit_rate": 0.7011385968111186,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"engine_lines": [
"strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots",
"strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is",
"strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)",
"strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)",
"strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)",
"strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)",
"strata serve: decode expert cache hit rate: 72.5% (2539 hits / 3504 lookups)",
"strata serve: decode expert cache hit rate: 77.3% (2817 hits / 3642 lookups)",
"strata serve: decode expert cache hit rate: 75.3% (16500 hits / 21916 lookups)",
"strata serve: decode expert cache hit rate: 80.0% (2978 hits / 3723 lookups)",
"strata serve: decode expert cache hit rate: 84.2% (98752 hits / 117301 lookups)",
"strata serve: decode expert cache hit rate: 70.1% (69215 hits / 98718 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k18",
"extra": [
"--layer-split",
"18"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 10383.7,
"pp_tok_s": 1547.2,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 16371.9,
"pp_tok_s": 1694.5,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4308.0,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 239.8,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 77.2,
"reps": [
74.6,
78.1,
79.0
],
"hit_rate": 0.9985378787878788,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His knees ached, not from age, but from the constant vibration of the floor beneath his feet. He reached the lantern room, the heart of the lighthouse, and checked the clockwork mechanism. The great lens, a prism of Fresnel glass, rotated with a steady, hypnotic *whirrr-click, whirrr-click*. It was the only sound that mattered. The light swept out into the black void, cutting through"
},
{
"name": "code",
"tok_s": 103.8,
"reps": [
97.6,
106.4,
107.3
],
"hit_rate": 0.9984863945578232,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 524 windows; per window: wait for the GPU 6.456 ms, pool + plan 0.181 ms, host staging 0.581 ms, commit 0.206 ms",
"strata serve: stage 1: 524 windows; per window: wait for the GPU 14.872 ms, pool + plan 0.501 ms, host staging 0.000 ms, commit 0.387 ms",
"strata serve: stage 0: 593 windows; per window: wait for the GPU 6.479 ms, pool + plan 0.185 ms, host staging 0.515 ms, commit 0.207 ms",
"strata serve: stage 1: 593 windows; per window: wait for the GPU 15.053 ms, pool + plan 0.496 ms, host staging 0.000 ms, commit 0.390 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 18)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4608 slots, 8.24 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 18-47, expert cache 7152 slots (14.14 GiB), 7152 of its 7680 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-17",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-17 (CUDA0), 18-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 98.7% (6159 hits / 6240 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (3796 hits / 3840 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (3811 hits / 3840 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (27723 hits / 27840 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (3807 hits / 3840 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (142002 hits / 143040 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (139882 hits / 140160 lookups)",
"strata serve: decode expert cache hit rate: 99.9% (131807 hits / 132000 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (119278 hits / 120480 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (117410 hits / 117600 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (117422 hits / 117600 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k19",
"extra": [
"--layer-split",
"19"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 9875.2,
"pp_tok_s": 1626.9,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 15498.0,
"pp_tok_s": 1790.1,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4085.5,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 238.7,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 79.3,
"reps": [
74.8,
85.6,
77.4
],
"hit_rate": 0.9977757017660928,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias stood at the top of the spiral staircase, his hand resting on the cold iron railing. He was not afraid. Fear was for the tourists who came in summer, wide-eyed and clutching their cameras. Elias was a keeper. He was a guardian.\n\nHe checked the logbook. The entry for the night was simple: *Wind, 60 knots. Visibility, zero. Light, operational.*\n\nHe walked down the stairs, his boots heavy on the metal grating. The smell of salt"
},
{
"name": "code",
"tok_s": 107.4,
"reps": [
98.9,
111.3,
112.1
],
"hit_rate": 0.9986286196529353,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header row\n and values from the corresponding row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with"
}
],
"stage_timing": [
"strata serve: stage 0: 533 windows; per window: wait for the GPU 6.226 ms, pool + plan 0.294 ms, host staging 0.561 ms, commit 0.225 ms",
"strata serve: stage 1: 533 windows; per window: wait for the GPU 14.156 ms, pool + plan 0.373 ms, host staging 0.000 ms, commit 0.371 ms",
"strata serve: stage 0: 599 windows; per window: wait for the GPU 6.314 ms, pool + plan 0.292 ms, host staging 0.501 ms, commit 0.225 ms",
"strata serve: stage 1: 599 windows; per window: wait for the GPU 14.366 ms, pool + plan 0.375 ms, host staging 0.000 ms, commit 0.374 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 19)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-18",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 98.5% (6141 hits / 6234 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (3797 hits / 3836 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (3814 hits / 3837 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (28659 hits / 28795 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (3814 hits / 3839 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (141378 hits / 142508 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (124963 hits / 125273 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (134574 hits / 134874 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (121132 hits / 122322 lookups)",
"strata serve: decode expert cache hit rate: 99.9% (114073 hits / 114235 lookups)",
"strata serve: decode expert cache hit rate: 99.9% (113598 hits / 113754 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k20",
"extra": [
"--layer-split",
"20"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 9044.3,
"pp_tok_s": 1776.4,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13928.7,
"pp_tok_s": 1991.8,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3743.5,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 236.8,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 76.4,
"reps": [
74.2,
78.4,
76.7
],
"hit_rate": 0.9979911611088791,
"text": "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry it from the bedrock, and it howled through the narrow slits of the lantern room glass.\n\nElias Thorne was seventy years old, but he moved with the grace of a man who had spent fifty years listening to the sea. He knew the rhythm of the waves against the rocks below\u2014the *thud, thud, crash*\u2014and he knew when that rhythm changed. When the sea grew too quiet, or too violent, he knew a storm was coming, or a ship was in trouble.\n\nTonight, the storm was a Category 4. The rain lashed against the windows like gravel thrown by a giant. Elias stood in the center of the lantern room, his hand resting on the cold brass railing. He wasn\u2019t afraid. He was a guardian.\n\nHe checked the clockwork mechanism. It was old, a relic from 1"
},
{
"name": "code",
"tok_s": 105.9,
"reps": [
103.2,
106.8,
107.7
],
"hit_rate": 0.9981849807154201,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 537 windows; per window: wait for the GPU 6.685 ms, pool + plan 0.403 ms, host staging 0.593 ms, commit 0.215 ms",
"strata serve: stage 1: 537 windows; per window: wait for the GPU 13.928 ms, pool + plan 0.282 ms, host staging 0.000 ms, commit 0.359 ms",
"strata serve: stage 0: 606 windows; per window: wait for the GPU 6.764 ms, pool + plan 0.399 ms, host staging 0.528 ms, commit 0.216 ms",
"strata serve: stage 1: 606 windows; per window: wait for the GPU 14.108 ms, pool + plan 0.288 ms, host staging 0.000 ms, commit 0.362 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 20)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 20-47, expert cache 7142 slots (14.14 GiB), 7142 of its 7168 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-19",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 98.9% (6162 hits / 6230 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (3803 hits / 3835 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (3810 hits / 3836 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (27185 hits / 27330 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (3807 hits / 3835 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (139825 hits / 140938 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (142122 hits / 142524 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (146556 hits / 146851 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (118026 hits / 119233 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (118729 hits / 118997 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (118791 hits / 119007 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k21",
"extra": [
"--layer-split",
"21"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 8880.5,
"pp_tok_s": 1809.1,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13654.6,
"pp_tok_s": 2031.8,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3680.6,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 235.4,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 77.4,
"reps": [
80.2,
80.8,
71.2
],
"hit_rate": 0.9973622550922132,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, ensuring the rotation was smooth, silent, and steady. *Tick. Tick. Tick.* The sound was the heartbeat of the coast.\n\n"
},
{
"name": "code",
"tok_s": 106.7,
"reps": [
100.6,
110.5,
109.0
],
"hit_rate": 0.998218711927068,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 527 windows; per window: wait for the GPU 6.934 ms, pool + plan 0.620 ms, host staging 0.530 ms, commit 0.245 ms",
"strata serve: stage 1: 527 windows; per window: wait for the GPU 13.912 ms, pool + plan 0.365 ms, host staging 0.000 ms, commit 0.359 ms",
"strata serve: stage 0: 595 windows; per window: wait for the GPU 7.031 ms, pool + plan 0.595 ms, host staging 0.472 ms, commit 0.245 ms",
"strata serve: stage 1: 595 windows; per window: wait for the GPU 14.051 ms, pool + plan 0.361 ms, host staging 0.000 ms, commit 0.361 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 21)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4627 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 21-47, expert cache 6912 slots (13.78 GiB), 6912 of its 6912 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-20",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-20 (CUDA0), 21-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 98.7% (5672 hits / 5748 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (4287 hits / 4314 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (4287 hits / 4315 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (29024 hits / 29229 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4316 lookups)",
"strata serve: decode expert cache hit rate: 98.8% (131499 hits / 133085 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (130974 hits / 131451 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (138767 hits / 139134 lookups)",
"strata serve: decode expert cache hit rate: 98.8% (121454 hits / 122932 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (116809 hits / 117079 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (118803 hits / 119015 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k22",
"extra": [
"--layer-split",
"22"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 8730.9,
"pp_tok_s": 1840.1,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13375.4,
"pp_tok_s": 2074.2,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3611.4,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 234.8,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 80.2,
"reps": [
78.4,
80.9,
81.5
],
"hit_rate": 0.9977764197412695,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a small, drafty cottage on the mainland, waiting for the day when the sea would finally claim him.\n\nTonight, the storm was a Category 4. The waves weren\u2019t just crashing; they were climbing. They reached the gallery railing, ten feet above the base of the tower, spraying a fine mist of brine that coated Elias\u2019s glasses.\n\nHe climbed the spiral stairs, his knees protesting with every step. The iron steps were cold, slick with condensation. At the top, in the lantern room, the air was thin and sharp. The great Fresnel lens, a cathedral of glass and brass, stood silent. It was time to wake it.\n\n"
},
{
"name": "code",
"tok_s": 106.4,
"reps": [
100.7,
110.3,
108.1
],
"hit_rate": 0.9971798370756316,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 529 windows; per window: wait for the GPU 7.229 ms, pool + plan 0.561 ms, host staging 0.529 ms, commit 0.233 ms",
"strata serve: stage 1: 529 windows; per window: wait for the GPU 13.058 ms, pool + plan 0.253 ms, host staging 0.000 ms, commit 0.334 ms",
"strata serve: stage 0: 598 windows; per window: wait for the GPU 7.325 ms, pool + plan 0.552 ms, host staging 0.469 ms, commit 0.235 ms",
"strata serve: stage 1: 598 windows; per window: wait for the GPU 13.238 ms, pool + plan 0.260 ms, host staging 0.000 ms, commit 0.337 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-21",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)",
"strata serve: decode expert cache hit rate: 98.7% (4256 hits / 4310 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4315 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (27008 hits / 27289 lookups)",
"strata serve: decode expert cache hit rate: 98.8% (4260 hits / 4313 lookups)",
"strata serve: decode expert cache hit rate: 98.5% (135183 hits / 137274 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (136132 hits / 136708 lookups)",
"strata serve: decode expert cache hit rate: 99.8% (135515 hits / 135817 lookups)",
"strata serve: decode expert cache hit rate: 98.4% (121287 hits / 123280 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (117658 hits / 118026 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (120574 hits / 120915 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k23",
"extra": [
"--layer-split",
"23"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 8742.6,
"pp_tok_s": 1837.7,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13084.2,
"pp_tok_s": 2120.3,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3566.1,
"turn2_tokens": 6660,
"reused": 6631,
"turn2_ms": 238.0,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 81.0,
"reps": [
76.8,
85.2,
81.1
],
"hit_rate": 0.9961302681992337,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, swallowing the horizon, throwing white foam against the granite base like a tantrum.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his wool trousers, the fabric stiff with salt and grease. He checked the clockwork mechanism that turned the lens. It was a beast of a thing, a Fresnel lens of eight feet in diameter, a cathedral of glass and crystal that focused the beam of the lamp into a single, piercing needle of light.\n\nHe wound the weights. *Click, click, click.* The gears engaged. The massive lens began its slow, hypnotic rotation.\n\nFor a moment, the"
},
{
"name": "code",
"tok_s": 108.4,
"reps": [
105.1,
109.0,
111.1
],
"hit_rate": 0.9961698810290479,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 537 windows; per window: wait for the GPU 7.423 ms, pool + plan 0.953 ms, host staging 0.542 ms, commit 0.237 ms",
"strata serve: stage 1: 537 windows; per window: wait for the GPU 12.223 ms, pool + plan 0.236 ms, host staging 0.000 ms, commit 0.324 ms",
"strata serve: stage 0: 606 windows; per window: wait for the GPU 7.519 ms, pool + plan 0.904 ms, host staging 0.483 ms, commit 0.239 ms",
"strata serve: stage 1: 606 windows; per window: wait for the GPU 12.395 ms, pool + plan 0.242 ms, host staging 0.000 ms, commit 0.326 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 23)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4609 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-22",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-22 (CUDA0), 23-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 96.8% (5528 hits / 5709 lookups)",
"strata serve: decode expert cache hit rate: 98.4% (4235 hits / 4303 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (4260 hits / 4308 lookups)",
"strata serve: decode expert cache hit rate: 98.6% (30643 hits / 31089 lookups)",
"strata serve: decode expert cache hit rate: 98.6% (4248 hits / 4309 lookups)",
"strata serve: decode expert cache hit rate: 98.3% (134776 hits / 137143 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (133024 hits / 133766 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (129995 hits / 130500 lookups)",
"strata serve: decode expert cache hit rate: 97.9% (115782 hits / 118287 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (117953 hits / 118464 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (117560 hits / 118012 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k24",
"extra": [
"--layer-split",
"24"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 8122.5,
"pp_tok_s": 1978.0,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 12285.8,
"pp_tok_s": 2258.1,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3407.0,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 234.0,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 83.5,
"reps": [
84.9,
83.3,
82.3
],
"hit_rate": 0.9949381327334084,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He was not merely a keeper; he was a guardian of silence.\n\nHe checked the clock. 11:42 PM. The rotation of the great Fresnel lens was due. With a practiced hand, he engaged the brake on the clockwork mechanism. The heavy brass gears groaned, then began their slow, rhythmic turn. *Tick. Tick. Tick.* It was a heartbeat"
},
{
"name": "code",
"tok_s": 109.5,
"reps": [
104.9,
111.0,
112.6
],
"hit_rate": 0.9953796671318199,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 519 windows; per window: wait for the GPU 7.835 ms, pool + plan 0.767 ms, host staging 0.557 ms, commit 0.244 ms",
"strata serve: stage 1: 519 windows; per window: wait for the GPU 11.922 ms, pool + plan 0.232 ms, host staging 0.000 ms, commit 0.325 ms",
"strata serve: stage 0: 587 windows; per window: wait for the GPU 7.943 ms, pool + plan 0.744 ms, host staging 0.497 ms, commit 0.246 ms",
"strata serve: stage 1: 587 windows; per window: wait for the GPU 12.073 ms, pool + plan 0.238 ms, host staging 0.000 ms, commit 0.326 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 24)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 24-47, expert cache 6144 slots (12.35 GiB), 6144 of its 6144 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-23",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-23 (CUDA0), 24-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 95.9% (5916 hits / 6171 lookups)",
"strata serve: decode expert cache hit rate: 97.4% (3717 hits / 3815 lookups)",
"strata serve: decode expert cache hit rate: 98.4% (3761 hits / 3823 lookups)",
"strata serve: decode expert cache hit rate: 98.1% (27138 hits / 27664 lookups)",
"strata serve: decode expert cache hit rate: 97.8% (3742 hits / 3826 lookups)",
"strata serve: decode expert cache hit rate: 97.9% (126114 hits / 128875 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (133626 hits / 134658 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (132675 hits / 133350 lookups)",
"strata serve: decode expert cache hit rate: 96.8% (113593 hits / 117399 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (118372 hits / 118949 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (116981 hits / 117524 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k26",
"extra": [
"--layer-split",
"26"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 7880.9,
"pp_tok_s": 2038.6,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 11771.9,
"pp_tok_s": 2356.7,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3323.9,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 231.5,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 83.8,
"reps": [
85.9,
83.1,
82.4
],
"hit_rate": 0.9933966961830739,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and green.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He was a keeper of the light, but more importantly, he was a keeper of time.\n\nHe checked his pocket watch. 11:42 PM. The rotation of the great Fresnel lens was due. With a practiced, rhythmic *clunk-clunk-clunk*, he wound the clockwork mechanism. The massive lens began its slow, hypnotic turn, sweeping its beam across"
},
{
"name": "code",
"tok_s": 109.7,
"reps": [
104.4,
112.7,
111.9
],
"hit_rate": 0.9938670271352759,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 519 windows; per window: wait for the GPU 8.376 ms, pool + plan 1.030 ms, host staging 0.566 ms, commit 0.273 ms",
"strata serve: stage 1: 519 windows; per window: wait for the GPU 10.886 ms, pool + plan 0.214 ms, host staging 0.000 ms, commit 0.297 ms",
"strata serve: stage 0: 588 windows; per window: wait for the GPU 8.506 ms, pool + plan 0.985 ms, host staging 0.505 ms, commit 0.274 ms",
"strata serve: stage 1: 588 windows; per window: wait for the GPU 11.036 ms, pool + plan 0.219 ms, host staging 0.000 ms, commit 0.298 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 26)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4568 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 26-47, expert cache 5632 slots (11.32 GiB), 5632 of its 5632 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-25",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-25 (CUDA0), 26-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 92.8% (5259 hits / 5665 lookups)",
"strata serve: decode expert cache hit rate: 95.2% (4056 hits / 4259 lookups)",
"strata serve: decode expert cache hit rate: 97.2% (4164 hits / 4285 lookups)",
"strata serve: decode expert cache hit rate: 97.1% (27690 hits / 28510 lookups)",
"strata serve: decode expert cache hit rate: 97.5% (4184 hits / 4293 lookups)",
"strata serve: decode expert cache hit rate: 96.9% (121839 hits / 125724 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (132165 hits / 133648 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (137652 hits / 138567 lookups)",
"strata serve: decode expert cache hit rate: 95.3% (111307 hits / 116822 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (118436 hits / 119329 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (119109 hits / 119844 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k28",
"extra": [
"--layer-split",
"28"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 7989.3,
"pp_tok_s": 2010.9,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 12132.9,
"pp_tok_s": 2286.6,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3433.5,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 228.0,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 83.5,
"reps": [
83.7,
82.4,
84.5
],
"hit_rate": 0.9900441970361987,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His knees ached, not from age, but from the constant vibration of the floor beneath his feet. He reached the lantern room, the heart of the lighthouse, and checked the clockwork mechanism. The great lens, a prism of Fresnel glass, rotated with a steady, hypnotic *whirrr-click, whirrr-click*. It was the only sound that mattered. The light swept out into the black void, cutting through"
},
{
"name": "code",
"tok_s": 112.5,
"reps": [
101.4,
112.1,
124.1
],
"hit_rate": 0.9896636587366694,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n```<|im_end|>"
}
],
"stage_timing": [
"strata serve: stage 0: 527 windows; per window: wait for the GPU 8.765 ms, pool + plan 1.401 ms, host staging 0.593 ms, commit 0.281 ms",
"strata serve: stage 1: 527 windows; per window: wait for the GPU 9.893 ms, pool + plan 0.195 ms, host staging 0.000 ms, commit 0.276 ms",
"strata serve: stage 0: 578 windows; per window: wait for the GPU 8.908 ms, pool + plan 1.359 ms, host staging 0.559 ms, commit 0.284 ms",
"strata serve: stage 1: 578 windows; per window: wait for the GPU 10.025 ms, pool + plan 0.200 ms, host staging 0.000 ms, commit 0.278 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 28)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4537 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 28-47, expert cache 5120 slots (10.30 GiB), 5120 of its 5120 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-27",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-27 (CUDA0), 28-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 88.8% (5405 hits / 6086 lookups)",
"strata serve: decode expert cache hit rate: 93.8% (3539 hits / 3773 lookups)",
"strata serve: decode expert cache hit rate: 94.2% (3560 hits / 3781 lookups)",
"strata serve: decode expert cache hit rate: 95.7% (26702 hits / 27899 lookups)",
"strata serve: decode expert cache hit rate: 95.9% (3647 hits / 3804 lookups)",
"strata serve: decode expert cache hit rate: 95.7% (122618 hits / 128160 lookups)",
"strata serve: decode expert cache hit rate: 98.6% (135035 hits / 136884 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (129476 hits / 130778 lookups)",
"strata serve: decode expert cache hit rate: 93.9% (111037 hits / 118290 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (118829 hits / 120140 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (90480 hits / 91425 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k30",
"extra": [
"--layer-split",
"30"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 8301.3,
"pp_tok_s": 1935.4,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 12507.6,
"pp_tok_s": 2218.1,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3448.7,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 229.4,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 81.1,
"reps": [
78.0,
84.4,
81.0
],
"hit_rate": 0.9798126997277784,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias stood at the top of the spiral staircase, his hand resting on the cold iron railing. He was not afraid. Fear was for the tourists who came in summer, wide-eyed and clutching their cameras. Elias was a keeper. He was a guardian.\n\nHe checked the logbook. The entry for the night was simple: *Wind, 60 knots. Visibility, zero. Light, operational.*\n\nHe walked down the stairs, his boots heavy on the metal grating. The smell of salt"
},
{
"name": "code",
"tok_s": 109.6,
"reps": [
100.7,
114.1,
114.1
],
"hit_rate": 0.9825370343977666,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 540 windows; per window: wait for the GPU 9.206 ms, pool + plan 1.794 ms, host staging 0.525 ms, commit 0.298 ms",
"strata serve: stage 1: 540 windows; per window: wait for the GPU 8.767 ms, pool + plan 0.173 ms, host staging 0.000 ms, commit 0.242 ms",
"strata serve: stage 0: 608 windows; per window: wait for the GPU 9.390 ms, pool + plan 1.733 ms, host staging 0.471 ms, commit 0.301 ms",
"strata serve: stage 1: 608 windows; per window: wait for the GPU 8.910 ms, pool + plan 0.178 ms, host staging 0.000 ms, commit 0.244 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 30)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4479 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 30-47, expert cache 4608 slots (9.19 GiB), 4608 of its 4608 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-29",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-29 (CUDA0), 30-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 84.6% (5099 hits / 6028 lookups)",
"strata serve: decode expert cache hit rate: 90.7% (3403 hits / 3751 lookups)",
"strata serve: decode expert cache hit rate: 91.1% (3415 hits / 3747 lookups)",
"strata serve: decode expert cache hit rate: 94.1% (26108 hits / 27737 lookups)",
"strata serve: decode expert cache hit rate: 93.4% (3534 hits / 3784 lookups)",
"strata serve: decode expert cache hit rate: 94.6% (127532 hits / 134866 lookups)",
"strata serve: decode expert cache hit rate: 98.6% (135828 hits / 137786 lookups)",
"strata serve: decode expert cache hit rate: 98.0% (132455 hits / 135184 lookups)",
"strata serve: decode expert cache hit rate: 91.0% (106351 hits / 116917 lookups)",
"strata serve: decode expert cache hit rate: 97.9% (115791 hits / 118246 lookups)",
"strata serve: decode expert cache hit rate: 98.3% (117198 hits / 119281 lookups)"
]
}
@@ -0,0 +1,85 @@
{
"label": "ks-k32",
"extra": [
"--layer-split",
"32"
],
"gpus": "0,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 8837.1,
"pp_tok_s": 1818.0,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13449.8,
"pp_tok_s": 2062.7,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3565.7,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 227.0,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 83.0,
"reps": [
75.0,
86.1,
87.8
],
"hit_rate": 0.9796934433020751,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow"
},
{
"name": "code",
"tok_s": 108.7,
"reps": [
98.8,
112.2,
115.1
],
"hit_rate": 0.9777186846317358,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 533 windows; per window: wait for the GPU 9.839 ms, pool + plan 2.192 ms, host staging 0.585 ms, commit 0.318 ms",
"strata serve: stage 1: 533 windows; per window: wait for the GPU 8.014 ms, pool + plan 0.156 ms, host staging 0.000 ms, commit 0.231 ms",
"strata serve: stage 0: 602 windows; per window: wait for the GPU 10.014 ms, pool + plan 2.111 ms, host staging 0.520 ms, commit 0.321 ms",
"strata serve: stage 1: 602 windows; per window: wait for the GPU 8.094 ms, pool + plan 0.160 ms, host staging 0.000 ms, commit 0.232 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 32)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4488 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 32-47, expert cache 4096 slots (8.26 GiB), 4096 of its 4096 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-31",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-31 (CUDA0), 32-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 81.3% (4889 hits / 6010 lookups)",
"strata serve: decode expert cache hit rate: 87.7% (3272 hits / 3733 lookups)",
"strata serve: decode expert cache hit rate: 87.9% (3280 hits / 3733 lookups)",
"strata serve: decode expert cache hit rate: 92.3% (24238 hits / 26254 lookups)",
"strata serve: decode expert cache hit rate: 91.5% (3457 hits / 3778 lookups)",
"strata serve: decode expert cache hit rate: 93.7% (133254 hits / 142240 lookups)",
"strata serve: decode expert cache hit rate: 98.0% (130112 hits / 132812 lookups)",
"strata serve: decode expert cache hit rate: 98.0% (130069 hits / 132765 lookups)",
"strata serve: decode expert cache hit rate: 89.1% (105263 hits / 118190 lookups)",
"strata serve: decode expert cache hit rate: 97.2% (116970 hits / 120309 lookups)",
"strata serve: decode expert cache hit rate: 97.8% (115450 hits / 118081 lookups)"
]
}
@@ -0,0 +1,76 @@
{
"label": "ks-single",
"extra": [],
"gpus": "0",
"needles": [
{
"tokens": 16066,
"prompt_ms": 9310.4,
"pp_tok_s": 1725.6,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 14085.4,
"pp_tok_s": 1969.6,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3388.7,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 200.7,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 86.7,
"reps": [
78.2,
91.4,
90.4
],
"hit_rate": 0.921882148773369,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and his hands were a map of the coastline he had guarded for fifty years. The knuckles were swollen, the skin cracked like dry earth, but they moved with a precision that no machine could replicate.\n\nHe stood on the gallery of the *Harrow Point* lighthouse, the iron railing cold against his palms. Below, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t look at the gauge. He didn\u2019t check the fuel levels. He knew. He always knew. The rhythm of the ocean, the pressure of the air, the subtle vibration"
},
{
"name": "code",
"tok_s": 105.2,
"reps": [
87.8,
113.5,
114.2
],
"hit_rate": 0.9109811738648947,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 382 windows; per window: wait for the GPU 15.155 ms, pool + plan 4.331 ms, host staging 0.656 ms, commit 0.458 ms",
"strata serve: stage 0: 455 windows; per window: wait for the GPU 15.790 ms, pool + plan 5.552 ms, host staging 0.688 ms, commit 0.467 ms",
"strata serve: stage 0: 524 windows; per window: wait for the GPU 16.064 ms, pool + plan 5.529 ms, host staging 0.606 ms, commit 0.472 ms",
"strata serve: stage 0: 593 windows; per window: wait for the GPU 16.305 ms, pool + plan 5.462 ms, host staging 0.540 ms, commit 0.475 ms"
],
"engine_lines": [
"strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots",
"strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is",
"strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)",
"strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)",
"strata serve: decode expert cache hit rate: 67.8% (2299 hits / 3391 lookups)",
"strata serve: decode expert cache hit rate: 68.5% (2345 hits / 3424 lookups)",
"strata serve: decode expert cache hit rate: 75.6% (16605 hits / 21959 lookups)",
"strata serve: decode expert cache hit rate: 73.3% (2608 hits / 3558 lookups)",
"strata serve: decode expert cache hit rate: 83.7% (104878 hits / 125346 lookups)",
"strata serve: decode expert cache hit rate: 92.7% (119739 hits / 129184 lookups)",
"strata serve: decode expert cache hit rate: 92.2% (116867 hits / 126770 lookups)",
"strata serve: decode expert cache hit rate: 68.1% (64111 hits / 94116 lookups)",
"strata serve: decode expert cache hit rate: 89.0% (96370 hits / 108259 lookups)",
"strata serve: decode expert cache hit rate: 91.1% (102827 hits / 112875 lookups)"
]
}
@@ -0,0 +1,72 @@
{
"label": "rel-5080",
"extra": [],
"gpus": "0",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2132.8,
"pp_tok_s": 1278.1,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 5008.9,
"pp_tok_s": 1672.8,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 7855.4,
"pp_tok_s": 2045.2,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13833.9,
"pp_tok_s": 2005.4,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3298.2,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 197.9,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 83.2,
"hit_rate": 0.8418683557684931,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow"
},
{
"name": "code",
"tok_s": 88.2,
"hit_rate": 0.7011385968111186,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"engine_lines": [
"strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots",
"strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is",
"strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)",
"strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)",
"strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)",
"strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)",
"strata serve: decode expert cache hit rate: 72.5% (2539 hits / 3504 lookups)",
"strata serve: decode expert cache hit rate: 77.3% (2817 hits / 3642 lookups)",
"strata serve: decode expert cache hit rate: 75.3% (16500 hits / 21916 lookups)",
"strata serve: decode expert cache hit rate: 80.0% (2978 hits / 3723 lookups)",
"strata serve: decode expert cache hit rate: 84.2% (98752 hits / 117301 lookups)",
"strata serve: decode expert cache hit rate: 70.1% (69215 hits / 98718 lookups)"
]
}
@@ -0,0 +1,78 @@
{
"label": "t75-5080",
"extra": [],
"gpus": "0",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2158.8,
"pp_tok_s": 1262.7,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 5060.0,
"pp_tok_s": 1655.9,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3389.7,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 213.5,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 80.4,
"reps": [
80.4
],
"hit_rate": 0.855538332528651,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, punctuated by whitecaps that looked like teeth.\n\nHe climbed the spiral stairs, his boots heavy with salt and exhaustion. The iron steps groaned under his weight, a sound that had become so familiar to him that he could sleep to it. But tonight, he wasn\u2019t sleeping. He was working.\n\nThe lens was the heart of the lighthouse. A massive, rotating Fresnel lens, a cathedral of glass and brass that turned with a mechanical hum. Elias checked the clockwork mechanism. It was smooth, rhythmic, a heartbeat in the dark. But the light itself was failing.\n\nHe climbed higher, into the lantern room. The wind battered the glass panes,"
},
{
"name": "code",
"tok_s": 87.5,
"reps": [
87.5
],
"hit_rate": 0.7075461363025227,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 39 windows; per window: wait for the GPU 17.252 ms, pool + plan 8.473 ms, host staging 0.611 ms, commit 0.525 ms",
"strata serve: stage 0: 47 windows; per window: wait for the GPU 18.018 ms, pool + plan 8.616 ms, host staging 0.607 ms, commit 0.534 ms",
"strata serve: stage 0: 169 windows; per window: wait for the GPU 15.223 ms, pool + plan 5.717 ms, host staging 0.688 ms, commit 0.467 ms",
"strata serve: stage 0: 243 windows; per window: wait for the GPU 16.500 ms, pool + plan 7.316 ms, host staging 0.742 ms, commit 0.481 ms"
],
"engine_lines": [
"strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots",
"strata generate: expert cache 4294 slots, 8.18 GiB of VRAM; policy is",
"strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)",
"strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)",
"strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)",
"strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)",
"strata serve: decode expert cache hit rate: 75.5% (16316 hits / 21602 lookups)",
"strata serve: decode expert cache hit rate: 74.4% (2660 hits / 3573 lookups)",
"strata serve: decode expert cache hit rate: 83.4% (92664 hits / 111086 lookups)",
"strata serve: decode expert cache hit rate: 72.0% (70946 hits / 98601 lookups)",
"strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots",
"strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is",
"strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)",
"strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)",
"strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)",
"strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)",
"strata serve: decode expert cache hit rate: 75.5% (16316 hits / 21602 lookups)",
"strata serve: decode expert cache hit rate: 74.4% (2659 hits / 3572 lookups)",
"strata serve: decode expert cache hit rate: 85.6% (101004 hits / 118059 lookups)",
"strata serve: decode expert cache hit rate: 70.8% (71044 hits / 100409 lookups)"
]
}
@@ -0,0 +1,103 @@
{
"label": "v-x2-auto",
"extra": [
"--layer-split",
"auto"
],
"gpus": "0,2",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2577.0,
"pp_tok_s": 1057.8,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 4433.5,
"pp_tok_s": 1889.9,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 7885.8,
"pp_tok_s": 2037.3,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13384.6,
"pp_tok_s": 2072.8,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3667.5,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 253.8,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 79.5,
"reps": [
78.9,
79.0,
80.7
],
"hit_rate": 0.9969903443250137,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, listening for the faint, rhythmic *tick-tick-tick* that signaled the rotation was true. If the rhythm faltered, ships"
},
{
"name": "code",
"tok_s": 108.9,
"reps": [
103.3,
113.7,
109.5
],
"hit_rate": 0.9971795386830036,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 542 windows; per window: wait for the GPU 7.167 ms, pool + plan 0.572 ms, host staging 0.550 ms, commit 0.232 ms",
"strata serve: stage 1: 542 windows; per window: wait for the GPU 12.855 ms, pool + plan 0.250 ms, host staging 0.000 ms, commit 0.334 ms",
"strata serve: stage 0: 610 windows; per window: wait for the GPU 7.276 ms, pool + plan 0.559 ms, host staging 0.493 ms, commit 0.234 ms",
"strata serve: stage 1: 610 windows; per window: wait for the GPU 13.048 ms, pool + plan 0.258 ms, host staging 0.000 ms, commit 0.337 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts",
"strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts",
"strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-21",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)",
"strata serve: decode expert cache hit rate: 98.5% (4241 hits / 4306 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (4262 hits / 4309 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (4290 hits / 4315 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4319 lookups)",
"strata serve: decode expert cache hit rate: 98.8% (28379 hits / 28721 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (4285 hits / 4314 lookups)",
"strata serve: decode expert cache hit rate: 98.5% (136232 hits / 138256 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (135540 hits / 136216 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (136812 hits / 137225 lookups)",
"strata serve: decode expert cache hit rate: 98.4% (118437 hits / 120406 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (112836 hits / 113230 lookups)"
]
}
@@ -0,0 +1,88 @@
{
"label": "v-x2r-auto",
"extra": [
"--layer-split",
"auto"
],
"gpus": "2,0",
"needles": [
{
"tokens": 16066,
"prompt_ms": 9610.0,
"pp_tok_s": 1671.8,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 14786.1,
"pp_tok_s": 1876.3,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3850.8,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 245.0,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 90.3,
"reps": [
91.0,
97.0,
82.8
],
"hit_rate": 0.993905472636816,
"text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak of the spiral staircase, every draft that slipped under the door, and every shift in the barometric pressure that preceded a storm. He was not merely a worker; he was the heartbeat of the coast.\n\nIt was November, the month of grey seas and shorter days. The fog had rolled in thick, a wall of white so dense that even the beam of the Fresnel lens seemed to struggle against it. Elias stood in the lantern room, his hands roughened by salt and rope, adjusting the rotation mechanism. The great lens, a cathedral of glass and brass, began its slow, rhythmic sweep. *Flash. Dark. Flash. Dark.*\n\nHe checked the log"
},
{
"name": "code",
"tok_s": 105.1,
"reps": [
98.4,
109.9,
107.0
],
"hit_rate": 0.9949900793650793,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 492 windows; per window: wait for the GPU 15.016 ms, pool + plan 0.297 ms, host staging 0.517 ms, commit 0.404 ms",
"strata serve: stage 1: 492 windows; per window: wait for the GPU 5.775 ms, pool + plan 0.854 ms, host staging 0.001 ms, commit 0.210 ms",
"strata serve: stage 0: 561 windows; per window: wait for the GPU 15.257 ms, pool + plan 0.306 ms, host staging 0.455 ms, commit 0.408 ms",
"strata serve: stage 1: 561 windows; per window: wait for the GPU 5.852 ms, pool + plan 0.820 ms, host staging 0.001 ms, commit 0.210 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55",
"strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free",
"strata generate: layer split auto: CUDA0 82 SMs at 1.86 GHz -> 0.48 ms per layer, 16.45 GiB for experts",
"strata generate: layer split auto: CUDA1 84 SMs at 2.81 GHz -> 0.31 ms per layer, 5.99 GiB for experts",
"strata generate: layer split auto: K=30 - predicted 20.8 ms per decode window; the caches hold 10684 of 12288 profiled pairs (~99.5% of the routed mass)",
"strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots",
"strata generate: expert cache 7680 slots, 14.23 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 30-47, expert cache 3004 slots (5.98 GiB), 3004 of its 4608 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-29",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-29 (CUDA0), 30-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 93.2% (5367 hits / 5760 lookups)",
"strata serve: decode expert cache hit rate: 93.7% (4049 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 96.7% (4178 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 97.7% (26272 hits / 26880 lookups)",
"strata serve: decode expert cache hit rate: 97.1% (4194 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 97.8% (110748 hits / 113280 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (113787 hits / 114240 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (127856 hits / 128640 lookups)",
"strata serve: decode expert cache hit rate: 96.3% (116528 hits / 120960 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (116423 hits / 117120 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (120354 hits / 120960 lookups)"
]
}
@@ -0,0 +1,89 @@
{
"label": "v-x3-auto",
"extra": [
"--layer-split",
"auto"
],
"gpus": "0,1,2",
"needles": [
{
"tokens": 16066,
"prompt_ms": 9525.4,
"pp_tok_s": 1686.6,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 15017.1,
"pp_tok_s": 1847.4,
"found": true,
"answer": "juniper-766<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4039.6,
"turn2_tokens": 6660,
"reused": 6631,
"turn2_ms": 360.2,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 67.6,
"reps": [
59.8,
83.1,
59.9
],
"hit_rate": 0.9967581085879247,
"text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with the force of a battering ram. Elias stood in the lantern room, his hands rough as sandpaper, adjusting the massive Fresnel lens. The rotation mechanism groaned, a sound like a ship\u2019s anchor chain being h"
},
{
"name": "code",
"tok_s": 89.6,
"reps": [
81.0,
104.8,
83.0
],
"hit_rate": 0.9975041387598007,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 2: 522 windows; per window: wait for the GPU 12.405 ms, pool + plan 0.242 ms, host staging 0.006 ms, commit 0.375 ms",
"strata serve: stage 0: 590 windows; per window: wait for the GPU 7.387 ms, pool + plan 0.549 ms, host staging 0.517 ms, commit 0.248 ms",
"strata serve: stage 1: 590 windows; per window: wait for the GPU 3.071 ms, pool + plan 0.011 ms, host staging 0.000 ms, commit 0.606 ms",
"strata serve: stage 2: 590 windows; per window: wait for the GPU 12.592 ms, pool + plan 0.250 ms, host staging 0.006 ms, commit 0.377 ms"
],
"engine_lines": [
"strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00",
"strata generate: layer split: CUDA1 holds its weights, session; 16.67 GiB free",
"strata generate: layer split: CUDA2 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA2 holds its weights, session and head; 18.13 GiB free",
"strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts",
"strata generate: layer split auto: CUDA1 68 SMs at 1.54 GHz -> 0.69 ms per layer, 13.50 GiB for experts",
"strata generate: layer split auto: CUDA2 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts",
"strata generate: layer split auto: K=22,23 - predicted 19.9 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 22-22, expert cache 256 slots (0.52 GiB), 256 of its 256 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA2 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-21",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-21 (CUDA0), 22-22 (CUDA1), 23-47 (CUDA2), one hand-off per window",
"strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)",
"strata serve: decode expert cache hit rate: 98.7% (4256 hits / 4310 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4315 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (29862 hits / 30170 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (4264 hits / 4313 lookups)",
"strata serve: decode expert cache hit rate: 98.6% (134418 hits / 136339 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (116986 hits / 117525 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (129134 hits / 129554 lookups)"
]
}
@@ -0,0 +1,84 @@
{
"label": "x2-auto-c1024",
"extra": [
"--layer-split",
"auto",
"--prefill",
"1024"
],
"gpus": "0,2",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2648.7,
"pp_tok_s": 1029.2,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 5547.0,
"pp_tok_s": 1510.5,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 10123.3,
"pp_tok_s": 1587.0,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 17652.0,
"pp_tok_s": 1571.7,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4379.9,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 235.5,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 82.7,
"hit_rate": 1.0,
"text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth."
},
{
"name": "code",
"tok_s": 111.1,
"hit_rate": 1.0,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV"
}
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: layer split auto: K=19 - the caches hold 12288 of 12288 profiled pairs (fullest device 99%)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3613 slots",
"strata generate: expert cache 4864 slots, 8.76 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7424 slots (14.66 GiB), 7424 of its 7424 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-18",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 100.0% (5760 hits / 5760 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (26400 hits / 26400 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (130080 hits / 130080 lookups)",
"strata serve: decode expert cache hit rate: 100.0% (110400 hits / 110400 lookups)"
]
}
@@ -0,0 +1,82 @@
{
"label": "x2-auto",
"extra": [
"--layer-split",
"auto"
],
"gpus": "0,2",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2711.7,
"pp_tok_s": 1005.3,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 5010.3,
"pp_tok_s": 1672.4,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 8994.8,
"pp_tok_s": 1786.1,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 15497.2,
"pp_tok_s": 1790.2,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4050.3,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 249.7,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 83.0,
"hit_rate": 0.9920220447608565,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. The massive Fresnel lens, a cathedral of glass and crystal, began its slow, hypnotic sweep"
},
{
"name": "code",
"tok_s": 101.8,
"hit_rate": 0.991767530342175,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-18",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 98.5% (6141 hits / 6234 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (3797 hits / 3838 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (3804 hits / 3838 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (3816 hits / 3839 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (3825 hits / 3839 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (27693 hits / 27832 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (3815 hits / 3839 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (127081 hits / 128103 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (119386 hits / 120377 lookups)"
]
}
@@ -0,0 +1,81 @@
{
"label": "x2-k16",
"extra": [
"--layer-split",
"16"
],
"gpus": "0,2",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2987.1,
"pp_tok_s": 912.6,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 5908.6,
"pp_tok_s": 1418.1,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 10655.8,
"pp_tok_s": 1507.7,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 18484.6,
"pp_tok_s": 1500.9,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4790.8,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 243.3,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 71.4,
"hit_rate": 0.9814261642156863,
"text": "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry the lighthouse from its bedrock. Inside, however, the air was still, smelling faintly of kerosene and old paper.\n\nElias had been the keeper of the Point for thirty-two years. He knew every creak in the floorboards, every draft that slipped through the window seals, and exactly how much oil the great Fresnel lens needed to turn its slow, hypnotic rotation.\n\nIt was 2:00 AM. The storm was at its peak. The sea was a chaotic black mirror, whipped into whitecaps that looked like jagged teeth.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His boots, heavy with salt and wear, thumped a steady rhythm against the stone. *Thump. Thump. Thump.*\n\nAt the top, the lantern room hummed with the vibration of"
},
{
"name": "code",
"tok_s": 86.4,
"hit_rate": 0.9798276439089693,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 16)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4096 slots, 7.17 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 16-47, expert cache 7124 slots (14.14 GiB), 7124 of its 8192 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-15",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-15 (CUDA0), 16-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 97.7% (5626 hits / 5760 lookups)",
"strata serve: decode expert cache hit rate: 98.1% (4237 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 98.8% (4269 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (4279 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (4298 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (28471 hits / 28800 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (4282 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 98.1% (128135 hits / 130560 lookups)",
"strata serve: decode expert cache hit rate: 98.0% (117109 hits / 119520 lookups)"
]
}
@@ -0,0 +1,81 @@
{
"label": "x2-k22",
"extra": [
"--layer-split",
"22"
],
"gpus": "0,2",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2537.7,
"pp_tok_s": 1074.2,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 4440.0,
"pp_tok_s": 1887.2,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 7872.5,
"pp_tok_s": 2040.8,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 13405.0,
"pp_tok_s": 2069.6,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 3610.4,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 236.0,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 78.1,
"hit_rate": 0.9851122208995093,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a hospital bed, waiting for the end.\n\nEvery night, Elias climbed the one hundred and twelve steps of the spiral staircase. His knees, worn smooth by the friction of his own boots over decades, protested with a sharp ache. He counted them. *One, two, three\u2026* The rhythm was his heartbeat. If he lost the count, he lost the light.\n\nAt the top, the lantern room hummed with the low, electric thrum of the Fresnel lens. It was a cathedral of glass and brass, a machine that had never failed him. Not once. Not in four decades.\n\nHe polished the brass railing with a rag that smelled of lemon and"
},
{
"name": "code",
"tok_s": 104.3,
"hit_rate": 0.9842543225870746,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-21",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)",
"strata serve: decode expert cache hit rate: 98.5% (4241 hits / 4306 lookups)",
"strata serve: decode expert cache hit rate: 98.9% (4262 hits / 4309 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (4290 hits / 4315 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4319 lookups)",
"strata serve: decode expert cache hit rate: 98.8% (28379 hits / 28721 lookups)",
"strata serve: decode expert cache hit rate: 99.3% (4285 hits / 4314 lookups)",
"strata serve: decode expert cache hit rate: 98.5% (135713 hits / 137764 lookups)",
"strata serve: decode expert cache hit rate: 98.4% (118518 hits / 120414 lookups)"
]
}
@@ -0,0 +1,82 @@
{
"label": "x2r-auto",
"extra": [
"--layer-split",
"auto"
],
"gpus": "2,0",
"needles": [
{
"tokens": 2726,
"prompt_ms": 2804.2,
"pp_tok_s": 972.1,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 5641.7,
"pp_tok_s": 1485.2,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 10643.4,
"pp_tok_s": 1509.5,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 18363.5,
"pp_tok_s": 1510.8,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 4517.2,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 245.6,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 78.9,
"hit_rate": 0.9913117283950618,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to sync with his own heartbeat. He had been doing this for forty years. His hands were mapped with scars from rope burns and broken glass, his eyes permanently squinted against the glare of the bulb."
},
{
"name": "code",
"tok_s": 93.4,
"hit_rate": 0.990286044973545,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55",
"strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free",
"strata generate: layer split auto: K=36 - the caches hold 11775 of 12288 profiled pairs (fullest device 100%)",
"strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots",
"strata generate: expert cache 8828 slots, 16.45 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 36-47, expert cache 2945 slots (5.99 GiB), 2945 of its 3072 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-35",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-35 (CUDA0), 36-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 98.6% (5678 hits / 5760 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (4283 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 99.2% (4285 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 99.7% (4306 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 99.5% (27700 hits / 27840 lookups)",
"strata serve: decode expert cache hit rate: 99.4% (4295 hits / 4320 lookups)",
"strata serve: decode expert cache hit rate: 99.1% (128474 hits / 129600 lookups)",
"strata serve: decode expert cache hit rate: 99.0% (119785 hits / 120960 lookups)"
]
}
@@ -0,0 +1,99 @@
{
"label": "x2t-auto",
"extra": [
"--layer-split",
"auto"
],
"gpus": "0,1",
"needles": [
{
"tokens": 2726,
"prompt_ms": 4201.1,
"pp_tok_s": 648.9,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 9655.6,
"pp_tok_s": 867.8,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 17573.8,
"pp_tok_s": 914.2,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 30615.6,
"pp_tok_s": 906.2,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 7864.7,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 366.9,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 45.5,
"reps": [
45.5
],
"hit_rate": 0.9703345151405784,
"text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, knew every bolt, every lever, and every creak in the iron bones of the tower.\n\nFor forty years, Elias had been the guardian of the Point. Not just of the light, but of the silence between the waves.\n\nIt was November. The sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that shook the floorboards beneath Elias\u2019s boots.\n\nHe climbed the stairs. One hundred and twelve steps. He counted them by feel, his left hand trailing along the cold iron railing. At the top, the air was"
},
{
"name": "code",
"tok_s": 58.0,
"reps": [
58.0
],
"hit_rate": 0.9700542735219787,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile"
}
],
"stage_timing": [
"strata serve: stage 0: 168 windows; per window: wait for the GPU 9.683 ms, pool + plan 0.509 ms, host staging 0.714 ms, commit 0.320 ms",
"strata serve: stage 1: 168 windows; per window: wait for the GPU 25.253 ms, pool + plan 0.881 ms, host staging 0.000 ms, commit 0.559 ms",
"strata serve: stage 0: 242 windows; per window: wait for the GPU 9.860 ms, pool + plan 0.550 ms, host staging 0.750 ms, commit 0.328 ms",
"strata serve: stage 1: 242 windows; per window: wait for the GPU 26.029 ms, pool + plan 0.980 ms, host staging 0.000 ms, commit 0.571 ms"
],
"engine_lines": [
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00",
"strata generate: layer split: CUDA1 holds its weights, session and head; 16.18 GiB free",
"strata generate: layer split auto: K=20 - the caches hold 10761 of 12288 profiled pairs (fullest device 100%)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 20-47, expert cache 6157 slots (12.19 GiB), 6157 of its 7168 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-19",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window",
"strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00",
"strata generate: layer split: CUDA1 holds its weights, session and head; 16.18 GiB free",
"strata generate: layer split auto: K=20 - the caches hold 10761 of 12288 profiled pairs (fullest device 100%)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots",
"strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 20-47, expert cache 6157 slots (12.19 GiB), 6157 of its 7168 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-19",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window",
"strata serve: decode expert cache hit rate: 96.6% (5559 hits / 5754 lookups)",
"strata serve: decode expert cache hit rate: 97.5% (4205 hits / 4315 lookups)",
"strata serve: decode expert cache hit rate: 97.8% (4217 hits / 4312 lookups)",
"strata serve: decode expert cache hit rate: 98.6% (4257 hits / 4318 lookups)"
]
}
@@ -0,0 +1,99 @@
{
"label": "x3-auto",
"extra": [
"--layer-split",
"auto"
],
"gpus": "0,2,1",
"needles": [
{
"tokens": 2726,
"prompt_ms": 3657.4,
"pp_tok_s": 745.3,
"found": true,
"answer": "meadow-254<|im_end|>"
},
{
"tokens": 8379,
"prompt_ms": 7594.1,
"pp_tok_s": 1103.4,
"found": true,
"answer": "juniper-766<|im_end|>"
},
{
"tokens": 16066,
"prompt_ms": 13996.4,
"pp_tok_s": 1147.9,
"found": true,
"answer": "falcon-174<|im_end|>"
},
{
"tokens": 27743,
"prompt_ms": 24255.2,
"pp_tok_s": 1143.8,
"found": true,
"answer": "willow-474<|im_end|>"
}
],
"chat": {
"turn1_tokens": 6584,
"turn1_ms": 6104.9,
"turn2_tokens": 6660,
"reused": 6632,
"turn2_ms": 393.4,
"answer": "lantern-417<|im_end|>",
"ok": true
},
"decode": [
{
"name": "story",
"tok_s": 51.9,
"reps": [
51.9
],
"hit_rate": 1.0,
"text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth."
},
{
"name": "code",
"tok_s": 69.7,
"reps": [
69.7
],
"hit_rate": 1.0,
"text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV"
}
],
"stage_timing": [
"strata serve: stage 2: 165 windows; per window: wait for the GPU 13.452 ms, pool + plan 0.162 ms, host staging 0.000 ms, commit 0.328 ms",
"strata serve: stage 0: 234 windows; per window: wait for the GPU 6.235 ms, pool + plan 0.145 ms, host staging 0.704 ms, commit 0.214 ms",
"strata serve: stage 1: 234 windows; per window: wait for the GPU 15.592 ms, pool + plan 0.246 ms, host staging 0.000 ms, commit 0.657 ms",
"strata serve: stage 2: 234 windows; per window: wait for the GPU 13.916 ms, pool + plan 0.177 ms, host staging 0.000 ms, commit 0.335 ms"
],
"engine_lines": [
"strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session; 18.62 GiB free",
"strata generate: layer split: CUDA2 PCIe probe 3.2 GB/s -> pcie_frac 0.00",
"strata generate: layer split: CUDA2 holds its weights, session and head; 16.18 GiB free",
"strata generate: layer split auto: K=12,33 - the caches hold 12288 of 12288 profiled pairs (fullest device 66%)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3072 slots",
"strata generate: expert cache 3072 slots, 5.41 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 12-32, expert cache 5376 slots (10.22 GiB), 5376 of its 5376 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA2 runs layers 33-47, expert cache 3840 slots (7.79 GiB), 3840 of its 3840 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-11",
"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)",
"strata serve: layer split: layers 0-11 (CUDA0), 12-32 (CUDA1), 33-47 (CUDA2), one hand-off per window",
"strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)",
"strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14",
"strata generate: layer split: CUDA1 holds its weights, session; 18.62 GiB free",
"strata generate: layer split: CUDA2 PCIe probe 3.2 GB/s -> pcie_frac 0.00",
"strata generate: layer split: CUDA2 holds its weights, session and head; 16.18 GiB free",
"strata generate: layer split auto: K=12,33 - the caches hold 12288 of 12288 profiled pairs (fullest device 66%)",
"strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3072 slots",
"strata generate: expert cache 3072 slots, 5.41 GiB of VRAM; policy is",
"strata generate: layer split: CUDA1 runs layers 12-32, expert cache 5376 slots (10.22 GiB), 5376 of its 5376 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA2 runs layers 33-47, expert cache 3840 slots (7.79 GiB), 3840 of its 3840 profiled pairs; slot 0 verified",
"strata generate: layer split: CUDA0 runs layers 0-11"
]
}
File diff suppressed because it is too large. Load diff
+9 -3
View File
@@ -311,10 +311,16 @@ print(r.choices[0].message.content)
**Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: the
live session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each new
assistant turn and every 16K prompt tokens). A checkpoint is used only when the prompt starts with exactly its tokens
and pictures. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, `--turn-token ID`.
and pictures. The oldest checkpoint - in practice the end of the system prompt, which every chat of the same client
shares - is kept for good while the rest rotates by least recent use, so a NEW chat that shares that prefix starts
reading after it instead of from token 0. A prompt read from the start is also checkpointed at the end of its system
prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that root exists for agent clients with long
system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`,
`--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`.
**Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats
re-reads the other one); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p /
**Current limits (v1):** one request at a time, and one conversation's history in the KV cache at a time (switching
between two chats re-reads the part where they diverge; the shared prefix, such as the system prompt, is reused); images
only when set up with them (below); no video. **Temperature / top_p / top_k / min_p /
seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result
is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the
engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out
+122
View File
@@ -0,0 +1,122 @@
# Strata on two or three GPUs (layer split)
One model can run across several NVIDIA cards in one PC. The layers are split into contiguous ranges, one per GPU:
the first card runs layers 0 to K-1, the next card runs K onward, and so on; the last card also runs the output head
and the draft (MTP) layer. Each card keeps an expert cache for **its own layers only**, so two cards hold about twice
the experts one card holds - for the Coder model on a 16 GB + 24 GB pair, nearly all of them, which is where the
speed comes from (decode then barely touches the CPU pool).
This is pipeline (layer) parallelism, not tensor parallelism: a token crosses from one card to the next once per
verify window (a few hundred KB through pinned RAM), not twice per layer. No NVLink or peer-to-peer access is
needed; cards on x4 or x1 slots work, and the PCIe share of each card is probed on its own link.
## Using it
**Nothing to type.** `START-HERE.bat` (Linux: `./setup.sh`) lists your NVIDIA cards and says for each one whether
Strata can use it:
```
Your NVIDIA GPUs:
GPU 0: NVIDIA GeForce RTX 5080, 16 GB VRAM - can be used
GPU 1: NVIDIA GeForce RTX 2080 Ti, 22 GB VRAM - not supported - older than the RTX 30 series (compute capability 7.5; Strata needs 8.0 or newer)
GPU 2: NVIDIA GeForce RTX 3090, 24 GB VRAM - can be used
...
1) GPU 0 (NVIDIA GeForce RTX 5080, 16 GB) + GPU 2 (NVIDIA GeForce RTX 3090, 24 GB) together (recommended)
2) GPU 2 (NVIDIA GeForce RTX 3090, 24 GB) only
3) GPU 0 (NVIDIA GeForce RTX 5080, 16 GB) only
Which GPUs? [1]:
```
When two or more cards can share the model, the two best together are recommended (the newest generation first:
it becomes the main card). A model installed on one card asks once, at its next start, whether to use both from
now on; the answer is kept.
**Choosing yourself** (at setup or at any start):
```
--gpus 0,2 these cards together, as nvidia-smi numbers them; the first is the main one. Remembered.
--gpus all every card that can share the model
--gpu 0 one card (at a start: for that start only)
--layer-split auto (default) or the first layer of each later card, e.g. 18 or 16,32
```
**Not supported** (setup says so and names the cards that can be used instead):
- a card older than the RTX 30 series (compute capability below 8.0: RTX 20, GTX 16/10);
- a card with less than 8 GB of VRAM, together with others (each card holds a copy of the dense weights and its
own prompt buffers);
- AMD and Intel GPUs, and a mix of NVIDIA with them.
Or edit an existing config (`strata-*.json`), then restart:
```json
"gpu": [0, 2],
"layer_split": "auto"
```
The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D1[,D2..]` (the later stages'
devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing
everything - the bit-exact check of the hand-off, not a speed mode.
**auto** tries every placement (all of them for two or three cards; proportional to the free VRAM beyond that) and
keeps the one whose caches would hold the most of the expert profile, hottest pairs weighted most; ties go to the
placement that leaves the fullest card the most room. The startup log prints the choice:
```
strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%)
strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window
```
## What each card holds
- **every card**: a copy of the dense weights (~3.4 GB for the Coder), its own session state (the KV cache of the full
context), its verify window and its prompt-path buffers, and an expert cache for its layers filled from the profile;
- **the last card**: also the output head and the draft layer (~0.8 GB);
- **host RAM**: the expert arena once, shared by all cards (the CPU pool computes whatever no card holds).
Prompts are read in chunks that flow through the cards in turn; while a later card reads chunk c, the first card
already reads chunk c+1. Conversation checkpoints save and restore every card's state; the adaptive expert swaps copy
into the card that owns the layer.
## Limits (for now)
- **Works across cards** (bench/results/2026-09-29-layer-split-limits):
- images (`--vision`): each card keeps its own image-position table;
- control vectors and the experimental speed projection: each card holds the vector's tables, switched on and
off per request on all of them;
- KV streaming (`--kv-resident`): each card streams the KV of its own session;
- mid-prompt checkpoints (`--prompt-cache-every`): each card saves its part of a checkpoint when it has read that
chunk;
- the older helper-GPU caches (`--expert-cache-remote`, docs/SECOND_GPU.md): they take the visible GPUs no stage
runs on, and hold only experts no stage's cache holds. On the test rig, a 2080 Ti helper made decoding slower,
as it did without a split: its per-layer round trip costs more than the CPU pool needs for those experts.
- `--mmap-experts` needs a canonical pack (`experts.bin`), with or without a split; a native (IQ) pack says so at
start.
- The prompt path has its own buffers on every card (1.5 GB each at the default 2048-token chunk; `--prefill 1024`
halves that) instead of borrowing cache slots as one card does. An explicit `--expert-cache` on the first card is
capped to leave room for them.
- On Windows only 8 GiB of the expert arena is pinned (more, mapped into two GPU contexts, leaves WDDM refusing
allocations); the PCIe share covers those layers.
- Every card needs compute capability 8.0 (RTX 30 or newer). A Turing card (RTX 20, sm_75) builds only with the
experimental `-DSTRATA_EXPERIMENTAL_SM75=ON`.
## Measured
The Coder on an RTX 5080 + RTX 3090 (Ryzen 9 9950X3D), 32K context; details in
`bench/results/2026-09-29-layer-split/`:
| | Prompt 16K / 28K tok/s | Decode story / code tok/s |
|---|---|---|
| 5080 alone | 1,726-2,017 / 1,970 | 83-87 / 88-105 |
| 5080 + 3090, best split (K=26) | 2,039 / 2,357 | 84 / 110 |
| 5080 + 3090, auto (K=22) | 2,037 / 2,073 | 80 / 109 |
- **Prompts gain the most** (+18-20%): each card reads its own layers of the chunk while the other reads the next.
- **Decode is on par with the faster card alone**, and ahead on code. Once both caches hold nearly every routed
expert, the per-layer GPU time decides.
- **Correctness:** one GPU is byte-identical to 0.1.20, and the hand-off itself is bit-exact.
**Which cards and in what order:**
- Put the fastest card first; auto gives it as many layers as its cache allows.
- Leave out a much slower card when two already hold the model. An RTX 2080 Ti as a third card made the 5080 +
3090 pair slower (68 / 90 tok/s decode): every extra card costs its own round per window.
- More cards pay off when the model's routed experts do not fit the faster ones.
+95
View File
@@ -0,0 +1,95 @@
# OrcaRouter IQ3_XXS compatibility
Validated on Linux with an RTX 5090 (32 GB), Ryzen 9 9950X3D and 128 GB RAM on 2026-09-27.
The target is `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF`, **IQ3_XXS** (two shards, 85.20 GB total).
It has Strata's Qwen4Exp geometry, but ordinary quantization also compresses the hyperconnection,
small attention and PLE projections which Strata's kernels read as BF16.
`tools/iq_pack.py --compat-bf16` expands only those projections, rounding to BF16 using nearest-even.
This adds rounding relative to the GGUF's dequantized weights; it does not recover the original BF16
checkpoint or its quality. Expert weights, native attention weights, embeddings and the 28.8 GB PLE
lookup table remain unchanged. The latter stays on disk. The pack records its conversions in
`compat-bf16.json`.
The native loader retains this pack's converted PLE key. Its existing native Q2_0 key path remains
available to the original model. Hugging Face snapshot symlinks are supported; all split shards must
finish downloading before packing. Pass the snapshot filename, not its hash-named blob target.
## Preparation
Build Strata normally using the pinned llama.cpp dependency. Python needs numpy, regex and gguf-py
from that dependency (`STRATA_GGUF_PY` can point to its `gguf-py` directory).
```sh
.venv/bin/python tools/iq_pack.py \
--gguf /path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf \
--out packs/orca-iq3_xxs --compat-bf16
```
Use this model's own tokenizer exported into the pack. Do not share another model's `dense.bin`,
and do not rename the Orca files to impersonate one of setup's GSQ-RCO models.
Strata's persistent server also requires the MTP runtime, prepared by the existing tools:
```sh
.venv/bin/python tools/mtp_fetch.py fetch --out mtp
.venv/bin/python tools/mtp_pack.py --src mtp --experts q2_0 --out mtp/mtp-q2_0.gguf
.venv/bin/python tools/mtp_rt.py --gguf mtp/mtp-q2_0.gguf --out mtp/rt
cp data/draft_vocab.bin mtp/rt/draft_vocab.bin
```
This uses the original model's draft head, as setup does for Swift. The target model verifies its
proposals; draft acceptance and performance must be measured for this fine-tune.
## Local server
Save the following as `strata-orca-iq3_xxs.json` at the repository root, replacing both `/path/to/`
entries with the **same first shard**. Orca's PLE table is in shard 1. Start with a 32K context and
512-token prefill chunks; the expert cache sizes itself to available VRAM. The expert arena alone
needs about 49.8 GiB of available system RAM, plus draft/runtime buffers and other applications.
```json
{
"exe": "build/strata",
"args": [
"--pack", "packs/orca-iq3_xxs",
"--native", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf",
"--ple-gguf", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf",
"--expert-profile", "data/expert-profile.bin", "--expert-cache", "auto",
"--prefill", "512", "--spec", "4", "--spec-min-p", "0.5",
"--mtp", "mtp/rt", "--max-context", "32768", "--kv", "int8"
],
"cwd": ".",
"tokenizer": "packs/orca-iq3_xxs/tokenizer",
"model_name": "orcarouter-qwen3.8-flash-next-uncensored-iq3_xxs",
"log": "strata-orca-iq3_xxs.log",
"host": "127.0.0.1",
"port": 8080
}
```
Run from the repository root:
```sh
.venv/bin/python -m serve.server --engine strata --config strata-orca-iq3_xxs.json --port 8080
```
The web interface is at `http://127.0.0.1:8080`; API clients use `http://127.0.0.1:8080/v1`.
Vision is not configured in this text-only example. Performance of the original GSQ-RCO model
does not establish this fine-tune's speed or accuracy.
## Scope and validation
- IQ3_XXS is the target of this change; other Orca quantizations are not validated.
- IQ3_M additionally uses Q5_0 expert down matrices, which the native GPU expert path does not support.
- The installer model menu is unchanged. This is an explicit local packing workflow.
- Focused conversion and split-file tests: `.venv/bin/python -m unittest discover -s tools -p test_iq_pack.py`.
- All eight packing tests, 17 server tests and the GPU gated-residual parity check passed.
- The complete model packed successfully: 460 tensors converted, 1.39 GiB of converted BF16 weights;
1.43 GiB total packed dense weights. The 48 expert layers remain IQ3_XXS gate/up and IQ4_NL down.
- Real server checks passed: arithmetic, Python code, translation, a longer explanation, multi-turn context
reuse (25 prompt tokens reused), streaming cancellation and a subsequent correct response. The engine
PID stayed unchanged. These are smoke tests, not a quality benchmark or a full-context stress test.
- With the configuration above, a 111-token explanation generated at 77.7 tokens/s (engine decode timing);
total request time was 1.77 seconds. This single short measurement is not a general throughput claim.
+84
View File
@@ -0,0 +1,84 @@
# CUDA1–3 expert experiment
CUDA0 keeps the dense layers, KV/state, MTP and its existing expert cache. Up to
three independent expert caches fill CUDA1, CUDA2 and CUDA3 in that order. Each
expert has one owner: CUDA0, one secondary GPU, or the CPU pool. Each secondary
GPU computes its rows while the CPU pool works; the results return through
private pinned host buffers before CUDA0 continues the layer. The GPU launches
can overlap, but each layer waits for all three.
The shipped profile ranks 8,000 `(layer, expert)` pairs. CUDA0 takes its usual
`--expert-cache auto` allocation. With only CUDA1, it takes the first remaining
pairs. When CUDA2 or CUDA3 is enabled, the remaining profiled pairs are assigned
round robin to the secondary GPUs. The ranked list is then extended with all
other pairs in expert-then-layer order and distributed in the same way. This
fills the additional VRAM and lets all secondary GPUs see frequent experts, but
unranked experts may hardly ever be routed. The startup
log reports slots and GiB per card; each request reports the number of expert
entries actually computed on each secondary GPU. Remote outputs are packed
before returning over PCIe/USB4: the request log compares MiB transferred
with the previous full-row transfer. The input and routing metadata use pinned
host staging. This reduces transfer traffic and launch overhead, but does not
release the expert arena in system RAM or significantly change VRAM use.
The optional `--gpu-placement layer` gives each layer to exactly one secondary
GPU (layer number modulo the number of enabled cards). It fills that card with
the most frequently routed experts of its layers first, then the unranked ones.
This can reduce USB4 device switches and synchronization when several secondary
cards serve the same layer in the default `stripe` mode. All three cards still
keep their requested expert slots; the primary CUDA0 cache and CPU fallback
continue to work. The log counts active layer launches on each card, so the
tradeoff can be measured alongside tokens per second. This placement is
experimental and may be slower if a given layer needs more than one card's
compute capacity.
The experiment requires the corresponding visible CUDA devices and a CUDA
enabled build. Each card must keep at least 512 MiB free. Tiers must be enabled
in order. On Windows, CUDA registration of the host expert arena is capped at
8 GiB to leave room for the contexts and MTP on CUDA0. The rest remains
available to the CPU pool; the PCIe expert path is available only for the
registered layers. Without secondary GPUs, the original uncapped registration
behavior applies.
On an existing Linux installation, apply the patch to its source tree, then run:
```sh
./setup.sh --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000
```
On Windows, from PowerShell in the installation folder:
```powershell
.\START-HERE.bat --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000
```
To test the layer placement instead, add `--gpu-placement layer` to the setup
command. To go back, run the same command with `--gpu-placement stripe`. After
the new engine is built, the mode can also be changed without a rebuild: edit
`--expert-cache-remote-placement` in `strata-iq3_xxs.json` from `layer` to
`stripe` or vice versa and restart the server. If the argument is absent, the
default is `stripe`.
Choose the same model, size, context and image settings as your current
installation when prompted. Setup recompiles the engine, updates its server
configuration, and starts it. Later starts keep those settings. To tune the
slots without recompiling, edit the values after `--expert-cache-device1`,
`--expert-cache-device2` and `--expert-cache-device3` in the stored
`strata-iq3_xxs.json`, then restart with `.\run-iq3_xxs.bat`.
Compare identical requests at one, two and four GPUs, preferably with several
repeats. VRAM use alone does not show useful offload: compare the per-request
CUDA1–3 counts and tokens per second. More GPU contexts and synchronization
may lower the speed. Prompt prefill still uses CUDA0; secondary GPUs serve
decode, including MTP verification. No peer-to-peer access is required.
Longer contexts reserve more KV/state memory on CUDA0, which reduces its
automatic expert cache. On a 64 GB PC `setup.py` limits IQ3_XXS to 128K even
if 262K was selected; the secondary caches still require the host expert arena.
To try 262K on 64 GB, choose Q2_0 or IQ2_XS instead and check that CUDA0 still
has enough free VRAM after loading. Benchmark long prompts separately from
short decode requests.
The existing warning about the CUDA0 expert-cache GPU hit path still applies:
its outputs diverge from cache-off runs. Treat performance as experimental
until the generated tokens have been validated.
+4
View File
@@ -126,6 +126,10 @@ public:
/// against a `cudaStreamNonBlocking` one. The first version used the async form and `verify_slot` refused
/// the whole run with "slot 0 differs from the arena at byte 0" - which is the check doing its job.
bool fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0);
/// perf-review D-4: `fill_slot_blocking`'s copy on the same (legacy) stream, but queued: many slots are refilled
/// with one `sync_queued` at the end instead of a wait per slot. Same ordering against earlier work, same bytes.
bool fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0);
bool sync_queued(std::string& err);
/// Reads `slot` back to the host and compares it to `host_blob`, byte for byte. **THE ONLY THING THAT SAYS
/// THE CACHE HOLDS THE EXPERT IT CLAIMS TO.** A slot table that is right about indices and wrong about
+6 -1
View File
@@ -31,6 +31,8 @@
namespace strata::core {
class RemoteExperts;
/// Where one routed expert's bytes come from.
///
/// Phase 2 has NO cache (`phase-2-correct-engine.md`: hit rate `h = 0`), so the only implementation is a
@@ -92,6 +94,8 @@ struct GpuPlanSink {
struct ExpertDispatch {
strata::kernels::cpu::ExpertPool* pool = nullptr;
ExpertSource* src = nullptr;
RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows
int remote_count = 0;
int64_t n_expert = strata::kernels::cpu::NE;
/// Counters, for the driver to report rather than for control flow.
@@ -320,7 +324,8 @@ public:
/// Allocates and loads `<pack_dir>/experts.bin`. Prints nothing; the caller reports `note()` and the load
/// rate, because those are the two numbers that say whether the arena is the one that was asked for.
bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err);
bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err,
uint64_t max_pinned_bytes = 0);
/// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's shard 1.
void set_gguf(const std::string& shard1) { gguf_ = shard1; }
void close();
+5
View File
@@ -76,6 +76,7 @@ public:
private:
bool record_forward(int T, int step_row0, cudaStream_t cs, std::string& err);
bool capture_prefill(int T, std::string& err);
bool capture_prefill_dev(int T, std::string& err); ///< E-4: without the mapped staging (inputs copied on device)
bool capture_round(int T, std::string& err);
bool capture_step(int j, std::string& err);
cudaGraphExec_t step_exec_[9] = {};
@@ -89,11 +90,15 @@ private:
const NativeHead* head_ = nullptr;
const float* window_R_ = nullptr;
int max_t_ = 0;
int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split)
int max_drafts_ = 1 << 30;
int64_t n_vocab_ = 0;
uint64_t vram_ = 0;
cudaStream_t cs_ = nullptr;
cudaGraphExec_t prefill_exec_[9] = {};
cudaGraphExec_t prefill_dev_exec_[9] = {};
int32_t* pf_dev_ = nullptr; ///< E-4: a prompt's rows' token / step / position records, uploaded at once
int64_t pf_cap_ = 0; ///< its capacity in ints
cudaGraphExec_t round_exec_[9] = {};
struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; };
+22
View File
@@ -0,0 +1,22 @@
#pragma once
// Multi-GPU: make `device` current for a scope and restore the caller's device after it. An object that owns CUDA
// streams, graphs and buffers on one device (a verify stage, the drafter) wraps its public calls in this, so the
// caller's thread may be on any device. A negative device, or the device already current, does nothing.
#include <cuda_runtime.h>
namespace strata::core {
struct OnDevice {
int previous = -1;
explicit OnDevice(int device) {
int cur = 0;
if (device >= 0 && cudaGetDevice(&cur) == cudaSuccess && cur != device && cudaSetDevice(device) == cudaSuccess)
previous = cur;
}
~OnDevice() { if (previous >= 0) cudaSetDevice(previous); }
OnDevice(const OnDevice&) = delete;
OnDevice& operator=(const OnDevice&) = delete;
};
} // namespace strata::core
+2 -1
View File
@@ -39,7 +39,8 @@ struct PinnedArena {
explicit PinnedArena(uint64_t bytes, uint64_t slice = 0);
/// Plan v0.3 P6: slices of different sizes (one per layer of a native pack), given as their start offsets
/// followed by the end of the last one. `slice_starts` holds the registered ones.
PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds);
/// `max_pinned_bytes`: optional cap on CUDA registration. 0 preserves the normal unrestricted path.
PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds, uint64_t max_pinned_bytes = 0);
std::vector<uint64_t> slice_starts;
~PinnedArena();
PinnedArena(const PinnedArena&) = delete;
+85
View File
@@ -0,0 +1,85 @@
#pragma once
#include "strata/core/expert_cache.hpp"
#include "strata/core/expert_source.hpp"
#include <cuda_runtime.h>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
namespace strata::core {
/// A static, profile-filled expert tier on another CUDA device. CUDA0 keeps all
/// dense weights and state; results return through the existing pinned CPU rows.
class RemoteExperts {
public:
RemoteExperts() = default;
~RemoteExperts();
RemoteExperts(const RemoteExperts&) = delete;
RemoteExperts& operator=(const RemoteExperts&) = delete;
/// Initialise the device before the host expert arena registers
/// tens of GiB of portable mapped memory with CUDA.
static bool preflight(int device, double& free_gib, std::string& err);
bool open(int device, int slots, int64_t layers, int64_t experts,
const std::vector<std::pair<int32_t, int32_t>>& ranked,
const ExpertCache& primary, ExpertSource& source,
std::vector<uint8_t>& claimed, std::string& err);
void close();
/// `kind` is the primary verifier's classification (-1 = CPU candidate),
/// or null on the one-token path. Entries already served on CUDA0 are excluded.
bool begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok,
int64_t k, const int32_t* kind, const int32_t* primary_res,
std::string& err);
bool owns(int64_t index) const { return owned_[(size_t) index] != 0; }
bool finish(float* out, std::string& err);
int64_t resident() const { return cache_.resident(); }
int64_t computed() const { return computed_; }
int64_t launched_layers() const { return launched_layers_; }
double gib() const { return cache_.gib(); }
uint64_t returned_bytes() const { return returned_bytes_; }
uint64_t full_row_bytes() const { return full_row_bytes_; }
/// host time spent in begin() (staging + launches) and in finish() (waiting for this GPU), cumulative
double ms_begin() const { return ms_begin_; }
double ms_wait() const { return ms_wait_; }
private:
int device_ = -1;
int64_t n_expert_ = 0;
int32_t groups_ = 0;
int64_t computed_ = 0;
int64_t launched_layers_ = 0;
uint64_t returned_bytes_ = 0;
uint64_t full_row_bytes_ = 0;
double ms_begin_ = 0, ms_wait_ = 0;
ExpertCache cache_;
cudaStream_t stream_ = nullptr;
float* h_x_ = nullptr;
float* h_out_ = nullptr;
void* h_meta_ = nullptr;
float* d_x_ = nullptr;
float* z_x_ = nullptr; ///< h_x_ as the helper GPU sees it (zero-copy: no input copy per layer)
float* z_out_ = nullptr; ///< h_out_ as the helper GPU sees it (zero-copy: no result copy)
bool zero_copy_ = false;
float* d_out_ = nullptr;
uint8_t* d_q8_ = nullptr;
float* d_scales_ = nullptr;
void* d_scratch_ = nullptr;
void* d_meta_ = nullptr; ///< one contiguous upload of grouped indices, instead of five small copies
int32_t* d_start_ = nullptr;
int32_t* d_dst_ = nullptr;
int32_t* d_tok_ = nullptr;
int32_t* d_count_ = nullptr;
unsigned long long* d_ptr_ = nullptr;
std::vector<uint8_t> owned_;
std::vector<uint8_t> layers_present_;
std::vector<int32_t> group_of_, group_id_;
std::vector<int32_t> start_, dst_, tok_, original_row_;
std::vector<unsigned long long> ptr_;
};
} // namespace strata::core
+32 -2
View File
@@ -44,6 +44,8 @@ using PoolMultiFn = void (*)(void* user, const float* x_f, const int32_t* ids, i
struct VerifyHits {
const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] slot or -1
const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena
const uint64_t* slot_off = nullptr; ///< E-6: host per-slot offsets when slots differ in size (null: slot * blob)
int64_t n_slots = 0; ///< E-6: how many (for the device copy)
int64_t blob = 0;
};
@@ -69,6 +71,7 @@ public:
/// parameters would otherwise be baked forever - so this can change between requests freely.
void set_sampling(const strata::kernels::SamplerParams& sp) {
sampling_ = sp; // row t of a window at pos0 draws Philox(seed, pos0 + t): see run()
if (next_) next_->set_sampling(sp);
}
/// The penalty histories for `sampling_.penalty_last_n`: ONE ROW PER WINDOW ROW, T rows of `history_len`
@@ -80,18 +83,35 @@ public:
void set_history(const int32_t* history, int history_len) {
hist_d_ = history;
hist_len_ = history_len;
if (next_) next_->set_history(history, history_len);
}
/// Off: `run` skips the request's head sampling and `out` is the recorded greedy pick. For windows whose
/// picks are discarded - a prompt read through windows commits every token - so they cost no sampler launch
/// or sync and never read a history staged for another position.
void set_head_sampling(bool on) { head_sampling_ = on; }
void set_head_sampling(bool on) { head_sampling_ = on; if (next_) next_->set_head_sampling(on); }
/// LAYER SPLIT (multi-GPU): this verifier runs layers [layer_begin, layer_end) of every window. A stage that
/// does not start at layer 0 takes its residual from `handoff_in` instead of embedding the tokens; a stage that
/// does not end at the last layer writes its residual to `handoff_out` and has no head. The hand-off holds,
/// per token, the residual R (hc x n_embd), the last layer's pending write bo (n_embd) and inject (hc): the next
/// stage folds that write into its first read exactly as the unsplit window does, so the split is bit-exact.
/// Both pointers must be device-visible (mapped pinned memory, portable when the stages are on two devices).
/// Set before `init`. Default: the whole model, no hand-off.
void set_stage(int64_t layer_begin, int64_t layer_end, const float* handoff_in, float* handoff_out) {
lb_ = layer_begin; le_ = layer_end; hand_in_ = handoff_in; hand_out_ = handoff_out;
}
/// 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; }
/// floats per token in a hand-off buffer
static int64_t handoff_floats(const ModelGeometry& g) { return (int64_t) g.hc * g.n_embd + g.n_embd + g.hc; }
/// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them.
bool commit(int n_keep, std::string& err);
/// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`.
const float* final_R(int t) const;
const float* final_R_all() const { return R_; }
const float* final_R_all() const { return next_ ? next_->final_R_all() : R_; }
/// The GPU plan the pool writes each layer (VRAM hits + the PCIe share of the misses); give it to the
/// dispatch (`ExpertDispatch::plan`) before the first `run`.
@@ -119,6 +139,16 @@ private:
const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply
int hist_len_ = 0;
bool head_sampling_ = true; ///< set_head_sampling
int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)
bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN)
uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's)
unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device
int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last)
const float* hand_in_ = nullptr;
float* hand_out_ = nullptr;
Verifier* next_ = nullptr;
void* next_user_ = nullptr;
bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs
bool capture_commit(std::string& err);
bool record_window(int T, cudaStream_t cs, std::string& err);
+6 -1
View File
@@ -43,7 +43,12 @@ const Cvec& cvec();
bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int mode, int first, int last,
int64_t n_embd, int64_t hc, std::string& err);
/// The per-request switch. Synchronizes the device when it changes, so call it between requests.
/// A layer split: put the loaded vector's tables on the CURRENT device too (cvec_apply uses the tables of the device
/// it runs on). No-op without a vector or when this device has them already.
bool cvec_replicate(std::string& err);
/// The per-request switch, on every device that holds the vector. Synchronizes them when it changes, so call it
/// between requests.
void cvec_set_enabled(bool on);
bool cvec_enabled();
+1
View File
@@ -18,6 +18,7 @@
namespace strata::kernels {
/// The table of the CURRENT device (a layer split sets one per device; null = the identity).
void mrope_table_set(const int32_t* device_table);
const int32_t* mrope_table();
@@ -27,6 +27,13 @@ bool native_qsa_indexer_enabled();
// max_cells is a positive fixed capacity; pos_base+max_cells must fit int32.
// Out-of-range device positions are ignored defensively, not host-validated.
// This adapter does not alter score accumulation, top-k, or finite 1e9 tail bias.
// perf-review C-2: the appends of cells [p0, p0 + n) at once, leaving the buffers exactly as n calls of the
// single append in order would (the prompt path appends a chunk before any query reads the state). raw [n, 128].
// Host-side positions (not for a captured graph).
void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma,
float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells,
float freq_base, void* stream);
void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device,
int32_t pos_base, const float* gamma, float epsilon,
const QsaIndexerBuffers& buffers, const QsaShapes& shapes,
@@ -0,0 +1,31 @@
// include/strata/kernels/qsa_prompt_attn.hpp - perf-review D-1: the prompt path's QSA attention on tensor cores.
//
// `qsa_decode_attn_batch` serves a prompt one query at a time with the decode kernel: FP32 dot products with a warp
// reduction per head and cell, 64-cell chunks whose partial sums go through global scratch to a second (merge)
// kernel. At 32K that is 21% of the prompt (5.6 s of 26 s on a 5070, Q2_0, int8 KV), and it is limited by
// instruction issue, not memory (~150 GB/s of logical reads, 3.4 TFLOP/s).
//
// This kernel keeps the same per-query selection (no masking, no union) and reads the same pools, but:
// * one block per (query, KV head) walks all its selected cells in chunks of 32 with an online softmax: no
// split-K scratch and no merge kernel;
// * q.k and p.v are m16n8k16 FP16 MMAs with FP32 accumulation over the 12 query heads of the KV head (+4 pad rows);
// * the stored values enter exactly: int8 codes are exact in FP16 and their per-64 scales are applied in FP32
// (to the q.k partial of each 64-dim group, and folded into p for p.v); FP16 KV is used as is;
// * q and p are split into FP16 hi + lo parts (two MMAs each), so they keep ~22 bits: the result differs from
// the FP32 kernel by summation order and the exp2 rounding, not by an FP16 cast.
// Not bitwise equal to `qsa_decode_attn_batch`; `qsa_prompt_attn_parity` bounds the difference and the prompt
// quality gate (needles, teacher-forced top-1) checks it end to end. Q4_0 KV is not handled (returns false).
#pragma once
#include "strata/kernels/qsa_decode_attn.hpp"
#include <cstdint>
namespace strata::kernels {
/// Same arguments and output as `qsa_decode_attn_batch` minus the scratch. Returns false (nothing launched) when the
/// pools are Q4_0 or the geometry is not 24 heads / 2 KV heads / 256: the caller then uses the old kernel.
bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream);
} // namespace strata::kernels
+3 -1
View File
@@ -24,7 +24,9 @@ namespace strata::kernels {
/// scores [nq, max_blocks]; q_idx [nq, idx_n_head, idx_dim] (normed and rotated); steps [nq, kStepCount].
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 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
///< batch's largest n_bid + 1; not for a captured graph)
/// ids [nq, cap] (cells, ascending); `cap` >= the largest selection width.
void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
+16
View File
@@ -39,6 +39,22 @@ void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const
/// outstanding at once (the split verify window keeps two).
void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream);
// ---- perf-review E-6: a layer whose routed experts are all in VRAM needs nothing from the host
/// One group's plan, built on the device when every routed expert of its n*k entries is resident: the host pool's
/// layout (counts | start | dst | tok | pad | ptr | ptr2 | start2, `capx` entries) and order (distinct experts in
/// routing order, their entries ascending), no PCIe groups. *skip = ring when it did, else 0.
void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert,
const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,
long long capx, uint32_t* skip, uint32_t ring, void* stream);
/// wait_flag_ge that also returns when *skip == value (device memory).
void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream);
/// copy_i32_from_mapped unless *skip == value.
void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value,
void* stream);
/// copy_from_mapped, or zeros when *skip == value (n a multiple of 4, 16-byte aligned).
void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value,
void* stream);
/// Rows of the S2/S4/S8 embedding for T token ids read from DEVICE memory; out (T, n). Bitwise `embedding_gather`.
void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens,
int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes,
+2 -1
View File
@@ -2,7 +2,8 @@
//
// The n-gram table (26.8 GiB) stays on the SSD and must never occupy RAM, including the OS file cache. A memory
// map cannot promise that; an unbuffered read can. On Windows this is FILE_FLAG_NO_BUFFERING | OVERLAPPED with
// an I/O completion port; on Linux, O_DIRECT (synchronous pread for now; io_uring is phase L).
// an I/O completion port; on Linux, O_DIRECT preads. Both issue the reads from a small thread pool (submit only
// queues), so many reads are in flight: STRATA_IO_THREADS sets its size (default 4 on Windows, 16 on Linux).
//
// Contract of every read: offset, length and buffer address are multiples of `alignment()` (4096 here).
// Reads past end of file return the bytes that exist; `Completion::bytes` says how many.
+18
View File
@@ -72,6 +72,12 @@ public:
/// K/V from them. The prefill stream is synchronized before the call.
std::function<bool(const float* R_rows, int64_t T, int64_t pos0, std::string& err)> on_chunk;
/// Layer split: called by every stage when it has read a chunk, with the position reached, while its own state
/// is still at that chunk's end (its stream synchronized; the last stage calls it just before `on_chunk`). An
/// earlier stage is a chunk or more ahead of the last one by the time `on_chunk` runs, so this is where a
/// mid-prompt checkpoint takes each stage's part. Runs on that stage's thread, with its device current.
std::function<bool(int64_t done, std::string& err)> on_stage_chunk;
/// Checked before every chunk: true stops the prompt early (`run` returns false with err "cancelled").
std::function<bool()> should_stop;
@@ -79,7 +85,19 @@ public:
/// embedding where non-null (an image's <|image_pad|> cells). Null (default): every position embeds its token.
const float* const* embd_rows = nullptr;
/// LAYER SPLIT (multi-GPU): this prompt path runs layers [layer_begin, layer_end) (-1: to the last) on the
/// device `init` runs on. A stage that does not start at layer 0 reads each chunk's residual rows from the
/// previous stage instead of embedding the tokens; a stage that does not end at the last layer copies its rows
/// to pinned host buffers (two, allocated by `init`) and runs `next` on them - on a thread, so the next stage
/// reads chunk c while this one reads chunk c + 1. `on_chunk` belongs on the last stage. Set before `init`.
void set_stage(int64_t layer_begin, int64_t layer_end, Prefill* next) {
stage_lb_ = layer_begin; stage_le_ = layer_end; next_ = next;
}
private:
int64_t stage_lb_ = 0, stage_le_ = -1;
Prefill* next_ = nullptr;
const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned)
bool carve(std::size_t T, void* alloc); // the device buffers of a chunk (prefill.cpp's Alloc)
struct Impl;
std::unique_ptr<Impl> impl_;
+43
View File
@@ -0,0 +1,43 @@
// include/strata/program/conv_cache.hpp - the conversation cache's retention policy: which checkpoint
// leaves when the cache is over its slot budget.
//
// The cache holds conversation checkpoints: snapshots of the running state (the GDN recurrence, the PLE
// history, the QSA indexer tails - `ConvCheckpoint` in generate.cpp) that a request resumes its prompt
// from instead of reading those tokens again. The request path keeps only the checkpoints whose tokens
// are a prefix of the current prompt - any other checkpoint's positional cells have been overwritten,
// because the KV cache is one arena that holds one branch of history at a time - so at any moment the
// retained checkpoints are a CHAIN: sorted by length, each a prefix of the next. That is a radix cache's
// tree collapsed onto the one branch of history the session can hold.
//
// The chain's root is therefore the deepest point every request so far has shared - in practice the end
// of the system prompt, which every new chat of the same client mounts through - and it is exactly the
// node a radix cache keeps alive while its leaves rotate. First-in-first-out kept it only by accident of
// being first: after `prompt_cache` newer checkpoints it was gone, and the next chat read the whole
// prefix again at prefill speed. So:
//
// * the root is PINNED: dropping it frees one slot's ~118 MB and costs every future conversation that
// shares the prefix a full re-read of it (a 30K system prompt is ~30 s at ~1,000 tok/s);
// * every other slot rotates by least recent use. A checkpoint's stamp advances when it is created,
// when a new checkpoint lands on its length, and when a request mounts through it.
//
// With a budget below two slots there is no room to keep root and leaf apart, so the pin switches off and
// the oldest checkpoint leaves - the previous behaviour, one slot = the newest point only.
#pragma once
#include <cstddef>
#include <cstdint>
namespace strata::program::conv_cache {
/// The index in `stamps` of the chain item to drop once the chain holds more than `cap` items. `stamps`
/// are the items' last-use stamps; the caller owns the chain and erases the returned index. Pure and
/// deterministic so conv_cache_test.cpp can walk the scenarios by hand.
inline size_t eviction_victim(const uint64_t* stamps, size_t n, int64_t cap) {
if (cap < 2 || n < 2) return 0; // no room for root and leaf: the pin is off, the oldest leaves
size_t v = 1; // the root (0) is pinned; least recent use among the rest
for (size_t i = 2; i < n; ++i)
if (stamps[i] < stamps[v]) v = i;
return v;
}
} // namespace strata::program::conv_cache
+51 -11
View File
@@ -24,6 +24,7 @@ import argparse
import collections
import base64
import hashlib
import codecs
import json
import os
import queue
@@ -179,6 +180,10 @@ class StrataEngine:
loading.set()
if self.max_context <= 0:
raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else ""))
# (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that
# report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones
if self.info.get("engine"):
self.info["version"] = str(self.info["engine"])
# the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks)
self.lines: queue.Queue = queue.Queue()
threading.Thread(target=self._pump, daemon=True).start()
@@ -233,6 +238,8 @@ class StrataEngine:
"decode_ms": float(f[4]), "finish": f[5]}
if len(f) >= 9: # the conversation cache's fields (engine 0.1.3+)
self.last.update(drafts_accepted=int(f[6]), drafts_offered=int(f[7]), reused=int(f[8]))
if len(f) >= 11: # decode hit rate fields
self.last.update(hits=int(f[9]), lookups=int(f[10]))
@staticmethod
def sampling_keys(sampling: dict) -> str:
@@ -450,13 +457,32 @@ class Vision:
self.proc.kill()
def gpu_list(cfg: dict) -> list[int]:
"""The config's "gpu": one card (2), or several for a layer split ([0, 2] or "0,2"), numbered as nvidia-smi
numbers them; [] when it names none."""
g = cfg.get("gpu")
if g is None or g == "":
return []
items = g if isinstance(g, (list, tuple)) else str(g).split(",")
return [int(str(x).strip()) for x in items if str(x).strip() != ""]
def engine_args(cfg: dict) -> list[str]:
"""The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in the
config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32")."""
args = list(cfg["args"])
if len(gpu_list(cfg)) > 1 and "--layer-split" not in args:
args += ["--layer-split", str(cfg.get("layer_split") or "auto")]
return args
def child_env(cfg: dict) -> dict:
"""The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that
compiled it) first on the library search path."""
env = dict(os.environ)
if cfg.get("gpu") is not None: # issue #51: the GPU to run on, numbered as nvidia-smi does; CUDA's
if gpu_list(cfg): # issue #51: the GPU(s) to run on, numbered as nvidia-smi does; CUDA's
env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # own default order (fastest first) can number the cards otherwise
env["CUDA_VISIBLE_DEVICES"] = str(cfg["gpu"])
env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in gpu_list(cfg))
dirs = [d for d in cfg.get("lib_dirs") or [] if Path(d).is_dir()]
if dirs:
var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
@@ -490,13 +516,19 @@ class ByteTokenizer:
# ------------------------------------------------------------------------------------------------ core
class Detokenizer:
"""Incremental decode: re-decode the generated ids and emit only the new, complete suffix (a multi-byte
character split across tokens is held until complete)."""
"""Incremental decode: each token's bytes go through an incremental UTF-8 decoder, which emits the complete
characters and holds a multi-byte character split across tokens until it is complete (invalid bytes become
U+FFFD, as a whole decode with errors="replace" makes them). Constant time per token - the old re-decode of
every generated id cost 2 ms per token after 8K tokens and 4 ms after 16K (perf-review F-1). A tokenizer
without `token_bytes` (the tests' byte tokenizer) keeps the re-decode."""
def __init__(self, tok):
self.tok, self.ids, self.sent = tok, [], 0
self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") if hasattr(tok, "token_bytes") else None
def push(self, t: int) -> str:
if self.inc is not None:
return self.inc.decode(self.tok.token_bytes(t))
self.ids.append(t)
text = self.tok.decode(self.ids)
if text.endswith("�"):
@@ -567,7 +599,8 @@ class Service:
if getattr(self, "telemetry", None) is None:
from serve.telemetry import Telemetry
self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s()},
gpu_index=int(getattr(self, "gpu_index", 0) or 0))
gpu_index=int(getattr(self, "gpu_index", 0) or 0),
gpu_indices=getattr(self, "gpu_indices", None))
def _tok_s(self):
with self.status_lock:
@@ -762,6 +795,7 @@ class Service:
last = dict(getattr(self.engine, "last", {}) or {})
started = self.status.get("started", time.time())
loaded = str((getattr(self.engine, "info", {}) or {}).get("cvec", 0)) not in ("0", "", "None")
hit_rate = round(last["hits"] / last["lookups"], 3) if last.get("lookups") else None
self.history.append({
"projection": (sampling or {}).get("experimental_speed_projection") is not False
if loaded else None,
@@ -769,7 +803,8 @@ class Service:
"prompt_tokens": len(ids), "reused": last.get("reused"), "output_tokens": n,
"prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"),
"decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1)
if n and last.get("generated") and last.get("decode_ms") else None})
if n and last.get("generated") and last.get("decode_ms") else None,
"hit_rate": hit_rate})
t = self.totals
t["requests"] += 1
t["prompt_tokens"] += len(ids)
@@ -781,8 +816,9 @@ class Service:
el = now - self.status.get("started", now)
ft = self.status.get("first_token")
rate = n / max(1e-6, now - ft) if ft else 0.0
hit_msg = f", expert cache {hit_rate*100:.1f}% hit" if hit_rate is not None else ""
print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) "
f"({finish}, cancel={cancel.is_set()})", flush=True)
f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True)
if os.environ.get("STRATA_DEBUG") and raw_ids:
print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True)
self.status["busy"] = False
@@ -1454,7 +1490,8 @@ def main() -> int:
help="the mock engine's answer (default: a short greeting); given more than once, requests get "
"them in turn and the last one repeats")
ap.add_argument("--port", type=int, default=8095)
ap.add_argument("--gpu", type=int, help="the GPU to run on, as nvidia-smi numbers them (also \"gpu\" in the config)")
ap.add_argument("--gpu", help="the GPU to run on, as nvidia-smi numbers them, or several for a layer split "
"(\"0,2\"; also \"gpu\" in the config)")
ap.add_argument("--tokenizer", default=str(ROOT / "pack/full/tokenizer"),
help="pack tokenizer directory (falls back to a byte tokenizer if absent)")
ap.add_argument("--open", action="store_true", help="open the local page in the browser once the model is ready")
@@ -1469,7 +1506,7 @@ def main() -> int:
a = ap.parse_args()
cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {} # Notepad adds a BOM
if a.gpu is not None:
cfg["gpu"] = a.gpu
cfg["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu
a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can
try: # before the minutes of loading: is the port free?
Server((a.host, a.port), BaseHTTPRequestHandler).server_close()
@@ -1506,7 +1543,9 @@ def main() -> int:
vision = Vision(cfg["vision"], log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None,
env=env)
print("loading the model (the first start takes a minute or two) ...", flush=True)
engine = StrataEngine(cfg["exe"], cfg["args"], cwd=cfg.get("cwd"), log=cfg.get("log"), env=env)
if len(gpu_list(cfg)) > 1:
print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True)
engine = StrataEngine(cfg["exe"], engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env)
warn_tight_ram(engine.info.get("arena_mib"))
else:
engine, vision, sampling_defaults = MockEngine(tok, a.script or [
@@ -1518,7 +1557,8 @@ def main() -> int:
sampling_defaults=sampling_defaults,
fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)
svc.api_key = a.api_key or cfg.get("api_key", "")
svc.gpu_index = cfg.get("gpu") or 0 # the Monitor reads the card the engine runs on (issue #51)
svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)
svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)
if a.config: # the Chat settings shared with other apps, from last time
svc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json"
try:
+25 -5
View File
@@ -169,14 +169,19 @@ class _CpuRamFallback:
# ------------------------------------------------------------------------------------------------ the sampler
class Telemetry:
def __init__(self, extra=None, gpu_index=0):
def __init__(self, extra=None, gpu_index=0, gpu_indices=None):
"""`extra()` -> dict of more series to record each second (the server's tok/s). `gpu_index`: the card the
engine runs on, numbered as nvidia-smi and NVML number them (by PCI bus)."""
engine runs on, numbered as nvidia-smi and NVML number them (by PCI bus); `gpu_indices`: all of them when
the model is split across several (issue #112) - the gpu_* readings are then their total (memory, power,
PCIe traffic), mean (load) or hottest (temperature), and "gpus" has each card's own."""
self.extra = extra
self.lock = threading.Lock()
self.now: dict = {}
self.hist = collections.defaultdict(lambda: collections.deque(maxlen=HISTORY))
self.gpu = _Nvml(gpu_index)
idx = list(gpu_indices) if gpu_indices and len(gpu_indices) > 1 else [gpu_index]
self.gpus = [(i, _Nvml(i)) for i in idx]
self.gpus = [(i, g) for i, g in self.gpus if g.ok()] or self.gpus[:1]
self.gpu = self.gpus[0][1]
try:
import psutil # noqa: F401
self.ps = sys.modules["psutil"]
@@ -184,7 +189,8 @@ class Telemetry:
self.ps = None
self.fallback = _CpuRamFallback()
self.static = {
"gpu_name": self.gpu.name() if self.gpu.ok() else None,
"gpu_name": " + ".join(g.name() or "?" for _, g in self.gpus) if self.gpu.ok() else None,
"gpu_count": len(self.gpus),
"cpu_name": _cpu_name(),
"cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None,
"threads": os.cpu_count(),
@@ -210,7 +216,21 @@ class Telemetry:
def sample(self):
s = {}
if self.gpu.ok():
g = self.gpu.read()
reads = [(i, g.read()) for i, g in self.gpus]
g = dict(reads[0][1])
if len(reads) > 1:
def vals(k):
return [r[k] for _, r in reads if r.get(k) is not None]
for k in ("mem_used", "mem_total", "power", "power_limit", "pcie_rx_mb", "pcie_tx_mb"):
v = vals(k)
g[k] = sum(v) if v else None
u = vals("util")
g["util"] = sum(u) / len(u) if u else None
t = vals("temp")
g["temp"] = max(t) if t else None
s["gpus"] = [{"index": i, "util": r.get("util"), "mem_used": r.get("mem_used"),
"mem_total": r.get("mem_total"), "temp": r.get("temp"), "power": r.get("power")}
for i, r in reads]
s.update({f"gpu_{k}": v for k, v in g.items()})
if self.ps:
try:
+107
View File
@@ -0,0 +1,107 @@
"""The streaming detokenizer (perf-review F-1): the incremental one emits exactly what the old re-decode did, token
by token, and its cost per token does not grow with the reply.
python -m unittest serve.test_detok (needs a pack's tokenizer; skipped without one)
"""
import os
import random
import sys
import time
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools"))
sys.path.insert(0, str(ROOT))
from serve.server import Detokenizer # noqa: E402
def find_tokenizer():
cands = [os.environ.get("STRATA_TOKENIZER", "")]
cands += [str(p) for p in ROOT.glob("packs/*/tokenizer")] + [str(p) for p in ROOT.glob("pack/*/tokenizer")]
cands += [r"C:\Users\AI-Server\Desktop\Strata\Public\Engine\pack\full\tokenizer"]
for c in cands:
if c and (Path(c) / "vocab.json").exists():
return Path(c)
return None
class OldDetokenizer:
"""The pre-0.1.22 algorithm: re-decode every generated id, hold a trailing U+FFFD."""
def __init__(self, tok):
self.tok, self.ids, self.sent = tok, [], 0
def push(self, t):
self.ids.append(t)
text = self.tok.decode(self.ids)
if text.endswith("\ufffd"):
return ""
delta, self.sent = text[self.sent:], len(text)
return delta
@unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here")
class Detok(unittest.TestCase):
@classmethod
def setUpClass(cls):
import json
import strata_tokenizer as ST
t = find_tokenizer()
vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))
toks = [None] * len(vocab)
for s, i in vocab.items():
toks[i] = s
cls.tok = ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"),
json.loads((t / "token_type.json").read_text()))
def same_stream(self, ids):
"""The same text as the old re-decode, never behind it (the old one held complete characters too while
the tail was an incomplete one; the new one holds only the incomplete bytes), and never ahead of what the
ids so far decode to."""
a, b = OldDetokenizer(self.tok), Detokenizer(self.tok)
self.assertIsNotNone(b.inc)
old = new = ""
for i, t in enumerate(ids):
old += a.push(t)
new += b.push(t)
self.assertTrue(new.startswith(old), f"token {i} ({t}): behind the old stream")
self.assertTrue(self.tok.decode(ids[:i + 1]).startswith(new), f"token {i} ({t}): ahead of the ids")
if not self.tok.decode(ids).endswith("�"):
self.assertEqual(old, new)
def test_text_with_split_characters(self):
text = ("Grüße aus Zürich! 你好,世界。日本語のテキスト 🌊🦊👩‍💻 and ASCII code: def f(x): return x**2\n" * 40)
self.same_stream(self.tok.encode(text))
def test_random_ids_and_broken_bytes(self):
rng = random.Random(5)
n = len(self.tok.tokens)
for _ in range(20): # random ids: split and invalid UTF-8 sequences everywhere (no U+FFFD token itself)
ids = [rng.randrange(n) for _ in range(300)]
ids = [t for t in ids if "\ufffd" not in self.tok.decode([t], errors="strict" if False else "replace")
or len(self.tok.token_bytes(t)) < 3]
self.same_stream(ids)
def test_constant_cost(self):
ids = self.tok.encode("The quick brown fox jumps over the lazy dog. " * 2000)[:16384]
d = Detokenizer(self.tok)
for t in ids[:1024]:
d.push(t)
t0 = time.perf_counter()
for t in ids[1024:1124]:
d.push(t)
early = time.perf_counter() - t0
for t in ids[1124:16000]:
d.push(t)
t0 = time.perf_counter()
for t in ids[16000:16100]:
d.push(t)
late = time.perf_counter() - t0
self.assertLess(late / 100, 0.0002, "a token after 16K tokens costs more than 0.2 ms")
self.assertLess(late, early * 5 + 0.002)
if __name__ == "__main__":
unittest.main()
+12 -5
View File
@@ -228,12 +228,18 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) {
const speed = live.state === "generating" ? live.tok_s : last ? last.decode_tok_s : null;
setMetric("speed", speed == null ? null : fmt(speed, 1), "tok/s", live.state === "generating" ? "now" : last ? "last request" : "");
spark("sp-speed", h.tok_s);
setMetric("gpu", hw.gpu_util == null ? null : fmt(hw.gpu_util), "%", st.gpu_name || "");
// a model split across several cards (issue #112): the cards show their total / mean / hottest, and each card's own
const per = (f) => (hw.gpus || []).map((g) => `GPU ${g.index} ${f(g)}`).join(" · ");
const multi = (hw.gpus || []).length > 1;
setMetric("gpu", hw.gpu_util == null ? null : fmt(hw.gpu_util), "%",
multi ? per((g) => (g.util == null ? "–" : `${fmt(g.util)}%`)) : st.gpu_name || "");
spark("sp-gpu", h.gpu_util, 100);
setMetric("vram", hw.gpu_mem_used == null ? null : gb(hw.gpu_mem_used), hw.gpu_mem_total ? `/ ${gb(hw.gpu_mem_total, 0)} GB` : "GB",
eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : "");
multi ? per((g) => (g.mem_used == null ? "–" : `${gb(g.mem_used)} GB`))
: eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : "");
spark("sp-vram", h.gpu_mem_used, hw.gpu_mem_total);
setMetric("temp", hw.gpu_temp == null ? null : fmt(hw.gpu_temp), "°C", "");
setMetric("temp", hw.gpu_temp == null ? null : fmt(hw.gpu_temp), "°C",
multi ? per((g) => (g.temp == null ? "–" : `${fmt(g.temp)}°`)) : "");
spark("sp-temp", h.gpu_temp, 90);
setMetric("power", hw.gpu_power == null ? null : fmt(hw.gpu_power), "W", hw.gpu_power_limit ? `of ${fmt(hw.gpu_power_limit)} W limit` : "");
spark("sp-power", h.gpu_power, hw.gpu_power_limit);
@@ -276,7 +282,7 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) {
// recent requests
const body = $("req-body");
if (!requests.length) {
body.innerHTML = `<tr><td colspan="7" class="muted">No requests yet</td></tr>`;
body.innerHTML = `<tr><td colspan="8" class="muted">No requests yet</td></tr>`;
} else {
const badge = {stop: ["", "Done"], length: ["", "Max tokens"], cancel: ["st-badge--queued", "Stopped"],
disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"]};
@@ -284,9 +290,10 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) {
const [cls, text] = badge[r.finish] || ["", r.finish || "–"];
const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"});
const proj = r.projection == null ? "" : ` <span class="st-badge${r.projection ? " st-badge--reading" : ""}" title="experimental speed projection ${r.projection ? "on" : "off"}">${r.projection ? "ESP" : "stock"}</span>`;
const hit = r.hit_rate == null ? "–" : `${(r.hit_rate * 100).toFixed(1)}%`;
return `<tr><td>${esc(t)}</td><td><span class="st-badge ${cls}">${esc(text)}</span>${proj}</td><td class="num">${fmt(r.prompt_tokens)}</td>
<td class="num">${fmt(r.reused)}</td><td class="num">${fmt(r.output_tokens)}</td><td class="num">${fmt(r.decode_tok_s, 1)}</td>
<td class="num">${fmt(r.duration_s, 1)} s</td></tr>`;
<td class="num">${hit}</td><td class="num">${fmt(r.duration_s, 1)} s</td></tr>`;
}).join("");
}
const all = $("req-all");
+2 -2
View File
@@ -117,8 +117,8 @@
<div class="table-wrap" id="req-wrap">
<table class="st-table">
<thead><tr><th>Time</th><th>Status</th><th class="num">Prompt</th><th class="num">Reused</th><th class="num">Output</th>
<th class="num">Tok/s</th><th class="num">Duration</th></tr></thead>
<tbody id="req-body"><tr><td colspan="7" class="muted">No requests yet</td></tr></tbody>
<th class="num">Tok/s</th><th class="num" title="While writing the answer: the share of the experts looked up that were already in VRAM (experts copied over PCIe are not counted)">Hit rate</th><th class="num">Duration</th></tr></thead>
<tbody id="req-body"><tr><td colspan="8" class="muted">No requests yet</td></tr></tbody>
</table>
</div>
<p class="muted req-totals" id="req-totals"></p>
+259 -34
View File
@@ -57,7 +57,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip"
# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages
CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"]
MIN_DRIVER = 580 # CUDA 13.0
MIN_ENGINE = (0, 1, 19) # v0.1.19: penalties on every drafted token; v0.1.17: one penalties stage (#53)
MIN_ENGINE = (0, 1, 22) # v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties
PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"]
MODELS = {
@@ -274,6 +274,162 @@ def gpus():
GPU_PICK = None # --gpu N (issue #51); None: the card with the most VRAM
SPLIT_MIN_VRAM_GB = 8 # a card sharing a model holds the dense weights and its own
# prompt buffers too (docs/MULTI_GPU.md)
def cc(g) -> str:
return f"{g['arch'][:-1]}.{g['arch'][-1]}"
def gpu_problem(g, together=False):
"""Why Strata cannot use this card, in plain words (None: it can)."""
if int(g["arch"]) < 80:
return (f"not supported - older than the RTX 30 series (compute capability {cc(g)}; Strata needs 8.0 or "
"newer)")
if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5:
return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model "
f"needs {SPLIT_MIN_VRAM_GB} GB or more)")
return None
def gpu_rank(g):
"""The order cards share a model in: the newest generation first (it gets the first layers and most of the
work), then the most VRAM."""
return (-int(g["arch"]), -round(g["vram_gb"]), g["index"])
def gpu_name(g) -> str:
return f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB)"
def gpu_table(found) -> None:
say(" Your NVIDIA GPUs:")
for g in found:
p = gpu_problem(g)
say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + ("can be used" if p is None else p))
def together_ok(found) -> list:
"""The cards that can share one model, in the order they would (empty if fewer than two)."""
ok_ = sorted([g for g in found if gpu_problem(g, together=True) is None], key=gpu_rank)
return ok_ if len(ok_) >= 2 else []
def parse_gpus(text, found) -> list:
"""--gpus / --gpu with several: "0,2" or "all" (every card that can share the model)."""
if str(text).strip().lower() == "all":
sel = [g["index"] for g in together_ok(found)]
if not sel:
gpu_table(found)
fail("--gpus all: this PC does not have two GPUs Strata can use together")
return sel
try:
sel = [int(x) for x in str(text).split(",") if x.strip()]
except ValueError:
fail(f"--gpus takes GPU numbers as nvidia-smi numbers them, e.g. --gpus 0,2 (or --gpus all), not {text!r}")
if len(sel) < 2 or len(set(sel)) != len(sel):
fail("--gpus takes two or more different GPUs, e.g. --gpus 0,2 (one GPU: --gpu 0)")
return sel
def check_gpus(sel, found, what="") -> None:
"""Stops with a plain message when a chosen card is missing or cannot be used, and says what can."""
together = len(sel) > 1
for i in sel:
g = next((x for x in found if x["index"] == i), None)
p = "not found on this PC" if g is None else gpu_problem(g, together)
if p is None:
continue
say()
gpu_table(found)
can = together_ok(found)
single = [x for x in found if gpu_problem(x) is None]
ones = " or ".join(f"--gpu {x['index']}" for x in single)
both = "--gpus " + ",".join(str(x["index"]) for x in can) if can else ""
hint = ((f"use these together: {both}" + (f" (or one card: {ones})" if not together else "")) if can else
f"use one card: {ones}" if single else "Strata needs an NVIDIA RTX 30 series or newer card")
fail(f"GPU {i}{'' if g is None else ' (' + g['name'] + ')'} {what}cannot be used: {p}", hint)
def engine_archs():
"""The GPU generations the installed engine has code for: (archs, ptx), or None when there is none."""
info = ROOT / "engine" / "BUILD.json"
try:
meta = json.loads(info.read_text())
except (OSError, ValueError):
return None
return [int(x) for x in meta.get("archs", [])], bool(meta.get("ptx"))
def engine_runs_on(g) -> bool:
ea = engine_archs()
if ea is None or not ea[0]:
return True
archs, ptx = ea
return int(g["arch"]) in archs or (ptx and int(g["arch"]) > max(archs))
def choose_gpus(a, found) -> list:
"""Which cards this install uses: --gpus / --gpu, or asked when two or more can share the model (the two best
together recommended), else the supported card with the most VRAM. Returns their numbers, the main one first."""
if a.gpus:
sel = parse_gpus(a.gpus, found)
check_gpus(sel, found)
return sel
if a.gpu is not None:
check_gpus([a.gpu], found)
return [a.gpu]
single = sorted([g for g in found if gpu_problem(g) is None], key=lambda x: (-round(x["vram_gb"]), x["index"]))
if not single:
gpu_table(found)
fail("none of your GPUs can run Strata", "it needs an NVIDIA RTX 30 series or newer (compute capability 8.0+)")
can = together_ok(found)
if not can:
return [single[0]["index"]]
say()
say(f" Strata can run the model on one GPU, or share it across {'these' if len(can) > 2 else 'both'}: then each"
" card holds the")
say(" experts of its own layers, so together they hold about twice as many, and prompts are read about 20%")
say(" faster (details: docs/MULTI_GPU.md). A much slower extra card can also make it slower.")
opts = [can[:2]] + ([can] if len(can) > 2 else []) + [[g] for g in single]
for i, o in enumerate(opts, 1):
label = (" + ".join(gpu_name(g) for g in o) + " together") if len(o) > 1 else gpu_name(o[0]) + " only"
say(f" {i}) {label}" + (" (recommended)" if i == 1 else ""))
for g in found:
if gpu_problem(g, together=True) is not None:
say(f" (GPU {g['index']}, {g['name']}: {gpu_problem(g, together=True)})")
pick = opts[int(ask("Which GPUs?", [str(i) for i in range(1, len(opts) + 1)], "1", a.yes or a.check)) - 1]
return [g["index"] for g in pick]
def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict:
"""Starting a model set up for one card on a PC with two or more that can share it: asked once (the answer is
saved in its config)."""
if isinstance(cfg.get("gpu"), list) or cfg.get("gpus_asked"):
return cfg
found = gpus()
can = together_ok(found)
if not can:
return cfg
pair = can[:2]
cfg["gpus_asked"] = True
say()
say(" This PC has " + " and ".join(gpu_name(g) for g in pair) + ": Strata can share the model across both.")
say(" Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md).")
missing = [g for g in pair if not engine_runs_on(g)]
if missing:
say(" The installed engine has no code for " + ", ".join(g["name"] for g in missing) + ": to use them "
"together, run START-HERE.bat --setup --gpus " + ",".join(str(g["index"]) for g in pair))
elif ask(" Use both from now on? (you can change it later: START-HERE.bat --gpu N for one card)",
["y", "n"], "y", yes) == "y":
cfg["gpu"] = [g["index"] for g in pair]
cfg["layer_split"] = cfg.get("layer_split") or "auto"
ok("from now on this model runs on " + " + ".join(gpu_name(g) for g in pair))
else:
ok("staying on one GPU (START-HERE.bat --gpus " + ",".join(str(g["index"]) for g in pair) + " switches)")
cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
return cfg
def gpu_info(pick=None):
@@ -316,7 +472,9 @@ def find_vcvars():
vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe"
if not vswhere.exists():
return None
p = out([str(vswhere), "-latest", "-products", "*", "-requires",
# CUDA 13 accepts Visual Studio 2019 and 2022 only: a newer one (2026 = version 18) installed next to them
# must not be picked ("unsupported Microsoft Visual Studio version"); with only a newer one there is none
p = out([str(vswhere), "-latest", "-products", "*", "-version", "[16.0,18.0)", "-requires",
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]).strip()
v = Path(p) / "VC/Auxiliary/Build/vcvars64.bat" if p else None
return v if v and v.exists() else None
@@ -419,7 +577,18 @@ def get_llama_cpp():
f.extractall(tmp)
top = next(tmp.iterdir())
shutil.rmtree(llama, ignore_errors=True)
top.replace(llama)
# PR #63: on Windows a rename can fail with PermissionError while an antivirus scanner still holds a file of the
# fresh unpack; shutil.move falls back to copy-and-delete, and a few retries let the scanner finish. The target
# is `llama` itself - moving into its parent would keep the zip's `llama.cpp-<sha>` folder name.
for attempt in range(5):
try:
shutil.move(str(top), str(llama))
break
except PermissionError:
if attempt == 4:
raise
shutil.rmtree(llama, ignore_errors=True) # a partial copy from the failed attempt
time.sleep(2)
shutil.rmtree(tmp, ignore_errors=True)
z.unlink(missing_ok=True)
z.with_name(z.name + ".done").unlink(missing_ok=True)
@@ -501,9 +670,11 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None:
shutil.rmtree(tmp, ignore_errors=True)
return None
archs = [int(a) for a in meta.get("archs", [])]
arch = int(gpu["arch"])
if arch not in archs and not (meta.get("ptx") and arch > max(archs)):
warn(f"the ready-made engine is built for {', '.join(str(a) for a in archs)}; your GPU is {arch}" + ("" if updating else ": compiling instead"))
miss = [int(x) for x in gpu.get("archs", [gpu["arch"]])
if int(x) not in archs and not (meta.get("ptx") and int(x) > max(archs))]
if miss:
warn(f"the ready-made engine is built for {', '.join(str(a) for a in archs)}; your GPU is "
f"{', '.join(str(x) for x in miss)}" + ("" if updating else ": compiling instead"))
shutil.rmtree(tmp, ignore_errors=True)
return None
for p in tmp.iterdir():
@@ -557,6 +728,7 @@ def update_installed_engine(url_base) -> None:
try: # a failed compile must not stop the model from starting
if gpu is None:
raise RuntimeError("no NVIDIA GPU found")
gpu = {**gpu, "archs": sorted({int(gpu["arch"]), *(int(x) for x in meta.get("archs", []))})}
build_engine(gpu, vision, False, get_llama_cpp())
except (Exception, SystemExit) as e:
warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one")
@@ -578,7 +750,7 @@ def update_installed_engine(url_base) -> None:
def install_build_tools(gpu, yes):
"""The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars)."""
nvcc, cuda_v = find_nvcc()
need_cuda = (12, 8) if int(gpu["arch"]) >= 120 else (12, 0)
need_cuda = (12, 8) if max(int(x) for x in gpu.get("archs", [gpu["arch"]])) >= 120 else (12, 0)
vcvars = find_vcvars() if WIN else None
have_cc = vcvars is not None if WIN else shutil.which("g++") is not None
missing = []
@@ -690,23 +862,25 @@ def build_engine(gpu, vision, yes, llama) -> Path:
ok("engine already built for this PC")
return eng
nvcc, vcvars = install_build_tools(gpu, yes)
archs = sorted({int(x) for x in gpu.get("archs", [gpu["arch"]])}) # every card the model runs on
cuda_archs = ";".join(str(x) for x in archs)
if not engine_ok:
say(" The engine's source changed: compiling it again (only what changed, a few minutes) ..."
if local and (eng / EXE).exists() else " Compiling the Strata engine for your GPU (10-20 minutes, once) ...")
cmake_build(ROOT, ROOT / "build", "strata",
["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={gpu['arch']}",
["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}",
f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}"], vcvars, "build-strata.bat")
shutil.copy2(ROOT / "build" / EXE, eng / EXE)
if not vision_ok:
say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ..."))
defs = [f"-DLLAMA_DIR={llama}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}"]
if vision == "gpu":
defs += [f"-DCMAKE_CUDA_ARCHITECTURES={gpu['arch']}", f"-DCMAKE_CUDA_COMPILER={nvcc}"]
defs += [f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", f"-DCMAKE_CUDA_COMPILER={nvcc}"]
cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision", defs, vcvars, "build-vision.bat")
shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE)
bindir = Path(nvcc).parent # the toolkit's own libraries (bin, bin/x64, lib64)
dirs = [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()]
stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": [int(gpu["arch"])],
stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": archs,
"vision": vision,
"cuda_dirs": dirs, "src": src, "vision_src": vsrc if want_vision else None}, indent=1))
ok(f"engine compiled: {eng / EXE}")
@@ -899,7 +1073,8 @@ def choices_from_config(cfg_path: Path) -> dict:
"kv": val("--kv") if val("--kv") in ("int8", "q4_0") else None,
"vision": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none",
"esp": ("on" if Path(esp_path).name == ESP_VECTOR.name else esp_path) if esp_path else "off",
"host": cfg.get("host"), "api_key": cfg.get("api_key"), "port": cfg.get("port"), "gpu": cfg.get("gpu")}
"host": cfg.get("host"), "api_key": cfg.get("api_key"), "port": cfg.get("port"), "gpu": cfg.get("gpu"),
"layer_split": cfg.get("layer_split")}
def find_in(roots: list, rel: str):
@@ -946,7 +1121,9 @@ def is_wsl() -> bool:
def hardware_key(cfg: dict) -> str:
"""What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting
(the context's KV cache and the image encoder take VRAM from the expert cache)."""
g = gpu_info(cfg.get("gpu")) or {}
sel = cfg.get("gpu")
gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}]
g = {"name": " + ".join(x.get("name", "?") for x in gl), "vram_gb": sum(x.get("vram_gb", 0) for x in gl)}
a = cfg.get("args", [])
ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?"
return "|".join([g.get("name", "?"), f"{g.get('vram_gb', 0):.0f}GB", cpu_info()[0], f"{ram_gb():.0f}GB",
@@ -1012,7 +1189,8 @@ def upgrade_config(cfg_path: Path, cfg: dict) -> dict:
return cfg
def start(cfg_path: Path, port: int | None, gpu: int | None = None, open_browser=True) -> int:
def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False,
layer_split=None) -> int:
cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig")))
missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()]
if missing:
@@ -1020,9 +1198,28 @@ def start(cfg_path: Path, port: int | None, gpu: int | None = None, open_browser
cfg_path.touch() # the most recently used model
cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
"--port", str(port or cfg.get("port", 8080))]
if gpu is not None:
gpu_info(gpu) # stops with the list of GPUs if there is no such one
found = gpus()
if isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on
check_gpus(gpu, found)
cfg["gpu"], cfg["gpus_asked"] = gpu, True
cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto"
cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
gpu = None
elif gpu is not None: # --gpu N: this start only, on that card
check_gpus([gpu], found)
cmd += ["--gpu", str(gpu)]
else:
cfg = offer_together(cfg_path, cfg, yes)
use = gpu if gpu is not None else cfg.get("gpu")
if isinstance(use, list):
check_gpus(use, found, "(chosen for this model) ")
byid = {g["index"]: g for g in found}
ok("GPUs: " + " + ".join(gpu_name(byid[i]) for i in use) + f" together (layers split {cfg.get('layer_split') or 'auto'})")
elif found:
g = next((x for x in found if x["index"] == use), None) if use is not None else max(
found, key=lambda x: (round(x["vram_gb"]), -x["index"]))
if g is not None:
ok("GPU: " + gpu_name(g))
if open_browser:
cmd.append("--open")
gb = 0.0
@@ -1072,8 +1269,13 @@ def main() -> int:
help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection "
"(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md")
ap.add_argument("--port", type=int, help="the server's port (default: the one the install was set up with, 8080 for a new one)")
ap.add_argument("--gpu", type=int, help="the GPU to use, numbered as nvidia-smi numbers them (default: the one with the "
"most VRAM; with --setup it is saved, when starting it overrides the saved one)")
ap.add_argument("--gpu", help="one GPU, numbered as nvidia-smi numbers them (default: asked when several can be "
"used; with --setup it is saved, when starting it is for that start only)")
ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them: \"0,2\", or \"all\" "
"(every card that can); the first is the main one. Saved, also when starting "
"(see docs/MULTI_GPU.md)")
ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"); "
"default auto, placed from each GPU's free VRAM")
ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other "
"devices on your network (issue #26; set --api-key too)")
ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)")
@@ -1092,6 +1294,13 @@ def main() -> int:
help="tune the engine's settings for this PC (about 5-10 minutes), then start the model")
ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS)
a = ap.parse_args()
if a.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report)
if "," in a.gpu:
a.gpus, a.gpu = a.gpus or a.gpu, None
elif a.gpu.strip().isdigit():
a.gpu = int(a.gpu)
else:
ap.error(f"--gpu takes a GPU number as nvidia-smi numbers them, e.g. --gpu 1 (or --gpus 0,2), not {a.gpu!r}")
say("Strata - Qwen3.8-Flash-Next on a normal PC (NVIDIA GPU + system RAM + CPU)")
data, elsewhere = data_folder(a.data_dir) # the model files: in the data folder, found from any copy
roots = [data, *elsewhere]
@@ -1114,10 +1323,17 @@ def main() -> int:
a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"]
a.host, a.api_key = a.host or ch["host"], a.api_key or ch["api_key"]
a.port = a.port or ch["port"]
a.gpu = a.gpu if a.gpu is not None else ch.get("gpu")
if isinstance(ch.get("gpu"), list): # a layer split: set up across the same cards again
a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"])
a.layer_split = a.layer_split or ch.get("layer_split")
else:
a.gpu = a.gpu if a.gpu is not None else ch.get("gpu")
a.yes = True
global GPU_PICK
GPU_PICK = a.gpu
# starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start
# on the first one alone unless given with --setup), --gpu N runs this start on one card; neither: the saved
# choice, and asked once when the PC has cards that could share the model
run_gpu = (parse_gpus(a.gpus, gpus()) if a.gpus else None) or a.gpu
port = a.port or 8080 # a new install's port (issue #32: --port for an existing one)
if have and a.calibrate and not (a.setup or a.model or a.family or a.check):
if not a.build:
@@ -1129,35 +1345,38 @@ def main() -> int:
say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}")
pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1]
calibrate_config(pick_cfg)
return 0 if a.no_start else start(pick_cfg, a.port, a.gpu)
return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split)
if have and not (a.setup or a.model or a.family or a.check or a.no_start):
if not a.build:
update_installed_engine(a.prebuilt)
if len(have) == 1:
return start(have[0], a.port, a.gpu)
return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split)
say()
for i, c in enumerate(have, 1):
say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}")
say(f" {len(have) + 1}) install another model / change settings")
pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes))
if pick <= len(have):
return start(have[pick - 1], a.port, a.gpu)
return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split)
# ---- 1. the PC
step(1, "checking your PC")
gpu = gpu_info()
if gpu is None:
found = gpus()
if not found:
fail("no NVIDIA GPU found (nvidia-smi did not answer)",
"install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC")
ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {gpu['arch'][:-1]}.{gpu['arch'][-1]}, "
f"driver {gpu['driver']}")
if gpu["count"] > 1:
say(f" {gpu['count']} NVIDIA GPUs: Strata uses GPU {gpu['index']}"
+ (" (the one with the most VRAM)" if a.gpu is None else "") + " - choose another with --gpu N:")
for x in gpus():
say(f" {x['index']}: {x['name']}, {x['vram_gb']:.0f} GB")
if int(gpu["arch"]) < 80:
fail("this GPU is older than the RTX 30 series (compute capability 8.0 is required)")
if len(found) > 1 or gpu_problem(found[0]) is not None:
gpu_table(found)
sel = choose_gpus(a, found) # asked when two or more cards can share the model
multi = sel if len(sel) > 1 else []
a.gpu = sel[0] # the main GPU: the checks and the sizing below are its
GPU_PICK = a.gpu
gpu = gpu_info(a.gpu)
chosen = [gpu_info(i) for i in sel]
gpu["archs"] = sorted({x["arch"] for x in chosen}) # the engine needs code for every one of them
if multi:
ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")
ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}")
if driver_major(gpu) < MIN_DRIVER:
fail(f"the NVIDIA driver is too old ({gpu['driver']}; {MIN_DRIVER} or newer is needed)",
"update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again")
@@ -1218,7 +1437,8 @@ def main() -> int:
"choose Q2_0 or IQ2_XS, or add RAM")
ok(f"size: {model}")
tag = fam["tag"] + model # names of the pack, config and start script
rec_ctx = 32768 if gpu["vram_gb"] < 14 else 65536 if gpu["vram_gb"] < 20 else 131072
small = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context
rec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072
if a.context:
ctx = a.context
else:
@@ -1404,6 +1624,11 @@ def main() -> int:
"lib_dirs": lib_dirs, "port": port}
if gpu["count"] > 1 or a.gpu is not None:
cfg["gpu"] = gpu["index"] # the engine is told this card (issue #51)
cfg["gpus_asked"] = True # chosen at setup: not asked again at start
if multi: # a layer split across these cards (the server adds the flag)
cfg["gpu"] = multi
cfg["layer_split"] = a.layer_split or "auto"
ok(f"layer split across GPUs {multi} ({cfg['layer_split']})")
if a.host:
cfg["host"] = a.host
if a.api_key:
+26
View File
@@ -265,6 +265,32 @@ bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std
return true;
}
bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) {
const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_);
uint8_t* dst = device_slot(slot);
if (dst == nullptr || host_blob == nullptr) {
err = dst == nullptr ? "ExpertCache::fill_slot_queued: slot outside the arena"
: "ExpertCache::fill_slot_queued: the host blob is null";
return false;
}
const cudaError_t e = cudaMemcpyAsync(dst, host_blob, n, cudaMemcpyHostToDevice, (cudaStream_t) 0);
if (e != cudaSuccess) {
err = std::string("ExpertCache::fill_slot_queued: ") + cudaGetErrorString(e);
return false;
}
++fills_;
return true;
}
bool ExpertCache::sync_queued(std::string& err) {
const cudaError_t e = cudaStreamSynchronize((cudaStream_t) 0);
if (e != cudaSuccess) {
err = std::string("ExpertCache::sync_queued: ") + cudaGetErrorString(e);
return false;
}
return true;
}
bool ExpertCache::verify_slot(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) {
const int64_t nb = bytes > 0 && bytes <= blob_ ? bytes : blob_;
const uint8_t* src = device_slot(slot);
+50 -3
View File
@@ -1,5 +1,6 @@
// src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract.
#include "strata/core/expert_source.hpp"
#include "strata/core/remote_experts.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/core/pinned.hpp"
@@ -199,6 +200,22 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons
const bool use_hits = graph_hits || (d.hits_ready() && d.decided);
int64_t njobs = 0;
if (d.remote_count > 0) {
int32_t kind[32];
if (k > 32) {
d.failed = true; d.fail = "remote experts: routing width exceeds 32"; return;
}
for (int64_t i = 0; i < k; ++i)
kind[i] = use_hits && ids[i] >= 0 && ids[i] < d.n_expert && (graph_hits
? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] >= 0
: d.is_hit[(size_t) i] != 0) ? 0 : -1;
static thread_local std::string remote_error;
for (int r = 0; r < d.remote_count; ++r)
if (!d.remote[r]->begin(d.layers, x_f, ids, 1, k, kind, d.host_res, remote_error)) {
d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
}
}
for (int64_t i = 0; i < k; ++i) {
const int64_t e = ids[i];
if (e < 0 || e >= d.n_expert) {
@@ -231,6 +248,13 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons
}
if (graph_hits) ++d.cache_refused; // token graph: a miss (nothing is admitted during a token)
bool remote_owns = false;
for (int r = 0; r < d.remote_count; ++r) remote_owns |= d.remote[r]->owns(i);
if (remote_owns) {
std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float));
continue;
}
// `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a
// hit, and using one for the other is how a hit's row would get two experts summed into it.
ExpertJob& j = d.jobs[(size_t) njobs++];
@@ -244,6 +268,13 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons
// Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`).
if (d.split_rows) d.pool->run_split(d.jobs.data(), (int) njobs);
else d.pool->run(d.jobs.data(), (int) njobs);
if (d.remote_count > 0) {
static thread_local std::string remote_error;
for (int r = 0; r < d.remote_count; ++r)
if (!d.remote[r]->finish(out, remote_error)) {
d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
}
}
++d.layers;
d.experts += k;
}
@@ -366,6 +397,15 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0 : -1;
}
}
if (d.remote_count > 0) {
static thread_local std::string remote_error;
for (int r = 0; r < d.remote_count; ++r) {
if (!d.remote[r]->begin(d.layers, x_f, ids, n_tok, k, kind, d.host_res, remote_error)) {
d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
}
for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2;
}
}
const auto c1 = std::chrono::steady_clock::now();
if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations
for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
@@ -388,7 +428,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
d.fail_expert = e;
return;
}
if (kind[i] >= 0) { // the GPU computes this entry (a VRAM hit or a PCIe read)
if (kind[i] >= 0) { // CUDA0, PCIe, or a remote result staged into this row below
if (kind[i] == 0) ++d.cache_hits;
std::memset(row, 0, (size_t) H * sizeof(float));
continue;
@@ -421,6 +461,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
pt("run", njobs);
if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs);
else d.pool->run_split_multi(d.jobs_multi.data(), njobs);
if (d.remote_count > 0) {
static thread_local std::string remote_error;
for (int r = 0; r < d.remote_count; ++r)
if (!d.remote[r]->finish(out, remote_error)) {
d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
}
}
const auto c4 = std::chrono::steady_clock::now();
pt("ran");
auto ms = [](auto a, auto b) { return std::chrono::duration<double, std::milli>(b - a).count(); };
@@ -616,7 +663,7 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:
ArenaExpertSource::~ArenaExpertSource() { close(); }
bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads,
std::string& err) {
std::string& err, uint64_t max_pinned_bytes) {
close();
const std::string path = pack_dir + "/experts.bin";
// plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver
@@ -657,7 +704,7 @@ bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int6
lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert);
}
bounds.push_back(want);
PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds);
PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes);
if (!a->valid()) {
delete a;
err = "ArenaExpertSource: the arena could not be reserved (" + std::to_string(want) + " B)";
+83 -1
View File
@@ -1,5 +1,6 @@
// src/core/mtp.cpp - see include/strata/core/mtp.hpp.
#include "strata/core/mtp.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/native_head.hpp"
#include "strata/kernels/bf16_gemv.hpp"
@@ -82,6 +83,8 @@ bool read_file(const std::string& path, std::vector<uint8_t>& out) {
MtpDrafter::~MtpDrafter() {
if (cs_) cudaStreamSynchronize(cs_);
for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e);
for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e);
if (pf_dev_) cudaFree(pf_dev_);
for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e);
for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e);
if (cs_) cudaStreamDestroy(cs_);
@@ -111,6 +114,7 @@ const void* MtpDrafter::q8(const char* name) const {
bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
int64_t window) {
cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there
g_ = &g;
ss_ = &ss;
max_t_ = max_t;
@@ -131,7 +135,15 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
}
std::vector<uint8_t> blob;
if (!read_file(rt_dir + "/dense.bin", blob)) { err = "mtp: cannot read dense.bin"; return false; }
if (cudaMalloc((void**) &dense_, blob.size()) != cudaSuccess) { err = "mtp: dense weights do not fit"; return false; }
const cudaError_t alloc = cudaMalloc((void**) &dense_, blob.size());
if (alloc != cudaSuccess) {
size_t free_bytes = 0, total_bytes = 0;
const cudaError_t info = cudaMemGetInfo(&free_bytes, &total_bytes);
err = "mtp: dense weights allocation failed (" + std::string(cudaGetErrorString(alloc)) +
"), requested " + std::to_string(blob.size() >> 20) + " MiB, CUDA0 free " +
(info == cudaSuccess ? std::to_string(free_bytes >> 20) + " MiB" : "unknown");
return false;
}
cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);
vram_ += blob.size();
}
@@ -243,6 +255,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
}
bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) {
const OnDevice on_device(device_);
wt_ = &wt;
head_ = head;
window_R_ = window_R;
@@ -469,6 +482,13 @@ bool MtpDrafter::capture_prefill(int T, std::string& err) {
return finish_capture(cs_, ok, prefill_exec_[T], "prefill", err);
}
bool MtpDrafter::capture_prefill_dev(int T, std::string& err) {
if (prefill_dev_exec_[T]) return true;
if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; }
const bool ok = record_forward(T, -1, cs_, err); // K/V only, rows [0, T); tok_/step_/pos_ filled before launch
return finish_capture(cs_, ok, prefill_dev_exec_[T], "prefill (device inputs)", err);
}
bool MtpDrafter::capture_round(int T, std::string& err) {
if (round_exec_[T]) return true;
using namespace strata::kernels;
@@ -511,6 +531,7 @@ bool MtpDrafter::capture_step(int j, std::string& err) {
}
void MtpDrafter::kv_restore(int64_t upto) {
const OnDevice on_device(device_);
if (st_.kv_mode != 2 || upto <= 0) return;
// the ring's blocks below `upto`, from the host copy: a checkpoint resume may have left later cells in them
const strata::kernels::QsaShapes s = shapes_of(*g_);
@@ -520,10 +541,69 @@ void MtpDrafter::kv_restore(int64_t upto) {
}
bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) {
const OnDevice on_device(device_);
const Clock::time_point t0 = Clock::now();
const int64_t HCN = g_->hc * g_->n_embd;
// cells the window can never reach again need no K/V
const int64_t first_needed = (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0;
// E-4: every group's token / step / position records uploaded at once; each group is then device copies and a
// graph on the one stream, with a single sync at the end (a group of <= max_t rows used to be staged in mapped
// memory and synced before the next: ~5,500 host round trips on a 32K prompt). The same work in the same
// order. STRATA_MTP_PREFILL_SYNC=1 keeps the old loop.
static const bool per_group_sync = std::getenv("STRATA_MTP_PREFILL_SYNC") != nullptr;
const int64_t NHp = g_->n_head, per_row = 1 + 4 + NHp;
if (!per_group_sync && n > 0) {
if (pf_cap_ < n * per_row) {
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;
}
std::vector<int32_t> rec((size_t) (n * per_row));
int32_t* tk = rec.data();
int32_t* stp = tk + n;
int32_t* ps = stp + 4 * n;
for (int64_t i = 0; i < n; ++i) {
const int64_t cell = cell0 + i;
tk[i] = next_tokens[i];
stp[i * 4 + 0] = (int32_t) cell;
stp[i * 4 + 1] = (int32_t) (cell + 1);
stp[i * 4 + 2] = (int32_t) ((cell + 1) / 4);
stp[i * 4 + 3] = (int32_t) (cell + 1);
for (int64_t h = 0; h < NHp; ++h) ps[i * NHp + h] = (int32_t) cell;
}
if (cudaMemcpyAsync(pf_dev_, rec.data(), rec.size() * sizeof(int32_t), cudaMemcpyHostToDevice, cs_) != cudaSuccess) {
err = "mtp prefill: the input records upload failed";
return false;
}
const int32_t* d_tk = pf_dev_;
const int32_t* d_stp = d_tk + n;
const int32_t* d_ps = d_stp + 4 * n;
for (int64_t c = 0; c < n; c += max_t_) {
const int T = (int) std::min<int64_t>(max_t_, n - c);
if (cell0 + c + T <= first_needed) continue;
if (!capture_prefill_dev(T, err)) return false;
if (cudaMemcpyAsync(tok_, d_tk + c, (size_t) T * 4, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess ||
cudaMemcpyAsync(step_, d_stp + c * 4, (size_t) T * 16, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess ||
cudaMemcpyAsync(pos_, d_ps + c * NHp, (size_t) (T * NHp) * 4, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess ||
cudaMemcpyAsync(Rin_, R_rows + (size_t) c * HCN, (size_t) T * HCN * sizeof(float), cudaMemcpyDeviceToDevice,
cs_) != cudaSuccess ||
cudaGraphLaunch(prefill_dev_exec_[T], cs_) != cudaSuccess) {
err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
}
if (cudaStreamSynchronize(cs_) != cudaSuccess) {
err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
ms_prefill += ms_since(t0);
return true;
}
for (int64_t c = 0; c < n; c += max_t_) {
const int T = (int) std::min<int64_t>(max_t_, n - c);
if (cell0 + c + T <= first_needed) continue;
@@ -551,6 +631,7 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_
bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err,
float* probs, float min_p, int* n_drafts) {
const OnDevice on_device(device_);
if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; }
if (!capture_round(T, err)) return false;
const Clock::time_point t0 = Clock::now();
@@ -601,6 +682,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
bool MtpDrafter::draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err,
float* probs, float min_p, int* n_drafts) {
const OnDevice on_device(device_);
// row 0 is the real pair; rows 1.. repeat it and only write cells the next round overwrites
const int64_t HCN = g_->hc * g_->n_embd;
for (int t = 0; t < T; ++t)
+7 -4
View File
@@ -13,9 +13,12 @@
namespace strata::core {
namespace {
bool eligible(const std::string& name, bool include_ple_key) {
bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) {
const auto& name = tensor.name;
if (name.rfind("blk.", 0) != 0) return false;
if (include_ple_key && name == "blk.1.ple_key.weight") return true;
// The native PLE kernel accepts Q2_0. Other quantized keys can be converted to BF16 by iq_pack;
// keep their packed bytes resident instead of overriding them with an unsupported native key.
if (name == "blk.1.ple_key.weight") return include_ple_key && tensor.type == 42; // 42 = Q2_0
static const char* suffixes[] = {".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight",
".attn_q.weight", ".attn_k.weight", ".attn_v.weight", ".attn_output.weight",
".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight"};
@@ -38,7 +41,7 @@ bool NativeDense::served_names(const std::vector<std::string>& shards, bool incl
for (const auto& path : shards) {
strata::GgufFile gguf(path);
for (const auto& tensor : gguf.tensors())
if (eligible(tensor.name, include_ple_key) && strata::kernels::native_mmvq_supported(tensor.type) &&
if (eligible(tensor, include_ple_key) && strata::kernels::native_mmvq_supported(tensor.type) &&
tensor.shape.size() == 2)
out.insert(tensor.name);
}
@@ -124,7 +127,7 @@ bool NativeDense::load(const std::vector<std::string>& shards, WeightTable& tabl
}
}
for (const auto& tensor : gguf.tensors()) {
if (!eligible(tensor.name, include_ple_key)) continue;
if (!eligible(tensor, include_ple_key)) continue;
if (!seen.insert(tensor.name).second) {
err = "native dense: duplicate tensor " + tensor.name; return false;
}
+11 -5
View File
@@ -129,23 +129,27 @@ PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, un
if (slice_bytes) slice_bytes = slice; // sliced registration: record the uniform size
}
PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds) : capacity(bytes) {
PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds,
uint64_t max_pinned_bytes) : capacity(bytes) {
if (bytes == 0) return;
base = reserve(bytes, backing, note);
// Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region
// that has already been faulted in page by page is far more expensive to register and may fail outright.
if (base) {
const cudaError_t e = cudaHostRegister(base, (size_t) bytes, cudaHostRegisterPortable | cudaHostRegisterMapped);
if (e == cudaSuccess) {
const bool capped = max_pinned_bytes > 0 && max_pinned_bytes < bytes && bounds.size() >= 2;
const cudaError_t e = capped ? cudaSuccess :
cudaHostRegister(base, (size_t) bytes, cudaHostRegisterPortable | cudaHostRegisterMapped);
if (!capped && e == cudaSuccess) {
note = "cudaHostRegister PORTABLE ok; " + note;
registered_bytes = bytes;
} else if (bounds.size() >= 2 && clear_error()) {
} else if (bounds.size() >= 2 && (capped || clear_error())) {
// Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start. The rest stays
// resident through the working-set lock below. (P6: slices may differ in size, one per layer.)
slice_bytes = 1; // sliced; the uniform constructor records the size
for (size_t i = 0; i + 1 < bounds.size(); ++i) {
const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i];
if (capped && (off > max_pinned_bytes || n > max_pinned_bytes - off)) break;
if (cudaHostRegister((uint8_t*) base + off, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped) != cudaSuccess) {
(void) cudaGetLastError();
break;
@@ -154,7 +158,9 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds) :
registered_bytes = off + n;
++registered_slices;
}
note = "cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); " +
note = (capped ? "cudaHostRegister limited to " + std::to_string(max_pinned_bytes >> 30) +
" GiB for CUDA1; " :
"cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); ") +
std::to_string(registered_slices) + " slices pinned (" + std::to_string(registered_bytes >> 30) +
" GiB); " + note;
if (registered_bytes < bytes) {
+325
View File
@@ -0,0 +1,325 @@
#include "strata/core/remote_experts.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <cstring>
namespace strata::core {
namespace {
constexpr int64_t H = strata::kernels::cpu::H;
constexpr int64_t FF = strata::kernels::cpu::FF;
constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10;
// Small enough to copy as one pinned buffer per layer. The kernels read the
// individual arrays through pointers into the same device allocation.
struct RemoteMeta {
unsigned long long ptr[CAP];
int32_t start[CAP + 1];
int32_t dst[CAP];
int32_t tok[CAP];
int32_t count;
};
struct DeviceScope {
int previous = -1;
bool ok = false;
cudaError_t status = cudaSuccess;
const char* failed_step = nullptr;
explicit DeviceScope(int device) {
status = cudaGetDevice(&previous);
if (status != cudaSuccess) {
previous = -1;
failed_step = "cudaGetDevice";
return;
}
status = cudaSetDevice(device);
if (status != cudaSuccess) {
failed_step = "cudaSetDevice";
return;
}
ok = true;
}
~DeviceScope() { if (previous >= 0) cudaSetDevice(previous); }
std::string error(int device) const {
return std::string("CUDA") + std::to_string(device) + " experts: " +
(failed_step ? failed_step : "device switch") +
"(" + std::to_string(device) + ") failed: " + cudaGetErrorString(status) +
" (CUDA error " + std::to_string((int) status) + ")";
}
};
bool check(cudaError_t result, const char* what, std::string& err, int device) {
if (result == cudaSuccess) return true;
err = "CUDA" + std::to_string(device) + " experts: " + what + ": " + cudaGetErrorString(result);
return false;
}
} // namespace
RemoteExperts::~RemoteExperts() { close(); }
bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) {
int count = 0;
if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false;
if (device < 1 || device >= count) {
err = "CUDA" + std::to_string(device) + " experts: CUDA device is not visible";
return false;
}
// The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up
// costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible
// before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default.
const char* spin = std::getenv("STRATA_REMOTE_SPIN");
if (!(spin && spin[0] == '0')) cudaInitDevice(device, cudaDeviceScheduleSpin | cudaDeviceMapHost, 0);
cudaGetLastError();
DeviceScope scope(device);
if (!scope.ok) { err = scope.error(device); return false; }
size_t free_bytes = 0, total_bytes = 0;
if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "preflight free memory", err, device)) return false;
free_gib = (double) free_bytes / 1073741824.0;
return true;
}
void RemoteExperts::close() {
if (device_ < 0) return;
DeviceScope scope(device_);
if (scope.ok) {
if (stream_) cudaStreamSynchronize(stream_);
cache_.close();
if (d_x_) cudaFree(d_x_);
if (d_out_) cudaFree(d_out_);
if (d_q8_) cudaFree(d_q8_);
if (d_scales_) cudaFree(d_scales_);
if (d_scratch_) cudaFree(d_scratch_);
if (d_meta_) cudaFree(d_meta_);
if (h_x_) cudaFreeHost(h_x_);
if (h_out_) cudaFreeHost(h_out_);
if (h_meta_) cudaFreeHost(h_meta_);
if (stream_) cudaStreamDestroy(stream_);
}
device_ = -1;
stream_ = nullptr;
h_x_ = h_out_ = d_x_ = d_out_ = nullptr;
h_meta_ = d_meta_ = nullptr;
d_q8_ = nullptr;
d_scales_ = nullptr;
d_scratch_ = nullptr;
d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr;
d_ptr_ = nullptr;
original_row_.clear();
layers_present_.clear();
}
bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts,
const std::vector<std::pair<int32_t, int32_t>>& ranked,
const ExpertCache& primary, ExpertSource& source,
std::vector<uint8_t>& claimed, std::string& err) {
close();
int count = 0;
if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false;
if (device < 1 || device >= count || slots <= 0 || ranked.empty() ||
layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts) {
err = "CUDA" + std::to_string(device) + " experts: need the device, ranked experts and positive slot count";
return false;
}
DeviceScope scope(device);
if (!scope.ok) { err = scope.error(device); return false; }
device_ = device;
n_expert_ = experts;
const auto& lay = strata::kernels::cpu::expert_layout();
std::vector<std::pair<int32_t, int32_t>> selected;
selected.reserve((size_t) slots);
std::vector<uint8_t> picked(claimed.size(), 0);
for (const auto& pair : ranked) {
if (pair.first < 0 || pair.first >= layers || pair.second < 0 || pair.second >= experts) continue;
const size_t index = (size_t) pair.first * (size_t) experts + (size_t) pair.second;
if (primary.slot_of(pair.first, pair.second) < 0 && !claimed[index] && !picked[index]) {
selected.push_back(pair);
picked[index] = 1;
if ((int) selected.size() >= slots) break;
}
}
if (selected.empty()) { err = "CUDA" + std::to_string(device) + " experts: no unclaimed experts remain"; close(); return false; }
std::vector<int64_t> sizes;
if (lay.native) {
sizes.reserve(selected.size());
for (const auto& pair : selected) sizes.push_back((int64_t) lay.blob_bytes(pair.first));
}
size_t free_bytes = 0, total_bytes = 0;
if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "free memory", err, device)) { close(); return false; }
uint64_t needed = 0;
for (const auto& pair : selected)
needed += lay.native ? (lay.blob_bytes(pair.first) + 255) / 256 * 256 : lay.max_blob;
// Leave room for the CUDA context, staging and later driver allocations, especially under WDDM.
if (needed + (512ull << 20) > free_bytes) {
err = "CUDA" + std::to_string(device) + " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string(device);
close(); return false;
}
const bool cache_ok = lay.native ? cache_.open_sized(sizes, layers, experts, err)
: cache_.open((int64_t) selected.size(), layers, experts,
(int64_t) lay.max_blob, err);
if (!cache_ok) { err = "CUDA" + std::to_string(device) + " experts: " + err; close(); return false; }
for (const auto& pair : selected) {
const int32_t slot = cache_.admit(pair.first, pair.second);
const uint8_t* blob = source.blob(pair.first, pair.second);
if (slot < 0 || !blob || !cache_.fill_slot_blocking(slot, blob, err, (int64_t) lay.blob_bytes(pair.first))) {
err = "CUDA" + std::to_string(device) + " experts: " +
(err.empty() ? "cache fill failed" : err);
close(); return false;
}
}
const auto& first = selected.front();
if (!cache_.verify_slot(cache_.slot_of(first.first, first.second), source.blob(first.first, first.second),
err, (int64_t) lay.blob_bytes(first.first))) {
err = "CUDA" + std::to_string(device) + " experts: " + err;
close(); return false;
}
const size_t scratch = std::max<size_t>(
(size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, FF),
strata::kernels::native_expert_scratch_bytes(CAP, FF));
const bool allocated =
check(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err, device) &&
check(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "input staging", err, device) &&
check(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "result staging", err, device) &&
check(cudaHostAlloc(&h_meta_, sizeof(RemoteMeta), cudaHostAllocPortable), "metadata staging", err, device) &&
check(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err, device) &&
check(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err, device) &&
check(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activation", err, device) &&
check(cudaMalloc((void**) &d_scales_, (size_t) CAP * (H / 32) * sizeof(float)), "activation scales", err, device) &&
check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) &&
check(cudaMalloc(&d_meta_, sizeof(RemoteMeta)), "group metadata", err, device);
if (!allocated) { close(); return false; }
// Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers
// directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies.
const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY");
zero_copy_ = !(zc && zc[0] == '0') &&
cudaHostGetDevicePointer((void**) &z_x_, h_x_, 0) == cudaSuccess &&
cudaHostGetDevicePointer((void**) &z_out_, h_out_, 0) == cudaSuccess;
cudaGetLastError();
auto* meta = (RemoteMeta*) d_meta_;
d_ptr_ = meta->ptr;
d_start_ = meta->start;
d_dst_ = meta->dst;
d_tok_ = meta->tok;
d_count_ = &meta->count;
owned_.resize(CAP);
layers_present_.assign((size_t) layers, 0);
group_of_.resize(CAP);
group_id_.reserve(CAP);
ptr_.reserve(CAP);
start_.reserve(CAP + 1);
dst_.reserve(CAP);
tok_.reserve(CAP);
original_row_.reserve(CAP);
computed_ = 0;
launched_layers_ = 0;
returned_bytes_ = full_row_bytes_ = 0;
for (const auto& pair : selected) {
layers_present_[(size_t) pair.first] = 1;
claimed[(size_t) pair.first * (size_t) experts + (size_t) pair.second] = 1;
}
return true;
}
bool RemoteExperts::begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok,
int64_t k, const int32_t* kind, const int32_t* primary_res,
std::string& err) {
// cumulative host time in here (staging and launches), reported per request by the driver
struct Timer { double& acc; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
~Timer() { acc += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); } } timer{ms_begin_};
const int64_t n = n_tok * k;
if (n <= 0 || n > CAP || n_tok > strata::kernels::cpu::MAXT || k != 10 || layer < 0 ||
(size_t) layer >= layers_present_.size() || device_ < 0) {
err = "CUDA" + std::to_string(device_) + " experts: invalid layer, routing width or window size";
return false;
}
std::fill(owned_.begin(), owned_.begin() + n, 0);
group_id_.clear(); ptr_.clear(); start_.clear(); dst_.clear(); tok_.clear(); original_row_.clear();
if (!layers_present_[(size_t) layer]) return true;
std::fill(group_of_.begin(), group_of_.begin() + n, -1);
for (int64_t i = 0; i < n; ++i) {
const int32_t e = ids[i];
if ((kind && kind[i] != -1) || e < 0 || e >= n_expert_ ||
(primary_res && primary_res[(size_t) layer * (size_t) n_expert_ + (size_t) e] >= 0)) continue;
const int32_t slot = cache_.slot_of(layer, e);
if (slot < 0) continue;
owned_[(size_t) i] = 1;
int32_t group = -1;
for (size_t g = 0; g < group_id_.size(); ++g)
if (group_id_[g] == e) { group = (int32_t) g; break; }
if (group < 0) {
group = (int32_t) group_id_.size();
group_id_.push_back(e);
ptr_.push_back((unsigned long long) cache_.device_slot(slot));
}
group_of_[(size_t) i] = group;
++computed_;
}
if (group_id_.empty()) return true;
for (size_t g = 0; g < group_id_.size(); ++g) {
start_.push_back((int32_t) dst_.size());
for (int64_t i = 0; i < n; ++i) if (group_of_[(size_t) i] == (int32_t) g) {
// The grouped kernels read the activation from `tok`, so their
// output row can instead be packed densely for the USB4 return.
original_row_.push_back((int32_t) i);
dst_.push_back((int32_t) dst_.size());
tok_.push_back((int32_t) (i / k));
}
}
start_.push_back((int32_t) dst_.size());
// Private pinned buffers survive until this GPU has consumed them. The CPU
// pool can write other output rows without a cross-device race.
std::memcpy(h_x_, x, (size_t) n_tok * H * sizeof(float));
auto* meta = (RemoteMeta*) h_meta_;
std::memcpy(meta->ptr, ptr_.data(), ptr_.size() * sizeof(ptr_[0]));
std::memcpy(meta->start, start_.data(), start_.size() * sizeof(start_[0]));
std::memcpy(meta->dst, dst_.data(), dst_.size() * sizeof(dst_[0]));
std::memcpy(meta->tok, tok_.data(), tok_.size() * sizeof(tok_[0]));
meta->count = (int32_t) group_id_.size();
DeviceScope scope(device_);
if (!scope.ok) { err = scope.error(device_); return false; }
groups_ = (int32_t) group_id_.size();
const cudaStream_t s = stream_;
const bool staged =
(zero_copy_ || check(cudaMemcpyAsync(d_x_, h_x_, (size_t) n_tok * H * sizeof(float), cudaMemcpyHostToDevice, s), "copy input", err, device_)) &&
check(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(RemoteMeta), cudaMemcpyHostToDevice, s), "copy group metadata", err, device_);
if (!staged) return false;
const auto& lay = strata::kernels::cpu::expert_layout();
if (lay.native) {
strata::kernels::quantize_q8_1_rows(zero_copy_ ? z_x_ : d_x_, n_tok, H, d_q8_, s);
const auto& fmt = lay.fmt[(size_t) layer];
auto L = strata::kernels::native_expert_layout(fmt.gu_type, fmt.d_type, fmt.n_embd, fmt.n_ff);
strata::kernels::native_expert_grouped(L, d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
groups_, (int64_t) dst_.size(), d_q8_, d_scratch_, zero_copy_ ? z_out_ : d_out_, s);
} else {
strata::kernels::quantize_q8_0_scaled(zero_copy_ ? z_x_ : d_x_, d_q8_, d_scales_, n_tok * H, s);
strata::kernels::moe_grouped_s2(d_ptr_, d_start_, d_count_, d_dst_, d_tok_,
groups_, (int64_t) dst_.size(), d_q8_, d_scales_, d_scratch_, zero_copy_ ? z_out_ : d_out_, s);
}
const uint64_t compact_bytes = (uint64_t) dst_.size() * H * sizeof(float);
if (!zero_copy_ && !check(cudaMemcpyAsync(h_out_, d_out_, (size_t) compact_bytes, cudaMemcpyDeviceToHost, s),
"copy results", err, device_)) return false;
++launched_layers_;
returned_bytes_ += compact_bytes;
full_row_bytes_ += (uint64_t) n * H * sizeof(float);
return true;
}
bool RemoteExperts::finish(float* out, std::string& err) {
if (group_id_.empty()) return true;
DeviceScope scope(device_);
if (!scope.ok) { err = scope.error(device_); return false; }
const auto w0 = std::chrono::steady_clock::now();
if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) return false;
ms_wait_ += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - w0).count();
for (size_t i = 0; i < original_row_.size(); ++i)
std::memcpy(out + (size_t) original_row_[i] * H, h_out_ + i * H, (size_t) H * sizeof(float));
return true;
}
} // namespace strata::core
+86 -22
View File
@@ -5,6 +5,7 @@
#endif
#include "strata/core/native_head.hpp"
#include "strata/core/on_device.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/bf16_gemv.hpp"
@@ -127,6 +128,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
const NativeHead* head, int max_t, std::string& err) {
g_diag_verifier.store(this);
diag_verify_fn().store(&diag_active_verifier);
cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there
wt_ = &wt;
g_ = &g;
ss_ = &ss;
@@ -153,6 +155,12 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
err = "verify: geometry differs from the artifact's";
return false;
}
if (le_ < 0) le_ = g.n_layers;
if (lb_ < 0 || lb_ >= le_ || le_ > g.n_layers || (lb_ > 0 && hand_in_ == nullptr) ||
(le_ < g.n_layers && hand_out_ == nullptr)) {
err = "verify: the stage's layer range or its hand-off buffers are wrong";
return false;
}
const WeightRef* wo = wt.find("output.weight");
if (wo == nullptr) { err = "verify: output.weight is missing"; return false; }
n_vocab_ = wo->ne1;
@@ -266,6 +274,21 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
err = "verify: stream create failed";
return false;
}
// E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on;
// exact, but neutral on RIBPC 1-2 GPUs: off by default)
{
const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN");
device_plan_ = v != nullptr && std::atoi(v) != 0;
}
if (device_plan_) {
bool ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess;
if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) {
ok2 = cudaMalloc((void**) &slot_off_d_, (size_t) hits.n_slots * sizeof(unsigned long long)) == cudaSuccess &&
cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long),
cudaMemcpyHostToDevice) == cudaSuccess;
}
if (!ok2) { cudaGetLastError(); device_plan_ = false; }
}
std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers\n", max_t,
(double) count.used / 1048576.0);
return true;
@@ -297,7 +320,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
(uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
const int64_t TS = (s.idx_block - 1) * ID;
const bool ple_on = ss.ple.ready();
const bool ple_on = ss.ple.ready() && ple_stage();
auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };
const int G = (split_ && T >= 2) ? 2 : 1;
const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T};
@@ -309,8 +332,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
copy_i32_from_mapped(pos_, m_pos_, (int64_t) T * NH, cs);
if (ple_on) copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);
// ---- the embeddings, broadcast to the hc streams
if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table
// ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's
// residual, pending write and inject (see set_stage)
const int64_t HB = Verifier::handoff_floats(g);
if (lb_ > 0) {
for (int t = 0; t < T; ++t) {
copy_from_mapped(Rt(t), hand_in_ + (size_t) t * HB, HC * N, cs);
copy_from_mapped(bo_ + (size_t) t * N, hand_in_ + (size_t) t * HB + HC * N, N, cs);
copy_from_mapped(inj2_ + (size_t) t * HC, hand_in_ + (size_t) t * HB + HC * N + N, HC, cs);
}
} else if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table
ne->gather_dev(tok_, T, emb_, cs);
broadcast_streams(emb_, R_, N, (int) HC, T, cs);
} else {
@@ -514,6 +545,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K;
if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false;
}
if (device_plan_) // E-6: every routed expert resident: this group's plan without the host
resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,
hits_.cache_base, slot_off_d_, (long long) hits_.blob,
plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,
(uint32_t) ((l - lb_) * G + grp + 1), cs);
doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);
{
@@ -547,11 +583,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// ---------------------------------------------------------------- post(l, group): experts, combine
auto post = [&](int64_t l, int grp) -> bool {
const int tb = tb_[grp], te = te_[grp], n = te - tb;
const uint32_t ring = (uint32_t) (l * G + grp + 1);
wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan
const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1);
const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K;
int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16);
copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident)
wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);
copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);
} else {
wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan
copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
}
const int32_t* p_counts = pl;
const int32_t* p_start = pl + 4;
const int32_t* p_dst = p_start + capx + 1;
@@ -576,7 +617,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
};
grouped(p_ptr, p_start, p_counts);
wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped
if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);
else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped
if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging
const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;
@@ -584,8 +626,14 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);
}
grouped(p_ptr2, p_start2, p_counts + 2);
wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows
copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);
if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros
wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);
copy_or_zero_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,
skip_ + grp, ring, cs);
} else {
wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows
copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);
}
moe_hit_add(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, cap, N, cs);
for (int t = tb; t < te; ++t) {
MoEBuffers mb = ss.moe;
@@ -602,12 +650,20 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
};
for (int grp = 0; grp < G; ++grp)
if (!pre(0, grp)) return false;
for (int64_t l = 0; l < g.n_layers; ++l)
if (!pre(lb_, grp)) return false;
for (int64_t l = lb_; l < le_; ++l)
for (int grp = 0; grp < G; ++grp) {
if (!post(l, grp)) return false;
if (l + 1 < g.n_layers && !pre(l + 1, grp)) return false;
if (l + 1 < le_ && !pre(l + 1, grp)) return false;
}
if (le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head
for (int t = 0; t < T; ++t) {
copy_from_mapped(hand_out_ + (size_t) t * HB, Rt(t), HC * N, cs);
copy_from_mapped(hand_out_ + (size_t) t * HB + HC * N, bo_ + (size_t) t * N, N, cs);
copy_from_mapped(hand_out_ + (size_t) t * HB + HC * N + N, inj2_ + (size_t) t * HC, HC, cs);
}
return true;
}
// ---- the head, T columns, and the argmax of each
{
@@ -695,7 +751,8 @@ bool Verifier::capture_commit(std::string& err) {
try {
copy_i32_from_mapped(commit_, m_commit_, 2 + MT, cs_);
int64_t qsa_index = 0, gdn_index = 0;
for (int64_t l = 0; l < g.n_layers && ok; ++l) {
for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
for (int64_t l = lb_; l < le_ && ok; ++l) {
const LayerView v(*wt_, l);
if (!is_qsa_layer(g, l)) {
const WeightRef* wnm = need(v, "ssm_norm.weight", err);
@@ -721,7 +778,7 @@ bool Verifier::capture_commit(std::string& err) {
++qsa_index;
}
}
if (ok && ss.ple.ready()) copy_indexed(ss.ple.hist, hist_snap_, HS, commit_ + 1, HS, cs_);
if (ok && ss.ple.ready() && ple_stage()) copy_indexed(ss.ple.hist, hist_snap_, HS, commit_ + 1, HS, cs_);
} catch (const std::exception& e) {
err = std::string("verify commit: ") + e.what();
ok = false;
@@ -744,6 +801,7 @@ bool Verifier::capture_commit(std::string& err) {
bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out,
std::string& err) {
using namespace strata::kernels;
const OnDevice on_device(device_);
if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
const ModelGeometry& g = *g_;
SessionState& ss = *ss_;
@@ -757,7 +815,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s);
for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) (pos0 + t);
}
if (ss.ple.ready()) {
if (ss.ple.ready() && ple_stage()) {
uint32_t rows[kVerifyMaxT * PLE_N_HEADS];
int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
for (int t = 0; t < T; ++t) {
@@ -785,8 +843,8 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
volatile uint32_t* const flag = h_flag_;
const int G = groups_[T] > 0 ? groups_[T] : 1;
const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
for (int64_t k = 0; k < g.n_layers * G; ++k) {
const int64_t l = k / G;
for (int64_t k = 0; k < (le_ - lb_) * G; ++k) {
const int64_t l = lb_ + k / G;
const int grp = (int) (k % G);
const uint32_t want = (uint32_t) (k + 1);
const Clock::time_point a = Clock::now();
@@ -844,6 +902,10 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
// own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to
// the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever
// the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw.
if (le_ < g.n_layers) { // a layer split's earlier stage: the hand-off is written (synced above)
++windows;
return next_ == nullptr || next_->run(T, tokens, pos0, pool, next_user_, out, err);
}
const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;
if (head_sampling_ && (sampled || hist_d_ != nullptr)) {
SamplerParams sp = sampling_;
@@ -934,6 +996,7 @@ void Verifier::publish_plan(void* ctx) {
}
bool Verifier::commit(int n_keep, std::string& err) {
const OnDevice on_device(device_);
if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }
const Clock::time_point t0 = Clock::now();
h_commit_[0] = n_keep;
@@ -944,12 +1007,13 @@ bool Verifier::commit(int n_keep, std::string& err) {
if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; }
const cudaError_t se = cudaStreamSynchronize(cs_);
if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; }
for (int t = 0; t < n_keep; ++t) {
ss_->ple_prev[0] = ss_->ple_prev[1];
ss_->ple_prev[1] = last_tokens_[t];
}
if (ple_stage()) // stages that share one session must advance it once
for (int t = 0; t < n_keep; ++t) {
ss_->ple_prev[0] = ss_->ple_prev[1];
ss_->ple_prev[1] = last_tokens_[t];
}
ms_commit += ms_since(t0);
return true;
return next_ == nullptr || next_->commit(n_keep, err);
}
} // namespace strata::core
+29 -2
View File
@@ -6,7 +6,8 @@
// `maddubs` and a `madd`. The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references): integer sums
// per block, times d_x * d_y * the format's constant - only the order of the float additions differs.
//
// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22). IQ1_M stays on ggml-cpu.
// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22). IQ1_M stays on ggml-cpu (no shipped
// model has IQ1_M expert rows: the 'Coder IQ1_M' pack's gate/up are IQ2_S / IQ3_XXS / IQ3_S).
#include "strata/kernels/cpu/iq_avx512.hpp"
#define GGML_COMMON_DECL_CPP
@@ -16,6 +17,7 @@
#include <immintrin.h>
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace strata::kernels::cpu {
@@ -26,6 +28,16 @@ inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); retur
inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; }
inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; }
// E-2: the IQ3 grids by one AVX-512 gather (the same words, the same results) - measured 3-5% SLOWER than the scalar
// lookups on a Ryzen 5 7600 (Zen 4 gathers are microcoded), so opt-in: STRATA_IQ_GATHER=1
const bool gather = std::getenv("STRATA_IQ_GATHER") != nullptr;
// E-2: software prefetch distance in bytes (STRATA_IQ_PREFETCH; 0 = off): -2-3% gate/up time on IQ3_S decode
// (the rows are read at ~30 GB/s by 6 cores, near what DDR5 with 4 KB pages gives: the pool is memory-bound)
const int prefetch_ahead = [] {
const char* v = std::getenv("STRATA_IQ_PREFETCH");
return v ? std::atoi(v) : 2048;
}();
// lanes 0-7 -> s0, 8-15 -> s1, 16-23 -> s2, 24-31 -> s3 (int16 lanes of a maddubs result: two values each)
inline __m512i scales4(int s0, int s1, int s2, int s3) {
const __m512i idx = _mm512_set_epi16(3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -98,7 +110,9 @@ template <> struct Fmt<18> { // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-
static constexpr float K = 0.25f;
static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
const uint8_t* q = b + 2 + 16 * j;
g = _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]],
// E-2: one gather of the 16 grid words (the scalar lookups assembled with set_epi32 cost ~30 uops)
g = gather ? _mm512_i32gather_epi32(_mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)), iq3xxs_grid, 4)
: _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]],
(int) iq3xxs_grid[q[11]], (int) iq3xxs_grid[q[10]], (int) iq3xxs_grid[q[9]], (int) iq3xxs_grid[q[8]],
(int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]],
(int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]);
@@ -119,12 +133,18 @@ template <> struct Fmt<21> { // IQ3_S: d, qs[64], qh[8], signs[32], scales[4]
static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
const uint8_t* q = b + 2 + 16 * j;
const uint32_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1];
if (gather) { // E-2: the 9-bit indices (the high bit from qh under a mask), one gather
__m512i idx = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q));
idx = _mm512_mask_add_epi32(idx, (__mmask16) (h0 | (h1 << 8)), idx, _mm512_set1_epi32(256));
g = _mm512_i32gather_epi32(idx, iq3s_grid, 4);
} else {
#define G3(k, h, kk) (int) iq3s_grid[q[k] | (((h >> kk) & 1) << 8)]
g = _mm512_set_epi32(G3(15, h1, 7), G3(14, h1, 6), G3(13, h1, 5), G3(12, h1, 4),
G3(11, h1, 3), G3(10, h1, 2), G3(9, h1, 1), G3(8, h1, 0),
G3(7, h0, 7), G3(6, h0, 6), G3(5, h0, 5), G3(4, h0, 4),
G3(3, h0, 3), G3(2, h0, 2), G3(1, h0, 1), G3(0, h0, 0));
#undef G3
}
m = _cvtu64_mask64(u64(b + 74 + 8 * j));
const uint8_t s = b[106 + j];
const int sa = 2 * (s & 15) + 1, sb = 2 * (s >> 4) + 1;
@@ -139,6 +159,13 @@ inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y,
const __m512i zero = _mm512_setzero_si512();
for (int i = 0; i < nblocks; ++i) {
const uint8_t* blk = row + (size_t) i * Fmt<TY>::bytes;
// E-2: the weight rows stream from DRAM (4 KB pages when large pages are refused): ask for the bytes a few
// blocks ahead (the next row's start included) before the decode needs them
if (prefetch_ahead > 0) {
const uint8_t* ahead = blk + (size_t) prefetch_ahead;
_mm_prefetch((const char*) ahead, _MM_HINT_T0);
_mm_prefetch((const char*) ahead + 64, _MM_HINT_T0);
}
__m512i acci[NT];
for (int t = 0; t < NT; ++t) acci[t] = _mm512_setzero_si512();
for (int j = 0; j < 4; ++j) {
+3 -2
View File
@@ -79,8 +79,9 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
int r0, int r1) {
// the multi-token kernels decode the weights once for all tokens: 2.0-2.4x ggml-cpu at three tokens, no faster
// at one (all are bound by the codebook lookups, ~5 GB/s per core), measured by native_expert_parity. AVX-512
// first, then the AVX-2 one (Zen 2/3, Intel 12th-14th gen); STRATA_NO_IQ512 / STRATA_NO_IQ256 fall back to
// ggml-cpu's single-token vec_dot.
// first, then the AVX-2 one (Zen 2/3, Intel 12th-14th gen). STRATA_NO_IQ512 drops an AVX-512 CPU to the
// AVX-2 kernel, STRATA_NO_IQ256 drops the AVX-2 kernel; ggml-cpu's single-token vec_dot is reached only with
// both set (and on a CPU without AVX-512, STRATA_NO_IQ512 changes nothing).
static const bool avx512 = cpu_avx512_ok() && std::getenv("STRATA_NO_IQ512") == nullptr;
static const bool avx2 = std::getenv("STRATA_NO_IQ256") == nullptr;
if (nt >= 2 && iq512_supported(f.gu_type)) { // one token: ggml-cpu is as fast or faster
+61 -23
View File
@@ -11,9 +11,33 @@ namespace {
constexpr int THREADS = 256;
constexpr int MAXK = 16; // n_embd up to 4096, held in registers between the dot and the update
Cvec g_cvec;
int* g_on = nullptr;
Cvec g_cvec; // the description; its device pointers are the uploading device's
bool g_on_host = false;
// the tables on every device that holds them (a layer split applies the vector on several)
constexpr int kDevices = 64;
struct DevTables { float* dir = nullptr; float* s = nullptr; int* on = nullptr; };
DevTables g_dev[kDevices];
std::vector<float> g_dir_host, g_s_host;
int cur_device() {
int d = 0;
if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kDevices) d = 0;
return d;
}
bool upload_here(std::string& err) {
DevTables& t = g_dev[cur_device()];
if (t.dir != nullptr) return true;
const int flag = g_on_host ? 1 : 0;
if (cudaMalloc(&t.dir, g_dir_host.size() * sizeof(float)) != cudaSuccess ||
cudaMalloc(&t.s, g_s_host.size() * sizeof(float)) != cudaSuccess || cudaMalloc(&t.on, sizeof(int)) != cudaSuccess ||
cudaMemcpy(t.dir, g_dir_host.data(), g_dir_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(t.s, g_s_host.data(), g_s_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(t.on, &flag, sizeof(int), cudaMemcpyHostToDevice) != cudaSuccess) {
err = "control vector: device allocation failed";
t = DevTables{};
return false;
}
return true;
}
// the fused hyper-connection read's gate (fused_gr.cu), so a write done here is bitwise the one it would have folded
__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); }
@@ -78,21 +102,26 @@ bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int
int64_t n_embd, int64_t hc, std::string& err) {
if (n_embd < 1 || n_embd > (int64_t) THREADS * MAXK) { err = "control vector: unsupported n_embd"; return false; }
if (s.empty() || dir.size() != s.size() * (size_t) n_embd) { err = "control vector: bad table sizes"; return false; }
float* d_dir = nullptr;
float* d_s = nullptr;
int* d_on = nullptr;
const int one = 1;
if (cudaMalloc(&d_dir, dir.size() * sizeof(float)) != cudaSuccess ||
cudaMalloc(&d_s, s.size() * sizeof(float)) != cudaSuccess || cudaMalloc(&d_on, sizeof(int)) != cudaSuccess ||
cudaMemcpy(d_dir, dir.data(), dir.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(d_s, s.data(), s.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(d_on, &one, sizeof(int), cudaMemcpyHostToDevice) != cudaSuccess) {
err = "control vector: device allocation failed";
return false;
int prev = 0; // a new vector replaces the old one on every device
cudaGetDevice(&prev);
for (int d = 0; d < kDevices; ++d) {
if (g_dev[d].dir == nullptr) continue;
cudaSetDevice(d);
cudaDeviceSynchronize();
cudaFree(g_dev[d].dir);
cudaFree(g_dev[d].s);
cudaFree(g_dev[d].on);
g_dev[d] = DevTables{};
}
g_cvec.dir = d_dir;
g_cvec.s = d_s;
g_cvec.on = d_on;
cudaSetDevice(prev);
g_dir_host = dir;
g_s_host = s;
g_on_host = true;
if (!upload_here(err)) return false;
const DevTables& t = g_dev[cur_device()];
g_cvec.dir = t.dir;
g_cvec.s = t.s;
g_cvec.on = t.on;
g_cvec.mode = mode;
g_cvec.first = first;
g_cvec.last = last;
@@ -100,26 +129,35 @@ bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int
g_cvec.hc = hc;
g_cvec.steered.assign(s.size(), false);
for (size_t l = 0; l < s.size(); ++l) g_cvec.steered[l] = s[l] != 0.0f;
g_on = d_on;
g_on_host = true;
return true;
}
bool cvec_replicate(std::string& err) { return !g_cvec.loaded() || upload_here(err); }
void cvec_set_enabled(bool on) {
if (g_on == nullptr || on == g_on_host) return;
cudaDeviceSynchronize(); // nothing in flight may still read the flag
if (!g_cvec.loaded() || on == g_on_host) return;
int prev = 0;
cudaGetDevice(&prev);
const int v = on ? 1 : 0;
cudaMemcpy(g_on, &v, sizeof(int), cudaMemcpyHostToDevice);
for (int d = 0; d < kDevices; ++d) {
if (g_dev[d].on == nullptr) continue;
cudaSetDevice(d);
cudaDeviceSynchronize(); // nothing in flight may still read the flag
cudaMemcpy(g_dev[d].on, &v, sizeof(int), cudaMemcpyHostToDevice);
}
cudaSetDevice(prev);
g_on_host = on;
}
bool cvec_enabled() { return g_on != nullptr && g_on_host; }
bool cvec_enabled() { return g_cvec.loaded() && g_on_host; }
void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj,
int64_t inj_ld, bool write, void* stream) {
if (!g_cvec.loaded() || T < 1) return;
const DevTables& t = g_dev[cur_device()];
if (t.dir == nullptr) throw std::runtime_error("cvec_apply: the control vector is not on this device (cvec_replicate)");
const dim3 grid((unsigned) g_cvec.hc, (unsigned) T);
cvec_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(R, g_cvec.dir, g_cvec.s, g_cvec.on, g_cvec.mode, layer,
cvec_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(R, t.dir, t.s, t.on, g_cvec.mode, layer,
(int) g_cvec.n_embd, (int) g_cvec.hc, r_ld, bo, bo_ld,
inj, inj_ld, write ? 1 : 0);
if (cudaPeekAtLastError() != cudaSuccess) throw std::runtime_error("cvec_apply: launch failed");
+14 -5
View File
@@ -315,11 +315,20 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
m.T = n_tok;
cudaStream_t st = (cudaStream_t) stream;
gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
static bool attr = false;
if (!attr) {
cudaFuncSetAttribute(gr_down_multi_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,
(int) (kFusedGrMaxT * TILE * sizeof(float)));
attr = true;
// the shared-memory opt-in is a per-DEVICE setting: once per device, not once per process (a layer split
// runs this kernel on two cards)
static bool attr[64] = {};
int dev = 0;
cudaGetDevice(&dev);
if (dev < 0 || dev >= 64 || !attr[dev]) {
// at most what the card allows (Turing: 64 KB - enough for windows of up to 6 tokens)
int optin = 0;
cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
int want = (int) (kFusedGrMaxT * TILE * sizeof(float));
if (optin > 0 && want > optin) want = optin;
cudaFuncSetAttribute(gr_down_multi_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, want);
cudaGetLastError();
if (dev >= 0 && dev < 64) attr[dev] = true;
}
gr_down_multi_kernel<<<DOWN_BLOCKS + 1, THREADS, (size_t) n_tok * TILE * sizeof(float), st>>>(m);
gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
+114
View File
@@ -93,6 +93,97 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_
else pooled[std::size_t(b + 1) * D + d] = dead[d];
if (d == 0 && pos != 0) *block_pos = rope_pos;
}
// ---- C-2: the batched append. The pooled key of a completed block b (its last cell pos = 4b+3), computed with
// the single append's arithmetic: keys rounded through F16, summed tail[0]+tail[1]+tail[2]+incoming in that order,
// the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch
// (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the
// spare after it (every earlier one's is overwritten by the next block in order).
__device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale,
const int32_t* mtab, bool zero_pos) {
float y = values[d];
if (d < ROT) {
const int pair = d % (ROT / 2);
const float theta = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair));
const float c = cosf(theta), s = sinf(theta);
const float a = values[pair], z = values[pair + ROT / 2];
y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
}
return y;
}
__device__ __forceinline__ float norm_scale(float mean, float* partials, int d) {
float square_sum = d < D ? mean * mean : 0.0f;
square_sum = warp_sum(square_sum);
const int lane = d % 32;
if (lane == 0) partials[d / 32] = square_sum;
__syncthreads();
square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f;
square_sum = warp_sum(square_sum);
return square_sum;
}
// cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead
__global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon,
float* __restrict__ dead, float* __restrict__ pooled, float theta_scale,
const int32_t* __restrict__ mtab) {
const int d = threadIdx.x;
__shared__ float values[D];
__shared__ float partials[32];
float mean = 0.0f;
if (d < D) {
const float incoming = __half2float(__float2half_rn(raw[d]));
float sum = incoming;
#pragma unroll
for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, incoming);
mean = __fmaf_rn(0.25f, sum, 0.0f);
}
const float square_sum = norm_scale(mean, partials, d);
const float scale = rsqrtf(square_sum / D + epsilon);
if (d < D) values[d] = scale * mean * gamma[d];
__syncthreads();
if (d >= D) return;
const float y = pooled_value(values, d, 0, theta_scale, mtab, true);
pooled[d] = y;
dead[d] = y;
}
__global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base,
const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail,
const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos,
int64_t first_block, int64_t last_block, float theta_scale, const int32_t* __restrict__ mtab) {
const int64_t b = first_block + blockIdx.x;
const int d = threadIdx.x;
__shared__ float values[D];
__shared__ float partials[32];
float mean = 0.0f;
if (d < D) {
auto key = [&](int j) -> float {
const int64_t cell = b * R + j;
return cell >= p0 ? __half2float(__float2half_rn(raw[(cell - p0) * D + d])) : tail[j * D + d];
};
float sum = key(0);
#pragma unroll
for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, key(j));
mean = __fmaf_rn(0.25f, sum, 0.0f);
}
const float square_sum = norm_scale(mean, partials, d);
const float scale = rsqrtf(square_sum / D + epsilon);
if (d < D) values[d] = scale * mean * gamma[d];
__syncthreads();
if (d >= D) return;
const int rope_pos = pos_base + R * (int) b;
pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, mtab, false);
if (b == last_block) {
pooled[std::size_t(b + 1) * D + d] = dead[d];
if (d == 0) *block_pos = rope_pos;
}
}
// the tail after the batch: slot s holds the key of the batch's last cell with cell % 4 == s (s < 3), if any
__global__ void append_tail(const float* __restrict__ raw, int64_t n, int64_t p0, float* __restrict__ tail) {
const int s = blockIdx.x, d = threadIdx.x;
if (d >= D) return;
const int64_t last = p0 + n - 1;
int64_t cell = last - ((last % R) - s + R) % R; // the last cell <= last with cell % 4 == s
if (cell < p0) return;
tail[s * D + d] = __half2float(__float2half_rn(raw[(cell - p0) * D + d]));
}
struct Span { const void* p; std::size_t n; };
void validate(Span s) {
const auto p = reinterpret_cast<std::uintptr_t>(s.p);
@@ -126,4 +217,27 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma,
float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells,
float freq_base, void* stream) {
if (n <= 0) return;
if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells ||
max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX ||
!std::isfinite(epsilon) || epsilon <= 0.0f || !std::isfinite(freq_base) || freq_base <= 1.0f)
throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions or parameters");
const float theta_scale = powf(freq_base, -2.0f / ROT);
const cudaStream_t st = static_cast<cudaStream_t>(stream);
const int32_t* mtab = mrope_table();
if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, mtab);
// completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n)
const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0
const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1
if (hi >= first)
append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, b.tail,
b.dead, b.pooled, b.block_pos, first, hi,
theta_scale, mtab);
append_tail<<<R - 1, D, 0, st>>>(raw, n, p0, b.tail);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
} // namespace strata::kernels
+20
View File
@@ -32,6 +32,7 @@ constexpr int D=128, HEADS=4, R=4, ROWS=32, WARPS=2, STRIDE=36, COMBINE=68;
struct TileA { uint32_t x[4]; };
struct TileB { uint32_t x[2]; };
struct TileC { float x[4]={0.0f,0.0f,0.0f,0.0f}; };
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800
__device__ __forceinline__ void load_a(TileA& a,const float* p) {
const float* src=p+(threadIdx.x%16)*STRIDE+(threadIdx.x/16)*4;
asm volatile("ldmatrix.sync.aligned.m8n8.x4.b16 {%0,%1,%2,%3}, [%4];"
@@ -48,6 +49,7 @@ __device__ __forceinline__ void mma(TileC& c,const TileA& a,const TileB& b) {
: "+f"(c.x[0]),"+f"(c.x[1]),"+f"(c.x[2]),"+f"(c.x[3])
: "r"(a.x[0]),"r"(a.x[1]),"r"(a.x[2]),"r"(a.x[3]),"r"(b.x[0]),"r"(b.x[1]));
}
#endif
__global__ __launch_bounds__(64,1) void score_kernel(
const float* __restrict__ pooled,const float* __restrict__ query,
const float* __restrict__ bias,const int32_t* __restrict__ step,
@@ -58,6 +60,23 @@ __global__ __launch_bounds__(64,1) void score_kernel(
const int row0=blockIdx.x*ROWS;
if(row0>full)return;
const int lane=threadIdx.x,warp=threadIdx.y;
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
// Turing (STRATA_EXPERIMENTAL_SM75, a layer-split stage): no tf32 mma. The same scores with FP32 FMAs, one row
// per thread of the first warp - rounded differently from the tensor-core path (FP32 instead of TF32 inputs).
if(warp!=0)return;
const int row=row0+lane;
if(row>full)return;
float h[HEADS];
for(int j=0;j<HEADS;++j){
float acc=0.0f;
for(int d=0;d<D;++d)acc=fmaf(pooled[size_t(row)*D+d],query[j*D+d],acc);
h[j]=fmaxf(acc,0.0f);
}
float sum=__fadd_rn(__fadd_rn(__fadd_rn(h[0],h[1]),h[2]),h[3]);
if(bias)sum=__fadd_rn(sum,bias[row]);
sum=__fadd_rn(sum,row==full&&n%R?1e9f:0.0f);
for(int i=row*R;i<n&&i<(row+1)*R;++i)cells[i]=sum;
#else
__shared__ __align__(16) float shared[WARPS*16*STRIDE];
float* tile=shared+warp*16*STRIDE;
TileC c[2];
@@ -118,6 +137,7 @@ __global__ __launch_bounds__(64,1) void score_kernel(
sum=__fadd_rn(sum,0.0f);
for(int i=row*R;i<n&&i<(row+1)*R;++i)cells[i]=sum;
}
#endif
}
struct Span{const void* p;size_t n;};
void validate(Span s){
+12 -3
View File
@@ -58,9 +58,18 @@ __global__ void apply(const float* x, float* out, int rows, int width,
out[start + pair + n_rot / 2] = a * s + b * c;
}
}
namespace { std::atomic<const int32_t*> mrope_tab{nullptr}; }
void mrope_table_set(const int32_t* device_table) { mrope_tab.store(device_table, std::memory_order_relaxed); }
const int32_t* mrope_table() { return mrope_tab.load(std::memory_order_relaxed); }
// one table per device (a layer split runs the rope kernels on several): set and read for the current device
namespace {
constexpr int kMropeDevices = 64;
std::atomic<const int32_t*> mrope_tab[kMropeDevices] = {};
int mrope_dev() {
int d = 0;
if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kMropeDevices) d = 0;
return d;
}
} // namespace
void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); }
const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); }
void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); }
void native_rope_apply(const float* x, float* out, int rows, int head_dim,
+5 -1
View File
@@ -656,7 +656,11 @@ void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t*
// then index past it at token 500. The kernel reads the real count from `step`, so a larger allocation is
// exactly what it wants. The opt-in therefore happens once, for the capacity.
const size_t smem = (size_t) (max_ids + 32) * sizeof(float);
static size_t s_configured = 0;
// per DEVICE: the opt-in is a device setting (a layer split runs this on two cards)
static size_t s_configured_dev[64] = {};
int cur_dev = 0;
cudaGetDevice(&cur_dev);
size_t& s_configured = s_configured_dev[(cur_dev >= 0 && cur_dev < 64) ? cur_dev : 0];
if (smem > s_configured) {
int dev = 0, max_shared = 0;
cudaGetDevice(&dev);
+663
View File
@@ -0,0 +1,663 @@
// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp.
#include "strata/kernels/qsa_prompt_attn.hpp"
#include "strata/kernels/kv_q8.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <math_constants.h>
#include <cstdio>
#include <cstdlib>
#include <type_traits>
namespace strata::kernels {
namespace {
constexpr int HD = 256; // head_dim
constexpr int G = 12; // query heads per KV head
#ifndef D1_CH
#define D1_CH 32
#endif
constexpr int CH = D1_CH; // cells per chunk
constexpr int THREADS = 128; // 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group)
constexpr int QS = HD + 8; // q row stride in halves (bank-conflict-free fragment loads)
// The MMA and cp.async below need sm_80. Builds for older cards (the experimental sm_75 one) compile them to a trap;
// qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs there.
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800
#define STRATA_PA_SM80 1
#else
#define STRATA_PA_SM80 0
#endif
__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint32_t* b) {
#if !STRATA_PA_SM80
__trap();
#else
asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
"{%0,%1,%2,%3};\n"
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
#endif
}
// Two int8 codes (low byte first) as an exact half2: 1024 + (c + 128) built in the mantissa, minus 1152.
__device__ __forceinline__ uint32_t i8x2_to_h2(uint32_t x) {
uint32_t y = ((x & 0xffu) | ((x & 0xff00u) << 8)) ^ 0x00800080u;
y |= 0x64006400u;
__half2 h = *reinterpret_cast<__half2*>(&y);
h = __hsub2(h, __halves2half2(__float2half(1152.f), __float2half(1152.f)));
return *reinterpret_cast<uint32_t*>(&h);
}
__device__ __forceinline__ uint32_t pack_h2(float lo_k, float hi_k) { // element k in the low half
__half2 h = __floats2half2_rn(lo_k, hi_k);
return *reinterpret_cast<uint32_t*>(&h);
}
// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1).
template <int KV_MODE>
struct Smem {
using Elem = typename std::conditional<KV_MODE == 1, int8_t, __half>::type;
static constexpr int ROW = KV_MODE == 1 ? HD + 16 : HD + 8; // elements; 16-byte aligned rows, banks spread
__half qh[16][QS];
__half ql[16][QS];
Elem k[CH][ROW];
Elem v[CH][ROW];
float ks[CH][4];
float vs[CH][4];
float s[16][CH + 1];
float qmax[THREADS / 32];
float alpha[16];
float lsum[16];
float mrow[16];
long long row[CH];
};
template <int KV_MODE>
__global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ steps, int n_kv_heads,
int page_size, float scale_log2, float* __restrict__ attn,
int cap) {
extern __shared__ __align__(16) unsigned char smem_raw[];
Smem<KV_MODE>& S = *reinterpret_cast<Smem<KV_MODE>*>(smem_raw);
const int qi = blockIdx.x, kvh = blockIdx.y;
const int n_head = n_kv_heads * G;
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
ids += (size_t) qi * cap;
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int gid = lane >> 2, tig = lane & 3;
// q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the
// lo halves stay out of FP16's subnormal range), then split into hi + lo halves
float qm = 0.0f;
for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
#pragma unroll
for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
if (lane == 0) S.qmax[warp] = qm;
__syncthreads();
qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
int qe = 0;
if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe
const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
for (int i = t; i < 16 * HD; i += THREADS) {
const int h = i / HD, d = i % HD;
const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;
const __half hi = __float2half_rn(x);
S.qh[h][d] = hi;
S.ql[h][d] = __float2half_rn(x - __half2float(hi));
}
if (t < 16) { S.mrow[t] = -CUDART_INF_F; S.lsum[t] = 0.0f; }
float acc[8][4];
#pragma unroll
for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
for (int c0 = 0; c0 < n; c0 += CH) {
const int nh = min(CH, n - c0);
if (t < CH) {
long long r = -1;
if (t < nh) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
S.row[t] = r;
}
__syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s
// gather the chunk's K and V rows (16-byte pieces) and their scales
{
constexpr int PIECES = HD * (int) sizeof(typename Smem<KV_MODE>::Elem) / 16; // per row
for (int i = t; i < CH * PIECES; i += THREADS) {
const int c = i / PIECES, pc = i % PIECES;
const long long r = S.row[c];
uint4 kx = make_uint4(0, 0, 0, 0), vx = kx;
if (r >= 0) {
if constexpr (KV_MODE == 1) {
kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);
vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);
} else {
kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);
vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);
}
}
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[c][0]) + pc * 16) = kx;
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[c][0]) + pc * 16) = vx;
}
for (int i = t; i < CH * 4; i += THREADS) {
const int c = i / 4, g = i % 4;
const long long r = S.row[c];
float a = 0.0f, b = 0.0f;
if (r >= 0) {
if constexpr (KV_MODE == 1) {
a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));
} else {
a = b = 1.0f;
}
}
S.ks[c][g] = a;
S.vs[c][g] = b;
}
}
__syncthreads();
// scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per 64-dim scale group
#pragma unroll
for (int nt = 0; nt < CH / 32; ++nt) {
const int cb = (warp + 4 * nt) * 8;
float sc[4] = {0.f, 0.f, 0.f, 0.f};
#pragma unroll
for (int g = 0; g < 4; ++g) {
float tg[4] = {0.f, 0.f, 0.f, 0.f};
#pragma unroll
for (int kk = 0; kk < 4; ++kk) {
const int k0 = (g * 4 + kk) * 16;
uint32_t ah[4], al[4], b[2];
ah[0] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig]);
ah[1] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig]);
ah[2] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig + 8]);
ah[3] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig + 8]);
al[0] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig]);
al[1] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig]);
al[2] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig + 8]);
al[3] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig + 8]);
if constexpr (KV_MODE == 1) {
b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig]));
b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]));
} else {
b[0] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig]);
b[1] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]);
}
mma16816(tg, ah, b);
#ifndef D1_NO_QLO
mma16816(tg, al, b);
#endif
}
const float s0 = S.ks[cb + 2 * tig][g], s1 = S.ks[cb + 2 * tig + 1][g];
sc[0] = fmaf(tg[0], s0, sc[0]);
sc[1] = fmaf(tg[1], s1, sc[1]);
sc[2] = fmaf(tg[2], s0, sc[2]);
sc[3] = fmaf(tg[3], s1, sc[3]);
}
const int c = cb + 2 * tig;
S.s[gid][c] = c < nh ? sc[0] * qdown : -CUDART_INF_F;
S.s[gid][c + 1] = c + 1 < nh ? sc[1] * qdown : -CUDART_INF_F;
S.s[gid + 8][c] = c < nh ? sc[2] * qdown : -CUDART_INF_F;
S.s[gid + 8][c + 1] = c + 1 < nh ? sc[3] * qdown : -CUDART_INF_F;
}
__syncthreads();
// online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)
{
constexpr int PER = CH / 8;
const int r = t >> 3, sub = t & 7;
float x[PER], mx = -CUDART_INF_F;
#pragma unroll
for (int j = 0; j < PER; ++j) { x[j] = S.s[r][sub * PER + j]; mx = fmaxf(mx, x[j]); }
#pragma unroll
for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
const float m_old = S.mrow[r];
const float m_new = fmaxf(m_old, mx);
float sum = 0.0f;
#pragma unroll
for (int j = 0; j < PER; ++j) {
const float e = x[j] == -CUDART_INF_F ? 0.0f : exp2f(x[j] - m_new);
S.s[r][sub * PER + j] = e;
sum += e;
}
#pragma unroll
for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
__syncwarp();
if (sub == 0) {
const float a = m_old == -CUDART_INF_F ? 0.0f : exp2f(m_old - m_new);
S.alpha[r] = a;
S.lsum[r] = fmaf(S.lsum[r], a, sum);
S.mrow[r] = m_new;
}
}
__syncthreads();
// p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w. The scale is folded into p relative to
// the chunk's largest, times 2^14 (p' <= 2^14: its lo half stays out of FP16's subnormal range); the chunk's
// sum is then added to the running one in FP32 with the factor taken back out
{
float vmax = 0.0f;
#pragma unroll
for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]);
#pragma unroll
for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
float tmp[8][4];
#pragma unroll
for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
#pragma unroll
for (int ks = 0; ks < CH / 16; ++ks) {
const int cA = ks * 16 + 2 * tig, cB = cA + 8;
const float w0 = S.vs[cA][warp] * vup, w1 = S.vs[cA + 1][warp] * vup, w2 = S.vs[cB][warp] * vup,
w3 = S.vs[cB + 1][warp] * vup;
const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1;
const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1;
const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3;
const float p12 = S.s[gid + 8][cB] * w2, p13 = S.s[gid + 8][cB + 1] * w3;
uint32_t ah[4], al[4];
ah[0] = pack_h2(p00, p01);
ah[1] = pack_h2(p10, p11);
ah[2] = pack_h2(p02, p03);
ah[3] = pack_h2(p12, p13);
{
const __half2* h = reinterpret_cast<const __half2*>(ah);
float2 f;
f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y);
f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y);
f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y);
f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y);
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int d = warp * 64 + j * 8 + gid;
uint32_t b[2];
if constexpr (KV_MODE == 1) {
const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8);
const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8);
b[0] = i8x2_to_h2(x0);
b[1] = i8x2_to_h2(x1);
} else {
const __half2 h0 = __halves2half2(S.v[cA][d], S.v[cA + 1][d]);
const __half2 h1 = __halves2half2(S.v[cB][d], S.v[cB + 1][d]);
b[0] = *reinterpret_cast<const uint32_t*>(&h0);
b[1] = *reinterpret_cast<const uint32_t*>(&h1);
}
mma16816(tmp[j], ah, b);
#ifndef D1_NO_PLO
mma16816(tmp[j], al, b);
#endif
}
}
const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown);
acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown);
acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown);
acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown);
}
}
}
__syncthreads();
const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];
const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int d = warp * 64 + j * 8 + 2 * tig;
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
if (gid + 8 < G)
*reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);
}
}
// ---- v2 (int8 KV): warp w owns dims [64w, 64w+64) for both q.k and p.v, which is also int8 scale group w. So a
// warp needs only its own 64-byte slice of each K and V row: it gathers it itself with cp.async into its own
// double-buffered stage while it computes the previous chunk, and q stays in registers. Only the q.k partial sums
// (one per dim group) cross warps, and they are added in a fixed order: the result is deterministic.
constexpr int CH2 = 32;
struct Smem2 {
int8_t kv[2][4][2][CH2][64]; // stage, warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell
float sc[2][4][2][CH2]; // stage, warp, K/V scale of the cell for the warp's group
float part[4][16][CH2 + 1]; // q.k per dim group
float p[16][CH2 + 1];
float qmax[4];
float alpha[16];
float lsum[16];
float mrow[16];
};
__device__ __forceinline__ int swz(int cell, int byte) { // byte offset of (cell, byte) in a stage slice
return cell * 64 + ((((byte >> 4) ^ (cell >> 1)) & 3) << 4) + (byte & 15);
}
__device__ __forceinline__ void cp_async16(void* smem, const void* gmem, bool valid) {
#if !STRATA_PA_SM80
__trap();
#else
const unsigned sa = (unsigned) __cvta_generic_to_shared(smem);
asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(sa), "l"(gmem), "r"(valid ? 16 : 0));
#endif
}
__device__ __forceinline__ void cp_async_commit() {
#if STRATA_PA_SM80
asm volatile("cp.async.commit_group;\n" ::);
#endif
}
__device__ __forceinline__ void cp_async_wait1() {
#if STRATA_PA_SM80
asm volatile("cp.async.wait_group 1;\n" ::);
#endif
}
__global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ steps, int n_kv_heads,
int page_size, float scale_log2,
float* __restrict__ attn, int cap) {
extern __shared__ __align__(16) unsigned char smem_raw[];
Smem2& S = *reinterpret_cast<Smem2*>(smem_raw);
const int qi = blockIdx.x, kvh = blockIdx.y;
const int n_head = n_kv_heads * G;
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
ids += (size_t) qi * cap;
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int gid = lane >> 2, tig = lane & 3;
const int dim0 = warp * 64;
// q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments
float qm = 0.0f;
for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
#pragma unroll
for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
if (lane == 0) S.qmax[warp] = qm;
if (t < 16) { S.mrow[t] = -CUDART_INF_F; S.lsum[t] = 0.0f; }
__syncthreads();
qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
int qe = 0;
if (qm > 0.0f) frexpf(qm, &qe);
const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
uint32_t qh[4][4], ql[4][4];
#pragma unroll
for (int kk = 0; kk < 4; ++kk) {
#pragma unroll
for (int r = 0; r < 4; ++r) {
const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8;
float2 x = make_float2(0.f, 0.f);
if (row < G) x = *reinterpret_cast<const float2*>(q + (size_t) row * HD + col);
x.x *= qup;
x.y *= qup;
const __half2 hi = __floats2half2_rn(x.x, x.y);
const float2 hf = __half22float2(hi);
const __half2 lo = __floats2half2_rn(x.x - hf.x, x.y - hf.y);
qh[kk][r] = *reinterpret_cast<const uint32_t*>(&hi);
ql[kk][r] = *reinterpret_cast<const uint32_t*>(&lo);
}
}
// the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead
const int n_chunks = (n + CH2 - 1) / CH2;
auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; };
auto row_of = [&](int cell) -> long long {
if (cell < 0) return -1;
const long long page = (long long) __ldg(p.page_table + cell / page_size);
return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
};
auto issue = [&](long long r, int st, float& ksr, float& vsr) {
#pragma unroll
for (int j = 0; j < 4; ++j) {
const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;
const long long rr = __shfl_sync(0xffffffffu, r, cell);
const bool ok = rr >= 0;
const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0;
cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok);
cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok);
}
ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
};
float ksn, vsn;
issue(row_of(cell_of(lane)), 0, ksn, vsn);
cp_async_commit();
S.sc[0][warp][0][lane] = ksn;
S.sc[0][warp][1][lane] = vsn;
long long r_next = row_of(cell_of(CH2 + lane));
int cell_next2 = cell_of(2 * CH2 + lane);
float acc[8][4];
#pragma unroll
for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
for (int ci = 0; ci < n_chunks; ++ci) {
const int st = ci & 1, c0 = ci * CH2;
const bool more = ci + 1 < n_chunks;
if (more) issue(r_next, st ^ 1, ksn, vsn);
cp_async_commit();
r_next = row_of(cell_next2);
cell_next2 = cell_of((ci + 3) * CH2 + lane);
cp_async_wait1();
__syncwarp();
const int8_t* K = &S.kv[st][warp][0][0][0];
const int8_t* V = &S.kv[st][warp][1][0][0];
// q.k over this warp's 64 dims, times the cell's K scale for this group
#pragma unroll
for (int nt = 0; nt < CH2 / 8; ++nt) {
float tg[4] = {0.f, 0.f, 0.f, 0.f};
const int cell = nt * 8 + gid;
#pragma unroll
for (int kk = 0; kk < 4; ++kk) {
uint32_t b[2];
b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig)));
b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig + 8)));
mma16816(tg, qh[kk], b);
mma16816(tg, ql[kk], b);
}
const int c = nt * 8 + 2 * tig;
const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1];
S.part[warp][gid][c] = tg[0] * s0;
S.part[warp][gid][c + 1] = tg[1] * s1;
S.part[warp][gid + 8][c] = tg[2] * s0;
S.part[warp][gid + 8][c + 1] = tg[3] * s1;
}
__syncthreads();
// online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
{
const int r = t >> 3, sub = t & 7;
float x[4], mx = -CUDART_INF_F;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const int c = sub * 4 + j;
x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown
: -CUDART_INF_F;
mx = fmaxf(mx, x[j]);
}
#pragma unroll
for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
const float m_old = S.mrow[r];
const float m_new = fmaxf(m_old, mx);
float sum = 0.0f;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float e = x[j] == -CUDART_INF_F ? 0.0f : exp2f(x[j] - m_new);
S.p[r][sub * 4 + j] = e;
sum += e;
}
#pragma unroll
for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
__syncwarp();
if (sub == 0) {
const float a = m_old == -CUDART_INF_F ? 0.0f : exp2f(m_old - m_new);
S.alpha[r] = a;
S.lsum[r] = fmaf(S.lsum[r], a, sum);
S.mrow[r] = m_new;
}
}
__syncthreads();
// p.v over this warp's 64 dims (as v1)
{
float vmax = S.sc[st][warp][1][lane];
#pragma unroll
for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
float tmp[8][4];
#pragma unroll
for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
#pragma unroll
for (int ks = 0; ks < CH2 / 16; ++ks) {
const int cA = ks * 16 + 2 * tig, cB = cA + 8;
const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup,
w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup;
const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1;
const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1;
const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3;
const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3;
uint32_t ah[4], al[4];
ah[0] = pack_h2(p00, p01);
ah[1] = pack_h2(p10, p11);
ah[2] = pack_h2(p02, p03);
ah[3] = pack_h2(p12, p13);
{
const __half2* h = reinterpret_cast<const __half2*>(ah);
float2 f;
f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y);
f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y);
f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y);
f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y);
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int d = j * 8 + gid;
const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8);
const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8);
uint32_t b[2];
b[0] = i8x2_to_h2(x0);
b[1] = i8x2_to_h2(x1);
mma16816(tmp[j], ah, b);
mma16816(tmp[j], al, b);
}
}
const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown);
acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown);
acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown);
acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown);
}
}
if (more) {
S.sc[st ^ 1][warp][0][lane] = ksn;
S.sc[st ^ 1][warp][1][lane] = vsn;
}
__syncwarp();
}
__syncthreads();
const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];
const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int d = dim0 + j * 8 + 2 * tig;
*reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
if (gid + 8 < G)
*reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);
}
}
bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
static bool attr = false;
const int bytes = (int) sizeof(Smem2);
if (!attr) {
if (cudaFuncSetAttribute(prompt_attn_i8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
cudaSuccess) {
cudaGetLastError();
return false;
}
attr = true;
}
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
prompt_attn_i8_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
return true;
}
template <int KV_MODE>
bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
static bool attr = false;
const int bytes = (int) sizeof(Smem<KV_MODE>);
if (!attr) {
if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
cudaSuccess) {
cudaGetLastError();
return false;
}
attr = true;
}
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
prompt_attn_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
return true;
}
} // namespace
bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {
if (n_q <= 0) return true;
{ // sm_80 or newer (the MMA and cp.async above); an older card keeps the old kernel
static int cc_major[64] = {};
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
if (cc_major[dev] == 0) {
int major = 0;
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) {
cudaGetLastError();
return false;
}
cc_major[dev] = major;
}
if (cc_major[dev] < 8) return false;
}
if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids ||
!steps || !pools.page_table)
return false;
cudaStream_t st = (cudaStream_t) stream;
if (pools.k_q != nullptr) {
if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false;
// STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control
// for how far the model amplifies an FP32-level change
static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
if (v1) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (!pools.k_pool || !pools.v_pool) return false;
return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
} // namespace strata::kernels
+4 -2
View File
@@ -151,13 +151,15 @@ __global__ void __launch_bounds__(TOPK_T) block_topk_kernel(const float* __restr
} // namespace
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 max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
if (nq <= 0) return;
if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535) {
std::fprintf(stderr, "qsa_block_scores: unsupported indexer geometry\n");
std::exit(1);
}
const dim3 grid((unsigned) ((max_blocks + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
// a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)
const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
block_scores_kernel<<<grid, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, max_blocks,
scores);
const cudaError_t e = cudaGetLastError();
+6 -3
View File
@@ -43,10 +43,13 @@ constexpr int MAX_SHARED_HALVES = 4096; // 8 KB of shared for x; n_embd 256
// byte -> the four code values with the -1 bias already applied, in element order (bits 0,2,4,6).
__constant__ float c_codes[256][4];
bool g_lut_ready = false;
bool g_lut_ready[64] = {}; // per device: __constant__ memory is per device (a layer split runs on two)
void ensure_lut() {
if (g_lut_ready) return;
int dev = 0;
cudaGetDevice(&dev);
if (dev < 0 || dev >= 64) dev = 0;
if (g_lut_ready[dev]) return;
float host[256][4];
for (int b = 0; b < 256; ++b) {
for (int k = 0; k < 4; ++k) {
@@ -58,7 +61,7 @@ void ensure_lut() {
std::fprintf(stderr, "s2_gemv_fast: cudaMemcpyToSymbol failed: %s\n", cudaGetErrorString(e));
std::exit(1);
}
g_lut_ready = true;
g_lut_ready[dev] = true;
}
// One block per output row. `staged` says whether x was copied to shared, so the SAME kernel covers both
+87
View File
@@ -428,6 +428,93 @@ __global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t valu
}
} // namespace
namespace {
__global__ void resident_plan_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res,
int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off,
long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip,
uint32_t ring) {
// one thread: at most kVerifyMaxT * 10 entries, the host's exact loop
for (int i = 0; i < n; ++i) {
const int32_t e = ids[i];
if (e < 0 || e >= n_expert || res[e] < 0) { *skip = 0; return; }
}
int32_t* counts = pl;
int32_t* start = pl + 4;
int32_t* dst = start + capx + 1;
int32_t* tok = dst + capx;
const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;
unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);
int32_t* start2 = pl + ptr_off + 4 * capx;
int groups = 0, entries = 0;
for (int i0 = 0; i0 < n; ++i0) {
bool first = true;
for (int j = 0; j < i0; ++j) if (ids[j] == ids[i0]) { first = false; break; }
if (!first) continue;
const int32_t slot = res[ids[i0]];
ptr[groups] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));
start[groups] = entries;
for (int i = i0; i < n; ++i)
if (ids[i] == ids[i0]) {
// an entry belongs to i0's group when its first occurrence is i0: the same expert id
dst[entries] = i;
tok[entries] = i / k;
++entries;
}
++groups;
}
start[groups] = entries;
start2[0] = entries;
counts[0] = groups;
counts[1] = entries;
counts[2] = 0;
__threadfence();
*skip = ring;
}
__global__ void wait_flag_ge_or_kernel(const volatile uint32_t* flag, uint32_t value, const volatile uint32_t* skip) {
if (*skip == value) return;
while (*flag < value) __nanosleep(100);
__threadfence_system();
}
__global__ void copy_i32_unless_kernel(int32_t* __restrict__ dst, const volatile int32_t* src, int n,
const uint32_t* skip, uint32_t value) {
if (*skip == value) return;
for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i];
}
__global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile float4* src, long long n4,
const uint32_t* skip, uint32_t value) {
const bool zero = *skip == value;
for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (long long) gridDim.x * blockDim.x)
dst[i] = zero ? make_float4(0.f, 0.f, 0.f, 0.f) : const_cast<const float4*>(src)[i];
}
} // namespace
void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert,
const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,
long long capx, uint32_t* skip, uint32_t ring, void* stream) {
resident_plan_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off,
blob, plan, capx, skip, ring);
check("resident_plan");
}
void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) {
wait_flag_ge_or_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, skip);
check("wait_flag_ge_or");
}
void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value,
void* stream) {
if (n <= 0) return;
copy_i32_unless_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(dst, (const volatile int32_t*) src, (int) n, skip, value);
check("copy_i32_from_mapped_unless");
}
void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value,
void* stream) {
if (n <= 0) return;
const long long n4 = n / 4;
const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64);
copy_or_zero_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>((float4*) dst, (const volatile float4*) src, n4, skip,
value);
check("copy_or_zero_from_mapped");
}
void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream) {
wait_flag_ge_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value);
check("wait_flag_ge");
+16 -5
View File
@@ -132,8 +132,14 @@ int main(int argc, char** argv) {
float* gp[NT];
for (int k = 0; k < NT; ++k) gp[k] = g.data() + k * FF;
(is512 ? cpu::iq512_rows : cpu::iq256_rows)(f.gu_type, blob.data(), f.gu_row, (int) H, a, NT, gp, 0, (int) FF);
const double rg = rel(g, gref);
std::printf(" %s %s gate rows vs ggml vec_dot: rel %.2e\n",
ggml_type_name((ggml_type) f.gu_type), tag, rel(g, gref));
ggml_type_name((ggml_type) f.gu_type), tag, rg);
if (rg > 1e-5) { // ggml's own vec_dot is the reference: above 1e-5 it is a real mismatch,
std::printf(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n",
ggml_type_name((ggml_type) f.gu_type), tag, rg); // not rounding (measured 3e-8)
++failures;
}
float* f1[1] = {ffp[0]};
const int it = 50;
const auto gu = is512 ? cpu::iq512_gu_rows : cpu::iq256_gu_rows;
@@ -177,16 +183,21 @@ int main(int argc, char** argv) {
if (f.d_type == 20) {
// (b3) the IQ4_NL multi-token AVX-2 kernel the pool now uses for IQ4_NL down projections,
// against ggml-cpu's single-token vec_dot on the SAME Q8_0 activations (h), plus timing.
std::vector<float> alt((size_t) NT * H), ref((size_t) NT * H);
std::vector<float> alt((size_t) NT * H), refd((size_t) NT * H);
float* altp[NT];
for (int k = 0; k < NT; ++k) altp[k] = alt.data() + k * H;
cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H);
const auto* tdc = ggml_get_type_traits_cpu((ggml_type) f.d_type);
for (int k = 0; k < NT; ++k)
for (int64_t r = 0; r < H; ++r)
tdc->vec_dot((int) FF, ref.data() + k * H + r, 0,
tdc->vec_dot((int) FF, refd.data() + k * H + r, 0,
blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1);
std::printf(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rel(alt, ref));
const double rdn = rel(alt, refd);
std::printf(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn);
if (rdn > 1e-5) { // measured 1e-7; same reasoning as the gate/up rows above
std::printf(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn);
++failures;
}
const int it = 50;
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < it; ++i)
@@ -195,7 +206,7 @@ int main(int argc, char** argv) {
for (int i = 0; i < it; ++i)
for (int k = 0; k < NT; ++k)
for (int64_t r = 0; r < H; ++r)
tdc->vec_dot((int) FF, ref.data() + k * H + r, 0,
tdc->vec_dot((int) FF, refd.data() + k * H + r, 0,
blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1);
const auto t2 = std::chrono::steady_clock::now();
const double usn = std::chrono::duration<double, std::micro>(t1 - t0).count() / it;
+209
View File
@@ -0,0 +1,209 @@
// src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp)
// against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model).
//
// Int8 and FP16 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051
// widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most
// of them as they do in a real prompt; short contexts take every cell). Checks:
// 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math);
// 2. the new and old outputs agree to a relative 1e-4 of the output scale;
// then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it).
// Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5]
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/qsa_prompt_attn.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <vector>
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 <typename T> T* up(const std::vector<T>& 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;
}
float h2f(uint16_t b) { __half h; *reinterpret_cast<uint16_t*>(&h) = b; return __half2float(h); }
uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
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 pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
std::mt19937 rng(1234 + fmt);
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_int_distribution<int> code(-127, 127);
std::uniform_real_distribution<float> sc(0.005f, 0.03f);
// pools; page table a shuffled permutation (the readers must follow it)
std::vector<int8_t> kq, vq;
std::vector<uint16_t> ks, vs, kh, vh;
if (fmt == 1) {
kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4);
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));
} else {
kh.resize(rows * HD); vh.resize(rows * HD);
for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
for (auto& x : vh) x = f2h(nd(rng));
}
std::vector<int32_t> table(pages);
for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
std::shuffle(table.begin(), table.end(), rng);
// queries at positions ctx - nq .. ctx - 1
const int64_t cap = k::qsa_selection_width(ctx, s);
std::vector<int32_t> ids((size_t) (nq * cap), 0), steps((size_t) (nq * k::kStepCount), 0);
std::vector<float> q((size_t) (nq * NH * HD));
for (auto& x : q) x = nd(rng) * 2.0f;
std::vector<int32_t> old_cells;
for (int64_t i = 0; i < nq; ++i) {
const int64_t pos = ctx - nq + i, nkv = pos + 1;
const int64_t w = k::qsa_selection_width(nkv, s);
int32_t* sel = ids.data() + i * cap;
steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w;
if (w == nkv) {
for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c;
continue;
}
const int64_t recent = 512, older = w - recent;
if ((int64_t) old_cells.size() != older) { // the older cells: a set that drifts ~3% per query
std::vector<int32_t> all((size_t) (nkv - recent));
for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c;
std::shuffle(all.begin(), all.end(), rng);
old_cells.assign(all.begin(), all.begin() + older);
} else {
std::uniform_int_distribution<int64_t> pick(0, older - 1), any(0, nkv - recent - 1);
for (int r = 0; r < older / 32; ++r) {
const int32_t c = (int32_t) any(rng);
if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c;
}
}
std::vector<int32_t> v(old_cells);
for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c);
std::sort(v.begin(), v.end());
std::copy(v.begin(), v.end(), sel);
}
k::QsaAttnPools pl;
if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }
else { pl.k_pool = up(kh); pl.v_pool = up(vh); }
pl.page_table = up(table);
const int32_t* d_ids = up(ids);
const int32_t* d_steps = up(steps);
const float* d_q = up(q);
float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr;
const int64_t batch = 32;
ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc");
ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc");
ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc");
auto old_run = [&]() {
for (int64_t t0 = 0; t0 < nq; t0 += batch)
k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s,
scratch, d_old + t0 * NH * HD, std::min(batch, nq - t0), nullptr);
};
auto new_run = [&]() {
if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nq, nullptr)) {
std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n");
std::exit(2);
}
};
old_run();
new_run();
ck(cudaDeviceSynchronize(), "run");
std::vector<float> o((size_t) (nq * NH * HD)), nw(o.size());
ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down");
ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down");
// 1. FP64 reference on a sample of queries
double err_old = 0, err_new = 0, ref_scale = 0;
for (int64_t i = 0; i < nq; i += std::max<int64_t>(1, nq / 16)) {
const int64_t w = steps[i * k::kStepCount + k::kStepWidth];
const int32_t* sel = ids.data() + i * cap;
for (int64_t h = 0; h < NH; ++h) {
const int64_t kvh = h / (NH / NKV);
std::vector<double> sco((size_t) w);
double mx = -1e300;
for (int64_t c = 0; c < w; ++c) {
const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
double a = 0;
for (int64_t d = 0; d < HD; ++d) {
const double kv = fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]);
a += (double) q[(i * NH + h) * HD + d] * kv;
}
sco[c] = a / 16.0;
mx = std::max(mx, sco[c]);
}
double l = 0;
for (auto& x : sco) { x = std::exp(x - mx); l += x; }
for (int64_t d = 0; d < HD; ++d) {
double a = 0;
for (int64_t c = 0; c < w; ++c) {
const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS;
const double vv = fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]);
a += sco[c] * vv;
}
const double r = a / l;
const size_t at = (size_t) ((i * NH + h) * HD + d);
ref_scale = std::max(ref_scale, std::fabs(r));
err_old = std::max(err_old, std::fabs(o[at] - r));
err_new = std::max(err_new, std::fabs(nw[at] - r));
}
}
}
// 2. new vs old everywhere
double diff = 0, scale = 0;
for (size_t i = 0; i < o.size(); ++i) {
diff = std::max(diff, (double) std::fabs(o[i] - nw[i]));
scale = std::max(scale, (double) std::fabs(o[i]));
}
// 3. speed
cudaEvent_t e0, e1;
cudaEventCreate(&e0);
cudaEventCreate(&e1);
float ms_old = 0, ms_new = 0;
cudaEventRecord(e0);
for (int r = 0; r < reps; ++r) old_run();
cudaEventRecord(e1);
ck(cudaEventSynchronize(e1), "time");
cudaEventElapsedTime(&ms_old, e0, e1);
cudaEventRecord(e0);
for (int r = 0; r < reps; ++r) new_run();
cudaEventRecord(e1);
ck(cudaEventSynchronize(e1), "time");
cudaEventElapsedTime(&ms_new, e0, e1);
const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale);
const bool ok2 = diff <= 1e-4 * scale;
std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of "
"scale); %.3f -> %.3f ms per chunk (%.2fx)\n",
ok1 && ok2 ? "PASS" : "FAIL", fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old,
err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new);
cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new);
cudaFree(scratch);
cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale);
cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table);
return ok1 && ok2 ? 0 : 1;
}
} // namespace
int main(int argc, char** argv) {
const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768;
const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048;
const int reps = argc > 3 ? std::atoi(argv[3]) : 5;
int fails = 0;
fails += run(1, ctx, nq, reps);
fails += run(0, ctx, nq, reps);
fails += run(1, 1500, std::min<int64_t>(nq, 1500), reps); // short context: the selection is every cell
fails += run(1, 2100, std::min<int64_t>(nq, 256), reps); // the identity-to-sparse edge
std::printf("FAILURES: %d\n", fails);
return fails;
}
+154 -30
View File
@@ -1,10 +1,14 @@
// src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp.
#include "strata/platform/direct_file.hpp"
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#if defined(_WIN32)
@@ -42,6 +46,26 @@ void DirectFile::free_aligned(void* p) {
#endif
}
namespace {
/// A queued read: `submit` only queues it; the pool's threads issue it (perf-review C-4 / F-2). One thread
/// issuing every read was the limit of the n-gram table's prompt reads: ~12 us of kernel time per read, ~80K
/// reads/s, while an NVMe drive serves several times that at depth.
struct Pending {
uint64_t offset;
void* buffer;
uint32_t length;
uint64_t tag;
};
/// The number of issuing threads: STRATA_IO_THREADS, else 4 (Windows: overlapped submits) / 16 (Linux: each
/// thread does one blocking pread, so the thread count is the queue depth).
int io_threads(int dflt) {
const char* v = std::getenv("STRATA_IO_THREADS");
const int n = v ? std::atoi(v) : dflt;
return std::clamp(n, 1, 64);
}
} // namespace
#if defined(_WIN32)
// ------------------------------------------------------------------------------------------------ Windows
namespace {
@@ -57,9 +81,14 @@ struct DirectFile::Impl {
HANDLE file = INVALID_HANDLE_VALUE;
HANDLE port = nullptr;
uint64_t size = 0;
std::mutex mu; // everything below
std::deque<Req*> free_reqs;
std::vector<Req*> all_reqs;
std::deque<Completion> immediate; // requests that failed after being counted as queued
std::deque<Completion> immediate; // requests that completed without a port packet (EOF) or failed
std::deque<Pending> queue; // submitted, not yet issued
std::condition_variable cv;
bool stop = false;
std::vector<std::thread> pool;
Req* take() {
if (free_reqs.empty()) {
@@ -71,6 +100,52 @@ struct DirectFile::Impl {
free_reqs.pop_front();
return r;
}
void issue(const Pending& p) {
Req* r;
{
std::lock_guard<std::mutex> lk(mu);
r = take();
}
std::memset(&r->ov, 0, sizeof r->ov);
r->ov.Offset = (DWORD) (p.offset & 0xFFFFFFFFull);
r->ov.OffsetHigh = (DWORD) (p.offset >> 32);
r->tag = p.tag;
if (!ReadFile(file, p.buffer, p.length, nullptr, &r->ov)) {
const DWORD e = GetLastError();
if (e != ERROR_IO_PENDING) {
std::lock_guard<std::mutex> lk(mu);
free_reqs.push_back(r);
// at or past end of file: a zero-byte completion; anything else: a failed one
immediate.push_back(Completion{p.tag, 0, e == ERROR_HANDLE_EOF});
PostQueuedCompletionStatus(port, 0, 0, nullptr); // wake a waiter to collect it
}
}
}
void worker() {
std::unique_lock<std::mutex> lk(mu);
for (;;) {
cv.wait(lk, [&] { return stop || !queue.empty(); });
if (stop && queue.empty()) return;
const Pending p = queue.front();
queue.pop_front();
lk.unlock();
issue(p);
lk.lock();
}
}
void stop_pool() {
{
std::lock_guard<std::mutex> lk(mu);
stop = true;
}
cv.notify_all();
for (std::thread& t : pool) t.join();
pool.clear();
stop = false;
}
};
DirectFile::DirectFile() : impl_(new Impl) {}
@@ -106,18 +181,22 @@ bool DirectFile::open(const std::string& path, std::string& err) {
close();
return false;
}
// Completions of reads that finish synchronously must still be queued to the port, so every submit
// produces exactly one packet and `wait` is the only completion path.
// Completions of reads that finish synchronously are still queued to the port, so every issued read
// produces exactly one packet; `wait` is the only completion path.
const int n = io_threads(4);
for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); });
return true;
}
void DirectFile::close() {
impl_->stop_pool();
if (impl_->port != nullptr) CloseHandle(impl_->port);
if (impl_->file != INVALID_HANDLE_VALUE) CloseHandle(impl_->file);
impl_->port = nullptr;
impl_->file = INVALID_HANDLE_VALUE;
impl_->size = 0;
impl_->immediate.clear();
impl_->queue.clear();
}
bool DirectFile::is_open() const { return impl_->file != INVALID_HANDLE_VALUE; }
@@ -129,31 +208,22 @@ bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t
err = "DirectFile: unaligned request";
return false;
}
Req* r = impl_->take();
std::memset(&r->ov, 0, sizeof r->ov);
r->ov.Offset = (DWORD) (offset & 0xFFFFFFFFull);
r->ov.OffsetHigh = (DWORD) (offset >> 32);
r->tag = tag;
if (!ReadFile(impl_->file, buffer, length, nullptr, &r->ov)) {
const DWORD e = GetLastError();
if (e != ERROR_IO_PENDING) {
impl_->free_reqs.push_back(r);
if (e == ERROR_HANDLE_EOF) { // at or past end of file: a zero-byte completion
impl_->immediate.push_back(Completion{tag, 0, true});
return true;
}
err = "DirectFile: ReadFile failed (error " + std::to_string(e) + ")";
return false;
}
{
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->queue.push_back(Pending{offset, buffer, length, tag});
}
impl_->cv.notify_one();
return true;
}
int DirectFile::wait(Completion* out, int max, int timeout_ms) {
int n = 0;
while (n < max && !impl_->immediate.empty()) {
out[n++] = impl_->immediate.front();
impl_->immediate.pop_front();
{
std::lock_guard<std::mutex> lk(impl_->mu);
while (n < max && !impl_->immediate.empty()) {
out[n++] = impl_->immediate.front();
impl_->immediate.pop_front();
}
}
if (n == max || !is_open()) return n;
OVERLAPPED_ENTRY entries[64];
@@ -161,9 +231,14 @@ int DirectFile::wait(Completion* out, int max, int timeout_ms) {
ULONG got = 0;
const DWORD t = timeout_ms < 0 ? INFINITE : (DWORD) timeout_ms;
if (!GetQueuedCompletionStatusEx(impl_->port, entries, want, &got, n > 0 ? 0 : t, FALSE)) return n;
std::lock_guard<std::mutex> lk(impl_->mu);
for (ULONG i = 0; i < got; ++i) {
if (entries[i].lpOverlapped == nullptr) { // a wake() packet, not a read
out[n++] = Completion{WAKE_TAG, 0, true};
if (entries[i].lpOverlapped == nullptr) { // a wake() packet (or an immediate completion's nudge)
while (n < max && !impl_->immediate.empty()) {
out[n++] = impl_->immediate.front();
impl_->immediate.pop_front();
}
if (n < max) out[n++] = Completion{WAKE_TAG, 0, true};
continue;
}
Req* r = (Req*) entries[i].lpOverlapped;
@@ -185,12 +260,44 @@ void DirectFile::wake() {
#else
// ------------------------------------------------------------------------------------------------ POSIX
// Phase L replaces this with io_uring. Until then a read completes inside `submit`, which is correct and
// keeps the tree compiling on Linux (plan v0.3 section 5.1 rule 4).
// perf-review F-2: a pool of threads, each doing blocking O_DIRECT preads, so reads run in parallel (the thread
// count is the queue depth). It replaced one synchronous pread inside `submit`, which read the n-gram table's
// rows one at a time.
struct DirectFile::Impl {
int fd = -1;
uint64_t size = 0;
std::mutex mu;
std::condition_variable cv_work, cv_done;
std::deque<Pending> queue;
std::deque<Completion> done;
bool stop = false;
std::vector<std::thread> pool;
void worker() {
std::unique_lock<std::mutex> lk(mu);
for (;;) {
cv_work.wait(lk, [&] { return stop || !queue.empty(); });
if (stop && queue.empty()) return;
const Pending p = queue.front();
queue.pop_front();
lk.unlock();
const ssize_t got = pread(fd, p.buffer, p.length, (off_t) p.offset);
lk.lock();
done.push_back(Completion{p.tag, got < 0 ? 0u : (uint32_t) got, got >= 0});
cv_done.notify_all();
}
}
void stop_pool() {
{
std::lock_guard<std::mutex> lk(mu);
stop = true;
}
cv_work.notify_all();
for (std::thread& t : pool) t.join();
pool.clear();
stop = false;
}
};
DirectFile::DirectFile() : impl_(new Impl) {}
@@ -203,14 +310,18 @@ bool DirectFile::open(const std::string& path, std::string& err) {
struct stat st;
if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; }
impl_->size = (uint64_t) st.st_size;
const int n = io_threads(16);
for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); });
return true;
}
void DirectFile::close() {
impl_->stop_pool();
if (impl_->fd >= 0) ::close(impl_->fd);
impl_->fd = -1;
impl_->size = 0;
impl_->done.clear();
impl_->queue.clear();
}
bool DirectFile::is_open() const { return impl_->fd >= 0; }
@@ -221,14 +332,27 @@ bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t
err = "DirectFile: unaligned request";
return false;
}
const ssize_t got = pread(impl_->fd, buffer, length, (off_t) offset);
impl_->done.push_back(Completion{tag, got < 0 ? 0u : (uint32_t) got, got >= 0});
{
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->queue.push_back(Pending{offset, buffer, length, tag});
}
impl_->cv_work.notify_one();
return true;
}
void DirectFile::wake() {} // reads complete inside submit; nothing ever blocks in wait
void DirectFile::wake() {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->done.push_back(Completion{WAKE_TAG, 0, true});
impl_->cv_done.notify_all();
}
int DirectFile::wait(Completion* out, int max, int) {
int DirectFile::wait(Completion* out, int max, int timeout_ms) {
std::unique_lock<std::mutex> lk(impl_->mu);
if (impl_->done.empty() && timeout_ms != 0) {
auto ready = [&] { return !impl_->done.empty(); };
if (timeout_ms < 0) impl_->cv_done.wait(lk, ready);
else impl_->cv_done.wait_for(lk, std::chrono::milliseconds(timeout_ms), ready);
}
int n = 0;
while (n < max && !impl_->done.empty()) {
out[n++] = impl_->done.front();
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more