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.
Security: The parser defaults to
--host 0.0.0.0, and authentication is disabled when neither--api-keynorMOE_API_KEYSis configured. On an untrusted, shared, or cloud host, bind to127.0.0.1or configure an API key before exposure. Completion routes and privileged/admin/stats,/v1/config, and/v1/reloadendpoints 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 8curl 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.
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(...)emitsDeprecationWarningand is scheduled for removal;MoE.serve(...)is the continuous-batching HTTP transition path, not a drop-in in-process call replacement.--max-waiting-requestsand--max-nfeed internal module state used by middleware.
--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 nativeEngine 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.
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.
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 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
DeepseekV2PagedAttentionandDeepseekV3PagedAttentionMLA 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.
/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_totalmoe_cuda_graph_replays_totalmoe_cuda_graph_capture_failures_totalmoe_cuda_graph_instancesmoe_cuda_graph_pool_bytesmoe_cuda_graph_scratch_kv_bytesmoe_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.
- 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. - Canary: enable one resident native-paged replica. Alert on any capture
failure, post-capture non-
eligiblecapability, request error, owner mismatch, memory-budget breach, or replay coverage below the workload target. - 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.
- 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.
- 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.
Implemented request fields:
model,promptmax_tokens,temperature,top_pn,best_ofstream,stop,logprobs,response_format
Accepted but currently no-op / unsupported:
echo,suffix,user
Accepted but currently no-op:
presence_penalty,frequency_penalty,logit_bias
Implemented request fields:
model,messagesmax_tokens,temperature,top_pn,stream,stoplogprobs,top_logprobsresponse_format
Accepted but currently no-op / unsupported:
user
Accepted but currently no-op:
presence_penalty,frequency_penalty,logit_bias
- Streaming uses SSE.
- The terminal event is
data: [DONE]. finish_reasonisstopon EOS or stop-sequence termination,lengthonmax_tokens, anderrorfor JSON-object validation failures.- Parallel sampling is constrained to
n <= --max-nandbest_of <= --max-n. - Streaming with parallel sampling requires
n=1andbest_of=1.
- API key source:
--api-keyfirst, thenMOE_API_KEYSif 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-limitis per-key requests/minute.0disables limiting.- Rate-limit failures return
429.
--max-waiting-requestsapplies queue backpressure on the scheduler.- When the queue reaches the threshold, the server returns
503with a queue-full error. --max-ncapsnandbest_of.nmust be positive;best_ofmust be positive and at leastn.
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-cachingenables reuse;--prefix-cache-max-entries(default1000, minimum1, 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 exampleprefix-aware-prefill-unavailable,incomplete-paged-layer-registry, orkv-store-binding-mismatch). Hybrid linear-attention models (Qwen3.5-MoE) reporthybrid-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/reloadinvalidates the prefix cache once after a successful module reload. Rollback is removing--enable-prefix-caching, restarting, and confirmingmoe_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/statsand zero-safemoe_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.
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-DFlashStartup 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_dynamicis 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_mlais the Stage 4b default-off target enabled byenable_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 bymax_resident_paged_speculative_sessions(default1) and must leave at leastmin_free_mla_blocks_after_admissionfree blocks (default1) after reserving the block-rounded peak for the full declaredprompt + max_tokensbudget plus up toDFlash block_size - 1transient verify tokens. Active sessions' committed and transient headroom that is not yet allocated is included. A rejected eligible request immediately usestemporary_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.
| 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.
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.
--startup-timeoutis disabled by default.- When enabled, startup timeout causes a hard exit.
--decode-step-timeoutis disabled by default.- When enabled, decode timeout marks the server unhealthy instead of exiting.
--enable-pyspy-dumpis 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.
401: invalid or missing API key.429: rate limit exceeded.503: request queue full.400: invalidn/best_of/ other request validation.finish_reason="error": JSON-object validation failure.- Penalties and
logit_biasare accepted by the request models but are not applied in sampling.
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:
- Stage 0: keep the feature off and collect fixed-split telemetry only.
- Stage 1: replay deterministic traces in CI; require zero budget/minimum violations and identical repeated decisions.
- Stage 2: enable one CUDA canary. Alert on reserve rejection, resize failure, fallback, output mismatch, or increased OOM/preemption rate.
- Stage 3: use a small production percentage and compare distributions; one run is not evidence of a gain.
- 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_enabledmoe_adaptive_memory_fallback_staticmoe_adaptive_memory_expert_target_bytesmoe_adaptive_memory_kv_target_blocksmoe_adaptive_memory_resize_attempts_totalmoe_adaptive_memory_resize_failures_totalmoe_adaptive_memory_reserve_rejections_totalmoe_adaptive_memory_expert_miss_costmoe_adaptive_memory_kv_pressure_cost
Reasons remain in /admin/stats, not labels. Policy knobs other than the enable
flag require restart.
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.
/admin/stats exposes the kv_swap object and /metrics exports:
moe_kv_swap_inflight,moe_kv_swap_inflight_bytesmoe_kv_swap_retiring_records,moe_kv_swap_host_residentmoe_kv_swap_host_bytes,moe_kv_swap_host_capacity_bytesmoe_kv_swap_backpressure_totalmoe_kv_swap_out_completed_total,moe_kv_swap_in_completed_totalmoe_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.
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.
- Stage 0: keep default sync; land CPU/CUDA correctness tests and telemetry.
- Stage 1: enable async on one canary; alert on failures, checksum failures, backpressure, pinned utilization, and p99 swap latency.
- Stage 2: expand async opt-in only after workload-specific A/B review; retain immediate restart/drain rollback to sync.
- 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 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.