From ac21812c1a620b868102642e681aed99b2efd960 Mon Sep 17 00:00:00 2001 From: SuperDistance <43229543+SuperDistance@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:16:13 -0700 Subject: [PATCH] serve: a long read gives way to a short request at the next chunk, not a chunk later or never (#656) The server sends BYIELD for a waiting request under half as long only when a PP line (or the 10 s heartbeat) arrives, and the engine looks for it at its next boundary. Where a boundary's own PP line is the only line for a while - every chunk of a --batch read on one GPU, and #2050's pipelined pieces - the BYIELD answers that line and reaches the engine after it has looked: the read gives way one boundary later, or never when that was the last one it could take. It is in time only where the engine saves a periodic checkpoint after the PP line (every 16,384 tokens by default). _control() now also calls on_quiet() whenever the engine has been quiet for half a second (its existing poll), and the solo and admission reads run the same check there as at a PP line. A BYIELD for a read that has ended is ignored by the engine, as before. serve/test_parallel.py: the fake engine takes --pp-every K (a PP line and a boundary every K chunks); a solo read and an admission must give way at their first boundary (both fail on main), and the rule (only to a much shorter request) holds on the poll too. Measured on one RTX 5090 (Swift 1.5 IQ3_S, --batch 4, the engine built from main), main's server and this one, two engine starts each (M F F M): a one-line request sent 0.2-8.6 s into a cold ~33K read, with nothing else decoding and with one stream decoding. Late (a boundary passed after the request waited): 28 of 40 runs on main, 12 of which never gave way; 4 of 40 with this change, all requests that started waiting 0.02-0.10 s before that boundary's PP line. Where main was late the short request's TTFT went 3.56 -> 1.70 s (nothing decoding) and 4.40 -> 1.57 s (one stream); where main never gave way 4.60 -> 1.51 s and 7.59 -> 2.35 s. Where both gave way at the same boundary, both requests' TTFTs were the same (medians within 0.02 s). On 2x RTX 5090 with #2050's STRATA_PIPED_READ_PIECE=8192: 6 of 12 late without it, none with it. --- serve/server.py | 45 ++++++++++++++++++++++++++---------------- serve/test_parallel.py | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 17 deletions(-) diff --git a/serve/server.py b/serve/server.py index ff1b935c..34269e42 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1064,10 +1064,11 @@ class StrataEngine: except (OSError, AttributeError): # the pipe is gone (or a restart's close() took the process): raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None - def _control(self, cancel, on_token, stop_when=None): + def _control(self, cancel, on_token, stop_when=None, on_quiet=None): """Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats. Calls on_token(id) for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE). `stop_when()` - true sends STOP once (the request is then read to its DONE).""" + true sends STOP once (the request is then read to its DONE). `on_quiet()` runs whenever the engine has been + quiet for half a second: between two PP lines of a read whose chunks take longer than that.""" stopped = False beat = time.monotonic() while True: @@ -1079,6 +1080,8 @@ class StrataEngine: if cancel.is_set() and not stopped: self._send("STOP") stopped = True + if on_quiet is not None: + on_quiet() if time.monotonic() - beat >= 10.0: beat = time.monotonic() yield None @@ -1370,21 +1373,25 @@ class StrataEngine: def others(): with self.slot_cv: return self.waiting > 0 - for x in self._control(cancel, pending.append, stop_when=others): + + def give_way(): # at a PP line, and between two far apart (the engine takes it at its next boundary) + nonlocal reserved + 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 + self.slot_claims.add(reserved) + if reserved is not None: + self._send(f"BYIELD {reserved}") + for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way): 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 - self.slot_claims.add(reserved) - if reserved is not None: - self._send(f"BYIELD {reserved}") + give_way() yield None phase = "none" # its DONE is read while pending: @@ -1480,17 +1487,21 @@ class StrataEngine: self._ctl_mode, self._ctl_result, self._yielded = "batch", None, None self._ctl_erred = False asked = False + + def ask(): # as give_way above, for the slot this admission reads into + nonlocal asked + if (not asked and not embeddings and yields < self.YIELDS_MAX and + self._shorter_waiting(len(prompt))): + self._send(f"BYIELD {slot}") + asked = True try: - for x in self._control(cancel, pending.append): + for x in self._control(cancel, pending.append, on_quiet=ask): 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 + ask() yield None except ValueError as e: # #1994: the engine says this slot is not free (its view and ours differ for a moment, or a diff --git a/serve/test_parallel.py b/serve/test_parallel.py index fbc8fb1c..1a638919 100644 --- a/serve/test_parallel.py +++ b/serve/test_parallel.py @@ -78,6 +78,7 @@ def window(): # one batch window: every active slot one token else: active[b] = [left, max_new, produced] log = open(args[args.index("--log") + 1], "a") if "--log" in args else None +PPK = int(args[args.index("--pp-every") + 1]) if "--pp-every" in args else 1 READF = "--readfield" in args # DONE's 15th field: the prompt tokens the engine read (a continued prompt: the 1 it copies) REUSE = "--reuse" in args # DONE's reused field as the engine gives it: a continued prompt is all held but its last def reused(ids): # token (the request's own output included), a fresh one the first 3 tokens @@ -131,6 +132,8 @@ while True: given = None for q in range(CH, len(ids) - 1, CH): time.sleep(STEP / 2) + if (q // CH) % PPK: # --pp-every K: a PP line and a boundary every K chunks (the pipelined groups' pieces) + continue print(f"PP {q} {len(ids)} 1 1", flush=True) held = [] while True: @@ -497,6 +500,19 @@ class ParallelService(unittest.TestCase): self.assertEqual(len(self.svc.history), 2) self.assertFalse(any(self.engine.slot_busy)) + def test_the_way_is_asked_between_far_apart_progress_lines(self): + """#656 when the PP lines come far apart (the pipelined groups' read in pieces of one chunk: one PP per piece, + at its end): the BYIELD goes out while the engine is quiet, so the read gives way at the first boundary after + the short request came. Asked only at a PP line, it reached the engine after that boundary's check and the + read gave way one piece later.""" + self.start(2, more=["--pp-every", "80"]) # a boundary every 80 chunks (~0.8 s): one in this read + long_q, short_q = "long " * 600, "short" + res = self.race(long_q, short_q) + self.assertEqual(res[long_q][0], "ok, done.") + self.assertEqual(res[short_q][0], "ok, done.") + yields = [x for x in self.log.read_text().splitlines() if x.startswith("YIELD ")] + self.assertEqual([int(x.split()[2]) for x in yields], [80 * 32], yields) + def test_three_requests_long_long_short_do_not_deadlock(self): """ENGINE_REVIEW finding 1 (0.1.41 check): two long prompts fill both slots, a short one arrives a moment later and wants one of them (the yield path). The reviewer's repro: long, long, short at 0.25 s steps. Every @@ -542,6 +558,25 @@ class ParallelService(unittest.TestCase): self.assertTrue(any(x.startswith("YIELD ") for x in log), log) self.assertFalse(any(self.engine.slot_busy)) + def test_an_admission_is_asked_between_far_apart_progress_lines(self): + """As above for a read admitted beside a decoding slot (BGEN, `ask()`): with one PP line per 80 chunks the + short request's BYIELD still reaches the first boundary.""" + self.start(3, more=["--pp-every", "80"]) + bg = threading.Thread(target=lambda: self.chat("LONGREPLY background", max_tokens=60)) + bg.start() + time.sleep(0.05) + long_q, short_q = "long " * 600, "short" + res = self.race(long_q, short_q) + bg.join(30) + self.assertEqual(res[long_q][0], "ok, done.") + self.assertEqual(res[short_q][0], "ok, done.") + log = self.log.read_text().splitlines() + admitted = [x.split() for x in log if x.startswith("BGEN ") and int(x.split()[2]) > 2600] + self.assertTrue(admitted, log) # the long read was an admission + yields = [x.split()[1:] for x in log if x.startswith("YIELD ")] + self.assertEqual(yields[:1], [[admitted[0][1], str(80 * 32)]], log) + self.assertFalse(any(self.engine.slot_busy)) + def test_no_way_given_to_a_long_one(self): """Two prompts of about the same length: no BYIELD (it only goes to a much shorter one).""" self.start(2) @@ -549,6 +584,13 @@ 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_no_way_given_to_a_long_one_between_far_apart_progress_lines(self): + """The ask between PP lines keeps the rule: a waiting request about as long gets no BYIELD there either.""" + self.start(2, more=["--pp-every", "80"]) + res = self.race("long " * 600, "lung " * 600) + 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)."""