翻篇收录说明
翻篇网页快照

13.3 计算图与编译 – 动手学深度学习

https://zh.d2l.ai/chapter_computational-performance/compilation.html

最近抓取:2026-12-04 15:25:44(北京时间)

最近内容变化:2026-12-04 15:25:44(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

正文摘录

在 13.1 节 中,包含八个运算的激活链 gelu_ish 耗时是在同一张量上做单次加法的八到九倍:每个运算都作为独立 GPU 内核运行,从 DRAM 读取输入再将输出写回 DRAM(搬运 18 次数组而非 2 次)。在小张量上,同一运算链还因第二个原因而变慢:每个运算都由 Python 逐一调度,主机启动每个内核耗时比 GPU 运行它还要长。 两种开销均源于即时执行——Python 每走到一个运算就立刻单独执行。在执行前把整段程序交给编译器可同时解决两者:算子融合将逐元素链合并为单个内核,只读一次输入、只写一次输出(消除访存带宽受限开销);内核重放录制一连串内核启动,之后用单次主机调用重放(消除开销受限成本)。大型计算受限矩阵乘本身无法从这两者中单独获益,但编译它周围的逐元素运算依然大有收益。 PyTorch import os torch.set_float32_matmul_precision('high') # fp32 matmuls may use tf32 # Detach PyTorch's profiler from the GPU when a profile ends; without this, # every kernel launch after the first profile stays about 30% slower os.environ['TEARDOWN_CUPTI'] = '1' 13.3.1 图捕获 13.3.1.1 计算图 神经网络的运算构成一张有向计算图,节点是基础算子,边携带张量(图 13.3.1)。尽管即时自动微分(1.5 节)会在前向传播期间录制反向磁带,但该记录来得太晚,无法优化前向传播本身:等磁带建好时,每个运算都已付出了主机调度时间 \(h\) 并在 GPU 显存中往返了一趟。优化程序需要图捕获——在运算执行之前先拿到计算图。 图 13.3.1: 带损失函数的两层网络计算图。自动微分反向遍历它;而在前向传播前就拿到整张图的编译器可以重写它。 13.3.1.2 追踪 现代框架通过追踪捕获计算图:用仅携带形状与数据类型、不含具体数值的符号占位符运行一次 Python 函数(图 13.3.2)。作用在占位符上的每个张量运算都会被记录为图中的一个节点,而仅依赖静态形状或循环边界的普通 Python 控制流则在追踪时展开。编译器随后将捕获的计算图降级为融合 GPU 内核,并按输入形状与数据类型缓存,供后续匹配调用直接复用。 图 13.3.2: 图捕获流程。首次调用在占位符上追踪函数;编译器将录制的计算图转化为内核,后续相同形状与数据类型的调用直接复用。依赖张量数值的分支无法被录制,而新的形状或数据类型可能触发重新捕获。 PyTorchJAX 在 PyTorch 中,torch.compile 通过 TorchDynamo (Ansel 等 2024年) 拦截 Python 字节码、将张量运算追踪成图,借助 AOTAutograd 提前捕获反向图,再由 Inductor 将前后向图编译为融合的 Triton 与 C++ 内核。Dynamo 会在输入形状与数据类型上附加守卫,后续调用只要通过守卫即可直接跳转至已编译内核。 在 JAX 中,jax.jit 使用抽象追踪器对象将函数追踪为带类型的中间表示(jaxpr,可用 jax.make_jaxpr 检视)(Frostig 等 2018年),再由 XLA 编译器降级为按输入形状与数据类型缓存的融合 GPU 内核。 13.3.1.3 依赖数值的分支 由于占位符不携带数值,追踪器无法求值诸如 if x.sum() > 0: 之类的数据依赖 Python 分支。捕获系统有三种应对方式: 冻结单个示例输入所走的分支——速度快,但当后续输入本应走另一分支时会悄然出错。 报错拒绝,要求程序员用图原语表达分支:要么用选择算子(两支都算再选其一),要么用条件算子。 回退到 Python,插入一个图断点:在条件处结束第一张图,让 Python 在物化数值上求值分支,再在第二张编译图中继续。 依赖静态张量形状的分支(if x.shape[0] > 4:)在追踪期即已知,无需特殊处理。下面看看我们的框架如何处理数据依赖分支。 PyTorchJAX def f(x): x = x * 2 if x.sum() > 0: # Python needs the value of this comparison return x + 1 return x - 1 explanation = torch._dynamo.explain(f)(torch.randn(8, device=d2l.try_gpu())) print(f'graphs: {explanation.graph_count}, ' f'breaks: {explanation.graph_break_count}') for graph in explanation.graphs: print(graph.code.strip()) graphs: 2, breaks: 1 def forward(self, L_x_ : torch.Tensor): l_x_ = L_x_ x = l_x_ * 2; l_x_ = None sum_1 = x.sum() gt = sum_1 > 0; sum_1 = None return (gt, x) def forward(self, L_x_ : torch.Tensor): l_x_ = L_x_ sub = l_x_ - 1; l_x_ = None return (sub,) def f(x): x = x * 2 if x.sum() > 0: # Python needs the value of this comparison return x + 1 return x - 1 try: jax.jit(f)(jnp.ones(8)) except jax.errors.TracerBoolConversionError as e: print(type(e).__name__) def f_select(x): # Both alternatives in the graph; select keeps one x = x * 2 return jax.lax.select(x.sum() > 0, x + 1, x - 1) print(jax.make_jaxpr(f_select)(jnp.ones(8))) TracerBoolConversionError { lambda ; a:f32[8]. let b:f32[8] = mul a 2.0:f32[] c:f32[] = reduce_sum[axes=(0,) out_sharding=None] b d:bool[] = gt c 0.0:f32[] e:f32[8] = add b 1.0:f32[] f:f32[8] = sub b 1.0:f32[] g:f32[8] = select_n d f e in (g,) } PyTorchJAX 默认情况下,torch.compile 会插入图断点:图 1 计算 x * 2 与 x.sum() > 0,将控制权交回 Python 求值 if,再为所选分支调度图 2。传入 fullgraph=True(或使用 torch.export)则会拒绝图断点;而用 torch.where(x.sum() > 0, x + 1, x - 1) 改写分支即可捕获单张图。较早的 torch.jit.trace 则会冻结示例输入所走的分支。 jax.jit 通过抛出 TracerBoolConversionError 拒绝此类分支。将 Python if 替换为 jax.lax.select(或在仅需执行所选分支时改用 jax.lax.cond)即可生成单个 jaxpr。 13.3.1.4 形状与重编译 由于编译器会针对张量形状特化内核(分块大小、循环边界、内存布局),改变输入形状——例如一个轮次末尾较短的最后一个小批量,或可变序列长度——就会触发重编译,除非编译器将其泛化为符号维度。实践中,我们通常将输入填充至少数分桶形状,或将变化轴标记为动态维度。 PyTorchJAX compilations = [] def recording_backend(gm, example_inputs): # Called once per compilation compilations.append(gm) return gm.forward # Run the captured graph as is g = torch.compile(lambda x: torch.sin(x) + 1, backend=recording_backend) for n in (8, 8, 16, 32): g(torch.ones(n, device=d2l.try_gpu())) print(f'compilations: {len(compilations)}') print(compilations[-1].code.strip()) compilations: 2 def forward(self, s77 : torch.SymInt, L_x_ : torch.Tensor): l_x_ = L_x_ sin = torch.sin(l_x_); l_x_ = None add = sin + 1; sin = None return (add,) @jax.jit def g(x): print(f'tracing g for shape {x.shape}') # Python runs only while tracing return jnp.sin(x) + 1 for n in (8, 8, 16, 32): g(jnp.ones(n)) tracing g for shape (8,) tracing g for shape (16,) tracing g for shape (32,) PyTorchJAX Dynamo 在首次调用(\(n = 8\))时编译,第二次调用(\(n = 8\))复用该图,见到 \(n = 16\) 时改用符号维度(SymInt s77)重新编译,此后 \(n = 32\) 便无需再次编译。 jax.jit 严格针对静态形状特化:Python 的 print 在长度 8、16 与 32 追踪时各执行一次(四次调用共追踪三次),而第二次长度为 8 的调用命中缓存。 13.3.2 算子融合 13.3.2.1 统计访存流量 在即时执行下,gelu_ish(x) 运行八个逐元素内核(六个一元算子各一读一写,加两个二元算子各两读一写),共搬运 \(10 + 8 = 18\) 个大小为 \(nb\) 字节的数组。融合内核只读取 x 一次,将全部七个中间值保留在寄存器中,最后写出结果一次(图 13.3.3),使访存流量缩减: \[ \frac{\textrm{bytes moved, eager}}{\textrm{bytes moved, fused}} = \frac{(10 + 8)\, n b}{(1 + 1)\, n b} = 9. \] 由于即便融合内核在 fp32 下每 8 字节也仅执行约 12 FLOPs(\(I \approx 1.5 \ll 82\) FLOP/字节),两个版本都访存带宽受限,因此融合应使 gelu_ish 提速约 \(9\times\)。 图 13.3.3: gelu_ish 的访存流量。即时执行运行八个内核,共读十个数组、写八个数组;融合内核只读输入一次,将七个中间结果保存在寄存器中,并写出结果一次。 PyTorchJAX x = torch.randn(4000, 4000, device=d2l.try_gpu()) compiled = torch.compile(d2l.gelu_ish) assert torch.allclose(d2l.gelu_ish(x), compiled(x), atol=1e-6) # Same answer arrays_moved = {'eager': 18, 'compiled': 2} # In units of x.nbytes for desc, fn in (('eager', d2l.gelu_ish), ('compiled', compiled)): b = d2l.Benchmark(lambda: fn(x), desc=desc) print(f'{b}, {arrays_moved[desc] * x.nbytes / b.time / 1e9:.0f} GB/s') eager: 1.25 ms/call, 920 GB/s compiled: 0.15 ms/call, 878 GB/s x = jax.random.normal(d2l.get_key(), (4000, 4000)) compiled = jax.jit(d2l.gelu_ish) assert jnp.allclose(d2l.gelu_ish(x), compiled(x), atol=1e-6) # Same answer arrays_moved = {'eager': 18, 'compiled': 2} # In units of x.nbytes for desc, fn in (('eager', d2l.gelu_ish), ('compiled', compiled)): b = d2l.Benchmark(lambda: fn(x), desc=desc) print(f'{b}, {arrays_moved[desc] * x.nbytes / b.time / 1e9:.0f} GB/s') eager: 1.84 ms/call, 627 GB/s compiled: 0.17 ms/call, 768 GB/s 两个版本均以 0.6–0.9 TB/s 流式访存,而编译版本仅凭省去 18 次 DRAM 传输中的 16 次,就快了 \(8\times\) 到 \(11\times\)——正好吻合 \(9\times\) 的字节数预测。 在 Transformer 模块内部,激活融合有多重要?对于宽度 \(d = 2048\)、FFN 隐藏宽度 \(4d = 8192\) 的 bf16 1B 参数 GPT,未融合的 8 算子激活在 \(M\) 个词元上搬运 \(18 \cdot 4dM \cdot 2 = 144\,dM\) 字节,而前后两次 FFN 矩阵乘共执行 \(2 \cdot 2 \cdot M \cdot d \cdot 4d = 16\,d^2M\) FLOPs。两者的耗时之比与词元数 \(M\) 无关: \[ \frac{t_\textrm{activation}}{t_\textrm{products}} = \frac{144\, dM/\beta}{16\, d^2 M/P} = \frac{9 I^*}{d} \approx 0.72 \] 此处 \(I^* = 164\) FLOP/字节,\(d = 2048\)。未融合时,激活耗时几乎达到两次矩阵乘的四分之三;融合后则不足十分之一。 13.3.2.2 融合模式 编译器常规支持两类融合模式: 逐元素链(激活函数、残差相加、暂退掩码、优化器更新),每个线程在寄存器中直接算出输出的第 \(i\) 个元素。 行归约(softmax、LayerNorm、RMSNorm),当每行能装入片上 SRAM 时,内核只读一次该行,在片上完成归约与规范化,再写出输出一次。 编译器不会发明新算法:它既无法加速计算受限的矩阵乘,也无法自动发现如 FlashAttention(10.5 节,(Dao 等 2022年))这类通过在线 softmax 重缩放避免物化 \(T \times T\) 注意力矩阵的分块算法(需用 CUDA 或 Triton (Tillet 等 2019年) 手写)。 13.3.3 编译完整训练步 现在我们来编译一个完整训练步——前向传播、平方损失、反向传播与 SGD 更新——对象是宽度为 1,024、采用 gelu_ish 激活的四层 MLP,批量大小为 512 个样本。 PyTorchJAX class MLP(nn.Module): """Linear layers with the gelu_ish chain between them.""" def __init__(self, width=1024, depth=4): super().__init__() self.layers = nn.ModuleList(nn.Linear(width, width) for _ in range(depth)) def forward(self, X): for layer in self.layers[:-1]: X = d2l.gelu_ish(layer(X)) return self.layers[-1](X) def train_step(net, X, Y, lr=0.1): # Forward, backward, SGD update loss = ((net(X) - Y) ** 2).mean() grads = torch.autograd.grad(loss, list(net.parameters())) with torch.no_grad(): for p, g in zip(net.parameters(), grads): p -= lr * g return loss def init_mlp(key, width=1024, depth=4): """Weights and biases drawn uniformly from +-1/sqrt(width).""" bound = 1 / width**0.5 keys = jax.random.split(key, (depth, 2)) return [(jax.random.uniform(kW, (width, width), minval=-bound, maxval=bound), jax.random.uniform(kb, (width,), minval=-bound, maxval=bound)) for kW, kb in keys] def mlp(params, X): # Linear layers with the gelu_ish chain between them for W, b in params[:-1]: X = d2l.gelu_ish(X @ W + b) W, b = params[-1] return X @ W + b def train_step(params, X, Y, lr=0.1): # Forward, backward, SGD update loss_fn = lambda p: ((mlp(p, X) - Y) ** 2).mean() loss, grads = jax.value_and_grad(loss_fn)(params) return loss, jax.tree.map(lambda p, g: p - lr * g, params, grads) 先预测单步耗时。四次前向矩阵乘与七次反向矩阵乘(第一层无需输入梯度)共执行约 \(11 \times 2 \cdot 512 \cdot 1024^2 \approx 1.2 \times 10^{10}\) FLOPs(tf32 82.6 TFLOP/s 下需 0.14 ms),而读取并更新 16 MiB 参数共搬运约 96 MiB(1 TB/s 下需 0.10 ms),实际设备工作量总计约 0.25 ms。然而即时执行会以每次 \(h \ge 10\) µs 发起超过 100 个独立运算(主机启动开销 > 1 ms),使即时步陷入开销受限区间。 由于编译在首次调用时付出 \(t_\textrm{compile}\),此后每步节省 \(t_\textrm{eager} - t_\textrm{compiled}\),它将在 \[ n^* = \frac{t_\textrm{compile}}{t_\textrm{eager} - t_\textrm{compiled}} \tag{13.3.1}\] 步后回本。 PyTorchJAX net = MLP().to(d2l.try_gpu()) X, Y = (torch.randn(512, 1024, device=d2l.try_gpu()) for _ in range(2)) compiled_step = torch.compile(train_step) t_first = d2l.Benchmark(lambda: compiled_step(net, X, Y), warmup=0, repeats=1).time # Includes compilation t_eager = d2l.Benchmark(lambda: train_step(net, X, Y)).time t_compiled = d2l.Benchmark(lambda: compiled_step(net, X, Y)).time saved = t_eager - t_compiled # Per step; a difference of two short times print(f'first call: {t_first:.1f} s\n' f'eager: {1000 * t_eager:.2f} ms, compiled: {1000 * t_compiled:.2f} ms\n' 'break-even: ' + (f'about {float(f"{t_first / saved:.1g}"):,.0f} steps' if saved > 0 else 'never, compiled is not faster')) # explain is internal to torch; it clears the compile cache and recompiles print('graphs:', torch._dynamo.explain(train_step)(net, X, Y).graph_count) first call: 0.6 s eager: 2.93 ms, compiled: 2.08 ms break-even: about 700 steps graphs: 2 params = init_mlp(d2l.get_key()) X, Y = (jax.random.normal(d2l.get_key(), (512, 1024)) for _ in range(2)) compiled_step = jax.jit(train_step) t_first = d2l.Benchmark(lambda: compiled_step(params, X, Y), warmup=0, repeats=1).time # Includes compilation t_eager = d2l.Benchmark(lambda: train_step(params, X, Y)).time t_compiled = d2l.Benchmark(lambda: compiled_step(params,