Skip to content

Latest commit

 

History

History
639 lines (523 loc) · 32.3 KB

serving.md

File metadata and controls

639 lines (523 loc) · 32.3 KB

OpenAI-compatible serving guide

Authoritative reference for the async OpenAI-compatible server.

MoE.generate() remains the current in-process synchronous path, but it emits DeprecationWarning and is scheduled for removal. MoE.serve() is recommended for continuous batching; it starts an async HTTP service and is not a drop-in replacement for an in-process return value.

Quick Start

Security: The parser defaults to --host 0.0.0.0, and authentication is disabled when neither --api-key nor MOE_API_KEYS is configured. On an untrusted, shared, or cloud host, bind to 127.0.0.1 or configure an API key before exposure. Completion routes and privileged /admin/stats, /v1/config, and /v1/reload endpoints share this authentication posture.

python -m moe_infinity.entrypoints.openai.api_server_v2 \
    --host 127.0.0.1 \
    --model deepseek-ai/DeepSeek-V2-Lite-Chat \
    --offload-dir ./offload_dir \
    --device-memory-ratio 0.5 \
    --kv-cache-ratio 0.25 \
    --max-batch-size 8
curl http://localhost:8000/v1/completions \
  -H 'Content-Type: application/json' \
  -d '{"model":"deepseek-ai/DeepSeek-V2-Lite-Chat","prompt":"Hello","max_tokens":32}'

For DFlash speculative decoding, use a validated pair such as openai/gpt-oss-20b with z-lab/gpt-oss-20b-DFlash, or leave --speculative-draft unset for non-DFlash targets.

For one-host multi-GPU ownership and CUDA_VISIBLE_DEVICES ordering, see Single-server multi-GPU.

CLI Reference

Stable options from api_server_v2.py:

Option Default Meaning
--host 0.0.0.0 Bind address
--port 8000 Listen port
--model required Model checkpoint or local path
--offload-dir required Expert offload directory
--speculative-draft none DFlash drafter checkpoint
--device-memory-ratio 0.75 GPU memory reserved for expert cache
--kv-cache-ratio 0.25 Remaining memory reserved for KV cache
--max-batch-size 32 Max concurrent sequences per batch
--api-key none Comma-separated Bearer keys
--rate-limit 0 Requests/minute/key; 0 disables
--max-waiting-requests 0 Queue depth backpressure threshold; 0 disables
--max-n 16 Cap for parallel sampling n / best_of
--enable-prefix-caching off Enable correctness-preserving prefix KV reuse (Qwen3 + FlashInfer)
--prefix-cache-max-entries 1000 Max prefix-index entries (startup-only, >= 1)
--kv-cache-format native KV storage format: native or int8_sym (opt-in)
--no-kv-cache-format-fallback off Refuse a native fallback when int8_sym is unsupported
--enable-decode-cuda-graphs off Permit decode graph qualification; unsafe runtimes still run eagerly
--decode-cuda-graph-batch-sizes 1 2 4 8 16 32 Positive capture/replay batch buckets
--decode-cuda-graph-context-sizes 128 256 512 1024 2048 4096 Positive native-paged context buckets
--decode-cuda-graph-warmup-iters 2 Warmup iterations before each lazy capture
--decode-cuda-graph-max-memory-bytes 0 Graph private-pool byte limit; 0 is unlimited
--startup-timeout none Startup watchdog timeout, seconds
--decode-step-timeout none Decode watchdog timeout, seconds
--enable-pyspy-dump off Scaffolded flag; currently accepted and stored, but no py-spy dump is triggered
--enable-contextpilot off Enable ContextPilot middleware
--contextpilot-debug off Enable ContextPilot fault-injection/admin hooks
--phase-specific-expert-policy / --no-phase-specific-expert-policy off Enable or explicitly disable phase-specific admission, prefetch, eviction, and mixed-batch ordering over the shared expert cache
--expert-eviction-policy legacy GPU expert-cache eviction policy: legacy, lru, lfu, lfu_k, lhu, lru_k, arc, 2q, lirs, s3fifo, sieve, w_tinylfu, layer_lru, lcnu. See Configuration

Internal / deprecated:

  • MoE.generate(...) emits DeprecationWarning and is scheduled for removal; MoE.serve(...) is the continuous-batching HTTP transition path, not a drop-in in-process call replacement.
  • --max-waiting-requests and --max-n feed internal module state used by middleware.

KV-cache quantization (opt-in)

--kv-cache-format int8_sym opts into symmetric INT8 KV storage. It is disabled by default; native remains the default and one-setting rollback. See Configuration for the storage/transfer/execution precision contract, memory formula, and MLA fallback behavior.

# Opt in to INT8 KV storage
python -m moe_infinity.entrypoints.openai.api_server_v2 \
    --model Qwen/Qwen3-30B-A3B --offload-dir /local/ssd/qwen3-kv \
    --host 127.0.0.1 --kv-cache-format int8_sym

# Strict qualification: refuse any fallback
python -m moe_infinity.entrypoints.openai.api_server_v2 \
    --model Qwen/Qwen3-30B-A3B --offload-dir /local/ssd/qwen3-kv \
    --host 127.0.0.1 --kv-cache-format int8_sym \
    --no-kv-cache-format-fallback

# Immediate rollback; native remains the default
python -m moe_infinity.entrypoints.openai.api_server_v2 \
    --model Qwen/Qwen3-30B-A3B --offload-dir /local/ssd/qwen3-kv \
    --host 127.0.0.1 --kv-cache-format native

Engine stats and /v1/config expose requested_kv_cache_format, effective_kv_cache_format, kv_cache_execution_backend, and kv_cache_format_decision_reason so operators can confirm the effective format and detect a fallback. If effective_kv_cache_format reports native after requesting int8_sym, the request fell back (for example mla_not_validated) and storage is not quantized.

Python Startup

from moe_infinity import MoE

model = MoE("deepseek-ai/DeepSeek-V2-Lite-Chat", {
    "offload_path": "./offload_dir/deepseek-v2-lite",
    "device_memory_ratio": 0.5,
})
model.serve(host="127.0.0.1", port=8000, offload_dir="./offload_dir")

Binding the Python startup path to 0.0.0.0 has the same exposure and auth implications as the CLI. Configure api_key or MOE_API_KEYS before using a non-loopback bind on an untrusted network.

MoE.serve() accepts the same serving knobs as the CLI for host, port, memory ratios, batch sizing, the prefix-cache flag, offload path, and DFlash drafter setup. With --enable-prefix-caching on a supported Qwen3 + FlashInfer runtime the flag activates request-path prefix KV reuse; otherwise the cold path runs unchanged.

Models without KV history are refused at startup

Serving never passes past_key_values to the model: KV history lives in the paged KV cache and reaches attention only through a *PagedAttention shim (DeepSeek-V2/V3, Qwen3, Qwen3.5, OLMoE, Mixtral). For any other model, or when no paged attention backend was built (use_native_engine=False, e.g. GLM-5.x, GLM-5.3-Flash, MiniMax-M3, Hy3), every decode step would attend only to itself. MoE.serve() and api_server_v2 therefore raise at startup, naming the model class and the reason. MOE_STRICT_PAGED_ATTENTION=0 downgrades this to a one-time warning (multi-token output is then wrong); MOE_STRICT_PAGED_ATTENTION=1 also turns the per-forward check of a directly built ModelRunner into an error. Use MoE.generate() for refused models.

Decode CUDA graphs (experimental, opt-in)

Decode CUDA graphs are disabled by default. Enabling the flag permits the runtime to evaluate graph safety; it does not override any safety rejection. The first rollout is deliberately limited to CUDA-resident models using the native paged-attention backend and exact ordinary-GQA moe_infinity.models.qwen3_paged_attention.Qwen3PagedAttention layers.

An eligible batch must be pure single-token decode, fit a configured batch and context bucket, and have an explicit eligible runtime capability. The scheduler cache and native backend must share one PagedKVStorage object, allocator, owner ID, block count, and per-layer tensor pointers. Storage, ModelRunner, every graph buffer, and the stable output must resolve to the same indexed CUDA device. Every Qwen3 layer must have a unique in-range integer layer_idx; registration creates a distinct layer-bound subclass and requires an allocation-free paged_kv_write_ proof that writes the current token to the authoritative slot_mapping before attention reads that layer's cache.

The following always execute eagerly:

  • prefill, mixed unsupported execution, and speculative verification;
  • sampling and request callbacks (sampling is never captured);
  • non-paged models (native_paged_required);
  • FlashInfer planning/run paths (flashinfer_plan_path);
  • exact DeepseekV2PagedAttention and DeepseekV3PagedAttention MLA classes (mla_layout_unsupported);
  • active model hooks, Archer begin/end callbacks, transfer schedulers, expert dispatch, expert/KV offload, or dynamic allocation paths;
  • mismatched storage ownership/device, unknown paged classes, invalid layer_idx, or incomplete per-layer write proofs;
  • batches outside configured buckets, capture failures, and quarantined keys.

Graph keys are (batch_bucket, context_bucket). Real rows retain scheduler order and current sequence metadata. Padding rows are compute-only and use unique scratch pages reserved from the same authoritative allocator; they do not enter scheduler accounting, sampling, callbacks, or token counts. Capture is lazy and may increase the first eligible step's latency. Denser bucket sets reduce padding but consume more graph private-pool memory and scratch KV capacity.

Reload invalidates graph states before Python modules reload. Hot replacement waits for the active engine step and closes the old graph runner before returning. Application shutdown stops and awaits the engine task before closing the current runner. The sole lock order is application _engine_lifecycle_lock → engine step ownership → CudaGraphRunner._lock; shutdown never awaits a task while holding these locks. Close is idempotent and returns scratch blocks to the authoritative allocator.

Monitoring and rollback

/admin/stats reports capability_safe, bounded capability_reason, storage owner ID, registered/proved layer counts, captures, replays, failures, replay fallbacks, graph private-pool bytes, and scratch KV bytes. Prometheus exports:

  • moe_cuda_graph_captures_total
  • moe_cuda_graph_replays_total
  • moe_cuda_graph_capture_failures_total
  • moe_cuda_graph_instances
  • moe_cuda_graph_pool_bytes
  • moe_cuda_graph_scratch_kv_bytes
  • moe_cuda_graph_fallback_total{reason="..."} over the fixed reason set

Never use request IDs, model IDs, graph keys, exception text, owner IDs, or class names as metric labels.

Emergency rollback is immediate: set MOE_DISABLE_CUDA_GRAPHS=1. The gate reads it for every batch, so replays stop without process restart. Confirm that the replay counter stops and the eager fallback counter increases. Call engine.invalidate_cuda_graphs("operator_rollback") to discard captured states, or restart without the enable flag when graph memory must be reclaimed immediately. shutdown() is reserved for replacement or process shutdown and also releases scratch reservations.

Staged rollout

  1. Shadow qualification: keep production disabled. Require exact ordinary-GQA Qwen3, capability_reason=eligible, complete (class_fqn, layer_idx, writer) proof coverage, allocator/backend identity, exact device equality, per-layer persistence, two-step CUDA equivalence, cleanup tests, and paired fixture/model evidence for each model/GPU/dtype/bucket set.
  2. Canary: enable one resident native-paged replica. Alert on any capture failure, post-capture non-eligible capability, request error, owner mismatch, memory-budget breach, or replay coverage below the workload target.
  3. Limited rollout: expand only while output parity stays clean, old-engine scratch returns after replacement/shutdown, and observed p50/p99 ITL, throughput, memory, and concurrency remain acceptable.
  4. General opt-in: retain a kill switch and per-model allowlist. DeepSeek MLA, non-paged, FlashInfer, and offloaded MoE remain unsupported regardless of benchmark results.
  5. Rollback: set MOE_DISABLE_CUDA_GRAPHS=1, verify counters, then restart without the enable flag if immediate memory reclamation is required.

This feature makes no speedup guarantee. Its utility boundary is resident, native-paged ordinary-GQA Qwen3 with complete write proofs. Supporting offloaded MoE requires a separate piecewise design with explicit eager attention, routing, dispatch, and transfer boundaries.

Request Fields and Streaming

/v1/completions

Implemented request fields:

  • model, prompt
  • max_tokens, temperature, top_p
  • n, best_of
  • stream, stop, logprobs, response_format

Accepted but currently no-op / unsupported:

  • echo, suffix, user

Accepted but currently no-op:

  • presence_penalty, frequency_penalty, logit_bias

/v1/chat/completions

Implemented request fields:

  • model, messages
  • max_tokens, temperature, top_p
  • n, stream, stop
  • logprobs, top_logprobs
  • response_format

Accepted but currently no-op / unsupported:

  • user

Accepted but currently no-op:

  • presence_penalty, frequency_penalty, logit_bias

Streaming

  • Streaming uses SSE.
  • The terminal event is data: [DONE].
  • finish_reason is stop on EOS or stop-sequence termination, length on max_tokens, and error for JSON-object validation failures.
  • Parallel sampling is constrained to n <= --max-n and best_of <= --max-n.
  • Streaming with parallel sampling requires n=1 and best_of=1.

Authentication and Rate Limiting

  • API key source: --api-key first, then MOE_API_KEYS if no CLI keys are provided.
  • Format: Authorization: Bearer <key>.
  • If no keys are configured, auth is disabled.
  • Exempt routes: GET /health, GET /metrics, GET /v1/models.
  • Protected routes: completions, chat completions, /admin/stats, /v1/config, /v1/reload.
  • --rate-limit is per-key requests/minute. 0 disables limiting.
  • Rate-limit failures return 429.

Backpressure and Parallel Sampling

  • --max-waiting-requests applies queue backpressure on the scheduler.
  • When the queue reaches the threshold, the server returns 503 with a queue-full error.
  • --max-n caps n and best_of.
  • n must be positive; best_of must be positive and at least n.

Prefix Caching

Prefix KV reuse is opt-in and default off. It reuses the physical KV of an exact shared prompt prefix so a warm request only recomputes its divergent suffix, with cold/warm equivalence.

  • --enable-prefix-caching enables reuse; --prefix-cache-max-entries (default 1000, minimum 1, startup-only) bounds the prefix index.
  • Supported scope. Reuse activates only on the Qwen3 paged-attention path with a complete per-layer registry, matching KV geometry, and real FlashInfer prefill/decode. Any other runtime keeps the existing cold path and reports a stable prefix_cache_disabled_reason (for example prefix-aware-prefill-unavailable, incomplete-paged-layer-registry, or kv-store-binding-mismatch). Hybrid linear-attention models (Qwen3.5-MoE) report hybrid-linear-attention-state-unsupported, because a reused KV prefix has no state for their recurrent layers.
  • Exact identity. A hit requires exact compatibility namespace (model, tokenizer, adapter, dtype, KV geometry, attention backend/layout, position config, runtime epoch), exact parent-entry path, and exact token blocks. SHA-256 is only a bucket accelerator and never substitutes for token equality.
  • Layer completeness. One physical block names K/V for every layer in a single validated layered store; export/import, checkpoint/restore, copy-on- write, publication, and eviction operate across all layers or fail closed.
  • Atomic pinned admission. All sequences in a request group (including n>1) are pinned with leases before any eviction, then admitted together or not at all; failed admission restores tables, free count, refcounts, statuses, and open-lease count.
  • Committed-range publication. Only fully committed, block-complete prompt ranges are published after a successful forward; failed or partial chunks and DFlash verify tails are never published.
  • Copy-on-write. Indexed blocks are immutable; any write to a shared partial tail first copies every layer to a private block.
  • Reload and rollback. /v1/reload invalidates the prefix cache once after a successful module reload. Rollback is removing --enable-prefix-caching, restarting, and confirming moe_prefix_cache_active 0; there is no persisted state to migrate.
  • DFlash exclusion. Reused-prefix and non-cold requests use ordinary paged execution and are excluded from DFlash delegation.
  • Observability. /admin/stats and zero-safe moe_prefix_cache_* Prometheus metrics expose enabled/active/disabled-reason, entries, open leases, hits, matched tokens, and invalidations.

Motivated by SGLang RadixAttention (https://lmsys.org/blog/2024-01-17-sglang/) and vLLM automatic prefix caching (https://docs.vllm.ai/en/stable/examples/features/automatic_prefix_caching); no universal speedup is claimed. Prefix reuse does not change expert ownership; the multi-GPU guide covers that layout separately.

DFlash Serving

Use DFlash with a validated pair such as:

python -m moe_infinity.entrypoints.openai.api_server_v2 \
    --model openai/gpt-oss-20b \
    --offload-dir ./offload_dir \
    --speculative-draft z-lab/gpt-oss-20b-DFlash

Startup validates structural pairing (hidden size, vocabulary, mask-token bounds, target layers, block constraints, and drafter shape) separately from executor/route-ahead reachability.

The persistent path creates one canonical session per eligible sequence. It preserves the request's temperature, top-k, top-p, budget, EOS set, and request-scoped generator. It does not silently turn sampled requests into greedy requests. Unsupported grammar/guided/logit-bias metadata, penalties, logprobs, or stop strings use the standard serving fallback before drafting. That fallback is not evidence of sampled serving.

Two cache execution contexts are observable in /admin/stats:

  • temporary_dynamic is the Stage 4a compatibility mode. It keeps a temporary private DynamicCache while the engine owns scheduling, callbacks, cancellation, and request accounting. Sampled sessions and ineligible model layouts remain here; this is not sampled paged-MLA serving.
  • paged_mla is the Stage 4b default-off target enabled by enable_deepseek_mla_paging=True. It is restricted to eligible greedy batch-1 DeepSeek V2/V3 MLA sessions. The engine owns packed latent/rope target pages; the draft cache is separate. Admission is bounded by max_resident_paged_speculative_sessions (default 1) and must leave at least min_free_mla_blocks_after_admission free blocks (default 1) after reserving the block-rounded peak for the full declared prompt + max_tokens budget plus up to DFlash block_size - 1 transient verify tokens. Active sessions' committed and transient headroom that is not yet allocated is included. A rejected eligible request immediately uses temporary_dynamic; it does not wait for a paged seat, and its sampling parameters are unchanged. That dense Stage 4a fallback owns a private target cache and can therefore increase total GPU memory use even though it consumes no MLA pages.

Paged MLA is currently resident-only and has no preemption/swap implementation. The scheduler does not preempt DRAFT/VERIFY sessions. Qwen and hybrid layouts fall back to Stage 4a; hybrid paged rollback is not claimed. Cancellation after an in-flight backend call releases session resources, and per-sequence page ownership prevents one cancellation or rollback from truncating another row. Completion/cancellation frees ownership, so a later request can be admitted. /admin/stats reports active paged sessions, current free blocks, configured limits, and counters for admitted, session_cap, free_block_reserve, and ineligible decisions. begin_failed is recorded only when adapter/session construction fails; admitted increments only after construction succeeds.

The guard is block-based admission control, not a general fairness proof. It does not preempt or swap admitted sessions. External cache consumers can still invalidate reserved headroom; such allocator failures clean up the affected request and are currently re-raised by the engine step.

Route-ahead is observer-only, and pairing evidence, executor reachability, prefetch-fired evidence, and cache ownership are reported as separate facts. GPT-OSS has named valid pairs but its resident expert path attaches no executor route-ahead. For the full evidence boundary (no real DeepSeek pair; Qwen tiny-fixture only), direct batching, RNG caveats, benchmarks, and exact CPU/GPU gates, see DFlash unified execution and the compatibility matrix.

Operational Endpoints

Endpoint Method Auth Body Response / scope Production note
/v1/models GET exempt none loaded model list safe for readiness checks
/health GET exempt none STARTING / HEALTHY / UNHEALTHY safe to expose
/metrics GET exempt none Prometheus text metrics safe to scrape internally
/admin/stats GET protected none queue, batch, cache, engine stats keep private
/v1/config GET protected none current runtime config admin-only
/v1/config POST protected JSON updates only max_batch_size and max_tokens_per_step are mutable admin-only
/v1/reload POST protected reload request hot-reload Python modules admin-only

The optional /contextpilot/toggle, /contextpilot/inject-fault, and /contextpilot/status routes are intentionally cataloged in docs/contextpilot/README.md rather than this core serving table. The fault-injection route is debug-only and requires --contextpilot-debug.

Phase-specific expert policy

The opt-in policy keeps one expert store and one GPU cache; it does not create prefill and decode pools. ExpertResidencyManager is the sole enabled-mode authority for persistent membership, resident bytes, leases, candidate protection, eviction reservations, and policy counters. Dispatcher and prefetch telemetry are views of that shared snapshot.

With --phase-specific-expert-policy, a mixed serving batch executes decode rows first and prefill rows second, once each, then restores original output order. With --no-phase-specific-expert-policy (the default), a non-paged mixed batch remains one combined forward and a paged mixed batch retains prefill-then- decode order.

To roll back, restart with --no-phase-specific-expert-policy. For in-process configuration, set "phase_specific_expert_policy": false. Subordinate policy keys may remain in JSON because they are inert while the master gate is false. No cache deletion or offload-store migration is required: phase is not stored in tensor IDs, topology, or checkpoint metadata.

Before disabling after a regression, capture /admin/stats, /metrics, the effective config, and the benchmark JSON. Check starvation_promotions, prefetch_rejected, TTFT, and TPOT, and do not change device_memory_ratio between A/B runs. See Configuration, Benchmarking, and Troubleshooting.

Adaptive expert precision is not parallel-merge composable with this fixed-size manager. Land this policy first, then rebase adaptive precision onto the same lease/accounting transactions and add combined tests before co-enabling them.

Watchdogs and Diagnostics

  • --startup-timeout is disabled by default.
  • When enabled, startup timeout causes a hard exit.
  • --decode-step-timeout is disabled by default.
  • When enabled, decode timeout marks the server unhealthy instead of exiting.
  • --enable-pyspy-dump is currently a scaffolded no-op flag: it is accepted and stored in watchdog config, but the watchdog flow does not trigger py-spy dumps yet.

If you need timeout debugging, use the watchdog logs and the troubleshooting guide rather than expecting a py-spy dump.

Failure Modes

  • 401: invalid or missing API key.
  • 429: rate limit exceeded.
  • 503: request queue full.
  • 400: invalid n / best_of / other request validation.
  • finish_reason="error": JSON-object validation failure.
  • Penalties and logit_bias are accepted by the request models but are not applied in sampling.

Adaptive-memory rollout and rollback

adaptive_memory_enabled is disabled by default. It reallocates only within a fixed per-GPU budget and preserves a hard free-memory reserve.

Roll out in stages:

  1. Stage 0: keep the feature off and collect fixed-split telemetry only.
  2. Stage 1: replay deterministic traces in CI; require zero budget/minimum violations and identical repeated decisions.
  3. Stage 2: enable one CUDA canary. Alert on reserve rejection, resize failure, fallback, output mismatch, or increased OOM/preemption rate.
  4. Stage 3: use a small production percentage and compare distributions; one run is not evidence of a gain.
  5. Stage 4: broaden opt-in only with model- and workload-specific evidence.

Rollback with POST /v1/config {"adaptive_memory_enabled": false}. The transaction closes scheduler and dispatcher admissions, drains request, transfer, fetch, execute, and task-pool queues, and synchronizes every relevant CUDA completion event before changing storage. It then attempts each device's static targets, publishes the physical effective split, and resumes admissions. If exact restoration cannot fit, requests resume at the last safe split and stats report static_restore_deferred. Restarting with the flag absent or false is the final rollback.

An expert donation becomes irreversible after reserved victims move to host and release GPU storage. If receiver growth then fails, the result is partial_donor_committed: the smaller expert target and unchanged KV target are published honestly. Normal misses may reload those experts later.

Native swap and transfer endpoints carry their owning device_id; device 1 is cuda:1 and is never routed through a hard-coded cuda:0. Device-local drain waits ignore unrelated GPUs.

Per-device Prometheus metrics use a bounded device="<index>" label:

  • moe_adaptive_memory_enabled
  • moe_adaptive_memory_fallback_static
  • moe_adaptive_memory_expert_target_bytes
  • moe_adaptive_memory_kv_target_blocks
  • moe_adaptive_memory_resize_attempts_total
  • moe_adaptive_memory_resize_failures_total
  • moe_adaptive_memory_reserve_rejections_total
  • moe_adaptive_memory_expert_miss_cost
  • moe_adaptive_memory_kv_pressure_cost

Reasons remain in /admin/stats, not labels. Policy knobs other than the enable flag require restart.

KV swap lifecycle and recovery

KV transfer state is independent from request SequenceStatus:

GPU_RESIDENT -> SWAP_OUT_IN_FLIGHT -> HOST_RESIDENT
HOST_RESIDENT -> SWAP_IN_IN_FLIGHT -> GPU_RESIDENT
SWAP_OUT_IN_FLIGHT / SWAP_IN_IN_FLIGHT -> CANCEL_PENDING -> CANCELLED
HOST_RESIDENT / SWAP_IN_IN_FLIGHT -> FAILED -> reprefill recovery

The scheduler calls poll_transfers() once at the start of a scheduling pass and aggregates all members of a request group before changing queues. Group phases are OUT_IN_FLIGHT, HOST_RESIDENT, IN_IN_FLIGHT, ROLLBACK_IN_FLIGHT, and REPREFILL_PENDING. Partial completion never makes a member runnable. Successful H2D restores each member's prior status; terminal metadata, checksum, or retry failure first removes cache transfer records and then separately moves the group from SequenceStatus.SWAPPED to SequenceStatus.WAITING for reprefill.

The producer stream happens-before the transfer stream, and an early consumer waits on the completion event. A ticket retains its stream, event, and staging tensors until retire succeeds. Cancellation removes scheduler visibility but keeps a generation-keyed tombstone, EVICTING/RESTORING blocks, host lease, and ticket until DMA retires. Shutdown stops admission, synchronizes every event, retires tickets, finalizes blocks and leases, closes transfer streams, and only then releases the pool. Exceeding the shutdown warning deadline does not permit unsafe reclamation.

/v1/reload reloads Python modules; it does not migrate live KV state. Drain and replace/restart the old engine for model changes.

KV swap telemetry

/admin/stats exposes the kv_swap object and /metrics exports:

  • moe_kv_swap_inflight, moe_kv_swap_inflight_bytes
  • moe_kv_swap_retiring_records, moe_kv_swap_host_resident
  • moe_kv_swap_host_bytes, moe_kv_swap_host_capacity_bytes
  • moe_kv_swap_backpressure_total
  • moe_kv_swap_out_completed_total, moe_kv_swap_in_completed_total
  • moe_kv_swap_failures_total{direction="out|in"}
  • moe_kv_swap_bytes_total{direction="d2h|h2d"}
  • moe_kv_swap_duration_seconds_sum{direction="d2h|h2d"}

Durations are observed completion latency from monotonic submission to event observation, not pure PCIe time. Metrics contain no sequence IDs, request IDs, tokens, or checksums.

External tier and non-goals

ExternalKVStore is a future pinned-host-to-external seam. This release has no external-store implementation, distributed storage, SSD/RDMA/object-store backend, multi-node protocol, or KV quantization. The Mooncake paper motivates decoupling transfer control from storage tiers; it is not a dependency or performance claim. In short, there is no external store implementation in this change. In short, there is no external storage implementation in this change.

Rollout and rollback

  1. Stage 0: keep default sync; land CPU/CUDA correctness tests and telemetry.
  2. Stage 1: enable async on one canary; alert on failures, checksum failures, backpressure, pinned utilization, and p99 swap latency.
  3. Stage 2: expand async opt-in only after workload-specific A/B review; retain immediate restart/drain rollback to sync.
  4. Stage 3: consider changing defaults only in a separate change backed by production data. Rollback requires draining/restarting with kv_swap_mode="sync"; never change the backend while transfers are in flight.

Chunked prefill (experimental)

Chunked prefill is disabled by default. Enable it with --enable-chunked-prefill; tune the hard per-row bound with --prefill-chunk-size (default 512) and prefill-only age promotion with --prefill-starvation-threshold-steps (default 8). max_tokens_per_step remains the total decode-plus-prefill budget. Runnable decode rows consume one token each before prefill receives the remaining budget.

Activation requires complete Qwen3 paged-layer registration, real FlashInfer, and the canonical production LayeredPagedKVStore. Hybrid linear-attention models (Qwen3.5-MoE) always fall back with hybrid_linear_attention_state_unsupported. Logical block capacity is min(memory_budget_blocks, block_store.physical_capacity); unequal capacities are valid. If any capability is unavailable, the engine reports chunked_prefill_active=false and an explicit chunked_prefill_fallback_reason, then uses the unchanged whole-prefill path. The first release rejects simultaneous enable_chunked_prefill=true and enable_prefix_caching=true at startup with ValueError: enable_chunked_prefill and enable_prefix_caching cannot both be true in the first release. Chunk transactions are standalone scheduler/KV transactions and do not import or duplicate a prefix implementation. Roll back by removing --enable-chunked-prefill (or disabling prefix caching) and restarting; no request or cache-format migration is required. PR #181 is design input for a future reconciliation only, not an implementation dependency. DFlash is used only for singleton prompts completed in one prefill launch; partially prefetched prompts stay on ordinary paged decode.

Operational risks are extra scheduler launches for long prompts, page-boundary fragmentation, prefill backpressure under saturated decode load, model/backend metadata incompatibility, and latency regressions from a poorly chosen chunk size. Roll out first in shadow benchmarks, then a paged-backend canary, then a small opt-in production cohort. Roll back by removing --enable-chunked-prefill; no persisted cache or request format migration is required.