Dissecting DeepInfer: Architecture, Latency Hiding, and Memory Topologies in DeepSeek-V4.1-Flash Inference
A static source teardown of DeepInfer at commit 9bd9cf243fc53ef9afbf8f04d391d989117d6ab9
Methodology disclosure. This paper comes entirely from static source reading, grep and repository metadata. Nothing in DeepInfer was built, imported or executed. No weights were loaded, no kernels launched and no benchmarks run. Every architectural statement is tied to a repository-relative path at the revision above. Where we rebuild a mechanism as math or pseudocode, we say so. Upstream README statements about performance and production use are reported as vendor claims and are not reproduced here.
# Evidence classes used throughout
| Tag | Meaning |
|---|---|
| [S] | Source-confirmed. Directly visible in the cited code (path:line where available). It describes what the code would request if run, not observed runtime behavior. |
| [I] | Inference. A systems consequence or reconstruction derived from source (a model, pseudocode, likely intent). Not measured. |
| [C] | Upstream claim. Stated in a README or vendor documentation. Not independently verified. |
| [O] | Open question. Static analysis cannot settle it. It needs execution, comparison against a reference, or further review. |
When a sentence mixes classes, the weakest tag applies.
# 1. Abstract
Serving a sparse Mixture-of-Experts model at frontier scale is now limited less by arithmetic than by four linked resources: the KV and state cache, cross-rank expert routing, host-side scheduling latency, and agreement among many ranks on what to run next. DeepInfer is the open-sourced offline inference engine for DeepSeek-V4.1-Flash. It addresses all four with an unusually model-specific design:
- a C++ scheduler bound into a Python engine;
- a "zero-overhead" pipeline that defers each decode step's post-processing behind the next step's forward submission;
- byte-level compressed attention caches (528 B/token FP8, 288 B/token FP4) with FP32 ring-buffered compression state;
- a bounded-replay prefill truncation scheme (YoCo);
- a fixed-block speculative drafter (DFlash) with Markov token recurrence (DSpark) and a confidence-driven variable-length verifier;
- a deterministic greedy expert-placement policy (EPLB) with in-place NCCL/IPC weight shuffling.
We rebuild these mechanisms from source, formalize the scheduling and placement objectives, and draw a clear line between what the code establishes and what the vendor claims. Two limits dominate. First, the release is explicitly not a serving stack: KV persistence, prefill/decode disaggregation and replica load balancing are excluded [C]. Second, the engine's attention and top-k kernels compile only for NVIDIA SM100/SM103 (Blackwell-class), with Ascend 950 as the other supported platform. Every pre-Blackwell NVIDIA GPU therefore falls outside what can execute [S]. We close with a research roadmap of falsifiable questions. Most of it runs on CPUs; the rest needs qualified accelerators.
For an example of checking numerical parity across implementations, see the ELYRAON Rust Transfer tests that compare generated Rust with CPython on typed numerical workloads.
# 2. Introduction & Background
# 2.1 The memory wall, restated for sparse-attention MoE
In a dense transformer, decode cost is dominated by streaming weights and KV entries through HBM. DeepSeek-V4.1-Flash, as implemented in DeepInfer, changes that cost structure in three ways.
- The KV cache is compressed and sparse-indexed, not just paged. Each attention layer stores a compressed latent (compression ratio 1 or 2) in FP8 or FP4 with explicit scale bytes. A separate indexer picks a top-k subset of candidates per query, and sliding-window attention (SWA) rings run alongside [S] (
deepinfer/worker/cache_engine.py:82-249,376-493;deepinfer/model_executor/models/v4_modules/index_attn.py:133-180,284-377). Bytes per token are a design variable, not a constant. - Some state is recurrent, not append-only. Ratio-2 compression keeps per-token FP32 score/latent vectors in a circular ring that spans chunk boundaries. Speculative rollback and SWA history add more retained tokens [S] (
deepinfer/model_executor/layers/tilelang_ops/cache_common.py:20-104). The cache is therefore a mix of paged blocks and per-sequence state slots, and the two must be allocated together. - Expert routing turns load imbalance into tail latency. Routed experts are spread across expert-parallel (EP) ranks, with optional redundant physical copies [S] (
deepinfer/model_executor/models/v4_modules/moe.py:1-112). The slowest rank in each step sets that step's length.
# 2.2 The routing dilemma
The MoE gate scores experts with sqrtsoftplus and selects them with noaux_tc top-k. Selection uses per-expert correction biases plus a separate bias for image tokens [S]. Because there is no auxiliary load-balancing loss, the serving system has to absorb routing skew itself. DeepInfer's answer is EPLB: periodic, history-driven replication and placement, followed by an in-place weight shuffle (§7). Whether rebalancing pays back its weight-movement pause is an empirical question the release does not answer [O].
# 2.3 Why dissect an offline engine
An offline engine takes a batch in and returns results. It drops networking, streaming and cross-tenant fairness, but keeps the core of any production server: the step loop, cache admission, multi-rank phase agreement and kernel orchestration. DeepInfer exposes these at a depth of model co-design that general-purpose engines usually hide. That makes it a useful reference on one question: how far should an inference engine be specialized to a single model?
# 2.4 Scope and non-goals
- Covered: the Python engine and worker, the C++ scheduler and block manager, the V4.1 model path, cache layouts, speculative decoding, EPLB, and the declared hardware and build requirements.
- Not claimed: runtime correctness, output quality, speedup, memory capacity for the official model, or superiority over any other engine.
- Not reproduced: vendored kernel source. Submodule licenses have not been reviewed (§11).
# 3. Architecture Overview & Control Plane
# 3.1 System decomposition
┌───────────────────────────────────────────────┐
user prompts ────────▶ │ deepinfer/entrypoints/llm.py :: LLM.generate │
(text | token IDs | │ per-request SamplingParams copy, submit, │
multimodal payload) │ loop step(), flush deferred, clone outputs │
└──────────────────────┬────────────────────────┘
│ add_request / step()
┌──────────────────────▼────────────────────────┐
│ deepinfer/engine/llm_engine.py :: LLMEngine │
│ _init_workers _init_cache _create_scheduler │
│ deferred-release pools, MM fetch, stats │
│ (optional profiling HTTP via ProfileManager)│
└───────┬──────────────────────────┬────────────┘
pybind │ │ worker processes
┌──────────────────────▼─────────┐ ┌────────────▼─────────────────────┐
│ csrc/engine/scheduler.hpp (C++)│ │ deepinfer/worker/worker.py │
│ waiting / running / prompted │ │ ZOS pipeline, accepted-token │
│ DP phase votes (all-reduce) │ │ repair, MTP confidence varlen │
│ prefill admission, chunking │ │ deepinfer/worker/model_runner.py │
│ decode + preemption │ │ cuda_graph_runner.py (+ DFlash) │
│ mtp_varlen.hpp, flops_est.hpp │ │ cache_engine.py (KVCacheManager) │
│ csrc/engine/block_manager.hpp │ └────────────┬─────────────────────┘
│ block 0 sentinel, refcounts, │ │
│ joint block+state allocation │ ┌────────────▼─────────────────────┐
│ input_metadata/block_load_plan │ │ DeepseekForCausalLM (V41Builder) │
│ prepare_sample.cpp (GIL off) │ │ embed ▸ [HC MoE decoder]×L ▸ │
└────────────────────────────────┘ │ norm ▸ head ▸ sampler ▸ DFlash │
└────────────┬─────────────────────┘
┌──────────────┬──────────────┬─────────────┼──────────────┬──────────────┐
▼ ▼ ▼ ▼ ▼ ▼
FlashMLA DeepGEMM DeepEP DeepSelect TileLang ops xgrammar
sparse MLA/MQA FP8/FP4 GEMM EP dispatch/ top-k index cuda/ & asc/ structured
prefill/decode (runtime JIT) combine selection (~30 each) output masks
[S] The Python front end (llm_engine.py, 1,029 lines) owns the lifecycle and process orchestration. The C++ scheduler (scheduler.hpp, 1,329 lines, exposed via pybind) owns every decision about sequence sets, block tables, state slots, preemption and MTP slots. The worker owns device execution and the asynchronous pipeline.
[S] LLM.generate clones the request outputs it returns because internal pools may reuse those objects (deepinfer/entrypoints/llm.py:30-82,118-198). Deferred-release pools keep Python and native objects alive across asynchronous work (deepinfer/engine/llm_engine.py:860-1016). Both point to a strict object-lifetime discipline, which the deferred pipeline in §4 requires.
[S] The optional profiling HTTP endpoint (deepinfer/engine/profile_server.py:136-159,182-227) is for profiling, not inference. The release has no online serving API, authentication or streaming transport.
# 3.2 Startup sequence
[S] (llm_engine.py _init_workers/_init_cache; deepinfer/model_executor/model_loader.py:83-153; deepinfer/hugging_face/{loading,weights,names}.py)
bind process/device ─▶ init process groups ─▶ build V4.1 params on `meta`
─▶ validate checkpoint coverage + shapes ─▶ load covered weights
(MoE physical-expert padding resolved against EP group size first)
─▶ synthetic profile forward ─▶ free-memory / peak-allocation accounting
─▶ all-rank agreement on a common num_blocks ─▶ allocate cache buffers
─▶ warm up + capture CUDA graphs (main runner + DFlash runner)
ModelConfig accepts auto or synthetic dummy weights and adds extra position headroom for lookahead and ZOS [S]. A common block count across ranks is required for correctness, not just speed: DP ranks vote on phases (§3.4), so they must share the same admission limits [I].
# 3.3 Hybrid distributed topology: DP × CP × EP × Engram
[S] ParallelProcessGroup builds these groups: world/local, data parallel (DP), context parallel (CP), expert parallel (EP) and Engram parallel. Selected groups also get CPU Gloo counterparts. On Ascend, distributed execution maps to HCCL and TileLang maps to its asc backend (deepinfer/platform.py:86-141; tilelang_ops/ops.py:13-22). NVIDIA uses NCCL, plus DeepEP's NVLink/RDMA transports.
With DP size $D$, CP size $C$ and EP size $E$:
$$
R_{\text{model}} = D\cdot C,\qquad E \mid R_{\text{model}},\qquad W \ge R_{\text{model}}\ \ (\text{world can be enlarged for Engram parallelism})
$$
- [S] EP groups are contiguous partitions of the $D\cdot C$ model ranks.
- [S] CP input metadata is broadcast from the driver and can use mirror or gather layouts. Attention and hidden-state gathers use CP collectives.
- [S] MoE traffic flows through user buffers and DeepEP. Engram embedding fetches use a separate Engram-parallel user buffer that runs in GPU or CPU-RDMA mode (
deepinfer/model_executor/parallel_utils/userbuffer.py:1-240). - [I] Because EP groups are contiguous, the rank numbering determines which DP×CP replicas share an expert set. NVLink locality therefore depends on how ranks map to hosts. This matters because the MegaMoE fast path is only taken when the EP group fits inside the NVLink domain the code queries (§7.5).
rank ─▶ 0 1 2 3 4 5 6 7 (illustrative: D=4, C=2, E=4) DP ├─d0─┤ ├─d1─┤ ├─d2─┤ ├─d3─┤ CP c0 c1 c0 c1 c0 c1 c0 c1 EP ├──── e-group 0 ────┤ ├──── e-group 1 ────┤
This example illustrates the formulas only. It is not a validated or recommended topology [I].
# 3.4 Phase selection and two-stage DP consensus
In NORMAL mode, every DP rank must run the same phase in a given step. If they diverged, the MoE-dispatch and CP collectives would mismatch [I]. PROMPT-only and COMPLETION-only modes force a single phase [S].
[S] Reconstructed from csrc/engine/scheduler.hpp:287-344:
procedure SELECT_PHASE(rank r):
if mode == PROMPT: return PREFILL
if mode == COMPLETION: return DECODE
ALL ← allreduce_AND(|waiting_r| > 0) # vote 1
ANY ← allreduce_OR (|waiting_r| > 0)
want ← (periodic ALL-point ∧ ALL) ∨ (periodic ANY-point ∧ ANY)
want ← want ∧ (gpu_cache_usage ≤ 0.90) # prefill watermark
if want:
admitted_r ← ADMIT_PREFILL(r) # may admit nothing
if allreduce_OR(admitted_r ≠ ∅): # vote 2
return PREFILL
return DECODE
The second vote is the subtle part. A rank can pass vote 1 because it has waiting work, yet admit nothing because of budget or capacity limits. Without vote 2, the fleet would run an empty prefill step and decode scheduling would keep resetting. The post-admission vote ensures a prefill step happens only when some rank actually admitted work [S/I].
[O] Under skewed arrivals, do the ALL/ANY intervals keep rank idle time low, or do they starve ranks whose queues fill late? Under long decode tails, can the fixed 90% watermark keep the fleet in decode while prefill demand builds?
# 3.5 Prefill admission
[S] Admission is FIFO over the waiting queue. A sequence is committed only after every check below passes (scheduler.hpp:230-344,390-539):
| Check | Constraint |
|---|---|
| Request count | running + admitted ≤ sequence limit |
| Token budget | batched prompt tokens ≤ batched-token limit |
| Context bound | Σ context lengths ≤ configured bound |
| Joint capacity | free KV blocks and free state slots are both sufficient |
| Chunk checkpoints | chunks respect the configured maximum prompt-work budget |
| CP alignment | chunk compatible with the context-parallel layout |
| Image boundary | a chunk boundary may not split an image-pad span; the span is adjusted as a unit |
When a sequence is forked, its partially filled final block is copied rather than shared [S].
[I] Strict FIFO creates head-of-line blocking. If the head request cannot be admitted, admissible requests behind it wait. Chunking eases this for long text prompts, but image-span protection makes chunk sizes coarser for multimodal requests.
# 3.6 Two distinct "slot-0" reservations
These two mechanisms are easy to conflate:
- [S] Physical KV block 0 (
csrc/engine/block_manager.hpp:30-128).BlockManagerreserves block 0 as a sentinel and hands out IDs from 1 upward. It reference-counts pinned and shared blocks and denies any request that would use up allnum_blocks. Block allocation and state-slot acquisition are guarded together (block_manager.hpp:145-242), so KV and state are acquired as one unit. - [S] Speculative-metadata slot 0 (scheduler /
layers/mtp_info_pool.py). Slot 0 is reserved as the padding target for speculative metadata.
[I] Both follow the same idiom: give padding and invalid lanes a valid target that no request ever owns. Fixed-shape kernels and CUDA graphs can then run without bounds branches. The cost is one block and one slot.
# 3.7 Decode scheduling and preemption
[S] (scheduler.hpp:622-645,765-789,917-924)
- Running requests are sorted by descending output length and scheduled from the opposite end.
- Under block pressure, the scheduler preempts from the longest-output end while another request remains.
- A preempted request is recomputed: it is reset and placed at the front of the waiting queue. Structured-output requests cannot be recomputed and instead finish as preempted.
- Deferred ZOS outputs belonging to a sequence that has already been reset for recomputation are skipped.
- Decode accounting reserves room for speculative and lookahead tokens.
[I] Evicting the longest-output request frees the most blocks per preemption, but it also discards the most work. Users should know that structured-output requests can terminate under memory pressure, because that is a visible difference in semantics.
# 3.8 The native CPU-to-kernel ABI
[S] csrc/engine/input_metadata/block_load_plan.cpp:14-59 turns the cache layout into zero-fill, paged and circular-ring segments. Each segment is packed as four pinned int32 values. The CUDA load kernel zero-fills when src_block_id == -1; otherwise it dequantizes with scale factors into BF16 (tilelang_ops/cuda/load_paged_kv_cache.py:84-126). Output coverage must not overlap unless an initialized output buffer is supplied (tilelang_ops/load_paged_kv_cache.py:37-60). Separately, csrc/engine/prepare_sample.cpp:40-90 releases the GIL, rejects mixed prefill/decode batches, validates sequence lengths and allocates pinned sampling metadata.
/* Reconstructed descriptor (illustrative, not vendor code) */
struct LoadSegment { /* 4 x int32, pinned host memory */
int32_t src_block_id; /* -1 => zero-fill */
int32_t src_begin;
int32_t src_end; /* exclusive */
int32_t dst_offset;
};
[O] These descriptors are only as safe as host-side validation. TileLang kernels declare T.assume preconditions (cuda/load_paged_kv_cache.py:74-98, cuda/compress.py:109-118). Whether the host enforces every one of them is unresolved.
# 4. Latency Hiding via Zero-Overhead Scheduling (ZOS)
# 4.1 The pipeline as implemented
[S] ZOS is on by default [C: README "zero-overhead batch scheduler"]. Under ZOS, a decode step's post-processing (token commit, stop checks, output mutation, structured-output matcher advance) is deferred. Worker step $t$ runs in this order (deepinfer/worker/worker.py:96-102,113-159,167-187,262-268):
- submit the main-model forward $F_t$ for step $t$;
- run the deferred post-processing $P_{t-1}$ for step $t-1$ on the host while $F_t$ is in flight;
- sample step $t$ ($S_t$);
- defer $P_t$ to step $t+1$.
Sampling for $t-1$ was already submitted inside step $t-1$. Events and accepted-token counts order the handoff, and some host-visible metadata is synchronized before CPU-side sampling work (worker.py:89-182,183-283).
host │ sched_t │ launch F_t │ P_{t-1} (CPU post) │ sync │ prep/launch S_t │ sched_{t+1} │ launch F_{t+1} │ P_t ...
device │ ════════ F_t (forward) ════════ ══ S_t ══ ════════ F_{t+1} ════════
▲ overlap window: P_{t-1} hidden under F_t
# 4.2 Breaking the dependency: GPU-side sequence-length repair
Speculative decoding creates a dependency problem. Step $t$'s key lengths depend on how many drafts were accepted at $t-1$, and with ZOS the host has not yet processed that result when it schedules $t$.
[S] DeepInfer fixes lengths on the device instead. compute_seqlens_k_zos (tilelang_ops/cuda/compute_seqlens_k_zos.py:1-38) runs one 128-thread CTA per sequence block. It adjusts each key length using the query length and accepted-token remap values, and remaps sequence rows. MTP confidence can also change query lengths (§6.4).
A reconstruction of the per-sequence relation [I]:
$$
k_i^{(t)} \;=\; k_i^{(t),\text{sched}} \;-\; \big(d_i^{(t-1)} - a_i^{(t-1)}\big) \;+\; \Delta q_i^{(t)}
$$
Here $d_i$ is the number of draft slots reserved, $a_i$ the number of tokens accepted on the GPU, and $\Delta q_i$ the query-length change from variable MTP. The scheduler plans with reserved lookahead capacity (§3.7), and the device subtracts rejected drafts once the accept count exists in device memory. The host never waits on it [I].
# 4.3 An analytical step-time model
[I] This model is ours; it was not measured. Let $h_\cdot$ be host time, $g_\cdot$ device time and $\sigma$ the explicit host-device syncs.
$$
T^{\text{serial}}_{\text{step}} \approx h_{\text{sched}} + h_{F} + g_F + \sigma + h_S + g_S + h_P
$$
$$
T^{\text{ZOS}}_{\text{step}} \approx h_{\text{sched}} + h_F + \max\!\big(g_F,\; h_P\big) + \sigma + h_S + g_S
$$
The saving is bounded by $\min(g_F, h_P)$. "Zero overhead" holds in the limit $h_P \le g_F$, where post-processing hides completely under the forward pass. CUDA graph replay (§4.5) shrinks $h_F$ toward a constant. The remaining serial terms are scheduling, launch, the sync and sampling.
# 4.4 Pipeline stall points
| Stall | Origin | Class |
|---|---|---|
| Host-visible metadata sync before CPU-side sampling | worker.py:183-283 |
[S] the sync exists; [O] its cost |
| Structured-output masks depend on matcher state advanced by $P_{t-1}$ | sampler applies bitmasks before verification (layers/sampler.py:411-596) |
[I] likely serializes $P_{t-1}$ ahead of $S_t$ for constrained rows |
| Preemption/reset invalidates deferred outputs | scheduler.hpp:917-924 |
[S] skip logic; [I] wasted post-processing |
| CUDA graph bucket padding | cuda_graph_runner.py:1-168 |
[S] bucketing; [I] padded lanes cost device time |
| Matcher compilation not finished | CPU thread pool; request waits | [S] |
| Prefill steps | ZOS deferral is described for decode | [I] prefill likely sees less overlap |
# 4.5 CUDA graphs
[S] The main graph runner rounds batch sizes up into capture buckets, captures after warm-up, keeps fixed input/output buffers, and replays the smallest eligible bucket. DFlash has its own graph runner that pads and strips per-request draft blocks (deepinfer/worker/cuda_graph_runner.py:1-168; deepinfer/worker/dflash_cuda_graph_runner.py:1-100). [I] Bucket granularity trades padding waste against the number of captured graphs and their memory. [O] No graph was captured or replayed in this study.
# 5. Memory Footprint & State Cache Engineering
# 5.1 Compressed sparse attention, not generic paging
[S] V4 attention combines the query and compressed-KV projections where compatible, builds sparse-index query/key projections where configured, and records whether each layer produces or consumes shared KV/index state (v4_modules/attn.py:481-671,752-882). Prefill calls a variable-length sparse attention path over current and cached representations. Decode selects cache indices and calls the sparse MLA/MQA decode kernel. SWA can be combined with compressed attention. KVCacheManager explicitly rejects full-attention layers, so the cache is a V4.1-specific design and not a generic KV store.
# 5.2 Per-token layouts
[S] From tilelang_ops/cache_common.py:20-104:
| Format | Data bytes | Scale bytes | Total B/token (main KV, per layer view) |
|---|---|---|---|
| FP8 | 512 | 16 | 528 |
| FP4 (packed) | 256 | 32 | 288 |
[I] 512 FP8 bytes and 256 packed-FP4 bytes both hold 512 elements, which suggests a 512-wide latent. FP4 needs twice the scale bytes, which suggests finer-grained scaling for FP4. The exact grouping and scale encoding were not traced. FP4 cuts main-KV bytes by $1 - 288/528 \approx 45.5\%$. At compression ratio $r=2$, bytes per original token halve again, to 264 (FP8) or 144 (FP4).
[S] Compression state is FP32, shaped [state_seq, ring, 2, dim]. [I] The axis of size 2 most plausibly holds the {score, latent} pair (§5.3).
# 5.3 Ratio-2 compression kernel
[S] (v4_modules/compress.py:38-167; tilelang_ops/cuda/compress.py:35-292) Each token $j$ is projected to a score $s_j$ and a latent $z_j$, and both per-token FP32 vectors are written to the ring. That lets a compression group straddle a chunk boundary. For each group $\mathcal{G}$ of $r$ tokens, the kernel reloads the group and computes a temporary max-subtracted softmax:
$$
m = \max_{j\in\mathcal{G}} s_j,\qquad
\hat z_{\mathcal{G}} = \frac{\sum_{j\in\mathcal{G}} e^{\,s_j - m}\, z_j}{\sum_{j\in\mathcal{G}} e^{\,s_j - m}}\quad(\text{elementwise, FP32})\;\to\;\text{BF16}
$$
The softmax accumulators are temporary. Only the per-token score/latent values persist in the ring [S]. The model wrapper then applies normalization, rotary and Hadamard transforms and casts to the cache format. The indexer can consume the pre-RoPE latent [S].
Prefill ordering. [S] Compute and state-store use separate launch grids, connected by a producer-consumer PDL synchronization point. Compile-time flags fix dimension, ratio and index; runtime arguments supply strides and lengths. [I] The split lets a chunk's tail tokens be consumed before their ring slot is overwritten, which removes a read-after-write hazard across chunks. [O] Register allocation, generated instructions and race-freedom under the real compiler cannot be seen in source.
[S] Related kernels (tilelang_ops/cuda/state_cache.py:1-136): one kernel copies a requested circular-ring slice into a temporary view, and another scatters flattened ring data to its destination using byte-addressed copies.
# 5.4 Fused transform → quantize → store
[S] The fused cache-transform builder exposes optional stages: norm, RoPE, Hadamard, FP8/FP4 cast and cache store. It enforces constraints on head dimension, rotary, scale factors, output stage and cache ABI. CUDA and Ascend implementations are separate, and Ascend adds SIMD/pipeline-stage constraints plus its own rstd_1ulp numeric helper (cuda/fused_transform.py:17-90; asc/fused_transform.py:31-105; asc/rstd_1ulp.py:23-74). [O] Numerical equivalence between the two backends has not been tested.
# 5.5 Sparse indexing and decode kernels
[S] The indexer projects the compressor output, normalizes it, applies rotary, quantizes the index keys, scores query-to-candidate rows and calls top-k (index_attn.py:133-180,284-377,421-548). Candidate IDs are int32, with -1 marking invalid entries. In prefill, attention loads old ring entries before writing slots that may alias them.
[S] FlashMLA sparse decode, head-64 path (vendor/FlashMLA/csrc/api/sparse_decode.cpp:187-345,382-462; .../sm100/decode/sparse/head64/kernel.cuh:177-275,297-334,664-736):
- Dispatch checks the architecture (SM100f) and shape constraints. It chooses split-K only under specific batch-invariant/top-k conditions, and allocates per-split FP32 output/LSE buffers when it splits.
- The kernel is templated on a top-k tile of 64. It launches 384 threads, sizes its grid by split mode and batch, sizes dynamic shared memory from a plan, double-buffers KV and index tiles, and synchronizes with named barriers.
- Softmax uses FP32 with base-2 exp/log. The attention-sink term is placed so that split partials do not each count it.
- The output may be FP8 with scale metadata for the next projection. Fallback paths pad head counts and trim the result (
layers/attention_backend.py:33-146).
[S] Other paths are separate implementations. Head-128 decode is its own kernel. Prefill dispatches head-64 to a dedicated path, and head-128 to a regular or small-top-k kernel (small-top-k when topk <= 1280 and its required features are supported). On Ascend, sparse decode uses Decode mode with head tile 64 and no split-KV metadata (sparse_prefill.cpp:19-58,198-218; sparse_decode.cpp:85-96,125-164). Conclusions about the head-64 decode launch must not be carried over to these paths.
[O] Split-K determinism, numerical error against a reference, and occupancy all remain unmeasured.
# 5.6 Cache accounting
[S] KVCacheManager computes per-layer byte layouts, ring sizes that include rollback room, extra tokens for prefill-store state and YoCo retention, and independent sharing maps for main KV and index K (_get_kv_mapped_layer_id, SharedLayerTopology). CacheEngine allocates one GPU byte buffer for cache payloads and a separate state buffer, then carves typed views out of them (cache_engine.py:851-978).
[I] Approximate per-sequence footprint for $n$ tokens and block size $b$:
$$
B(n) \approx \sum_{\ell\in\mathcal{O}_{\text{kv}}} \Big\lceil \tfrac{n}{r_\ell b}\Big\rceil b\, \beta_{\text{fmt}}
+ \sum_{\ell\in\mathcal{O}_{\text{idx}}} \Big\lceil \tfrac{n}{r_\ell b}\Big\rceil b\, \beta_{\text{idx}}
+ \sum_{\ell\in\mathcal{L}_{\text{swa}}} (w + \rho + y)\,\beta_{\text{swa}}
+ \sum_{\ell\in\mathcal{L}_{r=2}} 4\cdot R\cdot 2\cdot d
$$
- $\mathcal{O}_{\text{kv}}$, $\mathcal{O}_{\text{idx}}$: the layers that own main-KV and index state (layers that share state contribute nothing);
- $r_\ell \in \{1,2\}$: the compression ratio;
- $\beta_{\text{fmt}} \in \{528, 288\}$: bytes per token for the cache format;
- $w$: the SWA window; $\rho$: rollback history; $y$: YoCo or prefill-store extra tokens;
- $R$: the ring length; $d$: the state dimension.
Index and SWA per-token bytes ($\beta_{\text{idx}}, \beta_{\text{swa}}$) were not traced. [O] Fragmentation from allocating blocks and state slots jointly has not been studied.
# 5.7 YoCo bounded replay (prefill truncation)
[S] YoCo consumer layers start at n_prefill_layer. When DEEPINFER_YOCO_PREFILL_TRUNCATION_MODE is enabled, the model keeps only the indices of a retained token suffix at the producer/consumer boundary. It compacts hidden and residual rows and updates cross-layer candidate/index metadata to match (v4_modules/yoco.py:1-123). The documented invariant is:
$$
\texttt{KEEP\_TOKENS} \;\ge\; w_{\text{SWA}} + \rho_{\max}
$$
That is, the retained suffix must cover the sliding window plus the maximum speculative backtracking.
prompt tokens: [ 0 ............................................ n-1 ]
producer layers (< n_prefill_layer): process all n, write shared KV/index
│ compaction: keep suffix of length K
▼
consumer layers (≥ n_prefill_layer): [ n-K ........ n-1 ]
reuse producer KV/index; hidden/residual + candidate metadata compacted together
[I] The name and structure suggest a "cache once, consume many" producer/consumer split. If so, prefill compute in consumer layers scales with $K$ rather than $n$, while attention over the full context is still served from producer-written state. [O] It is unverified whether logits or tokens are exactly equivalent with truncation on versus off across boundary positions, rollback lengths, chunk boundaries and CP layouts. The README values are configuration guidance [C].
# 6. Speculative Decoding: DFlash, DSpark & Adaptive MTP
# 6.1 Architecture
[S] V41Builder adds one DFlash prediction head per configured next-token-prediction layer. DFlash can override the main model's MoE configuration and uses configured DSpark target layers and a configured Markov rank. DEEPINFER_USE_NEXTN_DECODE defaults to 5 (maximum drafts). DEEPINFER_ENABLE_MTP_VARLEN is a separate switch. DFlash has its own attention and SWA-cache update paths rather than reusing the main decoder's attention call unchanged.
[S] Key-cache coupling. The main-model forward also writes the DFlash layers' main-token keys, derived from target-layer features. In decode, draft positions overwrite their slots before any read, including positions that verification later rejects (models/mtp/dflash.py:198-228). [I] Rejected drafts therefore never need explicit cleanup: they are overwritten before anyone reads them.
# 6.2 Fixed-stride draft blocks and DSpark recurrence
[S] (dflash.py:279-387) For each request, DFlash builds a fixed-stride block of $N$ draft embeddings:
position: 0 1 2 ... N-1
input: [golden token] [noise] [noise] ... [noise]
└────────── one DFlash forward over the block ──────────┘
sample: y1 ← logits_1 (row by row)
y2 ← logits_2 ⊕ Markov(y1)
y3 ← logits_3 ⊕ Markov(y2) ... (no new decoder forward)
confidence: c_k = σ(clamp(w·h_k)) per draft position
[S] A single forward pass produces all hidden rows. Sampling then walks the output positions in order. The optional DSpark Markov embedding feeds the previously sampled draft ID into later-position logits without another decoder forward. A confidence head predicts each position's acceptance probability; its projection kernel accumulates in FP32 and clamps before the sigmoid (tilelang_ops/cuda/dflash.py:1-119). Input assembly uses fixed tiles and explicitly writes padded/invalid positions (cuda/get_kv_index.py:1-138). Results go to the MTP info pool. In decode, the whole path (input broadcast, metadata, draft layers, sampling and pool writes) can be replayed as a captured graph.
[I] One way to formalize it is $\ell_k = W h_k + M(y_{k-1})$, where $M$ is a low-rank Markov term. This restores some sequential dependency between drafts at roughly the cost of an embedding lookup, rather than the autoregressive drafter's $N$ forward passes. The exact functional form was not traced.
# 6.3 Verification
[S] (layers/sampler.py:411-596) The sampler maps proposal rows to requests and draft positions, applies blacklists and structured-output masks, gathers target and draft log-probabilities, accepts a prefix, emits the stop or bonus token, writes verification metadata, and schedules the next DFlash draft from the resulting golden tokens. The fused sampler keeps separate RNG offsets for draft, residual and verification choices (cuda/fused_sample.py:1-524).
[I] Separate residual offsets fit standard speculative rejection sampling: accept draft $y$ with probability $\min(1, p(y)/q(y))$, and otherwise resample from $\mathrm{norm}\big((p-q)_+\big)$. [O] It has not been tested whether the outputs follow the target distribution exactly across temperature, top-k, top-p and seed modes.
# 6.4 The variable-length verification heuristic
[S] Implemented in csrc/engine/mtp_varlen.hpp:160-207, tilelang_ops/cuda/schedule_mtp_varlen.py:26-81 and worker/worker.py:218-234.
Expected accepted tokens. For request $i$ with per-position confidences $c_{i,1..N}$, the GPU allocator forms cumulative products:
$$
\pi_{i,k} = \prod_{j=1}^{k} c_{i,j},\qquad \mathbb{E}[A_i] = \sum_{k=1}^{N} \pi_{i,k}
$$
The allocator ranks all $\pi_{i,k}$ globally, breaking ties by flat index [S]. [I] Because $\pi_{i,k}$ cannot increase with $k$, taking the global top-$T$ always yields a valid prefix for each request. Prefix validity comes from the ranking itself, with no explicit constraint.
Choosing the total budget $T$. [S] The scheduler sorts acceptance estimates and combines three inputs: an offline decode graph-size timing curve, an online forward-time slope, and sampler-time medians. It then picks the verification size with the highest estimated expected-token throughput. [I] Reconstructed objective:
$$
T^\star = \arg\max_{T}\; \frac{n + \sum_{(i,k)\in \text{top-}T} \pi_{i,k}}{\hat t_{\text{fwd}}(n+T) + \hat t_{\text{samp}}(n)}
$$
where $n$ is the number of sequences and $\hat t_{\text{fwd}}$ is the offline curve corrected by the online slope.
Estimators. [S]
| Estimator | Window / rule |
|---|---|
Sampler time SamplerRuntimeEstimator |
sliding median over 9 samples (minimum 5), keyed by sequence count, global fallback |
| Forward residuals | up to 5,000 recent samples |
| Per-graph medians | need 10 observations; median across eligible graph sizes gives the slope |
| No timing curve | schedule all available drafts |
Asymmetric staleness: N−2 versus N−1. [S] Total verification work is chosen from N−2 acceptance estimates. That total is then allocated per request using the newer N−1 estimates. Scheduling and process counters account for the post-processing lag that ZOS introduces. [I] Under ZOS, when step $t$ is scheduled on the host, the newest fully processed confidences are two steps old. One step newer confidences exist on the GPU, so they can be used for per-request allocation without a host sync. The design matches each decision to the newest data available to it without stalling the pipeline.
[O] The heuristic is only as good as confidence calibration and the representativeness of the timing curve. Neither has been measured. Acceptance by position, calibration error per workload and end-to-end benefit need qualified hardware.
# 6.5 FLOP accounting
[S] flops_estimator.hpp computes FP8-equivalent FLOP estimates for attention, MLP, router, HC, Engram and logits. It documents what it omits: small ops, vision, drafts, padding and replicas. It models MFU; it is not a hardware counter.
# 6.6 Sampling, structured output and determinism
[S] Fused sampling uses one CTA per row, stable FP32 log-sum-exp, a filter/radix stage for large vocabularies, top-k/top-p/temperature transforms and fixed-point random thresholds. Each sequence has a uint64 seed (sampler_utils.py). The structured-mask kernel treats each int32 word as 32 token bits and writes −∞ for forbidden logits (cuda/structure_output.py:1-59; cuda/random_sampling.py:1-258).
[S] Structured output wraps xgrammar (deepinfer/structure_output/):
- Matchers compile in a CPU thread pool while their requests wait.
- The matcher tracks trigger-token progress and an optional bound token.
- It supports rollback after verification, with history capped by the maximum draft count.
- Offline mode rejects serialized grammars and legacy multi-token bounds.
- A cache kill-switch exists.
[C] The README says batch-invariant mode and deterministic sampling are NVIDIA-only, and advises disabling variable MTP in its deterministic recipe. [S] runtime_config.py branches on DEEPINFER_BATCH_INVARIANT and PLATFORM.is_npu, and the FlashMLA split-K choice depends on batch-invariant mode. [I] Disabling varlen MTP for determinism makes sense: its timing-driven budget (§6.4) depends on measured runtimes, so the verification shapes, and possibly the outputs, would differ between runs.
# 7. Deterministic Expert Parallel Load Balancing (EPLB)
# 7.1 Problem statement
Let $L\in\mathbb{R}_{\ge 0}^{H\times X}$ be the historical token load of $X$ logical experts over $H$ steps. EPLB must choose replica counts $c_x\ge 1$ with $\sum_x c_x = P$ physical slots, and an assignment of physical experts to $G$ ranks [I formalization of deepinfer/model_executor/eplb/policy.py].
# 7.2 Stage 1: replication
[S] (policy.py:97-127) Greedily add replicas one at a time. For each candidate $x$, recompute the per-step load per copy with $c_x+1$ copies, and choose the candidate that minimizes:
$$
x^\star = \arg\min_{x}\; \sum_{h=1}^{H} \max_{x'} \frac{\tilde L_{h,x'}}{c'_{x'}},\qquad c' = c + e_x,\qquad \tilde L_{h,x} = L_{h,x} + x\cdot 10^{-4}
$$
The perturbation $x\cdot10^{-4}$ breaks ties between experts with the same current maximum.
# 7.3 Stage 2: placement
[S] (policy.py:31-70) Sort physical experts by $w_p = \big(\sum_h L_{h,x(p)}\big)/c_{x(p)}$ in descending order (stable sort). Assign each one to the rank that minimizes the sum over history of each step's maximum rank load, breaking ties with the lowest-rank argmin.
procedure EPLB_PLACE(physical experts P sorted desc by w_p, ranks G):
load[h][g] ← 0
for p in P: # stable order
best ← argmin_g Σ_h max_{g'} ( load[h][g'] + [g'=g]·L[h,x(p)]/c[x(p)] )
assign p → best # lowest g on ties
load[h][best] += L[h,x(p)]/c[x(p)] ∀h
[I] This is an LPT-style (longest processing time first) greedy for a multi-scenario makespan objective. It optimizes the sum of per-step bottlenecks rather than the bottleneck of the averaged load, so it is sensitive to temporal skew that averaging would hide. Per-rank slot capacity is presumably fixed by the physical layout; we did not trace that constraint. Naively, each placement costs $O(G\cdot H\cdot G)$, and the policy is tensorized PyTorch. [O] How close it gets to optimal is unknown. Comparing it with an exact solver on small instances is a cheap CPU experiment (§10).
# 7.4 Determinism and the 1e-4 tie-breaker
[S] Stable sorting and lowest-rank argmin make placement repeatable for an identical input tensor. Replication relies on the $x\cdot10^{-4}$ perturbation.
[I]/[O] Precision analysis (conditional). The teardown does not state the load dtype. If loads are float32, the ulp at magnitude $m\in[2^k, 2^{k+1})$ is $2^{k-23}$. Once $m\ge 1024$, the ulp ($\approx1.22\times10^{-4}$) is larger than the spacing between adjacent IDs ($10^{-4}$). Perturbations for neighboring expert IDs can then round to the same value, and the intended tie-break silently disappears. Ties then fall back to argmin's first-index rule, which is still deterministic, but the perturbation no longer does what it was written to do. For bf16 this happens much earlier; for float64 it does not happen at realistic loads. Conversely, if loads are integer token counts, real load differences (≥1) dwarf the perturbation's total range ($X\cdot10^{-4}$), so it cannot reorder experts whose loads genuinely differ.
Status: an unresolved question, not a verified defect. A further open question is whether CPU and GPU reductions, or different history-aggregation orders, produce bit-identical $L$. If not, "deterministic for an identical tensor" does not mean deterministic across nodes.
# 7.5 Applying the plan: in-place shuffling and the dispatch path
[S] eplb/shuffle.py:1-218 applies the new map in place:
- local copies for experts already on the rank;
- pairing of remote senders and receivers;
- batched NCCL point-to-point transfers;
- an intranode IPC-mirror path.
[I] In-place application requires that no slot is overwritten before its old contents have been sent. Its ordering and staging deserve a dedicated correctness review [O].
[S] Dispatch path selection (v4_modules/mlp.py:177-188,221-228,254-255,359-616). use_mega_moe requires a supported matmul type and an EP group inside the queried NVLink domain. On Ascend, the branch is taken only for FP8×FP4. MegaGate is GPU-only. Otherwise the explicit path is gate → DeepEP dispatch → grouped expert compute → combine, with the shared expert evaluated around the combine step. DeepEP returns an EventOverlap whose wait runs a deferred callback and keeps tensors alive (vendor/DeepEP/deep_ep/utils/event.py:1-106; .../buffers/ep.py:638-734,816-862). The C++ dispatch wrapper specializes JIT code on rank, expert, token, alignment, SM and transport properties, and launches a cooperative grid (vendor/DeepEP/csrc/kernels/ep/dispatch.hpp:1-155).
# 8. Emerging Model Innovations: Hyperconnections, Engram, Vision
# 8.1 Dynamic Hyperconnections (HC/mHC)
[S] V4 blocks keep multiple residual streams. MoeDecoderBlockHC asserts that both HC and dynamic HC are enabled. Mixing coefficients come from FP32 partial reductions and RMS normalization. Fused paths are chosen conditionally, and Engram layer boundaries affect which fusions are possible (v4_modules/hc.py:119-228,317-395; v4_modules/mhc_ops.py:20-148).
[I] In the standard hyperconnection form, with stream matrix $\mathbf{H}\in\mathbb{R}^{s\times d}$:
$$
x = \alpha(\mathbf{H})^\top \mathbf{H},\qquad \mathbf{H}' = B(\mathbf{H})\,\mathbf{H} + \beta(\mathbf{H})\, f(x)^\top
$$
"Dynamic" means $\alpha, \beta, B$ are computed from the normalized current streams. Systems impact: the residual state grows by a factor of $s$, and that state must be carried across YoCo compaction and CP gathers.
# 8.2 Engram parallelism
[S] (v4_modules/engram.py:107-219) Engram hashes n-grams from a compressed tokenizer, fetches sharded embeddings through the Engram-parallel user buffer (GPU or CPU-RDMA mode), projects them, and gate-fuses them into the hidden state at configured layers. World size can be enlarged to host Engram shards (§3.3).
tokens ─▶ compressed-tokenizer n-grams ─▶ hash ─▶ shard id ─┐
▼
Engram-parallel userbuffer (GPU | CPU-RDMA) ─▶ fetch rows ─▶ proj ─▶ gate ⊙ ─▶ hidden
[I] This turns part of the model's capacity into a distributed lookup table. Engram's cost is bound by memory and network, not compute, and it adds one more collective that every step depends on.
# 8.3 Vision-language pipeline
[S]
- The image processor converts inputs to RGB bytes and computes patch and resize metadata (
deepinfer/ve/processor/image_processor.py:1-220). - The CUDA RGB kernel takes HWC
uint8input, pads around the patch center, and works with 128 threads per patch. It disables FMA so its separate-operation order matches a CPU reference, and it rounds the center offset half-to-even for odd padding gaps (cuda/image_embed_ops.py:56-76,118-132). - The ViT uses patch size 14, width 1024, depth 32 and 16 heads, with variable-length non-causal attention over image boundaries and a SwiGLU MLP (
vision_encoder/vit.py:1-230). - Features are downsampled per batch, projected, and substituted at IMAGE-token positions (
vision_encoder/vl_aligner.py:61-93). - An NPU ViT attention fallback exists (
npu_ops/vit_attn.py:1-31). - The scheduler keeps image-pad spans intact at chunk boundaries (§3.5).
[O] Bitwise equivalence of the CPU and GPU preprocessing has not been tested, and the full path through PIL and different tokenizer versions has not been traced.
# 9. The Hardware Wall & Systems Reality Check
# 9.1 Declared kernel targets
| Component (commit) | Declared target | Evidence |
|---|---|---|
FlashMLA (2e5429f) |
CUDA_ARCHS = ["sm_100a","sm_103a"]; CUDA ≥ 13.1 (13.2 recommended); Hopper support removed; register-spill check at build |
[S] setup.py, [C] README |
DeepSelect (bfa4507) |
gencode only compute_100a/103a; the sm_80 and sm_90a lines are commented out |
[S] setup.py |
DeepGEMM (1fc9c66) |
SM90 or SM100; CUDA ≥ 12.9; kernels JIT-compiled at runtime; UE8M0 scales on SM100. Includes legacy A100-oriented Triton M-grouped GEMMs | [C] README; [S] deep_gemm/legacy/m_grouped_gemm.py:10-79 |
DeepEP (f6aa38f) |
Hopper or newer; CUDA ≥ 13.1; PyTorch ≥ 2.10; NVLink intranode + RDMA internode; zero-SM RDMA EP unsupported; needs nvidia-smi/ibstat |
[C] README |
| Top level | Python 3.12, GCC ≥ 13, CUDA 13, torch==2.13.0+cu132, nvidia-nccl-cu13==2.32.3, flash-attn-4==4.0.0b34; CANN 9.2 for Ascend |
[S] requirements-nvidia.txt, build.sh, README.md:47-56 |
Precise reading of "abandoning Hopper and Ampere." The phrase is only partly accurate. DeepGEMM still lists SM90, DeepEP still says "Hopper or newer", and DeepGEMM ships legacy A100-oriented Triton GEMMs. But the engine path as a whole depends on FlashMLA sparse attention and DeepSelect top-k, and both are built only for SM100/SM103. The executable NVIDIA requirement is therefore Blackwell-class [S]. Having older-architecture kernels in a vendored library does not make the whole engine run there [I].
# 9.2 Practical consequence
| Hardware class | Verdict (source-level) |
|---|---|
| Consumer Ampere (SM86) | Engine path cannot run: FlashMLA/DeepSelect need SM100/103. The model is also far larger than consumer VRAM (not sized here). |
| Pascal (SM61) | Below every kernel's minimum. CUDA 13 support for Pascal is not expected (toolchain fact, not verified here). |
| CPU-only nodes | Engine path impossible. CPU-reviewable logic (EPLB policy, scheduler structure, cache math) can be studied in isolation. |
| SM100/SM103 + NVLink/RDMA, or Ascend 950 | Required for any engine-level experiment. |
[O] Whether any TileLang kernel compiles for SM86 is unknown. Source inspection alone cannot settle it.
# 9.3 What the release provides versus what is missing
| Provided [S] | Missing [C: README :3-4,39-42] |
|---|---|
Offline LLM batch API |
KV cache system (persistence, sharing, offload) |
| Single model: DeepSeek-V4.1-Flash | Prefill/decode (and VE) disaggregation |
| C++ scheduler, ZOS, MTP/DFlash, YoCo, EPLB | DP-replica load balancing |
| Structured output (xgrammar) | Online serving API, auth, streaming |
| NVIDIA SM100/103 and Ascend 950 backends | Older-GPU support for the engine path |
# 9.4 Vendor claims versus operational reality
[C] The README says the engine "powers DeepSeek's large-scale production services" and publishes benchmark images. None of this is reproducible from the release: the production deployment depends on the excluded KV, disaggregation and load-balancing components, and the benchmarks would need Blackwell-class clusters. This paper reports no measured throughput, latency, speedup or memory figure, and makes no comparison with other engines.
# 10. Critical Research Roadmap & Open Systems Questions
Every item is stated as a falsifiable question with an acceptance rule. The CPU column marks work that needs no accelerator.
| # | Question | Method | CPU | Acceptance rule |
|---|---|---|---|---|
| R1 | Do the documented data contracts hold end to end (admission → scheduler output → metadata → forward/sample → output mutation → release)? | Static call/dataflow map of llm_engine.py, scheduler.hpp, worker.py, model_runner.py, sequence.hpp, metadata builders |
✓ | Every tensor/descriptor crossing the boundary has a named owner, lifetime and invariant; any gaps listed |
| R2 | How far is EPLB from optimal, and does rebalancing pay for its weight movement? | Isolate policy.py; compare with an exact assignment (ILP or brute force) on small synthetic $L$; sweep skew, drift and history length; count bytes moved separately |
✓ | Report objective gap distribution and movement cost; the hypothesis "greedy ≤ X% from optimal" is confirmed or rejected |
| R3 | Does the 1e-4 tie-breaker stay distinct at real load magnitudes and dtypes? | Determine the dtype of $L$; enumerate the magnitude at which adjacent-ID perturbations collide; test for ties | ✓ | Either no collision is shown under supported dtype/magnitude, or a reproducible collision case is documented |
| R4 | Do hand-derived cache byte formulas match the code? | Derive $B(n)$ from cache_engine.py and V4.1 fixtures; check FP4 scale overhead, ring and rollback sizing, sharing maps, alignment |
✓ | Hand calculations match dry-run layout output (with no model allocated) for all fixtures |
| R5 | Does two-vote DP consensus with a 90% watermark minimize rank idling and avoid starvation? | Deterministic event simulator built from the observed admission rules; sweep arrival skew, prompt length, watermark, rank imbalance and ALL/ANY intervals | ✓ | Simulator reproduces the source rules on unit traces; then report queue delay, idle slots and starvation versus alternative policies (as hypothesis generation only) |
| R6 | Does host validation cover every TileLang T.assume precondition? |
Cross-reference T.assume sites (e.g. load_paged_kv_cache.py:74-98, compress.py:109-118) against host checks |
✓ | Each precondition is mapped to a host check or listed as unguarded |
| R7 | Do Ascend variable-MTP caller limits bound its fixed scratch buffer? | Trace callers of asc/schedule_mtp_varlen.py:25-46,75-82 |
✓ | Proven bound, or a counterexample configuration |
| R8 | Are outputs equivalent across baseline/ZOS/MTP/YoCo/batch-invariant/EPLB settings? | Fixed inputs and seeds; compare logits/tokens on qualified hardware with owned weights; capture commit, model/tokenizer hashes, environment and resource traces | ✗ | Bitwise or tolerance-bounded equality per mode, with repeated runs and confidence intervals |
| R9 | Are MTP confidences calibrated, and does varlen improve throughput? | Acceptance by position, reliability diagrams, verifier work saved, end-to-end latency/throughput with MTP on and off | ✗ | Calibration error and speedup with CIs; the speedup claim is rejected if the CI includes 0 |
| R10 | Is ZOS overlap real, and where does it stall? | Device timelines measuring $g_F$, $h_P$ and sync costs from §4.3 | ✗ | Measured $T^{\text{ZOS}}$ vs $T^{\text{serial}}$; stall attribution adds up to within 10% of the observed gap |
| R11 | What would a full serving stack need? | Specify the KV-store persistence/retrieval contract, P/D transport, failure behavior, DP-replica admission | ✓ | Written interface spec; the offline engine is never described as a serving stack |
| R12 | Can derived artifacts be redistributed? | Record every submodule commit, recursive dependency, license and build-artifact provenance | ✓ | Complete license ledger before any binary or dataset is distributed |
These three items are open from the independent review and are not asserted as defects: R3 (EPLB perturbation), R7 (Ascend scratch bound), R6 (T.assume coverage).
# 11. Conclusion & Repository Provenance Index
# 11.1 Conclusion
DeepInfer is less a general inference engine than a co-designed runtime for one model, and it is most instructive exactly where that specialization shows:
- Byte-level cache formats. 528/288 B/token, FP32 compression rings, shared producer/consumer maps, and rejection of full-attention layers.
- A two-vote phase consensus. It keeps data-parallel ranks in lockstep without empty prefill cycles.
- A deferred pipeline. GPU-side length repair, rather than host knowledge of accepted tokens, is what lets post-processing hide under the next forward pass.
- A speculative stack. One draft forward, Markov token recurrence, and a verifier budget chosen by an online timing model fed deliberately mixed-staleness (N−2/N−1) confidence data.
- A greedy expert placer. It optimizes the history of per-step bottlenecks rather than averages.
The source establishes these mechanisms. It does not establish that they are correct at runtime, that they deliver the claimed speedups, or that they behave well under real workloads. The hardware gate (SM100/SM103 or Ascend 950) and the excluded serving components mean the vendor's production claims cannot be reproduced from this release. The highest-value next steps run on CPUs (R1–R7, R11, R12); engine-level validation (R8–R10) needs qualified accelerators, owned weights and a separately approved experiment.
# 11.2 Provenance
Revision: 9bd9cf243fc53ef9afbf8f04d391d989117d6ab9. Root license: Apache-2.0. Submodule licenses have not been reviewed.
Vendored submodules (top level):
| Submodule | Commit |
|---|---|
| DeepEP | f6aa38fe06cd4a0489e7730365d4e0114970a2f3 |
| DeepEP-Ascend | 3b25377d04b24fc6154698ded78a2bcb2c59afff |
| DeepGEMM | 1fc9c66975ee322d628b3288534ca0e9ce12a64d |
| DeepGEMM-Ascend | 3a35326271b069b8b5bf1a754435acd6cc91575b |
| DeepSelect | bfa4507d935f17ebfc3d0f00ff7d3c9a4d0e5c18 |
| FlashMLA | 2e5429fc5653bab6e081f09477126f731882a6a9 |
Uninitialized nested submodules (not traced): DeepEP deep_jit; DeepEP-Ascend clangd-ascend, deep_jit; DeepGEMM cutlass, deep_jit; DeepGEMM-Ascend clangd-ascend, deep-jit, magic_enum; DeepSelect csrc/3rdparty/cutlass; FlashMLA csrc/3rdparty/cutlass. scripts/build_vendor.sh:27-48 initializes submodules recursively, so their absence here does not mean a build would fail.
Inventory reconciliation.
- Live tree: 1,092 files excluding
.gitmetadata directories. By directory:vendor/750,deepinfer/223,csrc/33,tests/20, root 14,examples/18,eval/17,deep_cluster/8,doc/5,scripts/4. By extension:.py444,.hpp221,.cuh130,.cu109,.h47,.cpp31, and smaller groups. - Earlier archive inventory: 1,075 files plus 296 directories (1,371 entries). The archive omitted 17
.gitignore/.gitmodulesfiles. - Off-by-one: the tar listing has 1,372 members because it includes the root directory entry, which the 1,371 count does not.
- Content check: all 1,075 archived files match the live tree byte for byte.
- Coverage: semantic line coverage is selective, not exhaustive.
Cited-source index (selected):
| Subsystem | Primary files |
|---|---|
| Entry and engine | deepinfer/entrypoints/llm.py, deepinfer/engine/llm_engine.py, deepinfer/engine/profile_server.py |
| Scheduler/ABI | csrc/engine/scheduler.hpp, block_manager.hpp, mtp_varlen.hpp, flops_estimator.hpp, input_metadata/block_load_plan.cpp, prepare_sample.cpp |
| Worker | deepinfer/worker/worker.py, model_runner.py, cache_engine.py, cuda_graph_runner.py, dflash_cuda_graph_runner.py |
| Model | models/v4_modules/{attn,index_attn,compress,moe,mlp,hc,mhc_ops,engram,yoco}.py, models/mtp/dflash.py, vision_encoder/{vit,vl_aligner}.py |
| Kernels (TileLang) | tilelang_ops/{cache_common,load_paged_kv_cache}.py, cuda/{compress,state_cache,compute_seqlens_k_zos,dflash,get_kv_index,fused_sample,random_sampling,structure_output,fused_transform,image_embed_ops,schedule_mtp_varlen}.py, asc/{fused_transform,rstd_1ulp,schedule_mtp_varlen}.py |
| EPLB | deepinfer/model_executor/eplb/{policy,shuffle}.py, tests/models/test_eplb_policy.py (not run) |
| Sampling/grammar | layers/sampler.py, sampler_utils.py, deepinfer/structure_output/ |
| Platform/build | deepinfer/platform.py, npu_ops/{patch_imports,vit_attn,deep_select}.py, setup.py, build.sh, scripts/build.sh, pyproject.toml, requirements.txt |
| Vendor (read, not reproduced) | vendor/FlashMLA/csrc/api/sparse_{decode,prefill}.cpp, .../sm100/decode/sparse/head64/kernel.cuh, vendor/DeepEP/{deep_ep/utils/event.py,deep_ep/buffers/ep.py,csrc/kernels/ep/dispatch.hpp}, vendor/DeepGEMM/deep_gemm/legacy/, vendor/DeepSelect/deep_select/interface.py |
Methodology note. The analysis is static only. A separate model independently re-reviewed the source and found corrections and additions. These were checked against the cited source before being included; the reviewer's unresolved suggestions appear as R3, R6 and R7.