Skip to content

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++

#465 a request left alone in a slot goes back to the solo path; docs: BATCHING.md for one GPU, measured on the RTX 5070

Niko1221038430ff201c
diff --git a/README.md b/README.md
index b702820a6..1b3a32602 100644
--- a/README.md
+++ b/README.md
@@ -134,7 +134,8 @@ Sizes, downloads and what fits where: [docs/MODELS.md](docs/MODELS.md). You can
- **Pictures:** say yes to "Images?" in setup, then click **Picture** in the chat, or attach them in your app
(AMD cards: on Linux through the processor, not on Windows yet).
- **From your phone or another PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key <secret>` - always with a key.
-- **Good to know:** it answers one request at a time. The first message of a chat is read in full (about 1 minute
+- **Good to know:** it answers one request at a time (several at once is opt-in: `"parallel": 2`,
+ [BATCHING.md](docs/BATCHING.md)). The first message of a chat is read in full (about 1 minute
per 30,000 tokens); follow-ups start in seconds.
More: [where your chats are stored](docs/INSTALL.md#where-things-are-stored), [the API](docs/DETAILS.md#using-it).
diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md
index 8b6e1bb96..e1679b385 100644
--- a/docs/AI_SETUP.md
+++ b/docs/AI_SETUP.md
@@ -173,7 +173,8 @@ line when it is ready; the engine log is `strata-<model>.log` in the Strata fold
- **Claude Code:** `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`, `ANTHROPIC_MODEL` set to a Claude model name it knows
(Strata ignores the name), and any `ANTHROPIC_AUTH_TOKEN` (or the configured key).
- **Thinking level:** `"reasoning_effort": "none" | "low" | "medium" | "high"` (default high).
-- Strata answers one request at a time. API details: [DETAILS.md](DETAILS.md#using-it).
+- Strata answers one request at a time; `"parallel": N` in the model's config (or setup `--parallel N`) decodes up to
+ N together ([BATCHING.md](BATCHING.md)). API details: [DETAILS.md](DETAILS.md#using-it).
## 9. When something fails
diff --git a/docs/BATCHING.md b/docs/BATCHING.md
index 9637b4700..cdce5fea4 100644
--- a/docs/BATCHING.md
+++ b/docs/BATCHING.md
@@ -1,16 +1,24 @@
-# Several conversations at once (batch slots)
+# Several requests at once (batch slots)
-By default Strata serves **one request at a time**: the others wait in the server's queue. With `--batch N`
-the engine keeps up to N conversations open and decodes them **together**: every verify window then carries one
-token of each conversation, so the dense weights, the shared expert and the head are read once per window for
-all of them. Combined with a layer split across several GPUs and `--batch-groups`, the cards also work on
-different conversations at the same time instead of waiting for each other.
+By default Strata serves **one request at a time**: the others wait in the server's queue. With `"parallel": N`
+(the engine's `--batch N`, also spelled `--slots N`) the engine keeps up to N conversations open and decodes them
+**together**: every verify window then carries one token of each conversation, so the dense weights, the shared
+expert, the head and every routed expert two conversations share are read once per window for all of them.
+Combined with a layer split across several GPUs and `--batch-groups`, the cards also work on different
+conversations at the same time instead of waiting for each other.
-It is opt-in and changes nothing when the options are absent.
+It is opt-in and changes nothing when the options are absent (#465; the engine part is PR #559).
## Turning it on
-Add the options to the `args` list of the model's config (`strata-<model>.json`) and restart:
+One GPU: add `"parallel": 2` to the model's config (`strata-<model>.json`) and restart, or run setup with
+`--parallel 2`. Setup says what it recommends for the card (below); a larger number is kept as asked, with a note.
+
+```
+"parallel": 2
+```
+
+With a layer split, the engine options go into the config's `args`:
```
"args": [ ..., "--batch", "8", "--batch-groups", "4", "--trim-stage-weights" ],
@@ -19,36 +27,79 @@ Add the options to the `args` list of the model's config (`strata-<model>.json`)
| Option | What it does |
| --- | --- |
-| `--batch N` (2..8) | up to N conversations decoded together. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. |
+| `"parallel": N` / `--batch N` / `--slots N` (2..8) | up to N conversations decoded together; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. |
| `--batch-groups G` | with a layer split: the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. |
-| `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's. The VRAM this frees goes to the expert cache - which is what makes batching pay, since several conversations together touch more distinct experts than one. Useful without `--batch` too. |
+| `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. |
-The server needs nothing else: it reads `--batch` / `--batch-groups` from the engine's arguments.
+The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots (a
+window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads
+the count the engine reports (`INFO batch_slots=N`), and `GET /v1/status` says it (`concurrency.serving`).
+
+### What a slot costs, and what setup recommends
+
+Every slot's session takes VRAM that the expert cache would otherwise hold: 0.56 GiB at a 32K context with 8-bit
+KV, more with a longer context unless the KV cache streams (`--kv-resident`: then only the attention's 32K window
+stays in VRAM, and each slot's whole KV cache takes pinned RAM - 1.6 GB at 128K). On a card whose experts mostly run
+on the CPU, a batch also reads about as many distinct experts as the requests one by one (different conversations
+route to different experts), so the gain is in **latency** (nobody waits for a whole answer), and a request alone
+runs a little slower (the smaller expert cache) - see the measurements below. Setup recommends as many slots as take
+at most a fifth of the expert cache (~VRAM less 5 GB), up to 4: 2 on a 12 GB card, 3 on 16 GB, 4 from 24 GB; none
+below 12 GB.
## How the server uses the slots
- **One request alone** runs on the usual solo path (verify windows with MTP drafts): the fastest single stream.
- **When a second request arrives**, the first is stopped (`STOP`) and continues in a batch slot with its prompt
plus what it generated so far - the engine's prompt cache holds exactly that, so nothing is read again - and the
- new request is admitted next to it.
+ new request is admitted next to it. A request in a slot decodes **without MTP drafts** (one token per window).
+- **A request left alone in a slot** (the others finished, nobody waits) goes back to the solo path: the slot is
+ stopped, the engine copies its sessions back and decodes with MTP drafts again (at most twice per request; with
+ `--prompt-cache 0` it stays in the slot; `STRATA_PARALLEL_SOLO=0` turns it off). The draft layer's own K/V was
+ built for another conversation then, but measured it accepted as many drafts (140 of 172) as a draft layer that
+ read the conversation (140 of 173).
+- **More requests than slots** wait for a free one (`/metrics` -> `live.slots` shows each slot: idle, reading or
+ decoding, its tokens and tok/s; `live.running` the requests in flight).
- **Each admission** reads the request's prompt through the usual prompt path (prompt cache and conversation
checkpoints included) and produces its first token there; the state is then copied into the slot. Admissions
- are taken one at a time; the slots already decoding pause meanwhile.
-- Slots are assigned so that consecutive requests land in different pipeline groups.
+ are taken one at a time, and **the slots decode between the prompt's chunks**: after each chunk (`--prefill`,
+ 2048-8192 tokens) they decode for half as long as the chunk took (`STRATA_BATCH_DECODE_SHARE`, default 0.5), so
+ a long prompt slows the others down instead of stopping them. The chunks are the ones one uninterrupted read
+ takes, so the prompt's arithmetic is unchanged.
+- **A long prompt gives way to a short one** (#656's cooperative preemption): when a request with a prompt under
+ half as long is waiting, the server sends `BYIELD`; at its next chunk boundary the long read stops, the part read
+ so far is copied into a slot, the short request is admitted, and the long one then goes on from its slot with the
+ same chunks (at most twice per request).
+- **Each slot is a conversation cache.** A finished slot keeps what it holds (the prompt, the answer, and the
+ checkpoint at the prompt's last turn boundary); the next turn of that conversation goes to that slot and the
+ engine copies its state back (50-60 ms for a short conversation) instead of reading the history again - also for
+ a client that drops the reply's thinking from the history (the checkpoint matches up to the new turn). A new
+ conversation takes an empty slot, else the one used longest ago.
+- Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`).
- A client that disconnects stops its slot (`BSTOP`); the others go on.
## Exactness
A batch row's arithmetic is the single-token window's, so with greedy decoding **every conversation of a batch
produces exactly the tokens it produces alone** - verified token by token for 8 concurrent conversations of 150
-tokens, with and without the pipeline (`tools/batch_test.py`). Two settings make that comparison exact:
+tokens, with and without the pipeline (`tools/batch_test.py`), and on one RTX 5070 for 4 conversations, for a long
+prompt read while two others decode, for a prompt that gave way and went on, for a next turn continued from its
+slot, and for a request stopped in its slot and continued on the solo path (`tools/batch_interleave_test.py`). These
+settings make the comparison exact:
- `STRATA_IQ_MT_MIN=1` (the multi-token CPU expert kernels for every group, as for the solo path's own
- exactness tests), and
+ exactness tests: by default an expert's rows round differently alone than in a group, so the output depends on
+ how many rows of a window share an expert - which differs between a batch and a request alone),
- `--pcie-frac 0`: the PCIe share of the missed experts is chosen per window from the window's misses, so the
- same expert can run on the GPU in one window and on the CPU in another, which rounds differently. With a share,
- outputs stay coherent but can drift apart after some tokens, as they would between two solo runs whose windows
- differ.
+ same expert can run on the GPU in one window and on the CPU in another, which rounds differently, and
+- `--adapt-every 1000000` (the VRAM tier fixed), and `--no-prefill-borrow` while a prompt is read beside decoding
+ slots: their windows then see the expert cache without the slots the prompt borrowed (those experts run on the
+ CPU).
+
+With the default settings the outputs stay coherent but drift apart after some tokens, as two solo runs whose
+windows differ can. Measured on the RTX 5070 (Q2_0, 4 conversations of 200 tokens, `tools/batch_test.py` without
+the settings above): one equal to its solo run, the others apart from token 0, 99 and 174 - the first token already
+differed for one, because the adaptive VRAM tier had moved experts between the solo runs and the batch; all four
+texts read as well as their solo runs.
Sampled requests (temperature, top_p, top_k, min_p, seed) are drawn row by row with the solo window's
counter-based draw (Philox(seed, position)).
@@ -56,16 +107,40 @@ counter-based draw (Philox(seed, position)).
## Limits (for now)
- Batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo path keeps
- its drafts, which is why a request alone is not put in a slot).
+ its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone).
- Repetition / frequency / presence penalties are not applied in batch windows.
-- `--batch-groups` needs every stage on its own GPU.
-- The slot sessions take VRAM (each one like the stage's own session; a few hundred MB per slot at 64K context
- with KV streaming) and pinned RAM for their streamed K/V.
+- A prompt shorter than one chunk is read in one piece (the slots wait for it); a read gives way only at a chunk
+ boundary, and not for pictures.
+- Admissions are one at a time: two new long prompts are read one after the other.
+- `--batch-groups` needs every stage on its own GPU; a pipelined slot is not kept as a conversation cache.
+- The slot sessions take VRAM (above) and, with KV streaming, pinned RAM.
## Measured
+One RTX 5070 (12 GB), Ryzen 5 7600, 64 GB DDR5, Q2_0, 32K context, through the HTTP server: C different requests
+sent at once (an 800-word essay each, 256 tokens per answer, greedy, thinking off), median of 3 rounds:
+
+| Concurrent | Setting | Total tok/s | Per request tok/s | First token: median / last of the round |
+| ---: | --- | ---: | ---: | ---: |
+| 1 | one at a time (default) | 74.3 | 83.6 | 0.4 s / 0.4 s |
+| 1 | `"parallel": 2` | 64.6 | 71.5 | 0.4 s / 0.4 s |
+| 1 | `"parallel": 4` | 58.2 | 63.9 | 0.5 s / 0.5 s |
+| 2 | one at a time | 71.6 | 77.3 | 2.1 s / 4.1 s |
+| 2 | `"parallel": 2` | 59.6 | 32.5 | 0.7 s / 0.9 s |
+| 2 | `"parallel": 4` | 55.7 | 30.3 | 0.4 s / 0.7 s |
+| 4 | one at a time | 70.7 | 79.6 | 6.0 s / 11.2 s |
+| 4 | `"parallel": 2` | 61.9 | 32.8 | 4.7 s / 9.2 s |
+| 4 | `"parallel": 4` | 63.8 | 17.3 | 0.9 s / 1.7 s |
+
+On this card the slots buy **waiting time, not speed**: the fourth of four requests starts after 1.7 s instead of
+11.2 s, but together they decode ~10-20 % slower than one after the other, and a request alone loses 13 % (2 slots)
+or 24 % (4 slots), because the slots' sessions (0.56 GiB each) come out of the expert cache and most experts run
+on the CPU: a batch window over 4 conversations reads 24 CPU experts per layer against ~8 for one, so it costs about
+what the 4 tokens cost one after the other (`strata batch:` in the engine log: 54 ms per 4-row window, ~20 ms per
+1-row window). Cards that hold most experts in VRAM, and a layer split, are where the slots also add speed (below).
+
A 4-GPU layer split (4 x 16 GB, PCIe Gen3), IQ3_S, `--batch 8 --batch-groups 4 --trim-stage-weights`, through
-the HTTP server, 400 tokens per answer, temperature 0.7:
+the HTTP server, 400 tokens per answer, temperature 0.7 (PR #559):
| Concurrent requests | Per request | Total |
| ---: | ---: | ---: |
@@ -90,11 +165,13 @@ two long conversations alternating through the HTTP server: the first turns took
## Testing
-Three scripts drive a built engine or a running server; each exits non-zero on a failure.
+Four scripts drive a built engine or a running server; each exits non-zero on a failure. `serve/test_parallel.py`
+tests the server's side with a scripted engine (no GPU).
| Script | What it checks |
| --- | --- |
| `tools/batch_test.py` | the same prompts alone (`GEN`) and together in the batch slots (`BGEN`): every slot's greedy tokens equal its solo tokens; prints the aggregate rate. `--batch-groups` in `--extra` tests the pipeline, `--keys "temperature=0.7"` the sampled rows. |
+| `tools/batch_interleave_test.py` | a long prompt read while two slots decode, a prompt that gives way (`BYIELD`) and goes on, and a next turn continued from its slot: each equal to its solo tokens. |
| `tools/parking_test.py` | a follow-up to a conversation decodes the same tokens whether its state stayed live or came back from the parking cache (with a layer split: every stage's image). |
| `tools/early_close_test.py` | a client that stops reading a streamed answer early (alone, and with a second request running) does not leave its tokens to the next request (server). |
@@ -103,6 +180,8 @@ For exact comparisons pass `--pcie-frac 0 --adapt-every 1000000` (and the script
```
python3 tools/batch_test.py --exe engine/strata --config strata-<model>.json --batch 8 --n 8 \
--extra "--layer-split 12,24,36 --trim-stage-weights --batch-groups 4 --pcie-frac 0 --adapt-every 1000000"
+python3 tools/batch_interleave_test.py --exe engine/strata --config strata-<model>.json \
+ --extra "--pcie-frac 0 --adapt-every 1000000 --no-prefill-borrow"
python3 tools/parking_test.py --exe engine/strata --config strata-<model>.json \
--extra "--layer-split 12,24,36 --conversation-cache-mib 8192 --conversation-cache-slots 4 --pcie-frac 0"
STRATA_KEY=<key> python3 tools/early_close_test.py http://127.0.0.1:8080
@@ -118,8 +197,11 @@ On top of `GEN` / `GENI`:
| `BGENI <slot> <max_new> [keys] <file> <ids>` | in | the same with images |
| `BADM <slot> <1/0>` | out | after the admission's `DONE`: 1 = it continues in the slot, 0 = it ended |
| `BT <slot> <id>` | out | a token of that slot |
-| `BDONE <slot> <generated> <stop/length/cancel> <ms>` | out | the slot is free again |
+| `BDONE <slot> <generated> <stop/length/cancel> <ms>` | out | the slot is free again (it keeps its conversation) |
| `BSTOP <slot>` | in | end that slot at its next window |
+| `BYIELD <slot>` | in | the prompt being read gives way at its next chunk boundary; its part read waits in `<slot>` (the admission's own, or a free slot for a solo request) |
+| `YIELDED <slot> <tokens>` | out | before the `DONE cancel` of a read that gave way: the request is sent again later and goes on from there |
+| `INFO ... batch_slots=N` | out | the slots the engine runs (only with `--batch`) |
`tools/batch_test.py` drives the engine directly: the same prompts alone, then together, compared token by token,
and the aggregate rate.
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index d71e8bff2..1238ae704 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -683,8 +683,9 @@ sizes and K/V bytes reused during capture. `STRATA_SNAPSHOT_FULL_CAPTURE=1` disa
retention for diagnostic comparisons. Snapshots are not
persisted across restarts.
-**Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats
-re-reads the other one unless the opt-in cache above is enabled); 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 unless `"parallel": N` is set (opt-in batch slots, up to N requests
+decoded together: [BATCHING.md](BATCHING.md)), and one conversation cached at a time (switching between two chats
+re-reads the other one unless the opt-in cache above is enabled, or each conversation keeps its own batch slot); 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
diff --git a/serve/server.py b/serve/server.py
index 241503542..9e669827c 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -843,6 +843,19 @@ class StrataEngine:
self.slot_cv.notify_all()
return True
+ SOLO_AGAIN_MAX = 2 # how often a request left alone in a slot goes back to the solo path
+ SOLO_AGAIN_MIN_LEFT = 32 # ... only with at least this many tokens still allowed (max_tokens)
+
+ def _may_go_solo(self, left: int, times: int, embeddings) -> bool:
+ """A request decoding in a slot that is alone now (no other slot busy, nobody waiting) goes back to the solo
+ path with its MTP drafts: the engine continues it from the slot's sessions (its slot cache; INFO
+ slot_cache=1). STRATA_PARALLEL_SOLO=0 keeps it in the slot."""
+ if (embeddings or times >= self.SOLO_AGAIN_MAX or left < self.SOLO_AGAIN_MIN_LEFT or
+ not (self.info or {}).get("slot_cache") or os.environ.get("STRATA_PARALLEL_SOLO") == "0"):
+ return False
+ with self.slot_cv:
+ return sum(1 for b in self.slot_busy if b) == 1 and self.waiting == 0
+
def _shorter_waiting(self, plen: int) -> bool:
"""#656: someone waits for the control lines with a prompt under half this one's: worth giving way to."""
with self.slot_cv:
@@ -870,144 +883,169 @@ class StrataEngine:
slot, gen0, reserved = None, None, None
phase = "none" # solo -> (admit -> slot) ; "done" once the engine has finished with this request
stop_sent = False
- yields = 0
+ yields, solo_again = 0, 0
try:
- with self.slot_cv:
- alone = not any(self.slot_busy) and self.waiting == 0
- if alone and left > 1:
- head = f"GENI {left}{keys} {embeddings}" if embeddings else f"GEN {left}{keys}"
- self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
- phase = "solo"
- self._ctl_mode, self._ctl_result, self._yielded = "solo", None, None
- def others():
- with self.slot_cv:
- return self.waiting > 0
- for x in self._control(cancel, pending.append, stop_when=others):
+ while True: # a request in a slot that is left alone goes back to the solo path
+ if not holding:
+ ok = yield from self._take_control(cancel, len(prompt))
+ if not ok:
+ return
+ holding = True
+ with self.slot_cv:
+ alone = not any(self.slot_busy) and self.waiting == 0
+ if alone and left > 1:
+ head = f"GENI {left}{keys} {embeddings}" if embeddings else f"GEN {left}{keys}"
+ self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
+ phase = "solo"
+ self._ctl_mode, self._ctl_result, self._yielded = "solo", None, None
+ def others():
+ with self.slot_cv:
+ return self.waiting > 0
+ for x in self._control(cancel, pending.append, stop_when=others):
+ while pending:
+ t = pending.pop(0)
+ out.append(t)
+ yield t
+ if x is None: # a heartbeat (False: a token, flushed above)
+ if (reserved is None and not out and not embeddings and yields < self.YIELDS_MAX and
+ self._shorter_waiting(len(prompt))):
+ with self.slot_cv: # the slot the part read will wait in
+ reserved = self.pick_slot(prompt)
+ if reserved is not None:
+ self.slot_busy[reserved] = True
+ if reserved is not None:
+ self._send(f"BYIELD {reserved}")
+ yield None
+ phase = "none" # its DONE is read
while pending:
t = pending.pop(0)
out.append(t)
yield t
- if x is None: # a heartbeat (False: a token, flushed above)
- if (reserved is None and not out and not embeddings and yields < self.YIELDS_MAX and
- self._shorter_waiting(len(prompt))):
- with self.slot_cv: # the slot the part read will wait in
- reserved = self.pick_slot(prompt)
- if reserved is not None:
- self.slot_busy[reserved] = True
- if reserved is not None:
- self._send(f"BYIELD {reserved}")
- yield None
- phase = "none" # its DONE is read
- while pending:
- t = pending.pop(0)
- out.append(t)
- yield t
- if self._yielded is not None and reserved is not None and self._yielded[0] == reserved:
- slot, reserved = reserved, None # gave way: the read goes on in that slot (below)
- elif reserved is not None: # it did not give way: the slot is free again
- with self.slot_cv:
- self.slot_busy[reserved] = False
- self.slot_cv.notify_all()
- reserved = None
- if slot is None:
- finish = (self.last or {}).get("finish") if isinstance(self.last, dict) else None
- left = int(max_new) - len(out)
- if cancel.is_set() or left <= 0 or finish in ("stop", "length") or (out and out[-1] in EOS_IDS):
- return
- prompt = list(ids) + out # promoted: it continues in a batch slot from here
- while True:
- if slot is None:
- # a free slot (they free themselves at BDONE, which needs no control lines): the one that holds
- # the start of this prompt (its conversation's last turn), else the one used longest ago
- with self.slot_cv:
- while True:
- slot = self.pick_slot(prompt)
- if slot is not None:
- self.slot_busy[slot] = True
- break
- self.slot_cv.wait(timeout=10.0)
- if cancel.is_set():
- return
- if self._yielded is not None: # it gave way: the others waiting then go first
- self.slot_held[slot] = list(prompt[:self._yielded[1]])
- self._yielded = None
- yields += 1
- self.ctl.release()
- holding = False
- with self.slot_cv:
- epoch = self.ctl_epoch
- ok = yield from self._take_control(cancel, len(prompt), after_epoch=epoch)
- if not ok:
- return
- holding = True
- while not self.slot_q[slot].empty():
- self.slot_q[slot].get_nowait()
- head = f"BGENI {slot} {left}{keys} {embeddings}" if embeddings else f"BGEN {slot} {left}{keys}"
- live = {"slot": slot, "state": "reading", "prompt_tokens": len(prompt), "generated": 0,
- "started": time.time(), "first_token": None}
- self.slot_live[slot] = live
- self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
- self.slot_held[slot] = [] # the admission overwrites what the slot held
- phase = "admit"
- self._ctl_mode, self._ctl_result, self._yielded = "batch", None, None
- asked = False
- for x in self._control(cancel, pending.append):
+ if self._yielded is not None and reserved is not None and self._yielded[0] == reserved:
+ slot, reserved = reserved, None # gave way: the read goes on in that slot (below)
+ elif reserved is not None: # it did not give way: the slot is free again
+ with self.slot_cv:
+ self.slot_busy[reserved] = False
+ self.slot_cv.notify_all()
+ reserved = None
+ if slot is None:
+ finish = (self.last or {}).get("finish") if isinstance(self.last, dict) else None
+ left = int(max_new) - len(out)
+ if cancel.is_set() or left <= 0 or finish in ("stop", "length") or (out and out[-1] in EOS_IDS):
+ return
+ prompt = list(ids) + out # promoted: it continues in a batch slot from here
+ while True:
+ if slot is None:
+ # a free slot (they free themselves at BDONE, which needs no control lines): the one that holds
+ # the start of this prompt (its conversation's last turn), else the one used longest ago
+ with self.slot_cv:
+ while True:
+ slot = self.pick_slot(prompt)
+ if slot is not None:
+ self.slot_busy[slot] = True
+ break
+ self.slot_cv.wait(timeout=10.0)
+ if cancel.is_set():
+ return
+ if self._yielded is not None: # it gave way: the others waiting then go first
+ self.slot_held[slot] = list(prompt[:self._yielded[1]])
+ self._yielded = None
+ yields += 1
+ self.ctl.release()
+ holding = False
+ with self.slot_cv:
+ epoch = self.ctl_epoch
+ ok = yield from self._take_control(cancel, len(prompt), after_epoch=epoch)
+ if not ok:
+ return
+ holding = True
+ while not self.slot_q[slot].empty():
+ self.slot_q[slot].get_nowait()
+ head = f"BGENI {slot} {left}{keys} {embeddings}" if embeddings else f"BGEN {slot} {left}{keys}"
+ live = {"slot": slot, "state": "reading", "prompt_tokens": len(prompt), "generated": 0,
+ "started": time.time(), "first_token": None}
+ self.slot_live[slot] = live
+ self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
+ self.slot_held[slot] = [] # the admission overwrites what the slot held
+ phase = "admit"
+ self._ctl_mode, self._ctl_result, self._yielded = "batch", None, None
+ asked = False
+ for x in self._control(cancel, pending.append):
+ while pending:
+ t = pending.pop(0)
+ out.append(t)
+ yield t
+ if x is None:
+ if (not asked and not embeddings and yields < self.YIELDS_MAX and
+ self._shorter_waiting(len(prompt))):
+ self._send(f"BYIELD {slot}")
+ asked = True
+ yield None
+ cont = bool(self._ctl_result and self._ctl_result[1])
+ phase = "slot" if cont else "none"
while pending:
t = pending.pop(0)
out.append(t)
yield t
- if x is None:
- if (not asked and not embeddings and yields < self.YIELDS_MAX and
- self._shorter_waiting(len(prompt))):
- self._send(f"BYIELD {slot}")
- asked = True
- yield None
- cont = bool(self._ctl_result and self._ctl_result[1])
- phase = "slot" if cont else "none"
- while pending:
- t = pending.pop(0)
- out.append(t)
- yield t
- if not cont and self._yielded is not None and self._yielded[0] == slot and not cancel.is_set():
- continue # gave way: again once the shorter request is in
- break
- self.ctl.release()
- holding = False
- if not cont:
- return
- live.update(state="decoding", first_token=time.time(), generated=len(out))
- gen0 = len(out) - 1 # the admission's own token: the slot feeds it first
- while True:
- try:
- line = self.slot_q[slot].get(timeout=10.0)
- except queue.Empty:
- if cancel.is_set() and not stop_sent:
- self._send(f"BSTOP {slot}")
- stop_sent = True
- yield None
- continue
- if line is None:
- phase = "none"
- raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
- if line.startswith("BT "):
- t = int(line.split()[2])
- out.append(t)
- live["generated"] = len(out)
- if cancel.is_set():
- if not stop_sent:
+ if not cont and self._yielded is not None and self._yielded[0] == slot and not cancel.is_set():
+ continue # gave way: again once the shorter request is in
+ break
+ self.ctl.release()
+ holding = False
+ if not cont:
+ return
+ live.update(state="decoding", first_token=time.time(), generated=len(out))
+ gen0 = len(out) - 1 # the admission's own token: the slot feeds it first
+ going_solo = False
+ while True:
+ try:
+ line = self.slot_q[slot].get(timeout=10.0)
+ except queue.Empty:
+ if cancel.is_set() and not stop_sent:
self._send(f"BSTOP {slot}")
stop_sent = True
+ yield None
continue
- yield t
- elif line.startswith("BDONE "):
- phase = "none"
- f = line.split()
- if len(f) >= 5 and isinstance(self.last, dict):
- self.last = {**self.last, "finish": f[3], "decode_ms": float(f[4]),
- "generated": int(f[2]) if f[2].isdigit() else self.last.get("generated")}
- # what the slot's sessions hold now: the prompt and every token fed (all but the last one)
- self.slot_held[slot] = list(prompt) + out[gen0:-1] if len(out) > gen0 else []
- return
+ if line is None:
+ phase = "none"
+ raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
+ if line.startswith("BT "):
+ t = int(line.split()[2])
+ out.append(t)
+ live["generated"] = len(out)
+ if cancel.is_set():
+ if not stop_sent:
+ self._send(f"BSTOP {slot}")
+ stop_sent = True
+ continue
+ yield t
+ if not going_solo and not stop_sent and self._may_go_solo(int(max_new) - len(out), solo_again,
+ embeddings):
+ self._send(f"BSTOP {slot}") # alone now: on with the drafts (below)
+ going_solo = True
+ elif line.startswith("BDONE "):
+ phase = "none"
+ f = line.split()
+ if len(f) >= 5 and isinstance(self.last, dict):
+ self.last = {**self.last, "finish": f[3], "decode_ms": float(f[4]),
+ "generated": int(f[2]) if f[2].isdigit() else self.last.get("generated")}
+ # what the slot's sessions hold now: the prompt and every token fed (all but the last one)
+ self.slot_held[slot] = list(prompt) + out[gen0:-1] if len(out) > gen0 else []
+ if (going_solo and f[3:4] == ["cancel"] and not cancel.is_set() and len(out) < int(max_new)
+ and not (out and out[-1] in EOS_IDS)):
+ # the solo path continues it: the engine copies the slot's sessions back (all but the
+ # last token are in them) and decodes with MTP drafts again
+ self.slot_live[slot] = None
+ self.slot_used[slot] = time.time()
+ with self.slot_cv:
+ self.slot_busy[slot] = False
+ self.slot_cv.notify_all()
+ slot, gen0 = None, None
+ prompt, left = list(ids) + out, int(max_new) - len(out)
+ solo_again += 1
+ btrace("back to the solo path")
+ break
+ return
finally:
# a consumer that left early (or an error): keep the engine and this server in step
btrace("finally phase", phase, "slot", slot, "holding", holding)
diff --git a/serve/test_parallel.py b/serve/test_parallel.py
index 7369ee8c0..a56436536 100644
--- a/serve/test_parallel.py
+++ b/serve/test_parallel.py
@@ -36,14 +36,18 @@ def reader():
lines.put(l)
lines.put(None)
threading.Thread(target=reader, daemon=True).start()
-print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else ""), flush=True)
+print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else "") +
+ (" slot_cache=1" if "--slotcache" in args else ""), flush=True)
print("READY 4096 stop", flush=True)
-R = list(b"ok, done.") + [257]
-def reply(ids): # the rest of R after what the prompt already ends with (a request continued in a slot)
+LONG = list(b"LONGREPLY")
+def reply(ids): # the rest of the reply after what the prompt already ends with (a request continued)
ids = [int(x) for x in ids]
+ long_one = any(ids[i:i + len(LONG)] == LONG for i in range(len(ids)))
+ R = list(b"ok, " + b"la " * 15 + b"done." if long_one else b"ok, done.") + [257]
k = max(k for k in range(len(R)) if k == 0 or ids[-k:] == R[:k])
return R[k:]
active = {} # slot -> [tokens left, max_new, produced]
+stopped = set() # BSTOPped slots: they end "cancel"
def window(): # one batch window: every active slot one token
for b in sorted(active):
left, max_new, produced = active[b]
@@ -51,7 +55,9 @@ def window(): # one batch window: every active slot one token
produced += 1
print(f"BT {b} {t}", flush=True)
if t == 257 or produced >= max_new:
- print(f"BDONE {b} {produced} {'stop' if t == 257 else 'length'} 1.0", flush=True)
+ fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length'
+ stopped.discard(b)
+ print(f"BDONE {b} {produced} {fin} 1.0", flush=True)
del active[b]
else:
active[b] = [left, max_new, produced]
@@ -69,6 +75,7 @@ while True:
b = int(line.split()[1])
if b in active:
active[b][1] = 0
+ stopped.add(b)
continue
if line.startswith(("GEN ", "BGEN ")):
f = line.split()
@@ -185,7 +192,7 @@ class PickSlot(unittest.TestCase):
class ParallelService(unittest.TestCase):
"""The real StrataEngine and Service over HTTP, the fake engine behind them."""
- def start(self, slots, fit=None):
+ def start(self, slots, fit=None, slot_cache=False):
import serve.server as server
self.tmp = tempfile.TemporaryDirectory()
script = Path(self.tmp.name) / "fake_strata.py"
@@ -193,6 +200,7 @@ class ParallelService(unittest.TestCase):
self.log = Path(self.tmp.name) / "requests.log"
real = server.subprocess.Popen
extra = ["--batch", str(slots)] + (["--fit", str(fit)] if fit is not None else []) + ["--log", str(self.log)]
+ extra += ["--slotcache"] if slot_cache else []
with mock.patch.object(server.subprocess, "Popen",
lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
self.engine = StrataEngine("strata", extra)
@@ -324,6 +332,26 @@ class ParallelService(unittest.TestCase):
self.assertEqual(sorted(r[0] for r in res.values()), ["ok, done."] * 2)
self.assertFalse(any(x.startswith("YIELD ") for x in self.log.read_text().splitlines()))
+ def test_left_alone_it_goes_back_to_the_solo_path(self):
+ """A request decoding in a slot whose neighbour finished goes back to the solo path (MTP drafts), continued
+ from its slot - only with an engine that keeps the slots' conversations (INFO slot_cache=1)."""
+ self.start(2, slot_cache=True)
+ res = {}
+ long = threading.Thread(target=lambda: res.setdefault("long", self.chat("LONGREPLY please", max_tokens=200)))
+ long.start()
+ time.sleep(0.05)
+ short = self.chat("short", max_tokens=200)
+ long.join(30)
+ self.assertEqual(short["choices"][0]["message"]["content"], "ok, done.")
+ self.assertEqual(res["long"]["choices"][0]["message"]["content"], "ok, " + "la " * 15 + "done.")
+ kinds = [x.split()[0] for x in self.log.read_text().splitlines()]
+ # solo, then both in slots, then the long one alone again: a GEN after the BGENs
+ self.assertIn("BGEN", kinds)
+ self.assertEqual(kinds[-1], "GEN", kinds)
+ self.assertFalse(any(self.engine.slot_busy))
+ with self.svc.status_lock:
+ self.assertEqual(len(self.svc.history), 2)
+
def test_next_turn_goes_back_to_its_slot(self):
self.start(2)
a = "conversation A, first turn"
diff --git a/tools/batch_interleave_test.py b/tools/batch_interleave_test.py
index 9b2a1a7ff..a59109ae9 100644
--- a/tools/batch_interleave_test.py
+++ b/tools/batch_interleave_test.py
@@ -6,6 +6,13 @@ chunks interleaved with their windows), and a conversation's next turn continued
2. the same in the slots: A in slot 0, B in slot 1 next to it, then C in slot 2 while A and B decode - every slot's
tokens must equal its solo tokens
3. A's next turn (BGEN into slot 0, which still holds A): read from the slot, its tokens must equal the solo next turn
+ 4. a long prompt D gives way (BYIELD) at its first chunk boundary, a short E is admitted, D goes on from its slot
+ while E decodes: both equal their solo tokens
+ 6. A in a slot, stopped after 50 tokens and continued on the solo path (GEN of A + its tokens, from the slot): the
+ whole equals solo A (what the server does with a request left alone in a slot)
+ 5. (a measurement) a solo next turn continued from a slot: the drafts accepted
+ 7. F, A's history as a client sends it back without the reply's thinking, from slot 1's turn checkpoint: equal to
+ F solo (which continues from the same checkpoint of the live chain)
Exact comparisons need the same settings as batch_test.py (this script sets STRATA_IQ_MT_MIN=1):
python tools/batch_interleave_test.py --exe build/strata --config strata-<model>.json \\
@@ -72,6 +79,12 @@ def main():
sA, _ = run(eng, out, f"GEN {M} {ids(A)}")
A2 = A + sA + chat("Now do the same in Rust.")
sA2, _ = run(eng, out, f"GEN {M} {ids(A2)}")
+ # F: A's history as a client sends it back WITHOUT the reply's thinking - it shares A only up to A's last turn
+ # boundary (the checkpoint there); solo it continues from that checkpoint of the live chain
+ turn_at = max(i for i, t in enumerate(A) if t == A[0]) # A[0] is <|im_start|>
+ F = A[:turn_at] + tok.encode("<|im_start|>assistant\nA short answer.<|im_end|>\n", parse_special=True) + \
+ chat("Now in Go.")
+ sF, _ = run(eng, out, f"GEN {M} {ids(F)}")
sB, _ = run(eng, out, f"GEN {M} {ids(B)}")
sC, _ = run(eng, out, f"GEN {M} {ids(C)}")
sD, _ = run(eng, out, f"GEN {M} {ids(D)}")
@@ -161,6 +174,27 @@ def main():
d = next((k for k in range(min(len(got4[s]), len(ref))) if got4[s][k] != ref[k]), None)
print(f"slot {s} {name}: {len(got4[s])} tokens, solo {len(ref)}: "
f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
+ # 6. back to the solo path (what the server does with a request left alone in a slot): A in slot 1, BSTOP after
+ # 50 tokens, then GEN of A + what it produced - the engine continues from the slot with MTP drafts again
+ first, cont = run(eng, out, f"BGEN 1 {M} {ids(A)}", slot=1)
+ got6, sent = list(first), False
+ while cont:
+ l = eng.pending.pop(0) if eng.pending else next(out)
+ if l.startswith("BT 1 "):
+ got6.append(int(l.split()[2]))
+ if len(got6) >= 50 and not sent:
+ eng.send("BSTOP 1")
+ sent = True
+ elif l.startswith("BDONE 1 "):
+ break
+ tail6, _ = run(eng, out, f"GEN {M - len(got6)} {ids(A + got6)}") if len(got6) < M else ([], None)
+ same = got6 + tail6 == sA
+ ok &= same
+ both = got6 + tail6
+ d = next((k for k in range(min(len(both), len(sA))) if both[k] != sA[k]), None)
+ print(f"A in a slot, then solo again after {len(got6)} tokens: {len(both)} tokens, solo {len(sA)}: "
+ f"{'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
+
# 5. (a measurement, not a check) a SOLO next turn continued from slot 0: its tokens are exact either way, but the
# draft layer's own K/V was built for another conversation, so fewer drafts may be accepted than in a solo next
# turn whose drafter read the conversation (A2 in step 1)
@@ -174,13 +208,27 @@ def main():
print(f"solo next turn from a slot: drafts accepted {f[6]} of {f[7]} ({f[1]} tokens in {f[4]} ms)",
flush=True)
break
+ # 7. F from slot 1's turn checkpoint (slot 1 holds A since step 6): the engine log says "(its turn checkpoint)"
+ first, cont = run(eng, out, f"BGEN 2 {M} {ids(F)}", slot=2)
+ got7 = list(first)
+ while cont:
+ l = eng.pending.pop(0) if eng.pending else next(out)
+ if l.startswith("BT 2 "):
+ got7.append(int(l.split()[2]))
+ elif l.startswith("BDONE 2 "):
+ break
+ same = got7 == sF
+ ok &= same
+ d = next((k for k in range(min(len(got7), len(sF))) if got7[k] != sF[k]), None)
+ print(f"F (A's history without the reply's thinking) from slot 1's turn checkpoint: {len(got7)} tokens, solo "
+ f"{len(sF)}: {'IDENTICAL' if same else f'DIFFERS at {d}'}", flush=True)
eng.send("QUIT")
eng.p.wait(timeout=180)
log = Path(eng.log_path).read_text(errors="replace")
for l in log.splitlines():
if "drafts accepted" in l:
print(" log:", l.split("strata serve: ")[-1][:160], flush=True)
- for key in ("gave back", "takes", "the prompt was read in", "gives way"):
+ for key in ("gave back", "its turn checkpoint", "takes", "the prompt was read in", "gives way"):
print(f"engine log '{key}': {log.count(key)} lines", flush=True)
return 0 if ok else 2