|
| 1 | +"""The server's client-gone stop and per-token failures on the 27B decoders (synthetic weights): a request that |
| 2 | +stops early sends a prefix of the exact reply, one that fails raises, and the requests beside and after them are |
| 3 | +exact.""" |
| 4 | + |
| 5 | +import threading |
| 6 | + |
| 7 | +import pytest |
| 8 | +import torch |
| 9 | + |
| 10 | +if not torch.cuda.is_available(): |
| 11 | + pytest.skip("CUDA only", allow_module_level=True) |
| 12 | + |
| 13 | +from test_qwen27_multi import PROMPTS, SAMPLINGS, _Oracle, _model, _serial # noqa: E402 |
| 14 | + |
| 15 | +from tensorfold.cuda import server # noqa: E402 |
| 16 | +from tensorfold.cuda.scheduler import Scheduler # noqa: E402 |
| 17 | +from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine # noqa: E402 |
| 18 | +from tensorfold.server.cancellation import RequestCancelled # noqa: E402 |
| 19 | + |
| 20 | +COUNT = 20 |
| 21 | + |
| 22 | + |
| 23 | +class _Tok: |
| 24 | + def decode(self, ids, **kwargs): |
| 25 | + return "".join(chr(0x100 + int(t)) for t in ids) # one printable character a token |
| 26 | + |
| 27 | + |
| 28 | +def _app(engine): |
| 29 | + app = server.App.__new__(server.App) |
| 30 | + app.engine, app.served, app.tok = engine, "qwen27-synthetic", _Tok() |
| 31 | + app.default_thinking = False |
| 32 | + app.sampling = {"temperature": 0.0, "top_k": 0, "top_p": 1.0} |
| 33 | + app.max_tokens = COUNT |
| 34 | + app.native_context_window = app.context_window = 0 |
| 35 | + app.lock = threading.Lock() |
| 36 | + return app |
| 37 | + |
| 38 | + |
| 39 | +def _engine(w, scheduler=None): |
| 40 | + engine = Qwen27Engine.__new__(Qwen27Engine) |
| 41 | + engine.torch, engine.tp, engine.rank, engine.max_rows, engine.allow_copy = torch, 1, 0, 6, True |
| 42 | + engine.w, engine.draft, engine.eos, engine.cache = w, None, tuple(w.config.eos), [] |
| 43 | + engine.context_window = 4096 |
| 44 | + engine.concurrent, engine.multi, engine.scheduler = scheduler is not None, None, scheduler |
| 45 | + return engine |
| 46 | + |
| 47 | + |
| 48 | +def _run(app, prompt, sampling, count=COUNT, emit=lambda delta: True, cancelled=None): |
| 49 | + body = ({"temperature": 0.0} if sampling is None else |
| 50 | + {"temperature": sampling.temperature, "seed": sampling.seed, "top_k": sampling.top_k, |
| 51 | + "top_p": sampling.top_p}) |
| 52 | + prepared = server.PreparedRequest(list(prompt), count, [], False) |
| 53 | + return app.run(body, False, emit, prepared=prepared, cancelled=cancelled) |
| 54 | + |
| 55 | + |
| 56 | +def _after(n): |
| 57 | + """A ``cancelled`` that turns true at its n-th check: the client leaves mid-reply.""" |
| 58 | + |
| 59 | + checks = [] |
| 60 | + return lambda: checks.append(1) or len(checks) >= n |
| 61 | + |
| 62 | + |
| 63 | +def _keeping(sent): |
| 64 | + """An ``emit`` that keeps what the reply sends; ``_Tok`` gives one character a token.""" |
| 65 | + |
| 66 | + def emit(delta): |
| 67 | + sent.append(delta.get("content", "")) |
| 68 | + return True |
| 69 | + |
| 70 | + return emit |
| 71 | + |
| 72 | + |
| 73 | +def _ids(sent): |
| 74 | + return [ord(c) - 0x100 for c in "".join(sent)] |
| 75 | + |
| 76 | + |
| 77 | +def _failing(n): |
| 78 | + """An ``emit`` that fails at its n-th delta, as a broken per-token step does.""" |
| 79 | + |
| 80 | + deltas = [] |
| 81 | + |
| 82 | + def emit(delta): |
| 83 | + deltas.append(delta) |
| 84 | + if len(deltas) >= n: |
| 85 | + raise RuntimeError("emit failed") |
| 86 | + return True |
| 87 | + |
| 88 | + return emit |
| 89 | + |
| 90 | + |
| 91 | +def _full(w, prompt, sampling): |
| 92 | + ref = _serial(w, prompt, sampling, COUNT) |
| 93 | + assert len(ref) == COUNT, "the synthetic model ended this reply early; pick another prompt" |
| 94 | + return ref |
| 95 | + |
| 96 | + |
| 97 | +def test_one_stream_stops_early_and_stays_exact(): |
| 98 | + w = _model() |
| 99 | + engine = _engine(w) |
| 100 | + app = _app(engine) |
| 101 | + prompt, sampling = PROMPTS[1], SAMPLINGS[1] |
| 102 | + ref = _full(w, prompt, sampling) |
| 103 | + sent: list[str] = [] |
| 104 | + with pytest.raises(RequestCancelled): |
| 105 | + _run(app, prompt, sampling, emit=_keeping(sent), cancelled=_after(3)) |
| 106 | + n = len(_ids(sent)) |
| 107 | + assert 1 <= n < COUNT and _ids(sent) == ref[:n] |
| 108 | + # the prompt end kept by the stopped request resumes a longer prompt with a fresh prefill's tokens |
| 109 | + longer = prompt + ref[:5] + [42, 43] |
| 110 | + got = _run(app, longer, sampling, count=12) |
| 111 | + assert got["stats"]["cached"] == len(prompt) |
| 112 | + assert got["stats"]["token_sha"] == server.token_sha(_serial(w, longer, sampling, 12)) |
| 113 | + with pytest.raises(RuntimeError, match="emit failed"): |
| 114 | + _run(app, prompt, sampling, emit=_failing(3)) |
| 115 | + assert _run(app, prompt, sampling)["stats"]["token_sha"] == server.token_sha(ref) |
| 116 | + |
| 117 | + |
| 118 | +def test_shared_rounds_keep_the_other_streams_exact(): |
| 119 | + w = _model() |
| 120 | + refs = {tuple(p): _full(w, p, s) for p, s in zip(PROMPTS[:4], SAMPLINGS)} |
| 121 | + scheduler = Scheduler(_Oracle(w, refs, seed=3), max_streams=3) |
| 122 | + app = _app(_engine(w, scheduler)) |
| 123 | + gate = threading.Barrier(3) |
| 124 | + results: dict[int, object] = {} |
| 125 | + sent: list[str] = [] |
| 126 | + |
| 127 | + def go(i, **kw): |
| 128 | + gate.wait(timeout=120) |
| 129 | + try: |
| 130 | + results[i] = _run(app, PROMPTS[i], SAMPLINGS[i], **kw) |
| 131 | + except Exception as exc: # noqa: BLE001 |
| 132 | + results[i] = exc |
| 133 | + |
| 134 | + threads = [threading.Thread(target=go, args=(0,), kwargs={"emit": _keeping(sent), "cancelled": _after(3)}), |
| 135 | + threading.Thread(target=go, args=(1,), kwargs={"emit": _failing(3)}), |
| 136 | + threading.Thread(target=go, args=(2,))] |
| 137 | + for t in threads: |
| 138 | + t.start() |
| 139 | + for t in threads: |
| 140 | + t.join(timeout=120) |
| 141 | + assert not any(t.is_alive() for t in threads) |
| 142 | + left, failed, beside = results[0], results[1], results[2] |
| 143 | + n = len(_ids(sent)) |
| 144 | + assert isinstance(left, RequestCancelled) and 1 <= n < COUNT and _ids(sent) == refs[tuple(PROMPTS[0])][:n] |
| 145 | + assert isinstance(failed, RuntimeError) and str(failed) == "emit failed" |
| 146 | + assert beside["stats"]["token_sha"] == server.token_sha(refs[tuple(PROMPTS[2])]) |
| 147 | + after = _run(app, PROMPTS[3], SAMPLINGS[3]) |
| 148 | + assert after["stats"]["token_sha"] == server.token_sha(refs[tuple(PROMPTS[3])]) |
| 149 | + assert scheduler.decoder.live() == 0 |
0 commit comments