Skip to content

Commit 9a1e6f1

Browse files
nood-co1ashhart
authored andcommitted
fix: a failed admission no longer stops the 27B's concurrent CUDA scheduler
MultiDecoder._admit registered a stream before copying its prompt end into the prefix cache. When that copy raised (an allocation failure), the request got the error but the stream stayed registered without a token: the next round read its last token and failed every live stream, and the Scheduler's boxes.pop for it raised KeyError outside any handler. The worker thread exited, and every later request waited forever while /health answered ok. On two ranks the same KeyError stopped the worker before later requests could get the "restart both" error. - A stream is registered after its prompt-end copy, on both ranks. Successful admissions make the same calls in the same order, so rounds and drafted output are unchanged. - The Scheduler replies only to streams whose request still waits, so a dropped stream without a request no longer stops the loop. Test: tests/test_cuda_failed_admission.py on CPU stand-ins (the four tests fail without the fix). tests/cuda/test_qwen27_multi.py: one request's prompt-end copy fails, the others decode their serial tokens. (cherry picked from commit eb4156c)
1 parent 9270aeb commit 9a1e6f1

4 files changed

Lines changed: 235 additions & 3 deletions

File tree

‎src/tensorfold/cuda/scheduler.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,19 @@ def _admit(self, first=None) -> list[Stream]:
5757
done.append(stream)
5858
return done
5959

60+
def _reply(self, s: Stream, kind: str, value: Any) -> None:
61+
box = self.boxes.pop(id(s), None) # None: the stream's request has had its reply
62+
if box is not None:
63+
box.put((kind, value))
64+
6065
def _loop(self) -> None:
6166
while True:
6267
done = self._admit(None if self.decoder.live() else self.waiting.get()) # idle: wait for a request
6368
try:
6469
done += self.decoder.round()
6570
except Exception as exc: # noqa: BLE001 (the live requests fail)
6671
for s in self.decoder.drop():
67-
self.boxes.pop(id(s)).put(("error", exc))
72+
self._reply(s, "error", exc)
6873
self.decoder.finish(done)
6974
for s in done:
70-
self.boxes.pop(id(s)).put(("done", s.stats()))
75+
self._reply(s, "done", s.stats())

‎src/tensorfold/families/qwen3_5/cuda/multi.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,9 +113,9 @@ def _admit(self, s: Stream, hit) -> int:
113113
s.copies = CopyIndex() if self.allow_copy and s.draft and self.rank == 0 else None
114114
s.context = list(s.prompt)
115115
s.prefill_s, s.started = time.perf_counter() - t0, time.perf_counter()
116-
self.streams[s.sid] = s
117116
if s.draft:
118117
self.cache.add(list(s.prompt), private(s.st), s.snap)
118+
self.streams[s.sid] = s # last, so a failed copy leaves no stream behind
119119
return first
120120

121121
@torch.no_grad()

‎tests/cuda/test_qwen27_multi.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,49 @@ def go(i):
178178
assert serial == want and stats["cached"] == 0 and stats["min_rows"] == 1
179179

180180

181+
def test_a_failed_prompt_end_copy_fails_only_its_request(monkeypatch):
182+
"""One request's prompt-end copy runs out of memory: it gets the error, the others their serial tokens."""
183+
184+
w = _model()
185+
refs = {tuple(p): _serial(w, p, smp, 20) for p, smp in zip(PROMPTS, SAMPLINGS)}
186+
doomed = [2, 9, 4, 4, 1, 8, 8] # no other prompt has its length: only its copy fails
187+
188+
def failing(st):
189+
if st.pos == len(doomed):
190+
raise torch.OutOfMemoryError("CUDA out of memory (simulated at the prompt-end copy)")
191+
return private(st)
192+
193+
monkeypatch.setattr("tensorfold.families.qwen3_5.cuda.multi.private", failing)
194+
dec = _Oracle(w, refs, seed=5)
195+
sched = Scheduler(dec, max_streams=3)
196+
results: dict = {}
197+
198+
def go(key, prompt, sampling):
199+
got: list[int] = []
200+
try:
201+
results[key] = (got, sched.submit(prompt, 20, sampling, draft=True,
202+
emit=lambda new: got.extend(new) or False))
203+
except Exception as exc: # noqa: BLE001
204+
results[key] = (got, exc)
205+
206+
batches = [[(i, PROMPTS[i], SAMPLINGS[i]) for i in range(3)] + [("doomed", doomed, None)],
207+
[(i, PROMPTS[i], SAMPLINGS[i]) for i in (3, 4)]] # the second after the failure
208+
for batch in batches:
209+
threads = [threading.Thread(target=go, args=args, daemon=True) for args in batch]
210+
for t in threads:
211+
t.start()
212+
for t in threads:
213+
t.join(timeout=120)
214+
assert len(results) == len(PROMPTS) + 1, sorted(map(str, results))
215+
got, err = results["doomed"]
216+
assert got == [] and isinstance(err, torch.OutOfMemoryError), err
217+
for i, prompt in enumerate(PROMPTS):
218+
got, stats = results[i]
219+
assert isinstance(stats, dict) and got == refs[tuple(prompt)], (i, stats)
220+
assert sched.thread.is_alive() and not dec.streams
221+
assert all(entry[0] != doomed for entry in dec.cache.entries)
222+
223+
181224
def test_allocate_prices_drafts_against_the_curve():
182225
flat = lambda rows: 10.0 # noqa: E731 (rows cost nothing: every draft pays)
183226
assert allocate([[0.1, 0.5, 3.0], [0.2]], 2, 2.0, flat) == [3, 1]
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
"""A failed admission answers its own request; the concurrent CUDA scheduler goes on serving the others."""
2+
3+
import importlib
4+
import threading
5+
import time
6+
from types import SimpleNamespace
7+
8+
import pytest
9+
import torch
10+
11+
from tensorfold.cuda.scheduler import Scheduler
12+
from tensorfold.cuda.streams import Stream
13+
from tests.test_cuda_geometry import allocations # noqa: F401 (fixture: fake triton, so the module imports)
14+
15+
WAIT = 10.0 # seconds a reply may take; a stopped worker never replies
16+
17+
18+
class Request:
19+
"""``Scheduler.submit`` on its own thread; ``reply()`` is ("done", stats), ("error", exception) or None."""
20+
21+
def __init__(self, sched, prompt, count):
22+
self.got = []
23+
self.thread = threading.Thread(target=self._go, args=(sched, list(prompt), count), daemon=True)
24+
self.thread.start()
25+
26+
def _go(self, sched, prompt, count):
27+
try:
28+
self.got.append(("done", sched.submit(prompt, count, None, True, lambda new: False)))
29+
except Exception as exc: # noqa: BLE001
30+
self.got.append(("error", exc))
31+
32+
def reply(self):
33+
self.thread.join(WAIT)
34+
return self.got[0] if self.got else None
35+
36+
37+
def ask(sched, prompt, count):
38+
return Request(sched, prompt, count).reply()
39+
40+
41+
class St:
42+
"""A committed state: its position only (the stand-in prefill and copies hold no tensors)."""
43+
44+
def __init__(self, pos=0):
45+
self.pos, self.limit = pos, 0
46+
47+
48+
@pytest.fixture
49+
def decoders(monkeypatch, allocations): # noqa: F811
50+
"""``make(world)``: the 27B's ``MultiDecoder`` on CPU stand-ins; ``fail["copy"]`` fails the next prompt-end copy."""
51+
52+
multi = importlib.import_module("tensorfold.families.qwen3_5.cuda.multi")
53+
fail = {"copy": False}
54+
55+
def prefill(w, prompt, sampling, *rest, state=None):
56+
return St(len(prompt)), 7
57+
58+
def private(st):
59+
if fail["copy"]:
60+
fail["copy"] = False
61+
raise torch.OutOfMemoryError("CUDA out of memory (simulated at the prompt-end copy)")
62+
return St(st.pos)
63+
64+
monkeypatch.setattr(multi, "prefill", prefill)
65+
monkeypatch.setattr(multi, "prefill_tp", prefill)
66+
monkeypatch.setattr(multi, "private", private)
67+
monkeypatch.setattr(multi, "State", lambda w: St())
68+
monkeypatch.setattr(multi, "_share", lambda values, src, device: values) # two ranks: no NCCL here
69+
70+
def make(world=1):
71+
w = SimpleNamespace(config=SimpleNamespace(eos=(0,), vocab=10), norm=SimpleNamespace(device="cpu"),
72+
head=SimpleNamespace(n=10))
73+
dec = multi.MultiDecoder(w, None, allow_copy=False, world=world)
74+
dec.gate, dec.entered = threading.Event(), threading.Event() # a round waits at the gate while it is shut
75+
dec.gate.set()
76+
77+
def verify(plan, copied=None): # each window keeps its pending token, samples 5
78+
dec.entered.set()
79+
dec.gate.wait(WAIT)
80+
return [([pending], [-1]) for _, _, pending, _ in plan], None, None, None, [[5] for _ in plan]
81+
82+
dec._verify = verify
83+
dec._commit = lambda *args: None
84+
return dec
85+
86+
return make, fail
87+
88+
89+
A, B, C, D, E = ([k] * 5 + list(range(k * 10, k * 10 + 30)) for k in (1, 2, 3, 4, 5))
90+
91+
92+
def test_a_failed_prompt_end_copy_answers_its_request_and_the_worker_goes_on(decoders):
93+
make, fail = decoders
94+
dec = make()
95+
sched = Scheduler(dec, max_streams=4)
96+
assert ask(sched, A, 1)[0] == "done"
97+
fail["copy"] = True
98+
b = ask(sched, B, 64)
99+
assert b is not None and b[0] == "error" and isinstance(b[1], torch.OutOfMemoryError), b
100+
c, d = ask(sched, C, 1), ask(sched, D, 3) # D decodes two rounds
101+
assert c is not None and c[0] == "done", c
102+
assert d is not None and d[0] == "done", d
103+
assert sched.thread.is_alive()
104+
assert dec.live() == 0 and not dec.streams
105+
assert B not in [entry[0] for entry in dec.cache.entries]
106+
assert [entry[0] for entry in dec.cache.entries] == [A, C, D]
107+
108+
109+
def test_a_failed_admission_leaves_the_live_streams_decoding(decoders):
110+
make, fail = decoders
111+
dec = make()
112+
dec.gate.clear()
113+
sched = Scheduler(dec, max_streams=4)
114+
e = Request(sched, E, 3)
115+
assert dec.entered.wait(WAIT) # E is admitted; its first round waits
116+
fail["copy"] = True
117+
b = Request(sched, B, 64)
118+
deadline = time.monotonic() + WAIT
119+
while sched.waiting.qsize() == 0 and time.monotonic() < deadline:
120+
time.sleep(0.01)
121+
dec.gate.set() # B is admitted after E's first round
122+
got_b, got_e = b.reply(), e.reply()
123+
assert got_b is not None and got_b[0] == "error" and isinstance(got_b[1], torch.OutOfMemoryError), got_b
124+
assert got_e is not None and got_e[0] == "done", got_e
125+
assert sched.thread.is_alive() and not dec.streams
126+
127+
128+
def test_two_ranks_answer_every_later_request_with_the_restart_error(decoders):
129+
make, fail = decoders
130+
dec = make(world=2)
131+
sched = Scheduler(dec, max_streams=4)
132+
assert ask(sched, A, 1)[0] == "done"
133+
fail["copy"] = True
134+
b = ask(sched, B, 64)
135+
assert b is not None and b[0] == "error" and isinstance(b[1], torch.OutOfMemoryError), b
136+
assert isinstance(dec.broken, torch.OutOfMemoryError)
137+
for prompt in (C, D):
138+
got = ask(sched, prompt, 1)
139+
assert got is not None and got[0] == "error", got
140+
assert "restart both" in str(got[1])
141+
assert sched.thread.is_alive() and not dec.streams
142+
143+
144+
class FailingRound:
145+
"""A decoder whose first round fails; its ``drop()`` also returns a stream no request waits on."""
146+
147+
def __init__(self):
148+
self.streams, self.failed = [], False
149+
150+
def live(self):
151+
return len(self.streams)
152+
153+
def admit(self, s):
154+
self.streams.append(s)
155+
s.take([1])
156+
157+
def round(self):
158+
live = [s for s in self.streams if not s.done]
159+
if live and not self.failed:
160+
self.failed = True
161+
raise RuntimeError("a round failed")
162+
for s in live:
163+
s.take([2])
164+
return [s for s in live if s.done]
165+
166+
def drop(self):
167+
live = [s for s in self.streams if not s.done]
168+
self.streams = [s for s in self.streams if s.done]
169+
return live + [Stream([9], 1)]
170+
171+
def finish(self, done):
172+
gone = {id(s) for s in done}
173+
self.streams = [s for s in self.streams if id(s) not in gone]
174+
175+
176+
def test_a_dropped_stream_without_a_request_does_not_stop_the_worker():
177+
dec = FailingRound()
178+
sched = Scheduler(dec, max_streams=4)
179+
x = ask(sched, [1, 2, 3], 2)
180+
assert x is not None and x[0] == "error" and str(x[1]) == "a round failed", x
181+
y = ask(sched, [4, 5, 6], 2)
182+
assert y is not None and y[0] == "done", y
183+
assert sched.thread.is_alive() and not dec.streams
184+

0 commit comments

Comments
 (0)