Files
leleka/docs/original-serve.md
T
Pavlo RatushnyiandClaude Opus 5.5 88baa91c2f merge: claude/port-gpu-bringup (kv streaming, conversation cache, sm86) into claude/expert-residency
The stack keeps every behaviour: KV format/resident config, conversation resume
with periodic/turn/root checkpoints after each published chunk, and the expert
tier. prefill_phase waits the swaps in flight, runs the conversation-aware
chunk loop (prefill_actions), and refills every lent slot on every exit path;
prefill_chunk borrows the cache's last slots for that chunk only (so the
conversation checkpoints between chunks see the whole stack) or uses the
stack's own buffers. Backend wiring keeps kv/kv_resident/conversation and the
expert tier; the driver keeps the sm86 and expert-tier-probe features; the
smoke keeps the LELEKA_SMOKE_REPEAT timing loop and adds the tier report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:04:46 +02:00

14 KiB

Original mode17 serve path

Status: source-complete at the wiring level, not GPU-run (no device was available when this was written). Nothing here certifies quality or speed; selection is an operator choice, as for the other experimental modes.

What it is

generate.cpp's serve loop as a backend: the Original batched prompt read, then OriginalSpecController (spec 4, suffix draft 3, verify windows up to 6) over the native OriginalVerifier with MTP drafting and accepted-prefix commit. The preview path (the Rust-native decoder chain) is unchanged.

piece file
backend selection and owner loop crates/leleka-runtime/src/backend_original_serve.rs
per-request flow (admit, reset, prefill, decode) qwen_forward/original_serve_request.rs, original_serve_stack.rs
verifier assembly per decode phase qwen_forward/original_serve_verifier.rs
the owners behind the serve port qwen_forward/original_serve_host.rs, original_serve_native.rs
expert tier, lineage ledger, mode17 constants original_serve_pool.rs, original_serve_ledger.rs, original_serve_config.rs
VRAM expert tier (R4 residency, PCIe share, adaptive swaps, prompt loan) qwen_forward/original_serve_residency.rs; driver original_verify_gpu_plan.rs, original_expert_cache.rs
verified-window publication into QwenSession qwen_forward/session_original_verified.rs

Selecting it

leleka-inference ... [--backend-mode auto|original|preview] [--original-prefill-capacity N] [--mtp-rt-dir PATH] [--spec-min-p F] [--kv int8] [--kv-resident CELLS]

--kv / --kv-resident select the QSA KV storage and the resident window (default INT8, 32768 cells per layer in VRAM, the rest streamed from pinned host memory); see docs/kv-streaming.md.

  • auto (default): the Original path when every compiled asset and every verifier window asset/producer it needs is present in the build (leleka_cuda_driver::unsealed_original_serve_assets(): native head, sampler, verifier and MTP-session PTX, the window kernels unsealed_window_assets(), and any producer in UNBOUND_PRODUCERS) and the configuration can feed it (inherited sealed KAR archive, MTP pack, no KAR expert source, no experimental mode, context within the trained size); otherwise the preview path, with the reason on stderr. An --experimental-* flag selects preview unless the mode is given explicitly.
  • original: never falls back. Refuses naming what is missing, e.g. the unbound window producers or an unsealed PTX; refuses a KAR expert source (the Original executors read the pinned model's own mapped routed experts, not a KAR level decode).
  • preview: never starts the Original path.

The load must be the explicit KAR PLE MTP load, as for the windowed256 modes.

VRAM expert tier (off by default)

StackConfig::expert_tier (ExpertTierConfig), selected for leleka-inference and the smoke by environment:

variable Original flag default
LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS = auto | N --expert-cache off (a profile alone means auto)
LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes --expert-cache-per-layer global
LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=P --expert-profile none
LELEKA_ORIGINAL_SERVE_PCIE_FRAC --pcie-frac 0 (see below)
LELEKA_ORIGINAL_SERVE_ADAPT_EVERY / _ADAPT_SWAPS --adapt-every / --adapt-swaps 4 / 96
LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB / _DECODE_RESERVE_MIB --vram-reserve-mib / port only 700 / 1024 (auto sizing)
LELEKA_ORIGINAL_SERVE_PREFILL_BORROW=no --no-prefill-borrow borrow (with a profile)

What runs, literally after generate.cpp / expert_source.cpp:

  • The cache is opened after every other owner (original_cache_startup::open: auto/explicit, profile-sized slots, 3/4 retry), filled from the profile in rank order through the registered model bank (per-layer skips a full layer, global stops at the first refusal) and slot 0 is read back.
  • Each verify-window layer group is split on its own routed ids (split_group): resident experts are VRAM groups, the last nmiss * pcie_num >> 8 misses (at most the staging blobs, at most 64) are staged by DMA on the copy stream (flag B raised by a host function after the copies), the rest go to the CPU pool, which computes only its entries and zeroes the GPU's. The plan is published (flag A) before the CPU starts. Every VRAM pointer is a fenced slot whose owner is checked against the doorbell's ids.
  • Adaptive tier: per (layer, expert) routed counts; every adapt_every rounds the most-routed misses (count >= 2) replace the least-routed residents of their layer while the gain is >= 1.5, best adapt_swaps, then counts decay by 0.7. Swaps copy on the tier's own stream; an evicted expert is a miss at once, the new one resident when the copies' event completed (polled at each round start; waited at a request start).
  • Prompt loan: with a profile the prompt path borrows the cache's last slots (the configured chunk must leave 128 slots); the unlent prefix serves its hits; every lent slot is refilled from the bank before the decode phase, also after a failure or cancellation.

GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity); a reply with the tier on may differ slightly from one without it, and a repeated greedy request may differ after adaptive swaps.

Deviations: the loan is sized for the configured chunk, not per request (Prefill::relayout): the prompt executor is built for exactly one capacity; without a loan the prompt path has no cache hits (the driver only serves them from a lent prefix); pcie_frac defaults to 0 because the Original's 0.55 is for its copy kernel over a pinned contiguous complement, while this port stages the three per-tensor spans by DMA (pcie_mode 0, the mode the window graph records); expert_cache_cpu_order, remote caches, layer splits and the resident RAM mode are not ported (cpu_order only concerns the S2 hit kernel, not native packs).

Proof without a model: LELEKA_EXPERT_TIER_GPU=yes cargo test -p leleka-runtime --lib -- --ignored original_serve_residency_gpu (synthetic IQ4_XS/IQ4_NL experts: placement, bit-identical CPU entries, GPU entries within 3e-2 relative L1 of the CPU path; RTX 5090 2026-10-16: worst 1.155e-2). Not yet run on a device: the PCIe DMA share and adaptive swaps (they need the registered model bank), and every real-model run.

Request plumbing

  • Admission: n + max_new + 8 <= context_tokens (generate.cpp), before any work.
  • Sampling: the request's SamplingParams map field for field to the driver SamplerParams (driver_sampler_params); a greedy request without penalties takes the plain argmax. Unseeded requests take a clock seed. Penalty history is the literal per-row window (tail of the committed tokens + the window prefix), uploaded per window.
  • Rope / context: RopeConstants::from_serving_context() (the analytic RoPE form of the process serving context) feeds both the verifier's QSA append and the draft K/V policy.
  • MTP: the digest-pinned pack of the binding, or the Original --mtp DIR bank (--mtp-rt-dir); coupled draft sampling only with STRATA_SPEC_COUPLED as in the Original.
  • Without the conversation cache every request starts at position 0: the session, the draft ring and the twelve resident QSA layers are rolled back to the empty-prompt checkpoints taken at load.

Conversation cache

--prompt-cache N (StackConfig::conversation; off by default until the real-model smoke below has passed on a GPU, the Original's default is 6), --prompt-cache-every N (16384), --prompt-cache-root N (2048), --turn-token ID (248045, negative = none), STRATA_CKPT_REREAD=1 (re-read instead of restore, the Original's check of a checkpoint). Code: qwen_forward/original_serve_conversation.rs over the golden-tested policy in conversation/manager.rs.

  • Where a request starts: the live session when the prompt extends exactly what it holds, else the deepest kept checkpoint that is a prefix of the prompt, else the empty prompt; only prompt[resume..n-1] is prefilled. Usage::reused_input_tokens and the leleka-serve request outcome=... reused= line report resume.
  • Checkpoints (generate.cpp checkpoint_at): at the last <|im_start|> of the prompt, at the first one of a prompt read from 0 when at least --prompt-cache-root in (the pinned root), and every --prompt-cache-every fresh tokens; --prompt-cache of them, root pinned, the rest LRU.
  • A checkpoint is the session's Original checkpoint (immutable GDN/PLE host priors and the twelve resident QSA witnesses: index checkpoint + mapped K/V prefix) plus the MTP ring's immutable snapshot, taken together at a published chunk boundary (~118 MB of host RAM per checkpoint, as in the Original; the K/V stays positional). A restore re-stamps it onto the session's current branch generation (OriginalSessionCheckpoint::rebased_onto_current), rolls the session and the resident layers back (index/K-V epoch and coverage are re-checked by the driver), re-anchors the ring at its snapshot (OriginalDraftSession::resume_at) and runs the drafter's kv_restore(resume).
  • Live continuation is used only when the draft ring stands at the session's position after the decode phase (then settle_state reads the GDN/PLE state back). generate.cpp skips the draft of the last window on EOS/length and continues with that gap in the ring; this port's draft lineage does not admit the gap, so such a request resumes from its last turn checkpoint instead (it re-reads the reply).
  • Not bound: parking whole conversations in host RAM (--conversation-cache-mib, opt-in in the Original too).
  • Any failure of the cache drops it and the request reads its whole prompt; a failed or broken request drops it.

Verified-window publication

The verifier owns the canonical GDN image, the PLE history and the twelve QSA index/K-V journals for a decode phase. After each commit event the host publishes the accepted rows (position, predecessors and the twelve resident QSA witnesses, read from the verifier's own journal) to the session. The recurrent GDN/PLE state lags and is read back once at the end of the phase when a consumer needs it (StackConfig::settle_state); while it lags the session refuses prompt transactions and checkpoints. Commit and draft are serialized: the commit event completes and the session is published before the draft launches.

Running the GPU smoke

LELEKA_ORIGINAL_SERVE_SMOKE=yes \
LELEKA_STRA169_KAR_FD=… LELEKA_STRA169_KAR_PROVENANCE=… \
LELEKA_STRA169_IQ3S_SHARD0=… LELEKA_STRA169_IQ3S_SHARD1=… \
LELEKA_STRA169_MTP_PACK=… LELEKA_STRA169_MTP_STAGING=… \
[LELEKA_ORIGINAL_SERVE_RT_DIR=…] [LELEKA_ORIGINAL_SERVE_CAPACITY=1024] [LELEKA_ORIGINAL_SERVE_BUDGET_GIB=28] \
cargo test -p leleka-runtime --features cuda-driver -- --ignored original_serve_smoke

The long-context variant (original_serve_long_context_streamed_kv_smoke, LELEKA_ORIGINAL_SERVE_LONG_SMOKE=yes, LELEKA_ORIGINAL_SERVE_LONG_TOKENS, LELEKA_ORIGINAL_SERVE_KV_RESIDENT, LELEKA_ORIGINAL_SERVE_MAX_CONTEXT) is described in docs/kv-streaming.md.

It opens the stack, serves a greedy request twice (the second must reproduce the first across a reset), a sampled request with penalties, a request cancelled after its first committed round, and a final request that must reproduce the first. While UNBOUND_PRODUCERS is non-empty the stack refuses to open with the first missing producer's name; that is the expected result until they are bound.

Open items

  • The compiled assets the probe lists as unsealed: the native head, sampler, MTP session PTX and the two window kernels (original_verify_window_moe_experts.ptx, original_verify_window_qsa_gate.ptx) were sealed with nvcc 13.2.86 on 2026-10-15 (GPU load is verified separately by the host smokes; no numerical claim). A window asset whose bytes stop matching its pin fails the whole window before capture. Remaining placeholders (mmq_original_group_*, mtp_original_scalar_{gr,norm}, native_parity) are still reported as unsealed. All 21 former window producers are bound by the planner; the runtime attaches projections, hyper-connection/PLE, QSA and router/shared-expert operands (dense_original_verify.rs, cache_original_verify.rs) to every window graph.
  • A new OriginalVerifier is assembled and its graphs captured for every request (the QSA owners move one way into its journal); keeping one alive across requests needs a re-seed path.
  • Routed experts run on the all-CPU pool unless the VRAM expert tier is selected (above); it is not yet measured on the real model. The prefill chunk is an operator choice (default 2048) instead of the Original's slot-derived ladder.
  • Short prompts also take the batched prefill (the Original reads <= 64 tokens through verify windows).
  • Commit/draft overlap of the Original is traded for exactness (see above).
  • draft_first (CLI only), scaled RoPE tables (STRATA_ROPE_TABLE), multi-stage and vision requests are not supported.
  • Conversation cache: bound (see above) but off by default and not yet run on a GPU; parking and live continuation after an undrafted last window are not bound. The one-token prompt (no prompt append, so no streamed-KV resolver) is fixed by OriginalQsaMappedJournal::ensure_resolver at assemble (GPU test passes).
  • Host-side rolling costs not measured: 12 small device checkpoints per committed round, one GDN readback per request when settle_state is on.

Running the conversation smoke

Same inputs as the serve smoke; --exact backend::original_serve_smoke::original_serve_conversation_smoke_resume_matches_a_full_read. It serves a one-token prompt first, then chat A, then chat B = A + reply + a new user turn (must resume, reused > 0), then B again read from 0 (forget_conversation), asserting equal greedy tokens and printing TTFT on the CONV lines, then a new chat sharing the system prompt (root checkpoint). Optional LELEKA_CONVERSATION_SYSTEM_REPEAT (120), LELEKA_CONVERSATION_MAX_NEW (48), STRATA_CKPT_REREAD=1.