Math-06.矩阵微积分-06.常见层梯度手册

本页为 DL 常见层的 forward / backward 速查(分子布局,batch 单列或合并为矩阵形式)。

段末注释Softmax + CrossEntropy 联立 backward 时,梯度常简化为 $\hat{\mathbf{p}} - \mathbf{y}_{\mathrm{onehot}}$,数值上应使用 log_softmax + nll_loss

系列入口00.系列规划 | 前置:04 反向传播


1. Linear(全连接)(D3)

图 1 y = x W^T + b(PyTorch 约定)

PyTorch nn.Linear:$Y = X W^\top + \mathbf{b}$,$X \in \mathbb{R}^{B \times d_{\mathrm{in}}}$,$W \in \mathbb{R}^{d_{\mathrm{out}} \times d_{\mathrm{in}}}$。

已知 $\bar{Y} = \partial L / \partial Y$($B \times d_{\mathrm{out}}$):

$$
\bar{W} = \bar{Y}^\top X, \quad \bar{X} = \bar{Y} W, \quad \bar{\mathbf{b}} = \sum_{\mathrm{batch}} \bar{Y}
$$

张量 shape
$\bar{W}$ $d_{\mathrm{out}} \times d_{\mathrm{in}}$
$\bar{X}$ $B \times d_{\mathrm{in}}$

2. ReLU / Sigmoid / Tanh(D3)

ReLU:$y = \max(0, x)$ → $\bar{x} = \bar{y} \odot \mathbb{1}_{x>0}$

Sigmoid:$\sigma(x)$ → $\bar{x} = \bar{y} \odot \sigma(x)(1-\sigma(x))$

Tanh:$\bar{x} = \bar{y} \odot (1 - \tanh^2(x))$

存量激活函数


3. Softmax + CrossEntropy(D3–D6)

图 2 p - y 简洁梯度

Softmax:$p_i = e^{z_i} / \sum_j e^{z_j}$。One-hot 标签 $y$,CE $L = -\sum_i y_i \log p_i$。

联立 backward(对 logits $\mathbf{z}$):

$$
\frac{\partial L}{\partial z_i} = p_i - y_i
$$

性质 说明
简洁 无需显式 Jacobian
数值 log_softmax 算 $L$
Math-05/03 CE 梯度 = $\hat{p} - p_{\mathrm{true}}$

Label smoothing:$y_i \leftarrow (1-\varepsilon)\delta_{i,k} + \varepsilon/K$ → 梯度 $p_i - y_i^{\mathrm{smooth}}$。


4. LayerNorm(D3)

对特征维 $d$,单样本 $\mathbf{x}$:

$$
\hat{x}_i = \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}}, \quad y_i = \gamma_i \hat{x}_i + \beta_i
$$

$\bar{\mathbf{x}}$ 涉及 $\mu,\sigma$ 对全体 $x_i$ 的依赖,公式较长;实现交给框架。直觉:归一化后梯度更稳(Math-04/10)。


5. shape 总表(D7)

图 3 Linear + CE 栈

输入 输出 参数梯度
Linear $B \times d$ $B \times k$ $W$: $k \times d$
ReLU 同形 同形
Softmax+CE $B \times K$ logits 标量 $L$
Embedding $B \times L$ idx $B \times L \times h$ $E$: $V \times h$

6. 局限(D8)

图 4 实现注意

问题 说明
Conv 梯度 im2col / 专用 CUDA,手推见 CS231n
Softmax 分开写 数值不稳定
$\bar{W}$ batch 平均 需除以 $B$ 若 loss 是 mean

7. PyTorch 验证 Linear+CE(D12)

1
2
3
4
5
6
7
8
9
10
11
import torch
import torch.nn.functional as F

B, d, K = 8, 10, 5
x = torch.randn(B, d, requires_grad=True)
W = torch.randn(K, d, requires_grad=True)
logits = F.linear(x, W)
target = torch.randint(0, K, (B,))
loss = F.cross_entropy(logits, target)
loss.backward()
# logits grad = softmax(logits) - one_hot(target)

8. 小结

Linear:$\bar{W}=\bar{Y}^\top X$;Softmax+CE:$\bar{z}=p-y$。Attention 梯度见 20 专篇

系列导航04 反向传播 | 10 autograd

-------------本文结束感谢您的阅读-------------