diff --git a/crates/engine-qwen35-cuda/src/backend/proxy.rs b/crates/engine-qwen35-cuda/src/backend/proxy.rs index 19b9c4e6..1b4ec276 100644 --- a/crates/engine-qwen35-cuda/src/backend/proxy.rs +++ b/crates/engine-qwen35-cuda/src/backend/proxy.rs @@ -242,6 +242,20 @@ impl Drop for ActiveGuard<'_> { clear_active(self.0); } } +/// Work the owner thread still has for a request after its response was published +/// (`LELEKA_PREFIX_PARK_ASYNC`: the end-of-decode prefix checkpoint). +pub(super) trait DeferredTail { + fn run_deferred_tail(&mut self); +} +impl ActiveGuard<'_> { + /// The request is over for its client: the busy mark goes first, then the deferred tail runs. A request that + /// arrives meanwhile passes the admission (`Proxy::idle`) and waits in the control queue, which the owner reads + /// after the tail; it is never refused with `native generation is active`. + pub(super) fn release_then(self, tail: &mut impl DeferredTail) { + drop(self); + tail.run_deferred_tail(); + } +} pub(super) fn cancel_active(shared: &Shared) { if let Ok(active) = shared.active.lock() && let Some(active) = active.as_ref() diff --git a/crates/engine-qwen35-cuda/src/backend/tests.rs b/crates/engine-qwen35-cuda/src/backend/tests.rs index b7cab903..33cd5052 100644 --- a/crates/engine-qwen35-cuda/src/backend/tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/tests.rs @@ -332,3 +332,38 @@ fn preview_and_the_auto_fallback_are_refused_without_the_preview_path_feature() assert!(error.message.contains("preview-path"), "{}", error.message); } } + +/// A deferred tail that plays the next client: while the owner is still busy with it, the proxy admits a request +/// and puts its command in the control queue. +struct ClientDuringTail<'a> { + proxy: &'a Proxy, + admitted: Option>, + queued: Option>, +} +impl DeferredTail for ClientDuringTail<'_> { + fn run_deferred_tail(&mut self) { + self.admitted = Some(self.proxy.idle()); + let (reply, _) = mpsc::sync_channel(1); + self.queued = Some(self.proxy.send(Command::Reconfigure("{}".into(), reply))); + } +} +#[test] +fn a_request_arriving_during_the_deferred_tail_is_admitted_and_queued_not_refused() { + let (tx, rx) = mpsc::sync_channel(QUEUE); + let cancel = Arc::new(AtomicBool::new(false)); + let shared = Arc::new(Shared { + ready: AtomicBool::new(true), + shutdown: AtomicBool::new(false), + active: Mutex::new(Some(Active { id: "finished".into(), cancel })), + }); + let proxy = native_proxy(tx, Arc::clone(&shared)); + // while the request runs, the next one is refused + assert!(proxy.idle().is_err()); + let mut tail = ClientDuringTail { proxy: &proxy, admitted: None, queued: None }; + ActiveGuard(&shared).release_then(&mut tail); + assert!(tail.admitted.expect("the tail ran").is_ok(), "the busy mark is gone before the tail starts"); + assert!(tail.queued.expect("the tail ran").is_ok()); + // the owner reads its queue after the tail: the command is there, in order + assert!(matches!(rx.try_recv(), Ok(Command::Reconfigure(..)))); + assert!(shared.active.lock().unwrap().is_none()); +} diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs index 850edb72..ea03af0a 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs @@ -1,7 +1,7 @@ //! Moved out of the parent file by STRA-338 (same module path as before). use super::super::{ - ActiveGuard, BackendError, Command, ErrorCode, FinishReason, GENERATION_TIMEOUT, GenerationEvent, + ActiveGuard, BackendError, Command, DeferredTail, ErrorCode, FinishReason, GENERATION_TIMEOUT, GenerationEvent, GenerationFailure, GenerationSink, GenerationTerminal, LoadPhase, LoadedModel, ModelBinding, QUEUE, Reply, Shared, Tokenizer, Usage, Utf8Pending, clock_seed, emit_event, emit_terminal, exhausted, invalid, load_failure, prepare_prompt, request_sampler, unavailable, diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs index 92fe597e..6312395b 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs @@ -182,7 +182,7 @@ pub(super) fn serve_generate( command: (LoadedModel, GenerationRequest, Arc, Reply), ) -> Result<(), BackendError> { let (candidate, request, cancel, reply) = command; - let _guard = ActiveGuard(env.shared); + let guard = ActiveGuard(env.shared); let prompt = match admit_generate(env, &candidate, &request) { Ok(prompt) => prompt, Err(error) => { @@ -200,9 +200,24 @@ pub(super) fn serve_generate( return Ok(()); }; run_generation(env, owner, (&sink, &cancel), &prompt, &request); + guard.release_then(&mut AfterResponse { owner, shared: env.shared }); Ok(()) } +/// The owner after a request's terminal event: the end-of-decode prefix checkpoint it deferred +/// (`LELEKA_PREFIX_PARK_ASYNC`), then the prefix summary with the new node in it. +struct AfterResponse<'a, 'b, 'c> { + owner: &'a mut Stack<'b, 'c>, + shared: &'a Shared, +} +impl DeferredTail for AfterResponse<'_, '_, '_> { + fn run_deferred_tail(&mut self) { + if self.owner.prefix_after_response() { + publish_prefix_summary(self.owner, self.shared); + } + } +} + fn stack_unavailable() -> GenerationTerminal { GenerationTerminal::Failed { code: ErrorCode::BackendUnavailable, @@ -231,8 +246,6 @@ fn run_generation( } }; let _ = emit_terminal(sink, terminal, clock); - // the response is out: an end-of-decode checkpoint the request deferred (LELEKA_PREFIX_PARK_ASYNC) is taken now - owner.prefix_after_response(); publish_prefix_summary(owner, shared); if let Some(lost) = owner.health() { // a lost physical owner cannot be repaired in place: stop serving, keep the process diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs index 6f8bdab4..dd78e3ce 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs @@ -190,6 +190,11 @@ impl PrefixServe { self.take_decode_tail(device, consumed, keep) } + /// A request left its end-of-decode checkpoint for `after_response`. + pub(in super::super::super) fn has_deferred_tail(&self) -> bool { + self.pending_tail.is_some() + } + /// After the response of the request that deferred its end-of-decode checkpoint: take it now. The session stands /// where the decode left it (nothing ran on the device since), so this is the checkpoint `after_decode` would /// have taken. `None`: nothing was deferred. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs index 188caa45..c401b028 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs @@ -78,11 +78,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// request deferred, taken before the next request can start. Nothing ran on the device since the decode ended, /// so the parked bytes are those `prefix_after_decode` would have taken. Its profile sections are reported on /// their own line, `park_deferred`. - pub(crate) fn prefix_after_response(&mut self) { - if self.state.broken.is_some() { - return; + /// + /// Returns whether a checkpoint was deferred and attempted (the prefix summary has changed). + pub(crate) fn prefix_after_response(&mut self) -> bool { + if self.state.broken.is_some() || !self.prefix.as_ref().is_some_and(PrefixServe::has_deferred_tail) { + return false; } - let Some(mut prefix) = self.prefix.take() else { return }; + let Some(mut prefix) = self.prefix.take() else { return false }; { let _span = profile::span("prefix.after_response"); let taken = prefix.after_response(self); @@ -91,6 +93,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { self.prefix = Some(prefix); self.note_memory(); profile::report("park_deferred"); + true } /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint diff --git a/docs/experiments/step-ledger.md b/docs/experiments/step-ledger.md index 31dd4706..9d686c12 100644 --- a/docs/experiments/step-ledger.md +++ b/docs/experiments/step-ledger.md @@ -40,7 +40,7 @@ No per-step figure exists for A1-A3; each is a `not measured` row that needs a s | B2 | first token sampling and publication after prefill | not measured | not measured | n/a | none | hex-finish | open | | Q6 | `prefill.refill` of the lent expert slots (2,226 copy spans) | 137-140 ms per request | none | +138 ms; deferring it into the decode assembly (`LELEKA_REFILL_DEFER`): decode -0.92 % (CI -1.63..-0.21), end-to-end +0.56 % (CI -0.15..+1.27) | PROFILE, A/B `ab-l5v2` | hex-finish | fixing | | Q7 | `decode.assemble` (graph re-recording per request: `record_all` 83 ms of 98-109 ms, nine graphs, 54-62 capture + 27-30 instantiate) | 98-109 ms per request | none (vanilla keeps its graphs) | +98-109 ms | PROFILE | both | fixing (code 7570247d9, wired behind `LELEKA_DECODE_GRAPH_REUSE`, identity and section delta pending on the GPU): the speed session's handles, `park`/`rearm`/`reseed` and this side's key, `GraphReuse::begin`/`end`, QSA owner loan, drafter decision, shared-expert pin and stack wiring are merged and tested host-side and on the lifecycle fake; compare `decode.assemble` with `decode.reuse`, `decode.disassemble` with `decode.keep`, `record.*`, the first-draft capture, VRAM at the low-water mark; design and scenarios `docs/experiments/decode-graph-reuse.md` | -| B3 | prefill: prefix-cache parking in the request path (code `prefix.export_kv` 19.0 + `export_index` 2.3 + `park_tail` 14.7 + `park_block` 6.5 + `after_prefill` 9.4 + `after_chunk` 0.7 + `after_decode` 12.5, mean per request) | 65.1 ms | vanilla parks the conversation (checkpoints) inside its own prompt time, not separable | n/a until the instrumented vanilla | PROFILE `runs/dc1` | hex-finish | fixing (code a88a77b25, switches `LELEKA_PREFIX_PARK_FAST=1` and `LELEKA_PREFIX_PARK_ASYNC=1`, both off by default, identity and section delta pending). Reading of the code: the seven listed spans are nested, not additive (`export_kv` and `export_index` sit inside `park_block` and `park_tail`, which sit inside `after_prefill`, `after_chunk` and `after_decode`), so the request-path total is `after_prefill` + `after_chunk` + `after_decode` = 22.6 ms, not 65.1 ms. FAST: one context drain per park instead of 12, K/V pages copied into unzeroed vectors, index rows take the device-read staging as the result (same bytes; compare `prefix.export_kv` and `prefix.export_index`, new `prefix.export_drain`; the sub-spans `export.copy_fast` and `export.index_copy_fast` replace `export.sync`, `export.alloc`, `export.copy`, `export.index_alloc`, `export.index_copy`). ASYNC (with `--prefix-cache-tail reply`): the `after_decode` part (12.5 ms) is taken after the terminal event of the request, before the prefix summary and before the next request, and reported on the line `DBG profile park_deferred` (sum the `request` and `park_deferred` lines for an equal-work comparison); the tail node is in the store before the next request exactly as before. Not deferred: `after_prefill` and `after_chunk` (the last page also holds cells the decode overwrites and the recurrent state the decode advances, so a later park gives other bytes). Not done: pooled buffers (the store retains the vectors) and threaded copies of the 12 layers | +| B3 | prefill: prefix-cache parking in the request path (code `prefix.export_kv` 19.0 + `export_index` 2.3 + `park_tail` 14.7 + `park_block` 6.5 + `after_prefill` 9.4 + `after_chunk` 0.7 + `after_decode` 12.5, mean per request) | 65.1 ms | vanilla parks the conversation (checkpoints) inside its own prompt time, not separable | n/a until the instrumented vanilla | PROFILE `runs/dc1` | hex-finish | fixing (code a88a77b25, switches `LELEKA_PREFIX_PARK_FAST=1` and `LELEKA_PREFIX_PARK_ASYNC=1`, both off by default, identity and section delta pending). Reading of the code: the seven listed spans are nested, not additive (`export_kv` and `export_index` sit inside `park_block` and `park_tail`, which sit inside `after_prefill`, `after_chunk` and `after_decode`), so the request-path total is `after_prefill` + `after_chunk` + `after_decode` = 22.6 ms, not 65.1 ms. FAST: one context drain per park instead of 12, K/V pages copied into unzeroed vectors, index rows take the device-read staging as the result (same bytes; compare `prefix.export_kv` and `prefix.export_index`, new `prefix.export_drain`; the sub-spans `export.copy_fast` and `export.index_copy_fast` replace `export.sync`, `export.alloc`, `export.copy`, `export.index_alloc`, `export.index_copy`). ASYNC (with `--prefix-cache-tail reply`): the `after_decode` part (12.5 ms) is taken after the terminal event of the request, before the prefix summary and before the next request, and reported on the line `DBG profile park_deferred` (sum the `request` and `park_deferred` lines for an equal-work comparison); the tail node is in the store before the next request exactly as before. Not deferred: `after_prefill` and `after_chunk` (the last page also holds cells the decode overwrites and the recurrent state the decode advances, so a later park gives other bytes). Not done: pooled buffers (the store retains the vectors) and threaded copies of the 12 layers. GPU run 2026-11-09 (`prefill-prefix-park-identity-and-profile`): FAST kept the prefix reuse and cut the three `after_*` sections by 2.0 ms (23.5 to 21.5; the first-touch page faults of fresh host memory dominate and stay); ASYNC was refused by the runner (the busy mark `active` was still set while the owner ran the deferred step, so the next request got `runtime_capacity`). Fixed in the next commit: the busy mark is released before the deferred step, so a request that arrives meanwhile is admitted and waits in the control queue (test `a_request_arriving_during_the_deferred_tail_is_admitted_and_queued_not_refused`); pass criterion for the rerun: `cached_tokens` equal to shipped for all 30 and no `engine refused` in requests.log. Pre-faulted buffer pool not built: the store keeps every parked vector, so a pool is the store budget held pre-touched (tens of GiB, or sizes that do not match the variable tail) and needs a store free list or a slab type; allocator tuning (`MALLOC_TOP_PAD_`, `MALLOC_TRIM_THRESHOLD_`) can be tried without code | | B4 | decode hand-over: tear-down of the request (code `decode.disassemble`) | 11.7 ms per request | none | +11.7 ms | PROFILE `runs/dc1` | hex-finish | open | | B5 | host: admission of CPU work (code `cpu.admit`, 819 calls per request) | 43.2 ms per request | not measured | n/a | PROFILE `runs/dc1` | hex-finish | open |