Appearance
模型库与算子层 — 练习
练习 1:添加新模型
假设需要添加一个新的模型架构 "SimpleModelForCausalLM",请描述需要:
- 创建哪些文件?
- 实现哪些方法?
- 如何注册到 ModelRegistry?
参考答案
创建
vllm/model_executor/models/simple_model.py,实现模型类。必须实现:
__init__: 初始化模型层(embed、transformer layers、lm_head)forward: 前向传播,返回 logprobs 或 hidden statesload_weights: 从 HuggingFace checkpoint 加载权重- 可选:实现
SupportsLoRA、SupportsMultiModal等 Mixin
使用装饰器注册:
python@ModelRegistry.register("SimpleModelForCausalLM") class SimpleModelForCausalLM(nn.Module): ...
练习 2:注意力后端对比
对比以下注意力后端的性能特征:
| 后端 | Prefill | Decode | CUDA Graph |
|---|---|---|---|
| FlashAttention | ? | ? | ? |
| FlashInfer | ? | ? | ? |
| Triton | ? | ? | ? |
参考答案
| 后端 | Prefill | Decode | CUDA Graph |
|---|---|---|---|
| FlashAttention | 优秀(IO-aware 算法) | 需要额外优化 | 支持 |
| FlashInfer | 优秀(专为推理优化) | 最优(decode kernel) | 最佳支持 |
| Triton | 良好 | 良好 | 支持 |
FlashInfer 是 vLLM V1 的默认后端,专为推理场景优化,decode 性能最好。
练习 3:MoE 模型分析
分析 DeepSeek-V3 的 MoE 实现:
- 每层有多少个专家?
- Router 如何选择专家?
- Fused MoE kernel 如何加速计算?
参考答案
DeepSeek-V3 使用 256 个路由专家 + 1 个共享专家。每个 token 激活 top-8 路由专家 + 共享专家。
Router 是一个线性层,输出 256 个专家的分数,选择 top-8。使用 sigmoid 而非 softmax,配合负载均衡损失。
Fused MoE kernel 将以下操作融合为一个 kernel:
- Router 计算
- Token 到 Expert 的分发
- Expert 的线性计算
- 结果聚合 避免了多次 global memory 读写,显著减少延迟。
拓展挑战
- 阅读
vllm/model_executor/models/llama.py,理解 LLaMA 模型的完整实现 - 分析
fused_moe/目录下的 kernel 实现 - 研究
quantization/目录下的量化方法如何与线性层集成