面向 DeepSeek V4 系列模型的大规模高性能推理框架。源码级深度剖析:技术架构、核心组件、业务流、解决的问题场景,附三个工业级案例与可执行代码。
想象一家超大型餐厅接了 1000 桌宴席(1000 个推理请求),每桌菜不一样(prompt 不同),但厨房只有 8 口大锅(8 张 GPU)。DeepInfer 就是这个餐厅的总调度系统:
它不是一口锅,而是一套调度+烹饪+上菜的完整流水线——决定哪桌菜先进锅(Scheduler)、锅里的菜怎么排布不串味(KV Cache BlockManager)、8 口锅怎么分工(Expert Parallel)、怎么提前备菜让出菜更快(DFlash 投机采样)、以及怎么根据每桌菜的口味动态调整厨师分配(EPLB 负载均衡)。
| 关键词 | 含义 | 解决的问题 |
|---|---|---|
| MLA Attention | Multi-head Latent Attention,低秩压缩 KV cache | 长上下文场景下 KV cache 显存爆炸:把每 token 的 KV 从 num_heads × head_dim 压缩到 kv_lora_rank + rope_dim,显存降 10×+ |
| EPLB | Expert Parallel Load Balancing,MoE 专家负载均衡 | MoE 模型中某些专家被频繁调用(热点),导致部分 GPU 过载而其他空闲:动态给热点专家分配冗余副本并重排到各 GPU |
| DFlash MTP | Multi-Token Prediction 投机采样,用小模型预测多个 token | 自回归解码每步只出 1 个 token,访存瓶颈严重:让小模型一次猜 N 个 token,主模型批量验证,接受率越高吞吐越高 |
| 框架 | 定位 | 与 DeepInfer 关系 |
|---|---|---|
| vLLM | 通用 LLM 推理框架 | DeepInfer 衍生自 vLLM,保留了 PagedAttention/连续批处理,重写了模型层和调度器 |
| SGLang | 高性能推理+结构化输出 | 竞品,DeepInfer 的结构化输出用 xgrammar 实现,SGLang 用自有方案 |
| TensorRT-LLM | NVIDIA 官方推理引擎 | 竞品,DeepInfer 跨平台支持昇腾 NPU,TRT-LLM 仅 NVIDIA |
| DeepInfer | DeepSeek 模型专用推理框架 | 针对 DeepSeek V4 的 MLA/MoE/mHC/DFlash 做了深度定制优化 |
每个 Python 文件头部都标注 # SPDX-License-Identifier: Apache-2.0 和 # Derived from vLLM; modified by DeepSeek.。C++ 调度器 csrc/engine/scheduler.hpp 是完全自研的,不来自 vLLM。
DeepSeek V4 系列模型有三个让通用推理框架头疼的架构特性,DeepInfer 逐一给出了系统级解决方案:
| 问题 | 根因 | DeepInfer 方案 | 源码位置 |
|---|---|---|---|
| 长上下文显存爆炸 | 标准 Attention 的 KV cache = seq_len × num_heads × head_dim × 2 bytes,128K 上下文 × 128 heads × 128 dim = 4GB/请求 | MLA 低秩压缩:KV 先投影到 kv_lora_rank(如 512),再按需上投影。显存降至 ~0.4GB/请求 | v4_modules/mla_attn.pyv4_modules/compress.py |
| MoE 专家负载不均 | 256 个 routed expert 中,少数专家被高频路由(热点),EP 并行下某些 GPU 过载,其他空闲 | EPLB 全局重均衡:统计历史负载 → 贪心分配冗余副本 → 贪心排布到各 rank,目标 min Σ max(load) | eplb/policy.pyrebalance_experts_global() |
| 自回归解码访存瓶颈 | 每步 decode 只产 1 token,但需加载全部模型权重,算术强度极低,GPU 利用率差 | DFlash MTP 投机采样:小模型一次预测 N 个 draft token,主模型批量验证,接受率 70%+ 时吞吐 ~1.7× | models/mtp/dflash.pylayers/sampler.py |
| 超长 prefill 计算量爆炸 | 128K prompt 的 prefill 注意力是 O(n²),计算量和延迟都不可接受 | YoCo 截断 + 稀疏注意力:consumer 层只看局部窗口,MQA 索引器选 top-k block,prefill 从 O(n²) 降到 O(n×k) | v4_modules/yoco.pyv4_modules/index_attn.py |
| 多 GPU 通信开销 | EP 并行下 all-to-all dispatch/combine 通信量大,成为瓶颈 | deep_ep 库 + 用户缓冲区(userbuffer) + NUMA 绑定 + overlap 通信计算 | parallel_utils/parallel_state.pydeep_cluster/topology/bind.py |
| 调度与计算串行 | 传统推理框架先调度再计算,调度 CPU 操作和 GPU 计算不重叠 | ZOS (Zero-Overhead Scheduling):调度结果异步准备,post-process 延迟到下一步 forward 期间执行 | worker/zos_status.pyworker/worker.py |
DeepInfer 不是"又一个推理框架",而是针对 DeepSeek V4 模型架构特性的深度定制推理引擎。它的每个核心组件都对应 V4 模型的一个具体痛点:MLA↔KV压缩、EPLB↔MoE不均、DFlash↔解码瓶颈、YoCo↔长prefill、ZOS↔调度开销。这种"模型-引擎协同设计"是它与 vLLM/SGLang 的根本区别。
DeepInfer 采用 Python 编排 + C++ 高性能调度 的双层架构。Python 层负责模型定义、权重加载、采样逻辑;C++ 层负责请求调度、KV cache 块管理、序列状态机——这些是延迟敏感且需要精细内存管理的组件。
引擎编排核心,管理 Scheduler、Worker 池、BlockManager 的生命周期。接收用户请求,驱动每步 schedule→execute→output 循环。
关键设计:DeferredRelease 延后一轮释放资源,保证调用方读完输出张量后再回收,与 GPU 计算 overlap。
完全自研的 C++ 调度器。连续批处理、抢占式调度、chunked prefill、ZOS 零开销调度。
关键逻辑:每步检查 BlockManager 空闲块 → 分配/抢占 → 切分 prefill → 生成 SchedulerOutputs → 估算 FLOPs/MFU
Paged KV cache 块管理器。双向链表维护空闲块池,引用计数支持 prefix sharing,pin/unpin 支持状态缓存。
关键数据结构:Blocks 双向链表 + ref_count 引用计数 + clone/pin 状态机
GPU 执行器,每步运行 forward→post_process→sample 循环。ZOS 模式下 post-process 延迟到下一步 overlap。
关键设计:WorkerStepState 保存跨步状态,MetadataZOS 管理 GPU 元数据和 pinned CPU remap
模型执行器,管理模型加载、输入张量准备、CUDA Graph 捕获/重放。支持 DFlash 独立 CUDA Graph。
关键设计:CudaGraphRunner 按批次大小捕获多个 graph,消除 CPU launch 开销
KV cache 引擎,管理 V41 格式和 FP4 量化格式的 KV 存储。支持 state cache(跨请求持久化)和 SWA(滑动窗口注意力)。
关键计算:_kv_bytes_per_token() 根据 kv_lora_rank + rope_head_dim + 量化方式精确计算每 token 字节数
DeepSeek V4 模型实现。组装 embed_tokens + N 层 DeepseekDecoderLayer + lm_head,集成 DFlash MTP 模块。
关键设计:SharedLayerTopology 在构造时确定跨层 KV 共享拓扑,CrossLayerRuntime 在每次 forward 时传递共享值
MLA 注意力运行时:Q/KV 低秩投影、KV 存储、prefill/decode、稀疏索引、YoCo consumer 跳过。
关键组件:Compressor(压缩KV) + KProject(索引K) + MQA(稀疏topk) + SWA(滑动窗口)
MoE 运行时:TopKGate 路由 + deep_ep dispatch/combine + FP8/FP4 expert GEMM + EPLB 感知路由。
关键依赖:deep_ep(EP通信) + deep_gemm(FP8 GEMM) + tile_kernels(量化/反量化)
Multi-Token Prediction 投机采样模块。用小模型预测 draft tokens,主模型批量验证,ConfidenceHead 预测接受率。
关键设计:MarkovGPTHead 一阶马尔可夫修正 logits + AcceptRatePredictor 动态调整投机步数
专家负载均衡策略。rebalance_experts_global() 三步:分配冗余副本 → 贪心排布 → 生成 physical_to_logical_map。
关键算法:_batch_greedy_indices() 逐 expert 贪心放到当前最优 rank,目标 min Σ_step max_rank(load)
采样层:logits 计算 → temperature/top-k/top-p/min-p → 采样 → MTP 验证 → 结构化输出掩码。
关键设计:MTP 验证用 speculative decoding 接受/拒绝规则,拒绝点用残差概率重采样
DeepInfer 支持四种并行维度,通过 ParallelProcessGroup 统一管理:
| 并行类型 | 缩写 | 含义 | 通信库 |
|---|---|---|---|
| Data Parallel | DP | 数据并行,各 GPU 独立处理不同请求 | Gloo (CPU) / NCCL (GPU) |
| Expert Parallel | EP | 专家并行,256 个 expert 分布到各 GPU | deep_ep (自研 all-to-all) |
| Context Parallel | CP | 上下文并行,长序列切分到各 GPU 并行计算 | NCCL + SHM broadcast |
| Engram Parallel | ENP | n-gram 表并行,Engram 嵌入分片到各 GPU | torch.distributed |
parallel_state.py 中 create_process_groups() 接收 dp_size, ep_size, cp_size, enp_size 四个参数,创建对应的 ProcessGroup。CP 组内用共享内存 MessageQueue 广播小张量(如调度元数据),避免 NCCL 开销。
DeepInfer 通过 Platform 抽象层支持 NVIDIA GPU 和华为昇腾 NPU:
| 特性 | NVIDIA GPU | 华为昇腾 NPU |
|---|---|---|
| Tilelang 后端 | csrc/ CUDA kernel | asc/ 昇腾 kernel |
| 分布式后端 | NCCL | HCCL |
| FP8 scale 类型 | int32 (4 per group) | int16 (2 per group) |
| 注意力库 | flash-attn-4 | flash_mla (昇腾版) |
| NUMA 绑定 | 统一通过 deep_cluster/topology/bind.py | |
标准 Attention 像是每个厨师(head)都要把整本菜谱(KV)抄一份放自己案板上——100 个厨师就抄 100 份,菜谱越长案板越满(显存爆炸)。
MLA 的做法像是:先把菜谱压缩成一份摘要(kv_lora_rank),每个厨师案板上只放摘要。做菜时再从摘要还原出自己需要的那几页。摘要只有原来的 1/10,案板瞬间空了 90%。
标准 Multi-Head Attention 的 Q/K/V 投影:
# 标准 Attention: 每个头独立投影
Q = x @ W_q # [batch, seq, num_heads * head_dim]
K = x @ W_k # [batch, seq, num_heads * head_dim]
V = x @ W_v # [batch, seq, num_heads * head_dim]
# KV cache 大小 = seq_len * num_heads * head_dim * 2 bytes
# 128K ctx * 128 heads * 128 dim * 2B = 4,294,967,296 bytes ≈ 4GB / 请求
MLA 的低秩压缩投影:
# MLA Attention: 先压缩到低秩,再按需上投影
# 1. Q 低秩投影
q_lora = x @ W_dq # [batch, seq, q_lora_rank] 如 512
q_heads = RMSNorm(q_lora) @ W_uq # 按需展开到 num_heads * head_dim
# 2. KV 压缩投影 (关键!只存压缩后的)
kv_lora = x @ W_dkv # [batch, seq, kv_lora_rank] 如 512
# 只存 kv_lora,不存展开后的 K/V!
# 3. 计算时按需上投影
k_full = RMSNorm(kv_lora) @ W_uk # [batch, seq, num_heads * head_dim]
v_full = kv_lora @ W_uv # [batch, seq, num_heads * head_dim]
# KV cache 只存 kv_lora: seq_len * kv_lora_rank * 2 bytes
# 128K * 512 * 2B = 134,217,728 bytes ≈ 128MB / 请求
# 压缩比: 4GB / 128MB = 32x!
MLA 还集成了稀疏注意力机制,避免对超长上下文做全量 attention:
# v4_modules/index_attn.py 核心逻辑
class MQAIndexer:
"""Multi-Query Attention 稀疏索引器"""
def select_blocks(self, q, k_compressed, w):
# 1. 用压缩 K 计算粗粒度 block 级注意力分数
scores = relu(q @ k_compressed.T) * w # [num_blocks]
# 2. 选 top-k 个最相关 block
topk_indices = scores.topk(k=self.num_selected_blocks)
# 3. 只对选中的 block 做精细 attention
return topk_indices
# 效果: 128K 上下文只需对 ~2K tokens 做精细 attention
# 计算量从 O(n^2) 降到 O(n * k), k << n
DeepSeek V4 的 YoCo 架构将层分为 producer(生成完整 KV)和 consumer(只看局部窗口):
# v4_modules/yoco.py 核心逻辑
class YoCoAttention:
def forward(self, q, kv, layer_idx):
if self.is_consumer(layer_idx):
# consumer 层: 只看最近 window_size 个 token 的 KV
# 跳过全量 KV 重算,直接用滑动窗口
return self.swa_attention(q, kv[-self.window_size:])
else:
# producer 层: 正常 MLA attention
return self.mla_attention(q, kv)
# 效果: consumer 层的 prefill 从 O(n^2) 降到 O(n * window_size)
# 对于 128K 上下文, window=4096, 计算量降低 32x
V4 架构中某些层的 KV 可以被后续层复用,避免重复计算:
# v4_modules/cross_layer.py 核心逻辑
class CrossLayerRuntime:
"""跨层 KV 共享运行时"""
def __init__(self, topology):
self.topology = topology # SharedLayerTopology
self.shared_kv = {} # layer_idx -> shared KV tensor
def get_kv(self, layer_idx):
"""获取 KV: 如果本层是 consumer, 返回 producer 的 KV"""
producer = self.topology.get_producer(layer_idx)
if producer is not None:
return self.shared_kv[producer] # 直接复用
return None # 需要自己计算
def set_kv(self, layer_idx, kv):
"""存储 KV: 如果本层是 producer, 供 consumer 复用"""
if self.topology.is_producer(layer_idx):
self.shared_kv[layer_idx] = kv
MLA 的四重优化:① 低秩压缩(KV 显存降 32×)→ ② 稀疏索引(attention 计算降 32×)→ ③ YoCo consumer 跳过(prefill 降 32×)→ ④ 跨层共享(省去重复 KV 计算)。四者叠加,使 128K 上下文推理从"不可能"变成"可行"。
MoE 像是大餐厅有 256 个专精厨师(expert),每桌菜只请 8 个厨师做(top-8 routing)。问题是:川菜厨师天天被叫,粤菜厨师闲得发慌——8 口锅(GPU)有的过载有的空闲。
EPLB 就是餐厅经理的动态排班表:统计历史订单 → 给川菜厨师配 3 个分身(冗余副本)→ 把分身分到不同锅上 → 每口锅的总工作量基本一样。
# v4_modules/mlp.py DeepseekMoE 核心流程
class DeepseekMoE:
def forward(self, hidden_states):
# 1. TopK Gate: 为每个 token 选 top-k 个 expert
router_logits = self.gate(hidden_states) # [batch*seq, num_experts]
topk_weights, topk_indices = softmax_topk(
router_logits, k=self.top_k,
n_routed_experts=self.n_routed_experts
)
# 2. EPLB 重映射: logical expert → physical expert
# 如果 EPLB 启用, topk_indices 会被重映射到 physical expert
# 一个 logical expert 可能对应多个 physical copy
if self.eplb_enabled:
topk_indices = self.eplb_remap(topk_indices)
# 3. EP dispatch: 把 token 发到对应 expert 所在的 GPU
# deep_ep 的 userbuffer all-to-all
dispatched = self.ep_dispatch(hidden_states, topk_indices)
# 4. Expert GEMM: 每个 expert 做自己的 FFN
# FP8 量化: x_fp8 = quantize(x), y = dequantize(x_fp8 @ w_fp8)
expert_output = self.expert_gemm(dispatched) # deep_gemm FP8
# 5. EP combine: 把结果发回原 GPU
combined = self.ep_combine(expert_output, topk_indices)
# 6. 加权合并
output = combined * topk_weights.unsqueeze(-1)
return output.sum(dim=-2) # 对 top-k 维度求和
# eplb/policy.py 核心算法 (源码精简)
def rebalance_experts_global(
expert_load_history, # [num_steps, num_logical_experts] 历史负载
num_logical_experts, # 如 256
num_physical_experts, # 如 288 (含冗余)
num_ranks, # GPU 数量, 如 8
):
"""三步全局重均衡"""
# Step 1: 分配冗余副本
# 统计每个 logical expert 的平均负载
avg_load = expert_load_history.mean(dim=0) # [256]
# 贪心: 给负载最高的 expert 分配冗余副本
num_copies = assign_redundant_copies(
avg_load, num_physical_experts - num_logical_experts
)
# 例: expert_0 负载最高 → 分 2 个副本 → 总共 3 个 physical
# Step 2: 贪心排布 physical expert 到各 rank
# 目标: min Σ_step max_rank(load_on_rank)
physical_to_rank = _batch_greedy_indices(
expanded_load, # 含冗余的负载列表
num_ranks
)
# 每次把当前最重的 expert 放到当前最轻的 rank
# Step 3: 生成映射表
physical_to_logical_map = build_mapping(
num_copies, physical_to_rank, num_logical_experts
)
return physical_to_logical_map, physical_to_rank
def _batch_greedy_indices(load, num_ranks):
"""贪心: 每次把最重的 expert 放到最轻的 rank"""
rank_load = torch.zeros(num_ranks)
assignment = torch.zeros(len(load), dtype=torch.long)
for i in load.argsort(descending=True): # 从重到轻
lightest_rank = rank_load.argmin() # 当前最轻的 rank
assignment[i] = lightest_rank
rank_load[lightest_rank] += load[i]
return assignment
EPLB 不是每步都重均衡的。源码中 rebalance_experts_global() 在 warmup 阶段调用一次,之后每隔 N 步根据累积负载统计重新调用。重均衡后 physical_to_logical_map 会被广播到所有 rank,MoE 路由时用这个映射表重定向 token。
自回归解码像是一个字一个字地写文章——每写一个字都要翻一遍字典(加载模型权重),写得慢不是因为手慢(GPU 计算),而是翻字典太慢(访存瓶颈)。
DFlash 的做法像是先让徒弟猜接下来 4 个字(小模型快速预测),然后师傅一次性检查这 4 个字对不对(主模型批量验证)。如果对了 3 个,等于一次翻字典写了 4 个字——效率提升近 4 倍。
# models/mtp/dflash.py 核心流程 (源码精简)
class DFlashMTP:
"""Multi-Token Prediction 投机采样"""
def __init__(self, draft_model, main_model, num_speculative_tokens=4):
self.draft_model = draft_model # 小模型 (参数量 ~1/10)
self.main_model = main_model # 主模型
self.num_spec = num_speculative_tokens
self.confidence_head = AcceptRatePredictor() # 接受率预测
def generate_step(self, context_tokens):
# Step 1: Draft - 小模型快速预测 N 个 token
draft_logits = self.draft_model.forward(context_tokens)
draft_tokens = []
for i in range(self.num_spec):
token = sample(draft_logits)
draft_tokens.append(token)
draft_logits = self.draft_model.forward_step(token)
# Step 2: Verify - 主模型批量验证
verify_tokens = context_tokens + draft_tokens
main_logits = self.main_model.forward(verify_tokens) # 一次 forward 验证全部
# Step 3: Accept/Reject - 逐 token 比对
accepted = []
for i, (dt, ml) in enumerate(zip(draft_tokens, main_logits)):
main_token = sample(ml)
if dt == main_token:
accepted.append(dt) # 接受
else:
accepted.append(main_token) # 拒绝,用主模型结果
break # 后续 draft 全部丢弃
# Step 4: 动态调整投机步数
accept_rate = len(accepted) / self.num_spec
predicted_rate = self.confidence_head(draft_logits)
self.num_spec = adjust_spec_steps(predicted_rate)
return accepted # 可能一次返回 1~N+1 个 token
小模型的 logits 不够准确,DFlash 用一阶马尔可夫模型做修正:
# dflash.py MarkovGPTHead
class MarkovGPTHead:
"""一阶马尔可夫修正: P(token | prev_token) 叠加到 draft logits"""
def __init__(self, vocab_size):
# 预计算的转移概率表 [vocab_size, vocab_size]
self.transition = nn.Parameter(torch.zeros(vocab_size, vocab_size))
def forward(self, draft_logits, prev_token):
# draft_logits: [batch, vocab] 小模型预测
# transition[prev_token]: [vocab] 马尔可夫转移概率
corrected = draft_logits + self.transition[prev_token]
return corrected
| accept_rate | num_spec | 每步平均输出 | 等效吞吐提升 | 额外开销 |
|---|---|---|---|---|
| 90% | 4 | 1 + 0.9×4 = 4.6 tokens | ~4.6× | ~20% (小模型 forward) |
| 70% | 4 | 1 + 0.7×4 = 3.8 tokens | ~3.8× | ~20% |
| 50% | 2 | 1 + 0.5×2 = 2.0 tokens | ~2.0× | ~10% |
| 30% | 1 | 1 + 0.3×1 = 1.3 tokens | ~1.3× | ~5% |
DFlash 的 AcceptRatePredictor 会根据上下文动态调整 num_spec:在"容易预测"的上下文(如代码补全、重复模式)增大投机步数,在"难以预测"的上下文(如创意写作)减小。这种自适应投机比固定步数的 speculative decoding 更高效。
用户调用 llm.generate(prompts, sampling_params),引擎将 prompt 通过 tokenizer 编码为 token_ids,创建 Sequence 对象(含逻辑 token 列表、采样参数、block_table 初始为空),加入 Scheduler 的 waiting 队列。
C++ 调度器每步执行:① 检查 BlockManager 空闲块数量 → ② 从 waiting 队列取请求,尝试分配 KV cache blocks → ③ 若块不足,抢占 running 中优先级最低的请求(释放其 blocks 回到 waiting)→ ④ Chunked prefill:长 prompt 切分为多个 chunk 分步处理 → ⑤ 生成 SchedulerOutputs(含 scheduled_seqs、prompt_run 标志、seqlens_q、clone_states)→ ⑥ 估算本轮 FLOPs 和 MFU。
根据 SchedulerOutputs 准备 GPU 输入张量:① 收集所有 scheduled seq 的 token_ids → ② 查 embedding 表 → ③ 准备 position_ids、block_table(KV cache 块映射)→ ④ 准备 attention metadata(prefill/decode 分离、seqlens_q/seqlens_k)→ ⑤ 若 CUDA Graph 启用,匹配最接近的 graph batch size。
模型前向传播:① embed_tokens → ② 逐层执行 DeepseekDecoderLayer:RMSNorm → MLA Attention(压缩 KV + 稀疏索引 + YoCo consumer 跳过 + 跨层共享)→ MoE(TopK Gate → EP dispatch → expert GEMM → EP combine)→ 残差连接 → ③ 最后一层 norm → lm_head → logits。若 DFlash 启用,额外运行 draft model 生成 draft tokens。
采样层:① logits → temperature scaling → top-k/top-p/min-p 过滤 → ② 采样(greedy/random)→ ③ 若 MTP 启用,验证 draft tokens:逐 token 比对主模型 logits 和 draft logits,接受/拒绝 → ④ 若结构化输出启用,用 xgrammar 施加语法约束掩码 → ⑤ 生成采样结果(token_id + logprob + finish_reason)。
后处理:① 将新 token 追加到 Sequence → ② 检查 stop token / max_tokens → ③ 若完成,释放 KV cache blocks(或存入 state cache 供复用)→ ④ 生成 RequestOutput(含完整文本、token logprobs、finish_reason)→ ⑤ ZOS 模式下,post_process 延迟到下一步 forward 期间异步执行,与 GPU 计算 overlap。
ZOS 是 DeepInfer 独有的调度优化,核心思想是把 CPU 调度操作与 GPU 计算重叠:
# worker/zos_status.py + worker.py 核心逻辑
class Worker:
def step(self, scheduler_outputs):
# 传统方式: 串行
# 1. CPU: prepare_inputs (调度 + 张量准备)
# 2. GPU: model.forward (计算)
# 3. CPU: post_process (采样后处理)
# → CPU 和 GPU 不重叠, 调度开销完全暴露
# ZOS 方式: overlap
# Step N:
if self.zos_enabled:
# 1. GPU: 上一步的 post_process (异步, 与下面的 CPU 重叠)
self._async_post_process_prev()
# 2. CPU: 为当前步准备输入 (调度 + 张量准备)
inputs = self.prepare_inputs(scheduler_outputs)
# 3. GPU: 当前步 forward
output = self.model.forward(inputs)
# 4. 保存状态, post_process 延迟到下一步
self._defer_post_process(output)
else:
# 传统串行路径
inputs = self.prepare_inputs(scheduler_outputs)
output = self.model.forward(inputs)
result = self.post_process(output)
# 效果: 调度 CPU 操作隐藏在 GPU 计算时间内
# 对小 batch / 短序列场景, 端到端延迟降低 10-30%
某 AI 公司部署 DeepSeek-V4 模型(256 个 expert,128K 上下文),日均 500 万次 API 调用,要求 P99 延迟 < 2 秒。用 vLLM 部署遇到三个问题:① 128K 上下文 OOM(KV cache 4GB/请求)② MoE 专家负载不均导致部分 GPU 利用率 95% 而其他仅 30% ③ 长 prompt prefill 延迟超过 5 秒。
| 层级 | 组件 | 配置 |
|---|---|---|
| 接入层 | API Gateway + 负载均衡 | Nginx → 多实例 DeepInfer |
| 引擎层 | DeepInfer LLMEngine | 8 × H100 GPU, DP=2, EP=4 |
| 模型层 | DeepseekModel + MLA + MoE + DFlash | 256 expert, top-8, 128K ctx |
| 优化层 | EPLB + ZOS + CUDA Graph | EPLB warmup 100 步, ZOS 开启 |
| 基础设施 | deep_ep + deep_gemm + NUMA 绑定 | NUMA-aware, userbuffer |
# 案例 1: DeepSeek-V4 在线推理
# 安装: pip install deepinfer (需要 NVIDIA GPU + CUDA 12.x)
from deepinfer import LLM, SamplingParams
# 1. 初始化引擎 — 关键配置项
llm = LLM(
model="deepseek-ai/DeepSeek-V4", # 模型路径或 HuggingFace ID
tensor_parallel_size=4, # 4 GPU 张量并行
data_parallel_size=2, # 2 路数据并行
max_num_seqs=256, # 最大并发请求
max_model_len=131072, # 128K 上下文
gpu_memory_utilization=0.92, # GPU 显存利用率上限
# MLA 相关 (自动从模型 config 读取, 这里展示关键参数)
kv_lora_rank=512, # KV 压缩秩
rope_head_dim=64, # RoPE 维度
# MoE + EPLB
enable_eplb=True, # 开启专家负载均衡
eplb_num_physical_experts=288, # 256 logical + 32 redundant
eplb_rebalance_interval=1000, # 每 1000 步重均衡
# DFlash 投机采样
enable_mtp=True, # 开启 MTP
mtp_num_speculative_tokens=4, # 投机 4 个 token
# ZOS 零开销调度
enable_zos=True, # 开启 ZOS
# CUDA Graph
enforce_eager=False, # 启用 CUDA Graph
cuda_graph_max_capture_batch_size=256,
)
# 2. 准备请求
prompts = [
"请总结以下文档的核心观点:\n" + "..." * 50000, # 长文档摘要
"用 Python 实现一个红黑树的插入操作", # 代码生成
"解释量子纠缠现象,面向高中生", # 知识问答
]
sampling_params = SamplingParams(
temperature=0.7,
top_p=0.9,
max_tokens=2048,
)
# 3. 批量推理 (连续批处理自动生效)
outputs = llm.generate(prompts, sampling_params)
for output in outputs:
print(f"Prompt: {output.prompt[:50]}...")
print(f"Output: {output.outputs[0].text[:100]}...")
print(f"Tokens: {len(output.outputs[0].token_ids)}")
print(f"Finish: {output.outputs[0].finish_reason}")
print("---")
vs vLLM:① KV cache 显存 4GB→128MB/请求,并发数从 8 提升到 256 ② EPLB 后 GPU 利用率从 30%-95% 均衡到 60%-65% ③ DFlash 投机采样吞吐提升 ~2.8× ④ ZOS 调度开销降低 ~20% ⑤ 128K prefill 从 5.2s 降到 0.8s(YoCo+稀疏索引)
研究机构需要对 100 万篇论文做摘要提取,每篇平均 8K token,输出 512 token。要求 8 小时内完成,用 4 × H100 GPU。关键挑战:吞吐最大化(而非延迟),GPU 利用率要打满。
# 案例 2: 离线批量推理 — 吞吐最大化
from deepinfer import LLM, SamplingParams
import json, time
# 离线推理配置: 最大化吞吐
llm = LLM(
model="deepseek-ai/DeepSeek-V4",
tensor_parallel_size=4, # 4 GPU 全用于张量并行
max_num_seqs=512, # 大 batch 提高吞吐
max_model_len=16384, # 论文不需要 128K
gpu_memory_utilization=0.95, # 榨干显存
enable_eplb=True,
enable_mtp=True,
mtp_num_speculative_tokens=8, # 离线场景增大投机步数
enable_zos=True,
enforce_eager=False, # CUDA Graph
)
# 加载 100 万篇论文
papers = []
with open("papers.jsonl") as f:
for line in f:
paper = json.loads(line)
papers.append(f"请为以下论文写一段 200 字摘要:\n{paper['text']}")
print(f"共 {len(papers)} 篇论文待处理")
# 批量推理 — DeepInfer 自动连续批处理
sampling_params = SamplingParams(
temperature=0.3, # 低温度: 更确定性
top_p=0.9,
max_tokens=512,
ignore_eos=False,
)
start = time.time()
outputs = llm.generate(papers, sampling_params)
elapsed = time.time() - start
# 统计
total_tokens = sum(len(o.outputs[0].token_ids) for o in outputs)
throughput = len(papers) / elapsed
token_throughput = total_tokens / elapsed
print(f"处理 {len(papers)} 篇论文, 耗时 {elapsed:.1f}s")
print(f"论文吞吐: {throughput:.1f} 篇/秒")
print(f"Token 吞吐: {token_throughput:.1f} tokens/秒")
# 保存结果
with open("summaries.jsonl", "w") as f:
for paper, output in zip(papers, outputs):
result = {"summary": output.outputs[0].text}
f.write(json.dumps(result, ensure_ascii=False) + "\n")
IDE 插件提供实时代码补全,用户每输入一个字符就发请求。要求首 token 延迟 < 200ms,每秒处理 1000+ 请求。关键:DFlash 投机采样 + ZOS + prefix caching。
# 案例 3: 代码补全服务 — 低延迟
from deepinfer import LLM, SamplingParams
llm = LLM(
model="deepseek-ai/DeepSeek-Coder-V4",
tensor_parallel_size=2,
max_num_seqs=1024, # 高并发
max_model_len=8192, # 代码上下文不需要太长
gpu_memory_utilization=0.90,
# DFlash: 代码补全接受率高, 增大投机步数
enable_mtp=True,
mtp_num_speculative_tokens=6,
# ZOS: 降低调度开销, 对小 batch 关键
enable_zos=True,
# Prefix caching: 代码上下文高度复用
enable_prefix_caching=True,
# CUDA Graph: 消除 CPU launch 开销
enforce_eager=False,
cuda_graph_max_capture_batch_size=128,
)
# 模拟 IDE 代码补全请求
code_context = """import torch
import torch.nn as nn
class TransformerBlock(nn.Module):
def __init__(self, d_model, num_heads, d_ff):
super().__init__()
self.attention = nn.MultiheadAttention(d_model, num_heads)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.GELU(),
nn.Linear(d_ff, d_model)
)
def forward(self, x):
# """
# 代码补全: 贪心解码, 只需 1-2 个 token
params = SamplingParams(
temperature=0.0, # 贪心: 确定性输出
max_tokens=64, # 补全一小段
)
import time
start = time.time()
outputs = llm.generate([code_context], params)
latency = (time.time() - start) * 1000
print(f"首 token 延迟: {latency:.0f}ms")
print(f"补全结果:")
print(outputs[0].outputs[0].text)
三个因素叠加:① Prefix caching:同一文件的代码上下文高度复用,KV cache 直接命中,省去 prefill ② DFlash:代码补全的接受率通常 85%+(代码模式高度可预测),6 步投机平均一次出 5+ token ③ ZOS + CUDA Graph:调度开销隐藏在计算时间内,CPU launch 开销归零
DeepInfer 的 C++ 调度器 (csrc/engine/scheduler.hpp) 是完全自研的,不来自 vLLM。它是整个框架中延迟最敏感的组件,决定了请求的调度顺序、KV cache 的分配策略、以及抢占机制。
// csrc/engine/scheduler.hpp (源码精简)
class Scheduler {
// 三个请求队列
std::vector<Sequence*> waiting_; // 等待 prefill 的新请求
std::vector<Sequence*> running_; // 正在 decode 的请求
std::vector<Sequence*> swapped_; // 被抢占换出的请求
// KV cache 块管理器
BlockManager block_manager_;
// 调度配置
int max_num_seqs_; // 最大并发数
int chunk_prefill_size_; // chunked prefill 切分大小
bool enable_zos_; // ZOS 开关
// 调度输出
SchedulerOutputs schedule_outputs_;
};
class BlockManager {
// 空闲块池 (双向链表)
std::list<Block*> free_blocks_;
// 已分配块 (按 sequence 索引)
std::unordered_map<int, std::vector<Block*>> block_table_;
// 引用计数 (支持 prefix sharing)
std::unordered_map<Block*, int> ref_count_;
// pin 状态 (支持 state cache)
std::unordered_set<Block*> pinned_blocks_;
};
class Sequence {
int seq_id_; // 唯一 ID
std::vector<int> token_ids_; // 逻辑 token 列表
std::vector<int> block_table_; // KV cache 块索引
SamplingParams params_; // 采样参数
enum Status { WAITING, RUNNING, SWAPPED, FINISHED };
Status status_;
float priority_; // 抢占优先级
};
// Scheduler::schedule() 核心逻辑 (源码精简)
SchedulerOutputs Scheduler::schedule() {
SchedulerOutputs outputs;
// Phase 1: 尝试恢复 swapped 请求
for (auto* seq : swapped_) {
if (block_manager_.can_allocate(seq)) {
block_manager_.allocate(seq);
seq->status = RUNNING;
running_.push_back(seq);
outputs.scheduled_seqs.push_back(seq);
}
}
// Phase 2: 尝试 prefill waiting 请求
for (auto* seq : waiting_) {
// Chunked prefill: 长 prompt 切分
int chunk_size = std::min(
chunk_prefill_size_,
seq->remaining_tokens()
);
if (block_manager_.can_allocate_chunk(seq, chunk_size)) {
block_manager_.allocate_chunk(seq, chunk_size);
seq->status = RUNNING;
running_.push_back(seq);
outputs.scheduled_seqs.push_back(seq);
outputs.prompt_run = true;
} else if (!running_.empty()) {
// 块不足 → 抢占最低优先级请求
Sequence* victim = find_lowest_priority(running_);
block_manager_.free(victim);
victim->status = SWAPPED;
swapped_.push_back(victim);
// 重试分配
if (block_manager_.can_allocate_chunk(seq, chunk_size)) {
block_manager_.allocate_chunk(seq, chunk_size);
seq->status = RUNNING;
running_.push_back(seq);
outputs.scheduled_seqs.push_back(seq);
}
}
}
// Phase 3: 调度 running 请求的 decode
for (auto* seq : running_) {
if (seq->status == RUNNING && !outputs.is_prompt(seq)) {
outputs.scheduled_seqs.push_back(seq);
}
}
// Phase 4: 估算 FLOPs 和 MFU
outputs.flops = estimate_flops(outputs.scheduled_seqs);
outputs.mfu = outputs.flops / (gpu_peak_flops_ * step_time_);
return outputs;
}
// BlockManager 核心操作 (源码精简)
bool BlockManager::can_allocate(Sequence* seq) {
int needed = seq->num_blocks_needed();
return free_blocks_.size() >= needed;
}
void BlockManager::allocate(Sequence* seq) {
// Prefix sharing: 检查是否有已分配块匹配 prefix
auto prefix = find_prefix_match(seq->token_ids_);
if (prefix) {
// 复用已有块, 增加引用计数
for (auto* block : prefix->blocks) {
ref_count_[block]++;
seq->block_table_.push_back(block->id);
}
}
// 分配新块
int remaining = seq->num_blocks_needed() - seq->block_table_.size();
for (int i = 0; i < remaining; i++) {
Block* block = free_blocks_.front();
free_blocks_.pop_front();
ref_count_[block] = 1;
seq->block_table_.push_back(block->id);
}
}
void BlockManager::free(Sequence* seq) {
for (int block_id : seq->block_table_) {
Block* block = get_block(block_id);
ref_count_[block]--;
if (ref_count_[block] == 0 && !pinned_blocks_.count(block)) {
// 引用计数归零且未 pin → 回收
free_blocks_.push_back(block);
}
}
seq->block_table_.clear();
}
BlockManager 的 pin/unpin 机制支持 state cache:当一个请求完成后,可以 pin 住其 KV cache blocks,后续相同 prefix 的请求直接复用,省去 prefill 计算。这在代码补全(同一文件反复请求)和 RAG(相同文档反复查询)场景下效果显著。
| 依赖 | 用途 | 是否自研 |
|---|---|---|
| deep_ep | Expert Parallel all-to-all 通信库 | ✓ DeepSeek 自研 (git submodule) |
| deep_gemm | FP8 GEMM kernel | ✓ DeepSeek 自研 (git submodule) |
| deep_select | Top-k selection kernel | ✓ DeepSeek 自研 (git submodule) |
| tile_kernels / tilelang | Tile-based CUDA kernel 生成 | ✓ DeepSeek 自研 (git submodule) |
| flash-attn-4 | Flash Attention 4 库 | ✗ 第三方 |
| xgrammar | 结构化输出语法约束 | ✗ 第三方 |
| torch / torchvision | PyTorch 深度学习框架 | ✗ 第三方 |
| vllm | 衍生自 vLLM (部分代码复用) | ✗ 衍生基础 |
# .gitmodules (源码)
[submodule "deep_ep"]
path = deep_ep
url = https://github.com/deepseek-ai/deep_ep.git
[submodule "deep_gemm"]
path = deep_gemm
url = https://github.com/deepseek-ai/deep_gemm.git
[submodule "deep_select"]
path = deep_select
url = https://github.com/deepseek-ai/deep_select.git
[submodule "tile_kernels"]
path = tile_kernels
url = https://github.com/deepseek-ai/tile_kernels.git
[submodule "tilelang"]
path = tilelang
url = https://github.com/deepseek-ai/tilelang.git
DeepInfer/
├── deepinfer/ # Python 主包
│ ├── engine/ # 引擎层 (LLMEngine, Scheduler, Args)
│ ├── worker/ # Worker 层 (ModelRunner, CacheEngine, ZOS)
│ ├── model_executor/
│ │ ├── models/
│ │ │ ├── v4_modules/ # V4 核心模块 (MLA, MoE, Engram, YoCo, ...)
│ │ │ ├── mtp/ # MTP 投机采样 (DFlash)
│ │ │ └── deepseek.py # DeepSeek 模型组装
│ │ ├── eplb/ # 专家负载均衡
│ │ ├── parallel_utils/ # 并行状态管理
│ │ └── layers/ # 采样层
│ ├── entrypoints/ # 用户接口 (llm.py)
│ └── config.py # 配置
├── csrc/ # C++ 高性能层
│ └── engine/ # C++ 调度器 + BlockManager + Sequence
├── deep_ep/ # EP 通信库 (submodule)
├── deep_gemm/ # FP8 GEMM (submodule)
├── deep_select/ # Top-k selection (submodule)
├── tile_kernels/ # Tile kernel (submodule)
├── tilelang/ # Tile 语言 (submodule)
├── deep_cluster/ # 集群拓扑 + NUMA 绑定
├── examples/ # 示例代码
└── tests/ # 测试
Engram 像是餐厅的"常见菜式速查表":如果 90% 的客人都点"宫保鸡丁+米饭+可乐"这个组合,那不必每次都从头记,直接查表就行。Engram 把高频 n-gram 的 KV 预计算存表,遇到匹配直接查表跳过计算。
# v4_modules/engram.py 核心逻辑 (源码精简)
class EngramBuffer:
"""n-gram KV 压缩表"""
def __init__(self, ngram_size=3, max_entries=100000):
self.ngram_size = ngram_size
self.table = {} # tuple(token_ids) -> kv_cache
def lookup(self, token_ids):
"""查找 n-gram 匹配, 返回预计算的 KV"""
for i in range(len(token_ids) - self.ngram_size + 1):
ngram = tuple(token_ids[i:i+self.ngram_size])
if ngram in self.table:
return self.table[ngram] # 命中! 跳过这些 token 的 KV 计算
return None # 未命中
def insert(self, token_ids, kv_cache):
"""将新 n-gram + KV 存入表"""
for i in range(len(token_ids) - self.ngram_size + 1):
ngram = tuple(token_ids[i:i+self.ngram_size])
self.table[ngram] = kv_cache[i:i+self.ngram_size]
# 效果: 对重复模式 (代码、模板、FAQ) 可跳过 30-60% 的 KV 计算
mHC 是 V4 的残差混合机制,将不同层的输出按 head 拼接后做残差连接:
# v4_modules/hc.py 核心逻辑 (源码精简)
class MultiHeadConcat:
"""multi-Head Concatenation 残差混合"""
def __init__(self, num_layers, num_heads, head_dim):
# 每层贡献部分 head, 拼接成完整输出
self.heads_per_layer = num_heads // num_layers
self.projection = nn.Linear(head_dim, head_dim)
def forward(self, layer_outputs, residual):
# layer_outputs: [num_layers, batch, seq, heads_per_layer, head_dim]
# 拼接所有层的 head
concatenated = torch.cat(layer_outputs, dim=-2) # [batch, seq, num_heads, head_dim]
# 投影 + 残差
output = self.projection(concatenated) + residual
return output
V4 模型在构造时确定哪些层的 KV 可以被其他层复用:
# v4_modules/cross_layer.py (源码精简)
class SharedLayerTopology:
"""跨层共享拓扑: 定义 producer-consumer 关系"""
def __init__(self, num_layers, share_interval=4):
self.producer_layers = set(range(0, num_layers, share_interval))
self.consumer_to_producer = {}
for i in range(num_layers):
if i not in self.producer_layers:
# 找最近的 producer
self.consumer_to_producer[i] = i - (i % share_interval)
def get_producer(self, layer_idx):
return self.consumer_to_producer.get(layer_idx)
def is_producer(self, layer_idx):
return layer_idx in self.producer_layers
# 效果: 每 4 层只有 1 层计算 KV, 其他 3 层复用
# KV 计算量降低 ~4x, KV 存储量降低 ~4x
DeepInfer 支持 V41 格式的 KV cache,使用 FP4(4-bit 浮点)量化进一步压缩显存:
# cache_engine.py KV 字节计算 (源码精简)
def _kv_bytes_per_token(self):
"""计算每 token 的 KV cache 字节数"""
if self.kv_cache_dtype == "v41":
# V41 格式: FP4 量化
# 每组 16 个 FP4 值共享 1 个 scale (FP8)
bytes_per_element = 0.5 # 4 bit = 0.5 byte
scale_overhead = 1 / 16 # 每 16 个值 1 个 FP8 scale
total_per_element = bytes_per_element + scale_overhead
elif self.kv_cache_dtype == "fp8":
total_per_element = 1.0 # 8 bit = 1 byte
else:
total_per_element = 2.0 # FP16 = 2 bytes
# MLA: 只存压缩后的 kv_lora_rank + rope_dim
kv_dim = self.kv_lora_rank + self.rope_head_dim
return kv_dim * 2 * total_per_element # K + V
# 对比:
# FP16: 576 * 2 * 2.0 = 2304 bytes/token
# FP8: 576 * 2 * 1.0 = 1152 bytes/token
# V41: 576 * 2 * 0.5625 = 648 bytes/token (再降 3.5x)
# deep_cluster/topology/bind.py (源码精简)
class TopologyBinder:
"""NUMA 感知的 GPU 绑定"""
def bind(self):
# 1. 检测 NUMA 拓扑
numa_nodes = self.detect_numa_nodes() # 如 [0, 1]
gpus_per_numa = self.detect_gpus_per_numa() # 如 {0: [0,1,2,3], 1: [4,5,6,7]}
# 2. 为每个 GPU 绑定最近的 NUMA node
for numa_id, gpu_ids in gpus_per_numa.items():
for gpu_id in gpu_ids:
os.sched_setaffinity(0, self.get_cpu_set(numa_id))
torch.cuda.set_device(gpu_id)
# 设置 GPU 与同一 NUMA 的内存通信
self.set_p2p_access(gpu_id, gpus_per_numa[numa_id])
# 3. EP 通信: 确保 dispatch/combine 走 NVLink 而非 PCIe
self.configure_nvlink_groups()
# 效果: NUMA 远端访问延迟 ~2x, 绑定后 EP 通信延迟降低 30-50%
| 技术 | 全称 | 解决的问题 | 源码位置 | 效果 |
|---|---|---|---|---|
| MLA | Multi-head Latent Attention | KV cache 显存爆炸 | v4_modules/mla_attn.py | 显存降 32× |
| EPLB | Expert Parallel Load Balancing | MoE 专家负载不均 | eplb/policy.py | GPU 利用率均衡 |
| DFlash | DFlash MTP 投机采样 | 解码访存瓶颈 | models/mtp/dflash.py | 吞吐 1.7-4.6× |
| YoCo | YoCo Consumer 跳过 | 长 prefill 计算量 | v4_modules/yoco.py | prefill 降 32× |
| ZOS | Zero-Overhead Scheduling | 调度与计算串行 | worker/zos_status.py | 延迟降 10-30% |
| Engram | n-gram KV 压缩表 | 重复模式 KV 重算 | v4_modules/engram.py | 跳过 30-60% KV |
| mHC | multi-Head Concatenation | 跨层信息融合 | v4_modules/hc.py | 残差混合 |
| Cross-Layer | 跨层 KV 共享 | 层间 KV 冗余 | v4_modules/cross_layer.py | KV 降 4× |
| 稀疏索引 | MQA Sparse Index | 全量 attention 计算量 | v4_modules/index_attn.py | 计算降 32× |
| V41/FP4 | FP4 量化 KV cache | KV 显存进一步压缩 | worker/cache_engine.py | 再降 3.5× |
| Paged KV | PagedAttention 块管理 | KV 显存碎片化 | csrc/engine/block_manager.hpp | 零碎片 |
| deep_ep | EP all-to-all 通信 | MoE 通信开销 | deep_ep/ (submodule) | NUMA-aware |
| 场景 | 关键需求 | DeepInfer 优势 |
|---|---|---|
| 长上下文对话 (128K+) | 大 KV cache + 低 prefill 延迟 | MLA 32× 压缩 + YoCo 稀疏 + 稀疏索引 |
| 高并发在线服务 | 高 QPS + 低 P99 延迟 | 连续批处理 + ZOS + CUDA Graph + DFlash |
| 代码补全 / IDE 插件 | 极低首 token 延迟 + prefix 复用 | Prefix caching + DFlash(高接受率) + ZOS |
| 离线批量推理 | 吞吐最大化 + GPU 满载 | 大 batch + DFlash(大投机步数) + EPLB |
| MoE 模型部署 | 专家负载均衡 + EP 通信高效 | EPLB 全局重均衡 + deep_ep + NUMA 绑定 |
| 跨平台部署 | NVIDIA + 华为昇腾 | Platform 抽象层 + CANN/HCCL 支持 |
| 维度 | DeepInfer | vLLM | SGLang | TensorRT-LLM |
|---|---|---|---|---|
| MLA 支持 | ✓ 深度定制 | ✗ 需适配 | 部分 | ✗ |
| EPLB | ✓ 全局重均衡 | ✗ | ✗ | ✗ |
| MTP 投机采样 | ✓ DFlash 自适应 | 基础 | ✗ | 基础 |
| ZOS 零开销调度 | ✓ | ✗ | ✗ | ✗ |
| 跨平台 | NVIDIA + 昇腾 | NVIDIA | NVIDIA | NVIDIA only |
| Engram / mHC | ✓ | ✗ | ✗ | ✗ |
| C++ 调度器 | ✓ 自研 | Python | Python | C++ |
| 开源许可 | Apache-2.0 | Apache-2.0 | Apache-2.0 | 专有 |
DeepInfer 是目前对 DeepSeek V4 模型架构优化最深入的推理框架。它的核心价值不在于"通用推理能力",而在于模型-引擎协同设计——每个核心组件都精准对应 V4 架构的一个痛点,做到"对症下药"。对于部署 DeepSeek 模型的团队,DeepInfer 是首选;对于其他模型,vLLM/SGLang 仍是更通用的选择。