prefix cache: LELEKA_PREFIX_PARK_FAST (cheaper export, same bytes) and LELEKA_PREFIX_PARK_ASYNC (end-of-decode checkpoint after the response), both opt-in

PARK_FAST (typed setting prefix_park_fast, off by default). The export of a parked block read the 12 resident layers with one context synchronize per layer, a fresh zero-filled buffer per K/V span (resize(n, 0) before the copy overwrote every byte) and, for the index rows, a zero-filled buffer plus a zero-filled staging plus a second copy. With the switch on, the executor drains the context once per park and the layers read with export_pages_fast (copy from the mapped host image into the unzeroed spare capacity of the vector, exact_fill::fill_exact, length set only after every byte was written) and export_rows_fast (the completed device-read staging is the result: DeviceBuffer::copy_to_range_owned). Same source bytes, same layout, same sizes, same poisoning rules; the reference methods are unchanged. New profile spans: prefix.export_drain, export.copy_fast, export.index_copy_fast.

Not done for PARK_FAST: pooled buffers (the parked vectors are retained by the prefix store, so a fresh allocation per park is inherent; only evicted blocks could be recycled, which would need a store free list) and copying the 12 layers on threads (the context and the layers are Rc/non-Send; a Sync view of the mapped image would be needed).

PARK_ASYNC (typed setting prefix_park_async, PrefixConfig::defer_decode_tail, off by default, only with --prefix-cache-tail reply). after_decode records the tokens and the kept prompt-end limit and returns ChunkOutcome::Deferred; the owner loop runs OriginalServeStack::prefix_after_response right after the terminal event of the request and before the prefix summary is published. Nothing runs on the device between the end of the decode and that call (the owner thread is the only user of the stack and the deferred call is the next thing it does), so park_session, park_block and park_tail see the state after_decode saw and the parked bytes and store content are the same; a begin or invalidate that comes first drops the pending checkpoint. The profile sections of the deferred part are reported on their own DBG profile park_deferred line. Not deferred: after_prefill and after_chunk. They park cells of the last page that the decode overwrites (past the checkpoint end) and the recurrent state the decode advances, so parking them later would change the bytes.

Tests: settings default off and exact words, fill_exact equals the zero-filled copy, short or failed fill leaves the vector empty, deferred checkpoint equals the immediate one (outcome, nodes, blocks, bytes, live claim, resume of the next turn), pending dropped by begin and invalidate, nothing deferred with tail off or bypass; GPU-ignored tests of export_pages_fast and export_rows_fast against the reference exports added to the journal round trips.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-09 23:05:04 +01:00
co-authored by Claude Sonnet 5.5
parent 7f2612cd42
commit a88a77b254
24 changed files with 494 additions and 48 deletions
+15 -6
View File
@@ -73,24 +73,33 @@ impl DeviceBuffer<'_> {
/// synchronization with the same poisoning/leak rule as whole-buffer reads;
/// a failed synchronization never returns its bytes.
pub fn copy_to_range(&self, offset: usize, output: &mut [u8]) -> Result<()> {
let staging = self.copy_range_staged(offset, output.len())?;
output.copy_from_slice(&staging);
Ok(())
}
/// `copy_to_range` that hands the completed staging over instead of copying it into a second buffer: the same
/// transfer, synchronization and poisoning/leak rule, the same bytes, one allocation and one copy fewer.
pub fn copy_to_range_owned(&self, offset: usize, bytes: usize) -> Result<Vec<u8>> {
self.copy_range_staged(offset, bytes)
}
fn copy_range_staged(&self, offset: usize, bytes: usize) -> Result<Vec<u8>> {
if self.context.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, output.len())?;
let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, bytes)?;
let mut staging = Vec::new();
staging.try_reserve_exact(output.len()).map_err(|_| Error::HostAllocation)?;
staging.resize(output.len(), 0);
staging.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?;
staging.resize(bytes, 0);
let guard = self.context.enter()?;
let copy = self.context.driver.api.copy_to(handle, &mut staging);
let sync = self.context.driver.api.synchronize();
if sync.is_err() {
self.context.poisoned.set(true);
std::mem::forget(staging);
return combine(combine(copy, sync), guard.finish());
return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new());
}
combine(copy, guard.finish())?;
output.copy_from_slice(&staging);
Ok(())
Ok(staging)
}
pub fn copy_to(&self, output: &mut [u8]) -> Result<()> {
let staging = self.staging(output.len())?;
+93
View File
@@ -0,0 +1,93 @@
//! A byte vector of a size known up front, filled by a copy without first being filled with zeros.
//!
//! The prefix-cache export (`OriginalQsaMappedJournal::export_pages_fast`) writes every byte of a fresh buffer. The
//! usual `resize(n, 0)` then touches the whole buffer once for nothing (a memset and the page faults of a fresh
//! allocation) before the copy touches it again.
use crate::{Error, Result};
use std::mem::MaybeUninit;
/// `out` becomes exactly `total` bytes written by `fill` into its spare capacity, with no zero fill first.
///
/// `fill` gets `total` writable bytes and returns how many leading bytes it initialised. Anything but `total`, or an
/// error, leaves `out` empty: a half-written buffer is never exposed. A reused `out` keeps its capacity.
pub(crate) fn fill_exact(
out: &mut Vec<u8>,
total: usize,
fill: impl FnOnce(&mut [MaybeUninit<u8>]) -> Result<usize>,
) -> Result<()> {
out.clear();
out.try_reserve_exact(total).map_err(|_| Error::HostAllocation)?;
let written = fill(&mut out.spare_capacity_mut()[..total])?;
if written != total {
return Err(Error::InvalidSize);
}
// SAFETY: `fill` reported that it initialised the first `total` bytes of the spare capacity, `total` bytes were
// reserved above, and `u8` has no invalid bit pattern.
unsafe { out.set_len(total) };
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// A source split in pieces like the K/V page image: the pieces of the pattern in order.
fn pattern(len: usize) -> Vec<u8> {
(0..len).map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8).collect()
}
/// Copies `pieces` consecutive runs of `source` into `dst` the way the export copies its four runs.
fn copy_runs(source: &[u8], runs: &[usize], dst: &mut [MaybeUninit<u8>]) -> Result<usize> {
let (mut at, mut rest) = (0, dst);
for &n in runs {
let (piece, tail) = rest.split_at_mut(n);
for (d, s) in piece.iter_mut().zip(&source[at..at + n]) {
d.write(*s);
}
(at, rest) = (at + n, tail);
}
Ok(at)
}
#[test]
fn the_unzeroed_fill_gives_the_bytes_of_the_zero_filled_copy() {
let source = pattern(4 * 1056 * 3);
let runs = [3 * 2048, 3 * 2048, 3 * 64, 3 * 64];
let mut zeroed = vec![0u8; source.len()];
zeroed.copy_from_slice(&source);
let mut fast = Vec::new();
fill_exact(&mut fast, source.len(), |dst| copy_runs(&source, &runs, dst)).unwrap();
assert_eq!(fast, zeroed);
assert_eq!(fast.len(), 4 * 1056 * 3);
}
#[test]
fn a_reused_buffer_is_replaced_whatever_it_held_and_keeps_its_capacity() {
let source = pattern(512);
let mut out = vec![0xAAu8; 4096];
let capacity = out.capacity();
fill_exact(&mut out, 512, |dst| copy_runs(&source, &[256, 256], dst)).unwrap();
assert_eq!(out, source);
assert_eq!(out.capacity(), capacity, "no new allocation for a smaller export");
}
#[test]
fn a_short_or_failed_fill_leaves_the_buffer_empty() {
let source = pattern(64);
let mut out = vec![1u8; 8];
let short = fill_exact(&mut out, 64, |dst| copy_runs(&source, &[32], dst));
assert!(matches!(short, Err(Error::InvalidSize)));
assert!(out.is_empty());
let failed = fill_exact(&mut out, 64, |_| Err(Error::ContextPoisoned));
assert!(matches!(failed, Err(Error::ContextPoisoned)));
assert!(out.is_empty());
}
#[test]
fn a_size_that_cannot_be_reserved_is_a_host_allocation_error() {
let mut out = Vec::new();
let refused = fill_exact(&mut out, usize::MAX, |_| Ok(0));
assert!(matches!(refused, Err(Error::HostAllocation)));
assert!(out.is_empty());
}
}
+3
View File
@@ -182,6 +182,9 @@ mod qsa_index_ffi;
mod qsa_prompt_index;
// Genuine page4 INT8 owners and literal Original prompt/decode programs.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[allow(unsafe_code)]
mod exact_fill;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
mod kv_stream_gpu;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -136,6 +136,14 @@ mod parked_tests {
assert_eq!(*out, sub_span(kv, pages, 100, 150));
// beyond the reachable end is refused
assert!(journal.export_pages(500, 13, out).is_err());
// the fast export (drained context, no zero fill) returns the same bytes and refuses the same spans
let mut fast = vec![7u8; 3];
journal.export_pages_fast(0, pages, &mut fast).unwrap();
assert_eq!(fast, kv, "the fast export is byte for byte the export");
journal.export_pages_fast(100, 50, &mut fast).unwrap();
assert_eq!(fast, sub_span(kv, pages, 100, 150));
assert!(journal.export_pages_fast(500, 13, &mut fast).is_err());
assert!(journal.export_pages_fast(0, 0, &mut fast).is_err());
}
/// Rolled back, the image is written back in two pieces, and malformed spans are refused.
@@ -165,6 +173,16 @@ mod parked_tests {
assert_eq!(out, kv);
}
/// The fast export of the index image returns the rows of the export and refuses the same spans.
fn fast_rows_match(index: &OriginalQsaResidentIndex<'_>, rows: &[u8]) {
let (row, mut fast) = (OriginalQsaResidentIndex::ROW_BYTES, vec![7u8; 3]);
index.export_rows_fast(0, rows.len() / row, &mut fast).unwrap();
assert_eq!(fast, rows, "the fast export is byte for byte the export");
index.export_rows_fast(10, 20, &mut fast).unwrap();
assert_eq!(fast, rows[10 * row..30 * row]);
assert!(index.export_rows_fast(rows.len() / row, 1, &mut fast).is_err(), "rows beyond end / 4 are refused");
}
/// The index: pooled rows below end/4 plus a 2564-byte tail, written back whole and then in part.
fn index_round_trip<'c>(
index: &mut OriginalQsaResidentIndex<'c>,
@@ -181,6 +199,7 @@ mod parked_tests {
index.validate_checkpoint(&checkpoint).unwrap();
index.export_rows(0, cells / 4, out).unwrap();
assert_eq!(*out, rows, "the pooled rows come back");
fast_rows_match(index, &rows);
assert_eq!(index.export_tail(&checkpoint).unwrap(), tail_bytes, "the tail round-trips through the image");
// partial write-back: only the second half of the rows, on top of an image that already holds the first
let second = rows[(cells / 8) * OriginalQsaResidentIndex::ROW_BYTES..].to_vec();
@@ -189,11 +189,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
pub const HOST_PAGE_BYTES: usize = QSA_PROMPT_HOST_PAGE_BYTES;
/// Copy the pages `first_page..first_page + pages` of the reachable prefix out of the host image.
pub fn export_pages(&self, first_page: usize, pages: usize, out: &mut Vec<u8>) -> Result<()> {
self.validate_context(self.owner.context)?;
// whole pages up to the one holding the last reachable cell (a request-end checkpoint ends inside a page)
if pages == 0 || first_page.checked_add(pages).is_none_or(|e| e > self.end.div_ceil(4)) {
return Err(Error::InvalidQwenShape);
}
self.check_export(first_page, pages)?;
// the GPU wrote these cells through the mapped alias; every public writer drains, this keeps the read ordered
// after it
{
@@ -217,6 +213,35 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
}
Ok(())
}
/// The journal is this context's and the pages lie in the reachable prefix: whole pages up to the one holding the
/// last reachable cell (a request-end checkpoint ends inside a page).
fn check_export(&self, first_page: usize, pages: usize) -> Result<()> {
self.validate_context(self.owner.context)?;
if pages == 0 || first_page.checked_add(pages).is_none_or(|e| e > self.end.div_ceil(4)) {
return Err(Error::InvalidQwenShape);
}
Ok(())
}
/// `export_pages` for a caller that has drained the context since the last enqueue (one
/// `Context::synchronize` for all the layers of a park, not one per layer) and for a buffer that is only ever
/// written by the copy: the bytes are the same as `export_pages`, with no synchronize and no zero fill first.
/// With an undrained context the cells the GPU wrote last may not have landed: the caller owns that ordering.
pub fn export_pages_fast(&self, first_page: usize, pages: usize, out: &mut Vec<u8>) -> Result<()> {
self.check_export(first_page, pages)?;
let m = self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?;
let offsets = super::super::offsets()?;
let _p = crate::host_profile::span("export.copy_fast");
crate::exact_fill::fill_exact(out, pages * Self::HOST_PAGE_BYTES, |dst| {
let mut rest = dst;
let mut written = 0;
for (i, &page) in super::super::PAGE.iter().enumerate() {
let (run, tail) = rest.split_at_mut(pages * page);
m.read_uninit(offsets[i] + first_page * page, run)?;
(written, rest) = (written + run.len(), tail);
}
Ok(written)
})
}
/// Put parked spans `(first_page, bytes)` back into the host image and make the journal's reachable prefix end at
/// `end` cells: the cells below `end` that no span names must already hold the prefix (the caller's live-prefix
/// bookkeeping). Any written cell may have a stale copy in the VRAM resident window, so the resolver is reset
@@ -126,6 +126,17 @@ mod enabled {
}
Ok(())
}
/// `read` into bytes that are not initialised yet (the prefix-cache export fills a fresh buffer without
/// zeroing it first); every byte of `out` is written.
pub(crate) fn read_uninit(&self, o: usize, out: &mut [std::mem::MaybeUninit<u8>]) -> Result<()> {
let p = self.range(o, out.len())?;
// SAFETY: as `read`: `range` proved `[p, p + out.len())` lies inside the live allocation and `out` is a
// caller slice that cannot overlap it; the copy writes all `out.len()` bytes of `out`.
unsafe {
std::ptr::copy_nonoverlapping(p as *const u8, out.as_mut_ptr().cast::<u8>(), out.len());
}
Ok(())
}
pub(crate) fn close(&mut self) -> Result<()> {
if let Some(p) = self.host {
// SAFETY: `p` is the base returned by cuMemHostAlloc and not yet freed (`host` is cleared only after a
@@ -174,6 +185,9 @@ impl MappedAllocation {
pub(crate) fn read(&self, _: usize, _: &mut [u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn read_uninit(&self, _: usize, _: &mut [std::mem::MaybeUninit<u8>]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn write(&mut self, _: usize, _: &[u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
@@ -193,13 +193,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
pub const TAIL_BYTES: usize = CHECKPOINT_BYTES;
/// Copy the pooled key rows `first_row..first_row + rows` (all below the current end / 4) to the host.
pub fn export_rows(&self, first_row: usize, rows: usize, out: &mut Vec<u8>) -> Result<()> {
self.validate()?;
if self.in_flight || self.unpublished {
return Err(Error::InvalidQwenShape);
}
if rows == 0 || first_row.checked_add(rows).is_none_or(|e| e > self.end / 4) {
return Err(Error::InvalidQwenShape);
}
self.check_export(first_row, rows)?;
out.clear();
{
let _p = crate::host_profile::span("export.index_alloc");
@@ -209,6 +203,28 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
let _p = crate::host_profile::span("export.index_copy");
self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(first_row * Self::ROW_BYTES, out)
}
/// The image is settled and the rows lie below the current end / 4.
fn check_export(&self, first_row: usize, rows: usize) -> Result<()> {
self.validate()?;
if self.in_flight || self.unpublished {
return Err(Error::InvalidQwenShape);
}
if rows == 0 || first_row.checked_add(rows).is_none_or(|e| e > self.end / 4) {
return Err(Error::InvalidQwenShape);
}
Ok(())
}
/// `export_rows` that takes the device read's own staging as the result instead of zero filling `out` and copying
/// the staging into it: the same bytes, one allocation, one zero fill and one copy fewer. `out` is replaced.
pub fn export_rows_fast(&self, first_row: usize, rows: usize, out: &mut Vec<u8>) -> Result<()> {
self.check_export(first_row, rows)?;
let _p = crate::host_profile::span("export.index_copy_fast");
*out = self.image[0]
.as_ref()
.ok_or(Error::ContextPoisoned)?
.copy_to_range_owned(first_row * Self::ROW_BYTES, rows * Self::ROW_BYTES)?;
Ok(())
}
/// The bytes of a checkpoint of this lineage: everything `import` needs besides the rows below its end.
pub fn export_tail(&self, s: &OriginalQsaIndexCheckpoint<'ctx>) -> Result<Vec<u8>> {
self.validate()?;
@@ -231,6 +231,8 @@ 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
@@ -43,6 +43,7 @@ fn prefix_config(prefix: &super::super::PrefixCacheOptions) -> crate::qwen_forwa
Some(bytes) => PrefixBudget::Bytes(bytes),
},
block_tokens: prefix.block_tokens,
defer_decode_tail: crate::settings::process().serve.prefix_park_async,
..PrefixConfig::auto()
};
if let Some(seconds) = prefix.retention_s {
@@ -12,7 +12,9 @@ use super::super::prompt_device_rows::{
use super::super::prompt_device_rows::{
PromptDeviceFinal, PromptDeviceNormedRows, PromptDeviceRows, PromptDeviceSource,
};
use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior};
use super::super::qsa_index::prompt_device::resident_device::{
ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior, SpanExport,
};
use super::super::session::original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession};
use super::super::session::original_prompt::{
OriginalPromptInput, OriginalPromptTxn, OriginalSessionCheckpoint, ParkedBlock, ParkedSession,
@@ -140,7 +140,18 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
if self.layers.iter().flatten().count() != 12 {
return Err(Error::IdentityMismatch);
}
session.park_block(&self.layers, first, tokens)
let mode = self.span_export()?;
session.park_block(&self.layers, first, tokens, mode)
}
/// How this park reads the layers out: with `LELEKA_PREFIX_PARK_FAST` the context is drained here once, for all
/// twelve layers, instead of once per layer inside each read (nothing is enqueued between the reads).
fn span_export(&self) -> Result<SpanExport> {
if !crate::settings::process().serve.prefix_park_fast {
return Ok(SpanExport::Checked);
}
let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_drain");
self.context.synchronize().map_err(|_| Error::CudaExecution)?;
Ok(SpanExport::Drained)
}
/// Prefix cache: make the session and the twelve layers stand at `parked`, writing `blocks`. A failure poisons
/// the executor, as for `restore_session`.
@@ -70,6 +70,10 @@ pub(crate) struct PrefixConfig {
pub(crate) policy: PolicyParams,
/// The laptop profile of `auto` (smaller floor and ceiling).
pub(crate) laptop: bool,
/// `LELEKA_PREFIX_PARK_ASYNC`: the checkpoint at the end of the decode (`TailMode::Reply`) is not taken inside the
/// request but when the stack runs `after_response`, right after the response was published and before the next
/// request (default off).
pub(crate) defer_decode_tail: bool,
}
/// What the binding needs from the stack's owners.
@@ -123,6 +127,8 @@ pub(super) enum ChunkOutcome {
Rejected(Reject),
/// The host is short of memory: nothing was built.
LowMemory,
/// The end-of-decode checkpoint is left for `after_response` (`PrefixConfig::defer_decode_tail`).
Deferred,
Admitted {
tokens: usize,
new_blocks: usize,
@@ -131,6 +137,13 @@ pub(super) enum ChunkOutcome {
},
}
/// The end-of-decode checkpoint a request left for after its response: the tokens the session holds and the prompt-end
/// checkpoint that stays (`Req::limit`, which `finish` forgets).
struct PendingTail {
consumed: Vec<i32>,
keep: Option<usize>,
}
struct Req {
/// Last prompt position a checkpoint may cover (the last prompt token starts the first verify window).
limit: usize,
@@ -146,6 +159,8 @@ pub(super) struct PrefixServe<S: ByteSize, B: ByteSize> {
store: PrefixStore<S, B>,
live: Vec<i32>,
req: Option<Req>,
/// The end-of-decode checkpoint the last request deferred; dropped by the next `begin` and by `invalidate`.
pending_tail: Option<PendingTail>,
/// Sizes measured on the last real payloads (the estimates for the next admission).
seen_state_bytes: Option<usize>,
seen_block_bytes: Option<usize>,
@@ -21,6 +21,7 @@ impl PrefixConfig {
policy
},
laptop: false,
defer_decode_tail: false,
}
}
pub(crate) fn validate(&self, capacity: usize) -> Result<(), Error> {
@@ -183,6 +183,31 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
// the prompt-end checkpoint of this request stays: a client that resends the history without the reasoning
// of the reply continues from the prompt, not from the decode end
let keep = self.req.as_ref().map(|r| r.limit);
if self.cfg.defer_decode_tail {
self.pending_tail = Some(PendingTail { consumed: consumed.to_vec(), keep });
return Ok(ChunkOutcome::Deferred);
}
self.take_decode_tail(device, consumed, keep)
}
/// 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.
pub(in super::super::super) fn after_response<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &mut D,
) -> Result<Option<ChunkOutcome>, Error> {
let Some(PendingTail { consumed, keep }) = self.pending_tail.take() else { return Ok(None) };
self.note = None;
self.take_decode_tail(device, &consumed, keep).map(Some)
}
fn take_decode_tail<D: PrefixDevice<State = S, Block = B>>(
&mut self,
device: &mut D,
consumed: &[i32],
keep: Option<usize>,
) -> Result<ChunkOutcome, Error> {
let outcome = self.admit_tail(device, consumed, keep)?;
if matches!(outcome, ChunkOutcome::Admitted { .. } | ChunkOutcome::Exists) {
// the buffer holds exactly these cells, and the node has a copy of them
@@ -31,6 +31,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
store,
live: Vec::new(),
req: None,
pending_tail: None,
seen_state_bytes: None,
seen_block_bytes: None,
park_ms_request: 0.0,
@@ -162,6 +163,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
self.store.clear();
self.live.clear();
self.req = None;
self.pending_tail = None;
}
/// Head of a request: install the deepest checkpoint that is a prefix of `prompt`, if any (`None` = read from 0;
@@ -172,9 +174,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
prompt: &[i32],
) -> Result<Option<Start>, Error> {
let g = self.block_tokens;
self.park_ms_request = 0.0;
self.consider_ms_request = 0.0;
self.admitted_request = 0;
self.start_request_counters();
if self.bypass {
self.req = None;
return Ok(None);
@@ -195,6 +195,14 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
};
self.import_hit(device, prompt, (hit, limit), match_us)
}
/// A new request: its counters start at zero, and a checkpoint the last request deferred and nobody took is
/// dropped (it names a device state that is gone).
fn start_request_counters(&mut self) {
self.pending_tail = None;
self.park_ms_request = 0.0;
self.consider_ms_request = 0.0;
self.admitted_request = 0;
}
/// Where a hit lands in the positional buffer: how much of it the buffer already holds and what is copied back.
fn import_plan(&self, hit: &Match, head: &[i32]) -> ImportPlan {
let g = self.block_tokens;
@@ -236,6 +236,8 @@ fn governor() -> leleka_memory::Governor {
leleka_memory::Governor::new(cfg, std::sync::Arc::new(leleka_memory::FakeProc::default()))
}
#[path = "tests/deferred_decode_tail.rs"]
mod deferred_decode_tail;
#[path = "tests/one_token_prompt_reads.rs"]
mod one_token_prompt_reads;
#[path = "tests/second_session.rs"]
@@ -0,0 +1,123 @@
//! `PrefixConfig::defer_decode_tail` (`LELEKA_PREFIX_PARK_ASYNC`): the checkpoint at the end of the decode is taken
//! after the response, from the same device state, and is the checkpoint the immediate path takes.
use super::*;
fn deferring() -> PrefixServe<State, Block> {
PrefixServe::new(PrefixConfig { tail: TailMode::Reply, defer_decode_tail: true, ..cfg() }, 1024, 1 << 30, "test")
}
/// An agent turn up to the end of the decode: `begin`, the prompt, the decode of `reply`; returns the session's
/// tokens and what `after_decode` answered. The request is not finished.
fn decode_turn(
s: &mut PrefixServe<State, Block>,
d: &mut Fake,
(prompt, reply): (&[i32], &[i32]),
) -> (Vec<i32>, ChunkOutcome) {
let (_, resume) = begin_request(s, d, prompt);
read_chunks(s, d, prompt, (resume, None));
s.after_prefill(d, prompt).unwrap();
let mut consumed = prompt[..prompt.len() - 1].to_vec();
let decoded: Vec<i32> =
std::iter::once(prompt[prompt.len() - 1]).chain(reply[..reply.len() - 1].iter().copied()).collect();
d.read(&decoded, consumed.len());
consumed.extend_from_slice(&decoded);
let outcome = s.after_decode(d, &consumed).unwrap();
(consumed, outcome)
}
/// What a store holds, for comparing two caches.
fn shape(s: &PrefixServe<State, Block>) -> (usize, usize, usize, usize) {
(s.node_count(), s.block_count(), s.bytes(), s.live_tokens())
}
#[test]
fn the_deferral_is_off_by_default() {
assert!(!PrefixConfig::auto().defer_decode_tail);
assert!(!cfg().defer_decode_tail);
}
#[test]
fn a_deferred_checkpoint_is_taken_after_the_response_and_equals_the_immediate_one() {
let (mut now, mut later) = (tail_serve(TailMode::Reply), deferring());
let (mut d_now, mut d_later) = (Fake::new(), Fake::new());
let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300));
let (consumed, immediate) = decode_turn(&mut now, &mut d_now, (&first, &reply));
now.finish(true);
let (consumed_later, deferred) = decode_turn(&mut later, &mut d_later, (&first, &reply));
assert_eq!(consumed, consumed_later);
assert_eq!(deferred, ChunkOutcome::Deferred);
let before = shape(&later);
assert!(before.0 < shape(&now).0, "the decode-end node is not in the store while the response is produced");
// the request is finished (its claim on the buffer ends) and then the response is out
later.finish(true);
let taken = later.after_response(&mut d_later).unwrap().expect("a checkpoint was deferred");
let (
ChunkOutcome::Admitted { tokens, new_blocks, bytes, .. },
ChunkOutcome::Admitted { tokens: t, new_blocks: n, bytes: b, .. },
) = (taken, immediate)
else {
panic!("both paths admit: {taken:?} / {immediate:?}");
};
assert_eq!((tokens, new_blocks, bytes), (t, n, b));
assert_eq!(shape(&later), shape(&now), "the same nodes, blocks, bytes and live claim");
assert_eq!(later.after_response(&mut d_later).unwrap(), None, "taken once");
}
#[test]
fn the_next_turn_resumes_from_the_deferred_checkpoint_exactly_as_from_the_immediate_one() {
let (mut now, mut later) = (tail_serve(TailMode::Reply), deferring());
let (mut d_now, mut d_later) = (Fake::new(), Fake::new());
let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300));
decode_turn(&mut now, &mut d_now, (&first, &reply));
now.finish(true);
let (consumed, _) = decode_turn(&mut later, &mut d_later, (&first, &reply));
later.finish(true);
later.after_response(&mut d_later).unwrap();
let mut second = first.clone();
second.extend(reply.iter().copied());
second.extend(doc(34, 0, 60));
let (a, b) =
(now.begin(&mut d_now, &second).unwrap().unwrap(), later.begin(&mut d_later, &second).unwrap().unwrap());
assert_eq!(a.resume, consumed.len(), "the end of the previous decode");
assert_eq!((a.resume, a.switched, a.branch, a.copied_tokens), (b.resume, b.switched, b.branch, b.copied_tokens));
assert_eq!((d_now.position, d_now.digest), (d_later.position, d_later.digest));
}
#[test]
fn a_deferred_checkpoint_nobody_took_is_dropped_by_the_next_request_and_by_invalidate() {
let mut s = deferring();
let mut d = Fake::new();
let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300));
decode_turn(&mut s, &mut d, (&first, &reply));
s.finish(true);
let nodes = s.node_count();
// the next request starts first: the device state the checkpoint named is gone
s.begin(&mut d, &session(2, 0, 3, 5)).unwrap();
assert_eq!(s.after_response(&mut d).unwrap(), None);
assert_eq!(s.node_count(), nodes, "nothing was parked");
decode_turn(&mut s, &mut d, (&first, &reply));
s.finish(true);
s.invalidate();
assert_eq!(s.after_response(&mut d).unwrap(), None);
assert_eq!(s.node_count(), 0);
}
#[test]
fn nothing_is_deferred_when_the_tail_is_off_or_the_request_bypasses_the_cache() {
let mut off = PrefixServe::<State, Block>::new(
PrefixConfig { tail: TailMode::Prompt, defer_decode_tail: true, ..cfg() },
1024,
1 << 30,
"test",
);
let mut d = Fake::new();
let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300));
let (_, outcome) = decode_turn(&mut off, &mut d, (&first, &reply));
assert_eq!(outcome, ChunkOutcome::Nothing);
assert_eq!(off.after_response(&mut d).unwrap(), None);
let mut bypass = deferring();
bypass.set_bypass(true);
let (_, outcome) = decode_turn(&mut bypass, &mut Fake::new(), (&first, &reply));
assert_eq!(outcome, ChunkOutcome::Nothing);
assert_eq!(bypass.after_response(&mut Fake::new()).unwrap(), None);
}
@@ -69,23 +69,28 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
pub(in super::super) fn prefix_after_decode(&mut self, consumed: &[i32]) {
let Some(mut prefix) = self.prefix.take() else { return };
let _span = profile::span("prefix.after_decode");
match prefix.after_decode(self, consumed) {
Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => {
operator_text(&format!(
"prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} \
park_ms={park_ms:.1}",
bytes >> 20
));
}
Ok(other) => operator_text(&format!(
"prefix tail (decode end) not taken: {other:?}: {}",
prefix.take_note().unwrap_or_default()
)),
Err(error) => {
operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped"))
}
let taken = prefix.after_decode(self, consumed);
report_decode_tail(&mut prefix, taken.map(Some), "decode end");
self.prefix = Some(prefix);
}
/// After the response of a request was published (`LELEKA_PREFIX_PARK_ASYNC`): the end-of-decode checkpoint the
/// 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;
}
let Some(mut prefix) = self.prefix.take() else { return };
{
let _span = profile::span("prefix.after_response");
let taken = prefix.after_response(self);
report_decode_tail(&mut prefix, taken, "decode end, after the response");
}
self.prefix = Some(prefix);
self.note_memory();
profile::report("park_deferred");
}
/// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint
@@ -150,6 +155,26 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
}
/// The operator line of an end-of-decode checkpoint attempt (`None`: nothing was deferred, nothing to say).
fn report_decode_tail(
prefix: &mut PrefixServe<StackState, StackBlock>,
taken: std::result::Result<Option<ChunkOutcome>, Error>,
when: &str,
) {
match taken {
Ok(Some(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms })) => operator_text(&format!(
"prefix tail admit ({when}): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}",
bytes >> 20
)),
Ok(None | Some(ChunkOutcome::Deferred)) => {}
Ok(Some(other)) => operator_text(&format!(
"prefix tail ({when}) not taken: {other:?}: {}",
prefix.take_note().unwrap_or_default()
)),
Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the {when}; skipped")),
}
}
/// The chunk's loan from the expert cache: the smallest rung of the ladder that holds `count` rows, else the full loan.
fn lend_tail<'l, 'ctx>(
cache: &'l mut OriginalExpertCache<'ctx>,
@@ -32,6 +32,15 @@ pub(in crate::qwen_forward) struct ParkedLayerSpan {
pub(in crate::qwen_forward) kv: Vec<u8>,
pub(in crate::qwen_forward) index: Vec<u8>,
}
/// How a layer's span is read out for the prefix cache; both give the same bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::qwen_forward) enum SpanExport {
/// Each read drains the context itself and fills a zeroed buffer (the reference path).
Checked,
/// The caller drained the context once for all the layers of the park: the reads skip their own drain and write
/// buffers that are not zeroed first (`LELEKA_PREFIX_PARK_FAST`).
Drained,
}
/// A parked prefix to install into a resident layer: the layer's spans up to the position `end`, and the tail of its
/// index checkpoint at that position.
#[derive(Clone, Copy)]
@@ -8,24 +8,45 @@ use super::*;
impl<'ctx> ResidentQsaLayer<'ctx> {
/// Bytes of the cells `first..first + tokens` of this layer as a prefix-cache span (host K/V pages and pooled index
/// rows). `first` and `tokens` are multiples of four and lie below the layer's end.
pub(in crate::qwen_forward) fn export_span(&self, first: usize, tokens: usize) -> Result<ParkedLayerSpan> {
pub(in crate::qwen_forward) fn export_span(
&self,
first: usize,
tokens: usize,
mode: SpanExport,
) -> Result<ParkedLayerSpan> {
// `tokens` is a multiple of four for a grid block; a request-end checkpoint ends anywhere: whole pages cover
// its cells, and only the complete 4-cell rows of the index image are copied (the checkpoint's tail carries
// the partial one)
if first % 4 != 0 || tokens == 0 || first + tokens > self.current.next_position() as usize {
return Err(Error::InvalidPosition);
}
let (mut kv, mut index) = (Vec::new(), Vec::new());
{
let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_kv");
self.kv.export_pages(first / 4, (first + tokens).div_ceil(4) - first / 4, &mut kv).map_err(device_error)?;
let kv = self.export_kv(first, tokens, mode)?;
let index = self.export_index(first, tokens, mode)?;
Ok(ParkedLayerSpan { first_token: first, tokens, kv, index })
}
/// The host K/V pages of the cells `first..first + tokens`: whole pages, up to the one holding the last cell.
fn export_kv(&self, first: usize, tokens: usize, mode: SpanExport) -> Result<Vec<u8>> {
let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_kv");
let (pages, mut kv) = ((first + tokens).div_ceil(4) - first / 4, Vec::new());
match mode {
SpanExport::Checked => self.kv.export_pages(first / 4, pages, &mut kv),
SpanExport::Drained => self.kv.export_pages_fast(first / 4, pages, &mut kv),
}
let rows = (first + tokens) / 4 - first / 4;
.map_err(device_error)?;
Ok(kv)
}
/// The pooled index rows of the complete 4-cell rows in `first..first + tokens` (none: an empty vector).
fn export_index(&self, first: usize, tokens: usize, mode: SpanExport) -> Result<Vec<u8>> {
let (rows, mut index) = ((first + tokens) / 4 - first / 4, Vec::new());
if rows > 0 {
let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_index");
self.index.export_rows(first / 4, rows, &mut index).map_err(device_error)?;
match mode {
SpanExport::Checked => self.index.export_rows(first / 4, rows, &mut index),
SpanExport::Drained => self.index.export_rows_fast(first / 4, rows, &mut index),
}
.map_err(device_error)?;
}
Ok(ParkedLayerSpan { first_token: first, tokens, kv, index })
Ok(index)
}
/// The tail of the layer's index checkpoint at its current end (what `import` needs besides the spans).
pub(in crate::qwen_forward) fn export_tail(&self) -> Result<Vec<u8>> {
@@ -4,7 +4,7 @@
use super::super::dense_weight_cache::DenseWeightCache;
use super::super::prompt_device_rows::PromptWeights;
use super::super::qsa_index::prompt_device::resident_device::{
ParkedLayerSpan, ParkedPrefix, ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior, ResidentQsaSeal,
ParkedLayerSpan, ParkedPrefix, ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior, ResidentQsaSeal, SpanExport,
};
use super::*;
use std::cell::{Cell, RefCell};
@@ -241,6 +241,7 @@ impl<'driver> QwenSession<'driver> {
layers: &[Option<ResidentQsaLayer<'driver>>; STATE_CAPACITY],
first: usize,
tokens: usize,
mode: SpanExport,
) -> Result<ParkedBlock> {
if self.state_lag.is_some() || (first + tokens) as u64 > self.next_position {
return Err(Error::InvalidPosition);
@@ -248,7 +249,7 @@ impl<'driver> QwenSession<'driver> {
let mut out: [Option<ParkedLayerSpan>; STATE_CAPACITY] = std::array::from_fn(|_| None);
for slot in 0..48 {
match (&layers[slot], self.qsa_layers[slot]) {
(Some(layer), true) => out[slot] = Some(layer.export_span(first, tokens)?),
(Some(layer), true) => out[slot] = Some(layer.export_span(first, tokens, mode)?),
(None, false) => {}
_ => return Err(Error::IdentityMismatch),
}
@@ -31,6 +31,13 @@ pub(crate) struct ServeSettings {
/// `LELEKA_DRAFT_CHAIN_PIPELINE` is `1` or `on`: the MTP chain steps of a greedy draft run back to back, one
/// stream drain for the run (identity and paired A/B of docs/experiments/decode-tail-5090.md).
pub(crate) draft_chain_pipeline: bool,
/// `LELEKA_PREFIX_PARK_FAST` is `1` or `on`: the prefix-cache export of the K/V cells and index rows drains the
/// context once per park and writes into unzeroed buffers (the same bytes; identity and paired A/B of
/// docs/experiments/step-ledger.md row B3).
pub(crate) prefix_park_fast: bool,
/// `LELEKA_PREFIX_PARK_ASYNC` is `1` or `on`: the checkpoint at the end of a decode (`--prefix-cache-tail reply`)
/// is taken after the response was published, not before (row B3).
pub(crate) prefix_park_async: bool,
}
impl ServeSettings {
@@ -47,6 +54,8 @@ impl ServeSettings {
cpu_pool_plan: equals(env, "LELEKA_CPU_POOL_PLAN", "on"),
prefill_loan_tiers: one_of(env, "LELEKA_PREFILL_LOAN_TIERS", &["1", "on"]),
draft_chain_pipeline: one_of(env, "LELEKA_DRAFT_CHAIN_PIPELINE", &["1", "on"]),
prefix_park_fast: one_of(env, "LELEKA_PREFIX_PARK_FAST", &["1", "on"]),
prefix_park_async: one_of(env, "LELEKA_PREFIX_PARK_ASYNC", &["1", "on"]),
}
}
}
@@ -96,3 +96,15 @@ fn the_draft_chain_pipeline_is_one_or_on_and_off_by_default() {
assert_eq!(serve(&[("LELEKA_DRAFT_CHAIN_PIPELINE", value)]).draft_chain_pipeline, want, "pipeline {value:?}");
}
}
#[test]
fn the_prefix_park_switches_are_one_or_on_and_off_by_default() {
let defaults = serve(&[]);
assert!(!defaults.prefix_park_fast && !defaults.prefix_park_async);
for (value, want) in [("1", true), ("on", true), ("0", false), ("off", false), ("yes", false), ("", false)] {
assert_eq!(serve(&[("LELEKA_PREFIX_PARK_FAST", value)]).prefix_park_fast, want, "fast {value:?}");
assert_eq!(serve(&[("LELEKA_PREFIX_PARK_ASYNC", value)]).prefix_park_async, want, "async {value:?}");
}
let fast_only = serve(&[("LELEKA_PREFIX_PARK_FAST", "1")]);
assert!(fast_only.prefix_park_fast && !fast_only.prefix_park_async, "the two switches are independent");
}