Autograd是PyTorch最核心的魔法——你只需写前向传播,它自动为你计算梯度。理解计算图是掌握深度学习训练的关键。
如果说张量是PyTorch的"骨",那么Autograd就是PyTorch的"魂"。它让你从手动推导和实现梯度的痛苦中解放出来——你只需要定义前向传播(模型如何从输入计算输出),Autograd就能自动为你计算损失函数对每个参数的梯度。对于有数十亿参数的大模型,这个自动化是不可或缺的。
自动微分(Automatic Differentiation,AD)不同于数值微分(用有限差分近似导数,精度差)和符号微分(像Mathematica那样推导解析表达式,表达式膨胀)。自动微分将计算分解为一系列基本操作(加、乘、指数、对数等),每个基本操作的导数都已知,然后通过链式法则将这些局部导数组合起来,得到整体的梯度。
自动微分有两种模式:
PyTorch使用的是反向模式自动微分,也叫反向传播算法。它的计算复杂度与前向传播相同,这使得它对于参数远多于输出的深度学习模型来说极其高效。
PyTorch采用"Define-by-Run"模式:计算图在每次前向传播时动态构建。当你对requires_grad=True的张量执行操作时,PyTorch会自动记录这些操作,构建一个有向无环图(DAG),图的节点是操作(Function),边是张量。
反向传播的核心是链式法则。对于一个复合函数 L = f(g(h(x))),其导数为:
dL/dx = dL/df · df/dg · dg/dh · dh/dx
在计算图中,每个节点只需要知道两件事:(1) 如何计算前向输出,(2) 如何计算局部导数(即输出对输入的导数)。反向传播时,从输出端开始,沿着图的边反向传播,将局部导数相乘(链式法则),就能得到损失对任何输入的梯度。
import torch
# 默认不追踪梯度
x = torch.tensor([1.0, 2.0, 3.0])
print(f"requires_grad: {x.requires_grad}") # False
# 方式1:创建时指定
w = torch.randn(3, requires_grad=True)
print(f"w.requires_grad: {w.requires_grad}") # True
# 方式2:事后开启
b = torch.randn(3)
b.requires_grad_(True)
print(f"b.requires_grad: {b.requires_grad}") # True
# 方式3:通过nn.Parameter自动开启(大模型中最常见)
param = torch.nn.Parameter(torch.randn(3))
print(f"param.requires_grad: {param.requires_grad}") # True
# 传播规则:任何涉及requires_grad=True张量的操作,
# 其结果也自动开启梯度追踪
y = w * x + b
print(f"y.requires_grad: {y.requires_grad}") # True
import torch
x = torch.tensor([2.0], requires_grad=True)
w = torch.tensor([3.0], requires_grad=True)
b = torch.tensor([1.0], requires_grad=True)
# 前向传播
y = w * x # MulBackward0
z = y + b # AddBackward0
L = z ** 2 # PowBackward0
# 查看每个张量的grad_fn(生成它的反向传播函数)
print(f"y.grad_fn: {y.grad_fn}") # <MulBackward0>
print(f"z.grad_fn: {z.grad_fn}") # <AddBackward0>
print(f"L.grad_fn: {L.grad_fn}") # <PowBackward0>
# 沿着计算图回溯
print(f"\n计算图回溯:")
print(f" L的grad_fn: {L.grad_fn}")
print(f" L的next: {L.grad_fn.next_functions}")
# x没有grad_fn(它是叶子节点,用户直接创建的)
print(f"\nx.grad_fn: {x.grad_fn}") # None(叶子节点)
print(f"x.is_leaf: {x.is_leaf}") # True
print(f"y.is_leaf: {y.is_leaf}") # False(由操作生成)
| 概念 | 定义 | 梯度 |
|---|---|---|
| 叶子节点(leaf) | 用户直接创建的张量,或通过detach()创建的 | backward()后梯度存储在.grad中 |
| 非叶子节点 | 通过操作从其他张量生成的 | 默认不保存梯度(计算图释放后清除) |
| retain_grad() | 对非叶子节点调用,保留其梯度 | 梯度也会保存在.grad中 |
import torch
x = torch.tensor([2.0], requires_grad=True)
w = torch.tensor([3.0], requires_grad=True)
y = w * x # 非叶子节点
L = y.sum()
L.backward()
# 叶子节点的梯度
print(f"x.grad: {x.grad}") # tensor([3.]) — dL/dx = w = 3
print(f"w.grad: {w.grad}") # tensor([2.]) — dL/dw = x = 2
# 非叶子节点的梯度默认不保存
print(f"y.grad: {y.grad}") # None
# 如果需要保存非叶子节点的梯度
x = torch.tensor([2.0], requires_grad=True)
w = torch.tensor([3.0], requires_grad=True)
y = w * x
y.retain_grad() # 显式保留
L = y.sum()
L.backward()
print(f"y.grad (retained): {y.grad}") # tensor([1.])
在大多数深度学习场景中,损失是一个标量(单个数值),直接调用loss.backward()即可:
import torch
# 模拟一个简单的训练步骤
x = torch.randn(10, requires_grad=True)
w = torch.randn(10, requires_grad=True)
target = torch.tensor(1.0)
# 前向传播
y = (w * x).sum()
loss = (y - target) ** 2
# 反向传播(loss是标量)
loss.backward()
print(f"loss: {loss.item():.4f}")
print(f"dL/dw: {w.grad}")
print(f"dL/dx: {x.grad}")
当输出不是标量时,需要提供gradient参数,它相当于损失对输出的"种子梯度":
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x ** 2 # y = [1, 4, 9],非标量
# 非标量backward需要提供gradient参数
# gradient的形状必须与y相同
# 相当于计算 L = sum(gradient * y) 对 x 的梯度
y.backward(gradient=torch.ones_like(y))
print(f"gradient=ones: {x.grad}") # tensor([2., 4., 6.]) — dy/dx = 2x
# 等价于先sum再backward
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x ** 2
y.sum().backward()
print(f"sum().backward(): {x.grad}") # 同上
# 使用不同的gradient权重
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x ** 2
y.backward(gradient=torch.tensor([0.1, 0.5, 1.0]))
print(f"加权gradient: {x.grad}") # tensor([0.2, 2.0, 6.0])
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3 # y = 8
# 第一次backward默认会释放计算图
y.backward()
print(f"一阶导数 dy/dx = {x.grad}") # 12 (= 3x² = 3*4)
# 第二次backward会报错,因为计算图已被释放
# y.backward() # RuntimeError!
# retain_graph=True: 保留计算图,允许多次backward
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3
y.backward(retain_graph=True)
print(f"\n第一次backward: {x.grad}")
y.backward(retain_graph=True)
print(f"第二次backward(梯度累加): {x.grad}") # 24(12+12)
# create_graph=True: 构建梯度本身的计算图(用于高阶导数)
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3
y.backward(create_graph=True)
print(f"\n一阶导数: {x.grad}") # 12
x.grad.backward() # 对梯度再求导
print(f"二阶导数: {x.grad}") # 12 (= 6x = 12)
# 注意:这里x.grad已经被覆盖,需要用autograd.grad更安全
PyTorch的梯度是累加的——每次调用backward(),计算出的梯度会加到.grad上,而不是覆盖。这个设计有其历史原因和使用场景,但也常常导致初学者的困惑。
import torch
x = torch.tensor(2.0, requires_grad=True)
# 第一次backward
y1 = x ** 2
y1.backward()
print(f"第一次backward后: {x.grad}") # 4 (= 2x = 4)
# 第二次backward(梯度累加!)
y2 = x ** 2
y2.backward()
print(f"第二次backward后: {x.grad}") # 8 (4+4),不是4!
# 正确做法:每次backward前清零梯度
x.grad.zero_() # 手动清零
y3 = x ** 2
y3.backward()
print(f"清零后backward: {x.grad}") # 4
import torch
import torch.nn as nn
model = nn.Linear(10, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(3):
for batch_x, batch_y in dataloader:
# 标准三步曲
optimizer.zero_grad() # 1. 清零梯度
pred = model(batch_x) # 2. 前向传播
loss = nn.MSELoss()(pred, batch_y)
loss.backward() # 3. 反向传播
optimizer.step() # 4. 更新参数
import torch
import torch.nn as nn
model = nn.Linear(10, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# 梯度累积:用小batch模拟大batch的训练效果
accumulation_steps = 4 # 累积4个batch的梯度
effective_batch_size = 32 * accumulation_steps # 等效batch=128
optimizer.zero_grad() # 在外层清零
for i, (batch_x, batch_y) in enumerate(dataloader):
pred = model(batch_x)
loss = nn.MSELoss()(pred, batch_y)
# 除以累积步数,使梯度等效于大batch的平均
loss = loss / accumulation_steps
loss.backward() # 梯度累积
if (i + 1) % accumulation_steps == 0:
optimizer.step() # 累积够了才更新
optimizer.zero_grad() # 然后清零
gradient_accumulation_steps参数。
梯度hooks允许你在反向传播过程中拦截和修改梯度。这在梯度裁剪、梯度监控、自定义正则化等场景中非常有用。
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
# 注册梯度hook
def grad_hook(grad):
print(f"梯度hook被调用,梯度值: {grad}")
# 可以返回修改后的梯度
return grad * 2.0 # 将梯度放大2倍
handle = x.register_hook(grad_hook)
y = (x ** 2).sum()
y.backward()
print(f"最终梯度: {x.grad}") # 原始[2,4,6] * 2 = [4,8,12]
handle.remove() # 移除hook
import torch
import torch.nn as nn
model = nn.Sequential(nn.Linear(10, 50), nn.ReLU(), nn.Linear(50, 1))
# 场景1:监控每层梯度的范数(诊断训练问题)
grad_norms = {}
def make_hook(name):
def hook(grad):
grad_norms[name] = grad.norm().item()
return hook
for name, param in model.named_parameters():
param.register_hook(make_hook(name))
# 训练一步
x = torch.randn(8, 10)
target = torch.randn(8, 1)
loss = nn.MSELoss()(model(x), target)
loss.backward()
# 查看各层梯度范数
for name, norm in grad_norms.items():
print(f" {name}: grad_norm={norm:.4f}")
# 场景2:使用clip_grad_norm_进行梯度裁剪(更常用)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
print(f"\n裁剪后总梯度范数: "
f"{sum(p.grad.norm()**2 for p in model.parameters())**0.5:.4f}")
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x ** 4 # y = 16
# 一阶导数: dy/dx = 4x³ = 32
grad1 = torch.autograd.grad(y, x, create_graph=True)[0]
print(f"一阶导数 (4x³): {grad1.item():.1f}") # 32.0
# 二阶导数: d²y/dx² = 12x² = 48
grad2 = torch.autograd.grad(grad1, x)[0]
print(f"二阶导数 (12x²): {grad2.item():.1f}") # 48.0
# 三阶导数: d³y/dx³ = 24x = 48
grad3 = torch.autograd.grad(grad2, x)[0]
print(f"三阶导数 (24x): {grad3.item():.1f}") # 48.0
import torch
import torch.nn as nn
# MAML需要二阶导数:在内层训练后,对外层参数求导
model = nn.Linear(5, 1)
meta_lr = 0.01
inner_lr = 0.1
x = torch.randn(4, 5)
y = torch.randn(4, 1)
# 内层:用当前参数计算loss和梯度
loss = nn.MSELoss()(model(x), y)
grads = torch.autograd.grad(loss, model.parameters(), create_graph=True)
# 内层更新(需要保留计算图以便外层求导)
# theta' = theta - inner_lr * grad
# 外层loss需要对theta求导,因此内层更新必须在计算图中
# 外层:对更新后的参数计算meta-loss
# 这里简化为直接用梯度范数作为meta-loss
meta_loss = sum(g.norm() ** 2 for g in grads)
meta_loss.backward()
print(f"Meta-loss: {meta_loss.item():.4f}")
print(f"Meta-梯度已计算")
import torch
x = torch.randn(100, requires_grad=True)
# 在no_grad上下文中,不追踪梯度
with torch.no_grad():
y = x * 2 + 1
print(f"y.requires_grad: {y.requires_grad}") # False
print(f"y.grad_fn: {y.grad_fn}") # None
# 退出上下文后恢复正常
z = x * 3
print(f"z.requires_grad: {z.requires_grad}") # True
# 大模型中的典型用途:推理和参数手动更新
model = torch.nn.Linear(10, 1)
# 推理时不需要梯度,节省内存和计算
with torch.no_grad():
input_data = torch.randn(5, 10)
output = model(input_data)
print(f"推理输出: {output.shape}")
# 手动更新参数时也需要no_grad
with torch.no_grad():
for param in model.parameters():
param -= 0.01 * param.grad # 如果有梯度的话
import torch
x = torch.randn(3, requires_grad=True)
# detach(): 从计算图中分离张量
y = x ** 2
y_detached = y.detach()
print(f"y.requires_grad: {y.requires_grad}") # True
print(f"y_detached.requires_grad: {y_detached.requires_grad}") # False
# detach的典型用途:停止梯度流(如RL中的target value)
# 或者用于计算一些不需要反向传播的中间量
w = torch.randn(3, requires_grad=True)
target = (w ** 2).detach() # target不需要梯度
loss = ((x - target) ** 2).sum()
loss.backward()
print(f"梯度只对x计算: x.grad={x.grad is not None}, w.grad={w.grad}")
# enable_grad: 在no_grad中临时开启
with torch.no_grad():
with torch.enable_grad():
a = torch.randn(3, requires_grad=True)
b = (a ** 2).sum()
print(f"enable_grad中: {b.requires_grad}") # True
import torch
# in-place操作(带_后缀的方法)可能破坏计算图
x = torch.randn(3, requires_grad=True)
# 这些是in-place操作:
# x.add_(1) # x += 1
# x.mul_(2) # x *= 2
# x[0] = 5.0 # 索引赋值
# 安全的替代方案:使用非in-place版本
y = x + 1 # 创建新张量,不修改x
z = y * 2
print(f"x: {x}")
print(f"y: {y}")
print(f"z: {z}")
# 注意:对叶子节点使用in-place操作会报错
# x.add_(1) # RuntimeError: a leaf Variable that requires grad
# is being used in an in-place operation
# 但zero_()是例外,它专门用于清零梯度
x_grad = torch.tensor([1.0, 2.0, 3.0])
x_grad.zero_() # 这是安全的
import torch
# 场景:计算梯度惩罚(WGAN-GP中的常见操作)
def gradient_penalty(critic, real, fake):
alpha = torch.rand(real.shape[0], 1)
alpha = alpha.expand_as(real)
interpolated = alpha * real + (1 - alpha) * fake
interpolated.requires_grad_(True) # 需要对插值点求导
critic_output = critic(interpolated)
# 对输入求梯度
grads = torch.autograd.grad(
outputs=critic_output,
inputs=interpolated,
grad_outputs=torch.ones_like(critic_output),
create_graph=True, # 需要二阶导数
retain_graph=True,
)[0]
penalty = ((grads.norm(2, dim=1) - 1) ** 2).mean()
return penalty
# detach的另一个用途:从GPU取数据到CPU用于日志
loss = torch.randn(1, requires_grad=True)
loss_value = loss.detach().item() # 获取标量值用于打印
print(f"Loss值: {loss_value:.4f}")
import torch
# 错误示范:前向传播后修改了参与计算的张量
x = torch.randn(3, requires_grad=True)
y = x * 2
# x.add_(1) # 修改了x!再backward会报错或结果错误
# y.sum().backward() # RuntimeError!
# 正确做法:先backward再修改
x = torch.randn(3, requires_grad=True)
y = x * 2
y.sum().backward()
print(f"梯度: {x.grad}") # tensor([2., 2., 2.])
# 现在可以安全地修改x
optimizer.zero_grad()导致梯度累加;(2) 在no_grad()上下文中意外创建了需要梯度的操作;(3) 在前向传播和反向传播之间修改了张量。养成使用optimizer.zero_grad() → forward → loss → backward → step的标准模式可以避免大部分问题。
当PyTorch内置的操作不足以满足需求时,你可以通过继承torch.autograd.Function来自定义前向和反向传播。这在实现特殊激活函数、自定义损失、或需要高效梯度的场景中非常有用。
import torch
# 自定义Function:实现ReLU的变体——LeakyReLU的手动实现
class MyLeakyReLU(torch.autograd.Function):
@staticmethod
def forward(ctx, x, negative_slope=0.01):
# ctx是上下文对象,用于保存backward需要的信息
ctx.save_for_backward(x)
ctx.negative_slope = negative_slope
# 前向计算
return torch.where(x >= 0, x, negative_slope * x)
@staticmethod
def backward(ctx, grad_output):
# 从ctx恢复前向传播时保存的信息
x, = ctx.saved_tensors
negative_slope = ctx.negative_slope
# 计算梯度: dReLU/dx = 1 if x>=0 else negative_slope
grad_input = torch.where(x >= 0,
torch.ones_like(x),
torch.full_like(x, negative_slope))
# 返回的梯度数量必须与forward的输入数量一致
# 对negative_slope不需要梯度,返回None
return grad_input * grad_output, None
# 使用自定义Function
x = torch.tensor([-2.0, -1.0, 0.5, 1.0], requires_grad=True)
y = MyLeakyReLU.apply(x, 0.1)
print(f"前向输出: {y}") # tensor([-0.2, -0.1, 0.5, 1.0])
y.sum().backward()
print(f"梯度: {x.grad}") # tensor([0.1, 0.1, 1.0, 1.0])
import torch
import torch.nn as nn
# Swish(x) = x * sigmoid(x)
# Swish'(x) = sigmoid(x) + x * sigmoid(x) * (1 - sigmoid(x))
# = sigmoid(x) * (1 + x * (1 - sigmoid(x)))
class SwishFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
sigmoid_x = torch.sigmoid(x)
ctx.save_for_backward(x, sigmoid_x)
return x * sigmoid_x
@staticmethod
def backward(ctx, grad_output):
x, sigmoid_x = ctx.saved_tensors
# Swish的导数
grad = sigmoid_x * (1 + x * (1 - sigmoid_x))
return grad * grad_output
# 包装成nn.Module以便在模型中使用
class Swish(nn.Module):
def forward(self, x):
return SwishFunction.apply(x)
# 在模型中使用
model = nn.Sequential(
nn.Linear(768, 1024),
Swish(), # 使用自定义激活函数
nn.Linear(1024, 10)
)
# 验证梯度
x = torch.randn(4, 768, requires_grad=True)
output = model(x)
loss = output.sum()
loss.backward()
print(f"梯度已计算: {x.grad is not None}")
print(f"梯度范数: {x.grad.norm():.4f}")
| 规则 | 说明 |
|---|---|
| forward必须是staticmethod | 使用@staticmethod装饰器,第一个参数是ctx |
| backward返回值数量 | 必须与forward的输入数量一致(不含ctx),不需要梯度的返回None |
| ctx.save_for_backward | 只保存张量,非张量用ctx.attr = value |
| backward中的梯度方向 | grad_output是"上游传来的梯度",返回的是"传给下游的梯度" |
| 不要在forward中创建需要梯度的张量 | forward中的操作不参与自动微分,必须手动实现 |
import torch
import torch.nn as nn
# 创建一个简单模型
model = nn.Sequential(
nn.Linear(10, 20),
nn.ReLU(),
nn.Linear(20, 1)
)
x = torch.randn(5, 10)
y = model(x).sum()
# 打印计算图信息(无需torchviz)
def print_graph(tensor, level=0):
if tensor.grad_fn is None:
print(" " * level + f"Leaf: {tensor.shape}")
return
print(" " * level + f"{tensor.grad_fn}")
for fn, _ in tensor.grad_fn.next_functions:
if fn is not None:
# 递归打印(简化版)
print(" " * (level + 1) + f" → {fn}")
print("计算图结构:")
print_graph(y)
import torch
# 开启异常检测(调试NaN梯度问题)
# torch.autograd.set_detect_anomaly(True)
# 当梯度出现NaN时,开启异常检测可以定位到具体操作
x = torch.tensor([1.0, -1.0, 0.0], requires_grad=True)
# 可能产生NaN的操作
y = torch.log(x) # log(0) = -inf, log(-1) = nan
print(f"y值: {y}") # 包含nan和-inf
# 安全的替代方案:添加epsilon或使用clamp
x_safe = torch.tensor([1.0, 0.01, 0.01], requires_grad=True)
y_safe = torch.log(x_safe.clamp(min=1e-8))
print(f"安全y值: {y_safe}")
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(768, 2048),
nn.ReLU(),
nn.Linear(2048, 768)
)
# 前向+反向
x = torch.randn(32, 768)
loss = model(x).sum()
loss.backward()
# 梯度健康度检查
print("梯度健康度报告:")
print(f"{'参数名':<30} {'形状':<20} {'范数':>10} {'最大值':>10} {'是否有NaN':>10}")
for name, param in model.named_parameters():
if param.grad is not None:
grad = param.grad
print(f"{name:<30} {str(grad.shape):<20} "
f"{grad.norm().item():>10.4f} {grad.abs().max().item():>10.4f} "
f"{str(torch.isnan(grad).any().item()):>10}")
| 知识点 | 核心要点 |
|---|---|
| 反向模式AD | PyTorch使用反向模式自动微分,通过链式法则自动计算梯度 |
| 计算图 | Define-by-Run模式,前向传播时动态构建,backward后默认释放 |
| requires_grad | 开启梯度追踪,操作结果自动继承 |
| backward() | 标量直接调用,非标量需提供gradient参数 |
| 梯度累加 | 每次backward梯度累加到.grad,需手动zero_grad清零 |
| 梯度累积 | 利用累加特性模拟大batch训练 |
| no_grad/detach | 推理和手动更新时禁用梯度,detach分离计算图 |
| 高阶导数 | create_graph=True + autograd.grad计算高阶导数 |
| 自定义Function | 实现forward和backward,用于特殊操作 |
| 常见陷阱 | in-place操作、忘记zero_grad、前向后修改张量 |
Autograd是PyTorch区别于普通数值计算库的核心能力。理解计算图的构建和反向传播的原理,不仅能帮助你写出正确的代码,更能让你在遇到问题时快速定位和解决。在后续章节中,我们将看到Autograd如何与nn.Module结合,让模型定义和训练变得更加简洁和强大。