Skip to content

DeepSeek V4.1-Flash ​

Serve DeepSeek V4.1-Flash with TokenSpeed, then tune the MoE, speculative decoding, and Engram table configuration for your deployment.

Prerequisites ​

  • Install a TokenSpeed build with DeepSeek V4.1 (deepseek_v41) support and get access to the deepseek-ai/DeepSeek-V4.1-Flash checkpoint.
  • Provide eight GPUs for the baseline --tensor-parallel-size 8 command, or adjust the parallel layout for your hardware.
  • To reproduce the validated CI configuration, use deepseek-ai/DeepSeek-V4.1-Flash-1017. The B200 and AMD GSM8K CI jobs, the GB300 Slurm 1P1D GSM8K job, and the manual 1P1D smoke test use this checkpoint. The 1P1D CI tasks set MODEL explicitly so both serving roles and the evaluation client select the same checkpoint.

Start the server ​

  1. Start TokenSpeed with eight-way tensor parallelism and expert parallelism. This configuration sets a 32768-token context, a 262144-token total cache budget, and a 32-sequence limit. It serves the model as deepseek-v41-flash on port 8000. To reproduce CI, replace deepseek-ai/DeepSeek-V4.1-Flash with deepseek-ai/DeepSeek-V4.1-Flash-1017:

    bash
    tokenspeed serve deepseek-ai/DeepSeek-V4.1-Flash \
      --served-model-name deepseek-v41-flash \
      --trust-remote-code \
      --tensor-parallel-size 8 \
      --enable-expert-parallel \
      --dtype bfloat16 \
      --max-model-len 32768 \
      --max-total-tokens 262144 \
      --max-num-seqs 32 \
      --chunked-prefill-size 8192 \
      --max-cudagraph-capture-size 32 \
      --disable-kvstore \
      --host 0.0.0.0 \
      --port 8000
  2. From a host that can reach the server, query the readiness endpoint. If you run curl from another host or changed --port, replace 127.0.0.1:8000 with the server's address:

    bash
    curl --fail --silent --show-error http://127.0.0.1:8000/readiness

    When the server is ready, the endpoint returns a successful HTTP status and curl exits with status 0. Use deepseek-v41-flash as the model name in inference requests.

Control masked token IDs ​

The target LM head masks BOS, PAD, and the image control/placeholder token IDs 0, 2, 129262..129264 to -inf. The mask applies before ordinary sampling, fused argmax, and speculative verification, and to target-side logprob scoring; draft-model proposals are unchanged. Pass --disable-deepseek-v41-token-blacklist to allow these tokens.

Understand FlatKV attention and prefix replay ​

DeepSeek V4.1 (deepseek_v41) runs on its own FlatKV attention backend with a four-group KV cache: the global KV chains, the SWA rows, and the compressor tails. The recipe declares the last two replayable: they never enter the prefix cache, and a prefix hit re-feeds the cached prefix's last 128 tokens so the model regenerates them into the request's own pages (SWA bounded replay). For more information, see scheduler bounded replay.

The backend masks the global KV and index rows those replayed tokens recompute, so the shared rows stay exactly what the first computation produced. The CED decoder (layers 20–39) keeps up to the last 128 positions of a completing prompt and at most one row from an unfinished chunk. The encoder and decoder use separate prefill graphs around the eager narrowing step. --prefill-graph-capture-token-sizes sets encoder buckets in input tokens. All encoder sizes share one set of decoder buckets. The default ladder doubles up to the 128-row window and then grows in steps of 128 or more. Its last bucket is the smaller of the encoder ceiling and the decoder's row capacity. Use --prefill-graph-decoder-capture-token-sizes to set exact retained-row capacities. --disable-prefill-graph disables both prefill graphs. For more information, see prefill graphs around a row narrowing.

Tune Hopper MXFP4 MoE kernels ​

On Hopper, the routed MXFP4 experts run on FlashInfer's CUTLASS mixed-input grouped GEMM (flashinfer_cutlass_mxfp4_w4a16_moe_apply), which auto selects over Marlin. Marlin dequantizes in registers and scales linearly with the token count. The CUTLASS kernel stays weight-bandwidth bound.

The following measurements cover one MoE layer on one EP8 rank of an H20 with CUDA Graph replay. All times are in microseconds:

Tokens per MoE callCUTLASS W4A16Marlin W4A16CUTLASS W4A8
96502656282
1926211552338
5766712855380
8192-token prefill chunk451779992195

The measurements have the following operational consequences:

  • Autotuning and cache reuse: Startup runs FlashInfer's tactic autotuner inside the kernel tuning window (about five minutes for this kernel on H20), including each distinct draft expert geometry. Decode-capable roles also traverse the shared speculative path once to discover the draft model's other operators. Prefill-only roles skip that traversal because they do not allocate decode/verify scratch. --disable-autotune loads a matching persistent cache and uses heuristic tactics for uncovered shapes, which is fine for bring-up. Pipeline-parallel launches skip tuning but can reuse a cache from a full-model run with the same engine role, tensor/expert parallel layout, and environment. Independent prefill and decode roles keep separate caches. The tuner creates cache directories on the first successful save.
  • Optional FP8 activations: --moe-mxfp4-fp8-activation switches to the W4A8 variant with FP8 activations and Humming residual scales. The measurements in the preceding table show another 1.8x speedup, at a few percent of relative error on the expert outputs from FP8 activation rounding. Treat this option as opt-in and confirm the served model on GSM8K or a similar check before relying on it.

--moe-backend marlin keeps the previous kernel and stays required for DeepEP all-to-all layouts and for Kimi-K3's SiTU experts, which the CUTLASS epilogue does not implement.

Optional: Enable same-checkpoint DSpark decoding ​

Add --speculative-algorithm DSPARK to the server command for same-checkpoint DSpark decoding. The draft seeds its context windows from the decoder's kept rows, and each draft stage attends its 128-row window plus the non-causal proposal block through the same selected_attention workspace kernel as the target's prefill (FlashMLA on sm90+, Triton elsewhere). The FP32 arithmetic remains the CPU reference.

A prefix cache hit re-feeds the groups' whole retention window, which is exactly the 128-token attention window (the compressor-tail group retains its unfinished pair the same way). The scheduler requires --chunked-prefill-size of at least that window plus one prefix page and never leaves a prompt's final chunk shorter than it. The replayed rows attend SWA keys from the replay start only, the truncation the model is trained for. The runtime never recomputes the cached global KV from them. usage.prompt_tokens_details.cached_tokens reports the hit through the end of the replayed window, so it stays a multiple of the prefix granularity.

Under prefill/decode disaggregation, the prefill node replays on its own prefix hits exactly as described in the preceding paragraphs and ships each group's retained tail. The decode node lands the tail and never re-feeds. Even on one machine, let Mooncake pick an RDMA transport rather than forcing the intra-node NVLink one.

Base logits and greedy block sampling ​

Same-checkpoint DSpark computes its public FP32 base logits straight from the target's BF16 LM-head shard: BF16 products are exact in FP32, so a BF16 GEMM with an FP32 accumulator reproduces the reference's FP32 head math up to summation order without an FP32 copy of the shard. The draft path reads the head in place under CUDA Graph replay, so in-place target weight updates need no refresh.

The greedy block sampler runs one Triton kernel per block step on each tensor-parallel rank: it gathers the previous token's BF16 Markov bigram row from a replicated table, adds the bigram bias (a BF16 tensor-core dot against the rank's Markov projection shard, sharded like the LM head) to the rank's base logits, and packs the best (logit, token) of every vocabulary tile into one int64 candidate. One all-gather per step shares the candidates. The next step's kernel (or the final resolve) reduces them to the torch.argmax winner over the whole vocabulary, with ties broken toward the lowest token ID. A five-token block is therefore six kernels and five all-gathers instead of a per-step chain of masked embedding lookups, GEMMs, reductions, and two all-gathers.

Draft numerical kernels ​

The CUDA draft path also preserves the checkpoint's UE8M0-scaled FP8 activation round-trip with a fused tokenspeed-kernel operation. It computes the same per-group power-of-two scale and returns dequantized values in the input dtype. The fusion removes intermediate reduction and elementwise launches but does not change the model's quantization contract.

DSpark attention RMSNorm uses the platform kernel on CUDA while retaining its explicit FP32-accumulating PyTorch expression as the CPU reference. The fused path preserves the existing output dtype and is safe to capture and replay in the target CUDA Graph.

Optional: Share Engram tables across instances ​

V4.1 instances in one NVLink domain can share the two immutable Engram tables through CUDA FABRIC handles. All workers need access to the same IMEX channel. This placement requires PP1 and resident weights throughout the group's lifetime.

To share the tables, follow these steps:

  1. Start every instance with the same checkpoint, revision, Engram table layout, --engram-group-size (the total number of participating GPUs), and --engram-group-store (a fresh directory on a file system they all see). For example, two separately launched two-GPU instances both take --engram-group-size 4 --engram-group-store /shared/run-42/engram. Replace /shared/run-42/engram with a fresh directory on your shared file system.
  2. Choose a table placement for every instance. By default, the rows occupy HBM. Add --engram-host-table on every instance to place each slice in its GPU's host NUMA memory. Both placements use the same packed-row lookup as a shared host table and read the rank's local query IDs directly.

The workers split the table into whole rows at CUDA allocation boundaries. Each GPU maps one contiguous view of all rows and loads only its own range from the checkpoint. A small table can have owners with empty ranges.

The store exchanges raw CUDA FABRIC handles at startup. Exporters keep their allocations alive through a single model-wide wait for all mappings and checkpoint writes. Each instance then reads the rows it needs independently. Restart the whole group with a fresh store to replace a worker or reload weights.

Prepare and commit Engram history ​

Before each forward, one pinned upload carries every request's Engram history snapshot. prepare_ngram_inputs resolves the previous-three tokens and validity mask, clears padding, and computes table rows for all Engram layers in one launch. The model consumes these prepared hashes through stable input buffers. Preparation leaves accepted request state unchanged; after sampling, commit_ngram_inputs advances accepted history and cache lengths together in a second launch. Hashes are bit-identical to the eager reference, which remains the CPU path. Per-batch token and request counts stay runtime kernel arguments; only bounded tile sizes and fixed model/pool geometry specialize compilation. Both kernels are checked against the default per-thread stack budget, so first use does not reserve extra spill memory on every SM. Retraction snapshots carry the accepted frontier; the first restored decode reseeds Engram history from its token snapshot and commits it only after verification.

Run the GB300 Slurm 1P1D CI ​

The GB300 Slurm 1P1D EvalScope configuration runs one TP4 prefill engine and one TP4 decode engine on two four-GPU nodes. Node 0 also hosts the SMG gateway and the Slurm evaluation client, which connects to 127.0.0.1:8000. Both engines use same-checkpoint DSpark, mega_moe with expert parallelism on Blackwell, host-resident Engram tables, and Mooncake transfer after the completed prompt (layerwise-interval=0). The YAML disables decode prefix caching. The gateway uses deepseek_v31 reasoning parsing. The 262144-token cache budget limits admission independently of the 32768-token per-request context and 16-sequence cap.

The gate checks GSM8K accuracy of at least 0.90 on 100 samples with EvalScope 1.11.1, greedy decoding, concurrency 8, and up to 30000 generated tokens. It participates in the GB300 Slurm per-commit workflow. To run only this case, follow these steps:

  1. In Slurm Dispatch, select the GB300 Slurm 1P1D EvalScope YAML.
  2. Choose cluster gb300.
  3. Optional: Provide a pull request number.

The launcher uses PD_SLURM=1 to assign one role per node and clears Slurm topology discovery only inside each worker process. Node 0 starts the gateway with the prefill worker on a same-host socket and the decode worker on tcp://<node 0>:DECODE_HANDSHAKE_PORT (18348), then publishes its address in the launcher's job-and-step-scoped artifact directory, which both nodes share; node 1's decode engine dials it there. The gateway is ready after both engines register. Worker logs remain separate as prefill.log, decode.log, and lb.log.

When you need an explicit RDMA device selection, set DISAGGREGATION_IB_DEVICE. The GB300 task selects mlx5_0,mlx5_1,mlx5_2,mlx5_3 to keep transfers on the InfiniBand fabric. Automatic discovery also includes Ethernet RNICs, which can cause incompatible RoCE/InfiniBand endpoint pairings during the RDMA handshake. Without PD_SLURM=1, the same launcher retains the single-node smoke topology.

TokenSpeed documentation