<AI Infra Atlas> 学习笔记03 / KERNELS & COMPILERS
AI Infra 03 — Kernels & Compilers
From CUDA threads to multi-level IR.
这一章从 GPU Kernel 的执行细节出发,逐步上升到 Tensor Program、计算图、自动微分、编译器优化和跨硬件代码生成。核心问题始终是:在保持计算语义的前提下,如何减少数据搬运、充分利用硬件资源,并控制编译和执行成本?
0. 全局知识地图
PyTorch / JAX / TensorFlow Model / Framework
│
▼
Graph capture / high-level IR What to compute
│
▼
Graph transformation Autograd / Decomposition / Fusion
│
▼
Tensor / Loop / Buffer IR How to compute
│
▼
Scheduling / Memory Planning Tiling / Layout / Parallelism
│
▼
Target code generation Triton / C++ / CUDA / Library calls
│
▼
CPU / GPU / TPU Hardware execution
这是抽象层级,而不是所有编译器都必须遵循的固定调用链。MLIR 是支持多个层级的编译基础设施;Triton 是块级 Kernel 语言及编译器;Inductor、XLA 和 TVM 则在更广泛的模型或张量程序优化层面工作。
| 小节 | 核心内容 | 学习状态 |
|---|---|---|
| 03.1 CUDA Kernel 与内存合并 | Grid、Block、Warp、SM、Coalescing、Bank Conflict、Synchronization | 理论完成,CUDA GPU 实测待完成 |
| 03.2 Triton 与算子融合 | Program、Mask、Stride、Reduction、RMSNorm、Autotune | 理论完成,GPU 实测待完成 |
| 03.3 计算图、AOTAutograd 与 Inductor | FX Graph、Guards、重计算、动态 Shape、Lowering、Fusion、生成代码 | 理论与核心 CPU 实验完成 |
| 03.4 MLIR、XLA 与 TVM | 多层 IR、Dialect、Pass、TensorIR、Schedule Search | 理论完成,JAX/TVM 实际运行未验证 |
1. CUDA Kernel 与内存合并
1.1 执行模型:软件层级与硬件层级
Software Hardware (NVIDIA GPU)
Grid GPU
├─ Thread Block 0 ────────────────► SM 0
│ ├─ Warp 0 (32 threads) ├─ Warp schedulers
│ ├─ Warp 1 (32 threads) ├─ Registers
│ └─ ... ├─ Shared memory / L1
├─ Thread Block 1 ────────────────► SM 1
└─ ... ...
L2 (shared across SMs)
Device memory (HBM/GDDR)
- Grid:一次 Kernel Launch 对应的 Thread Block 集合。
- Block:协作与 Shared Memory 分配的基本单位。一个 Block 的线程在同一个 SM 上执行,一个 SM 可以同时驻留多个 Block。
- Warp:NVIDIA GPU 的 32 个线程组成的调度单位。
- Thread:逻辑执行实例,并不永久绑定某个 CUDA Core。
- SM:Streaming Multiprocessor,硬件执行资源集合。Block 的执行顺序通常不保证,不能依赖不同 Block 之间的隐式同步。
基本 Vector Add:
__global__ void vector_add(
const float* A, const float* B, float* C, int N) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < N) {
C[i] = A[i] + B[i];
}
}
int threads = 256;
int blocks = (N + threads - 1) / threads;
vector_add<<<blocks, threads>>>(A, B, C, N);
__global__ 定义可由 Host 发起的 GPU Kernel;__device__ 定义设备函数;__host__ 定义 Host 函数。完整 Launch 语法是 kernel<<<gridDim, blockDim, sharedMemBytes, stream>>>(...)。
blocks = ceil(N / threads)
launched_threads = blocks × threads
extra_threads = launched_threads - N
warps_per_block = ceil(threads / 32)
当 threads = 256:
| N | Blocks | 多余线程 |
|---|---|---|
| 1 | 1 | 255 |
| 1023 | 4 | 1 |
| 1024 | 4 | 0 |
| 1000003 | 3907 | 189 |
边界判断用于避免 Out-of-bounds,不代表 GPU 没有启动这些多余线程。
1.2 Memory Hierarchy
| Memory | Scope | 特点 |
|---|---|---|
| Registers | Thread | 私有、低延迟、容量有限 |
| Shared Memory | Block | Block 内协作、显式管理、可能发生 Bank Conflict |
| L1 | SM | 硬件 Cache,具体组织依架构而定 |
| L2 | GPU | 多个 SM 共享 |
| Global Memory | Device | 容量大、相对高延迟,HBM/GDDR |
减少昂贵的数据搬运通常比单纯增加计算指令更重要。Shared Memory 并不自动比 Global Memory 更快:如果没有数据复用,引入额外拷贝、同步或资源占用,反而可能得不偿失。
1.3 Global Memory Coalescing
对于一个 Warp,理想情况下相邻线程访问相邻元素:
Coalesced: thread t -> A[t]
Strided: thread t -> A[t * stride]
在现代 NVIDIA GPU 常见的 32-byte sector 模型下,假设 FP32、32 个活跃线程、基地址对齐且不考虑 Cache 复用:
| 访问方式 | 有效数据 | 涉及 Sector | 请求覆盖字节 | 利用率 |
|---|---|---|---|---|
A[t] |
128 B | 4 | 128 B | 100% |
A[t*8] |
128 B | 32 | 1024 B | 12.5% |
Useful bytes = 32 × 4 B = 128 B
Sector utilization = useful bytes / requested sector bytes
8 倍的请求覆盖字节不等于执行时间必定增加 8 倍:实际 DRAM Traffic 还受 Cache、并行度、访问合并和硬件行为影响。
Row-major 矩阵:
offset(row, col) = row × num_cols + col
相邻线程沿列索引递增通常连续;沿行索引递增则跨行。要注意这是针对 Row-major Layout 的结论,并不是“访问列一定慢”的普遍规律。
1.4 Shared Memory Bank Conflict
以常见的 32 Banks、每个 Bank 的地址映射单位为 4 bytes 的模式为例:
bank_id = (byte_address / 4) % 32
假设 32 个线程访问不同的 FP32 地址 shared[t * stride],简化模型下冲突度为:
conflict_degree = gcd(stride, 32)
| Stride(元素) | 冲突度 |
|---|---|
| 1 | 1(无冲突) |
| 2 | 2-way |
| 3 | 1 |
| 16 | 16-way |
| 32 | 32-way |
| 34 | 2-way |
| 35 | 1 |
例外:多个线程读取同一个 Shared Memory 地址可以使用 Broadcast,不应将相同地址误判为多路冲突。实际 Bank 行为还与访问类型和硬件架构有关。
常见优化:给二维 Tile 增加 Padding,使跨行 Stride 不再是 32 的倍数。
__shared__ float tile[32][33];
Global Memory Coalescing 与 Shared Memory Bank Conflict 是不同存储层级的问题。前者关注一个 Warp 的地址请求覆盖多少内存事务/sector,后者关注同时访问哪些 Bank。
1.5 Synchronization
__syncthreads() 是 Block 级 Barrier,保证相关内存操作对 Block 内线程可见。所有应参与的线程必须在一致的控制流中到达 Barrier。
// Bad: not all threads necessarily enter the branch
if (i < N) {
tile[threadIdx.x] = input[i];
__syncthreads();
}
// Better: guard memory accesses, not the barrier
if (i < N) {
tile[threadIdx.x] = input[i];
} else {
tile[threadIdx.x] = 0.0f;
}
__syncthreads();
__syncwarp() 作用于参与的 Warp 线程;Host 侧的 CUDA Stream/Event/Device Synchronization 是另一层概念。普通 Block Barrier 不提供跨 Block 同步。
1.6 Kernel Fusion:减少中间结果物化
假设每个元素为 FP32,且中间 Tensor 不需要被其他计算保留。忽略 Cache、额外元数据和实际硬件事务,仅计算理想逻辑访存量。
C = A + B
D = C * 2
| 执行方案 | 逻辑访存量/element | Launch 数 |
|---|---|---|
| 两个独立 Kernel | 12 + 8 = 20 B | 2 |
| 一个 Fused Kernel | 12 B | 1 |
C = A + B
D = C * E
F = D + G
不融合:36 B/element;融合:20 B/element;计算量都是 3 FLOPs/element。Arithmetic Intensity 分别为 3/36 与 3/20 FLOPs/B。
Fusion 的主要收益是减少中间 Tensor 的物化、访存量和 Launch Overhead,而不是让单次内存访问本身变快。过度融合可能增加活跃变量、Register Pressure、Spilling 或跨线程通信,降低 Occupancy。
1.7 Occupancy、Bandwidth 与 Roofline
Occupancy = resident active warps per SM / maximum resident warps per SM
AI = FLOPs / bytes moved
P <= min(P_peak, BW_peak × AI)
Occupancy 是驻留 Warp 比例,不等于计算单元利用率,也不是越高必然越快。
Vector Add C=A+B:每个元素 1 FLOP、2 次 FP32 读和 1 次 FP32 写,共 12 B。
FLOPs = N
Logical bytes = 12N
AI = 1/12 FLOPs/B
Effective BW (GB/s) = 12N / (time_ms × 10^6)
若理论峰值为 60 TFLOPS、带宽 2 TB/s,则简化 Roofline 上限为 min(60, 2/12) ≈ 0.167 TFLOPS,属于低 AI 的 Memory-bound 模型。实际小 Kernel 还可能主要受 Launch/Latency 限制。
D=A*B+C:2 FLOPs(FMA 按 2 FLOPs 计),16 B,AI=0.125 FLOPs/B。
Effective Bandwidth 使用的是算法逻辑字节数,不一定等于 Profiler 测得的 DRAM Bandwidth;热 Cache 下甚至可能超过 HBM 峰值。Roofline 中 FLOPs 与 bytes 必须使用一致的定义。
1.8 实验计划与验证
Repo: 03-kernels-compilers/01-cuda-kernel/vector_add.cu
实验代码设计:固定随机种子、CPU Reference、多个非整除 N、GPU Warmup、CUDA Event 多次计时、输出误差检查和 CSV 记录。
nvcc -O3 vector_add.cu -o vector_add
./vector_add | tee results.csv
compute-sanitizer --tool memcheck ./vector_add
记录 N、Blocks、Threads、Max Error、CPU Time、GPU Time、Effective Bandwidth。可使用 Nsight Systems 观察时间线、Nsight Compute 分析 Kernel 内部指标。
CUDA Launch 对 Host 通常是异步的,不能仅在 Launch 前后使用 Host Timer 来测 GPU 执行时间。计时应使用正确的同步或 CUDA Event。较大输入用于减少 Cache 对带宽测试的干扰。
状态:Apple Silicon 本机不能运行 NVIDIA CUDA;GPU 性能尚未实测,不记录虚构结果。
2. Triton 与算子融合
2.1 Triton 位于什么层级?
Triton 是用于编写和编译块级并行 Kernel 的语言与编译器。它可以由开发者直接使用,也可以由 Inductor 等上层编译器生成。
PyTorch / handwritten Triton Python DSL
│
▼
Triton IR (TTIR) -> Triton GPU IR (TTGIR)
│
▼
LLVM IR -> PTX -> GPU machine code (SASS)
以上是典型 NVIDIA Backend 的简化路径。Triton JIT 会对编译期常量等信息进行特化,并缓存相应的编译结果。
与 CUDA 手写 Thread-level 逻辑相比,Triton 让开发者描述一组数据上的运算,编译器决定如何将数据映射到线程、Warp 和硬件资源。
| CUDA | Triton |
|---|---|
blockIdx |
tl.program_id() |
threadIdx 与显式线程计算 |
tl.arange() 等块级索引表达 |
| CUDA Thread Block | 常见 NVIDIA 路径中一个 Triton Program 对应一个 CTA |
| Block Dim | num_warps 等执行配置(不等于 BLOCK_SIZE) |
BLOCK_SIZE 描述逻辑数据块元素数量,num_warps 描述一个 Program 使用的 Warp 数。例如 BLOCK_SIZE=4096、num_warps=4 时,通常有 128 个线程,平均处理 32 个元素/线程;具体映射由编译器决定。
2.2 Pointer、Offset 与 Mask
import triton
import triton.language as tl
@triton.jit
def vector_add(A, B, C, N, BLOCK_SIZE: tl.constexpr):
pid = tl.program_id(0)
offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < N
a = tl.load(A + offsets, mask=mask, other=0)
b = tl.load(B + offsets, mask=mask, other=0)
tl.store(C + offsets, a + b, mask=mask)
Launch Grid 可设为 (triton.cdiv(N, BLOCK_SIZE),)。Triton 指针加法以元素为单位,不是字节。mask=False 的 Load 不访问对应地址,other 给出替代值;Store 的 Mask 则避免越界写入。
2.3 Shape、Stride 与 Tensor Layout
offset(i, j) = i × stride0 + j × stride1
X = torch.randn(128, 2048)
Y = X[:, :1024]
# Y.shape = (128, 1024)
# Y.stride = (2048, 1)
Shape 是逻辑尺寸,Stride 是沿某个维度移动一个元素时对应的存储偏移。Slice、Padding、Transpose 都可能使 Shape 和物理布局的关系发生变化。
如果每个 Program 处理一行,且列方向连续,则指针为 X + row * stride_x + offsets。若列 Stride 不为 1,就必须显式处理或限制输入布局。
2.4 RMSNorm
对形状 [M,H] 的输入,每行独立归一化,Weight 形状为 [H]。
mean_square = (1/H) × sum(x_i^2)
inv_rms = 1 / sqrt(mean_square + eps)
y_i = x_i × inv_rms × w_i
RMSNorm 不像 LayerNorm 那样减去均值,它使用均方根进行归一化。eps 用于数值稳定性。
若输入来自 [B,S,H],可在布局允许的情况下将 B、S 合并为 M。一个 Program 处理一个 Token(row),不需要不同 Program 之间进行归约同步。
PyTorch Reference:
import torch
def rmsnorm_reference(x, weight, eps=1e-5):
if x.shape[-1] == 0:
raise ValueError("hidden dimension must be positive")
dtype = x.dtype
x = x.float()
w = weight.float()
mean_square = (x * x).mean(dim=-1, keepdim=True)
return (x * torch.rsqrt(mean_square + eps) * w).to(dtype)
Triton 实现:
@triton.jit
def rmsnorm_kernel(X, W, Y, stride_x, stride_y, H, eps,
BLOCK_SIZE: tl.constexpr):
row = tl.program_id(0)
offsets = tl.arange(0, BLOCK_SIZE)
mask = offsets < H
x = tl.load(X + row * stride_x + offsets,
mask=mask, other=0.).to(tl.float32)
w = tl.load(W + offsets,
mask=mask, other=0.).to(tl.float32)
mean_square = tl.sum(x * x, axis=0) / H
inv_rms = tl.rsqrt(mean_square + eps)
y = x * inv_rms * w
tl.store(Y + row * stride_y + offsets, y, mask=mask)
Wrapper 应验证二维输入、CUDA Device、dtype 一致、连续的最后一维、Weight Shape [H];H>0,M=0 时直接返回空输出。学习版本可限制 H<=16384,使用 BLOCK_SIZE=triton.next_power_of_2(H)、初始 num_warps=4,Grid 为 (M,)。
这一实现只展示 Forward,并非完整 Autograd 算子,也没有为任意布局或超宽维度优化。
2.5 Reduction 与 Padding
Tree Reduction 的总工作量为 O(H),理想并行深度为 O(log H)。具体实现可以结合线程内部归约、Warp Shuffle、Shared Memory 和跨 Warp 同步。
如果 H=6、BLOCK_SIZE=8,后两个位置被 Mask,求和时用 0 作为替代值,但最终必须除以 H=6,而不是 BLOCK_SIZE=8。
| Reduction | Masked value(Identity) |
|---|---|
| Sum | 0 |
| Product | 1 |
| Max | -inf |
| Min | +inf |
Max/Min 这里以浮点类型为例。对于全负数输入,使用 0 做 Max Padding 会污染结果。H=1025 时 next_power_of_2=2048,也意味着近一半逻辑位置被 Mask,可能带来资源和调度开销。
2.6 Mixed Precision 与数值正确性
FP16/BF16 可以用于存储,但通常需要在 FP32 中进行平方和 Reduction。
例如 FP16 最大有限值为 65504,而 300^2=90000。如果先使用 FP16 平方再转换成 FP32,溢出已经发生。
因此应该先转换为 FP32,再计算平方、均值和 rsqrt,最后写回目标 dtype。
对于接近零的输入,eps 可以避免除零和分母过小;Reference 与 Triton 必须使用相同的 eps,才能进行公平比较。
2.7 Fusion 的逻辑访存模型
Manual Eager RMSNorm 可分为 Square、Mean、Add eps、Rsqrt、Normalize、Weight Multiply。假设 FP32、每行 H 元素,忽略行级标量、Cache、Spill 等:
Square: read X + write S = 8H B
Mean: read S = 4H B
Normalize: read X + write normalized = 8H B
Weight: read normalized + W + write Y = 12H B
Total = 32H B
Fused: read X + W + write Y = 12H B
Ideal logical traffic reduction = 62.5%
这是理想逻辑数据流分析,不代表实际 HBM Traffic 或实际 Speedup。Weight 可能由多个 Program 通过 Cache 复用,Native PyTorch RMSNorm 也可能已经有优化实现。
2.8 Autotuning
@triton.autotune(
configs=[
triton.Config({}, num_warps=2),
triton.Config({}, num_warps=4),
triton.Config({}, num_warps=8),
],
key=["H"],
)
@triton.jit
def rmsnorm_kernel(...):
...
这是调优结构示意(省略完整函数签名)。使用 Autotune 后由配置决定 num_warps,不应在 Launch 时重复指定同一个参数。
较少 Warp 可能使每线程工作和 Register Pressure 增加;较多 Warp 可能提高并行度,却增加跨 Warp 通信或减少可驻留 Program 数量。不能仅凭理论选出最佳配置。
调优结果按 Key 复用。本例只以 H 为 Key;真实场景还可能需要考虑 M、dtype、硬件及其他影响性能的因素。固定一行一个 Program 的算法不能任意选择小于 H 的 BLOCK_SIZE 而不修改归约逻辑。
2.9 实验与测试设计
Repo: 03-kernels-compilers/02-triton-fusion/。
对比 Manual Eager Reference、torch.nn.functional.rms_norm 和 Triton 实现。Native PyTorch Baseline 很重要:超过手写 Eager 不代表超过已有高性能算子。
测试维度:H=1、7、1023、1024、1025、4096;M=0;拒绝 H=0;FP32/FP16/BF16(视设备支持);随机输入、全零、小值和极端大值、非连续行间距。使用与 dtype 相适应的容差,比较绝对误差和带分母下限的相对误差。
记录 M、H、dtype、max_abs_error、max_rel_error、eager_ms、native_ms、triton_ms、speedup。Warmup 后通过 CUDA Event 或 triton.testing.do_bench 多次测量中位数;首次 JIT 与 Autotune 开销单独记录。
状态:GPU 实验尚未运行;不能把上面的理想访存模型当作测得的性能结果。
3. 计算图、AOTAutograd 与 Inductor
本节是本章实操最完整的一节。我们在 Apple Silicon CPU 上运行了 PyTorch 2.15.0 的 Dynamo、AOTAutograd 和 Inductor,直接观察 FX Graph、前反向图、重编译日志、Scheduler IR 和生成的 C++。以下明确区分实测结果、推断与尚未验证的假设。
3.1 Eager vs Graph Execution
Eager 模式下 Python 遇到 Tensor Operator 就通过 PyTorch Dispatcher 调用相应实现。GPU 执行可以异步进行,并非每个算子都需要 Host 等待完成。Eager 便于调试,但通常缺少跨算子的全局优化视野。
Graph Execution 则将一段计算表示成图,显式表达输入、输出、算子和依赖关系。编译器因此可以进行跨算子的 Fusion、Layout Transformation、Memory Planning 和 Code Generation。原生 Eager 算子本身也可能已经高度优化。
Python Model / torch.compile()
|
v
TorchDynamo Graph capture + Guards
|
v
FX Graph
|
v
AOTAutograd Functionalization / Decomposition
| Differentiation / Partitioning
+-------------------------------+
v v
Forward Graph Backward Graph (training)
| |
+-------------------------------+
v
TorchInductor Lowering / Fusion / Scheduling
Memory Planning / Code Generation
|
+-------------+--------------+
v v v
CPU C++ GPU Triton External Libraries
+-------------+--------------+
v
Hardware execution
这是默认 Inductor Backend 的典型抽象流程,不是每次调用必须走过的全部步骤。推理不需要反向图;训练的反向代码编译也可能延迟到首次 backward。torch.compile() 是入口,不等于某个单独的优化 Pass。Triton 是可选的下层 Kernel 编译路径,不是 Inductor 的唯一输出。
数据库类比:Python/SQL 表达 What to compute,FX Graph/Logical Plan 表达计算关系,Inductor/Physical Planner 决定 How to compute,生成 Kernel/Execution Engine 执行物理计划。这个类比并非严格的一一对应。
3.2 Dynamo:捕获、FX Graph 和 Guards
Dynamo 利用 CPython Frame Evaluation 机制分析 Python Bytecode,将可捕获的 Tensor Operations 表达成 FX Graph。图可以是具有分支与汇合的 DAG,而非简单的线性序列。
def f(x):
a = x * 2
b = x + 1
return a + b
这里 a、b 都依赖 x,但彼此不依赖,最终 Add 依赖二者。编译器可以分析依赖、重复计算、生命周期和融合机会。
Guards 是对编译时假设的运行时验证,例如 Tensor Shape、dtype、device、stride、Python Scalar、对象属性和运行状态。如果某个缓存版本的 Guards 不匹配,Dynamo 尝试其他适用版本;没有匹配版本时可能重新捕获、编译,或在达到限制时回退。
Guard Failure 不是 Cache Staleness。 例如 B=32 的版本不适用于 B=64,但仍然可能在之后的 B=32 请求中复用。它的适用条件不匹配,并不意味着旧版本过期。
3.3 Graph Break 与 Recompilation
def f(x):
a = x * 2
print("intermediate")
return torch.relu(a) + 1
在默认不捕获该打印的情况下,Dynamo 可能将图切成两段,中间执行 Python 逻辑,然后恢复捕获。显式 torch._dynamo.graph_break() 可用于教学实验。
Without break: [ Mul -> ReLU -> Add ] one graph
With break: [ Mul ] -> Python -> [ ReLU -> Add ]
切图可能迫使中间结果物化,限制跨图 Fusion,增加 Python Dispatch、Guard 检查和执行边界开销。但 Graph Break 本身并非错误,某些 Host Logic 或高频重编译区域也可能值得有意隔离。
| 概念 | Graph Break | Recompilation |
|---|---|---|
| 原因 | 当前区域无法继续捕获 | 缓存版本的适用条件不匹配 |
| 结果 | 一个函数拆成多个图 | 同一图区域出现多个版本 |
| 成本 | 减少优化范围、增加执行边界 | 额外编译延迟和缓存压力 |
| 排查 | graph_breaks、fullgraph=True |
recompiles、guards、dynamic |
一个完整的 Graph 仍可能频繁 Recompile;一个具有多个 Graph Break 的函数也可能复用所有已有版本。Graph、Operator、Kernel 是不同粒度:一个 Graph 可以包含多个 Operator,最终生成一个或多个 Kernel/Library Calls。fullgraph=True 要求捕获区域不发生 Graph Break,并非要求生成单一 Kernel。
Metadata-dependent vs Data-dependent
| 条件 | 类型 |
|---|---|
x.shape[0] > 32 |
Metadata-dependent |
x.dtype == torch.float16 |
Metadata-dependent |
x.stride(0) == 1024 |
Metadata-dependent |
x[0, 0] > 0 |
Data-dependent |
x.sum() > 0 |
Data-dependent |
判断方法:保持 Shape、Layout、dtype 等 Metadata 不变,只替换 Tensor 内的数值,条件结果是否可能改变?如果会,就依赖实际数据。索引本身已知,不代表索引指向的数值已知。
Shape 条件通常可通过特化或符号约束和 Guards 表达。普通 Python 的 Data-dependent Branch 通常更难捕获,还可能在 GPU 上引入 Device-to-Host Synchronization。torch.cond 可将条件与分支显式表达为图内计算,但存在自身的输入输出及算子支持约束。
3.4 实验 A:观察真实的 FX Graph
实验模型:
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(128, 512)
self.fc2 = nn.Linear(512, 128)
def forward(self, x):
x = self.fc1(x)
x = torch.nn.functional.gelu(x)
x = self.fc2(x)
x = torch.relu(x)
x = x * 2.0
return x + 1.0
自定义 Backend 用于观察 Dynamo 的输出,而不是生成优化后的机器码:
def inspect_backend(gm, example_inputs):
print(gm.graph)
print(gm.code)
gm.graph.print_tabular() # optional: requires tabulate
return gm.forward
compiled_model = torch.compile(model, backend=inspect_backend,
fullgraph=True)
第一次实测成功进入 Backend 并打印图,但 print_tabular() 因缺少 tabulate 抛出 BackendCompilerFailed。可安装 python -m pip install tabulate 或删除这一行。该报错并非 Dynamo Capture 失败;当时的这一轮输出数值对比尚未执行,后续 Inductor Benchmark 完成了模型输出的对比验证。
真实图包含 5 个 Placeholder、6 个 call_function 和 1 个 Output(共 12 个节点):
| 节点 | 计算或输入 | Shape |
|---|---|---|
| w1 | fc1.weight | [512,128] |
| b1 | fc1.bias | [512] |
| input | x | [32,128] |
| w2 | fc2.weight | [128,512] |
| b2 | fc2.bias | [128] |
| x | linear(input,w1,b1) | [32,512] |
| x_1 | gelu(x) | [32,512] |
| x_2 | linear(x_1,w2,b2) | [32,128] |
| x_3 | relu(x_2) | [32,128] |
| x_4 | mul(x_3,2) | [32,128] |
| x_5 | add(x_4,1) | [32,128] |
| output | (x_5,) | [32,128] |
Parameter Lifting:虽然 Python 接口只有 model(x),权重与 Bias 在捕获后的 Graph 中成为显式输入。
num_users=1 表示结果只被一个不同的 FX Node 使用(不是总 Operand 次数)。多个 Consumer 会影响物化、复用与融合决策。
实际 Generated Python 中出现:
x_1 = torch._C._nn.gelu(x); x = None
x_3 = torch.relu(x_2); x_2 = None
x_4 = x_3 * 2.0; x_3 = None
这是 Last Use 后解除 Python 引用的表现,不意味着底层 Storage 一定立即释放,也不证明已经发生 Inductor Buffer Reuse;仍须考虑其他引用、Alias、Autograd 和 Allocator。
3.5 AOTAutograd:自动微分与图划分
AOTAutograd 将可微计算转换为可供编译器优化的前向与反向图。主要概念:
- Functionalization:将 Mutation 和 View/Alias 关系转换成更便于分析的函数式表达,同时保留原语义及外部可观察修改。
- Decomposition:将部分复杂算子分解为更基础的 ATen Operations,暴露内部计算结构。
- Partitioning:确定 Forward 和 Backward 的边界,哪些值保存,哪些可以重计算。
Decomposition 与 Fusion 不矛盾:前者打开数学结构,后者重新安排物理执行边界。某些高性能 Library Operation 则可能保留为独立调用。
训练时梯度可能依赖 Forward 的中间值。若中间值大、重计算便宜,且必要输入仍可用,则重计算可能减少 Activation Memory;在 Memory-bound 场景中,重新计算甚至可能比加载中间结果更快。这是 Activation Checkpointing 和部分 Attention Backward 实现的共同思想。
3.6 实验 B:真实 AOTAutograd 前反向图
def loss_fn(x, w):
y = x * w
return (y * y).mean()
x = torch.randn(8, requires_grad=True)
w = torch.randn(8, requires_grad=True)
compiled_loss = torch.compile(loss_fn, backend="aot_eager", fullgraph=True)
loss = compiled_loss(x, w)
loss.backward()
TORCH_LOGS="aot_graphs" python inspect_autograd.py 2>&1 | tee runs/autograd.log
数学表达(N=8):
真实日志中的 Forward Graph(省略类型与无关日志前缀):
def forward(self, primals_1, primals_2):
mul = torch.ops.aten.mul.Tensor(primals_1, primals_2)
mul_1 = torch.ops.aten.mul.Tensor(mul, mul)
mean = torch.ops.aten.mean.default(mul_1)
return (mean, primals_1, primals_2)
其中 primals_1=x、primals_2=w。用户可见结果仍是标量 loss,但 Forward 内部返回 x、w 供 Backward 使用。
真实 Backward Graph(省略解除引用语句):
def forward(self, primals_1, primals_2, tangents_1):
expand = torch.ops.aten.expand.default(tangents_1, [8])
div = torch.ops.aten.div.Scalar(expand, 8)
mul = torch.ops.aten.mul.Tensor(primals_1, primals_2)
mul_2 = torch.ops.aten.mul.Tensor(div, mul)
add = torch.ops.aten.add.Tensor(mul_2, mul_2)
mul_4 = torch.ops.aten.mul.Tensor(add, primals_1)
mul_5 = torch.ops.aten.mul.Tensor(add, primals_2)
return (mul_5, mul_4)
| Node | 语义 |
|---|---|
| tangents_1 | 上游梯度;标量 loss.backward() 默认传入 1 |
| expand | 将标量梯度逻辑扩展到 8 个元素 |
| div | Mean 的梯度:每个元素 1/8(一般为上游梯度除以 8) |
| mul | 重计算 y=x*w |
| mul_2 | 梯度贡献 y/8 |
| add | y*y 两条输入路径的梯度累加,得到 2y/8 |
| mul_4 | dw=dy*x |
| mul_5 | dx=dy*w |
| return | 按 Forward 输入顺序返回 dx、dw |
y*y 的两个 Operand 都引用 y,因此反向传播中两个贡献相加,而不一定直接出现 *2。
实际观察到 Recomputation
Forward: x,w -> y=x*w -> z=y*y -> mean(z)
returns loss + x,w (does not save y)
|
Backward: saved x,w + incoming gradient
-> recompute y=x*w -> dy -> dx,dw
x、w 本来就是梯度计算所需的值,因此本次图划分没有额外保存 y,而选择重新执行便宜的逐元素乘法。日志确认了生成图的这一行为,但不能仅凭日志确定 Partitioning 的具体成本模型。
Metadata、Zero Stride、FakeTensor
| 日志字段 | 含义 |
|---|---|
f32[8][1]cpu |
FP32,shape=(8,),stride=(1,),CPU |
f32[][]cpu |
零维标量 Tensor |
f32[8][0]cpu |
8 个逻辑元素共享一个存储位置的 View |
is_leaf=True |
Autograd 叶子 Tensor |
mutates_data=False |
输入数据未被原地修改 |
mutates_metadata=False |
输入 Metadata 未被修改 |
requires_grad=True |
需要梯度 |
OutputType.non_alias |
输出非输入 Alias |
saved_tensor_is_graph_input=[True, True] |
保存的两个 Tensor 都是图输入 |
expand() 使用 stride=0 让每个逻辑位置指向同一物理地址,offset(i)=i*0=0,无需真的复制 8 份标量。下一步 div 则产生 stride=1 的结果。
FakeTensor 可模拟 Shape、Stride、dtype、Device 和输出 Metadata,不需要实际执行对应的大规模数值运算。例如仅由 A=[1024,4096] 和 B=[4096,8192] 即可推导 MatMul 输出 [1024,8192]。
ATen 是 PyTorch 的底层 Tensor Operator 接口体系。torch.ops.aten.mul.Tensor 表达明确的算子语义,而不是某个特定 CPU/GPU 指令。
实测 Loss:0.43576735258102417。
x.grad = [ 3.3064e-03, 5.9900e-02, -2.9093e-02, -6.0232e-01,
-3.4334e-04, -5.2726e-02, -5.0006e-06, 2.6180e-01]
w.grad = [ 7.8569e-03, 1.1823e-01, -2.2115e-02, -4.5813e-01,
9.7252e-06, -9.4385e-02, -8.4131e-04, 4.3766e-02]
Forward 与 Backward 成功执行,但这份脚本没有独立比较 Eager 梯度,因此不能声称已完成梯度数值等价测试。
3.7 Inductor:Lowering、Fusion、Memory Planning
Lowering 将高层算子表示转换为更接近目标执行的 IR。例如 relu(x+b) 可变成逐元素循环,随后选择 SIMD、线程并行或 GPU Kernel。
主要优化包括 Fusion、Layout、Loop Scheduling、Buffer Lifetime Analysis、Memory Planning、Dead Code Elimination、Constant Folding、Autotuning 和目标代码生成。并非每项都会应用于每个模型。
| Kernel Fusion | Memory Planning |
|---|---|
| 避免产生不必要的物化中间结果 | 为必须存在的 Buffer 规划存储和复用 |
| 减少数据搬运与执行边界 | 降低峰值内存与分配成本 |
| 可能减少 Kernel 数量 | 不一定改变 Kernel 数量 |
当一个 Buffer 的最后一个 Consumer 完成且不存在危险的别名、额外引用等约束时,其存储可能被复用。编译器也可能保留 GEMM Library Call,而不是生成自己的 MatMul Kernel。
3.8 Dynamic Shape、Specialization 与缓存
torch.compile 参数 |
语义 |
|---|---|
dynamic=False |
主要静态特化 |
dynamic=True |
尽可能从开始使用动态尺寸 |
dynamic=None |
默认,通常先特化,再尝试动态化发生变化的维度 |
例如输入 [B,128],B=32、64、128。静态模式可能为每个 B 建立版本;动态模式用符号 B 表示可变化的维度,并附带范围、相等关系、整除等约束。动态 Shape 并不保证永不重编译。
Static Shape 提供更多编译时信息,可能帮助 Tiling、Unroll、Mask 简化和 Kernel 选择;Dynamic Shape 则提高复用率、减少 Cold Request Latency。
Serving 层还可选择 Shape Bucketing,例如将 Sequence Length 101、128 归到 128,将 193、255 归到 256。通过有限特化版本换取缓存稳定性,代价是 Padding 和无效计算。这是可选的系统设计,不是 Dynamo 自动保证的功能。
3.9 实验 C:Eager vs Inductor Benchmark(真实数据)
环境:Apple Silicon CPU、PyTorch 2.15.0、FP32、4 CPU Threads;MLP 128→512→128,GELU 与 ReLU+Mul+Add;eval() 与 no_grad();Warmup 20 次,重复测量 100 次,取 Median 与近似 P95。输入 Batch 顺序 [32,64,128,32,64,256]。
记录指标:Wrapper Creation、First Invocation(可能含 Capture、Compilation、Cache Lookup 与执行)、Steady-state Median/P95、Max Abs/Rel Error、Speedup。普通 CPU 运算不需要 CUDA Synchronization;GPU Benchmark 必须处理异步执行。
TORCH_LOGS="graph_breaks,recompiles" \
python benchmark_mlp.py --dynamic false \
2> runs/static.log | tee runs/static.csv
TORCH_LOGS="graph_breaks,recompiles" \
python benchmark_mlp.py --dynamic true \
2> runs/dynamic.log | tee runs/dynamic.csv
两组全部 12 行测试的 Max Abs Error 和 Max Rel Error 都为 0(仅限测试输入)。Wrapper Creation:Static 1098.814 ms;Dynamic 1144.727 ms。
Static 原始测量(单位 ms,Speedup 无量纲):
| B | Visit | Eager First | Compiled First | Eager Median | Compiled Median | Eager P95 | Compiled P95 | Speedup |
|---|---|---|---|---|---|---|---|---|
| 32 | 1 | 10.247000 | 1784.833083 | 0.047250 | 0.075771 | 0.048084 | 0.107959 | 0.624 |
| 64 | 1 | 0.140542 | 46.300834 | 0.068834 | 0.099417 | 0.074000 | 0.131083 | 0.692 |
| 128 | 1 | 0.280000 | 26.426250 | 0.104021 | 0.137062 | 0.128833 | 0.149083 | 0.759 |
| 32 | 2 | 0.070541 | 0.096459 | 0.044583 | 0.083375 | 0.047709 | 0.099959 | 0.535 |
| 64 | 2 | 0.086500 | 0.106042 | 0.068667 | 0.096042 | 0.072375 | 0.116333 | 0.715 |
| 256 | 1 | 0.279000 | 27.739625 | 0.163375 | 0.182020 | 0.173459 | 0.192667 | 0.898 |
Dynamic 原始测量(单位 ms):
| B | Visit | Eager First | Compiled First | Eager Median | Compiled Median | Eager P95 | Compiled P95 | Speedup |
|---|---|---|---|---|---|---|---|---|
| 32 | 1 | 0.343666 | 1037.450208 | 0.047917 | 0.079583 | 0.048792 | 0.105250 | 0.602 |
| 64 | 1 | 0.135416 | 0.125250 | 0.068104 | 0.096813 | 0.073750 | 0.131291 | 0.703 |
| 128 | 1 | 0.384292 | 0.157917 | 0.104563 | 0.138084 | 0.129041 | 0.160959 | 0.757 |
| 32 | 2 | 0.092125 | 0.085875 | 0.043271 | 0.078917 | 0.047459 | 0.093875 | 0.548 |
| 64 | 2 | 0.076875 | 0.089458 | 0.068896 | 0.093375 | 0.075625 | 0.109333 | 0.738 |
| 256 | 1 | 0.196250 | 0.185208 | 0.165354 | 0.183146 | 0.173917 | 0.207333 | 0.903 |
实际 Guard Failure 日志
Static 日志(缩写保留所有 Guard Failure):
[0/1] Recompiling function forward
0/0: tensor 'x' size mismatch at index 0. expected 32, actual 64
[0/2] Recompiling function forward
0/1: expected 64, actual 128
0/0: expected 32, actual 128
[0/3] Recompiling function forward
0/1: expected 64, actual 256
0/0: expected 32, actual 256
0/2: expected 128, actual 256
Dynamic 的 runs/dynamic.log 为空,没有观察到 Graph Break 或 Recompilation。Static 也没有记录 Graph Break。结果:Static 4 个编译版本、3 次重编译;Dynamic 在测试范围内没有重编译,结合耗时推断复用了一个动态版本,但未直接打印其 Symbolic Guards。
Static: B32 -> V0 B64 -> V1 B128 -> V2
B32 -> V0 B64 -> V1 B256 -> V3
Dynamic: B32 -> V0 B64 -> V0 B128 -> V0
B32 -> V0 B64 -> V0 B256 -> V0
Dynamic Shape 的主要收益是避免新 Shape 的重编译延迟,而不是必然提升单次计算速度。本次两组 Compiled 稳态延迟相近,未显示明显动态化性能损失。
反直觉结果:Compiled 比 Eager 慢
初次访问各 Batch 的中位数(单位 μs):
| B | Eager(Static 组) | Static | Dynamic |
|---|---|---|---|
| 32 | 47.250 | 75.771 | 79.583 |
| 64 | 68.834 | 99.417 | 96.813 |
| 128 | 104.021 | 137.062 | 138.084 |
| 256 | 163.375 | 182.020 | 183.146 |
两种 Compiled 在正常 Benchmark 中均未超过各自 Eager Baseline;随着 B 增大,首次访问 Shape 的 Speedup 接近 1,但仍小于 1。
潜在解释(均未通过 Profiler 确认 Root Cause):Compiled Wrapper/Guards/Buffer Allocation 等固定开销、小型 MLP 的 Linear 已使用优化底层算子、CPU Cache 降低 Fusion 节省的真实访存成本、OpenMP 线程调度开销等。
Amdahl's Law(假设其他部分不变且没有新增开销):
p 是可优化部分占原耗时比例,s 是该部分加速倍数。若 p=10%,即使 s 趋于无穷,整体也最多约 1.11 倍。这解释了为什么优化局部 Elementwise 操作不保证端到端获益。
这些结果只适用于当前 CPU、模型、输入和实验条件,不能推广为 GPU 上 Inductor 更慢。
3.10 实验 D:Fresh Cache 与 Debug Artifacts
TORCHINDUCTOR_CACHE_DIR="$(mktemp -d)" \
TORCH_COMPILE_DEBUG=1 \
python benchmark_mlp.py --dynamic false \
2>&1 | tee runs/inductor_debug.log
生成了 4 套 Debug Trace,分别对应 B=32、64、128、256。以 B=32 为例:
torch_compile_debug/run_2026_11_29_20_43_13_851217-pid_48425/
torchinductor/model__0_inference_0.0/
fx_graph_readable.py
fx_graph_runnable.py
fx_graph_transformed.py
inductor_provenance_tracking_node_mappings.json
ir_pre_fusion.txt
ir_post_fusion.txt
output_code.py
Fresh Cache + Debug 的 First Invocation 对比(ms):
| B | 原 Static 实验 | Fresh Cache + Debug |
|---|---|---|
| 32 | 1784.833083 | 6475.965291 |
| 64 | 46.300834 | 1044.593833 |
| 128 | 26.426250 | 791.224666 |
| 256 | 27.739625 | 763.051709 |
同时改变 Cache Directory 和 Debug 设置,不能把全部时间差归因于磁盘 Cache Miss。Dynamo 进程内 Guard/Graph Cache 与 Inductor 编译产物缓存是不同层级:Dynamo Recompile 不必然意味着底层机器码也完全从头生成。
Debug 运行全部输出误差依旧为 0,但性能测量出现噪声,例如 B128 Compiled Median=429.375 μs、P95=1273.667 μs;B32 第二次访问 Eager Median=165.605 μs,明显高于此前。原因未查明,不把 Debug 运行作为最终性能比较依据。
3.11 实验 E:真实 Pre-fusion / Post-fusion IR
以 B=32 的两份 Scheduler IR 为例,均包含如下四个节点(摘录并简化):
| Node | 类型 | Input -> Output | Shape | 计算 |
|---|---|---|---|---|
| op0 | ExternKernelSchedulerNode | W1,b1,X -> buf0 | [32,512] | extern_kernels.addmm |
| op1 | SchedulerNode(ComputedBuffer) | buf0 -> buf1 | [32,512] | GELU |
| op2 | ExternKernelSchedulerNode | W2,b2,buf1 -> buf2 | [32,128] | extern_kernels.addmm |
| op3 | SchedulerNode(ComputedBuffer) | buf2 -> buf3 | [32,128] | ReLU, Mul, Add |
两份 IR 都已经将 ReLU、Mul、Add 放在同一个 op3_loop_body:
# 摘录:ir_pre_fusion.txt / ir_post_fusion.txt
class op3_loop_body:
var_ranges = {p0: 4096}
index0 = p0
def body(self, ops):
get_index = self.get_index('index0')
load = ops.load('buf2', get_index)
relu = ops.relu(load)
constant = ops.constant(2.0, torch.float32)
mul = ops.mul(relu, constant)
constant_1 = ops.constant(1.0, torch.float32)
add = ops.add(mul, constant_1)
get_index_1 = self.get_index('index0')
store = ops.store('buf3', get_index_1, add, None)
return store
说明本次计算在 Scheduler Fusion Pass 前就已经组合成一个 Loop Body;不能简单把融合都归于 Pre/Post 之间的 Pass。没有出现 FusedSchedulerNode 也不代表没有融合。
GELU 则在 op1 中以 0.5*x*(1+erf(x/sqrt(2))) 表达。两次 Linear 由 extern_kernels.addmm 表达,即 Bias + MatMul,不从这份代码推断具体 BLAS 库实现。
MemoryDep 显式描述 Buffer 的访问依赖,StarDep 表示更粗粒度的 Buffer 依赖;FixedLayout 记录设备、dtype、Shape 和 Stride。can_inplace=True 为可能的原地复用提供线索,但是否真正复用需要看最终代码。
3.12 实验 F:真实生成的 C++ 与 Buffer Reuse
最终 output_code.py 包含两个生成的 C++ Kernel:
// cpp_fused_gelu_0, 摘录核心运算,省略错误处理和边界检查
#pragma omp parallel num_threads(4)
{
#pragma omp for
for (int64_t x0 = 0; x0 < 16384; x0 += 4) {
auto v = at::vec::Vectorized<float>::loadu(in_out_ptr0 + x0, 4);
auto a = v * at::vec::Vectorized<float>(0.5f);
auto b = v * at::vec::Vectorized<float>(0.7071067811865476f);
auto result = a * (b.erf() + at::vec::Vectorized<float>(1.0f));
result.store(in_out_ptr0 + x0);
}
}
// cpp_fused_add_mul_relu_1, 摘录核心运算,省略错误处理和边界检查
#pragma omp parallel num_threads(4)
{
#pragma omp for
for (int64_t x0 = 0; x0 < 4096; x0 += 4) {
auto tmp0 = at::vec::Vectorized<float>::loadu(in_out_ptr0 + x0, 4);
auto tmp1 = at::vec::clamp_min(tmp0, decltype(tmp0)(0));
auto tmp4 = tmp1 * at::vec::Vectorized<float>(2.0f);
auto tmp7 = tmp4 + at::vec::Vectorized<float>(1.0f);
tmp7.store(in_out_ptr0 + x0);
}
}
两个片段依据真实生成代码缩写,非完整可独立编译文件。循环步长 4,Vectorizedin_out_ptr0 同时读写,直接证明此处原地更新。
真实 Wrapper 的核心调用(省略部分断言、引用释放和调试注释):
buf0 = empty_strided_cpu((32, 512), (512, 1), torch.float32)
extern_kernels.addmm(arg1_1, arg2_1,
reinterpret_tensor(arg0_1, (128, 512), (1, 128), 0),
alpha=1, beta=1, out=buf0)
buf1 = buf0; del buf0 # reuse
cpp_fused_gelu_0(buf1)
buf2 = empty_strided_cpu((32, 128), (128, 1), torch.float32)
extern_kernels.addmm(arg4_1, buf1,
reinterpret_tensor(arg3_1, (512, 128), (1, 512), 0),
alpha=1, beta=1, out=buf2)
del buf1
buf3 = buf2; del buf2 # reuse
cpp_fused_add_mul_relu_1(buf3)
return (buf3,)
reinterpret_tensor 将原始 Linear 权重以转置 Shape 和 Stride 解释,无需此处显式复制转置数据(外部算子内部是否额外处理布局未检查)。buf1 = buf0、buf3 = buf2 证实了 Buffer Reuse。
X [32,128]
|
v
Linear 1: external addmm -> allocate buf0 [32,512]
|
v
GELU: generated SIMD/OpenMP C++ -> reuse buf0 as buf1
|
v
Linear 2: external addmm -> allocate buf2 [32,128]
|
v
ReLU + Mul + Add: fused SIMD/OpenMP C++ -> reuse buf2 as buf3
|
v
Y [32,128]
原始六个算子变成四个主要计算调用,其中两个为外部 addmm、两个为生成 C++。外部调用内部的实际执行步骤没有进一步分析。
实验最重要的结论:编译器确实实现了 Fusion、Buffer Reuse、SIMD 和多线程,但本次正常 Benchmark 仍然没有端到端加速。 不能仅凭 Kernel 数量、优化名称或生成代码的复杂度判断性能。
3.13 编译成本摊销与 Debugging 方法
如果 Compiled 稳态比 Eager 快,且只需一次额外编译,简化的盈亏平衡点为:
例如额外编译 5s,每次 Eager 2ms、Compiled 1ms,约需 5000 次调用抵消编译成本。若 Compiled 稳态反而更慢,则此简化模型下无法靠重复执行摊销。
分层故障隔离:
| Backend | 覆盖范围 |
|---|---|
| 普通 Eager | 无 Dynamo 图编译 |
backend="eager" |
Dynamo 捕获、以 Eager 执行图 |
backend="aot_eager" |
Dynamo + AOTAutograd、以 Eager 执行转换后的图 |
backend="inductor" |
Dynamo + AOTAutograd + Inductor 及下游工具链 |
前两种编译 Backend PASS 而 Inductor FAIL,应优先调查 Inductor Lowering、Scheduling、Codegen、C++/Triton Compiler、Library 和工具链,而非先怀疑 Graph Capture。这是缩小故障域,不是绝对排除上游问题。
| 工具 | 观察内容 |
|---|---|
TORCH_LOGS="graph_breaks" |
Graph Break 原因和位置 |
TORCH_LOGS="recompiles" |
Guard Failure / 重编译 |
TORCH_LOGS="guards,dynamic" |
适用条件及符号 Shape |
TORCH_LOGS="aot_graphs" |
前反向图 |
TORCH_LOGS="output_code" |
生成代码 |
TORCH_COMPILE_DEBUG=1 |
编译阶段 IR、代码与 Debug Trace |
torch.profiler |
实际运行 Timeline 和算子耗时 |
fullgraph=True |
主动暴露 Graph Break |
测试方法:先比较正确性,再分别测量 Cold Start 与 Steady State;记录 Warmup、重复次数、Cache 状态、dtype、Shape、线程数及硬件。性能 Benchmark 与 Debug/Profiling 可以独立运行。切勿仅报告最快一次或把整个含 I/O 的脚本总耗时归因于编译器。
本次已完成核心 CPU 实操;显式 Graph Break Demo、独立梯度对比、Auto Dynamic 模式、大 Batch 扩展和性能 Root Cause Profiling 未提供实际结果,留作可选实验。
4. MLIR、XLA 与 TVM
4.1 为什么需要多层 IR?
IR(Intermediate Representation)提供了编译过程中表达计算的共同语言。不同抽象层保留不同信息:
| IR 层级 | 表达 | 适合优化 |
|---|---|---|
| Graph / Tensor IR | 算子、Shape、依赖、Reduction | 图融合、代数化简、Shape 推导 |
| Structured Tensor Program | 迭代空间、索引、计算结构 | Tiling、结构化融合、Tensorization |
| Loop / Buffer IR | 循环、内存、布局、访问 | Loop Order、Bufferization、Vectorization |
| Hardware-specific IR | 并行映射、设备指令和内存作用域 | 硬件相关调度和代码生成 |
过早转换成机器指令会让 MatMul、Reduction 等高层数学结构难以识别,从而限制全局优化机会。不是机器码不能优化,而是高层语义在低层表达中不容易恢复。
公共 IR 也帮助解耦多个前端与后端。在理想模型中,F 个前端与 H 个硬件后端的适配路径从 O(F*H) 减少至 O(F+H)。实际仍需处理语义差异、算子覆盖和硬件特性,不能将此简化为真实工程成本公式。
4.2 MLIR 与 Dialect
MLIR(Multi-Level Intermediate Representation)属于 LLVM 生态,是构建编译器的基础设施,而非单一模型编译器、Runtime 或万能算子库。核心是允许多种 Dialect 共存,并通过 Pass 逐步 Lowering(Progressive Lowering)。
| Dialect | 关注内容 | 示例 |
|---|---|---|
| stablehlo / tosa | 高层机器学习 Tensor Operations | stablehlo.dot_general |
| linalg | 结构化线性代数 | linalg.matmul |
| tensor | 张量操作 | tensor.extract_slice |
| arith | 基础算术 | arith.addf |
| scf / affine | 结构化或仿射循环、控制流 | scf.for |
| memref | 内存引用与布局 | memref.load |
| vector | 向量计算 | vector.transfer_read |
| gpu / nvvm | GPU 执行与 NVIDIA 相关表达 | gpu.launch |
| llvm | 接近 LLVM IR 的表示 | llvm.load |
不同 Dialect 不仅表示不同层级,也可以表达同一层级的不同领域。MLIR 没有要求每个编译栈遵循同一条 Dialect Pipeline。
func.func @add(%a: f32, %b: f32) -> f32 {
%c = arith.addf %a, %b : f32
return %c : f32
}
func.func 与 arith.addf 属于不同 Dialect,%a、%b、%c 为 SSA Values。
SSA(Static Single Assignment)要求每个 SSA Value 只定义一次:
x0 = a + b
x1 = x0 * 2
x2 = x1 + 1
这样便于 Def-Use、Liveness、CSE、Dead Code Elimination 等分析。SSA 不代表内存不可修改,仍需跟踪 Memory Effects 和 Aliasing。
4.3 Compiler Pass 与 Bufferization
Pass 对 IR 执行一次分析或转换。Pass Pipeline 将多种优化按照适当顺序组织,但不是固定单向流程,一种 Pass 也可能反复执行。
| Pass | 作用 |
|---|---|
| Canonicalization | 规范化等价表达 |
| Constant Folding / Propagation | 计算或传播已知常量 |
| CSE | 消除可安全复用的公共子表达式 |
| DCE | 删除无用且无必要副作用的计算 |
| Fusion | 合并计算区域 |
| Tiling | 组织迭代空间、增强数据复用 |
| Bufferization | 从 Tensor Value 转为具有存储语义的表示 |
| Vectorization | 将适合的计算映射为向量操作 |
| Dialect Conversion | 转换为目标 Dialect 表达 |
每种优化依赖的信息不同:Fusion 需要算子依赖和语义,Tiling 需要迭代空间,Bufferization 需要 Alias、读写关系等,Vectorization 需要 Loop、Layout、硬件能力等。Pass 顺序应尽可能保留相应信息。
Bufferization 决定 Tensor 结果如何由具体存储表达,包括是否分配新 Buffer、何时安全复用输入。上一节 Inductor 实际观察到的 buf1=buf0 解决的是相似的内存问题,但并非调用 MLIR Bufferization Pass。
4.4 XLA、StableHLO、MLIR 与 Triton 的关系
XLA(Accelerated Linear Algebra)是 OpenXLA 生态中的机器学习编译器,与 JAX、TensorFlow、PyTorch/XLA 等前端集成,在 TPU 生态尤其重要。HLO 是其重要高层计算表示,StableHLO 则是基于 MLIR 的具有兼容性目标的算子规范和 Dialect。
JAX / supported framework integration
|
v
StableHLO (MLIR-based dialect / portable representation)
|
v
XLA HLO optimization + target-specific planning
|
+-----------+------------+
v v v
Triton Native Optimized
codegen codegen library calls
+-----------+------------+
v
GPU execution
上图以可选 GPU 路径为例。XLA 可进行 HLO Fusion、Algebraic Simplification、Layout、Buffer Assignment、Scheduling,并根据 Backend 选择原生 Codegen、Triton 或已有 Library Calls。CPU、TPU 路径与 GPU 不同;各前端接入的 IR 流程也不必完全一致。
MLIR 可以用于高层 StableHLO,也可以用于 Triton 自身内部的编译 IR;它并不是 XLA 固定执行链中的某一个独立阶段。Triton 同样可以被 Inductor 作为可选 GPU Codegen 路径。
| 技术 | 本质 | 主要职责 |
|---|---|---|
| MLIR | Compiler Infrastructure | 定义多种 IR、Dialect、Pass、Conversion |
| StableHLO | 算子规范及 MLIR Dialect | 表达高层 ML 计算与兼容接口 |
| XLA | ML Compiler | 优化计算图、选择硬件执行方案 |
| TVM | ML Compiler & Deployment Stack | 图和 Tensor Program 优化、调优、部署 |
| Inductor | PyTorch Compiler Backend | FX/ATen 图的 Lowering、调度、生成代码 |
| Triton | Kernel DSL & Compiler | 编译块级并行 Kernel |
| LLVM | Compiler Infrastructure | 较低层 IR 优化和机器码生成 |
这些不是全部相互替代的技术。XLA、TVM、Inductor 比较接近模型编译系统;Triton 与 CUDA C++ 属于 Kernel 实现路径;MLIR 与 LLVM 则是覆盖不同且部分重叠层级的基础设施。
4.5 TVM:Computation vs Schedule
Apache TVM 是面向机器学习编译、Tensor Program 优化和部署的开源项目。现代架构包含 Relax(高层图及符号 Shape/Dataflow)和 TensorIR(Loops、Buffers、Blocks),并支持跨层联合优化。旧资料常见 Relay、TE、AutoTVM、Ansor 等术语。
Frontend -> Relax <-> TensorIR -> Target Code -> Runtime
^
|
Schedule / MetaSchedule
关键思想:分离计算定义(What)和执行调度(How)。
相同的数学定义可采用不同 Loop Order。假设矩阵为 Row-major、C 已清零:
# i-j-k: 内层 k 变化,B[k,j] 的元素步长为 N
for i in range(M):
for j in range(N):
for k in range(K):
C[i, j] += A[i, k] * B[k, j]
# i-k-j: 内层 j 变化,连续访问 B 和 C
for i in range(M):
for k in range(K):
for j in range(N):
C[i, j] += A[i, k] * B[k, j]
第二种通常更有利于 Row-major Cache Locality 和 SIMD,但还需考虑 C 重复更新、Cache 容量、编译器优化及浮点数值语义。不能普遍断言某一种 Loop Order 必然最快。
| Schedule Primitive | 含义 |
|---|---|
| split / tile | 拆分循环、数据分块 |
| reorder | 改变循环顺序 |
| fuse | 合并循环迭代空间(区别于 Graph Fusion) |
| parallel / bind | 映射 CPU 线程或 GPU 执行维度 |
| vectorize / unroll | 向量化或展开循环 |
| cache_read / cache_write | 引入指定存储作用域的 Buffer |
| tensorize | 将匹配的计算块映射到专用指令/Intrinsic |
Tensorization 要求计算结构、dtype、Tile Shape、Layout 等满足硬件约束,例如将适合的矩阵计算块映射到 Tensor Core MMA Intrinsic。
4.6 MetaSchedule 与 Autotuning
Tensor Program + Target Hardware
-> Search Space (tiling, loop order, thread mapping ...)
-> Cost Model / Search Strategy
-> Compile and measure candidate schedules on target hardware
-> Feedback / select best observed schedule
-> Tuning Database
理论成本模型无法准确覆盖 Cache Hit Rate、Register Pressure、Occupancy、访存延迟和实际 Codegen 质量等复杂交互。更大的 Tile 可能提升复用却增加资源压力。实际测量用来验证模型预测,成本模型用来降低搜索开销。
Triton Autotune 常搜索开发者给定的 Kernel Config(如 BLOCK_SIZE、num_warps);TVM MetaSchedule 可通过 Schedule Rules 搜索更丰富的 Tensor Program 调度变换。这是常见抽象与粒度差异,不是排他性的能力边界。
调优也消耗编译、测量时间及目标硬件资源;更大的搜索预算不保证线性收益。应结合 Workload 生命周期、Shape 动态性与调用频率决定是否值得调优。
4.7 为什么不同编译栈的 Fusion 不一样?
同一个 Y=ReLU(X @ W) 有不同合法物理执行方案:
Plan A: Optimized GEMM Library -> materialized C -> ReLU Kernel
Plan B: Tiled MatMul -> on-chip accumulator -> ReLU epilogue -> store Y
Plan B 可能减少全局内存中间读写和 Kernel Launch,但 Plan A 的 GEMM 实现可能远优于自定义融合 Kernel。也可能存在支持 Epilogue 的库调用路径。
影响决策:Frontend IR、Pass Ordering、Shape/dtype、Layout、硬件资源、Library 能力、Numerical Semantics、Cost Model 和 Autotuning Budget。
同一硬件的峰值计算能力和带宽不会因编译器改变,但实际达到的 Throughput、Bandwidth、AI 和资源占用可能改变。回忆 Roofline:
Fusion 首先必须合法,其次才考虑收益。Kernel 数量少不等于性能好。
4.8 Hardware Portability vs Performance Portability
| 硬件 | 重要执行特点 | 调度重点 |
|---|---|---|
| CPU | Core、SIMD、Cache | Loop Order、Cache Tiling、线程开销 |
| GPU | SM、Warp、Shared Memory、Tensor Core | Coalescing、Occupancy、Tiling、Tensorization |
| TPU | Matrix Unit、专用数据流 | 计算映射、片上存储、通信 |
Source Portability 指同一模型代码可被平台接受;Functional Portability 指能够正确执行;Performance Portability 指在不同硬件上均达到相对良好的效率。三者并不等价。
4.9 练习:ReLU(MatMul(X,W)) 的完整抽象流程
X=[32,128]、W=[128,512]、Y=[32,512]。
Framework: torch.relu(x @ w)
|
v
High-level IR: MatMul -> ReLU
| Shape inference, graph simplification, fusion legality
v
Fusion / library decision
| Dependency + Cost Model
v
Tensor / Loop IR: i,j,k + reduction + epilogue
| Tiling, loop order, bufferization
v
Scheduled Program
| Layout, SIMD/warp mapping, storage scopes, tensorization
v
Target Code: CPU C++ / GPU kernel / optimized library
融合后的概念性 Loop IR(不是某个真实编译栈的导出语法):
for i in range(32):
for j in range(512):
acc = 0.0
for k in range(128):
acc += X[i, k] * W[k, j]
Y[i, j] = max(acc, 0.0)
ReLU 必须在该输出元素完整归约之后执行,不能随意施加在每个 K Tile 的部分和上。实际 Tiling 还需要考虑 K 维、尾部、Layout、片上存储和累加精度。
可选 JAX/XLA 观察实验(未运行、未验证本机 Python 3.14 安装兼容性):
import jax
import jax.numpy as jnp
@jax.jit
def f(x, w):
return jax.nn.relu(x @ w)
x = jnp.ones((32, 128), dtype=jnp.float32)
w = jnp.ones((128, 512), dtype=jnp.float32)
lowered = f.lower(x, w)
print(lowered.compiler_ir(dialect="stablehlo"))
compiled = lowered.compile()
print(compiled.as_text())
y = compiled(x, w)
y.block_until_ready()
print(y.shape)
不同 JAX/Backend 版本的 IR 输出可能不同;建议在独立环境中尝试,不改变已有 PyTorch venv。TVM 的实际调优亦留作可选实验。
4.10 Observability 与可比性
| 编译栈 | 诊断产物 |
|---|---|
| MLIR | Dialect IR、Pass 前后快照、Pass Pipeline |
| XLA | StableHLO、Optimized HLO、Backend Dumps |
| TVM | Relax、TensorIR、Schedule Trace、Tuning Records |
| Inductor | FX/ATen、Pre/Post-fusion IR、Generated Code、Guards |
| Triton | TTIR、TTGIR、LLVM IR、PTX 等(取决于后端) |
Provenance 用于关联原始模型、IR 节点、生成代码和 Profiler Event。我们实测 output_code.py 中的 Original ATen、Topologically Sorted Source Nodes、Provenance debug handles 以及映射 JSON,就是这种来源追踪信息的具体例子。
Profiler 告诉我们时间花在哪里,Compiler Artifacts 帮助追溯执行策略如何产生、在哪个阶段发生回归。它们是诊断证据,不是简单的性能参数。映射不一定是一对一。
跨框架比较需要控制计算语义、输入 Shape、dtype、累加精度、Layout、硬件、Library Calls、Compilation Cache、Autotuning Budget、Warmup 和重复测量条件;先验证正确性,再报告 Cold Start、Steady-state Latency、Throughput、Memory Usage 和重编译情况。
5. Chapter 03 复习索引与易错点
| 容易混淆 | 正确理解 |
|---|---|
| Block vs SM | Block 是软件执行单位,SM 是硬件资源;一个 SM 可驻留多个 Block |
| Triton BLOCK_SIZE vs num_warps | 前者是逻辑数据块元素数,后者决定参与执行的 Warp 数;并不一一对应 |
| Coalescing vs Bank Conflict | 前者主要描述 Global Memory 访问事务,后者描述 Shared Memory Bank 访问竞争 |
| Shared Memory vs Register | Block 共享存储 vs Thread 私有寄存器;都有资源限制 |
| Occupancy vs Utilization | 活跃驻留 Warp 比例不等于实际硬件计算利用率 |
| Effective BW vs DRAM BW | 逻辑字节数/时间不等于实测 DRAM 字节数/时间 |
| Shape vs Stride | 逻辑维度 vs 物理索引步长 |
| Mask vs Padding identity | Mask 防止越界访问;用于归约的替代值必须匹配算子 |
| Graph vs Operator vs Kernel | 捕获区域、数学操作、物理执行程序,粒度不同 |
| Guard Failure vs Stale Cache | 不满足适用条件不代表缓存过期 |
| Graph Break vs Recompile | 捕获中断 vs 编译版本不匹配 |
| Metadata vs Data | dtype/shape/stride 是属性;x[i] 的值、sum/max 依赖实际数据 |
| Decomposition vs Fusion | 暴露数学计算结构 vs 重新组织物理执行边界 |
| Fusion vs Buffer Reuse | 避免物化 vs 复用已有存储 |
| Static vs Dynamic Shape | 编译期特化与运行时泛化之间的权衡 |
| MLIR vs StableHLO vs XLA vs Triton | 基础设施、计算规范、模型编译器、Kernel 编译器 |
| Computation vs Schedule | What to compute vs How to compute |
| Portability vs Performance | 能正确运行不代表能高效运行 |
| Cold vs steady-state | 编译和初始化开销必须与稳定执行时间区分 |
五个贯穿全章的思想
- Computation vs Schedule:数学计算定义与物理执行策略可以分离。
- Progressive Lowering:在适当抽象层保留并利用语义,逐渐引入执行细节。
- Data Movement:减少不必要的数据搬运往往比减少 FLOPs 更重要,但需结合实际瓶颈。
- Specialization vs Generalization:特化有优化机会,泛化有缓存复用与灵活性。
- Measurement-driven Optimization:性能不能从优化名称推导,必须用正确性、实际数据与诊断证据验证。
6. 官方参考资料
- NVIDIA CUDA C++ Programming Guide
- NVIDIA CUDA Best Practices Guide
- Triton Tutorials
- PyTorch torch.compile tutorial
- PyTorch Compiler Documentation
- Inductor CPU Debugging and Profiling
- MLIR Language Reference
- MLIR Linalg Dialect
- OpenXLA XLA Documentation
- StableHLO
- Apache TVM Documentation
- JAX Ahead-of-time Lowering and Compilation
7. 实验状态与后续
03.1 与 03.2 已完成理论及代码设计,待 NVIDIA GPU 上实际运行并验证。03.3 核心 CPU 实验已完成,留下可复用日志及生成代码分析;小 MLP 的性能退化根因仍未确定。03.4 已完成概念学习及抽象流程设计,JAX/XLA、TVM 真实运行作为可选扩展。本文没有将示意代码、理论估算或未运行的 GPU 实验混同为实际测试结果。
The mathematical computation defines correctness; the hardware defines constraints; the compiler searches for an efficient execution strategy.