从零构建 LLM 推理引擎
本教程以 xinfer 为对象,说明如何用 Rust、DirectML 与 D3D12 实现一个可运行 Qwen2.5 的 LLM 推理引擎,并覆盖 GPU kernel、KV cache、采样、性能优化与 Xbox GDK 部署。
Part 0 — Tutorial Orientation
- Part 0教程导论:我们要从零构建什么?
定义教程目标、实现边界、工具链、crate 依赖关系与 Lab 0。
Part I — Foundations: Large Language Models
- Module 1从 n-gram 到 Transformer
从 next-token prediction 与 logits 出发,说明 n-gram 的限制、attention 机制与 decoder-only 结构。
- Module 2Transformer Block:算子逐个看
给出 RMSNorm、linear、attention、GQA、RoPE、SwiGLU 与 LM head 的 shape 约定和计算式。
- Module 3自回归生成、KV Cache 与采样
分析 prefill/decode 流程、KV cache 的作用、sampling 策略、tokenizer、chat template 与吞吐指标。
Part II — Foundations: GPU Compute & Shaders
- Module 4为什么需要 GPU,什么是 Shader?
介绍 CPU/GPU 执行模型、SIMT、内存层次、coalescing、dispatch grid 与 roofline 分析。
- Module 5GPU Compute API 版图
比较 CUDA、Vulkan、Metal、OpenCL 与 D3D12+DirectML,并说明 HAL 的设计动机。
- Module 6HLSL 与 Direct3D 12 编程模型
说明 HLSL compute、资源类型、groupshared memory、DXC、D3D12 对象、barriers 与 root signature。
Part III — The Concrete Candidates
- Module 7Qwen2 / Qwen2.5 模型
读取 config.json、safetensors 与 dtype 信息,建立 Qwen2/Qwen2.5 的模型尺寸和显存估算方法。
- Module 8DirectML 与 Direct3D 12 Backend
讨论 DirectML operator 生命周期、HLSL kernel、RDNA4 GEMM device removed 问题,以及 PC/Xbox device creation。
Part IV — Implementation: Building xinfer
- Module 9Phase 0:项目脚手架与 Backend Bring-up
建立 Cargo workspace,初始化 D3D12/DirectML device,并实现 GEMM 与 affine kernel 的最小路径。
- Module 10Phase 1:硬件抽象层 HAL
定义 Device/Buffer traits、buffer 状态跟踪、Executor、operator/kernel wrapper 与 GPU timer。
- Module 11Phase 2:Transformer Ops as Kernels
为 RMSNorm、RoPE、SwiGLU、add、GQA attention 与 matmul 建立 CPU reference、GPU kernel 和 parity 测试。
- Module 12Phase 3:组装 Qwen2 模型
处理权重命名、CPU/GPU forward、debug layer、device removed 诊断与 custom matmul 接入。
- Module 13Phase 4:Runtime、KV Cache、Decode 与 Sampling
实现 per-layer KV cache、prefill/decode、samplers、tokenizer 集成与端到端生成示例。
- Module 14Phase 5:Layer Streaming
说明模型权重超过 VRAM 时的 copy queue、staging、double-buffering 与 cross-queue state 管理。
Part V — Performance Engineering
Part VI — Portability & Deployment
- Module 18Xbox GDK 部署路径
说明 Rust C ABI staticlib、C++ GDK host、device injection、ctypes 验证与 GDK desktop 流程。
- Module 19Productionizing
整理 logging/tracing、GenerateStats、memory reporting、CLI、reproducibility 与 README 要求。
Appendices
- A–G附录:数学、Rust、浮点、调试、术语与阅读清单
提供点积、matmul、softmax、FFI、f32/f16/bf16、PIX、D3D12 debug layer、术语表与仓库地图速查。