Building an LLM Inference Engine from ScratchAppendices A–G
Appendices

附录:数学、Rust、浮点、调试、术语与阅读清单

本页汇总数学、系统编程、浮点、调试与术语资料,供阅读正文和实验时查阅。

A数学速查:点积、矩阵乘、softmax 稳定性

点积

ab=i=0d1aibia\cdot b = \sum_{i=0}^{d-1} a_i b_i

点积给出两个向量逐元素乘积的总和。Attention score 通常由 query 与 key 的点积再按维度缩放得到。

矩阵乘 shape

ARM×K,BRK×NC=ABRM×NA\in\mathbb{R}^{M\times K},\quad B\in\mathbb{R}^{K\times N} \quad\Rightarrow\quad C=AB\in\mathbb{R}^{M\times N}
Ci,j=p=0K1Ai,pBp,jC_{i,j}=\sum_{p=0}^{K-1}A_{i,p}B_{p,j}

HuggingFace transposed-weight linear

HuggingFace checkpoint 中的线性层权重通常按[out_features, in_features]存储:

Y=XW,XRS×K,WRN×K,YRS×NY = XW^\top,\qquad X\in\mathbb{R}^{S\times K},\quad W\in\mathbb{R}^{N\times K},\quad Y\in\mathbb{R}^{S\times N}

稳定 softmax

pi=exp(zim)jexp(zjm),m=maxjzjp_i = \frac{\exp(z_i-m)}{\sum_j\exp(z_j-m)},\qquad m=\max_j z_j

对所有 logits 同时减去最大值不会改变 softmax 结果,可降低指数运算溢出的风险。

BRust 系统编程与 FFI 速查

Ownership 与 GPU 资源

Rust ownership 可用于表达 GPU 资源的生命周期:一个DmlBuffer拥有对应的 COM resource handle;对象 drop 时释放引用计数。由于 GPU 命令异步执行,资源释放或复用必须晚于 GPU 对该资源的最后一次访问。

unsafe

调用 D3D12、DirectML 或 FFI 时需要使用unsafe。本教程采用的边界是:将unsafe限制在小范围内,对外提供安全接口,并记录调用者必须满足的前置条件。

C ABI

#[no_mangle]
pub extern "C" fn xinfer_version() -> *const c_char {
    ...
}

C ABI 设计遵循以下规则:

  • 不要让 panic 跨过 FFI 边界;
  • 用 opaque handle 隐藏 Rust 内部结构;
  • 用错误码返回状态,用last_error提供消息;
  • 谁分配,谁释放。

bytemuckhalf

bytemuck::cast_slice用于在满足布局条件时把数值切片视为字节切片,便于上传到 GPU。half::f16half::bf16用于加载或转换半精度权重。

C浮点:f32 / f16 / bf16、舍入与容差

格式字节特点本项目用途
f324精度较高,带宽占用大CPU reference、activation
f162尾数较少,显存减半GPU weights
bf162指数范围接近 f32,尾数更少checkpoint dtype,加载时转换

浮点加法不满足严格结合律:

(a+b)+ca+(b+c)in floating point(a+b)+c \ne a+(b+c)\quad\text{in floating point}

因此,CPU 与 GPU 的归约顺序不同会产生微小数值差异。测试通常采用容差判断:

maxiyigpuyicpu<ε\max_i |y_i^{gpu}-y_i^{cpu}| < \varepsilon

DGPU 调试:PIX、D3D12 debug layer、device removed

D3D12 debug layer

D3D12 debug layer 可报告资源状态错误、非法绑定和命令列表使用错误。开发 GPU backend 时应尽早启用。

Device removed

当 GPU device 被移除或重置时,D3D12 调用可能返回类似0x887A0005的 HRESULT。调试步骤:

  1. 打开 debug layer;
  2. 调用GetDeviceRemovedReason
  3. 隔离到最小 shape / 最小 kernel;
  4. 检查 resource states 与 bindings;
  5. 必要时绕开有问题的库 operator,改写 custom kernel。

PIX

PIX 是 Windows 与 Xbox 平台的 GPU 捕获和分析工具,可检查 command list、resource state、shader 与 timing。正文不依赖 PIX;在复杂 GPU 问题和性能分析中应优先考虑使用。

E术语表

术语解释
GEMMGeneral Matrix-Matrix Multiplication,矩阵乘 C=ABC=AB
GEMVMatrix-Vector multiplication,decode 中常见的 M=1M=1 线性层。
GQAGrouped-Query Attention,多个 query heads 共享较少 KV heads。
RoPERotary Position Embedding,用旋转把位置信息注入 Q/K。
SwiGLU门控 MLP 激活:SiLU(gate)up\operatorname{SiLU}(gate)\odot up
KV cache缓存每层历史 token 的 K/V,避免重复计算。
SRVShader Resource View,shader 只读资源视图。
UAVUnordered Access View,shader 可读写资源视图。
LDS / groupshared同一 threadgroup 内共享的高速内存。
HALHardware Abstraction Layer,把模型层与具体 backend 解耦。
DXILDirectX Intermediate Language,DXC 生成的现代 shader IR。

F仓库地图

路径内容
crates/xinfer-core基础类型、Qwen config、CPU reference ops。
crates/xinfer-backendHAL traits。
crates/xinfer-dmlD3D12/DirectML backend、buffers、kernels、copy queue、timer。
crates/xinfer-loaderconfig 与 safetensors 加载。
crates/xinfer-modelQwen2 CPU/GPU forward、KV cache、streaming。
crates/xinfer-runtimegeneration loop、sampling、GenerateStats。
crates/xinfer-tokenizerHF tokenizer wrapper 与 Qwen chat template。
crates/xinfer-ffiC ABI:staticlib/cdylib。
crates/xinfer-cli命令行入口。
shaders/HLSL kernels。
xbox/C++ GDK host 与构建脚本。
generated/教程材料、报告、本地生成输出。

G阅读清单

Transformer 与 LLM

  • Vaswani et al., “Attention Is All You Need”.
  • RoPE: “RoFormer: Enhanced Transformer with Rotary Position Embedding”.
  • Grouped-Query Attention / Multi-Query Attention 相关论文。
  • FlashAttention 系列论文。

量化与推理系统

  • GGUF / llama.cpp quantization 文档。
  • weight-only quantization / GPTQ / AWQ 相关资料。
  • vLLM / paged attention 论文与工程文章。

GPU / DirectX

  • Microsoft Direct3D 12 documentation。
  • HLSL reference。
  • DirectML documentation。
  • PIX on Windows documentation。
  • Microsoft GDK documentation。