Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
prefill: --prefill-pipe, chunks sized for a layer split's pipeline (#1441, opt-in; b/a from setup's --calibrate)
Niko1221125025a770c4
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 5bd5fbbbd..9c1eed695 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -486,7 +486,7 @@ START-HERE.bat --calibrate tune the engine for this PC (aboWith more than one model installed, it asks which one to start. `run-<model>.bat` starts a model directly.-**Tuning for your PC (`--calibrate`, engine 0.1.19).** Four engine settings depend on the PC more than on the model:+**Tuning for your PC (`--calibrate`, engine 0.1.19).** These engine settings depend on the PC more than on the model:- the share of the experts missing from VRAM that are copied to the GPU instead of computed by the CPU(`--pcie-frac`: a fast PCIe link and a slower CPU want more, a laptop's narrower link less);- how sure the draft layer must be to add another guess to a check (`--spec-min-p`);@@ -494,7 +494,9 @@ With more than one model installed, it asks which one to start. `run-<model>.bat- how busily the VRAM expert cache follows the conversation (`--adapt-every`, `--adapt-swaps`, `--adapt-decay`): a PCwhose CPU reads the missed experts slowly (DDR3 or DDR4 in few channels) gains from swapping more. On a XeonE5-2673 v3 with DDR3 and an RTX 4060 Ti on PCIe 3.0 x8, 160 swaps every window measured +7.9% over the default- (Q2_0, with the swaps taking effect a window later, #764); see #906.+ (Q2_0, with the swaps taking effect a window later, #764); see #906;+- on two or more cards (a layer split), the prompt chunks that keep the cards reading at once (`--prefill-pipe`, the+ prompt read speed of fresh prompts rather than the output speed; see docs/MULTI_GPU.md).The defaults were measured on a Ryzen 5 7600 with an RTX 5070. Setup offers to measure them on your PC after aninstall; `START-HERE.bat --calibrate` (Linux: `./setup.sh --calibrate`) does it any time. It measures the outputdiff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.mdindex 62a8a177a..40c7178cf 100644--- a/docs/MULTI_GPU.md+++ b/docs/MULTI_GPU.md@@ -199,6 +199,76 @@ that overlap instead of one, a 32K one four instead of two. Same tokens; 2x / 3x32K +18% / +21% / +29%, 64K +4% / +12% / +17%, 8K unchanged. `STRATA_SPLIT_CHUNK16K=1` keeps 16384.) Conversation checkpoints save and restore every card's state; the adaptive expert swaps copyinto the card that owns the layer.+## Prompt chunks sized for the pipeline (`--prefill-pipe`, opt-in; setup's `--calibrate` sets it)++`--prefill auto` takes the largest chunk the buffers allow (up to 8192), which is what one card wants: a chunk costs a+fixed pass over its layers' experts (b: dequantized, or streamed over PCIe where they are not in VRAM) plus a part per+token (a), so few large chunks are cheapest. A layer split reads a prompt as a pipeline - stage s reads chunk c while+stage s+1 reads chunk c-1 - and then takes about sum_i (b + a C_i) + (S - 1) max_i (b + a C_i) for chunks C_i over S+stages: large or uneven chunks keep the later cards waiting (a 10.7K-token prompt in a 7680 and a 3011 chunk over+four stages: the first stage carried 24 of the 36 s), small ones pay b again and again.++`--prefill-pipe R` reads each prompt in the chunk count with the least pipeline time for b/a = R tokens, when that+beats today's split by 3% or more: every count from the fewest the buffers allow is tried, each chunk evened out on the+256-token grid (at least 512, at most the buffers' chunk; keep `--prefill auto` so long prompts may use large chunks).+b/a differs by an order of magnitude between rigs - about 700 tokens on four GP100 dies (every expert in VRAM, slow+arithmetic), about 5000 on two RTX 3090 Ti (part of the experts streamed per chunk, fast arithmetic) - and a wrong one+costs: a fixed 1024 read 19-24% slower on the two RTX 3090 Ti and 22-36% slower on two RTX 4090 (reported in the PR by+MistyMoonR). So it is neither guessed nor learned from the prompts the engine serves (that made a prompt's chunks, and+so its output bits, depend on how busy the PC happened to be): like the PCIe share and the draft floor, it is a+setting of the PC that setup's `--calibrate` measures once (`tools/calibrate.py`: on a layer split, the prompt read+speed of a 2K- and an 8K-token prompt - the same text every time, after a header of its own so nothing is reused -+with the chunks off, evened out and b/a 768, 1536, 3072 and 6144; the best is kept only when it reads faster than off+in each of three paired rounds and by more than 3% in the median) and writes into the config. Measured so: four GP100+dies keep b/a 768 (355-356 against 219-220 tok/s in every round, +62%); two RTX 3090 Ti keep it off (nothing read+faster than off, b/a 768 20% slower). A first version that read a different stretch of text per value and confirmed in+two rounds picked 1536 on the RTX 3090 Ti pair from one fast read - where the experts are streamed, the read speed+depends on the text. `--prefill-pipe 1` needs no+b/a: it is `STRATA_PREFILL_EQUAL=1`'s rule (#693) - today's chunk count, evened out on the 256-token grid, and only+when today's last chunk has 1024 tokens or more (3072 with `STRATA_PREFILL_CPU_SHARE` set). A chunk that size streams+every expert its card does not hold, a shorter one only the experts it routes to, so a prompt just past the chunk size+reads as one full chunk and a nearly free tail, and evening that out would add a second full pass over the experts:+the first version evened every split out, and on two RTX 4090 MistyMoonR's calibration read 1,601 tok/s with it+against 2,129 off. 0 (the default) is today's split;+`STRATA_PREFILL_PIPE=<R>` is the same as the flag where the config cannot carry it. The chunk geometry changes the+rounding, which is why it is opt-in.++A prompt segment (the prompt between two of its cuts: the system-prompt root, the last turn, a `pin=`) is planned once,+on its whole length and R, and every run of it reads in that chunk. So its chunks, and the loan its buffers are laid+out for, are the same whether it is read in one run, in pieces between the windows of decoding `--batch` slots, or goes+on after a `BYIELD` or from a periodic checkpoint taken inside it (the slot and the checkpoint keep the plan; the read+goes on in it when it continues the same segment, else it plans again and says so in the log). The output bits then+match as far as the experts the cards hold do (`--adapt-swaps 0` for byte-identical repeats, as without the pipe).+Before this, a read beside decoding slots re-planned every piece, and one that went on after a `BYIELD` re-planned what+was left. A chunk the pipe planned takes no `STRATA_PREFILL_CPU_SHARE`: the stages read+such chunks at the same time, and which stage got the CPU pool first would decide which experts the CPU computed. The+DONE line ends with `chunk=` (the first chunk of the request's longest batched segment) and `experts_streamed=` (the+expert blobs its prompt copied to the cards), and the INFO line carries `prefill_cap`, `prefill_stages`,+`stream_all_min` and `prefill_pipe`. One line in the log says what a plan chose:++ strata prefill: 10058 tokens in 1280-token chunks over 4 stages (--prefill-pipe 706: b/a)++Four GP100 dies (PH402 SKU 200, `--layer-split 12,24,36`, Flash-Next IQ3_XXS, 64K context), prompt tok/s, fresh+prompts, two interleaved rounds (each within 0.2%), with b/a 1024 (the same chunks as 700-890, measured on this rig):++| Prompt tokens | `--prefill auto` | `--prefill 2048` | `--prefill auto` + `--prefill-pipe 1024` (chunk) |+| ---: | ---: | ---: | ---: |+| 2,013 | 180.9 | 181.4 | 228.0 (1024) |+| 3,865 | 207.6 | 276.5 | 312.4 (1024) |+| 10,041 | 261.1 | 433.0 | 432.6 (2048) |+| 28,998 | 475.7 | 554.1 | 559.7 (3328) |++Two RTX 3090 Ti (CUDA 12.9 build for sm_86, two stages, Swift 1.5 IQ3_XXS, 1M context, 13,371 of 24,576 experts in+VRAM), prompt tok/s, fresh prompts, two starts per arm, each reading the four prompts twice (the cold first pass after+a card was freed is left out); b/a 5836 and 6432 (timed on the rig), against 1024:++| Prompt tokens | `--prefill auto` | + b/a 5836 / 6432 (chunk) | for comparison: b/a 1024 |+| ---: | ---: | ---: | ---: |+| 2,035 | 694-815 | 698-816 (today's) | 560-562 |+| 3,887 | 1,127-1,207 | 1,115-1,227 (today's) | 880-885 |+| 10,063 | 1,437-1,553 | 1,654-1,681 (2 x 5120) | 1,109-1,113 |+| 29,019 | 2,532-2,603 | 2,566-2,620 (today's) | 2,064-2,089 |+## Limits (for now)- **Works across cards** (bench/results/2026-09-29-layer-split-limits):diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hppindex 08e9cb804..74f0248da 100644--- a/include/strata/core/conversation_cache.hpp+++ b/include/strata/core/conversation_cache.hpp@@ -29,6 +29,16 @@ struct ConversationCheckpoint {// from, so retention never evicts it (conv_cache.hpp) and a parked conversation holding it stays parked. A run-time// mark only: it is not in the session file, a request that pins the same prefix again sets it.bool pinned = false;+ // --prefill-pipe on a layer split: the plan a prompt segment [from, to) is read in - its chunk (0: none), the loan+ // its buffers were laid out for (which experts the prompt reads in place and which it streams: that sets bits+ // too), the pipe value it was planned with, whether it is one chunk and whether the plan changed the buffers'+ // chunks. A periodic checkpoint taken inside such a segment keeps it, so a read that goes on from there reads the+ // rest in the same chunks with the same loan. Run-time only, like `pinned` (a layer split saves no session files).+ struct PromptPlan {+ int64_t chunk = 0, from = -1, to = -1, lend = 0;+ double pipe = 0.0;+ bool single = false, chunked = false;+ } plan;// Ordinary layer-split checkpoints retain each device's running state.// Whole-session parking is currently single-GPU and rejects these parts.std::vector<ConversationCheckpoint> stage_parts;diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hppindex b4f100df0..79d23a4ac 100644--- a/include/strata/prefill/prefill.hpp+++ b/include/strata/prefill/prefill.hpp@@ -81,8 +81,41 @@ public:/// ring (a big one only pays when the copy engine, not the host copies, is the limit); set before bytes_needed.static void set_pinned_share(double share);static double pinned_share();- /// The chunk size from which a chunk streams every expert the GPU does not hold (1024; STRATA_PREFILL_STREAM_MIN).+ /// The chunk size from which a chunk streams every expert the GPU does not hold, routed or not; a smaller one+ /// stages only the experts it routes to. 1024, or STRATA_PREFILL_STREAM_MIN, or the CPU share's limit once that+ /// is armed (3072 when STRATA_PREFILL_CPU_SHARE is set).static int64_t stream_all_min_tokens();+ /// --prefill-pipe (opt-in): the chunk a layer split's first stage reads an `n`-token prompt in, for `stages`+ /// stages, chunks of at most `cap` (the buffers' size) and a stage-chunk cost of b + a C with b/a = `ratio` tokens+ /// (0: unknown - STRATA_PREFILL_EQUAL's rule: the same chunk count as `cap` gives, evened out when its last chunk+ /// has stream_all_min tokens or more): the chunk count with the pipeline's least time, see the definition. `cap`+ /// when that is today's split or not 3% better than it. A function of its arguments only.+ static int64_t pipeline_chunk(int64_t n, int64_t cap, int stages, double ratio);+ /// --prefill-pipe for this run: 0 off (the buffers' chunks), 1 today's chunk count evened out (STRATA_PREFILL_EQUAL's+ /// rule), a number > 1 the rig's b/a in tokens (setup's --calibrate measures it). Default: STRATA_PREFILL_PIPE, else 0.+ static void set_pipe(double value);+ /// The same for the next prompts only (the `pipe=` request key, setup's calibration); < 0 = the run's own value.+ static void set_pipe_request(double value);+ /// The --prefill-pipe value in force (the request's, else the run's).+ static double pipe_setting();+ /// What a --prefill-pipe value plans by: -1 off, 0 today's chunk count evened out, else b/a in whole tokens (two+ /// spellings of one value, e.g. a request key and the flag, compare equal).+ static int64_t pipe_key(double value);+ /// The stages of the prompt path from this one on (1 without a layer split).+ int stage_count() const;+ /// --prefill-pipe on a layer split's first stage: the chunk an `n`-token segment is read in when it is read whole+ /// (pipeline_chunk over chunk(), the stage count and pipe_setting()), or 0 when the pipe is off here (one stage,+ /// value 0, or a later stage) and the buffers' chunk applies. The engine plans a segment once, on its whole+ /// length, and reads every part of it with force_chunk, so its chunks do not depend on how it is cut into runs.+ int64_t plan_chunk(int64_t n) const;+ /// The next run on this (first) stage only: chunks of `chunk` tokens (at most chunk()) instead of a plan, from+ /// its first token; `single`: the segment is one chunk (the stage helper may bind); `planned`: the chunks came+ /// from a --prefill-pipe plan (such a read takes no CPU share: its chunks overlap on the stages by design).+ void force_chunk(int64_t chunk, bool single, bool planned);+ /// One log line for a planned segment (the same as a whole read logs when its plan differs from chunk()).+ static void log_plan(int64_t n, int64_t chunk, int stages);+ /// The expert blobs this stage and the later ones copied host -> device so far (PrefillStats::experts_streamed).+ int64_t chain_experts_streamed() const;/// #340: the streamed ring's slot count for chunks that stream every expert, instead of the pinned-share rule/// (0 = that rule). Set before any `bytes_needed`/`init` (both count the ring); STRATA_PREFILL_RING still wins.static void set_ring_override(int slots);@@ -200,6 +233,9 @@ private:Prefill* next_ = nullptr;Prefill* helper_ = nullptr; ///< set_stage_helperbool single_chunk_ = false; ///< a later stage: the prompt is one chunk (set by the stage before)+ bool pipe_chunked_ = false; ///< a later stage: the chunks came from a --prefill-pipe plan (set likewise)+ int64_t force_chunk_ = 0; ///< force_chunk, for the next run (0: none)+ bool force_single_ = false, force_planned_ = false;bool bind_stage_helper(int64_t T); // binds the helper's buffers for a one-chunk prompt of T tokensconst float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned)diff --git a/serve/server.py b/serve/server.pyindex 5ca7f4e4d..2f19431d6 100644--- a/serve/server.py+++ b/serve/server.py@@ -1096,6 +1096,13 @@ class StrataEngine:self.last.update(prompt_read=int(f[14]))if len(f) >= 16: # #588 (engine 0.1.39+): routed experts read over PCIeself.last.update(offloaded=int(f[15]))+ for tok in f[16:]: # key=value fields after the positional ones (the prompt's+ key, eq, value = tok.partition("=") # first chunk and its streamed expert blobs)+ if eq and key in ("chunk", "experts_streamed"):+ try:+ self.last[key] = int(value)+ except ValueError:+ passdef vram(self, reserve_mib: int | None, timeout: float = 120.0) -> dict:"""#533: `VRAM <reserve_mib>` between requests (the caller holds the service's FIFO): the engine shrinks its@@ -1173,6 +1180,10 @@ class StrataEngine:v = tune.get(k)if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0:keys += f" {k}={float(v)!r}"+ # a layer split's prompt chunks (--prefill-pipe): 0 off, 1 evened out, > 1 the rig's b/a in tokens+ v = tune.get("prefill_pipe")+ if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 262144.0:+ keys += f" pipe={float(v)!r}"# --aux-cpus for this request: 1 puts the engine's threads that are neither pool workers nor the host on the# spare CPUs, 0 leaves them where they were created (true/false or 1/0; the engine started without a spare CPU# ignores a 1). Anything else is not sent.@@ -4586,13 +4597,13 @@ def request_stats(segments: list[dict]) -> dict:if not segments:return {}result = dict(segments[-1])- for key in ("reused", "prompt_read"):+ for key in ("reused", "prompt_read", "chunk"):if key in segments[0]:result[key] = segments[0][key]else:result.pop(key, None)for key in ("prompt_ms", "decode_ms", "generated", "drafts_offered", "drafts_accepted",- "hits", "lookups", "offloaded", "ram_blobs", "file_blobs", "file_mb"):+ "hits", "lookups", "offloaded", "ram_blobs", "file_blobs", "file_mb", "experts_streamed"):if any(segment.get(key) is not None for segment in segments):result[key] = sum(segment.get(key) or 0 for segment in segments)return resultdiff --git a/serve/test_server.py b/serve/test_server.pyindex 3a49ff255..738448134 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -26,7 +26,7 @@ from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, EngineNonFinite,PP_DONE_TAIL, Service,StrataEngine, api_key_of, engine_args, key_matches, layer_split_value, prompt_progress,prompt_tokens_seen,- request_timings, serve, start_failure_hint)+ request_stats, request_timings, serve, start_failure_hint)from types import SimpleNamespace # noqa: E402ROOT = Path(__file__).resolve().parents[1]@@ -1548,6 +1548,13 @@ class SamplingKeys(unittest.TestCase):bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2})self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")])+ def test_tune_prefill_pipe(self):+ self.assertIn("pipe=1536.0", self.keys(temperature=0, strata_tune={"prefill_pipe": 1536}))+ self.assertIn("pipe=0.0", self.keys(temperature=0, strata_tune={"prefill_pipe": 0}))+ for bad in (-1, True, "800", 1e9):+ self.assertFalse([x for x in self.keys(temperature=0, strata_tune={"prefill_pipe": bad})+ if x.startswith("pipe=")], bad)+def test_tune_aux_cpus(self):for val, want in ((True, "aux_cpus=1"), (1, "aux_cpus=1"), (False, "aux_cpus=0"), (0, "aux_cpus=0"),(1.0, "aux_cpus=1"), (0.0, "aux_cpus=0")):@@ -2507,6 +2514,30 @@ class CancelledRead(unittest.TestCase):StrataEngine._parse_done(e, "DONE 0 98179 17565.0 0.0 cancel 0 0 0 0 0 0 0 0.0")self.assertNotIn("prompt_read", e.last)+ def test_parse_done_chunk_fields(self):+ """The prompt's first chunk and its streamed expert blobs come as key=value fields after the positional ones,+ with or without the five --lookup-chain fields; an older line has neither."""+ e = SimpleNamespace()+ StrataEngine._parse_done(e, "DONE 5 12000 900.0 80.0 stop 3 4 0 7 9 0 0 0.0 12000 2 chunk=1536 "+ "experts_streamed=24576")+ self.assertEqual((e.last["chunk"], e.last["experts_streamed"], e.last["offloaded"]), (1536, 24576, 2))+ StrataEngine._parse_done(e, "DONE 5 12000 900.0 80.0 stop 3 4 0 7 9 0 0 0.0 12000 2 1 2 3 4 5 chunk=8192 "+ "experts_streamed=0")+ self.assertEqual((e.last["chunk"], e.last["experts_streamed"]), (8192, 0))+ StrataEngine._parse_done(e, "DONE 5 12000 900.0 80.0 stop 3 4 0 7 9 0 0 0.0 12000 2")+ self.assertNotIn("chunk", e.last)+ self.assertNotIn("experts_streamed", e.last)+ StrataEngine._parse_done(e, "DONE 5 12000 900.0 80.0 stop 3 4 0 7 9 0 0 0.0 12000 2 chunk=x other=1")+ self.assertNotIn("chunk", e.last)+ self.assertNotIn("other", e.last)++ def test_request_stats_chunk_fields(self):+ """Across a request's continuations the streamed blobs add up; the chunk is the request's own read's."""+ stats = request_stats([{"prompt_ms": 10.0, "chunk": 1536, "experts_streamed": 100},+ {"prompt_ms": 2.0, "chunk": 64, "experts_streamed": 5}])+ self.assertEqual((stats["chunk"], stats["experts_streamed"], stats["prompt_ms"]), (1536, 105, 12.0))+ self.assertNotIn("chunk", request_stats([{"prompt_ms": 1.0}, {"prompt_ms": 1.0, "chunk": 64}]))+def test_prompt_tokens_seen(self):last = {"finish": "cancel", "reused": 1000, "prompt_read": 2000}self.assertEqual(prompt_tokens_seen(98179, last), 3000)diff --git a/setup.py b/setup.pyindex 8bb6ef9b2..b7778435c 100644--- a/setup.py+++ b/setup.py@@ -4752,7 +4752,8 @@ def calibrate_config(cfg_path: Path) -> bool:cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))say()say(" Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the")- say(" draft depth, the CPU threads, the expert cache). It takes roughly 15-30 minutes (3 rounds of each value); the PC is busy meanwhile.")+ say(" draft depth, the CPU threads, the expert cache; on two or more cards also the prompt chunks). It takes")+ say(" roughly 15-30 minutes (3 rounds of each value); the PC is busy meanwhile.")try:since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0except OSError:diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cppindex 2fa71c7ce..a96753e2b 100644--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@ -56,6 +56,7 @@#include <memory>#include <mutex>#include <thread>+#include <utility>#include <vector>#ifndef STRATA_PREFILL_MMQ@@ -160,11 +161,12 @@ constexpr int RING_MAX = 1024; // the arrays; the ring itself is ring_s// chunk) 779 -> 912 / 766 -> 844, the same output. Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk// takes other kernels), so 1024 is the floor. STRATA_PREFILL_STREAM_MIN overrides (A/B). With the CPU share armed// (Prefill::arm_cpu_share) it is the share's own limit instead: the share applies to staged chunks only.+constexpr int64_t kStreamAllMinDefault = 1024; // the default above (and the CPU share's default limit)int64_t g_stream_min_share = 0;inline int64_t stream_all_min() {static const int64_t env = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_MIN"); return e ? (int64_t) std::atoll(e) : (int64_t) -1; }();if (env >= 0) return env;- return g_stream_min_share > 0 ? g_stream_min_share : (int64_t) 1024;+ return g_stream_min_share > 0 ? g_stream_min_share : kStreamAllMinDefault;}// STRATA_PREFILL_CPU_SHARE (opt-in; set_cpu_pool): a chunk below stream_all_min() hands the decode CPU pool - idle// while a prompt is read - the non-resident experts few of its tokens route to, instead of streaming them over PCIe.@@ -201,10 +203,10 @@ inline bool cpu_share_on() { return cpu_share_env() != 0.0; }inline int64_t cpu_share_max() {static const int64_t v = [] {const char* e = std::getenv("STRATA_PREFILL_CPU_SHARE_MAX");- return e ? std::max<int64_t>(1024, (int64_t) std::atoll(e)) : (int64_t) 3072;+ return e ? std::max<int64_t>(kStreamAllMinDefault, (int64_t) std::atoll(e)) : (int64_t) 3072;}();static const bool explicit_max = std::getenv("STRATA_PREFILL_CPU_SHARE_MAX") != nullptr;- if (g_share_default && cpu_share_explicit() == -2.0 && !explicit_max) return 1024; // the default's measured range+ if (g_share_default && cpu_share_explicit() == -2.0 && !explicit_max) return kStreamAllMinDefault; // its measured rangereturn v;}// On a layer split every stage may have the pool (set_cpu_pool), and the stages read different chunks at the same time:@@ -1865,6 +1867,105 @@ void Prefill::set_ring_budget(int slots, int64_t small_max) {double Prefill::pinned_share() { return g_pinned_share; }int64_t Prefill::stream_all_min_tokens() { return stream_all_min(); }+// --prefill-pipe (opt-in; STRATA_PREFILL_PIPE): a layer split reads a prompt as a pipeline - stage s reads chunk c while+// stage s+1 reads chunk c-1. A stage-chunk costs its layers x (b + a C): a fixed part per chunk (b: the pass over the+// layer's experts - dequantized, or streamed over PCIe where they are not in VRAM) and a part per token (a). The prompt+// then takes about sum_i (b + a C_i) + (S - 1) max_i (b + a C_i) for chunks C_i over S stages: few large or uneven+// chunks keep the later stages waiting (a 10.7K prompt in a 7680 and a 3011 chunk over four GP100 dies: the first+// stage carried 24 of 36 s), many small ones pay b again and again. In units of a that is k r + n + (S - 1)(r + C) for+// k chunks of C tokens (the last one the rest) and r = b/a, so the rule tries every chunk count from the fewest the+// buffers allow, each chunk evened out on the 256-token grid and at least 512, and keeps the cheapest - when it beats+// today's split (chunks of `cap`, the last the rest) by 3%. r differs by an order of magnitude between rigs: ~700 tokens+// on four GP100 dies (every expert in VRAM, slow arithmetic), ~5000 on two RTX 3090 Ti (fast arithmetic, part of the+// experts streamed per chunk), and a wrong r costs (1024 on two RTX 4090: 22-36% slower). The engine neither guesses r+// nor learns it from the prompts it serves - that made a prompt's chunks, and so its output bits, depend on how busy+// the PC happened to be: setup's --calibrate measures it once (tools/calibrate.py) and writes `--prefill-pipe <r>`.+// `--prefill-pipe 1` needs no r: STRATA_PREFILL_EQUAL's rule - today's chunk count evened out, only when today's last+// chunk has stream_all_min() tokens or more. A chunk that size streams every expert its stage does not hold, a shorter+// one only the experts it routes to: a tail of a few tokens is nearly free, and evening it out would add a full pass+// (two RTX 4090, a prompt 25 tokens past 8192: 25% slower). --calibrate tries it like the other values.+namespace {+double g_pipe = -1.0; // --prefill-pipe; < 0: not given (STRATA_PREFILL_PIPE, else 0)+double g_pipe_req = -1.0; // the `pipe=` request key; < 0: none+double pipe_value() {+ if (g_pipe_req >= 0.0) return g_pipe_req;+ if (g_pipe >= 0.0) return g_pipe;+ static const double env = [] {+ const char* v = std::getenv("STRATA_PREFILL_PIPE");+ return v != nullptr && v[0] != '\0' ? std::max(0.0, std::atof(v)) : 0.0;+ }();+ return env;+}+} // namespace+void Prefill::set_pipe(double value) { g_pipe = value; }+void Prefill::set_pipe_request(double value) { g_pipe_req = value; }+double Prefill::pipe_setting() { return pipe_value(); }+namespace {+// b/a in whole tokens: 0 for none (or NaN), at most 2^20 (llround of an infinity is undefined - `pipe=inf` parses)+int64_t ratio_tokens(double ratio) { return ratio > 0.0 ? (int64_t) std::llround(std::min(ratio, 1048576.0)) : 0; }+} // namespace+int64_t Prefill::pipe_key(double value) { return !(value > 0.0) ? -1 : value <= 1.0 ? 0 : ratio_tokens(value); }+// In whole tokens (r rounded): integer sums and a 97/100 test, so a near-tie cannot fall one way in one build and the+// other way in another (the same chunks as the double version for every whole r: an exact 97% is not better).+int64_t Prefill::pipeline_chunk(int64_t n, int64_t cap, int stages, double ratio) {+ if (stages < 2 || n <= 0 || cap <= 0) return cap;+ const int64_t r = ratio_tokens(ratio), S1 = stages - 1;+ if (r == 0) {+ // `--prefill-pipe 1`: STRATA_PREFILL_EQUAL's rule (#693, generate.cpp equal_chunk) - today's chunk count, evened+ // out on the 256-token grid, only when today's last chunk streams every expert anyway (stream_all_min tokens or+ // more): evening a short tail out would add a full pass over the experts (two RTX 4090: 25% slower)+ const int64_t k = (n + cap - 1) / cap;+ const int64_t last = n - (k - 1) * cap;+ if (k <= 1 || last < stream_all_min()) return cap;+ const int64_t per = (n + k - 1) / k;+ return std::min(cap, ((per + 255) / 256) * 256);+ }+ auto cost = [&](int64_t c) { // chunks of c tokens, the last the rest+ const int64_t k = (n + c - 1) / c;+ return k * r + n + S1 * (r + std::min(c, n));+ };+ const int64_t today = std::min(n, cap);+ const int64_t today_cost = cost(today);+ const int64_t k_min = (n + cap - 1) / cap;+ const int64_t k_max = ratio > 0.0 ? std::max<int64_t>(k_min, std::min<int64_t>(64, (n + 511) / 512)) : k_min;+ int64_t best = today;+ int64_t best_cost = today_cost;+ for (int64_t k = k_min; k <= k_max; ++k) {+ const int64_t c = std::min(cap, std::max<int64_t>(512, (((n + k - 1) / k + 255) / 256) * 256));+ const int64_t v = cost(c);+ if (v < best_cost) { best_cost = v; best = c; }+ }+ return (best < today && 100 * best_cost < 97 * today_cost) ? best : cap;+}+int Prefill::stage_count() const {+ int stages = 1;+ for (const Prefill* p = next_; p != nullptr; p = p->next_) ++stages;+ return stages;+}+int64_t Prefill::plan_chunk(int64_t n) const {+ const double pipe = pipe_value();+ const int stages = stage_count();+ if (pipe <= 0.0 || hand_in_ != nullptr || stages < 2) return 0;+ return pipeline_chunk(n, impl_->T, stages, pipe > 1.0 ? pipe : 0.0);+}+void Prefill::force_chunk(int64_t chunk, bool single, bool planned) {+ force_chunk_ = chunk;+ force_single_ = single;+ force_planned_ = planned;+}+void Prefill::log_plan(int64_t n, int64_t chunk, int stages) {+ const double pipe = pipe_value();+ std::fprintf(stderr, "strata prefill: %lld tokens in %lld-token chunks over %d stages (--prefill-pipe %s)\n",+ (long long) n, (long long) chunk, stages,+ pipe > 1.0 ? (std::to_string((long long) ratio_tokens(pipe)) + ": b/a").c_str()+ : "1: today's chunk count, evened out");+}+int64_t Prefill::chain_experts_streamed() const {+ int64_t sum = 0;+ for (const Prefill* p = this; p != nullptr; p = p->next_) sum += p->stats_.experts_streamed;+ return sum;+}+uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src) {return bytes_needed_impl(g, ss, chunk, false, src);}@@ -2086,6 +2187,9 @@ struct PeTimer {bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {err.clear();+ // force_chunk is for this run only: taken before any early return can leave it to the next one+ const int64_t forced = hand_in_ == nullptr ? std::exchange(force_chunk_, 0) : 0;+ const bool forced_single = force_single_, forced_planned = force_planned_;Impl& m = *impl_;const core::OnDevice on_device(m.device);const core::ModelGeometry& g = *m.g;@@ -2122,7 +2226,23 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri// layer split: a prompt of one chunk runs the stages one after the other, so the next stage's GPU idles while// this one reads; it streams and computes a share of this stage's experts then (set_stage_helper), in the// place of a --peer-device peer, and gives the stage back its own buffers when the run ends- const bool single_chunk = hand_in_ == nullptr ? n <= m.T : single_chunk_;+ // the chunk this prompt is read in: the buffers' size, or with --prefill-pipe on a layer split the one that keeps+ // every stage busy (pipeline_chunk: 1 evens today's chunk count out, a number > 1 is the rig's b/a). Only the first+ // stage chooses: a later one is handed one chunk at a time. A run the engine forced (force_chunk: one part of a+ // segment it planned on its whole length) reads in that chunk and keeps the segment's single/planned flags.+ if (forced > m.T) {+ err = "prefill: a forced chunk of " + std::to_string((long long) forced) + " tokens is larger than the buffers' " ++ std::to_string((long long) m.T);+ return false;+ }+ const int64_t planned_C = forced > 0 ? 0 : plan_chunk(n);+ const int64_t C = forced > 0 ? forced : planned_C > 0 ? planned_C : m.T;+ if (planned_C > 0 && C < std::min(n, m.T)) log_plan(n, C, stage_count());+ const bool single_chunk = hand_in_ == nullptr ? (forced > 0 ? forced_single : n <= C) : single_chunk_;+ // a read the pipe chunked takes no CPU share: its chunks overlap on the stages by design, and which stage won the+ // pool would decide which experts the CPU computed (other bits) - timing, where the chunks are a function of n+ const bool pipe_chunked = hand_in_ == nullptr ? (forced > 0 ? forced_planned : planned_C > 0 && C < std::min(n, m.T))+ : pipe_chunked_;const bool helped = single_chunk && bind_stage_helper(n);if (helped) std::swap(m.pp, m.help_pp);struct HelpScope {@@ -2158,8 +2278,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri(ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) &&m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64;const int32_t prev0[2] = {prev[0], prev[1]};- auto ple_gather = [&m, &ss, tokens, n, prev0](int64_t c0, int buf, std::string& e) -> bool {- const int64_t T = std::min(m.T, n - c0);+ auto ple_gather = [&m, &ss, tokens, n, prev0, C](int64_t c0, int buf, std::string& e) -> bool {+ const int64_t T = std::min(C, n - c0);auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokensint32_t pv[2] = {at(c0), at(c0 + 1)};for (int64_t t = 0; t < T; ++t) {@@ -2175,10 +2295,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stristd::future<bool> ple_next; // declared after everything it reads: an early return waits for itint ple_buf = 0;- for (int64_t c0 = 0; c0 < n; c0 += m.T) {+ for (int64_t c0 = 0; c0 < n; c0 += C) {if (should_stop && should_stop()) { err = "cancelled"; return false; }if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); }- const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0;+ const int64_t T = std::min(C, n - c0), p0 = pos0 + c0;core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251++stats_.chunks;pt.mark(kPfStart, cs);@@ -2280,13 +2400,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::strierr = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError());return false;}- if (c0 + m.T < n) {+ if (c0 + C < n) {// the other buffer's upload (a chunk ago) is done before the SSD thread refills itif (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) {err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError());return false;}- ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] {+ ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + C, b = ple_buf ^ 1] {strata::aux_cpus::pin_current_thread();return ple_gather(c1, b, ple_next_err);});@@ -2345,7 +2465,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stribool held = false;~PoolHold() { if (held) g_cpu_pool_busy.store(false, std::memory_order_release); }} pool_hold;- if (cpu_pool_ != nullptr && cpu_share_on() && !stream_all) {+ if (cpu_pool_ != nullptr && cpu_share_on() && !stream_all && !pipe_chunked) {bool expect = false;pool_hold.held = g_cpu_pool_busy.compare_exchange_strong(expect, true, std::memory_order_acq_rel);}@@ -4170,6 +4290,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::strinext_err_.clear();next_->hand_in_ = h;next_->single_chunk_ = single_chunk;+ next_->pipe_chunked_ = pipe_chunked;next_run_ = std::async(std::launch::async, [this, tokens, c0, T, p0] {strata::aux_cpus::pin_current_thread();return next_->run_impl(tokens + c0, T, p0, next_err_);@@ -4239,7 +4360,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::strifor (float v : h) { c += !std::isfinite(v); if (std::isfinite(v)) mx = std::max(mx, (double) std::fabs(v)); }std::fprintf(stderr, " %lld non-finite (max |x| %.3g)", (long long) c, mx);};- const int64_t last = (n - 1) % m.T;+ const int64_t last = (n - 1) % C;std::fprintf(stderr, "strata dbg: prompt end: last residual row");bad(m.R + last * D, D);if (ss.ple.ready()) { std::fprintf(stderr, "; PLE history"); bad(ss.ple.hist, (int64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM); }diff --git a/src/program/generate.cpp b/src/program/generate.cppindex ba00f94d7..ae76d8567 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -533,8 +533,10 @@ struct Options {int vram_reserve_later_mib = -1;/// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path).int64_t prefill_chunk = 0;- /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk- /// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect).+ /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. A chunk of+ /// stream_all_min tokens or more (1024 by default) streams every expert the GPU does not hold once, routed or not+ /// (a smaller one only the experts it routes to), so a bigger chunk streams fewer bytes per token (the "ubatch"+ /// effect).bool prefill_auto = false;/// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or/// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context@@ -544,6 +546,10 @@ struct Options {/// a bare `--prefill auto` (no ":N", no STRATA_PREFILL_AUTO_MAX): the gfx12 Linux rule below may raise its ceilingbool prefill_auto_bare = false;bool prefill_gfx12_16k = false; ///< the gfx12 default raised the auto chunk ceiling to 16384 (a layer split takes 8192 back, 0.1.44)+ /// --prefill-pipe (opt-in): a layer split's prompt chunks sized for its pipeline (Prefill::pipeline_chunk): 0 off,+ /// 1 today's chunk count evened out, a number > 1 the rig's b/a in tokens (setup's --calibrate measures it).+ /// < 0: not given - STRATA_PREFILL_PIPE, else off.+ double prefill_pipe = -1.0;bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread/// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after/// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead.@@ -843,6 +849,10 @@ void usage() {" --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n"" the largest chunk up to 8192 whose buffers the expert cache can lend;\n"" auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n"+ " --prefill-pipe R opt-in, a layer split: prompt chunks sized so the stages read at once - R is\n"+ " this PC's b/a in tokens (setup's --calibrate measures it); 1 only evens out\n"+ " the buffers' chunk count (STRATA_PREFILL_EQUAL's rule); 0 off (default; or\n"+ " STRATA_PREFILL_PIPE)\n"" --no-pool skip the CPU expert pool (the GPU-only floor)\n"" --sync-every-layer debug: synchronise after every layer\n"" --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n"@@ -2065,6 +2075,7 @@ int main(int argc, char** argv) {v.c_str(), (long long) strata::platform::host_limits::kWinHipAutoChunkCap);}}+ else if (a == "--prefill-pipe") o.prefill_pipe = std::max(0.0, std::atof(next("--prefill-pipe")));else if (a == "--no-split-rows") o.no_split_rows = true;else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true;else if (a == "--vram-elastic") o.vram_elastic = true;@@ -3733,10 +3744,11 @@ int main(int argc, char** argv) {// whole expert blobs, which a split without borrowing sizes at 96 (Prefill::set_ring_override below) and books// here - without it a `--no-prefill-borrow` split filled the cards and the draft head no longer fit)const int64_t split_ring_mib =- (multi_gpu && !pf_borrow && o.prefill_chunk >= 1024)+ (multi_gpu && !pf_borrow && o.prefill_chunk >= strata::prefill::Prefill::stream_all_min_tokens())? (int64_t) ((96ull * (uint64_t) strata::kernels::cpu::expert_layout().max_blob + (1ull << 20) - 1) >> 20): 0;if (split_ring_mib > 0) strata::prefill::Prefill::set_ring_override(96);+ if (o.prefill_pipe >= 0.0) strata::prefill::Prefill::set_pipe(o.prefill_pipe);const int64_t split_pf_mib =(o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 + split_ring_mib : 0;// ---- WHAT A STAGE RESERVES, AND ON WHICH STAGE. The flat 1 GiB this used to withhold from EVERY stage@@ -8132,6 +8144,9 @@ int main(int argc, char** argv) {std::vector<ConvCheckpoint> checks;uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance itint64_t tail_ckpt_len = -1; // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none)+ // --prefill-pipe: the plan of the prompt segment being read (read_part sets it around its runs), for the+ // checkpoints taken inside it+ ConvCheckpoint::PromptPlan seg_plan;bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with// without --mtp the conversation cache stays on: a parked image carries the draft layer's K/V only when there is one// (the snapshots accept a null draft)@@ -8466,6 +8481,7 @@ int main(int argc, char** argv) {}}c.used = ++check_clock;+ if (seg_plan.chunk > 0 && L > seg_plan.from && L < seg_plan.to) c.plan = seg_plan; // inside a planned segmentif (as_tail) { // only one tail checkpoint stays alive: the previous request's goesconst int64_t old_tail = tail_ckpt_len;checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& k) {@@ -9592,7 +9608,8 @@ int main(int argc, char** argv) {"mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f ""spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d ""conversation_cache_min_free_mib=%lld conversation_cache_min_tokens=%lld "- "tail_role_token=%lld vram_elastic=%d%s engine=" STRATA_VERSION "\n",+ "tail_role_token=%lld vram_elastic=%d "+ "prefill_cap=%lld prefill_stages=%d stream_all_min=%lld prefill_pipe=%g%s engine=" STRATA_VERSION "\n",(long long) o.max_context, o.kv.c_str(),(long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0),@@ -9605,6 +9622,11 @@ int main(int argc, char** argv) {o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots,(long long) o.conversation_cache_min_free_mib, (long long) o.conversation_cache_min_tokens,(long long) o.tail_role_token, xcache.segmented() ? 1 : 0,+ // the prompt path: its chunk cap (the VRAM command's relend can lower it later), the stages a+ // prompt flows through, the chunk size from which a chunk streams every expert, --prefill-pipe+ (long long) o.prefill_chunk, sp.stage_count(),+ (long long) strata::prefill::Prefill::stream_all_min_tokens(),+ strata::prefill::Prefill::pipe_setting(),o.batch > 0 ? (" batch_slots=" + std::to_string(o.batch) +" slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0) +" batch_groups=" + std::to_string(o.batch_groups)).c_str() : "");@@ -9833,6 +9855,7 @@ int main(int argc, char** argv) {// #879: it was running when non-finite logits dropped the cached state; its state may have started from// that state (a checkpoint, a parked conversation), so it is not kept as a cache when it endsbool tainted = false;+ ConvCheckpoint::PromptPlan partial_plan; ///< --prefill-pipe: the segment it stopped in, read on in its chunks};std::vector<BSlot> bs((size_t) std::max(o.batch, 0));// timing of the batch windows since the slots were last all idle (one stderr line then)@@ -10663,6 +10686,7 @@ int main(int argc, char** argv) {// tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of// the missed experts and the draft-probability floor, for this request onlydouble req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p;+ double req_pipe = -1.0; // --prefill-pipe for this request (setup's calibration of a layer split)int req_aux_cpus = -1; // aux_cpus=0|1: --aux-cpus for this request (-1 = the start-up value)// #2228: img_keys=<hex>,<hex>,... (GENI): each picture's key from the server (its normalized bytes' hash),// in prompt order. With them the conversation cache matches a picture by its key and grid, not by its@@ -10695,6 +10719,7 @@ int main(int argc, char** argv) {else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10);else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0);else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0);+ else if (key == "pipe") req_pipe = std::max(0.0, (double) fv);else if (key == "aux_cpus") req_aux_cpus = std::atoi(tok.c_str() + eq + 1) != 0 ? 1 : 0;else if (key == "img_keys") {req_img_keys.clear();@@ -10711,6 +10736,7 @@ int main(int argc, char** argv) {// unknown keys are skipped: the ids start at the first token without '='}}+ strata::prefill::Prefill::set_pipe_request(req_pipe); // every request sets it: none carries overstd::vector<float> req_bias;std::string bias_error;if (req_bias_present && (o.batch > 0 ||@@ -10851,6 +10877,7 @@ int main(int argc, char** argv) {}cur = ids;const Clock::time_point r0 = Clock::now();+ const int64_t streamed0 = sp.chain_experts_streamed(); // the DONE line's experts_streamed= is the difference// ---- where this request starts reading: the live session, or a checkpoint, whose tokens AND pictures are// exactly the start of this prompt - at most n - 1 of them, the last token is always the first windowauto starts_with = [&](const std::vector<int32_t>& pre, const std::vector<ImgKey>& pre_imgs) -> bool {@@ -10931,6 +10958,10 @@ int main(int argc, char** argv) {int slot_source = -1;int64_t slot_tokens = 0;bool resumed_from0 = false; // a prompt read parked in a slot (BYIELD) that had started at token 0+ // --prefill-pipe: the plan of the segment a read goes on in (a BYIELD park, a periodic checkpoint), and+ // where it goes on; read_part reads the rest of that segment in its chunks+ ConvCheckpoint::PromptPlan resume_plan;+ int64_t resume_plan_at = -1, resume_plan_end = -1; // where it goes on, and the segment end it needsconst ConvCheckpoint* slot_ck = nullptr; // the slot's checkpoint the prompt continues from (else its end)if (o.prompt_cache > 0 && req_imgs.empty())for (int b = 0; b < (int) bs.size(); ++b) {@@ -11042,8 +11073,12 @@ int main(int argc, char** argv) {// checkpoints as if it had not stoppedif (slot_ck == nullptr && bs[(size_t) slot_source].partial && admit_slot == slot_source) {resumed_from0 = bs[(size_t) slot_source].partial_from0;+ resume_plan = bs[(size_t) slot_source].partial_plan;+ resume_plan_at = slot_tokens;+ resume_plan_end = resume_plan.to;for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks) checks.push_back(c);bs[(size_t) slot_source].partial = false;+ bs[(size_t) slot_source].partial_plan = {};}if (slot_ck != nullptr) {live = slot_ck->ids;@@ -11192,6 +11227,28 @@ int main(int argc, char** argv) {return 1;}}+ // --prefill-pipe: going on from a periodic checkpoint taken inside a planned segment (whatever restored it:+ // a checkpoint of this session, of a slot or of a parked conversation), the rest of that segment is read+ // in its chunks. STRATA_CKPT_REREAD reads [0, resume) again in the chunks the saving read had, which it+ // can only when that segment started at 0. The BYIELD park set resume_plan above.+ if (resume_plan.chunk <= 0 && resume > 0 && !stages.empty())+ for (const ConvCheckpoint& k : checks)+ if ((int64_t) k.ids.size() == resume && k.plan.chunk > 0) {+ if (reread_to <= 0) {+ resume_plan = k.plan;+ resume_plan_at = resume;+ resume_plan_end = k.plan.to;+ } else if (k.plan.from == 0) { // [0, resume) only: its end is the checkpoint+ resume_plan = k.plan;+ resume_plan_at = 0;+ resume_plan_end = resume;+ } else {+ std::fprintf(stderr, "strata serve: STRATA_CKPT_REREAD: the checkpoint is inside a "+ "segment that started at %lld, so a read from 0 has other chunks\n",+ (long long) k.plan.from);+ }+ break;+ }// KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers'// host copies and slots are always current (every writer writes both), so they need nothingif (use_mtp && resume > 0 && reread_to <= 0) mtp.kv_restore(resume);@@ -11473,16 +11530,20 @@ int main(int argc, char** argv) {// lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens// rounded up to 256), laid out in the last of the slots it may borrow - per participant, out of that// participant's own cache, and marking only that participant's own layers- auto lend = [&](int64_t tokens, std::string& e) -> bool {+ int64_t seg_lend = 0; // the loan the last lend left (the largest participant's chunk; 0: none)+ auto lend = [&](int64_t tokens, std::string& e, int64_t exact) -> bool {+ seg_lend = 0;if (pf_parts.empty()) return true; // its own buffers: nothing to lendconst auto t_ln = Clock::now();// what this segment needs, capped by the configured chunk: a request lends only what its own// prompt needs, so a large chunk costs a short prompt nothingconst int64_t want_full = equal_chunk(tokens, o.prefill_chunk);// #340: a short enough request reads in the stages' own S-token chunks (nothing lent)- const int64_t want = o.prefill_head_alias ? o.prefill_chunk- : split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small)- : want_full;+ const int64_t want_seg = o.prefill_head_alias ? o.prefill_chunk+ : split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small)+ : want_full;+ // `exact`: a planned segment read on - the loan it was read with (what is left would size another)+ const int64_t want = exact > 0 ? std::min(exact, o.prefill_chunk) : want_seg;if (want <= 0) {e = "prefill: cannot lend buffers for an empty request segment";return false;@@ -11541,6 +11602,8 @@ int main(int argc, char** argv) {}p.lent_chunk = want_p;}+ for (const PfPart& p : pf_parts)+ if (p.first >= 0) seg_lend = std::max(seg_lend, p.lent_chunk);if (any) res_upload();if (trace) {int64_t n_lent = 0;@@ -11569,20 +11632,73 @@ int main(int argc, char** argv) {// far is copied into <slot> (this admission's own, or a free one the server reserved for a solo request),// the request ends with `YIELDED <slot> <tokens>` + DONE cancel, and the server sends it again later: it// continues from the slot with the same chunks. #656's cooperative preemption, with a slot as the park.+ int64_t req_chunk = 0, req_chunk_len = 0; // the DONE line's chunk=: the longest batched segment's first chunkauto read_part = [&](int64_t a0, int64_t b0, std::string& e) -> bool {+ // --prefill-pipe on a layer split: the segment's chunk is planned ONCE, on its whole length (or taken+ // from the read it goes on from: resume_plan), and every run of it reads in that chunk (force_chunk) -+ // the same chunks whether it is read in one run, in pieces beside decoding slots, or goes on after a+ // BYIELD or from a checkpoint. Without the pipe nothing here changes: runs read in the buffers' chunk.+ ConvCheckpoint::PromptPlan plan;+ if (!stages.empty()) {+ if (resume_plan.chunk > 0 && a0 == resume_plan_at) {+ using strata::prefill::Prefill;+ const ConvCheckpoint::PromptPlan& rp = resume_plan;+ if (b0 == resume_plan_end && rp.from >= 0 && rp.from <= a0 && (a0 - rp.from) % rp.chunk == 0 &&+ rp.chunk <= sp.chunk() && Prefill::pipe_key(rp.pipe) == Prefill::pipe_key(Prefill::pipe_setting())) {+ plan = rp;+ } else {+ std::fprintf(stderr, "strata prefill: the read going on at %lld is not the segment "+ "[%lld, %lld) it was planned in (%lld-token chunks): planned again\n",+ (long long) a0, (long long) rp.from, (long long) rp.to, (long long) rp.chunk);+ }+ resume_plan = {}; // the first segment only+ }+ if (plan.chunk <= 0) {+ const int64_t c = sp.plan_chunk(b0 - a0);+ if (c > 0) {+ plan.chunk = c;+ plan.from = a0;+ plan.to = b0;+ plan.lend = seg_lend;+ plan.pipe = strata::prefill::Prefill::pipe_setting();+ plan.single = b0 - a0 <= c;+ plan.chunked = c < std::min(b0 - a0, sp.chunk());+ if (plan.chunked) strata::prefill::Prefill::log_plan(b0 - a0, c, sp.stage_count());+ }+ }+ }+ const bool planned = plan.chunk > 0;+ const bool plan_single = planned && plan.single;+ if (b0 - a0 > req_chunk_len) {+ req_chunk_len = b0 - a0;+ req_chunk = planned ? std::min(plan.chunk, b0 - a0) : std::min(sp.chunk(), b0 - a0);+ }+ seg_plan = plan; // the checkpoints taken inside it keep it; cleared when the segment is done+ struct SegPlanScope {+ ConvCheckpoint::PromptPlan& p;+ ~SegPlanScope() { p = {}; }+ } seg_plan_scope{seg_plan};+ auto run = [&](int64_t q, int64_t r) -> bool {+ if (planned) sp.force_chunk(plan.chunk, plan_single, plan.chunked);+ return sp.run(ids.data() + q, r - q, q, e);+ };// (a layer split reads its stages as a pipeline over one run's chunks: beside slots a chunk at a time, with// none decoding in pieces of STRATA_BATCH_YIELD_CHUNKS chunks (default 8; 0 = one run) so a BYIELD is taken)static const int64_t yield_chunks = [] {const char* v = std::getenv("STRATA_BATCH_YIELD_CHUNKS");return v != nullptr ? (int64_t) std::max(0, std::atoi(v)) : (int64_t) 8;}();- const int64_t C = std::max<int64_t>(sp.chunk(), 1);+ // a piece's chunk: the buffers' chunk, or with a plan as many whole planned chunks as that holds (the+ // stages still pipeline inside a piece, and every piece starts on the plan's grid)+ const int64_t C = planned ? std::max<int64_t>(1, sp.chunk() / plan.chunk) * plan.chunk+ : std::max<int64_t>(sp.chunk(), 1);+ const int64_t C_read = planned ? plan.chunk : C; // what the yield test calls a chunkconst int64_t piece = strata::program::batch_read_piece(o.batch > 0, piped, !stages.empty(), batch_on(), C, yield_chunks);- if (piece <= 0) return sp.run(ids.data() + a0, b0 - a0, a0, e);+ if (piece <= 0) return run(a0, b0);for (int64_t q = a0; q < b0;) {const int64_t r = std::min(b0, q + piece);const auto tq = Clock::now();- if (!sp.run(ids.data() + q, r - q, q, e)) return false;+ if (!run(q, r)) return false;q = r;if (q >= b0) continue;int ys = -1;@@ -11606,7 +11722,7 @@ int main(int argc, char** argv) {// read left), text only, and into a slot that is not decodingconst bool can = ys < (int) bs.size() && !bs[(size_t) ys].active &&(admit_slot < 0 || ys == admit_slot) && req_imgs.empty() && o.prompt_cache > 0 &&- b0 - q > std::max<int64_t>(C, o.short_read);+ b0 - q > std::max<int64_t>(C_read, o.short_read);std::string ye;const auto ty = Clock::now();std::vector<int32_t> pre(ids.begin(), ids.begin() + q);@@ -11617,6 +11733,7 @@ int main(int argc, char** argv) {sl.cached = true;sl.partial = true;sl.partial_from0 = read_from == 0 || resumed_from0;+ if (planned) sl.partial_plan = plan; // the resend reads the rest in these chunkssl.cvec = cvec_cached;for (const ConvCheckpoint& c : checks) // the root / periodic checkpoints of this readif ((int64_t) c.ids.size() <= q && std::equal(c.ids.begin(), c.ids.end(), ids.begin(),@@ -11774,7 +11891,11 @@ int main(int argc, char** argv) {std::printf("ERR refilling a lent slot failed: %s\n", err.c_str());return 1;}- if (!win && !lend(to - at, err)) {+ // a read going on in a planned segment gets the loan it was read with (what is left would size+ // another, and the loan decides which experts are read in place: bits)+ const int64_t plan_lend = resume_plan.chunk > 0 && at == resume_plan_at && to == resume_plan_end+ ? resume_plan.lend : 0;+ if (!win && !lend(to - at, err, plan_lend)) {std::printf("ERR lending the prompt path its slots failed: %s\n", err.c_str());return 1;}@@ -12928,18 +13049,23 @@ int main(int argc, char** argv) {// not in [lookups])// [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows]// (only with --lookup-chain)+ // chunk=<tokens> experts_streamed=<blobs> (key=value, last: the first chunk of the request's longest+ // batched segment, 0 when it read none; the expert blobs its prompt read copied host -> device on+ // every stage - not the CPU share's, the stage helper's or a --peer-device peer's)char chain_txt[128] = "";if (o.lookup_chain > 0)std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok,(long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows);if (yielded_at >= 0) std::printf("YIELDED %d %lld\n", yielded_slot, (long long) yielded_at);- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld%s\n",+ std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld%s chunk=%lld "+ "experts_streamed=%lld\n",(long long) produced_n,(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,(long long) resume, (long long) req_hits, (long long) req_look,(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),(double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n,- (long long) req_offload, chain_txt);+ (long long) req_offload, chain_txt, (long long) req_chunk,+ (long long) (sp.chain_experts_streamed() - streamed0));std::fflush(stdout);if (admit_slot >= 0) { // --batch: BADM <slot> <1 = continues in the batch windows | 0 = done>bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 &&diff --git a/tools/calibrate.py b/tools/calibrate.pyindex 3ed6a4c85..7cd6d4eef 100644--- a/tools/calibrate.py+++ b/tools/calibrate.py@@ -13,8 +13,14 @@ measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5):its use counts fade. A PC whose CPU reads the missed experts slowly (DDR3, ~24 GB/s) gains fromswapping more: 160 swaps every window measured +7.9% over the default tier on a Xeon E5-2673 v3 (DDR3) with anRTX 4060 Ti on PCIe 3.0 x8 (Q2_0; with the swaps taking effect a window later, #764).-The first two are measured through one engine (per-request `strata_tune` keys); the worker count and the adaptive-tier need a restart per value. Decode speed only: the prompt path streams every expert whatever these settings say.+ --prefill-pipe a layer split only: the prompt chunks that keep the stages reading at once. The best chunk count+ depends on b/a, the fixed cost of a chunk over that of a token, which differs by an order of+ magnitude between rigs (about 700 tokens on four GP100 dies, 5000 on two RTX 3090 Ti) and costs+ when it is wrong (a fixed 1024 read 22-36% slower on two RTX 4090) - so it is measured here, once,+ as the prompt read speed of fresh prompts, rather than guessed or learned while the PC serves.+The first two and the prompt chunks are measured through one engine (per-request `strata_tune` keys); the worker+count and the adaptive tier need a restart per value. Those are decode speed: the prompt path streams every expert+whatever they say.A setting is kept only when it beats the default by more than MIN_GAIN in an interleaved re-measurement - theadaptive expert tier and the OS make single measurements noisy by a few percent.@@ -46,6 +52,9 @@ MAX_NEW = 128# the expert tier follows a text over some windows: 128-token answers end before it shows (on a Xeon E5-2673 v3 with# DDR3, every 1 / 160 / 0.97 measured +0.7% with 128 tokens and +7.9% with 512-token answers), so its step uses theseTIER_MAX_NEW = 512+# --prefill-pipe's values: 0 the buffers' chunks (the engine default), 1 their count evened out, then b/a in tokens+PIPE_VALUES = (0, 1, 768, 1536, 3072, 6144)+PIPE_TOKENS = (2048, 8192) # fresh prompts read per value (their text: the install's docs/*.md)PROMPTS = ("Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests.","Explain in two paragraphs how a refrigerator moves heat from inside to outside.",@@ -99,6 +108,59 @@ def host_worker_extras() -> list[int]:return []+def doc_prompt(tok):+ """`make(i, n)`: a fresh prompt of about n tokens - the same stretch of the docs' text for every i, after a header+ that differs for every i, so no read reuses an earlier one's cache and the reads differ only in their chunks (where+ experts are streamed, the read speed depends on the text: a different stretch per read measured the text)."""+ text = "\n\n".join(p.read_text(encoding="utf-8", errors="replace") for p in sorted((ROOT / "docs").glob("*.md")))+ body = tok.encode(text, parse_special=False) or [0]+ tail = tok.encode("<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n", parse_special=True)++ def make(i: int, n: int) -> list[int]:+ head = tok.encode(f"<|im_start|>user\n[calibration read {i}] Summarize:\n", parse_special=True)+ return head + (body * (n // len(body) + 1))[:n] + tail+ return make+++def measure_pipe(eng, make, say=print) -> tuple[float, dict]:+ """--prefill-pipe on one running engine (a layer split): the prompt read speed of fresh prompts per value, then the+ best against the default (0) in SWEEP_ROUNDS paired rounds (back to back, the order alternating). It is kept only+ when it is faster in every round and by more than MIN_GAIN in the median: on two RTX 3090 Ti one read can be 20%+ off, and a b/a too small for the rig reads 19-24% slower there. One pass over the values, not `sweep`'s rounds:+ every value reads the same text (`doc_prompt`), and on four GP100 dies one pass already takes about 4 minutes."""+ reads = [0]++ def rate(v: float) -> float:+ ms = toks = 0.0+ for n in PIPE_TOKENS:+ reads[0] += 1+ sampling = {"temperature": 0, "strata_checkpoint": False, "strata_tune": {"prefill_pipe": v}}+ for _ in eng.generate(make(reads[0], n), 1, sampling, threading.Event()):+ pass+ last = eng.last or {}+ ms += float(last.get("prompt_ms") or 0.0)+ toks += float(last.get("prompt_read") or (last.get("prompt_tokens") or 0) - (last.get("reused") or 0))+ return toks / (ms / 1000.0) if ms > 0 and toks > 0 else 0.0++ rate(0) # the first long read after a start faults the weights in+ by_value = {}+ for v in PIPE_VALUES:+ by_value[v] = [rate(v)]+ say(f" prompt chunks {'off' if v == 0 else 'evened out' if v == 1 else f'b/a {v}'}: {by_value[v][0]:.0f} tok/s")+ best = max(by_value, key=lambda k: by_value[k][0])+ confirm = {0: [], best: []}+ chosen = 0+ if best != 0:+ for r in range(SWEEP_ROUNDS):+ for k in ((0, best) if r % 2 == 0 else (best, 0)):+ confirm[k].append(rate(k))+ gains = [c / d - 1.0 for d, c in zip(confirm[0], confirm[best]) if d > 0]+ if len(gains) == SWEEP_ROUNDS and min(gains) > 0.0 and statistics.median(gains) > MIN_GAIN:+ chosen = best+ return chosen, {"pipe_sweep": {str(k): v for k, v in by_value.items()},+ "pipe_confirm": {str(k): v for k, v in confirm.items()}}++def pick(measured: dict, default_key, min_gain: float = MIN_GAIN):"""The key with the best median tok/s, or `default_key` unless the best beats it by more than min_gain."""med = {k: statistics.median(v) for k, v in measured.items() if v}@@ -150,7 +212,7 @@ def run(cfg: dict, say=print, start_engine=None) -> dict:tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"),json.loads((tpath / "token_type.json").read_text()))ids_list = [chat_ids(tok, p) for p in PROMPTS]- return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras())+ return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras(), doc_prompt(tok))def engine_args(cfg: dict) -> list[str]:@@ -199,7 +261,7 @@ def sweep(s, values: list, base_tune: dict, key: str, label: str, say) -> dict:return out-def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=()) -> dict:+def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=(), long_prompt=None) -> dict:t0 = time.time()report: dict = {}say(" Loading the model for the measurements ...")@@ -212,6 +274,16 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worked_workers = int(info.get("pool_workers", 0)) or Nones = Session(eng, ids_list)s.warm_up()+ # 0. a layer split's prompt chunks (prompt read speed; independent of the decode settings below)+ pipe = 0+ # the engine's own count of prompt stages where it reports one (a split can leave one, e.g.+ # --split-skip-if-fits), else the flag+ stages = info.get("prefill_stages")+ split = stages > 1 if isinstance(stages, int) else "--layer-split" in base_args+ if long_prompt is not None and split:+ say(" Measuring the prompt chunks of the layer split ...")+ pipe, rep_pipe = measure_pipe(eng, long_prompt, say)+ report.update(rep_pipe)# 1. the PCIe share, at the default draft floorby_pcie = sweep(s, sorted(set(PCIE_FRACS) | {round(d_pcie, 2)}), {"spec_min_p": d_minp}, "pcie_frac","PCIe share", say)@@ -235,6 +307,8 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workefinally:close(eng)settings = {}+ if pipe:+ settings["--prefill-pipe"] = str(int(pipe))if chosen != dflt:settings["--pcie-frac"] = f"{chosen[0]:.2f}"settings["--spec-min-p"] = f"{chosen[1]:.2f}"@@ -323,7 +397,7 @@ def close(eng):DEFAULTS = {"--pcie-frac": None, "--spec-min-p": "0.5", "--pool-workers": None, # None: the engine's own choice- "--adapt-every": None, "--adapt-swaps": None, "--adapt-decay": None}+ "--adapt-every": None, "--adapt-swaps": None, "--adapt-decay": None, "--prefill-pipe": None}def apply(args: list[str], settings: dict) -> list[str]:diff --git a/tools/test_calibrate.py b/tools/test_calibrate.pyindex 7ce1bdd0f..914634fbb 100644--- a/tools/test_calibrate.py+++ b/tools/test_calibrate.py@@ -22,8 +22,9 @@ import calibrate as CAL # noqa: E402class FakeEngine:"""Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`."""- def __init__(self, args, speed, info_workers=6, starts=None, adapt=None):+ def __init__(self, args, speed, info_workers=6, starts=None, adapt=None, read=None, reads=None):self.args = list(args)+ self.read, self.reads = read, reads # prompt read speed = read(prefill_pipe); the values it read withself.adapt_bonus = (adapt or {}).get(CAL.arg_value(args, "--adapt-swaps"), 1.0)w = CAL.arg_value(args, "--pool-workers")self.workers = int(w) if w else info_workers@@ -41,18 +42,84 @@ class FakeEngine:for _ in range(max_new):yield 1self.last = {"generated": max_new, "decode_ms": max_new / rate * 1000.0}+ if "prefill_pipe" in tune and self.read is not None:+ n = len(ids)+ self.last.update(prompt_tokens=n, prompt_read=n, prompt_ms=n / self.read(tune["prefill_pipe"]) * 1000.0)+ if self.reads is not None:+ self.reads.append(tune["prefill_pipe"])BASE = ["--pack", "p", "--spec", "4", "--spec-min-p", "0.5", "--max-context", "8192"]class Calibrate(unittest.TestCase):- def run_with(self, speed, workers=6, base=BASE, adapt=None):+ def run_with(self, speed, workers=6, base=BASE, adapt=None, read=None, reads=None):starts = []- res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts, adapt),- say=lambda *_: None)+ res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts, adapt, read, reads),+ say=lambda *_: None, long_prompt=lambda i, n: [1] * n)return res, starts+ def test_prefill_pipe_on_a_layer_split(self):+ # two stages that read fastest with b/a 1536: kept, and only one engine start measures it+ split = BASE + ["--layer-split", "auto"]+ reads = []+ res, _ = self.run_with(lambda f, p, w: 50.0, base=split, reads=reads,+ read=lambda v: {1536: 600.0, 768: 560.0, 1: 520.0}.get(v, 500.0))+ self.assertEqual(res["settings"].get("--prefill-pipe"), "1536")+ self.assertEqual(sorted(set(reads)), sorted(set(CAL.PIPE_VALUES)))+ self.assertIn("pipe_sweep", res["report"])+ self.assertEqual(CAL.arg_value(CAL.apply(split, res["settings"]), "--prefill-pipe"), "1536")++ def test_prefill_pipe_noise_stays_off(self):+ # 2% faster evened out: below MIN_GAIN, so the engine default (off) stays+ res, _ = self.run_with(lambda f, p, w: 50.0, base=BASE + ["--layer-split", "auto"],+ read=lambda v: 510.0 if v == 1 else 500.0)+ self.assertNotIn("--prefill-pipe", res["settings"])++ def test_prefill_pipe_must_win_every_round(self):+ # 1536 looks 12% faster in the sweep and the median, but one paired round reads slower: noise, it stays off+ calls = {}++ def read(v):+ calls[v] = calls.get(v, 0) + 1+ if v != 1536:+ return 500.0+ return [560.0, 560.0, 560.0, 480.0, 560.0, 560.0][min(calls[v], 6) - 1]+ res, _ = self.run_with(lambda f, p, w: 50.0, base=BASE + ["--layer-split", "auto"], read=read)+ self.assertNotIn("--prefill-pipe", res["settings"])+ self.assertEqual(len(res["report"]["pipe_confirm"]["1536"]), 3)++ def test_prefill_pipe_reads_the_same_text(self):+ # every read: the same stretch of text after a header of its own (only the chunks differ between values)+ tok = type("T", (), {"encode": lambda s, t, **k: [ord(c) for c in t]})()+ make = CAL.doc_prompt(tok)+ a, b = make(1, 300), make(2, 300)+ self.assertNotEqual(a[:40], b[:40])+ self.assertEqual(a[-320:], b[-320:])++ def test_prefill_pipe_only_on_a_layer_split(self):+ reads = []+ res, _ = self.run_with(lambda f, p, w: 50.0, read=lambda v: 600.0 if v == 1536 else 500.0, reads=reads)+ self.assertEqual(reads, [])+ self.assertNotIn("--prefill-pipe", res["settings"])+ # an old calibration's value goes when a new one does not keep it+ self.assertIsNone(CAL.arg_value(CAL.apply(BASE + ["--prefill-pipe", "800"], {}), "--prefill-pipe"))++ def test_prefill_pipe_follows_the_engines_stage_count(self):+ # --layer-split that left one prompt stage (the engine says prefill_stages=1): nothing to measure+ reads = []++ class OneStage(FakeEngine):+ def __init__(self, *a, **k):+ super().__init__(*a, **k)+ self.info["prefill_stages"] = 1+ res = CAL.measure(BASE + ["--layer-split", "auto"], [[1, 2, 3]] * 3,+ lambda a: OneStage(a, lambda f, p, w: 50.0, 6, None, None,+ lambda v: 600.0 if v == 1536 else 500.0, reads),+ say=lambda *_: None, long_prompt=lambda i, n: [1] * n)+ self.assertEqual(reads, [])+ self.assertNotIn("--prefill-pipe", res["settings"])+def test_defaults_kept_when_flat(self):res, _ = self.run_with(lambda f, p, w: 50.0)self.assertEqual(res["settings"], {})@@ -157,7 +224,8 @@ class Calibrate(unittest.TestCase):(tok / "token_type.json").write_text(json.dumps([1, 1]))seen = []saved = CAL.measure- CAL.measure = lambda args, ids_list, start_engine, say=print, extra=(): seen.append(args) or {}+ CAL.measure = lambda args, ids_list, start_engine, say=print, extra=(), long_prompt=None: (+ seen.append(args) or {})fake = type("ST", (), {"Tokenizer": lambda *a: type("T", (), {"encode": lambda s, t, **k: [0]})()})try:with mock.patch.dict(sys.modules, {"strata_tokenizer": fake}):