diff --git a/TECHNICAL_REPORTS/0.9/3723-admission-join-output-thread-20261203.en.md b/TECHNICAL_REPORTS/0.9/3723-admission-join-output-thread-20261203.en.md new file mode 100644 index 000000000..f23181419 --- /dev/null +++ b/TECHNICAL_REPORTS/0.9/3723-admission-join-output-thread-20261203.en.md @@ -0,0 +1,268 @@ +# PR #3723: Admissions join the pipelined decode loop, and streaming moves to an output thread on CUDA + +**Date**: 2026-12-03 +**Status**: Open draft (part 2 of #3669, closes it; part of epic #3671; part 1 is #3719, report `3719-pipelined-decode-graph-replay-20261203.en.md`) +**Language**: Rust (scheduler admission and decode-tick routing, a new `admission_join` scheduler module, a new `output_thread` batch module and its scheduler side `output_routing`, finish hooks, sequence result building, metrics), Markdown (scheduler and env-var docs) +**Risk**: Medium. Two changes of ownership on the CUDA decode path. First, an admission no longer tears down a pipelined decode-graph lookahead: the step in flight is kept with its speculative append across the admission's prefill, so `lookahead_safe` on an armed pipelined tick no longer looks at the prefill queue or a parked chunked prefill, and every path that changes membership (preemption, pad-row release, mixed and budgeted steps) had to learn to wait for or unwind the kept step. Review found one such path that did not (the `MLXCEL_MIXED_STEP` arm, MEDIUM, fixed). Second, for routable requests the detokenizer state and the client sender move to a per-worker output thread, so the order of everything the client sees now depends on a queue handoff. Kill switches: `MLXCEL_PIPELINE_ADMISSION_JOIN=0` restores the teardown on every admission, `MLXCEL_OUTPUT_THREAD=0` keeps all streaming on the scheduler thread, and `MLXCEL_DECODE_GRAPH_PIPELINE=0` (from #3719) turns off the pipelined graph ticks the join depends on. Metal, ROCm and CPU cannot reach either change. + +## Summary + +#3719 delivered item 1 of #3669: on CUDA, a decode-graph tick the #632 lookahead pipeline can run launches step n+1's graph before step n's tokens are read. It left three things for this PR. An admission still tore the pipeline down, detokenization and streaming still ran on the scheduler thread, and most of the host-read audit was undone. + +This PR does all three. Before an admission's prefill, `prepare_admission` reads the step in flight (step n+1) to the host and keeps it with its speculative append. The next decode tick takes a new arm, `pipelined_join_decode`: it commits step n+1 to the old rows and primes step n+2 over the old and new rows together, so a new row joins at step n+2 and nothing is unwound or run twice. A request whose text cannot decide its next step (no stop strings, no generation bound, no token-only drafter) is routed to a per-worker output thread when it joins the decode batch. From then on the scheduler only pushes token ids onto a bounded queue, and the thread detokenizes, streams, builds the final result and sends `Done`. The remaining synchronous host reads on the decode path are listed with reasons in `docs/CONTINUOUS_BATCHING.md`. + +All validation ran on a shared GB10 host. The parity runs used test-fast binaries, and no throughput was measured, so every number here is indicative: it shows correctness and parity on GB10, not performance. A null control (main against main) changed one prompt in one cell per run under `--max-num-batched-tokens 256`, so a single differing row under that budget is within existing timing variance. The B200 measurements that #3669's acceptance criteria ask for (nsys idle gaps, serving table) are deferred, which means this PR closes #3669 with those two criteria unmet (section 4). + +## 1. Problem + +After #3719, the CUDA decode loop overlapped step n's host work with step n+1's GPU work, but only while batch membership stayed the same. Two costs remained. + +- **Admissions.** Every admission (a queued prompt's prefill, a parked prefill's next chunk, the prefill pieces of a budgeted step under `--max-num-batched-tokens`) called `discard_lookahead`: it waited for step n+1, unwound its speculative KV append, and the next decode tick ran step n+1 again synchronously over the new membership. Step n+1's forward was computed twice, and the pipeline had to refill. `lookahead_safe()` was also false while anything waited in the prefill queue or a chunked prefill was parked, so under steady arrivals the pipeline was often not primed at all. +- **Streaming.** `SequenceFinishHooks::stop_text` (`finish.rs`) ran the incremental detokenizer and `emit_decoded_piece` for every committed token on the scheduler thread. With #3719 that work overlapped the next step's GPU time, but it still sat on the thread that has to launch the step after. + +Issue #3669 asked for four items. #3719 delivered item 1 and part of item 4 (#3719 report section 4). This PR takes: + +2. Admissions that join at step N+2 without tearing the pipeline down. +3. Off-thread detokenization and streaming. +4. The rest of the audit of synchronous host reads in the step loop. + +## 2. Design + +### 2.1 Preparing an admission + +`BatchScheduler::prepare_admission` (new `scheduler/admission_join.rs`) replaces the unconditional `discard_lookahead` before a prefill. It keeps the stored lookahead when all of these hold: + +- the join is on (`admission_joins_pipeline`: `MLXCEL_PIPELINE_ADMISSION_JOIN` not off and `pipelined_graphs()` true, which is CUDA only), +- the lookahead is a decode-graph step (`LookaheadRead::Graph`), not an eager one, +- no preemption is pending. + +Then it calls `settle_lookahead`, which reads the in-flight step's tokens from their pinned copy (`read_lookahead`) and stores them in the lookahead as `StepTokens::Host`. The speculative append stays, so the lookahead still covers its rows. A failed read fails the step's rows through `fail_lookahead_readback`, as a failed steady read does. In every other case `prepare_admission` is the old teardown, `discard_lookahead`, and counts `record_admission_teardown`. + +**Deviation from the issue.** #3669 described step n+1 running with the old membership while the new rows join at n+2. That holds, but the join reads step n+1 to the host before the prefill instead of leaving it on the device and feeding it into step n+2. The prefill's forward runs on the same generation stream and would wait for step n+1 anyway, so the read costs no overlap the prefill had not already given up. In return, step n+2 needs no mixed host and device staging (old rows' tokens on the device, new rows' first tokens on the host), and the KV invariant stays simple: only the old rows hold a speculative append. What the join saves is the unwind and the re-run of step n+1, not continuous overlap across the admission. + +### 2.2 The join tick + +`run_lookahead_tick` gains an arm before the stale-id-set fallback. It applies when `lookahead_params` is some, `lookahead_safe()` holds, and `admission_join_applies(la, seq_ids)`: + +- the join is on, the tick is an armed decode-graph tick (`decode_graphs_armed`) and the lookahead is a graph step, so both steps run the replayable structure, +- `seq_ids` is a strict superset of `la.ids`, +- every row not in `la.ids` is live (not finished) and has its first token committed. + +`pipelined_join_decode` then reads `la`'s tokens (already on the host after `settle_lookahead`) and checks each old row with `lookahead_token_finishes` (end of sequence, `max_tokens`, cancellation). If none finishes, it commits the tokens with `apply_fused_decode_tokens`, counts `record_lookahead_step` and `record_admission_join`, and calls `maybe_prime_lookahead(seq_ids)`, which primes step n+2 over the whole batch. The new rows' first tokens, sampled by their prefill, are their inputs in that step. From the tick after, the steady pipeline runs over the joined batch. + +If an old row stops on step n+1's token, the tick behaves like a stale lookahead: `apply_lookahead_trim` unwinds the old rows' append, the tick runs synchronously over the live rows (`dispatch_sync_decode`) and primes again. Only the old rows hold a speculative append, so the trim covers exactly them. + +### 2.3 What still tears the pipeline down + +- **Preemption.** `preempt_sequence` calls `discard_lookahead` first when the join is on, so a kept lookahead that covers the victim is unwound before the victim's caches are released. Without the join every caller has already torn it down. +- **Any finish or cancellation.** `finalize_completed` is unchanged: a finished or cancelled row in the batch discards the lookahead before KV donation or slot reuse. +- **An eager lookahead.** `prepare_admission` keeps only graph steps. +- **A row that stops on step n+1's token** (section 2.2). + +Releasing a decode pad row is not a teardown. `release_decode_pad_rows` calls `settle_lookahead` before the pad rows' blocks go back to the pool, because the kept step may still be reading them. The lookahead is kept. + +### 2.4 The wider prime gate + +`lookahead_safe` on an armed pipelined tick with the join on now returns `!should_preempt()` only. A queued prompt or a parked chunked prefill no longer stops the prime, because the admission that follows keeps the lookahead. Off the join, or on a tick that is not an armed graph tick, the old gate (`lookahead_pipeline_safe`: empty prefill queue, no chunked prefill, no pending preemption) applies unchanged. + +### 2.5 Mixed and budgeted steps + +Both run a decode and a prefill piece in one tick. + +- `execute_budgeted_step` (`--max-num-batched-tokens`, #3717): without the join, `prepare_admission` (the teardown) runs before the decode, as before. With the join, the decode runs first and may keep and prime a lookahead, then `prepare_admission` settles it before the prefill pieces. +- The `MLXCEL_MIXED_STEP` arm of the run loop (#908 prototype) does the same. Before review fix 4685a8126 it primed a graph step that the chunk then ran under, and the next tick threw that step away. It now calls `prepare_admission` after the decode and before the chunk, as the budgeted step does. + +### 2.6 Routing to the output thread + +`spawn_model_worker_with_batch_config` calls `enable_output_thread` before `serve()` in the `Hybrid` and `Router` serving modes (the standard loop). The thread starts when `output_thread_requested()` is true (CUDA, and `MLXCEL_OUTPUT_THREAD` not off) and the scheduler does not dispatch speculative decoding. The disaggregated prefill and decode roles do not start it, nor do schedulers built by tests unless a test asks. + +`finish_prefill` calls `route_output` just before a sequence enters the active batch, after its first token has been streamed and after `prime_prompt_lookup` has set any token-only drafter. `output_thread::routable` admits the request when: + +- its stop matcher is inactive (no stop strings), +- its `GenerationBounds` is inactive (no `n_indent`, no `t_max_predict_ms`), +- it has no token-only drafter (`token_only` is `None`: no prompt lookup, no full-model draft), +- it is not finished. + +These are the requests whose text cannot decide whether their next step runs. Finishes that depend on token ids only (end of sequence, `max_tokens`, the context bound) stay on the scheduler thread and need no text. + +On attach, the request's `StreamingDecodeState` and client sender move to the thread in an `Attach` record, and `seq.routed` holds a `RoutedOutput` link in their place. `seq.response_tx` becomes the sender of a private channel whose receiver is in the link. + +### 2.7 Order of everything the client sees + +The scheduler still sends some events itself for a routed request, through `seq.response_tx` (an error, a failed forward). These land on the private channel. `RoutedOutput::token` first drains that channel into `Event` records (`forward_events`), then pushes the `Token` record, and `finish`, `detach` and the link's drop do the same. The thread handles one request's records in queue order, so the client sees exactly the sequence of events the scheduler thread would have sent. `SequenceFinishHooks::stop_text` pushes the token and returns `false`, which is what the inactive stop matcher would have returned. + +### 2.8 Finishing a routed request + +`finalize_completed` takes the link out of the sequence and sends a `Finish` record with a `ResultTemplate`. That type is the non-detokenizer half of `take_generation_result`, factored out in `sequence.rs` so both paths build the same result. The thread streams the detokenizer's held tail, builds the result, records the completion telemetry (`record_request_completion`) and sends `Done`. An unrouted request goes through the new `send_finished_result`, which is the old inline code. Review fix 4685a8126 keeps a routed row registered on the thread until `Done` is sent, so a panic during the finish still answers the client with an error. + +A link dropped without a finish (an abort, a shutdown drain) forwards what it was sent and pushes `Close`, so the client's stream ends. + +### 2.9 Failure handling and slow clients + +- The queue is a `sync_channel` of 4096 records (`QUEUE_CAPACITY`), one per worker. The client channel is the existing unbounded `mpsc` sender, so the output thread never waits on a client. The scheduler waits only if the output thread itself falls 4096 records behind. +- Each record runs under `catch_unwind`. A panic answers that request with an error, sets its `cancelled` flag for the scheduler and drops its later records. Other requests continue. +- `OutputWorker`'s drop closes the queue and joins the thread after it has handled every queued record. The `output_worker` field is declared after every field that holds a `SequenceInfo`, because a routed row's queue handle must drop before the join can return. Review fix e77c84fe6 documents that requirement on the field. + +### 2.10 Preemption takes the request back + +`preempt_sequence` calls `unroute_output` on the victim. `RoutedOutput::detach` forwards pending events, pushes a `Detach` record and waits up to `DETACH_TIMEOUT` (10 s) for the client sender to come back after every record queued before it. The re-prefill then streams on the scheduler thread with that sender. A request the thread already failed, or one it does not hand back in time, is cancelled. + +### 2.11 Audit of synchronous host reads (item 4) + +- `step_rows.rs` performs no device reads: the row hooks read host state only (stop matcher, bounds, structured matcher). +- `speculative_finalize.rs` performs none directly: speculative rounds verify on the host inside the drivers, and those ticks never pipeline. + +The reads that remain on the decode path, and the reason each stays, are a table in `docs/CONTINUOUS_BATCHING.md`: `read_lookahead_tokens` on the eager pipeline (no captured graph, so no pinned copy), the synchronous step `Engine::step_padded` through `run_engine_step` (the fallback for everything the pipeline does not run), a synchronous graph replay's readback (no step to overlap with), and the pinned read in `settle_lookahead` from `prepare_admission` and `release_decode_pad_rows`. No read was replaced in this PR; the audit documents them. + +### 2.12 Kill switches and observability + +- `MLXCEL_PIPELINE_ADMISSION_JOIN`: read once by `admission_join_requested`. `0`, `false`, `off` or `no` (trimmed, case-insensitive) restores the teardown on every admission. `admission_join_from(env, pipelined_graphs)` is the pure form and is false whenever pipelined graphs are off, so it is false on Metal, ROCm and CPU whatever the environment says. +- `MLXCEL_OUTPUT_THREAD`: read once by `output_thread_requested`. The same four values keep all streaming on the scheduler thread. `output_thread_from(env, backend)` is false on every backend but CUDA. +- `MLXCEL_DECODE_GRAPH_PIPELINE=0` (#3719) turns off pipelined graph ticks and with them the join. +- `/metrics` gains `mlxcel_batch_decode_lookahead_admission_joins_total` and `mlxcel_batch_decode_lookahead_admission_teardowns_total`. The output thread has internal counters (`OutputStats`: attached, tokens, failed) logged at shutdown, not exported. + +## 3. Validation (GB10, sm_121, shared host) + +All GPU tests ran under `gpu-lock` with `--test-threads=1` and the test-fast profile. The source for this section is the PR body. No throughput or latency was measured, and the host was shared with other work. + +### 3.1 Unit tests (9 of 9 pass) + +`output_thread_tests.rs` (8) and the gate test in `admission_join.rs` (1): + +| Test | What it checks | +|---|---| +| `the_output_thread_streams_what_the_scheduler_thread_streams` | Four multi-byte replies stream identically on both threads | +| `a_detokenization_failure_fails_only_its_request` | An injected panic on one token fails only that request | +| `the_failed_request_is_cancelled_for_the_scheduler` | The failed request's `cancelled` flag is set | +| `scheduler_events_keep_their_order_with_routed_tokens` | Scheduler-sent events interleave with routed tokens in send order | +| `a_client_that_never_reads_does_not_stall_the_scheduler` | The scheduler keeps pushing while a client never reads | +| `a_detached_request_gets_its_client_back_after_its_queued_pieces` | Detach returns the sender after the queued pieces | +| `requests_whose_text_decides_the_next_step_are_not_routed` | Stop strings, bounds and token-only rows stay inline | +| `the_output_thread_is_cuda_only_and_has_a_kill_switch` | Gate and switch | +| `admission_join_needs_pipelined_graphs_and_has_a_kill_switch` | Gate and switch | + +### 3.2 Scheduler pipeline tests + +`scheduler_decode_graphs_tests::pipeline` passed in full on Llama 3.2 1B 4bit and on Gemma 4 12B 4bit. New tests in `scheduler_decode_graph_pipeline_tests.rs`: + +- `an_admission_during_the_pipeline_joins_at_the_step_after_next`, run with no budget and with `--max-num-batched-tokens 256`. Both late rows join, no admission teardown happens, the KV-length invariant of #3719 holds after every tick, the pool slabs do not move, and tokens equal the teardown arm row for row. +- `a_natural_end_of_sequence_with_the_next_step_in_flight_matches_the_synchronous_path`. This closes the test gap #3719 section 5.2 listed. +- `four_concurrent_multibyte_requests_stream_the_same_on_the_output_thread`. It uses the Llama 3 chat format and skips on other tokenizers. + +### 3.3 Greedy parity on the server + +`mlxcel-server` binaries built with the test-fast profile (not release), Llama 3.2 1B 4bit, `--parallel 8`, 8 chat prompts of 64 tokens, temperature 0, streamed. Two traffic shapes: a burst, and arrivals staggered 150 ms apart. Each shape ran with no budget and with `--max-num-batched-tokens 256`, so a run has four cells. Arms: main at `ac5716b8f`, the branch at its defaults, the branch with both new switches off, and a second main run as a null control. + +Across two full runs of the matrix, the branch at its defaults was byte-identical to main in all 8 cells. + +### 3.4 Null control + +The second main run differed from the first in one prompt (#5) in one cell per run: the 256-budget burst in run 1 and the 256-budget stagger in run 2. The branch with both switches off showed the same change once. Main against main differing under budget 256 means the budgeted scheduler's output already depends on batching timing there. A single differing row under that budget is therefore not evidence against this PR, and equally the 8 of 8 result does not exclude a timing-dependent difference that these runs did not hit. + +### 3.5 Counters (run 2) + +| Arm | Joins | Admission teardowns | Pipelined replays | +|---|---|---|---| +| Branch, no budget | 5 | 0 | 209 | +| Branch, budget 256 | 7 | 0 | 209 | +| Branch, switches off, no budget | 0 | 6 | 197 | +| Branch, switches off, budget 256 | 0 | 5 | 198 | +| Main, no budget | n/a | n/a | 207 | + +The counters show that the join path ran and replaced the teardowns. The replay counts depend on arrival timing on a shared host and are not a speed measurement. + +### 3.6 Static checks + +- `cargo fmt --all --check`: clean. +- Scoped clippy (`--features cuda --lib --tests -D warnings`): clean. +- `cargo check -p mlxcel --lib --tests` at default features: clean. +- Contract checks (`make verify-*`): all pass. + +## 4. Scope against the issue + +| #3669 item | Status | Notes | +|---|---|---| +| 1. Graph-replay lookahead | Delivered in #3719 | | +| 2. Admissions join at step N+2 | Delivered, default on CUDA | Step n+1 is read to the host before the prefill (section 2.1) | +| 3. Off-thread detokenization and streaming | Delivered, default on CUDA | One bounded queue per worker, not a bounded channel per request (section 5.3) | +| 4. Audit of synchronous host reads | Delivered as documentation | No read replaced; the remaining ones are tabled with reasons | + +| Acceptance criterion | Status | +|---|---| +| nsys median idle gap under 100 us, p99 under 500 us at c=8 | Not met here, deferred to B200 (section 5.6) | +| Serving table at c=1, 8, 32 before and after | Not met here, deferred to B200 | +| Test: stop at step N with N+1 in flight matches the synchronous path | Met (#3719 tests, plus the natural end-of-sequence test here) | +| Test: an admission joins at the step after next without teardown | Met | +| Test: output-thread text matches the scheduler thread for 4 multi-byte requests | Met | +| Greedy parity, 64 tokens x 8 prompts, against the pre-change server | Met on Llama 3.2 1B 4bit on GB10, with the null control of section 3.4 | +| Metal unreachable | Met: both gates are tested pure functions that are false off CUDA | +| Default decode loop on CUDA | Met | + +The PR body says `Closes #3669`. Merging it closes the issue with the two B200 performance criteria still open, so they need a home in epic #3671. + +Part 1's follow-up list (#3719 report section 5.5), item by item: item 2 is delivered (section 2.1 to 2.5); item 3 is delivered for routable requests, with `bounds` rows staying inline rather than `bounds` moving to the thread; the rest of item 4 is the audit table, with `read_lookahead_tokens` on the eager pipeline kept and documented; the B200 measurements are still deferred; the natural end-of-sequence test is delivered. + +## 5. Open items + +### 5.1 Review follow-ups + +The review findings come from the PR body's Review section; the PR has no review comments of its own. + +pr-reviewer found no CRITICAL or HIGH issues and two MEDIUM ones, both fixed in 4685a8126: + +- The `MLXCEL_MIXED_STEP` arm primed a graph step that the chunk then ran under, and the next tick discarded it. It now keeps the joined lookahead through its decode and calls `prepare_admission` before the chunk (section 2.5). +- A routed row was unregistered before `Done` was sent, so a panic while finishing left the client without an error. It now stays registered until `Done` (section 2.8). + +pr-security-checker found no CRITICAL, HIGH or MEDIUM issues. One LOW was fixed in e77c84fe6: the required drop order of the `output_worker` field is documented on it. + +### 5.2 LOW findings left open + +- Taking back a preempted routed request blocks the scheduler for up to 10 s (`DETACH_TIMEOUT`) if the output thread is that far behind. After the timeout the request is cancelled. +- `record_admission_teardown` also counts teardowns of eager lookaheads, so `mlxcel_batch_decode_lookahead_admission_teardowns_total` is not limited to graph ticks. +- The membership check in `admission_join_applies` (`la.ids.iter().all(|id| seq_ids.contains(id))` and its inverse) is quadratic in batch size. It runs only on ticks whose id set differs from the lookahead's. + +### 5.3 Deviations from the issue + +- **Join reads step n+1 to the host** before the prefill rather than feeding it on the device (section 2.1). +- **One bounded queue per worker.** The issue asked for a bounded channel per request with today's drop-to-disconnect policy. The PR uses one 4096-record queue per worker, and the client channel stays the existing unbounded one. A client that never reads therefore does not stall the scheduler, but its unread events stay in memory until the request ends, as on main. +- **Rows with generation bounds stay inline.** The issue listed `bounds` among what moves to the thread. The PR routes only requests without bounds, because `n_indent` and `t_max_predict_ms` can end a request on its text or time before the next step. + +### 5.4 Known limits and test gaps + +- **One model on the server.** Server parity ran on Llama 3.2 1B 4bit only. Gemma 4 12B 4bit ran the scheduler tests, not the server matrix. +- **Parity under budget 256 is bounded by the null control** (section 3.4). +- **The budgeted and mixed-step join paths** are covered by the admission test with `--max-num-batched-tokens 256` and by the server matrix; the `MLXCEL_MIXED_STEP` arm's fix has no dedicated test in the PR body. +- **The multi-byte scheduler test skips** on tokenizers without the Llama 3 chat format. +- **No test drives a preemption of a routed request** through the scheduler; detach is covered at the output-thread level. + +### 5.5 Docs against code + +Fixed in this PR in a separate commit (8a115b5af): + +- `docs/CONTINUOUS_BATCHING.md` listed the release of a decode pad row under "Teardown remains for". `release_decode_pad_rows` calls `settle_lookahead`, which reads the step and keeps the lookahead. The paragraph now says so. +- The `MLXCEL_PIPELINE_ADMISSION_JOIN` row of `docs/environment-variables.md` said "a cancellation that frees blocks" tears the pipeline down, taking the issue's wording. `finalize_completed` tears down on any finished or cancelled row, as `docs/CONTINUOUS_BATCHING.md` already said. The row now says "any finish or cancellation". +- The host-read table had a row for `prepare_admission` only. `release_decode_pad_rows` takes the same pinned read through `settle_lookahead`, and the row now names both. +- Both docs said every worker on CUDA runs an output thread. `enable_output_thread` is called only in the `Hybrid` and `Router` serving modes and returns early under speculative dispatch. Both docs now say the disaggregated roles (`--node-role`) keep streaming inline. +- `docs/CONTINUOUS_BATCHING.md` said the routing excludes a "prompt-lookup drafter". `routable` excludes any token-only drafter (`token_only`), which also covers a full-model `--draft-model`. The text now says so. +- The join paragraph said a new row "decodes its first token" at step n+2. Its first token comes from its prefill; step n+2 forwards it. The text now says that. + +Not fixed (source comments, left to avoid touching Rust in a docs commit): + +- The `admission_join.rs` module doc also lists "a released decode pad row" under teardown. +- `prepare_admission`'s "Used by" names the Prefill arm and `execute_budgeted_step` but not the `MLXCEL_MIXED_STEP` arm, which calls it since 4685a8126. + +### 5.6 Deferred to the B200 follow-up (epic #3671) + +- nsys idle gaps between consecutive decode graphs over 25 s of steady c=8 decode on Gemma 4 31B NVFP4 (targets: median under 100 us, p99 under 500 us). +- The `scripts/bench/serving_compare.py` table at c=1, 8 and 32 before and after, with the c=1 regression bound of 2% and the c=8 and c=32 TPOT improvement. +- Steps/s at 1, 4, 8 and 64 rows. + +GB10 is the only validation target in this wave. No B200 measurement backs anything in this report. + +## 6. Learning points + +- **Keeping a step across a membership change is cheaper when it is settled first.** Reading step n+1 to the host before the prefill gave up no overlap the shared stream had not already given up, and it kept the KV invariant to "only the old rows hold a speculative append". Feeding it on the device would have needed mixed staging for one tick. +- **Widening a gate moves the burden to every path the old gate excluded.** `lookahead_safe` used to keep the pipeline off whenever an admission was near, so admission-adjacent paths never saw a lookahead. Once it no longer did, the mixed-step arm, preemption and pad-row release each needed their own wait or unwind, and review found the one that did not have it. +- **Moving a sender changes who controls ordering.** Events the scheduler sends for a routed request go through a private channel that the routed link drains before every token, so the client sees one ordered stream from two producers. +- **A null control sets the bar for parity claims.** Main against main differed under budget 256, so the branch's 8 of 8 is read against that floor, and a future single-row difference under the budget is not by itself a regression. +- **Report what a closing PR leaves open.** The PR closes #3669 with its two performance criteria unmet on purpose; stating that in the report keeps the B200 work from looking done. diff --git a/TECHNICAL_REPORTS/0.9/3723-admission-join-output-thread-20261203.ko.md b/TECHNICAL_REPORTS/0.9/3723-admission-join-output-thread-20261203.ko.md new file mode 100644 index 000000000..8e2208f60 --- /dev/null +++ b/TECHNICAL_REPORTS/0.9/3723-admission-join-output-thread-20261203.ko.md @@ -0,0 +1,268 @@ +# PR #3723: CUDA에서 admission을 파이프라인된 디코드 루프에 합류시키고 스트리밍을 출력 스레드로 옮기기 + +**날짜**: 2026-12-03 +**상태**: 열린 드래프트 (#3669의 2부, 이 PR이 이슈를 닫음, 에픽 #3671의 일부, 1부는 #3719이며 리포트는 `3719-pipelined-decode-graph-replay-20261203.ko.md`) +**언어**: Rust (스케줄러 admission과 디코드 틱 라우팅, 새 `admission_join` 스케줄러 모듈, 새 `output_thread` 배치 모듈과 그 스케줄러 쪽인 `output_routing`, finish 훅, 시퀀스 결과 생성, 메트릭), Markdown (스케줄러 문서와 환경 변수 문서) +**위험도**: 중간. CUDA 디코드 경로에서 소유권이 두 군데 바뀐다. 첫째, admission이 더 이상 파이프라인된 디코드 그래프 lookahead를 해체하지 않는다. 진행 중인 스텝은 speculative append와 함께 admission의 prefill 동안 유지된다. 그래서 armed 파이프라인 틱의 `lookahead_safe`는 더 이상 prefill 큐나 parked chunked prefill을 보지 않으며, 멤버십을 바꾸는 모든 경로(preemption, 패드 행 해제, mixed 스텝과 예산 스텝)가 유지된 스텝을 기다리거나 되돌리도록 바뀌어야 했다. 리뷰에서 그렇게 하지 않던 경로 하나(`MLXCEL_MIXED_STEP` 경로, MEDIUM)가 발견되어 수정되었다. 둘째, 라우팅 가능한 요청은 detokenizer 상태와 클라이언트 sender가 워커별 출력 스레드로 옮겨가므로, 클라이언트가 보는 모든 것의 순서가 큐 인계에 달려 있다. 끄는 스위치: `MLXCEL_PIPELINE_ADMISSION_JOIN=0`은 모든 admission에서 해체를 되살리고, `MLXCEL_OUTPUT_THREAD=0`은 모든 스트리밍을 스케줄러 스레드에 두며, `MLXCEL_DECODE_GRAPH_PIPELINE=0`(#3719)은 합류가 의존하는 파이프라인 그래프 틱을 끈다. Metal, ROCm, CPU에서는 두 변경 모두에 닿을 수 없다. + +## 요약 + +#3719는 #3669의 항목 1을 전달했다. CUDA에서 #632 lookahead 파이프라인이 돌릴 수 있는 디코드 그래프 틱은 스텝 n의 토큰을 읽기 전에 스텝 n+1의 그래프를 launch한다. 이 PR에는 세 가지가 남았다. admission은 여전히 파이프라인을 해체했고, detokenization과 스트리밍은 여전히 스케줄러 스레드에서 돌았으며, 호스트 읽기 감사 대부분이 끝나지 않았다. + +이 PR은 세 가지를 모두 한다. admission의 prefill 전에 `prepare_admission`이 진행 중인 스텝(스텝 n+1)을 호스트로 읽고 speculative append와 함께 유지한다. 다음 디코드 틱은 새 경로 `pipelined_join_decode`를 탄다. 스텝 n+1을 기존 행에 커밋하고 기존 행과 새 행을 합쳐 스텝 n+2를 prime한다. 그래서 새 행은 스텝 n+2에서 합류하고, 되돌리거나 두 번 실행되는 것은 없다. 텍스트가 다음 스텝을 결정할 수 없는 요청(stop 문자열 없음, 생성 한도 없음, token-only drafter 없음)은 디코드 배치에 들어갈 때 워커별 출력 스레드로 라우팅된다. 그 뒤로 스케줄러는 토큰 id만 bounded 큐에 넣고, 출력 스레드가 detokenize, 스트리밍, 최종 결과 생성, `Done` 전송을 한다. 디코드 경로에 남은 동기식 호스트 읽기는 이유와 함께 `docs/CONTINUOUS_BATCHING.md`에 표로 정리했다. + +모든 검증은 공유 GB10 호스트에서 했다. 동일성 실행은 test-fast 바이너리를 썼고 처리량은 측정하지 않았으므로, 여기의 모든 수치는 참고용이다. GB10에서의 정확성과 동일성을 보여 줄 뿐 성능을 보여 주지 않는다. null 대조(main 대 main)는 `--max-num-batched-tokens 256`에서 실행마다 한 셀의 프롬프트 하나가 달랐다. 따라서 그 예산에서 한 행이 다른 것은 기존 타이밍 편차 범위 안이다. #3669의 인수 기준이 요구하는 B200 측정(nsys 유휴 간격, 서빙 표)은 미뤘다. 즉 이 PR은 그 두 기준을 충족하지 않은 채 #3669를 닫는다(4절). + +## 1. 문제 + +#3719 이후 CUDA 디코드 루프는 스텝 n의 호스트 작업을 스텝 n+1의 GPU 작업과 겹쳤지만, 배치 멤버십이 그대로일 때만 그랬다. 두 가지 비용이 남았다. + +- **Admission.** 모든 admission(대기 중인 프롬프트의 prefill, parked prefill의 다음 chunk, `--max-num-batched-tokens`에서 예산 스텝의 prefill 조각)이 `discard_lookahead`를 호출했다. 스텝 n+1을 기다리고, 그 speculative KV append를 되돌린 뒤, 다음 디코드 틱이 새 멤버십으로 스텝 n+1을 동기식으로 다시 돌렸다. 스텝 n+1의 forward가 두 번 계산되었고, 파이프라인은 다시 채워져야 했다. 또 prefill 큐에 무엇이든 대기 중이거나 chunked prefill이 parked 상태이면 `lookahead_safe()`가 거짓이었으므로, 요청이 꾸준히 들어올 때는 파이프라인이 아예 prime되지 않는 경우가 많았다. +- **스트리밍.** `SequenceFinishHooks::stop_text`(`finish.rs`)는 커밋되는 모든 토큰마다 스케줄러 스레드에서 증분 detokenizer와 `emit_decoded_piece`를 돌렸다. #3719로 이 작업은 다음 스텝의 GPU 시간과 겹쳤지만, 여전히 그다음 스텝을 launch해야 하는 스레드 위에 있었다. + +이슈 #3669는 네 가지를 요청했다. #3719는 항목 1과 항목 4의 일부를 전달했다(#3719 리포트 4절). 이 PR이 맡는 것: + +2. 파이프라인을 해체하지 않고 스텝 N+2에서 합류하는 admission. +3. 스레드 밖 detokenization과 스트리밍. +4. 스텝 루프의 동기식 호스트 읽기 감사의 나머지. + +## 2. 설계 + +### 2.1 admission 준비 + +`BatchScheduler::prepare_admission`(새 `scheduler/admission_join.rs`)이 prefill 전의 무조건적인 `discard_lookahead`를 대체한다. 다음이 모두 성립하면 저장된 lookahead를 유지한다. + +- 합류가 켜져 있다(`admission_joins_pipeline`: `MLXCEL_PIPELINE_ADMISSION_JOIN`이 꺼져 있지 않고 `pipelined_graphs()`가 참, 즉 CUDA만), +- lookahead가 eager 스텝이 아니라 디코드 그래프 스텝이다(`LookaheadRead::Graph`), +- 대기 중인 preemption이 없다. + +그러면 `settle_lookahead`를 호출한다. 이 함수는 진행 중인 스텝의 토큰을 pinned 복사본에서 읽고(`read_lookahead`) lookahead에 `StepTokens::Host`로 저장한다. speculative append는 남으므로 lookahead는 여전히 자기 행을 덮는다. 읽기가 실패하면 실패한 steady 읽기처럼 `fail_lookahead_readback`으로 그 스텝의 행을 실패시킨다. 그 밖의 모든 경우 `prepare_admission`은 예전의 해체인 `discard_lookahead`이고, `record_admission_teardown`을 센다. + +**이슈와 다른 점.** #3669는 스텝 n+1이 기존 멤버십으로 돌고 새 행이 n+2에서 합류한다고 설명했다. 이는 그대로 성립하지만, 합류는 스텝 n+1을 디바이스에 남겨 스텝 n+2에 넣는 대신 prefill 전에 호스트로 읽는다. prefill의 forward는 같은 생성 스트림에서 돌고 어차피 스텝 n+1을 기다리므로, 이 읽기는 prefill이 이미 포기한 것 이상의 겹침을 잃지 않는다. 대신 스텝 n+2에 호스트와 디바이스를 섞은 스테이징(기존 행의 토큰은 디바이스, 새 행의 첫 토큰은 호스트)이 필요 없고, KV 불변식도 단순하게 유지된다. speculative append를 가진 것은 기존 행뿐이다. 합류가 아끼는 것은 스텝 n+1의 되돌리기와 재실행이지, admission을 가로지르는 연속적인 겹침이 아니다. + +### 2.2 합류 틱 + +`run_lookahead_tick`에 stale id 집합 폴백보다 앞선 경로가 생겼다. `lookahead_params`가 있고, `lookahead_safe()`가 성립하고, `admission_join_applies(la, seq_ids)`일 때 적용된다. + +- 합류가 켜져 있고, 틱이 armed 디코드 그래프 틱(`decode_graphs_armed`)이며 lookahead가 그래프 스텝이다. 그래서 두 스텝 모두 재생 가능한 구조로 돈다. +- `seq_ids`가 `la.ids`를 모두 포함하면서 더 큰 집합(진상위집합)이다. +- `la.ids`에 없는 모든 행이 살아 있고(끝나지 않았고) 첫 토큰이 커밋되어 있다. + +그러면 `pipelined_join_decode`가 `la`의 토큰을 읽고(`settle_lookahead` 뒤라 이미 호스트에 있다) 각 기존 행을 `lookahead_token_finishes`(시퀀스 끝, `max_tokens`, 취소)로 확인한다. 끝나는 행이 없으면 `apply_fused_decode_tokens`로 토큰을 커밋하고, `record_lookahead_step`과 `record_admission_join`을 세고, `maybe_prime_lookahead(seq_ids)`를 호출해 배치 전체에 대해 스텝 n+2를 prime한다. 새 행의 첫 토큰은 prefill이 샘플링한 것이고, 그 스텝의 입력이 된다. 그다음 틱부터는 합류한 배치 위에서 steady 파이프라인이 돈다. + +기존 행이 스텝 n+1의 토큰에서 멈추면 이 틱은 stale lookahead처럼 동작한다. `apply_lookahead_trim`이 기존 행의 append를 되돌리고, 틱은 살아 있는 행에 대해 동기식으로 돌고(`dispatch_sync_decode`) 다시 prime한다. speculative append를 가진 것은 기존 행뿐이므로 trim은 정확히 그 행들을 덮는다. + +### 2.3 여전히 파이프라인을 해체하는 것 + +- **Preemption.** 합류가 켜져 있으면 `preempt_sequence`가 먼저 `discard_lookahead`를 호출하므로, victim을 덮는 유지된 lookahead는 victim의 캐시가 해제되기 전에 되돌려진다. 합류가 꺼져 있으면 모든 호출자가 이미 해체를 마친 상태다. +- **모든 종료나 취소.** `finalize_completed`는 바뀌지 않았다. 배치에 끝났거나 취소된 행이 있으면 KV 기부나 슬롯 재사용 전에 lookahead를 버린다. +- **eager lookahead.** `prepare_admission`은 그래프 스텝만 유지한다. +- **스텝 n+1의 토큰에서 멈추는 행**(2.2절). + +디코드 패드 행 해제는 해체가 아니다. 유지된 스텝이 패드 행의 블록을 아직 읽고 있을 수 있으므로, `release_decode_pad_rows`는 그 블록을 풀에 돌려주기 전에 `settle_lookahead`를 호출한다. lookahead는 유지된다. + +### 2.4 넓어진 prime 조건 + +합류가 켜진 armed 파이프라인 틱에서 `lookahead_safe`는 이제 `!should_preempt()`만 반환한다. 대기 중인 프롬프트나 parked chunked prefill은 더 이상 prime을 막지 않는다. 뒤따르는 admission이 lookahead를 유지하기 때문이다. 합류가 꺼져 있거나 armed 그래프 틱이 아니면 예전 조건(`lookahead_pipeline_safe`: 빈 prefill 큐, chunked prefill 없음, 대기 중인 preemption 없음)이 그대로 적용된다. + +### 2.5 mixed 스텝과 예산 스텝 + +둘 다 한 틱에 디코드와 prefill 조각을 돌린다. + +- `execute_budgeted_step`(`--max-num-batched-tokens`, #3717): 합류가 꺼져 있으면 예전처럼 디코드 전에 `prepare_admission`(해체)이 돈다. 합류가 켜져 있으면 디코드가 먼저 돌며 lookahead를 유지하고 prime할 수 있고, 그 뒤 `prepare_admission`이 prefill 조각 전에 그것을 settle한다. +- 런 루프의 `MLXCEL_MIXED_STEP` 경로(#908 프로토타입)도 같다. 리뷰 수정 4685a8126 전에는 chunk가 그 아래에서 도는 그래프 스텝을 prime했고, 다음 틱이 그 스텝을 버렸다. 이제 예산 스텝처럼 디코드 뒤, chunk 전에 `prepare_admission`을 호출한다. + +### 2.6 출력 스레드로의 라우팅 + +`spawn_model_worker_with_batch_config`는 `Hybrid`와 `Router` 서빙 모드(표준 루프)에서 `serve()` 전에 `enable_output_thread`를 호출한다. `output_thread_requested()`가 참이고(CUDA, `MLXCEL_OUTPUT_THREAD`가 꺼져 있지 않음) 스케줄러가 speculative decoding을 dispatch하지 않을 때 스레드가 시작된다. 분산 prefill과 디코드 역할은 이 스레드를 시작하지 않고, 테스트가 만든 스케줄러도 테스트가 요청하지 않는 한 시작하지 않는다. + +`finish_prefill`은 시퀀스가 active 배치에 들어가기 직전, 첫 토큰이 스트리밍된 뒤이자 `prime_prompt_lookup`이 token-only drafter를 설정한 뒤에 `route_output`을 호출한다. `output_thread::routable`은 다음일 때 요청을 받는다. + +- stop matcher가 비활성이다(stop 문자열 없음), +- `GenerationBounds`가 비활성이다(`n_indent` 없음, `t_max_predict_ms` 없음), +- token-only drafter가 없다(`token_only`가 `None`: prompt lookup 없음, full-model draft 없음), +- 끝나지 않았다. + +이들은 텍스트가 다음 스텝을 돌릴지 결정할 수 없는 요청이다. 토큰 id에만 의존하는 종료(시퀀스 끝, `max_tokens`, 컨텍스트 한도)는 스케줄러 스레드에 남고 텍스트가 필요 없다. + +attach하면 요청의 `StreamingDecodeState`와 클라이언트 sender가 `Attach` 레코드로 스레드에 옮겨가고, 그 자리에 `seq.routed`가 `RoutedOutput` 링크를 가진다. `seq.response_tx`는 수신 쪽이 링크에 있는 private 채널의 sender가 된다. + +### 2.7 클라이언트가 보는 모든 것의 순서 + +스케줄러는 라우팅된 요청에 대해서도 일부 이벤트(에러, 실패한 forward)를 `seq.response_tx`로 직접 보낸다. 이 이벤트는 private 채널에 쌓인다. `RoutedOutput::token`은 먼저 그 채널을 `Event` 레코드로 비우고(`forward_events`) 나서 `Token` 레코드를 넣으며, `finish`, `detach`, 링크의 drop도 같은 순서를 따른다. 스레드는 한 요청의 레코드를 큐 순서대로 처리하므로, 클라이언트는 스케줄러 스레드가 보냈을 이벤트 순서를 정확히 그대로 본다. `SequenceFinishHooks::stop_text`는 토큰을 넣고 `false`를 반환하는데, 이는 비활성 stop matcher가 반환했을 값이다. + +### 2.8 라우팅된 요청의 종료 + +`finalize_completed`는 시퀀스에서 링크를 꺼내 `ResultTemplate`과 함께 `Finish` 레코드를 보낸다. 이 타입은 `take_generation_result`에서 detokenizer와 무관한 절반으로, 두 경로가 같은 결과를 만들도록 `sequence.rs`에 분리되었다. 스레드는 detokenizer가 붙잡고 있던 꼬리를 스트리밍하고, 결과를 만들고, 완료 텔레메트리(`record_request_completion`)를 기록하고, `Done`을 보낸다. 라우팅되지 않은 요청은 예전 인라인 코드인 새 `send_finished_result`를 탄다. 리뷰 수정 4685a8126은 라우팅된 행을 `Done`을 보낼 때까지 스레드에 등록된 채로 두므로, 종료 중 panic이 나도 클라이언트는 에러를 받는다. + +종료 없이 drop된 링크(abort, 종료 시 drain)는 받은 것을 전달하고 `Close`를 넣으므로 클라이언트의 스트림이 끝난다. + +### 2.9 실패 처리와 느린 클라이언트 + +- 큐는 워커당 하나인 4096 레코드의 `sync_channel`(`QUEUE_CAPACITY`)이다. 클라이언트 채널은 기존의 unbounded `mpsc` sender이므로 출력 스레드는 클라이언트를 기다리지 않는다. 스케줄러는 출력 스레드 자체가 4096 레코드만큼 뒤처질 때만 기다린다. +- 각 레코드는 `catch_unwind` 아래에서 돈다. panic이 나면 그 요청에 에러로 답하고, 스케줄러를 위해 `cancelled` 플래그를 세우고, 이후 레코드를 버린다. 다른 요청은 계속된다. +- `OutputWorker`의 drop은 큐를 닫고, 스레드가 이미 쌓인 모든 레코드를 처리한 뒤 join한다. 라우팅된 행의 큐 핸들이 먼저 drop되어야 join이 끝나므로, `output_worker` 필드는 `SequenceInfo`를 가진 모든 필드 뒤에 선언된다. 리뷰 수정 e77c84fe6이 이 요구 사항을 필드에 문서화했다. + +### 2.10 preemption은 요청을 되찾아 온다 + +`preempt_sequence`는 victim에 대해 `unroute_output`을 호출한다. `RoutedOutput::detach`는 대기 중인 이벤트를 전달하고 `Detach` 레코드를 넣은 뒤, 앞서 쌓인 모든 레코드 다음에 클라이언트 sender가 돌아오기를 최대 `DETACH_TIMEOUT`(10초) 동안 기다린다. 그 뒤 재prefill은 그 sender로 스케줄러 스레드에서 스트리밍한다. 스레드가 이미 실패시킨 요청이나 제때 돌려주지 않은 요청은 취소된다. + +### 2.11 동기식 호스트 읽기 감사 (항목 4) + +- `step_rows.rs`는 디바이스 읽기를 하지 않는다. 행 훅은 호스트 상태(stop matcher, bounds, structured matcher)만 읽는다. +- `speculative_finalize.rs`는 직접 하지 않는다. speculative 라운드는 드라이버 안에서 호스트로 검증하고, 그런 틱은 파이프라인되지 않는다. + +디코드 경로에 남은 읽기와 그 이유는 `docs/CONTINUOUS_BATCHING.md`의 표에 있다. eager 파이프라인의 `read_lookahead_tokens`(캡처한 그래프가 없으므로 pinned 복사본도 없다), `run_engine_step`을 거치는 동기식 스텝 `Engine::step_padded`(파이프라인이 돌리지 않는 모든 것의 폴백), 동기식 그래프 재생의 readback(겹칠 스텝이 없다), 그리고 `prepare_admission`과 `release_decode_pad_rows`에서 `settle_lookahead`를 통한 pinned 읽기다. 이 PR에서 바뀐 읽기는 없고, 감사는 이들을 문서화한다. + +### 2.12 끄는 스위치와 관측 + +- `MLXCEL_PIPELINE_ADMISSION_JOIN`: `admission_join_requested`가 한 번 읽는다. `0`, `false`, `off`, `no`(앞뒤 공백 제거, 대소문자 무시)는 모든 admission에서 해체를 되살린다. `admission_join_from(env, pipelined_graphs)`가 순수 함수 형태이며 파이프라인 그래프가 꺼져 있으면 언제나 거짓이므로, 환경 변수와 무관하게 Metal, ROCm, CPU에서 거짓이다. +- `MLXCEL_OUTPUT_THREAD`: `output_thread_requested`가 한 번 읽는다. 같은 네 값이 모든 스트리밍을 스케줄러 스레드에 둔다. `output_thread_from(env, backend)`는 CUDA 외의 모든 백엔드에서 거짓이다. +- `MLXCEL_DECODE_GRAPH_PIPELINE=0`(#3719)은 파이프라인 그래프 틱을 끄고, 그와 함께 합류도 끈다. +- `/metrics`에 `mlxcel_batch_decode_lookahead_admission_joins_total`과 `mlxcel_batch_decode_lookahead_admission_teardowns_total`이 추가된다. 출력 스레드에는 종료 시 로그로 남는 내부 카운터(`OutputStats`: attached, tokens, failed)가 있고, 외부로 내보내지는 않는다. + +## 3. 검증 (GB10, sm_121, 공유 호스트) + +모든 GPU 테스트는 `gpu-lock` 아래에서 `--test-threads=1`과 test-fast 프로필로 돌았다. 이 절의 출처는 PR 본문이다. 처리량이나 지연 시간은 측정하지 않았고, 호스트는 다른 작업과 공유했다. + +### 3.1 단위 테스트 (9개 모두 통과) + +`output_thread_tests.rs`(8개)와 `admission_join.rs`의 조건 테스트(1개): + +| 테스트 | 확인하는 것 | +|---|---| +| `the_output_thread_streams_what_the_scheduler_thread_streams` | 멀티바이트 응답 4개가 두 스레드에서 똑같이 스트리밍된다 | +| `a_detokenization_failure_fails_only_its_request` | 한 토큰에서 주입한 panic이 그 요청만 실패시킨다 | +| `the_failed_request_is_cancelled_for_the_scheduler` | 실패한 요청의 `cancelled` 플래그가 세워진다 | +| `scheduler_events_keep_their_order_with_routed_tokens` | 스케줄러가 보낸 이벤트가 보낸 순서대로 라우팅된 토큰 사이에 들어간다 | +| `a_client_that_never_reads_does_not_stall_the_scheduler` | 클라이언트가 읽지 않아도 스케줄러는 계속 넣는다 | +| `a_detached_request_gets_its_client_back_after_its_queued_pieces` | detach가 쌓인 조각 뒤에 sender를 돌려준다 | +| `requests_whose_text_decides_the_next_step_are_not_routed` | stop 문자열, bounds, token-only 행은 인라인에 남는다 | +| `the_output_thread_is_cuda_only_and_has_a_kill_switch` | 조건과 스위치 | +| `admission_join_needs_pipelined_graphs_and_has_a_kill_switch` | 조건과 스위치 | + +### 3.2 스케줄러 파이프라인 테스트 + +`scheduler_decode_graphs_tests::pipeline`이 Llama 3.2 1B 4bit와 Gemma 4 12B 4bit에서 모두 통과했다. `scheduler_decode_graph_pipeline_tests.rs`의 새 테스트: + +- `an_admission_during_the_pipeline_joins_at_the_step_after_next`, 예산 없이와 `--max-num-batched-tokens 256`으로 실행. 늦게 온 두 행이 모두 합류하고, admission 해체가 일어나지 않고, #3719의 KV 길이 불변식이 매 틱 뒤에 성립하고, 풀 slab이 움직이지 않으며, 토큰이 해체 경로와 행마다 같다. +- `a_natural_end_of_sequence_with_the_next_step_in_flight_matches_the_synchronous_path`. #3719 5.2절에 적은 테스트 공백을 메운다. +- `four_concurrent_multibyte_requests_stream_the_same_on_the_output_thread`. Llama 3 chat 형식을 쓰며 다른 토크나이저에서는 건너뛴다. + +### 3.3 서버 greedy 동일성 + +test-fast 프로필(release 아님)로 빌드한 `mlxcel-server` 바이너리, Llama 3.2 1B 4bit, `--parallel 8`, 64 토큰의 chat 프롬프트 8개, temperature 0, 스트리밍. 트래픽 모양은 두 가지다. 한꺼번에 도착하는 burst와 150 ms 간격의 엇갈린 도착. 각 모양을 예산 없이와 `--max-num-batched-tokens 256`으로 돌렸으므로 실행 하나에 셀이 4개다. 경로: `ac5716b8f`의 main, 기본값의 브랜치, 두 새 스위치를 끈 브랜치, null 대조로 쓴 두 번째 main 실행. + +행렬 전체를 두 번 돌린 결과, 기본값의 브랜치는 8개 셀 모두에서 main과 바이트 단위로 같았다. + +### 3.4 Null 대조 + +두 번째 main 실행은 실행마다 한 셀에서 프롬프트 하나(#5)가 첫 번째와 달랐다. 실행 1에서는 예산 256의 burst, 실행 2에서는 예산 256의 엇갈린 도착이었다. 스위치를 끈 브랜치도 같은 변화를 한 번 보였다. 예산 256에서 main과 main이 다르다는 것은 그 설정에서 예산 스케줄러의 출력이 이미 배칭 타이밍에 의존한다는 뜻이다. 따라서 그 예산에서 한 행이 다른 것은 이 PR에 불리한 증거가 아니며, 마찬가지로 8개 중 8개라는 결과가 이 실행들이 마주치지 않은 타이밍 의존 차이를 배제하지도 않는다. + +### 3.5 카운터 (실행 2) + +| 경로 | 합류 | admission 해체 | 파이프라인 재생 | +|---|---|---|---| +| 브랜치, 예산 없음 | 5 | 0 | 209 | +| 브랜치, 예산 256 | 7 | 0 | 209 | +| 브랜치, 스위치 끔, 예산 없음 | 0 | 6 | 197 | +| 브랜치, 스위치 끔, 예산 256 | 0 | 5 | 198 | +| main, 예산 없음 | 해당 없음 | 해당 없음 | 207 | + +카운터는 합류 경로가 돌았고 해체를 대체했음을 보여 준다. 재생 횟수는 공유 호스트에서의 도착 타이밍에 달려 있으며 속도 측정이 아니다. + +### 3.6 정적 검사 + +- `cargo fmt --all --check`: 깨끗함. +- 범위를 좁힌 clippy(`--features cuda --lib --tests -D warnings`): 깨끗함. +- 기본 feature의 `cargo check -p mlxcel --lib --tests`: 깨끗함. +- 계약 검사(`make verify-*`): 모두 통과. + +## 4. 이슈 대비 범위 + +| #3669 항목 | 상태 | 비고 | +|---|---|---| +| 1. 그래프 재생 lookahead | #3719에서 전달 | | +| 2. 스텝 N+2에서 합류하는 admission | 전달, CUDA 기본값 | 스텝 n+1은 prefill 전에 호스트로 읽힌다(2.1절) | +| 3. 스레드 밖 detokenization과 스트리밍 | 전달, CUDA 기본값 | 요청별 bounded 채널이 아니라 워커당 bounded 큐 하나(5.3절) | +| 4. 동기식 호스트 읽기 감사 | 문서로 전달 | 바뀐 읽기는 없고, 남은 읽기를 이유와 함께 표로 정리 | + +| 인수 기준 | 상태 | +|---|---| +| c=8에서 nsys 유휴 간격 중앙값 100 us 미만, p99 500 us 미만 | 여기서는 미충족, B200으로 미룸(5.6절) | +| c=1, 8, 32 전후 서빙 표 | 여기서는 미충족, B200으로 미룸 | +| 테스트: N+1이 진행 중일 때 스텝 N에서 멈춤이 동기식 경로와 같음 | 충족(#3719 테스트와 여기의 자연스러운 시퀀스 끝 테스트) | +| 테스트: admission이 해체 없이 그다음 스텝에서 합류 | 충족 | +| 테스트: 멀티바이트 요청 4개에서 출력 스레드 텍스트가 스케줄러 스레드와 같음 | 충족 | +| 변경 전 서버 대비 64 토큰 x 프롬프트 8개 greedy 동일성 | GB10의 Llama 3.2 1B 4bit에서 충족, 3.4절의 null 대조와 함께 | +| Metal에서 도달 불가 | 충족: 두 조건 모두 CUDA 밖에서 거짓인 순수 함수이며 테스트됨 | +| CUDA의 기본 디코드 루프 | 충족 | + +PR 본문에는 `Closes #3669`가 있다. 병합하면 B200 성능 기준 두 개가 열린 채로 이슈가 닫히므로, 그 기준은 에픽 #3671 안에 자리가 필요하다. + +1부의 후속 목록(#3719 리포트 5.5절)을 항목별로 보면 다음과 같다. 항목 2는 전달되었다(2.1절부터 2.5절). 항목 3은 라우팅 가능한 요청에 대해 전달되었는데, `bounds`가 스레드로 옮겨가는 대신 bounds가 있는 행은 인라인에 남는다. 항목 4의 나머지는 감사 표이며, eager 파이프라인의 `read_lookahead_tokens`는 유지되고 문서화되었다. B200 측정은 여전히 미뤄져 있다. 자연스러운 시퀀스 끝 테스트는 전달되었다. + +## 5. 남은 항목 + +### 5.1 리뷰 후속 조치 + +리뷰 결과의 출처는 PR 본문의 Review 절이다. PR 자체에는 리뷰 코멘트가 없다. + +pr-reviewer는 CRITICAL이나 HIGH 이슈를 찾지 못했고 MEDIUM 두 건을 찾았으며, 둘 다 4685a8126에서 수정되었다. + +- `MLXCEL_MIXED_STEP` 경로는 chunk가 그 아래에서 도는 그래프 스텝을 prime했고, 다음 틱이 그것을 버렸다. 이제 디코드 동안 합류한 lookahead를 유지하고 chunk 전에 `prepare_admission`을 호출한다(2.5절). +- 라우팅된 행은 `Done`을 보내기 전에 등록이 해제되었으므로, 종료 중 panic이 나면 클라이언트가 에러를 받지 못했다. 이제 `Done`까지 등록된 채로 남는다(2.8절). + +pr-security-checker는 CRITICAL, HIGH, MEDIUM 이슈를 찾지 못했다. LOW 한 건은 e77c84fe6에서 수정되었다. `output_worker` 필드에 필요한 drop 순서를 그 필드에 문서화했다. + +### 5.2 열린 채로 둔 LOW + +- 출력 스레드가 그만큼 뒤처져 있으면, preemption된 라우팅 요청을 되찾을 때 스케줄러가 최대 10초(`DETACH_TIMEOUT`) 동안 멈춘다. 시간이 지나면 요청은 취소된다. +- `record_admission_teardown`은 eager lookahead의 해체도 세므로, `mlxcel_batch_decode_lookahead_admission_teardowns_total`은 그래프 틱에 한정되지 않는다. +- `admission_join_applies`의 멤버십 확인(`la.ids.iter().all(|id| seq_ids.contains(id))`와 그 역)은 배치 크기에 대해 이차다. id 집합이 lookahead와 다른 틱에서만 돈다. + +### 5.3 이슈와 다른 점 + +- **합류는 스텝 n+1을 prefill 전에 호스트로 읽는다.** 디바이스에서 넣지 않는다(2.1절). +- **워커당 bounded 큐 하나.** 이슈는 지금의 drop-to-disconnect 정책을 유지하는 요청별 bounded 채널을 요청했다. PR은 워커당 4096 레코드 큐 하나를 쓰고, 클라이언트 채널은 기존의 unbounded 채널로 둔다. 그래서 읽지 않는 클라이언트가 스케줄러를 멈추지는 않지만, 읽지 않은 이벤트는 main에서처럼 요청이 끝날 때까지 메모리에 남는다. +- **생성 한도가 있는 행은 인라인에 남는다.** 이슈는 스레드로 옮겨갈 것 중에 `bounds`를 넣었다. PR은 bounds가 없는 요청만 라우팅한다. `n_indent`와 `t_max_predict_ms`는 텍스트나 시간으로 다음 스텝 전에 요청을 끝낼 수 있기 때문이다. + +### 5.4 알려진 한계와 테스트 공백 + +- **서버에서는 모델 하나.** 서버 동일성은 Llama 3.2 1B 4bit에서만 돌았다. Gemma 4 12B 4bit는 서버 행렬이 아니라 스케줄러 테스트를 돌았다. +- **예산 256에서의 동일성은 null 대조가 한계를 정한다**(3.4절). +- **예산 스텝과 mixed 스텝의 합류 경로**는 `--max-num-batched-tokens 256`의 admission 테스트와 서버 행렬이 다룬다. `MLXCEL_MIXED_STEP` 경로의 수정에는 PR 본문상 전용 테스트가 없다. +- **멀티바이트 스케줄러 테스트는** Llama 3 chat 형식이 없는 토크나이저에서 건너뛴다. +- **라우팅된 요청의 preemption을 스케줄러로 구동하는 테스트가 없다.** detach는 출력 스레드 수준에서만 다룬다. + +### 5.5 문서와 코드의 차이 + +이 PR의 별도 커밋(8a115b5af)에서 수정: + +- `docs/CONTINUOUS_BATCHING.md`는 디코드 패드 행 해제를 "Teardown remains for" 아래에 적었다. `release_decode_pad_rows`는 `settle_lookahead`를 호출하며, 이 함수는 스텝을 읽고 lookahead를 유지한다. 이제 문단이 그렇게 말한다. +- `docs/environment-variables.md`의 `MLXCEL_PIPELINE_ADMISSION_JOIN` 행은 이슈의 표현을 따라 "블록을 해제하는 취소"가 파이프라인을 해체한다고 했다. `finalize_completed`는 끝났거나 취소된 모든 행에서 해체하며, `docs/CONTINUOUS_BATCHING.md`는 이미 그렇게 말했다. 이제 행은 "any finish or cancellation"이라고 말한다. +- 호스트 읽기 표에는 `prepare_admission` 행만 있었다. `release_decode_pad_rows`도 `settle_lookahead`를 통해 같은 pinned 읽기를 하므로, 이제 그 행이 둘 다 적는다. +- 두 문서 모두 CUDA의 모든 워커가 출력 스레드를 돌린다고 했다. `enable_output_thread`는 `Hybrid`와 `Router` 서빙 모드에서만 호출되고 speculative dispatch에서는 일찍 반환한다. 이제 두 문서 모두 분산 역할(`--node-role`)은 스트리밍을 인라인에 둔다고 말한다. +- `docs/CONTINUOUS_BATCHING.md`는 라우팅이 "prompt-lookup drafter"를 제외한다고 했다. `routable`은 모든 token-only drafter(`token_only`)를 제외하며, full-model `--draft-model`도 포함한다. 이제 문장이 그렇게 말한다. +- 합류 문단은 새 행이 스텝 n+2에서 "첫 토큰을 디코드한다"고 했다. 첫 토큰은 prefill에서 오고, 스텝 n+2는 그것을 forward한다. 이제 문장이 그렇게 말한다. + +수정하지 않음(소스 주석이며, 문서 커밋에서 Rust를 건드리지 않으려고 남김): + +- `admission_join.rs` 모듈 문서도 해체 아래에 "a released decode pad row"를 적는다. +- `prepare_admission`의 "Used by"는 Prefill 경로와 `execute_budgeted_step`만 적고, 4685a8126부터 이 함수를 호출하는 `MLXCEL_MIXED_STEP` 경로는 적지 않는다. + +### 5.6 B200 후속으로 미룬 항목 (에픽 #3671) + +- Gemma 4 31B NVFP4에서 c=8 steady 디코드 25초 동안 연속한 디코드 그래프 사이의 nsys 유휴 간격(목표: 중앙값 100 us 미만, p99 500 us 미만). +- c=1, 8, 32에서 전후 `scripts/bench/serving_compare.py` 표. c=1 회귀 한도 2%와 c=8, c=32 TPOT 개선 포함. +- 1, 4, 8, 64 행에서의 초당 스텝 수. + +이 wave에서 검증 대상은 GB10뿐이다. 이 리포트의 어떤 내용도 B200 측정에 근거하지 않는다. + +## 6. 학습 포인트 + +- **멤버십 변경을 가로질러 스텝을 유지할 때는 먼저 settle하는 편이 싸다.** prefill 전에 스텝 n+1을 호스트로 읽어도 공유 스트림이 이미 포기한 것 이상의 겹침은 잃지 않았고, KV 불변식은 "speculative append를 가진 것은 기존 행뿐"으로 유지되었다. 디바이스에서 넣었다면 한 틱 동안 섞인 스테이징이 필요했을 것이다. +- **조건을 넓히면 예전 조건이 배제하던 모든 경로에 부담이 옮겨간다.** 예전 `lookahead_safe`는 admission이 가까우면 파이프라인을 껐으므로, admission 근처의 경로는 lookahead를 볼 일이 없었다. 그 조건이 사라지자 mixed 스텝 경로, preemption, 패드 행 해제가 각자 기다리거나 되돌려야 했고, 리뷰는 그렇게 하지 않던 하나를 찾았다. +- **sender를 옮기면 순서를 통제하는 주체가 바뀐다.** 스케줄러가 라우팅된 요청에 보내는 이벤트는 private 채널을 거치고, 라우팅 링크가 매 토큰 전에 그 채널을 비운다. 그래서 클라이언트는 두 생산자로부터 하나의 순서 있는 스트림을 본다. +- **null 대조가 동일성 주장의 기준선을 정한다.** 예산 256에서 main과 main이 달랐으므로, 브랜치의 8개 중 8개는 그 바닥선에 비추어 읽어야 하고, 앞으로 그 예산에서 한 행이 다르게 나와도 그것만으로는 회귀가 아니다. +- **닫는 PR이 남기는 것을 적는다.** 이 PR은 두 성능 기준을 의도적으로 충족하지 않은 채 #3669를 닫는다. 리포트에 그것을 적어야 B200 작업이 끝난 것처럼 보이지 않는다. diff --git a/docs/CONTINUOUS_BATCHING.md b/docs/CONTINUOUS_BATCHING.md index b562ed233..ffc86535d 100644 --- a/docs/CONTINUOUS_BATCHING.md +++ b/docs/CONTINUOUS_BATCHING.md @@ -622,7 +622,22 @@ On CUDA most of a decode step's host time is the evaluation of its lazy MLX grap - **Feedback.** Step n+1's input tokens are step n's sampled tokens. They are copied on the device into the token slot of the persistent step-input buffer (`step_inputs::stage_i32_from_device`), after the step's host bytes and before the slot's event, so the staged layout is the one a host-staged step has: the pipelined step keys like the synchronous one and replays the same graph. - **Collect.** Step n's tokens are read from its pinned copy after its event (`PendingTokens::wait`), while step n+1 runs. Two slots per graph are enough because at most two steps are in flight; a read whose slot a third launch reused is refused rather than answered with later tokens. -The host therefore builds step n+1 while step n runs, and commits step n (stop checks, detokenization, streaming) while step n+1 runs. The rest is the #632 state machine unchanged: a row that finishes at step n (length, end of sequence, a stop string, a cancellation), an admission, a preemption or a changed id set waits for the step in flight, unwinds the speculative appends (`apply_lookahead_trim`) and re-runs the tick synchronously, which for a graph tick is a synchronous replay. Rows whose every layer is pool-backed layer state (Gemma 4 with its default paged sliding state) join the pipeline on these ticks too: the pool's block tables unwind their speculative appends exactly, which the eager pipeline cannot assume for scheduler-owned state, so on the eager path they stay synchronous as before. `verify` and `eager` modes never pipeline. `MLXCEL_DECODE_GRAPH_PIPELINE=0` restores #3668's routing: a replayed step is synchronous, by default a tick of more than one row that the lookahead pipeline can run stays with the eager pipeline, and `MLXCEL_DECODE_GRAPHS=always` replays the multi-row ticks synchronously too. The pipeline engages only where it engages for eager steps: no `--max-kv-size` bound (which a single-slot `--ctx-size` launch also sets), no pending admission, chunked prefill or preemption, and no loop detection. +The host therefore builds step n+1 while step n runs, and commits step n (stop checks, detokenization, streaming) while step n+1 runs. The rest is the #632 state machine unchanged: a row that finishes at step n (length, end of sequence, a stop string, a cancellation), an admission, a preemption or a changed id set waits for the step in flight, unwinds the speculative appends (`apply_lookahead_trim`) and re-runs the tick synchronously, which for a graph tick is a synchronous replay. Rows whose every layer is pool-backed layer state (Gemma 4 with its default paged sliding state) join the pipeline on these ticks too: the pool's block tables unwind their speculative appends exactly, which the eager pipeline cannot assume for scheduler-owned state, so on the eager path they stay synchronous as before. `verify` and `eager` modes never pipeline. `MLXCEL_DECODE_GRAPH_PIPELINE=0` restores #3668's routing: a replayed step is synchronous, by default a tick of more than one row that the lookahead pipeline can run stays with the eager pipeline, and `MLXCEL_DECODE_GRAPHS=always` replays the multi-row ticks synchronously too. The pipeline engages only where it engages for eager steps: no `--max-kv-size` bound (which a single-slot `--ctx-size` launch also sets), no pending preemption (and, with `MLXCEL_PIPELINE_ADMISSION_JOIN=0`, no pending admission or chunked prefill), and no loop detection. + +**Admissions join the pipeline (issue #3669).** An admission no longer tears a pipelined graph tick down. Before a queued prompt's prefill, a parked prefill's next chunk, or the prefill pieces of a budgeted step (`--max-num-batched-tokens`), the stored lookahead's in-flight step is read to the host (the prefill's forward would wait for it anyway, since both run on the generation stream) and kept with its speculative append. Step n+1 has then run with the old membership. On the next decode tick the old rows commit step n+1's tokens and step n+2 is launched over the whole batch, so a newly admitted row joins at the step after next, which forwards the first token its prefill sampled; from the tick after, the steady pipeline runs over the joined batch. Nothing is unwound and no step is run twice. Because a queued prompt or a parked chunked prefill no longer ends the pipeline, a pipelined graph tick keeps priming while requests wait; only a pending preemption stops it. Teardown remains for a preemption (the lookahead is torn down before the victim's caches are released), any finish or cancellation (`finalize_completed`), a lookahead built on the eager path, and a row that stops on step n+1's token (its tick unwinds the old rows' append and runs synchronously). Releasing a decode pad row does not tear the lookahead down: the step in flight read that row's block, so it is read to the host first (`settle_lookahead`) and kept. `MLXCEL_PIPELINE_ADMISSION_JOIN=0` restores the teardown. `/metrics` counts `mlxcel_batch_decode_lookahead_admission_joins_total` and `mlxcel_batch_decode_lookahead_admission_teardowns_total`. + +**Streaming on an output thread (issue #3669).** On CUDA each worker of the standard serving loop runs one output thread for detokenization and streaming, unless it dispatches speculative decoding; the disaggregated prefill and decode roles (`--node-role`) keep streaming on the scheduler thread. A request is routed to it when it joins the decode batch, if its text cannot decide its next step: no stop strings, no `n_indent` or `t_max_predict_ms` bound, and no token-only drafter (prompt lookup or a full-model `--draft-model`). Its first token is streamed by the prefill as before; from then on the scheduler thread only pushes token ids onto a bounded queue (4096 records), and the output thread runs the incremental detokenizer, sends the pieces, streams the held tail at the end, builds the final result, records its completion telemetry and sends `Done`. Finishes that depend on token ids only (end of sequence, `max_tokens`, the context bound) stay on the scheduler thread. Every other event the scheduler sends for a routed request (an error, a failed forward) goes through the same queue, in the order it was sent, so the client sees exactly the stream the scheduler thread would have sent. A slow client cannot stall the scheduler: the client channel is unbounded, so the output thread never waits on a client, and the queue only fills if detokenization falls behind decode by 4096 tokens. A panic while handling one request answers that request with an error and cancels it; other requests continue. A preempted request takes its client sender back from the output thread before it is re-queued. Requests with stop strings or generation bounds keep the synchronous path, because their text can end the request before the next step. `MLXCEL_OUTPUT_THREAD=0` keeps all streaming on the scheduler thread. Metal, ROCm and CPU builds never start the thread. + +**Synchronous host reads left on the decode path (issue #3669).** A pipelined graph tick reads only the pinned copy of the step before (after its event) and, on a teardown, waits for the step in flight without reading it. The reads that remain, and why: + +| Where | Read | Why it stays | +|---|---|---| +| `read_lookahead_tokens` (eager lookahead pipeline) | `try_tokens_to_host` on the step's lazy token array | An eager step is not a captured graph, so there is no pinned copy; the read waits for that step only, with the next one already scheduled | +| `Engine::step_padded` (synchronous step, `run_engine_step`) | Evaluation and host read of the sampled tokens | The synchronous step is the fallback for everything the pipeline does not run (stochastic draws, penalties, structured output, logprobs, a teardown re-run); its next step needs the token | +| Synchronous graph replay (`dispatch_sync_decode` armed) | The replay's own readback after a stream synchronize | A tick the pipeline cannot run has no step to overlap with | +| `step_rows.rs` | None | The row hooks read host state only (stop matcher, bounds, structured matcher); the token reaches them already on the host | +| `speculative_finalize.rs` | None directly | Speculative rounds (MTP, DFlash, prompt lookup) verify proposals against the target's tokens on the host inside the speculative drivers; acceptance needs the comparison before the next round, and those ticks are never pipelined | +| `prepare_admission`, `release_decode_pad_rows` (both through `settle_lookahead`) | The pinned copy of the step in flight | Taken before an admission's prefill, which would wait for that step on the shared stream anyway, and before a pad row's block goes back to the pool, since the step in flight reads it | **Controls and failure.** `MLXCEL_DECODE_GRAPHS=0` switches the feature off and restores the previous step unchanged; `always` replays every eligible step whatever the lookahead pipeline could do; `eager` keeps the step structure but evaluates every step, and `verify` replays and evaluates each step and fails it on a token mismatch (both are diagnostics). `MLXCEL_DECODE_GRAPH_MAX_BS` caps the bucket. A capture that fails before any node could have been marked evaluated leaves the step to be evaluated; a capture that fails after that point is fatal for the step, which fails, and graphs are disabled. Three non-fatal capture failures, or 48 captures with fewer replays than captures, also disable graphs. A CUDA error on a launch or readback fails that step's requests with the error string and disables graphs for that engine (each model engine has its own `DecodeGraphs`) with one error log. Misses, parameter mismatches, evictions, suspensions, capture failures and verify mismatches appear only in the log. Each capture logs `Captured decode graphs (buckets [...]) in s, arena `, and `/metrics` carries `mlxcel_batch_decode_graph_replays_total`, `mlxcel_batch_decode_graph_captures_total`, `mlxcel_batch_decode_graphs`, `mlxcel_batch_decode_graph_bytes` and `mlxcel_batch_decode_graph_pipelined_replays_total` (the replays launched before the previous step's tokens were read). A CUDA error while waiting for a pipelined replay's tokens fails that step's rows like a failed synchronous readback and disables graphs for the engine. Metal, ROCm and CPU builds never construct any of this: `mlxcel_core::step_graph::mode_from` returns off for every backend but CUDA whatever the environment says. diff --git a/docs/environment-variables.md b/docs/environment-variables.md index 73fd6f09d..da7d262ef 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -744,6 +744,8 @@ mode remains visible through startup logs and `kv_cache_mode_effective`. | `MLXCEL_DECODE_PADDING` | `0`/`false`/`off`/`no` disable (case-insensitive); anything else keeps the default; read once | on where `MLXCEL_STEP_INPUTS` is on (CUDA), off elsewhere | Whether a decode step over pooled rows is padded to its bucket size (issue #3667): 1, 2, 4, 8, 16, 24, 32, then every 16 up to `--parallel`, from `decode_bucket_for` in `src/server/batch/scheduler/step_rows.rs`. Pad rows run token id 0 through the model after the real rows, write their KV into a block of their own that no request reads, and have their logits dropped before sampling, so the real rows' tokens are those of the unpadded step. A step keeps a handful of shapes this way, which the whole-step graph capture of issue #3668 builds on. Padding applies only when every row keeps its KV in the paged block pool; Gemma 4 rows (scheduler-owned layer state, paged or dense), a single row and a step already at a bucket size run unpadded. A padded step computes the pad rows too, so a batch between two buckets (3, 5 to 7, 9 to 15 rows) does more work per step; set `0` to compare. | | `MLXCEL_DECODE_GRAPHS` | `0`/`false`/`off`/`no` disable; `always` replays every eligible step, including multi-row ticks the lookahead pipeline could run; `eager` keeps the replayable step structure but evaluates every step; `verify` replays and also evaluates each step, failing it on a token mismatch; anything else keeps the default; read once | on where `MLXCEL_STEP_INPUTS` is on (CUDA), never on elsewhere | Whether eligible decode steps are answered by launching a captured CUDA graph instead of evaluating the step's lazy MLX graph (issue #3668), read by `mlxcel_core::step_graph::mode`. A step is captured the second time its key comes up and replayed from then on: one `cudaGraphLaunch`, one upload of the step inputs and one readback of the sampled tokens, with no `cudaGraphAddKernelNode`, `cudaGraphExecUpdate`, `cudaGraphInstantiate` or `cudaGraphDestroy`. The key hashes the step's lazy graph (primitives, shapes, topology), the device address of every evaluated input (weights, pool slabs, the step-input buffer), the contents of small host constants, the staging layout and the sampler parameters, so a step that would hand the GPU anything else is evaluated. Eligible: every row keeps its KV in the paged pool (pooled families, and Gemma 4 with its default paged sliding state; not with `MLXCEL_PAGED_SLIDING=0`), one shared greedy draw (`temperature 0` or `top_k 1`), and no penalty, structured-output mask, token override, logprobs or speculative dispatch (a token bias stays eligible). Everything else, and every backend but CUDA, runs the eager step. A tick the lookahead pipeline can run is replayed on the pipeline (`MLXCEL_DECODE_GRAPH_PIPELINE`, issue #3669): step n+1's graph is launched before step n's tokens are read. Every other eligible tick is replayed synchronously. With `MLXCEL_DECODE_GRAPH_PIPELINE=0` a replayed step is always synchronous, so by default a tick of more than one row that the lookahead pipeline can run stays with the eager pipeline (on GB10 with Llama 3.2 1B the pipelined eager step decoded 134 and 100 steps/s at four and eight rows against 126 and 95 replayed synchronously, while one row replayed at 206 against 180), and `always` replays the multi-row ticks synchronously too. Graph steps always take the fused paged read, and plan it for the batch's page tier (a power of two), so their rounding can differ from `0` in the last bit. `0` restores the previous step unchanged. `eager` and `verify` are diagnostics: `eager` is the arm a parity run compares replay against, `verify` doubles the work of every step. A CUDA error on a replay fails that step's requests and disables graphs for that engine (each model engine has its own decode-graph state) with one error log. Counters: `mlxcel_batch_decode_graph_replays_total`, `mlxcel_batch_decode_graph_captures_total`, `mlxcel_batch_decode_graphs`, `mlxcel_batch_decode_graph_bytes` and `mlxcel_batch_decode_graph_pipelined_replays_total` on `/metrics`. See [CONTINUOUS_BATCHING.md](CONTINUOUS_BATCHING.md#decode-graphs-on-cuda). | | `MLXCEL_DECODE_GRAPH_PIPELINE` | `0`/`false`/`off`/`no` disable (case-insensitive); anything else keeps the default; read once | on wherever decode graphs replay (CUDA), never on elsewhere | Whether a decode-graph tick that the lookahead pipeline can run is pipelined (issue #3669), read by `mlxcel_core::step_graph::pipeline_requested` and combined with the `MLXCEL_DECODE_GRAPHS` mode (`verify` and `eager` never pipeline). Step n+1 is built and, when it matches a captured graph, launched with a copy of its tokens queued into a pinned slot behind it, fed step n's tokens by a device-to-device copy into the step-input buffer, before step n's tokens are read from their own pinned copy; the host then commits step n (stop checks, detokenization, streaming) while the GPU runs step n+1. Rows whose every layer is pool-backed layer state (Gemma 4 with its default paged sliding state) join the pipeline on these ticks. Off restores #3668's routing, where a replay is synchronous and multi-row ticks the pipeline can run stay eager. Counter: `mlxcel_batch_decode_graph_pipelined_replays_total` on `/metrics`. See [CONTINUOUS_BATCHING.md](CONTINUOUS_BATCHING.md#decode-graphs-on-cuda). | +| `MLXCEL_PIPELINE_ADMISSION_JOIN` | `0`/`false`/`off`/`no` disable (case-insensitive); anything else keeps the default; read once | on wherever decode-graph ticks pipeline (CUDA), never on elsewhere | Whether an admission keeps a pipelined decode-graph tick running (issue #3669). Before a prompt's prefill, a prefill chunk or a budgeted step's prefill pieces (`--max-num-batched-tokens`), the step in flight is read to the host and kept; the next decode tick commits it to the old rows and launches the step after over the whole batch, so a new row joins at step n+2 instead of the pipeline being torn down and refilled. A preemption, any finish or cancellation, and a row that stops on the kept step's token still tear it down. Off restores the teardown on every admission. Counters: `mlxcel_batch_decode_lookahead_admission_joins_total` and `mlxcel_batch_decode_lookahead_admission_teardowns_total` on `/metrics`. See [CONTINUOUS_BATCHING.md](CONTINUOUS_BATCHING.md#decode-graphs-on-cuda). | +| `MLXCEL_OUTPUT_THREAD` | `0`/`false`/`off`/`no` disable (case-insensitive); anything else keeps the default; read once | on with the CUDA backend, never on elsewhere | Whether each model worker runs an output thread for detokenization and streaming (issue #3669). Only the standard serving loop starts it; the disaggregated prefill and decode roles (`--node-role`) keep streaming on the scheduler thread. A request without stop strings, a generation bound or a token-only row is routed to it when it joins the decode batch: the scheduler hands it each sampled token through a bounded queue and goes on to the next step, and the thread detokenizes, streams and sends the final result in the order the scheduler produced them. A client that reads slowly does not stall the scheduler, and a detokenization failure fails only that request. Requests whose text decides their next step, and every request of a worker that dispatches speculative decoding, stream on the scheduler thread as before. Off keeps all streaming on the scheduler thread. See [CONTINUOUS_BATCHING.md](CONTINUOUS_BATCHING.md#decode-graphs-on-cuda). | | `MLXCEL_DECODE_GRAPH_MAX_BS` | positive integer; unset, `0` or unparsable means no cap; read once | no cap | Largest decode bucket (rows after padding) that runs as a decode-graph step (issue #3668), read by `mlxcel_core::step_graph::max_bucket`. A larger step keeps the eager step and the lookahead pipeline. Each captured graph keeps the buffers of its step's intermediates alive (reported as `arena` in the capture log line and as `mlxcel_batch_decode_graph_bytes`), which grows with the bucket and the vocabulary; lower the cap to bound that. | | `MLXCEL_DECODE_GRAPH_DUMP` | directory path; unset or empty disables; read once | unset | Diagnostic for decode graphs (issue #3668), read by `mlxcel_core::engine::decode_graphs`. The first 12 decode-graph steps that match no captured graph write `decode-graph-miss-.txt` into the directory: the step's key (graph signature, staging layout hash, noted host values) and one line per input and node of its lazy graph with the address or content hash, shapes and running hash each contributes. A family whose eligible steps never replay changes something every step; a `diff` of two consecutive files shows which input or node. Has no effect where decode graphs are off. | | `MLXCEL_KV_INPLACE_WRITE` | `0`/`false`/`off`/`no` disables | on | A single-token FP16 decode step writes its K/V row into the dense cache buffer in place instead of through `slice_update` (#1959). While the previous pipelined step is in flight its command buffer holds the cache buffer, so `slice_update` could never donate it and copied the whole cache every step. The in-place write is taken only when the cache's own last write produced the current buffers and nothing rolled it back since, so a buffer shared with a prompt-cache snapshot, a restored or detached cache never has a row it holds rewritten; any other case takes one copying write and returns to in-place. Measured on M1 Ultra (`bench_decode.sh`, tg128): command-r7b 4-bit +2.5% decode at context 16, +4.1% at 512, +8.2% at 2048; Llama 3.1 8B +4.6% and Qwen2.5 7B +2.7% at 512; peak memory footprint about 0.6 GB lower at 2048 + 512. The rotating sliding-window cache takes the same path while it is still filling its window (every slot is new), which is +3% decode on Gemma 3 4B and Gemma 4 12B at pp512; once the window is full each step overwrites a slot a snapshot may still hold, so those writes keep copying. The server's paged KV pool takes the same in-place write for rows of a block held by one sequence that already owns its pool row (#1964): under the default lookahead decode the slab copy halved single-request decode, and the fix takes Llama 3.1 8B from 47 to 105 tok/s and Qwen2.5 7B from 68 to 108 at concurrency 1, with aggregate throughput +16 to +38% at concurrency 4. Disable only to compare against the copying path. | diff --git a/src/server/batch/active.rs b/src/server/batch/active.rs index b3c0791e7..ffc53753d 100644 --- a/src/server/batch/active.rs +++ b/src/server/batch/active.rs @@ -178,6 +178,7 @@ mod tests { let decode_state = StreamingDecodeState::new(&tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id: SequenceId::from_raw(id_val), diff --git a/src/server/batch/finish.rs b/src/server/batch/finish.rs index 73fd3c92b..f6cf0993f 100644 --- a/src/server/batch/finish.rs +++ b/src/server/batch/finish.rs @@ -28,6 +28,7 @@ use mlxcel_core::sampling::TokenLogprobData; use mlxcel_core::{FinishCause, FinishHooks, FinishInput, finish_step}; use super::generation_bounds::GenerationBounds; +use super::output_thread::RoutedOutput; use super::sequence::{FinishReason, SequenceInfo, SequenceState, emit_decoded_piece}; use super::stop_matcher::StopMatcher; use crate::server::model_provider::GenerateEvent; @@ -110,6 +111,9 @@ pub(crate) struct SequenceFinishHooks<'s> { pub(crate) stop_matcher: &'s mut StopMatcher, pub(crate) bounds: &'s mut GenerationBounds, pub(crate) response_tx: &'s mpsc::Sender, + /// The request's link to the output thread when it is routed (#3669): + /// its tokens are pushed there and detokenized off this thread. + pub(crate) routed: Option<&'s RoutedOutput>, pub(crate) tokenizer: &'s MlxcelTokenizer, pub(crate) logprobs: Option, pub(crate) prompt_len: usize, @@ -119,6 +123,14 @@ pub(crate) struct SequenceFinishHooks<'s> { impl FinishHooks for SequenceFinishHooks<'_> { fn stop_text(&mut self, token: i32, generated_len: usize) -> bool { + // A routed request has no stop strings and no generation bound + // (`output_thread::routable`), so its text never stops it: the output + // thread detokenizes and streams the token, exactly as the inactive + // matcher below would, and the answer here is the matcher's `false`. + if let Some(routed) = self.routed { + routed.token(token, generated_len, self.logprobs.take()); + return false; + } // Stream through the request's stop matcher (#1466): text that could // still become a stop string is held back, and a completed stop string // ends the sequence with the match excluded. @@ -166,6 +178,7 @@ pub(crate) fn run_finish_step( stop_matcher, bounds, response_tx, + routed, generated_tokens, sampling, prompt_tokens, @@ -180,6 +193,7 @@ pub(crate) fn run_finish_step( stop_matcher, bounds, response_tx, + routed: routed.as_ref(), tokenizer, logprobs, prompt_len: prompt_tokens.len(), diff --git a/src/server/batch/finish_step_tests.rs b/src/server/batch/finish_step_tests.rs index 905dff3ba..08eaa2567 100644 --- a/src/server/batch/finish_step_tests.rs +++ b/src/server/batch/finish_step_tests.rs @@ -164,6 +164,7 @@ fn make_sequence( let mut sampling = SamplingConfig::greedy(); sampling.loop_detection = s.loop_detection; let seq = SequenceInfo { + routed: None, bounds: GenerationBounds::new(s.n_indent, None), retention: Default::default(), seq_id: SequenceId::from_raw(2168), diff --git a/src/server/batch/mod.rs b/src/server/batch/mod.rs index c99814c3a..70b6eea1b 100644 --- a/src/server/batch/mod.rs +++ b/src/server/batch/mod.rs @@ -46,6 +46,9 @@ pub(crate) mod generation_bounds; /// keeping `MLXCEL_ENABLE_MTP_B1` as a manual force. pub(crate) mod mtp_policy; pub mod observability; +/// Off-thread detokenization and streaming on CUDA (issue #3669): the +/// per-worker output thread routed decode rows stream through. +pub(crate) mod output_thread; mod prefill_cohort; mod queue; #[path = "scheduler/mod.rs"] diff --git a/src/server/batch/observability.rs b/src/server/batch/observability.rs index c0b191d9d..cf43fa4ce 100644 --- a/src/server/batch/observability.rs +++ b/src/server/batch/observability.rs @@ -225,6 +225,13 @@ pub struct BatchObservability { pub decode_graphs: AtomicU64, pub decode_graph_bytes: AtomicU64, pub decode_graph_pipelined_replays: AtomicU64, + /// Admissions joined to the pipelined decode loop (issue #3669): a + /// decode tick committed the kept lookahead's step to the old rows and + /// primed the next step over the joined batch. + pub decode_lookahead_admission_joins: AtomicU64, + /// Admissions that tore a stored lookahead down (issue #3669): every + /// admission off CUDA, or with `MLXCEL_PIPELINE_ADMISSION_JOIN=0`. + pub decode_lookahead_admission_teardowns: AtomicU64, // -- llama-server b10621 metric families (issue #1440) -- /// Prompt tokens actually forwarded through prefill, excluding tokens @@ -449,6 +456,8 @@ impl BatchObservability { decode_graphs: AtomicU64::new(0), decode_graph_bytes: AtomicU64::new(0), decode_graph_pipelined_replays: AtomicU64::new(0), + decode_lookahead_admission_joins: AtomicU64::new(0), + decode_lookahead_admission_teardowns: AtomicU64::new(0), llama_prompt_tokens_processed: AtomicU64::new(0), llama_prompt_tokens_cached: AtomicU64::new(0), llama_prompt_us_total: AtomicU64::new(0), @@ -615,6 +624,18 @@ impl BatchObservability { self.decode_lookahead_steps.fetch_add(1, Ordering::Relaxed); } + /// Record one admission joined to the pipelined decode loop (#3669). + pub fn record_admission_join(&self) { + self.decode_lookahead_admission_joins + .fetch_add(1, Ordering::Relaxed); + } + + /// Record one admission that tore a stored lookahead down (#3669). + pub fn record_admission_teardown(&self) { + self.decode_lookahead_admission_teardowns + .fetch_add(1, Ordering::Relaxed); + } + /// Record one decode forward that ran with pad rows (issue #3667). pub fn record_padded_step(&self) { self.decode_padded_steps.fetch_add(1, Ordering::Relaxed); @@ -932,6 +953,12 @@ impl BatchObservability { decode_graph_pipelined_replays: self .decode_graph_pipelined_replays .load(Ordering::Relaxed), + decode_lookahead_admission_joins: self + .decode_lookahead_admission_joins + .load(Ordering::Relaxed), + decode_lookahead_admission_teardowns: self + .decode_lookahead_admission_teardowns + .load(Ordering::Relaxed), current_batch_size: self.current_batch_size.load(Ordering::Relaxed), current_queue_depth: self.current_queue_depth.load(Ordering::Relaxed), cache_pool_active: self.cache_pool_active.load(Ordering::Relaxed), @@ -1087,6 +1114,10 @@ pub struct ObservabilitySnapshot { pub decode_graphs: u64, pub decode_graph_bytes: u64, pub decode_graph_pipelined_replays: u64, + /// Admissions joined to the pipelined decode loop (issue #3669). + pub decode_lookahead_admission_joins: u64, + /// Admissions that tore a stored lookahead down (issue #3669). + pub decode_lookahead_admission_teardowns: u64, pub current_batch_size: usize, pub current_queue_depth: usize, pub cache_pool_active: usize, diff --git a/src/server/batch/output_thread.rs b/src/server/batch/output_thread.rs new file mode 100644 index 000000000..ac3958ba5 --- /dev/null +++ b/src/server/batch/output_thread.rs @@ -0,0 +1,561 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Off-thread detokenization and streaming (issue #3669, item 3). +//! +//! The scheduler thread used to detokenize every committed token and send +//! the piece to the client itself (`SequenceFinishHooks::stop_text`). With +//! the decode step pipelined on CUDA, that host work runs while the next +//! step is on the GPU, but it still sits on the thread that launches the +//! step after that. This module moves it to one output thread per worker. +//! +//! A request is routed when its text cannot decide whether the next step +//! runs: no stop strings, no b10621 generation bound (`n_indent`, +//! `t_max_predict_ms`), and no token-only drafter. Its finish then depends on +//! token ids only (EOS, `max_tokens`, the context bound), which stay on the +//! scheduler thread. Requests with stop strings keep the synchronous path. +//! +//! Routing happens when the prompt joins the decode batch, after its first +//! token was streamed by the prefill. The request's detokenizer state and +//! its client sender move to the output thread ([`OutputRecord::Attach`]); +//! the sequence keeps a sender into a private channel instead, so every +//! event the scheduler still sends for it (an error, a preemption notice) +//! lands in that channel in program order. The scheduler forwards those +//! events onto the output thread's queue before each token it pushes and +//! before the request's finish, so the client sees them in exactly the order +//! the scheduler produced them. +//! +//! The output thread's queue is bounded ([`QUEUE_CAPACITY`] records). A slow +//! client cannot fill it: the client channel is unbounded, so the output +//! thread never blocks on a client. Only a detokenizer that falls behind the +//! decode loop by the whole queue makes the scheduler wait, which is the +//! back-pressure that keeps memory bounded. +//! +//! A panic while handling one request's record fails that request alone: it +//! is answered with an error, its cancellation flag is set so the scheduler +//! finishes it, and its later records are dropped. +//! +//! CUDA only, behind [`OUTPUT_THREAD_ENV`]: the worker spawns the thread +//! only where [`output_thread_requested`] is true, and a scheduler without +//! one routes nothing, so Metal, ROCm and CPU keep the synchronous path. + +use std::collections::{HashMap, HashSet}; +use std::panic::AssertUnwindSafe; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc; +use std::thread::JoinHandle; +use std::time::Duration; + +use mlxcel_core::hardware::GpuBackendKind; +use mlxcel_core::sampling::TokenLogprobData; + +use super::observability::BatchObservability; +use super::sequence::{ResultTemplate, SequenceInfo}; +use crate::server::model_provider::model_worker::StreamingDecodeState; +use crate::server::model_provider::{GenerateEvent, TokenMeta}; +use crate::tokenizer::MlxcelTokenizer; + +/// Environment switch for the output thread: `0`/`false`/`off`/`no` keeps +/// detokenization and streaming on the scheduler thread. Unset means on for +/// CUDA and off elsewhere. +pub(crate) const OUTPUT_THREAD_ENV: &str = "MLXCEL_OUTPUT_THREAD"; + +/// Records the output thread's queue holds before the scheduler waits. +pub(crate) const QUEUE_CAPACITY: usize = 4096; + +/// How long a preemption waits for the output thread to hand a request's +/// client sender back before the request is failed instead. +const DETACH_TIMEOUT: Duration = Duration::from_secs(10); + +/// Whether the worker runs an output thread: [`OUTPUT_THREAD_ENV`] read once, +/// else on CUDA only. +/// +/// Used by: `BatchScheduler::enable_output_thread` +pub(crate) fn output_thread_requested() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + output_thread_from( + std::env::var(OUTPUT_THREAD_ENV).ok().as_deref(), + mlxcel_core::hardware::gpu_backend_kind(), + ) + }) +} + +/// Pure resolution behind [`output_thread_requested`]. The environment can +/// turn the thread off on CUDA; it cannot turn it on anywhere else. +#[must_use] +pub(crate) fn output_thread_from(env: Option<&str>, backend: GpuBackendKind) -> bool { + backend == GpuBackendKind::Cuda + && !matches!( + env.map(|v| v.trim().to_ascii_lowercase()).as_deref(), + Some("0" | "false" | "off" | "no") + ) +} + +/// Whether `seq`'s text can never decide its next step, so its +/// detokenization may run behind the scheduler. +pub(crate) fn routable(seq: &SequenceInfo) -> bool { + !seq.stop_matcher.is_active() + && !seq.bounds.is_active() + && seq.token_only.is_none() + && !seq.state.is_finished() +} + +/// One unit of work for the output thread. Records of one request are +/// handled in the order they were queued. +enum OutputRecord { + /// The request's client sender and detokenizer state move here. + Attach { + key: u64, + client: mpsc::Sender, + state: Box, + cancelled: Arc, + }, + /// One committed token: detokenize it and stream the piece. + Token { + key: u64, + token: i32, + decoded: usize, + logprobs: Option, + }, + /// An event the scheduler sent for the request, forwarded as it is. + Event { key: u64, event: GenerateEvent }, + /// The request finished: stream the detokenizer's held tail, build the + /// result and send `Done`. + Finish { + key: u64, + template: Box, + }, + /// Hand the client sender back (a preemption re-queues the request). + Detach { + key: u64, + reply: mpsc::Sender>>, + }, + /// The sequence was dropped without a finish: drop its client sender. + Close { key: u64 }, +} + +impl OutputRecord { + fn key(&self) -> u64 { + match self { + Self::Attach { key, .. } + | Self::Token { key, .. } + | Self::Event { key, .. } + | Self::Finish { key, .. } + | Self::Detach { key, .. } + | Self::Close { key } => *key, + } + } +} + +/// What the output thread has done, for tests and logs. +#[derive(Debug, Default)] +pub(crate) struct OutputStats { + /// Requests routed to the thread. + pub(crate) attached: AtomicU64, + /// Tokens detokenized on the thread. + pub(crate) tokens: AtomicU64, + /// Requests the thread failed (a panic while handling one of them). + pub(crate) failed: AtomicU64, +} + +/// The output thread of one worker and the scheduler's handle on it. +pub(crate) struct OutputWorker { + tx: Option>, + handle: Option>, + next_key: u64, + stats: Arc, +} + +impl OutputWorker { + /// Spawn the thread. `observability` receives each routed request's + /// completion telemetry, which the scheduler records itself for the + /// requests it streams. + pub(crate) fn spawn( + tokenizer: Arc, + observability: Option>, + ) -> std::io::Result { + Self::spawn_with(tokenizer, observability, None) + } + + /// [`Self::spawn`], where `fail_on_token` makes the thread panic while + /// handling that token id (tests only). + fn spawn_with( + tokenizer: Arc, + observability: Option>, + fail_on_token: Option, + ) -> std::io::Result { + let (tx, rx) = mpsc::sync_channel(QUEUE_CAPACITY); + let stats = Arc::new(OutputStats::default()); + let thread_stats = Arc::clone(&stats); + let handle = std::thread::Builder::new() + .name("mlxcel-output".to_string()) + .spawn(move || { + OutputThread { + tokenizer, + observability, + stats: thread_stats, + rows: HashMap::new(), + failed: HashSet::new(), + fail_on_token, + } + .run(&rx); + })?; + Ok(Self { + tx: Some(tx), + handle: Some(handle), + next_key: 0, + stats, + }) + } + + /// Counters for tests and logs. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn stats(&self) -> &OutputStats { + &self.stats + } + + /// Route `seq` to the output thread when [`routable`] allows it: its + /// client sender and detokenizer state move to the thread, and + /// `seq.routed` takes their place. Returns whether it was routed. + pub(crate) fn attach(&mut self, seq: &mut SequenceInfo, tokenizer: &MlxcelTokenizer) -> bool { + if seq.routed.is_some() || !routable(seq) { + return false; + } + let Some(tx) = self.tx.clone() else { + return false; + }; + let key = self.next_key; + self.next_key += 1; + let (events_tx, events_rx) = mpsc::channel(); + let client = std::mem::replace(&mut seq.response_tx, events_tx); + let state = std::mem::replace( + &mut seq.decode_state, + StreamingDecodeState::new(tokenizer, &[]), + ); + let record = OutputRecord::Attach { + key, + client, + state: Box::new(state), + cancelled: Arc::clone(&seq.cancelled), + }; + match tx.send(record) { + Ok(()) => { + seq.routed = Some(RoutedOutput { + key, + events: events_rx, + tx, + closed: false, + }); + true + } + Err(mpsc::SendError(OutputRecord::Attach { client, state, .. })) => { + // The thread is gone: keep streaming on the scheduler. + seq.response_tx = client; + seq.decode_state = *state; + false + } + Err(_) => false, + } + } +} + +impl Drop for OutputWorker { + fn drop(&mut self) { + // Closing the queue ends the thread once it has handled every record + // already queued, so no routed request loses its tail or `Done`. + drop(self.tx.take()); + tracing::debug!( + attached = self.stats.attached.load(Ordering::Relaxed), + tokens = self.stats.tokens.load(Ordering::Relaxed), + failed = self.stats.failed.load(Ordering::Relaxed), + "output thread stopping" + ); + if let Some(handle) = self.handle.take() + && handle.join().is_err() + { + tracing::error!("output thread panicked outside a request"); + } + } +} + +/// A routed sequence's link to the output thread, held in +/// [`SequenceInfo::routed`]. +pub(crate) struct RoutedOutput { + key: u64, + /// What the scheduler sent through the sequence's `response_tx` since the + /// last forward, in the order it sent it. + events: mpsc::Receiver, + tx: mpsc::SyncSender, + /// A finish or detach has been queued; nothing more is sent. + closed: bool, +} + +impl RoutedOutput { + fn push(&self, record: OutputRecord) { + // A closed queue means the thread is gone, and with it the client + // sender: the client has already seen its stream end. + let _ = self.tx.send(record); + } + + /// Forward the events the scheduler sent since the last forward. + fn forward_events(&self) { + while let Ok(event) = self.events.try_recv() { + self.push(OutputRecord::Event { + key: self.key, + event, + }); + } + } + + /// Queue one committed token, after any event the scheduler sent before + /// it. + pub(crate) fn token(&self, token: i32, decoded: usize, logprobs: Option) { + self.forward_events(); + self.push(OutputRecord::Token { + key: self.key, + token, + decoded, + logprobs, + }); + } + + /// Queue the request's finish: the thread streams the held tail, builds + /// the result from `template` and its detokenizer state, and sends `Done`. + pub(crate) fn finish(mut self, template: ResultTemplate) { + self.forward_events(); + self.push(OutputRecord::Finish { + key: self.key, + template: Box::new(template), + }); + self.closed = true; + } + + /// Take the client sender back from the thread, after every record + /// queued before (a preemption re-queues the request and re-prefills it + /// on the scheduler). `None` when the thread failed the request or did + /// not answer within [`DETACH_TIMEOUT`]. + pub(crate) fn detach(mut self) -> Option> { + self.forward_events(); + let (reply, answer) = mpsc::channel(); + self.push(OutputRecord::Detach { + key: self.key, + reply, + }); + self.closed = true; + answer.recv_timeout(DETACH_TIMEOUT).ok().flatten() + } +} + +impl Drop for RoutedOutput { + fn drop(&mut self) { + if !self.closed { + // The sequence left without a finish (an abort, a shutdown drain): + // deliver what it was sent, then let the client stream end. + self.forward_events(); + self.push(OutputRecord::Close { key: self.key }); + } + } +} + +struct Row { + client: mpsc::Sender, + state: StreamingDecodeState, + cancelled: Arc, +} + +struct OutputThread { + tokenizer: Arc, + observability: Option>, + stats: Arc, + rows: HashMap, + /// Requests failed by a panic; their later records are dropped. + failed: HashSet, + fail_on_token: Option, +} + +impl OutputThread { + fn run(mut self, rx: &mpsc::Receiver) { + while let Ok(record) = rx.recv() { + let key = record.key(); + if self.failed.contains(&key) { + match record { + OutputRecord::Detach { reply, .. } => { + let _ = reply.send(None); + self.failed.remove(&key); + } + OutputRecord::Finish { .. } | OutputRecord::Close { .. } => { + self.failed.remove(&key); + } + _ => {} + } + continue; + } + // No record follows a finish, a detach or a close, so a request + // failed on one of those is not remembered as failed. + let last = matches!( + record, + OutputRecord::Finish { .. } + | OutputRecord::Detach { .. } + | OutputRecord::Close { .. } + ); + let outcome = std::panic::catch_unwind(AssertUnwindSafe(|| self.handle(record))); + if let Err(panic) = outcome { + self.fail(key, &panic_message(panic.as_ref())); + if last { + self.failed.remove(&key); + } + } + } + } + + fn handle(&mut self, record: OutputRecord) { + match record { + OutputRecord::Attach { + key, + client, + state, + cancelled, + } => { + self.stats.attached.fetch_add(1, Ordering::Relaxed); + self.rows.insert( + key, + Row { + client, + state: *state, + cancelled, + }, + ); + } + OutputRecord::Token { + key, + token, + decoded, + logprobs, + } => { + if self.fail_on_token == Some(token) { + panic!("injected detokenization failure on token {token}"); + } + let Some(row) = self.rows.get_mut(&key) else { + return; + }; + self.stats.tokens.fetch_add(1, Ordering::Relaxed); + // Exactly the scheduler's `stop_text` with an inactive stop + // matcher: a piece only when the detokenizer emits one, and + // the token's logprobs ride that piece or are dropped. + if let Some(text) = row.state.on_token(token, &self.tokenizer) { + let meta = TokenMeta { + token_id: Some(token), + decoded: Some(decoded), + ..TokenMeta::default() + }; + let event = match logprobs { + Some(lp) => GenerateEvent::TokenWithLogprobs(text, meta, lp), + None => GenerateEvent::Token(text, meta), + }; + let _ = row.client.send(event); + } + } + OutputRecord::Event { key, event } => { + if let Some(row) = self.rows.get(&key) { + let _ = row.client.send(event); + } + } + OutputRecord::Finish { key, template } => { + // The row stays registered until `Done` is sent, so a panic + // while finishing still answers the client with an error. + let Some(row) = self.rows.get_mut(&key) else { + return; + }; + // `close_text_stream` with an inactive stop matcher: the held + // tail goes out as one more token event, counted like the + // scheduler counts it. + if let Some(tail) = row.state.flush(&self.tokenizer) { + let meta = TokenMeta { + token_id: None, + decoded: Some(template.generated_len()), + ..TokenMeta::default() + }; + let _ = row.client.send(GenerateEvent::Token(tail, meta)); + } + let state = std::mem::replace( + &mut row.state, + StreamingDecodeState::new(&self.tokenizer, &[]), + ); + let result = template.build(state); + if let Some(obs) = &self.observability { + obs.record_request_completion( + result.prompt_tokens, + result.cached_tokens, + result.prompt_eval_ms, + result.generation_only_ms, + result.completion_tokens, + result.decode_window_tokens, + ); + } + tracing::info!( + prompt_tokens = result.prompt_tokens, + cached_tokens = result.cached_tokens, + generation_time_ms = result.generation_time_ms, + "prompt-cache: request completed: cached={}/{} prompt tokens, total {}ms", + result.cached_tokens, + result.prompt_tokens, + result.generation_time_ms, + ); + if let Some(row) = self.rows.remove(&key) { + let _ = row.client.send(GenerateEvent::Done(result)); + } + } + OutputRecord::Detach { key, reply } => { + let _ = reply.send(self.rows.remove(&key).map(|row| row.client)); + } + OutputRecord::Close { key } => { + self.rows.remove(&key); + } + } + } + + /// Fail `key` alone: answer its client with an error, ask the scheduler + /// to finish it, and drop its later records. + fn fail(&mut self, key: u64, message: &str) { + tracing::error!( + request = key, + error = message, + "output thread failed a request" + ); + self.stats.failed.fetch_add(1, Ordering::Relaxed); + if let Some(row) = self.rows.remove(&key) { + row.cancelled.store(true, Ordering::Relaxed); + let _ = row.client.send(GenerateEvent::Error(format!( + "streaming output failed: {message}" + ))); + } + self.failed.insert(key); + } +} + +fn panic_message(panic: &(dyn std::any::Any + Send)) -> String { + if let Some(s) = panic.downcast_ref::<&str>() { + (*s).to_string() + } else if let Some(s) = panic.downcast_ref::() { + s.clone() + } else { + "panic".to_string() + } +} + +#[cfg(test)] +#[path = "output_thread_tests.rs"] +mod tests; diff --git a/src/server/batch/output_thread_tests.rs b/src/server/batch/output_thread_tests.rs new file mode 100644 index 000000000..7d993f578 --- /dev/null +++ b/src/server/batch/output_thread_tests.rs @@ -0,0 +1,469 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The output thread against the scheduler-thread stream (issue #3669). +//! +//! Each test drives the same token streams through the production finish +//! entry point (`finish_decode_token`, the engine's finish step over the +//! sequence's hooks) twice: once streamed on the calling thread, once routed +//! to an [`OutputWorker`]. The client must see the same events either way. +//! The tokenizer is Llama 3.2's byte-level BPE, so multi-byte UTF-8 +//! characters split across tokens and the detokenizer holds partial pieces +//! back. Skipped when the checkpoint's tokenizer is not on disk. + +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, mpsc}; +use std::time::{Duration, Instant}; + +use mlxcel_core::cache::SequenceId; +use mlxcel_core::generate::SamplingConfig; + +use super::*; +use crate::server::batch::RequestPriority; +use crate::server::batch::finish::{ContextBound, finish_decode_token}; +use crate::server::batch::generation_bounds::GenerationBounds; +use crate::server::batch::sequence::{SequenceInfo, SequenceState}; +use crate::server::batch::stop_matcher::StopMatcher; + +const TOKENIZER_DIR: &str = "models/llama-3.2-1b-instruct-4bit"; + +fn tokenizer() -> Option> { + let dir = Path::new(TOKENIZER_DIR); + if !dir.join("tokenizer.json").exists() { + if std::env::var("MLXCEL_REQUIRE_MODELS").is_ok_and(|v| v != "0") { + panic!("MLXCEL_REQUIRE_MODELS is set: no tokenizer at {TOKENIZER_DIR}"); + } + eprintln!("SKIPPED output_thread tests: no tokenizer at {TOKENIZER_DIR}"); + return None; + } + Some(Arc::new( + crate::tokenizer::load_tokenizer(dir).expect("load tokenizer"), + )) +} + +fn encode(tokenizer: &MlxcelTokenizer, text: &str) -> Vec { + tokenizer + .encode(text, false) + .expect("tokenize") + .into_iter() + .map(|t| t as i32) + .collect() +} + +/// Four replies, each with characters of two to four UTF-8 bytes. +const REPLIES: [&str; 4] = [ + "안녕하세요, 세계! 오늘은 바다가 잔잔합니다. 🌊🌊", + "Café crème, naïve façade, Größe, Ærøskøbing — ok.", + "日本語のテキストと絵文字 🍣🍜 を混ぜた返事です。", + "Ελληνικά και русский текст 🚀 with emoji 👩‍🚀 and ∑∫√.", +]; + +fn sequence( + tokenizer: &MlxcelTokenizer, + prompt: &[i32], + max_tokens: usize, +) -> (SequenceInfo, mpsc::Receiver) { + let (tx, rx) = mpsc::channel(); + let seq = SequenceInfo { + bounds: GenerationBounds::default(), + retention: Default::default(), + seq_id: SequenceId::from_raw(3669), + state: SequenceState::Decoding, + prompt_tokens: prompt.to_vec(), + sampling: SamplingConfig::greedy(), + max_tokens, + eos_token_ids: Vec::new(), + priority: RequestPriority::Normal, + lora_scales: None, + logprobs_config: Default::default(), + vlm_embeddings: None, + images: Vec::new(), + audio: Vec::new(), + generated_tokens: Vec::new(), + generated_text: String::new(), + decode_state: StreamingDecodeState::new(tokenizer, prompt), + stop_matcher: StopMatcher::default(), + prefill_offset: prompt.len(), + prefill_start_offset: 0, + already_cached_tokens: 0, + eos_terminated: false, + response_tx: tx, + cancelled: Arc::new(AtomicBool::new(false)), + created_at: Instant::now(), + prefill_start: Some(Instant::now()), + first_token_time: Some(Instant::now()), + token_only: None, + token_history: Vec::new(), + sampler: Default::default(), + merged_eos: vec![-1], + thinking: crate::server::thinking_budget::ThinkingState::disabled(), + structured: None, + routed: None, + }; + (seq, rx) +} + +/// A streamed event without its timings. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Seen { + Token(String, TokenMeta), + Done { + text: String, + tokens: Vec, + completion_tokens: usize, + finish_reason: String, + }, + Error(String), +} + +fn seen(rx: &mpsc::Receiver, until_done: bool) -> Vec { + let mut out = Vec::new(); + loop { + let event = if until_done { + match rx.recv_timeout(Duration::from_secs(10)) { + Ok(event) => event, + Err(_) => break, + } + } else { + match rx.try_recv() { + Ok(event) => event, + Err(_) => break, + } + }; + let item = match event { + GenerateEvent::Token(text, meta) => Seen::Token(text, meta), + GenerateEvent::TokenWithLogprobs(text, meta, _) => Seen::Token(text, meta), + GenerateEvent::Done(result) => Seen::Done { + text: result.text, + tokens: result.generated_token_ids, + completion_tokens: result.completion_tokens, + finish_reason: result.finish_reason, + }, + GenerateEvent::Error(err) => Seen::Error(err), + _ => continue, + }; + let terminal = matches!(item, Seen::Done { .. } | Seen::Error(_)); + out.push(item); + if terminal && until_done { + break; + } + } + out +} + +/// Finish `seq` the way `finalize_completed` does: the held tail, then +/// `Done`, on this thread or through its routed output. +fn finalize(seq: &mut SequenceInfo, tokenizer: &MlxcelTokenizer) { + if let Some(routed) = seq.routed.take() { + routed.finish(seq.result_template(0, None)); + } else { + let tail = seq.decode_state.flush(tokenizer); + seq.close_text_stream(tail); + let result = seq.take_generation_result(tokenizer, 0, None); + let _ = seq.response_tx.send(GenerateEvent::Done(result)); + } +} + +/// Run the four replies interleaved one token per request per round, routed +/// through `worker` when given. Returns each request's events. +fn run(tokenizer: &Arc, worker: Option<&mut OutputWorker>) -> Vec> { + let prompt = encode(tokenizer, "Reply in several scripts:"); + let streams: Vec> = REPLIES.iter().map(|r| encode(tokenizer, r)).collect(); + let mut rows: Vec<_> = streams + .iter() + .map(|s| sequence(tokenizer, &prompt, s.len())) + .collect(); + if let Some(worker) = worker { + for (seq, _) in &mut rows { + assert!(worker.attach(seq, tokenizer), "a plain request routes"); + } + } + let longest = streams.iter().map(Vec::len).max().unwrap_or(0); + for step in 0..longest { + for ((seq, _), stream) in rows.iter_mut().zip(&streams) { + let Some(&token) = stream.get(step) else { + continue; + }; + let cause = + finish_decode_token(seq, tokenizer, token, None, false, ContextBound::default()); + if cause.is_some() { + finalize(seq, tokenizer); + } + } + } + rows.iter() + .map(|(_, rx)| seen(rx, true)) + .collect::>() +} + +#[test] +fn the_output_thread_streams_what_the_scheduler_thread_streams() { + let Some(tokenizer) = tokenizer() else { + return; + }; + let expected = run(&tokenizer, None); + let mut worker = OutputWorker::spawn(Arc::clone(&tokenizer), None).expect("spawn"); + let routed = run(&tokenizer, Some(&mut worker)); + for (row, (got, want)) in routed.iter().zip(&expected).enumerate() { + let Some(Seen::Done { text, .. }) = want.last() else { + panic!("request {row} finished on the scheduler thread: {want:?}"); + }; + assert_eq!(text, REPLIES[row], "request {row} round-trips its text"); + assert!( + want.len() < REPLIES[row].chars().count() + 2, + "multi-byte pieces were held back and merged in request {row}" + ); + assert_eq!(got, want, "request {row} differs on the output thread"); + } + assert_eq!(worker.stats().attached.load(Ordering::Relaxed), 4); + assert_eq!( + worker.stats().tokens.load(Ordering::Relaxed) as usize, + REPLIES + .iter() + .map(|r| encode(&tokenizer, r).len()) + .sum::() + ); +} + +#[test] +fn a_detokenization_failure_fails_only_its_request() { + let Some(tokenizer) = tokenizer() else { + return; + }; + let expected = run(&tokenizer, None); + // A token only the second reply contains. + let others: Vec = [0, 2, 3] + .iter() + .flat_map(|&i| encode(&tokenizer, REPLIES[i])) + .collect(); + let poison = *encode(&tokenizer, REPLIES[1]) + .iter() + .find(|t| !others.contains(t)) + .expect("a token unique to the second reply"); + let mut worker = + OutputWorker::spawn_with(Arc::clone(&tokenizer), None, Some(poison)).expect("spawn"); + let prompt = encode(&tokenizer, "Reply in several scripts:"); + let (mut seq, rx) = sequence(&tokenizer, &prompt, 64); + assert!(worker.attach(&mut seq, &tokenizer)); + let cancelled = Arc::clone(&seq.cancelled); + let routed = run(&tokenizer, Some(&mut worker)); + for row in [0, 2, 3] { + assert_eq!(routed[row], expected[row], "request {row} is unaffected"); + } + assert!( + matches!(routed[1].last(), Some(Seen::Error(_))), + "the failed request is answered with an error: {:?}", + routed[1] + ); + assert_eq!(worker.stats().failed.load(Ordering::Relaxed), 1); + // An unrelated routed request attached before the failure still streams. + finish_decode_token( + &mut seq, + &tokenizer, + encode(&tokenizer, "ok")[0], + None, + false, + ContextBound::default(), + ); + finalize(&mut seq, &tokenizer); + assert!(matches!(seen(&rx, true).last(), Some(Seen::Done { .. }))); + assert!(!cancelled.load(Ordering::Relaxed)); +} + +#[test] +fn the_failed_request_is_cancelled_for_the_scheduler() { + let Some(tokenizer) = tokenizer() else { + return; + }; + let token = encode(&tokenizer, "boom")[0]; + let mut worker = + OutputWorker::spawn_with(Arc::clone(&tokenizer), None, Some(token)).expect("spawn"); + let prompt = encode(&tokenizer, "Say boom:"); + let (mut seq, rx) = sequence(&tokenizer, &prompt, 8); + assert!(worker.attach(&mut seq, &tokenizer)); + finish_decode_token( + &mut seq, + &tokenizer, + token, + None, + false, + ContextBound::default(), + ); + let events = seen(&rx, true); + assert!(matches!(events.last(), Some(Seen::Error(_))), "{events:?}"); + assert!(seq.cancelled.load(Ordering::Relaxed)); + // Its later records are dropped, and its finish sends nothing more. + finalize(&mut seq, &tokenizer); + drop(worker); + assert!(rx.try_recv().is_err()); +} + +#[test] +fn scheduler_events_keep_their_order_with_routed_tokens() { + let Some(tokenizer) = tokenizer() else { + return; + }; + let mut worker = OutputWorker::spawn(Arc::clone(&tokenizer), None).expect("spawn"); + let prompt = encode(&tokenizer, "Count:"); + let (mut seq, rx) = sequence(&tokenizer, &prompt, 64); + assert!(worker.attach(&mut seq, &tokenizer)); + for token in encode(&tokenizer, " one two") { + finish_decode_token( + &mut seq, + &tokenizer, + token, + None, + false, + ContextBound::default(), + ); + } + // An error the scheduler sends through the sequence (a failed forward) + // after two words, then the sequence is dropped without a finish. + let _ = seq + .response_tx + .send(GenerateEvent::Error("forward failed".to_string())); + drop(seq); + let events = seen(&rx, true); + let text: String = events + .iter() + .filter_map(|e| match e { + Seen::Token(t, _) => Some(t.as_str()), + _ => None, + }) + .collect(); + assert_eq!(text, " one two"); + assert_eq!( + events.last(), + Some(&Seen::Error("forward failed".to_string())) + ); + drop(worker); + assert!( + matches!( + rx.recv_timeout(Duration::from_secs(5)), + Err(mpsc::RecvTimeoutError::Disconnected) + ), + "the client stream ends once the dropped sequence is closed" + ); +} + +#[test] +fn a_client_that_never_reads_does_not_stall_the_scheduler() { + let Some(tokenizer) = tokenizer() else { + return; + }; + let mut worker = OutputWorker::spawn(Arc::clone(&tokenizer), None).expect("spawn"); + let prompt = encode(&tokenizer, "Repeat:"); + let (mut seq, rx) = sequence(&tokenizer, &prompt, usize::MAX); + assert!(worker.attach(&mut seq, &tokenizer)); + let token = encode(&tokenizer, " la")[0]; + // Several times the queue capacity, with the client never reading. + let pushes = QUEUE_CAPACITY * 4; + let start = Instant::now(); + for _ in 0..pushes { + finish_decode_token( + &mut seq, + &tokenizer, + token, + None, + false, + ContextBound::default(), + ); + } + assert!( + start.elapsed() < Duration::from_secs(60), + "pushing {pushes} tokens took {:?}", + start.elapsed() + ); + finalize(&mut seq, &tokenizer); + let events = seen(&rx, true); + assert_eq!(events.len(), pushes + 1, "every piece and the Done arrived"); +} + +#[test] +fn a_detached_request_gets_its_client_back_after_its_queued_pieces() { + let Some(tokenizer) = tokenizer() else { + return; + }; + let mut worker = OutputWorker::spawn(Arc::clone(&tokenizer), None).expect("spawn"); + let prompt = encode(&tokenizer, "Hello:"); + let (mut seq, rx) = sequence(&tokenizer, &prompt, 64); + assert!(worker.attach(&mut seq, &tokenizer)); + for token in encode(&tokenizer, " hi there") { + finish_decode_token( + &mut seq, + &tokenizer, + token, + None, + false, + ContextBound::default(), + ); + } + let routed = seq.routed.take().expect("routed"); + let client = routed.detach().expect("the client sender comes back"); + let before: String = seen(&rx, false) + .iter() + .filter_map(|e| match e { + Seen::Token(t, _) => Some(t.clone()), + _ => None, + }) + .collect(); + assert_eq!(before, " hi there"); + let _ = client.send(GenerateEvent::Error("preempted".to_string())); + assert_eq!(seen(&rx, false), vec![Seen::Error("preempted".to_string())]); +} + +#[test] +fn requests_whose_text_decides_the_next_step_are_not_routed() { + let Some(tokenizer) = tokenizer() else { + return; + }; + let mut worker = OutputWorker::spawn(Arc::clone(&tokenizer), None).expect("spawn"); + let prompt = encode(&tokenizer, "Hi:"); + let (mut stop, _rx) = sequence(&tokenizer, &prompt, 8); + stop.stop_matcher = StopMatcher::new(["\n".to_string()]); + assert!(!worker.attach(&mut stop, &tokenizer), "stop strings"); + let (mut bounded, _rx) = sequence(&tokenizer, &prompt, 8); + bounded.bounds = GenerationBounds::new(2, None); + assert!( + !worker.attach(&mut bounded, &tokenizer), + "generation bounds" + ); + let (mut plain, _rx) = sequence(&tokenizer, &prompt, 8); + assert!(worker.attach(&mut plain, &tokenizer)); + assert!( + !worker.attach(&mut plain, &tokenizer), + "a routed request is not routed twice" + ); +} + +#[test] +fn the_output_thread_is_cuda_only_and_has_a_kill_switch() { + for backend in [ + GpuBackendKind::Metal, + GpuBackendKind::Rocm, + GpuBackendKind::None, + ] { + for env in [None, Some("1"), Some("on")] { + assert!(!output_thread_from(env, backend), "{backend:?} {env:?}"); + } + } + assert!(output_thread_from(None, GpuBackendKind::Cuda)); + for off in ["0", "false", " Off ", "no"] { + assert!( + !output_thread_from(Some(off), GpuBackendKind::Cuda), + "{off}" + ); + } +} diff --git a/src/server/batch/queue.rs b/src/server/batch/queue.rs index a890a3be1..1e2fa1277 100644 --- a/src/server/batch/queue.rs +++ b/src/server/batch/queue.rs @@ -360,6 +360,7 @@ mod tests { let decode_state = StreamingDecodeState::new(&tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id: SequenceId::from_raw(id_val), diff --git a/src/server/batch/scheduler/admission.rs b/src/server/batch/scheduler/admission.rs index af917f1c8..ec326eb6d 100644 --- a/src/server/batch/scheduler/admission.rs +++ b/src/server/batch/scheduler/admission.rs @@ -656,6 +656,7 @@ impl BatchScheduler { let sampler = RowSampler::new(&sampling); let seq = SequenceInfo { + routed: None, retention, seq_id, state: SequenceState::Queued, diff --git a/src/server/batch/scheduler/admission_join.rs b/src/server/batch/scheduler/admission_join.rs new file mode 100644 index 000000000..86d84f095 --- /dev/null +++ b/src/server/batch/scheduler/admission_join.rs @@ -0,0 +1,242 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Admissions join the pipelined decode loop without tearing it down +//! (issue #3669, item 2). +//! +//! Before this, every admission (a queued prompt's prefill, a chunk of a +//! parked prefill, a budgeted step with prefill pieces) dropped the stored +//! lookahead: the in-flight step n+1 was waited for, its speculative append +//! unwound, and the next decode tick re-ran step n+1 synchronously over the +//! new membership. Step n+1's forward was computed twice. +//! +//! Now, on a pipelined decode-graph tick (CUDA), step n+1 keeps the old +//! membership and its result is kept: +//! +//! 1. [`BatchScheduler::prepare_admission`] runs before the prefill. It reads +//! the in-flight step's tokens to the host (the prefill's forward would +//! wait for the step anyway, since both run on the generation stream) and +//! stores them with the lookahead. Its speculative append stays: the +//! lookahead still covers its rows. +//! 2. The admission runs. It does not touch the old rows' caches. +//! 3. The next decode tick sees the stored lookahead's rows plus the new +//! ones. [`BatchScheduler::pipelined_join_decode`] commits step n+1's +//! tokens to the old rows, then primes step n+2 over the whole batch, in +//! which the new rows decode their first token. From the tick after, the +//! steady pipeline runs over the joined batch. +//! +//! Teardown remains for a preemption (`preempt_sequence` tears the lookahead +//! down first), a cancellation or any other finish (`finalize_completed`), +//! a released decode pad row (the step read it), and a row that stops on +//! step n+1's token (the tick unwinds the old rows and runs synchronously, +//! as the stale path does). +//! +//! `MLXCEL_PIPELINE_ADMISSION_JOIN=0` restores the teardown. Off CUDA the +//! decode-graph mode is off, so no tick is a pipelined graph tick and every +//! admission tears down as before. + +use mlxcel_core::engine::StepTokens; + +use super::graph_pipeline::LookaheadRead; +use super::*; + +/// Environment switch for joining admissions into the pipelined decode loop: +/// `0`/`false`/`off`/`no` turns it off. Unset means on wherever pipelined +/// decode graphs are on (CUDA). +pub(crate) const ADMISSION_JOIN_ENV: &str = "MLXCEL_PIPELINE_ADMISSION_JOIN"; + +/// Whether [`ADMISSION_JOIN_ENV`] leaves the join on, read once. The +/// scheduler combines it with pipelined decode graphs, as +/// [`admission_join_from`] does. +/// +/// Used by: `BatchScheduler` construction +pub(crate) fn admission_join_requested() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| admission_join_from(std::env::var(ADMISSION_JOIN_ENV).ok().as_deref(), true)) +} + +fn env_off(env: Option<&str>) -> bool { + matches!( + env.map(|v| v.trim().to_ascii_lowercase()).as_deref(), + Some("0" | "false" | "off" | "no") + ) +} + +/// Pure resolution of the join: it needs pipelined decode graphs +/// (`BatchScheduler::pipelined_graphs`, false on every backend but CUDA) +/// and the environment not turning it off. +#[must_use] +pub(crate) fn admission_join_from(env: Option<&str>, pipelined_graphs: bool) -> bool { + pipelined_graphs && !env_off(env) +} + +impl BatchScheduler { + /// Whether admissions join the pipelined decode loop instead of tearing + /// it down. + pub(super) fn admission_joins_pipeline(&self) -> bool { + self.admission_join && self.pipelined_graphs() + } + + /// Prepare the stored lookahead for an admission or a prefill chunk. + /// + /// Without the join (or for an eager lookahead, or with a preemption + /// pending) this is the old teardown, [`Self::discard_lookahead`]. With + /// it, a decode-graph lookahead is kept: its step is read now + /// ([`Self::settle_lookahead`]), so the admission's prefill runs on a + /// quiet stream and a failure of that step is answered against its own + /// rows, and the next decode tick joins the new rows to it. + /// + /// Used by: the run loop's Prefill arm, `execute_budgeted_step` + pub(super) fn prepare_admission(&mut self) { + let Some(la) = self.decode_lookahead.as_ref() else { + return; + }; + let keep = self.admission_joins_pipeline() + && matches!(la.read, LookaheadRead::Graph(_)) + && !self.should_preempt(); + if keep { + self.settle_lookahead(); + } else { + self.discard_lookahead(); + self.batch_observability.record_admission_teardown(); + } + } + + /// Read a stored lookahead's in-flight decode-graph step to the host and + /// keep its tokens with it, so nothing of it is in flight any more. Its + /// speculative append stays. A failed read fails the step's rows as a + /// failed steady read does. No-op for an idle pipeline or a step already + /// on the host. + /// + /// Used by: [`Self::prepare_admission`], `release_decode_pad_rows` + pub(super) fn settle_lookahead(&mut self) { + if !self + .decode_lookahead + .as_ref() + .is_some_and(|la| matches!(la.read, LookaheadRead::Graph(StepTokens::Pending(_)))) + { + return; + } + let la = self.decode_lookahead.take().expect("checked above"); + match self.read_lookahead(&la) { + Ok(tokens) => { + self.decode_lookahead = Some(DecodeLookahead { + read: LookaheadRead::Graph(StepTokens::Host(tokens)), + ..la + }); + } + Err(msg) => self.fail_lookahead_readback(la, None, &msg), + } + } + + /// Whether this tick joins newly admitted rows to the stored lookahead + /// `la`: the join is on, the tick is an armed decode-graph tick and `la` + /// a decode-graph step (so both run the replayable structure), and + /// `seq_ids` is `la.ids` plus rows `la` does not cover, each live with + /// its first token committed. + pub(super) fn admission_join_applies( + &self, + la: &DecodeLookahead, + seq_ids: &[SequenceId], + ) -> bool { + if !self.admission_joins_pipeline() + || !self.decode_graphs_armed() + || !matches!(la.read, LookaheadRead::Graph(_)) + || la.ids.len() >= seq_ids.len() + || !la.ids.iter().all(|id| seq_ids.contains(id)) + { + return false; + } + seq_ids.iter().filter(|id| !la.ids.contains(id)).all(|&id| { + self.active_batch + .get(id) + .is_some_and(|seq| !seq.state.is_finished() && !seq.generated_tokens.is_empty()) + }) + } + + /// The join tick: commit step n+1 (`la`) to its rows, then prime step + /// n+2 over `seq_ids`, `la`'s rows and the newly admitted ones, whose + /// first token (from their prefill) step n+2 forwards. A row that stops + /// on step n+1's token unwinds `la`'s rows and runs the tick + /// synchronously, as a stale lookahead does: only `la`'s rows hold a + /// speculative append. + pub(super) fn pipelined_join_decode(&mut self, la: DecodeLookahead, seq_ids: &[SequenceId]) { + let toks = match self.read_lookahead(&la) { + Ok(tokens) => tokens, + Err(msg) => { + self.fail_lookahead_readback(la, None, &msg); + return; + } + }; + let mut finishing = toks.len() != la.ids.len(); + if !finishing { + for (i, &seq_id) in la.ids.iter().enumerate() { + let Some(seq) = self.active_batch.get(seq_id) else { + finishing = true; + break; + }; + if lookahead_token_finishes( + toks[i], + seq.generated_tokens.len(), + seq.max_tokens, + &seq.merged_eos, + seq.cancelled.load(Ordering::Relaxed), + ) { + finishing = true; + break; + } + } + } + if finishing { + let failed = self.apply_lookahead_trim(&la.ids, lookahead_teardown_positions(false)); + drop(la); + let live = Self::without_failed(seq_ids, &failed); + if live.is_empty() { + return; + } + self.dispatch_sync_decode(&live); + self.maybe_prime_lookahead(&live); + return; + } + let committed = la.ids.clone(); + drop(la); + self.apply_fused_decode_tokens(&committed, &toks); + self.batch_observability.record_lookahead_step(); + self.batch_observability.record_admission_join(); + #[cfg(test)] + { + self.admission_joins += 1; + } + self.maybe_prime_lookahead(seq_ids); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn admission_join_needs_pipelined_graphs_and_has_a_kill_switch() { + // Off CUDA the decode-graph mode is off, so `pipelined_graphs` is + // false and no environment turns the join on. + for env in [None, Some("1"), Some("on"), Some("0")] { + assert!(!admission_join_from(env, false), "{env:?}"); + } + assert!(admission_join_from(None, true)); + assert!(admission_join_from(Some("1"), true)); + for off in ["0", "false", " OFF ", "no"] { + assert!(!admission_join_from(Some(off), true), "{off}"); + } + } +} diff --git a/src/server/batch/scheduler/budgeted_step.rs b/src/server/batch/scheduler/budgeted_step.rs index f94649c5e..9e766460b 100644 --- a/src/server/batch/scheduler/budgeted_step.rs +++ b/src/server/batch/scheduler/budgeted_step.rs @@ -164,12 +164,17 @@ impl BatchScheduler { decode_rows: ids.len(), prefill: Vec::new(), }); - if !step.prefill.is_empty() { + // With admissions joining the pipeline (#3669, CUDA) the decode below + // keeps it, and its lookahead is prepared for the prefill pieces after + // the decode, as the Prefill arm prepares it. + let join = self.admission_joins_pipeline(); + if !step.prefill.is_empty() && !join { // Admission and chunk continuation change batch membership or the // KV caches outside the decode fast path, so a prebuilt lookahead // goes first (#632 invalidation), as in the Prefill and MixedStep // arms. A decode-only step keeps the lookahead pipeline. - self.discard_lookahead(); + // (`prepare_admission` is that teardown while the join is off.) + self.prepare_admission(); } // Decode first, against the id set captured at planning time, so a // prompt this step admits joins the batch for the next tick. @@ -177,6 +182,9 @@ impl BatchScheduler { self.execute_decode_step(ids); self.batch_observability.record_scheduler_step(); } + if !step.prefill.is_empty() && join { + self.prepare_admission(); + } let ran = self.run_budgeted_prefill(&step.prefill); if ran != step.prefill_tokens() { tracing::trace!( diff --git a/src/server/batch/scheduler/config.rs b/src/server/batch/scheduler/config.rs index c98914fda..bf9a4912a 100644 --- a/src/server/batch/scheduler/config.rs +++ b/src/server/batch/scheduler/config.rs @@ -95,7 +95,7 @@ impl BatchScheduler { engine: Engine::new(model, CachePool::new(pool_capacity)), prefill_queue: PrefillQueue::with_capacity(max_queue_depth), active_batch: ActiveBatch::new(max_batch_size), - tokenizer, + tokenizer: Arc::new(tokenizer), forced_reasoning_message: std::cell::RefCell::new(None), sleep_idle: None, idle_sleep_due: false, @@ -214,6 +214,10 @@ impl BatchScheduler { decode_graph_mode: mlxcel_core::step_graph::mode(), decode_graph_max_bucket: mlxcel_core::step_graph::max_bucket(), decode_graph_pipeline: mlxcel_core::step_graph::pipeline_requested(), + admission_join: admission_join::admission_join_requested(), + #[cfg(test)] + admission_joins: 0, + output_worker: None, decode_pad_rows: Vec::new(), #[cfg(test)] decode_padded_forwards: 0, diff --git a/src/server/batch/scheduler/decode_tick.rs b/src/server/batch/scheduler/decode_tick.rs index 2c668c021..08d5a072c 100644 --- a/src/server/batch/scheduler/decode_tick.rs +++ b/src/server/batch/scheduler/decode_tick.rs @@ -87,6 +87,13 @@ impl BatchScheduler { /// Shared by slot preemption ([`Self::try_evict_for_preemption`]) and paged /// block reclaim, which choose their victims differently (issue #1982). pub(super) fn preempt_sequence(&mut self, victim_id: SequenceId) -> bool { + // An admission keeps the pipelined lookahead (#3669), so one can be + // stored here, covering the victim: unwind it before the victim's + // caches are released. Without the join every caller has torn it + // down already. + if self.admission_joins_pipeline() { + self.discard_lookahead(); + } if let Some(mut victim) = self.active_batch.remove(victim_id) { tracing::info!( "Preempting sequence {} (priority={:?}, {} tokens generated)", @@ -94,6 +101,9 @@ impl BatchScheduler { victim.priority, victim.generated_tokens.len() ); + // A request streaming on the output thread (#3669) takes its + // client sender back: its re-prefill streams on this thread. + Self::unroute_output(&mut victim); // follow-up: when the victim is a VL request the // text model holds a per-sequence MRoPE entry under the old @@ -419,6 +429,17 @@ impl BatchScheduler { let _decode_budget = mlxcel_core::DecodeCommandBufferBudget::enter(); self.pipelined_steady_decode(la, seq_ids, ¶ms.unwrap()); } + // Rows admitted while the lookahead's step ran join it (#3669): + // the step ran with the old membership, its tokens are committed + // and the next step is primed over the whole batch. + Some(la) + if params.is_some() + && self.lookahead_safe() + && self.admission_join_applies(&la, seq_ids) => + { + let _decode_budget = mlxcel_core::DecodeCommandBufferBudget::enter(); + self.pipelined_join_decode(la, seq_ids); + } Some(la) => { // Stale id set or no longer eligible/safe: no step n+1 prime was // issued, so undo the one speculative KV position and fall back @@ -508,6 +529,12 @@ impl BatchScheduler { /// (queue non-empty), a chunked-prefill interleave, or a pending /// preemption, each of which mutates batch membership next tick. pub(super) fn lookahead_safe(&self) -> bool { + // A pipelined decode-graph tick keeps its lookahead across admissions + // and prefill chunks (#3669, `admission_join`): only a pending + // preemption, which unwinds it, makes the prime pointless. + if self.admission_joins_pipeline() && self.decode_graphs_armed() { + return !self.should_preempt(); + } lookahead_pipeline_safe( self.prefill_queue.is_empty(), self.chunked_prefill_seq.is_some(), @@ -608,7 +635,7 @@ impl BatchScheduler { } /// `seq_ids` without the ids a failed teardown just finished. - fn without_failed(seq_ids: &[SequenceId], failed: &[SequenceId]) -> Vec { + pub(super) fn without_failed(seq_ids: &[SequenceId], failed: &[SequenceId]) -> Vec { seq_ids .iter() .copied() @@ -1328,8 +1355,6 @@ impl BatchScheduler { // text the non-streaming result.text still carries (issue #633). // The tail passes through the stop matcher, which also releases // whatever the matcher itself was holding back (issue #1466). - let tail = seq.decode_state.flush(&self.tokenizer); - seq.close_text_stream(tail); let cached = seq.already_cached_tokens; // Classic decode reports no acceptance block (#1314); a // prompt-lookup row reports its verify rounds (#2255). @@ -1337,29 +1362,19 @@ impl BatchScheduler { .token_only .as_ref() .and_then(|row| row.speculative_stats()); - let result = seq.take_generation_result(&self.tokenizer, cached, speculative); - // Per-request TTFT / decode-rate telemetry (epic #623 #624). - // Recorded once here, where the finished sequence's timings are - // available, never on the per-token hot path. - self.batch_observability.record_request_completion( - result.prompt_tokens, - result.cached_tokens, - result.prompt_eval_ms, - result.generation_only_ms, - result.completion_tokens, - result.decode_window_tokens, - ); - tracing::info!( - prompt_tokens = seq.prompt_tokens.len(), - cached_tokens = cached, - generation_time_ms = result.generation_time_ms, - "prompt-cache: request completed: \ - cached={}/{} prompt tokens, total {}ms", - cached, - seq.prompt_tokens.len(), - result.generation_time_ms, - ); - let _ = seq.response_tx.send(GenerateEvent::Done(result)); + if let Some(routed) = seq.routed.take() { + // Streaming on the output thread (#3669): it holds the + // detokenizer, so it streams the held tail, builds the + // result, records the completion telemetry and sends + // `Done`, after every event queued before. A routed + // request has no stop strings, so nothing here could + // reclassify its finish. + routed.finish(seq.result_template(cached, speculative)); + } else { + let tail = seq.decode_state.flush(&self.tokenizer); + seq.close_text_stream(tail); + self.send_finished_result(&mut seq, cached, speculative); + } // donate the full KV cache back to // the prompt-cache store on *healthy* finishes (Stop / @@ -1411,6 +1426,39 @@ impl BatchScheduler { } } + /// Build `seq`'s final result on this thread, record its completion + /// telemetry and send `Done` (a request streaming on this thread). + fn send_finished_result( + &mut self, + seq: &mut SequenceInfo, + cached: usize, + speculative: Option, + ) { + let result = seq.take_generation_result(&self.tokenizer, cached, speculative); + // Per-request TTFT / decode-rate telemetry (epic #623 #624). + // Recorded once here, where the finished sequence's timings are + // available, never on the per-token hot path. + self.batch_observability.record_request_completion( + result.prompt_tokens, + result.cached_tokens, + result.prompt_eval_ms, + result.generation_only_ms, + result.completion_tokens, + result.decode_window_tokens, + ); + tracing::info!( + prompt_tokens = seq.prompt_tokens.len(), + cached_tokens = cached, + generation_time_ms = result.generation_time_ms, + "prompt-cache: request completed: \ + cached={}/{} prompt tokens, total {}ms", + cached, + seq.prompt_tokens.len(), + result.generation_time_ms, + ); + let _ = seq.response_tx.send(GenerateEvent::Done(result)); + } + /// Remove queued sequences whose client has already disconnected. /// /// This prevents cancelled requests from ever entering the active batch, diff --git a/src/server/batch/scheduler/handoff.rs b/src/server/batch/scheduler/handoff.rs index 00fa662cf..7250fe2c2 100644 --- a/src/server/batch/scheduler/handoff.rs +++ b/src/server/batch/scheduler/handoff.rs @@ -401,6 +401,7 @@ impl BatchScheduler { let decode_state = StreamingDecodeState::new(&self.tokenizer, &prompt_tokens); let sampler = RowSampler::new(&sampling); let seq = SequenceInfo { + routed: None, retention: Default::default(), seq_id, state: SequenceState::Queued, @@ -535,6 +536,7 @@ impl BatchScheduler { let sampler = RowSampler::new(&sampling); let seq = SequenceInfo { + routed: None, retention: Default::default(), seq_id, state: SequenceState::Decoding, diff --git a/src/server/batch/scheduler/mod.rs b/src/server/batch/scheduler/mod.rs index 277952896..98d91678e 100644 --- a/src/server/batch/scheduler/mod.rs +++ b/src/server/batch/scheduler/mod.rs @@ -379,7 +379,8 @@ pub struct BatchScheduler { active_batch: ActiveBatch, // -- Tokenizer -- - tokenizer: MlxcelTokenizer, + /// Shared with the output thread (#3669), which detokenizes routed rows. + tokenizer: Arc, /// Memo for the tokenized `--reasoning-budget-message` (#1470), keyed by /// the message text so a changed live setting re-encodes. One entry is /// enough: the message is a server-wide setting delivered per request. @@ -918,6 +919,25 @@ pub struct BatchScheduler { /// never off CUDA. See [`graph_pipeline`]. decode_graph_pipeline: bool, + /// Whether `MLXCEL_PIPELINE_ADMISSION_JOIN` leaves admissions joining the + /// pipelined decode loop on (#3669). Takes effect only with pipelined + /// decode graphs, so never off CUDA. See [`admission_join`]. + admission_join: bool, + + /// Admission joins this scheduler ran (#3669), for tests. + #[cfg(test)] + pub(super) admission_joins: usize, + + /// The worker's output thread (#3669), started by + /// [`Self::enable_output_thread`] on CUDA. `None` keeps every request's + /// detokenization and streaming on the scheduler thread. + /// + /// Keep this field after every field that holds a `SequenceInfo` + /// (`active_batch`, `prefill_queue`, `chunked_prefill_seq`): fields drop + /// in declaration order, and the worker's drop joins its thread, which + /// ends only once every routed row has dropped its queue handle. + output_worker: Option, + /// The open pad rows of [`Self::decode_padding`], reused from step to /// step and closed when the batch empties. decode_pad_rows: Vec, @@ -1171,6 +1191,7 @@ fn validate_dense_detached_kv_modes_against_table( } mod admission; +mod admission_join; mod admission_watermark; mod block_reclaim; mod budgeted_step; @@ -1181,6 +1202,7 @@ mod graph_pipeline; mod handoff; #[path = "../scheduler.rs"] mod mtp_dispatch; +mod output_routing; mod pad_trim; mod paged_layout; mod paged_sliding; diff --git a/src/server/batch/scheduler/output_routing.rs b/src/server/batch/scheduler/output_routing.rs new file mode 100644 index 000000000..d3c38b4e7 --- /dev/null +++ b/src/server/batch/scheduler/output_routing.rs @@ -0,0 +1,99 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The scheduler's side of the output thread (issue #3669, item 3): starting +//! it, routing a request to it when the request joins the decode batch, and +//! taking a routed request back when it is preempted. The thread itself is +//! `crate::server::batch::output_thread`. + +use super::*; +use crate::server::batch::output_thread::{OutputWorker, output_thread_requested}; + +impl BatchScheduler { + /// Start the worker's output thread where `MLXCEL_OUTPUT_THREAD` allows + /// it (CUDA only, on by default) and no speculative dispatch drives the + /// decode loop. Called by the worker before it serves, not by the + /// constructor, so schedulers built by tests keep streaming on their own + /// thread unless a test asks otherwise. + /// + /// Used by: `spawn_model_worker_with_batch_config` + pub(crate) fn enable_output_thread(&mut self) { + if self.output_worker.is_some() + || !output_thread_requested() + || self.should_dispatch_speculative() + { + return; + } + match OutputWorker::spawn( + Arc::clone(&self.tokenizer), + Some(Arc::clone(&self.batch_observability)), + ) { + Ok(worker) => { + tracing::info!( + "decode output thread: detokenization and streaming of requests without \ + stop strings run off the scheduler thread (#3669)" + ); + self.output_worker = Some(worker); + } + Err(err) => { + tracing::warn!("decode output thread unavailable, streaming stays inline: {err}"); + } + } + } + + /// Route `seq`, about to join the decode batch, to the output thread when + /// there is one and its text cannot decide its next step. + /// + /// Used by: `finish_prefill` + pub(super) fn route_output(&mut self, seq: &mut SequenceInfo) { + if self.should_dispatch_speculative() { + return; + } + if let Some(worker) = self.output_worker.as_mut() { + worker.attach(seq, &self.tokenizer); + } + } + + /// Take a routed `seq` back from the output thread before it is + /// re-queued (preemption), so its re-prefill streams on this thread with + /// its own client sender. A request the output thread already failed, or + /// that it did not hand back in time, is cancelled: its client has seen + /// an error or its stream end. + pub(super) fn unroute_output(seq: &mut SequenceInfo) { + let Some(routed) = seq.routed.take() else { + return; + }; + match routed.detach() { + Some(client) => seq.response_tx = client, + None => { + tracing::warn!( + seq_id = %seq.seq_id, + "output thread did not hand a preempted request back; cancelling it" + ); + seq.cancelled.store(true, Ordering::Relaxed); + } + } + } + + /// The output thread's counters, for tests. + #[cfg(test)] + pub(super) fn routed_requests(&self) -> Option { + self.output_worker.as_ref().map(|worker| { + worker + .stats() + .attached + .load(std::sync::atomic::Ordering::Relaxed) + }) + } +} diff --git a/src/server/batch/scheduler/prefill.rs b/src/server/batch/scheduler/prefill.rs index 0b6fcda9e..332922cef 100644 --- a/src/server/batch/scheduler/prefill.rs +++ b/src/server/batch/scheduler/prefill.rs @@ -1124,6 +1124,9 @@ impl BatchScheduler { ); return; } + // Off-thread streaming (#3669): a request whose text cannot decide + // its next step streams through the output thread from here on. + self.route_output(&mut seq); if let Err(err) = self.active_batch.add(seq) { tracing::error!("Failed to add sequence to active batch: {err}"); } diff --git a/src/server/batch/scheduler/run_loop.rs b/src/server/batch/scheduler/run_loop.rs index 3968118dd..46b8b08d2 100644 --- a/src/server/batch/scheduler/run_loop.rs +++ b/src/server/batch/scheduler/run_loop.rs @@ -284,11 +284,12 @@ impl BatchScheduler { match action { BatchSchedulerAction::Prefill(seq_id) => { // Admission / chunked-prefill interleave / preemption all - // change batch membership; tear down any prebuilt lookahead - // (trimming its speculative KV) before the prefill runs so - // the next decode rebuilds against the new batch (#632 - // invalidation). - self.discard_lookahead(); + // change batch membership. A pipelined decode-graph + // lookahead is kept for the next decode tick to join the + // new rows to (#3669, `admission_join`); any other is torn + // down (trimming its speculative KV) before the prefill + // runs (#632 invalidation). + self.prepare_admission(); // Use batched prefill when max_batch_prefill > 1 and at // least 2 requests are waiting, otherwise take the regular // single-request path so there is zero overhead for the @@ -323,14 +324,16 @@ impl BatchScheduler { // explains why that split is the useful experiment. // // Same #632 invalidation invariant as the Prefill arm. - // Like the SpeculativeRound arm's discard, this is a - // guaranteed no-op rather than load-bearing cleanup: - // `lookahead_safe()` returns false whenever a chunked - // prefill is parked, so no lookahead can exist on any tick - // that reaches here, and the decode below cannot build one. - // Kept so the invariant holds by construction if that - // precondition ever changes. - self.discard_lookahead(); + // Without the admission join this discard is a no-op kept + // for the invariant: `lookahead_safe()` is false while a + // chunked prefill is parked, so no lookahead exists here. + // With the join (#3669, CUDA) the decode keeps and primes + // one, and `prepare_admission` settles it before the chunk + // runs, as in `execute_budgeted_step`. + let join = self.admission_joins_pipeline(); + if !join { + self.discard_lookahead(); + } // Decode runs first, against the id set `decide_action` // captured. The terminal chunk calls `finish_prefill`, // which admits the prompt into the active batch; decoding @@ -338,6 +341,9 @@ impl BatchScheduler { // freshly admitted sequence start decoding on the next one. self.execute_decode_step(&ids); self.batch_observability.record_scheduler_step(); + if join { + self.prepare_admission(); + } // Count the tick only when a chunk really ran. The counter // is this prototype's dispatch proof, so it must not move // on a tick where the parked sequence was already drained diff --git a/src/server/batch/scheduler/shared_budget.rs b/src/server/batch/scheduler/shared_budget.rs index fff3c758a..35c2ad447 100644 --- a/src/server/batch/scheduler/shared_budget.rs +++ b/src/server/batch/scheduler/shared_budget.rs @@ -194,6 +194,7 @@ mod tests { let prompt_tokens = vec![1; prompt_len]; let decode_state = StreamingDecodeState::new(&tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id: SequenceId::from_raw(id), diff --git a/src/server/batch/scheduler/step_inputs.rs b/src/server/batch/scheduler/step_inputs.rs index e827c058e..7013c5615 100644 --- a/src/server/batch/scheduler/step_inputs.rs +++ b/src/server/batch/scheduler/step_inputs.rs @@ -165,6 +165,12 @@ impl BatchScheduler { /// of every block reclaim (`release_spare_blocks`), so a pad row never /// costs a cached prefix or a running request its blocks. pub(super) fn release_decode_pad_rows(&mut self) { + // A pipelined decode-graph step kept across an admission (#3669) may + // still be running over the pad rows: let it finish before their + // blocks go back to the pool. + if !self.decode_pad_rows.is_empty() { + self.settle_lookahead(); + } for id in std::mem::take(&mut self.decode_pad_rows) { self.engine.close(id); } diff --git a/src/server/batch/scheduler/step_rows.rs b/src/server/batch/scheduler/step_rows.rs index eef56ebaf..000aef650 100644 --- a/src/server/batch/scheduler/step_rows.rs +++ b/src/server/batch/scheduler/step_rows.rs @@ -171,6 +171,7 @@ pub(crate) fn step_row<'s>( stop_matcher, bounds, response_tx, + routed, prompt_tokens, vlm_embeddings, thinking, @@ -187,6 +188,7 @@ pub(crate) fn step_row<'s>( stop_matcher, bounds, response_tx, + routed: routed.as_ref(), tokenizer, logprobs: None, prompt_len: prompt_tokens.len(), diff --git a/src/server/batch/scheduler_cohort_parity_tests.rs b/src/server/batch/scheduler_cohort_parity_tests.rs index 56e08bedb..a066df09a 100644 --- a/src/server/batch/scheduler_cohort_parity_tests.rs +++ b/src/server/batch/scheduler_cohort_parity_tests.rs @@ -153,6 +153,7 @@ fn make_seq( let (tx, rx) = mpsc::channel(); let decode_state = StreamingDecodeState::new(tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id, diff --git a/src/server/batch/scheduler_decode_graph_pipeline_tests.rs b/src/server/batch/scheduler_decode_graph_pipeline_tests.rs index 23ea2f3ff..ad7e53384 100644 --- a/src/server/batch/scheduler_decode_graph_pipeline_tests.rs +++ b/src/server/batch/scheduler_decode_graph_pipeline_tests.rs @@ -38,6 +38,32 @@ struct Finished { tokens: Vec, text: String, finish_reason: String, + /// The streamed text pieces, in order. + pieces: Vec, +} + +/// The pieces a request streamed and how it finished. Waits a bounded time +/// for a request streamed by an output thread. +fn collect_finished(rx: &mpsc::Receiver) -> Finished { + let mut pieces = Vec::new(); + loop { + match rx.recv_timeout(std::time::Duration::from_secs(30)) { + Ok(GenerateEvent::Token(text, _) | GenerateEvent::TokenWithLogprobs(text, _, _)) => { + pieces.push(text); + } + Ok(GenerateEvent::Done(result)) => { + return Finished { + tokens: result.generated_token_ids, + text: result.text, + finish_reason: result.finish_reason, + pieces, + }; + } + Ok(GenerateEvent::Error(err)) => panic!("generation error: {err}"), + Ok(_) => {} + Err(err) => panic!("request did not finish: {err}"), + } + } } struct Run { @@ -49,6 +75,8 @@ struct Run { /// append (a stored lookahead covered the row). kv_checks: usize, kv_speculative: usize, + /// Requests routed to the output thread, when the arm ran one. + routed: Option, } #[derive(Default)] @@ -111,9 +139,23 @@ fn run_rows( arm: &Arm, per_row: &[ServerGenerateOptions], cancel: Option<(usize, usize)>, +) -> Run { + run_rows_with(path, arm, per_row, cancel, None) +} + +/// [`run_rows`] with the given prompts instead of the generated ones. +fn run_rows_with( + path: &std::path::Path, + arm: &Arm, + per_row: &[ServerGenerateOptions], + cancel: Option<(usize, usize)>, + given: Option<&[Vec]>, ) -> Run { let mut sched = scheduler(path, arm); - let prompts = prompts(&sched.tokenizer, per_row.len(), arm.filler_words); + let prompts = match given { + Some(given) => given.to_vec(), + None => prompts(&sched.tokenizer, per_row.len(), arm.filler_words), + }; let mut flags = Vec::new(); let rxs: Vec<_> = prompts .iter() @@ -146,7 +188,7 @@ fn run_rows( } match sched.decide_action() { BatchSchedulerAction::Prefill(id) => { - sched.discard_lookahead(); + sched.prepare_admission(); sched.execute_prefill(id); } BatchSchedulerAction::Decode(ids) => { @@ -158,25 +200,16 @@ fn run_rows( } sched.finalize_completed(); } - let finished = rxs - .iter() - .map(|rx| { - rx.try_iter() - .find_map(|event| match event { - GenerateEvent::Done(result) => Some(Finished { - tokens: result.generated_token_ids, - text: result.text, - finish_reason: result.finish_reason, - }), - GenerateEvent::Error(err) => panic!("generation error: {err}"), - _ => None, - }) - .expect("request finished") - }) - .collect(); + let stats = sched.decode_graph_stats(); + let routed = sched.routed_requests(); + // Dropping the scheduler joins its output thread, if any, after every + // record it was handed. + drop(sched); + let finished = rxs.iter().map(collect_finished).collect(); Run { finished, - stats: sched.decode_graph_stats(), + routed, + stats, kv_violations: kv.violations, kv_checks: kv.checks, kv_speculative: kv.speculative, @@ -452,3 +485,296 @@ fn an_armed_tick_that_is_not_a_graph_step_does_not_prime_a_graph_only_row_eagerl check_kv(&mut sched, 0, &mut kv); assert!(kv.violations.is_empty(), "{:?}", kv.violations); } + +/// What a staggered-arrival run left. +struct ArrivalRun { + finished: Vec, + joins: usize, + admission_teardowns: u64, + kv: KvCheck, + /// Pool slab addresses when the first late row arrived, and at the end. + slabs: (Vec, Vec), + budgeted_steps: u64, +} + +/// Run one request per entry of `per_row`, enqueuing row `i` before tick +/// `arrivals[i]`, through the run loop's arms: the Prefill arm prepares the +/// stored lookahead for the admission (`prepare_admission`), and with +/// `budget` set the budgeted planner's steps run as the run loop runs them. +fn run_arrivals( + path: &std::path::Path, + arm: &Arm, + join: bool, + budget: Option, + per_row: &[ServerGenerateOptions], + arrivals: &[usize], +) -> ArrivalRun { + let mut sched = scheduler(path, arm); + sched.admission_join = join; + sched.max_num_batched_tokens = budget; + let prompts = prompts(&sched.tokenizer, per_row.len(), arm.filler_words); + let mut rxs: Vec>> = + (0..per_row.len()).map(|_| None).collect(); + let mut kv = KvCheck::default(); + let mut slabs_before = Vec::new(); + let first_late = arrivals.iter().copied().filter(|&a| a > 0).min(); + let max_tokens = per_row.iter().map(|o| o.max_tokens).max().unwrap_or(0); + let last_arrival = arrivals.iter().copied().max().unwrap_or(0); + for tick in 0..(last_arrival + max_tokens * 8 + 64 * per_row.len()) { + for (row, &at) in arrivals.iter().enumerate() { + if at == tick { + if Some(at) == first_late { + slabs_before = slab_addresses(&sched); + } + rxs[row] = Some(enqueue(&mut sched, &prompts[row], per_row[row].clone())); + } + } + match sched.decide_action() { + BatchSchedulerAction::Prefill(id) => { + sched.prepare_admission(); + sched.execute_prefill_action(id); + } + BatchSchedulerAction::Decode(ids) => { + sched.execute_decode_step(&ids); + check_kv(&mut sched, tick, &mut kv); + } + BatchSchedulerAction::BudgetedStep(ids) => { + sched.execute_budgeted_step(&ids); + check_kv(&mut sched, tick, &mut kv); + } + BatchSchedulerAction::Idle if tick < last_arrival => {} + BatchSchedulerAction::Idle => break, + other => panic!("unexpected scheduler action {other:?}"), + } + sched.finalize_completed(); + } + let slabs_after = slab_addresses(&sched); + let snapshot = sched.batch_observability.snapshot(); + let joins = sched.admission_joins; + drop(sched); + let finished = rxs + .iter() + .map(|rx| collect_finished(rx.as_ref().expect("every row arrived"))) + .collect(); + ArrivalRun { + finished, + joins, + admission_teardowns: snapshot.decode_lookahead_admission_teardowns, + kv, + slabs: (slabs_before, slabs_after), + budgeted_steps: snapshot.budgeted_steps_processed, + } +} + +/// Rows arrive while the others decode on the pipeline: each admission +/// keeps the in-flight step, which runs with the old membership, and the +/// new row joins at the step after next. Nothing is torn down, every row's +/// KV stays at its committed tokens plus the stored lookahead's append, the +/// pool slabs stay in place, and the tokens are those of the run that tears +/// the pipeline down at each admission. Run with and without a per-step +/// token budget (`--max-num-batched-tokens`, #3670). +#[test] +#[ignore = "needs a real checkpoint and the CUDA backend"] +fn an_admission_during_the_pipeline_joins_at_the_step_after_next() { + let Some(path) = checkpoint() else { + return; + }; + let per_row: Vec<_> = [48, 48, 40, 32].into_iter().map(row_options).collect(); + let arrivals = [0, 0, 14, 27]; + for budget in [None, Some(256)] { + let arm = Arm::new(DecodeGraphMode::Replay, 4); + let joined = run_arrivals(&path, &arm, true, budget, &per_row, &arrivals); + let torn = run_arrivals(&path, &arm, false, budget, &per_row, &arrivals); + eprintln!( + "budget {budget:?}: joined {} joins, {} admission teardowns, {} budgeted steps; \ + teardown arm {} joins, {} admission teardowns", + joined.joins, + joined.admission_teardowns, + joined.budgeted_steps, + torn.joins, + torn.admission_teardowns + ); + assert!( + joined.joins >= 2, + "both late rows joined ({} joins, budget {budget:?})", + joined.joins + ); + assert_eq!( + joined.admission_teardowns, 0, + "no admission tore the pipeline down (budget {budget:?})" + ); + assert_eq!(torn.joins, 0, "the teardown arm joined nothing"); + // Without a budget the queued prompt reaches the Prefill arm with the + // lookahead stored, which tears it down. With one, the queued prompt + // makes the step's decode unsafe for the lookahead first, so the + // decode tick unwinds it before any admission sees it. + if budget.is_none() { + assert!( + torn.admission_teardowns > 0, + "the teardown arm tore down at admissions" + ); + } + if budget.is_some() { + assert!(joined.budgeted_steps > 0, "the budget engaged"); + } + for (name, run) in [("joined", &joined), ("teardown", &torn)] { + assert!( + run.kv.violations.is_empty(), + "{name}: KV length broke the invariant: {:?}", + &run.kv.violations[..run.kv.violations.len().min(8)] + ); + } + assert!( + joined.kv.speculative > 0, + "the invariant was checked with a step in flight" + ); + assert!(joined.slabs.0.iter().all(|&a| a != 0)); + assert_eq!( + joined.slabs.0, joined.slabs.1, + "a pool slab moved across the admissions" + ); + for (row, (got, want)) in joined.finished.iter().zip(&torn.finished).enumerate() { + assert_eq!( + got, want, + "row {row} differs between the join and the teardown (budget {budget:?})" + ); + } + } +} + +/// Rows that end on their own end-of-sequence token, with the next step in +/// flight, match the synchronous paths. The prompts are chat turns that +/// ask for a one-line answer, so the model ends its turn well within the +/// budget. +#[test] +#[ignore = "needs a real checkpoint and the CUDA backend"] +fn a_natural_end_of_sequence_with_the_next_step_in_flight_matches_the_synchronous_path() { + let Some(path) = checkpoint() else { + return; + }; + // One-sentence answers: long enough for the step graphs to be captured + // and replayed, short enough to end well within the budget. + let questions = [ + "In one short sentence, why is the sky blue?", + "In one short sentence, what does a bee do?", + "In one short sentence, what is a prime number?", + ]; + let per_row: Vec<_> = questions + .iter() + .map(|_| { + let mut o = row_options(96); + o.ignore_eos = false; + o + }) + .collect(); + let capacity = 4; + let mut reference: Option> = None; + for (name, arm) in arms(capacity) { + let sched = scheduler(&path, &arm); + let prompts: Vec> = questions + .iter() + .map(|q| chat_prompt(&sched.tokenizer, q)) + .collect(); + drop(sched); + let run = run_rows_with(&path, &arm, &per_row, None, Some(&prompts)); + assert!( + run.kv_violations.is_empty(), + "{name}: {:?}", + run.kv_violations + ); + for (row, done) in run.finished.iter().enumerate() { + eprintln!( + "{name} row {row}: {} tokens, finish {}: {:?}", + done.tokens.len(), + done.finish_reason, + done.text + ); + } + if name == "pipelined" { + assert!( + run.finished + .iter() + .any(|d| d.finish_reason == "stop" && d.tokens.len() < 96), + "a row ended on its end of sequence" + ); + assert!(run.stats.is_some_and(|s| s.pipelined_replays > 0)); + } + match &reference { + None => reference = Some(run.finished), + Some(expected) => assert_eq!(&run.finished, expected, "{name} differs"), + } + } +} + +/// Whether the checkpoint's tokenizer speaks the Llama 3 chat format that +/// [`chat_prompt`] renders. +fn llama3_chat(tokenizer: &MlxcelTokenizer) -> bool { + tokenizer + .encode_with_special("<|start_header_id|>", false, true) + .is_ok_and(|ids| ids.len() == 1) +} + +/// A Llama 3 chat turn for `question`. +fn chat_prompt(tokenizer: &MlxcelTokenizer, question: &str) -> Vec { + let text = format!( + "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{question}<|eot_id|>\ + <|start_header_id|>assistant<|end_header_id|>\n\n" + ); + tokenizer + .encode_with_special(&text, false, true) + .expect("tokenize") + .into_iter() + .map(|t| t as i32) + .collect() +} + +/// Four concurrent requests whose replies carry multi-byte UTF-8 stream the +/// same pieces, text and finish whether the scheduler thread or the output +/// thread detokenizes them (#3669 item 3). +#[test] +#[ignore = "needs a real checkpoint and the CUDA backend"] +fn four_concurrent_multibyte_requests_stream_the_same_on_the_output_thread() { + let Some(path) = checkpoint() else { + return; + }; + let questions = [ + "한국어로 바다에 대한 짧은 시를 써 주세요.", + "日本語で富士山について二文で説明してください。", + "Écris deux phrases en français sur le café, avec des emoji.", + "Напиши два предложения по-русски о зиме и добавь эмодзи.", + ]; + let per_row: Vec<_> = questions.iter().map(|_| row_options(40)).collect(); + let mut runs = Vec::new(); + for output_thread in [false, true] { + let mut arm = Arm::new(DecodeGraphMode::Replay, 4); + arm.output_thread = output_thread; + let sched = scheduler(&path, &arm); + if !llama3_chat(&sched.tokenizer) { + eprintln!("skipped: the prompts use the Llama 3 chat format"); + return; + } + let prompts: Vec> = questions + .iter() + .map(|q| chat_prompt(&sched.tokenizer, q)) + .collect(); + drop(sched); + runs.push(run_rows_with(&path, &arm, &per_row, None, Some(&prompts))); + } + let (scheduler_thread, output_thread) = (&runs[0], &runs[1]); + assert_eq!(output_thread.routed, Some(4), "every request was routed"); + let multibyte = scheduler_thread + .finished + .iter() + .filter(|d| d.pieces.iter().any(|p| !p.is_ascii())) + .count(); + assert!(multibyte >= 2, "replies carry multi-byte text"); + for (row, (got, want)) in output_thread + .finished + .iter() + .zip(&scheduler_thread.finished) + .enumerate() + { + assert_eq!(got.pieces.concat(), got.text, "row {row} streamed its text"); + assert_eq!(got, want, "row {row} differs on the output thread"); + } +} diff --git a/src/server/batch/scheduler_decode_graphs_tests.rs b/src/server/batch/scheduler_decode_graphs_tests.rs index adea88a4a..697c64995 100644 --- a/src/server/batch/scheduler_decode_graphs_tests.rs +++ b/src/server/batch/scheduler_decode_graphs_tests.rs @@ -151,6 +151,8 @@ struct Arm { /// Pipelined decode graphs (#3669, `MLXCEL_DECODE_GRAPH_PIPELINE`); /// `false` keeps every replay synchronous, as #3668 shipped it. pipeline: bool, + /// Stream routed requests through an output thread (#3669 item 3). + output_thread: bool, } impl Arm { @@ -166,6 +168,7 @@ impl Arm { filler_words: 24, force_sync: false, pipeline: true, + output_thread: false, } } } @@ -201,6 +204,15 @@ fn scheduler(path: &std::path::Path, arm: &Arm) -> BatchScheduler { if arm.force_sync { sched.lookahead_force_sync = true; } + if arm.output_thread { + sched.output_worker = Some( + crate::server::batch::output_thread::OutputWorker::spawn( + Arc::clone(&sched.tokenizer), + None, + ) + .expect("spawn the output thread"), + ); + } install_thread_local_default_stream(sched.generation_stream.as_ref()); sched } diff --git a/src/server/batch/scheduler_prompt_cache_tests.rs b/src/server/batch/scheduler_prompt_cache_tests.rs index d640d9455..353dbd899 100644 --- a/src/server/batch/scheduler_prompt_cache_tests.rs +++ b/src/server/batch/scheduler_prompt_cache_tests.rs @@ -557,6 +557,7 @@ fn sequence_info_fields_transport_cache_hit_metadata() { let decode_state = StreamingDecodeState::new(&tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id: SequenceId::from_raw(7), diff --git a/src/server/batch/scheduler_seed_determinism_tests.rs b/src/server/batch/scheduler_seed_determinism_tests.rs index 8f9362ecb..b1844724d 100644 --- a/src/server/batch/scheduler_seed_determinism_tests.rs +++ b/src/server/batch/scheduler_seed_determinism_tests.rs @@ -191,6 +191,7 @@ fn make_seq_with( let (tx, rx) = mpsc::channel(); let decode_state = StreamingDecodeState::new(tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id, diff --git a/src/server/batch/scheduler_tests.rs b/src/server/batch/scheduler_tests.rs index 9e26f7b0d..67e6b16d9 100644 --- a/src/server/batch/scheduler_tests.rs +++ b/src/server/batch/scheduler_tests.rs @@ -51,6 +51,7 @@ fn make_test_sequence(id_val: u64) -> (SequenceInfo, mpsc::Receiver>, + + // -- Off-thread streaming (#3669) -- + /// Set when the request is routed to the worker's output thread: its + /// detokenizer state and client sender live there, `decode_state` is an + /// empty placeholder and `response_tx` feeds this link's private channel, + /// so every event still reaches the client in the order it was sent. + /// `None` streams on the scheduler thread, as before. + pub(crate) routed: Option, } impl SequenceInfo { @@ -625,11 +633,72 @@ impl SequenceInfo { &mut self.decode_state, StreamingDecodeState::new(tokenizer, &[]), ); - let prompt_len = self.prompt_tokens.len(); - let mut result = match self.stop_matcher.matched() { - Some(word) => state.finish_stopped_by_word( - word.to_string(), - self.stop_matcher.emitted_len(), + self.result_template(cached_tokens, speculative) + .build(state) + } + + /// Everything [`Self::take_generation_result`] reads from the sequence + /// besides its detokenizer state, so the result can be built where that + /// state lives: on the output thread for a routed request (#3669). + pub(crate) fn result_template( + &self, + cached_tokens: usize, + speculative: Option, + ) -> ResultTemplate { + ResultTemplate { + created_at: self.created_at, + prompt_len: self.prompt_tokens.len(), + max_tokens: self.max_tokens, + cached_tokens, + stopped_by: self + .stop_matcher + .matched() + .map(|word| (word.to_string(), self.stop_matcher.emitted_len())), + context_exhausted: self.retention.context_exhausted, + bound: self.bounds.fired(), + generated_token_ids: self.generated_tokens.clone(), + speculative, + } + } +} + +/// The parts of a finished request's [`GenerationResult`] that do not come +/// from its detokenizer, taken from the sequence by +/// [`SequenceInfo::result_template`]. +/// +/// [`GenerationResult`]: crate::server::model_provider::GenerationResult +#[derive(Debug)] +pub(crate) struct ResultTemplate { + created_at: Instant, + prompt_len: usize, + max_tokens: usize, + cached_tokens: usize, + /// The stop string that matched and the bytes that reached the client. + stopped_by: Option<(String, usize)>, + context_exhausted: bool, + bound: Option, + generated_token_ids: Vec, + speculative: Option, +} + +impl ResultTemplate { + /// Generated tokens of the request, which the stream's tail flush + /// reports as its count. + pub(crate) fn generated_len(&self) -> usize { + self.generated_token_ids.len() + } + + /// The final result from the request's detokenizer `state`. + pub(crate) fn build( + self, + state: StreamingDecodeState, + ) -> crate::server::model_provider::GenerationResult { + let prompt_len = self.prompt_len; + let cached_tokens = self.cached_tokens; + let mut result = match self.stopped_by { + Some((word, emitted)) => state.finish_stopped_by_word( + word, + emitted, self.created_at, prompt_len, self.max_tokens, @@ -643,7 +712,7 @@ impl SequenceInfo { // OpenAI string is "length" and the native pair is `stop_type: // "limit"` with `truncated: true`, which the finish helpers cannot // derive because the token count sits below `max_tokens`. - if self.retention.context_exhausted + if self.context_exhausted && !matches!( result.stop_kind, crate::server::model_provider::StopKind::Word(_) @@ -660,7 +729,7 @@ impl SequenceInfo { if !matches!( result.stop_kind, crate::server::model_provider::StopKind::Word(_) - ) && let Some(bound) = self.bounds.fired() + ) && let Some(bound) = self.bound { if let BoundStop::Indent { keep_bytes } = bound { // Upstream's "cut the last line": the text is erased from the @@ -677,10 +746,10 @@ impl SequenceInfo { // token that completed a string stop sequence even though its text is // excluded from `content` (measured against the pinned binary, #1477). // `generated_tokens` is exactly that sequence. - result.generated_token_ids = self.generated_tokens.clone(); + result.generated_token_ids = self.generated_token_ids; // The drafter acceptance summary the caller's round loop produced // (#1314), or `None` on every classic-decode path. - result.speculative = speculative; + result.speculative = self.speculative; result } } diff --git a/src/server/batch/serving_handoff_parity_tests.rs b/src/server/batch/serving_handoff_parity_tests.rs index 8d7356a45..8cf98e137 100644 --- a/src/server/batch/serving_handoff_parity_tests.rs +++ b/src/server/batch/serving_handoff_parity_tests.rs @@ -177,6 +177,7 @@ fn make_request_with( let (tx, rx) = mpsc::channel(); let decode_state = StreamingDecodeState::new(tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id, diff --git a/src/server/batch/speculative_burst_tests.rs b/src/server/batch/speculative_burst_tests.rs index 9ca214a2e..834de88ef 100644 --- a/src/server/batch/speculative_burst_tests.rs +++ b/src/server/batch/speculative_burst_tests.rs @@ -301,6 +301,7 @@ fn make_test_sequence() -> (SequenceInfo, mpsc::Receiver) { let decode_state = StreamingDecodeState::new(&tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id: SequenceId::from_raw(42), diff --git a/src/server/batch/speculative_slice_tests.rs b/src/server/batch/speculative_slice_tests.rs index a3f917387..7002181a8 100644 --- a/src/server/batch/speculative_slice_tests.rs +++ b/src/server/batch/speculative_slice_tests.rs @@ -262,6 +262,7 @@ fn make_slice_sequence_with_id( let prompt_tokens = vec![1, 2, 3]; let decode_state = StreamingDecodeState::new(&tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id: SequenceId::from_raw(raw_id), diff --git a/src/server/batch/stop_sequence_tests.rs b/src/server/batch/stop_sequence_tests.rs index 74152f2cc..76d5dd9ff 100644 --- a/src/server/batch/stop_sequence_tests.rs +++ b/src/server/batch/stop_sequence_tests.rs @@ -71,6 +71,7 @@ fn make_sequence( let prompt_tokens: Vec = Vec::new(); let decode_state = StreamingDecodeState::new(tokenizer, &prompt_tokens); let seq = SequenceInfo { + routed: None, bounds: Default::default(), retention: Default::default(), seq_id: SequenceId::from_raw(1), diff --git a/src/server/model_worker.rs b/src/server/model_worker.rs index 33324e264..af843a74a 100644 --- a/src/server/model_worker.rs +++ b/src/server/model_worker.rs @@ -1080,7 +1080,12 @@ pub(crate) fn spawn_model_worker_with_batch_config( scheduler.serve(); } } - ServingMode::Hybrid | ServingMode::Router => scheduler.serve(), + ServingMode::Hybrid | ServingMode::Router => { + // Detokenization and streaming off the scheduler + // thread (#3669, CUDA only). + scheduler.enable_output_thread(); + scheduler.serve(); + } } // The loop ends here unless the idle window expired. A serving diff --git a/src/server/routes/metrics.rs b/src/server/routes/metrics.rs index 5f97285f0..cee59bc72 100644 --- a/src/server/routes/metrics.rs +++ b/src/server/routes/metrics.rs @@ -206,6 +206,12 @@ pub async fn metrics(State(state): State) -> Response { # HELP mlxcel_batch_decode_graph_pipelined_replays_total Replayed decode steps launched before the previous step's tokens were read (issue #3669); 0 off CUDA\n\ # TYPE mlxcel_batch_decode_graph_pipelined_replays_total counter\n\ mlxcel_batch_decode_graph_pipelined_replays_total {decode_graph_pipelined_replays}\n\ + # HELP mlxcel_batch_decode_lookahead_admission_joins_total Admissions joined to the pipelined decode loop without a teardown (issue #3669); 0 off CUDA\n\ + # TYPE mlxcel_batch_decode_lookahead_admission_joins_total counter\n\ + mlxcel_batch_decode_lookahead_admission_joins_total {decode_lookahead_admission_joins}\n\ + # HELP mlxcel_batch_decode_lookahead_admission_teardowns_total Admissions that tore a stored decode lookahead down (issue #3669)\n\ + # TYPE mlxcel_batch_decode_lookahead_admission_teardowns_total counter\n\ + mlxcel_batch_decode_lookahead_admission_teardowns_total {decode_lookahead_admission_teardowns}\n\ # HELP mlxcel_cuda_unified_buffer_requests_total Unified (host-visible) buffers the CUDA allocator handed out: host-built arrays above 8 bytes and device buffers moved for a host read (issue #3667); 0 off CUDA\n\ # TYPE mlxcel_cuda_unified_buffer_requests_total counter\n\ mlxcel_cuda_unified_buffer_requests_total {unified_buffer_requests}\n\ @@ -340,6 +346,8 @@ pub async fn metrics(State(state): State) -> Response { decode_graphs = obs.decode_graphs, decode_graph_bytes = obs.decode_graph_bytes, decode_graph_pipelined_replays = obs.decode_graph_pipelined_replays, + decode_lookahead_admission_joins = obs.decode_lookahead_admission_joins, + decode_lookahead_admission_teardowns = obs.decode_lookahead_admission_teardowns, unified_buffer_requests = mlxcel_core::memory::unified_alloc_count(), prefill_chunks = obs.prefill_chunks_processed, mixed_steps = obs.mixed_steps_processed,