4.4  数值稳定性与模型初始化

在 4.2 节 中,用 \(\mathcal{N}(0, 0.01^2)\) 权重初始化单隐藏层 MLP 虽然使第一轮进展缓慢,但网络随后恢复并达到了 \(87\%\) 的准确率。如果沿用同样的 \(\mathcal{N}(0, 0.01^2)\) 初始化堆叠十个宽度为 \(256\) 的隐藏层,会发生什么?十轮过后,损失仍纹丝不动地停在 \(\log 10 \approx 2.30\),准确率停在 \(10\%\) 的随机猜测水平。反之,若用 \(\mathcal{N}(0, 1)\) 初始化权重,激活值和梯度会大得惊人,单次 SGD 更新就会把权重推向极远,使下一次前向传播上溢为 inf 和 NaN。

如 4.3 节 所示,在 \(K\) 层网络中,前向激活值和反向梯度都要穿过 \(K\) 个权重与斜率矩阵的连乘。除非每层都能保持信号方差、使乘性因子接近 \(1\),否则信号要么按指数消失到零,要么按指数爆炸到无穷大。本节量化逐层方差传播,推导 Xavier 与 He 初始化,在 Fashion-MNIST 的 10 层 MLP 上验证它们,并证明为什么初始权重必须随机以打破隐藏单元之间的置换对称性。

4.4.1 梯度消失与梯度爆炸

4.4.1.1 跨层连乘

在宽度为 \(h\)、隐藏层为 \(\mathbf{Z}^{(k)} = \mathbf{H}^{(k-1)}\mathbf{W}^{(k)} + \mathbf{b}^{(k)}\) 与 \(\mathbf{H}^{(k)} = \phi(\mathbf{Z}^{(k)})\) 的 \(K\) 层 MLP 中,4.3 节 给出的反向递推按下式将激活梯度向下传递一层:

\[ \frac{\partial L}{\partial \mathbf{H}^{(k-1)}} = \Bigl(\frac{\partial L}{\partial \mathbf{H}^{(k)}} \odot \phi'\bigl(\mathbf{Z}^{(k)}\bigr)\Bigr)\, \mathbf{W}^{(k)\top}. \tag{4.4.1}\]

将 式 4.4.1 从顶层隐藏层 \(K - 1\) 展开到第 \(k\) 层,即可把第 \(k\) 层的梯度写成 \(K - 1 - k\) 个矩阵–斜率因子的连乘:

\[ \begin{aligned} \frac{\partial L}{\partial \mathbf{H}^{(k)}} &= \frac{\partial L}{\partial \mathbf{H}^{(K-1)}}\; \underbrace{\odot\, \phi'\bigl(\mathbf{Z}^{(K-1)}\bigr)\, \mathbf{W}^{(K-1)\top}}_{\textrm{layer } K-1} \\ &\quad \cdots\; \underbrace{\odot\, \phi'\bigl(\mathbf{Z}^{(k+1)}\bigr)\, \mathbf{W}^{(k+1)\top}}_{\textrm{layer } k+1}. \end{aligned} \tag{4.4.2}\]

考虑单个样本经过宽度为 \(h\) 的一层,其上游梯度行为 \(\mathbf{g}'\)、下游梯度行为 \(\mathbf{g}\),权重 \(w_{ij}\) 独立同分布且均值为 \(0\)、方差为 \(\tau^2\)。在初始化时将权重、斜率和上游梯度近似视为相互独立,则每个分量 \(g_i = \sum_{j=1}^h w_{ij}\,\phi'(z_j)\,g'_j\) 的均方期望为

\[ \begin{aligned} \mathbb{E}[g_i^2] &= \sum_{j=1}^h \mathbb{E}[w_{ij}^2]\,\mathbb{E}[\phi'(z_j)^2]\,\mathbb{E}[(g'_j)^2] \\ &= \underbrace{h\, \tau^2\, \mathbb{E}\bigl[\phi'(z)^2\bigr]}_{\textrm{per-layer factor}}\, \mathbb{E}[(g'_j)^2]. \end{aligned} \tag{4.4.3}\]

经过 \(t\) 层后,梯度的均方值会乘以 \(\big(h\,\tau^2\,\mathbb{E}[\phi'(z)^2]\big)^t\)。对对称分布的预激活值与 ReLU,有一半时间 \(\phi'(z) \in \{0, 1\}\) 取 \(1\),因此 \(\mathbb{E}[\phi'(z)^2] = 1/2\),每层倍率为 \(\frac{1}{2}h\tau^2\)。在宽度 \(h = 256\) 时:

  • 取 \(\tau = 0.01\):倍率为 \(256 \times 10^{-4} / 2 = 0.0128\),经过 \(9\) 跳后梯度均方值衰减为原来的 \(0.0128^9 \approx 10^{-17}\)(梯度消失)。
  • 取 \(\tau = 1\):倍率为 \(256 \times 1 / 2 = 128\),经过 \(9\) 跳后梯度均方值膨胀为原来的 \(128^9 \approx 10^{19}\)(梯度爆炸)。
  • 采用 sigmoid 激活函数(\(\sigma'(z) \leq 1/4\),因此 \(\mathbb{E}[\sigma'(z)^2] \leq 1/16\)):即便 \(h\tau^2 = 1\),每层也会将梯度均方值至少压缩到原来的 \(16\) 分之一 (Bengio 等 1994年)。

下面用 moments 在初始化时的 10 层、宽度 256 网络上直接验证这三项预测:

def moments(phi, dphi, scale, depth=10, width=256, n=256):
    """Mean squares of the activations and of their gradients, per layer."""
    Ws = [scale * torch.randn(width, width) for _ in range(depth)]
    H, Zs, acts = torch.randn(n, width), [], []
    for W in Ws:  # forward pass, keeping the pre-activations
        Zs.append(H @ W)
        H = phi(Zs[-1])
        acts.append(float((H ** 2).mean()))
    G, grads = torch.randn(n, width), []  # dL/dH at the top layer
    for W, Z in zip(reversed(Ws), reversed(Zs)):  # backward pass
        grads.insert(0, float((G ** 2).mean()))
        G = (G * dphi(Z)) @ W.T  # dL/dH one layer down
    return acts, grads

relu = (torch.relu, lambda Z: (Z > 0).float())
sigmoid = (torch.sigmoid, lambda Z: torch.sigmoid(Z) * (1 - torch.sigmoid(Z)))
def moments(phi, dphi, scale, depth=10, width=256, n=256):
    """Mean squares of the activations and of their gradients, per layer."""
    Ws = [scale * tf.random.normal((width, width)) for _ in range(depth)]
    H, Zs, acts = tf.random.normal((n, width)), [], []
    for W in Ws:  # forward pass, keeping the pre-activations
        Zs.append(H @ W)
        H = phi(Zs[-1])
        acts.append(float(tf.reduce_mean(H ** 2)))
    G, grads = tf.random.normal((n, width)), []  # dL/dH at the top layer
    for W, Z in zip(reversed(Ws), reversed(Zs)):  # backward pass
        grads.insert(0, float(tf.reduce_mean(G ** 2)))
        G = (G * dphi(Z)) @ tf.transpose(W)  # dL/dH one layer down
    return acts, grads

relu = (tf.nn.relu, lambda Z: tf.cast(Z > 0, tf.float32))
sigmoid = (tf.sigmoid, lambda Z: tf.sigmoid(Z) * (1 - tf.sigmoid(Z)))
def moments(phi, dphi, scale, depth=10, width=256, n=256):
    """Mean squares of the activations and of their gradients, per layer."""
    Ws = [scale * jax.random.normal(d2l.get_key(), (width, width))
          for _ in range(depth)]
    H, Zs, acts = jax.random.normal(d2l.get_key(), (n, width)), [], []
    for W in Ws:  # forward pass, keeping the pre-activations
        Zs.append(H @ W)
        H = phi(Zs[-1])
        acts.append(float((H ** 2).mean()))
    G, grads = jax.random.normal(d2l.get_key(), (n, width)), []  # dL/dH
    for W, Z in zip(reversed(Ws), reversed(Zs)):  # backward pass
        grads.insert(0, float((G ** 2).mean()))
        G = (G * dphi(Z)) @ W.T  # dL/dH one layer down
    return acts, grads

relu = (jax.nn.relu, lambda Z: (Z > 0).astype(jnp.float32))
sigmoid = (jax.nn.sigmoid,
           lambda Z: jax.nn.sigmoid(Z) * (1 - jax.nn.sigmoid(Z)))
def moments(phi, dphi, scale, depth=10, width=256, n=256):
    """Mean squares of the activations and of their gradients, per layer."""
    Ws = [scale * mnp.random.normal(size=(width, width))
          for _ in range(depth)]
    H, Zs, acts = mnp.random.normal(size=(n, width)), [], []
    for W in Ws:  # forward pass, keeping the pre-activations
        Zs.append(H @ W)
        H = phi(Zs[-1])
        acts.append(float((H ** 2).mean()))
    G, grads = mnp.random.normal(size=(n, width)), []  # dL/dH at the top
    for W, Z in zip(reversed(Ws), reversed(Zs)):  # backward pass
        grads.insert(0, float((G ** 2).mean()))
        G = (G * dphi(Z)) @ W.T  # dL/dH one layer down
    return acts, grads

relu = (npx.relu, lambda Z: (Z > 0).astype('float32'))
sigmoid = (npx.sigmoid, lambda Z: npx.sigmoid(Z) * (1 - npx.sigmoid(Z)))

我们对比三种配置:\(\tau = 0.01\) 的 ReLU(与 4.2 节 相同)、\(\tau = 1\) 的 ReLU,以及 \(\tau^2 = 1/256\) 的 sigmoid(此时 \(h\tau^2 = 1\),从而单独分离出激活函数的衰减效应)。

runs = {'ReLU, N(0, 0.01²)': moments(*relu, 0.01),
        'ReLU, N(0, 1)': moments(*relu, 1.0),
        'sigmoid, N(0, 1/256)': moments(*sigmoid, 1 / 16)}
for name, (acts, grads) in runs.items():
    print(f'{name}: gradient mean square at layer 1: {grads[0]:.1e}')
d2l.plot(list(range(1, 11)), [grads for acts, grads in runs.values()],
         'layer', 'mean square of gradient', legend=list(runs),
         yscale='log', figsize=(4.5, 3))
ReLU, N(0, 0.01²): gradient mean square at layer 1: 8.5e-18
ReLU, N(0, 1): gradient mean square at layer 1: 8.2e+18
sigmoid, N(0, 1/256): gradient mean square at layer 1: 5.5e-12

ReLU, N(0, 0.01²): gradient mean square at layer 1: 7.8e-18
ReLU, N(0, 1): gradient mean square at layer 1: 7.3e+18
sigmoid, N(0, 1/256): gradient mean square at layer 1: 5.1e-12

ReLU, N(0, 0.01²): gradient mean square at layer 1: 8.5e-18
ReLU, N(0, 1): gradient mean square at layer 1: 7.9e+18
sigmoid, N(0, 1/256): gradient mean square at layer 1: 5.0e-12

ReLU, N(0, 0.01²): gradient mean square at layer 1: 1.3e-17
ReLU, N(0, 1): gradient mean square at layer 1: 6.8e+18
sigmoid, N(0, 1/256): gradient mean square at layer 1: 5.5e-12

在对数纵轴上,三条曲线都是直线,其斜率与解析倍率 式 4.4.3 吻合(第 1 层分别为 \(10^{-17}\)、\(10^{19}\) 和 \(5 \times 10^{-12}\))。

4.4.2 参数初始化

4.4.2.1 Xavier 初始化

如何选择初始权重方差 \(\tau^2\),使每层倍率都等于 \(1\)?考虑含 \(n_{\textrm{in}}\) 个输入(层的扇入,fan-in)和 \(n_{\textrm{out}}\) 个输出(扇出,fan-out)的线性层 \(o_j = \sum_{i=1}^{n_{\textrm{in}}} x_i w_{ij}\),其中权重 \(w_{ij}\) 独立同分布且均值为 \(0\)、方差为 \(\tau^2\),输入 \(x_i\) 不相关且均值为 \(0\)、方差为 \(\gamma^2\)。在前向传播中,\(\mathbb{E}[o_j] = 0\),且

\[\mathrm{Var}[o_j] = \mathbb{E}[o_j^2] = \sum_{i=1}^{n_{\textrm{in}}} \mathbb{E}[x_i^2]\,\mathbb{E}[w_{ij}^2] = n_{\textrm{in}}\, \tau^2 \gamma^2.\]

跨层保持前向方差需要 \(n_{\textrm{in}}\tau^2 = 1\);由单位斜率下的 式 4.4.3,保持反向梯度方差需要 \(n_{\textrm{out}}\tau^2 = 1\)。当 \(n_{\textrm{in}} \neq n_{\textrm{out}}\) 时,Xavier 初始化(又称 Glorot 初始化 (Glorot 和 Bengio 2010年))取两者的平均:

\[\frac{1}{2}(n_{\textrm{in}} + n_{\textrm{out}})\,\tau^2 = 1 \quad \Longleftrightarrow \quad \tau^2 = \frac{2}{n_{\textrm{in}} + n_{\textrm{out}}}, \tag{4.4.4}\]

即从 \(\mathcal{N}\!\left(0, \frac{2}{n_{\textrm{in}} + n_{\textrm{out}}}\right)\) 或方差匹配的均匀分布 \(U\!\left(-\sqrt{\frac{6}{n_{\textrm{in}} + n_{\textrm{out}}}},\, \sqrt{\frac{6}{n_{\textrm{in}} + n_{\textrm{out}}}}\right)\) 中采样权重。Xavier 初始化是线性层以及零中心单位斜率激活函数(如 \(\tanh\))的标准选择。

4.4.2.2 He 初始化

对于 ReLU 层,将对称零均值预激活值 \(z\) 的负半轴置零会使其均方值减半:\(\mathbb{E}[\mathrm{ReLU}(z)^2] = \frac{1}{2}\mathbb{E}[z^2]\)。只要权重零均值且独立,即便输入 \(x_i = \mathrm{ReLU}(z_i)\) 的均值为正,\(\mathbb{E}[o_j^2] = n_{\textrm{in}}\tau^2\,\mathbb{E}[x_i^2]\) 依然成立,因此激活均方值 \(v^{(k)} = \mathbb{E}[(h_i^{(k)})^2]\) 经过一层 ReLU 后按如下方式演化:

\[v^{(k)} = \frac{1}{2}\, n_{\textrm{in}}\, \tau^2\, v^{(k-1)}. \tag{4.4.5}\]

因此,要使 \(v^{(k)} = v^{(k-1)}\) 随深度保持不变,必须将方差加倍:

\[\tau^2 = \frac{2}{n_{\textrm{in}}}. \tag{4.4.6}\]

这就是 He 初始化(又称 Kaiming 初始化 (He 等 2015年)),是 ReLU 网络的默认方案(注意,除非显式指定 He 初始化,否则框架标准线性层往往默认使用 \(1/(3n_{\textrm{in}})\)、\(1/n_{\textrm{in}}\) 或 Xavier)。

4.4.2.3 跨深度的激活值、梯度与训练

我们先在 10 层合成 ReLU 探针 moments(*relu, ...) 上对比 \(\mathcal{N}(0, 0.01^2)\)、Xavier(\(\tau^2 = 1/256\))和 He(\(\tau^2 = 2/256\)):

runs = {'N(0, 0.01²)': moments(*relu, 0.01),
        'Xavier': moments(*relu, (1 / 256) ** 0.5),
        'He': moments(*relu, (2 / 256) ** 0.5)}
for name, (acts, grads) in runs.items():
    print(f'{name}: activations at layer 10: {acts[-1]:.1e}, '
          f'gradient at layer 1: {grads[0]:.1e}')
d2l.plot(list(range(1, 11)), [acts for acts, grads in runs.values()],
         'layer', 'mean square of activations', legend=list(runs),
         yscale='log', figsize=(4.5, 3))
N(0, 0.01²): activations at layer 10: 1.2e-19, gradient at layer 1: 1.2e-17
Xavier: activations at layer 10: 7.4e-04, gradient at layer 1: 1.9e-03
He: activations at layer 10: 5.7e-01, gradient at layer 1: 8.3e-01

N(0, 0.01²): activations at layer 10: 1.1e-19, gradient at layer 1: 8.8e-18
Xavier: activations at layer 10: 7.1e-04, gradient at layer 1: 1.8e-03
He: activations at layer 10: 1.2e+00, gradient at layer 1: 1.0e+00

N(0, 0.01²): activations at layer 10: 1.7e-19, gradient at layer 1: 9.8e-18
Xavier: activations at layer 10: 9.4e-04, gradient at layer 1: 1.9e-03
He: activations at layer 10: 1.2e+00, gradient at layer 1: 1.2e+00

N(0, 0.01²): activations at layer 10: 1.0e-19, gradient at layer 1: 8.5e-18
Xavier: activations at layer 10: 6.0e-04, gradient at layer 1: 1.7e-03
He: activations at layer 10: 9.0e-01, gradient at layer 1: 9.6e-01

可以看到,\(\mathcal{N}(0, 0.01^2)\) 把第 10 层激活值压扁到 \(\sim 10^{-19}\),Xavier 在每个 ReLU 层都将激活均方值减半(第 10 层降至 \(\sim 2^{-10} \approx 10^{-3}\)),而 He 初始化将激活值与梯度都稳定在 \(O(1)\) 附近。为了观察这种方差传播如何支配真实训练,下面定义一个含 10 个隐藏层的 ReLU 分类器 DeepMLP,按规则 std(n_in, n_out) 为每层设置权重标准差:

class DeepMLP(d2l.Classifier):
    """A deep MLP whose weights have the standard deviation std(n_in, n_out)."""
    def __init__(self, std, lr, depth=10, width=256):
        super().__init__()
        self.save_hyperparameters(ignore=['std'])
        sizes = [784] + [width] * depth + [10]
        layers = [nn.Flatten()]
        for n_in, n_out in zip(sizes[:-1], sizes[1:]):
            layer = nn.Linear(n_in, n_out)
            nn.init.normal_(layer.weight, std=std(n_in, n_out))
            nn.init.zeros_(layer.bias)
            layers += [layer, nn.ReLU()]
        self.net = nn.Sequential(*layers[:-1])  # No ReLU after the logits
class DeepMLP(d2l.Classifier):
    """A deep MLP whose weights have the standard deviation std(n_in, n_out)."""
    def __init__(self, std, lr, depth=10, width=256):
        super().__init__()
        self.save_hyperparameters(ignore=['std'])
        sizes = [784] + [width] * depth + [10]
        self.net = tf.keras.models.Sequential([tf.keras.layers.Flatten()])
        for k, (n_in, n_out) in enumerate(zip(sizes[:-1], sizes[1:])):
            normal = tf.keras.initializers.RandomNormal(stddev=std(n_in, n_out))
            self.net.add(tf.keras.layers.Dense(
                n_out, activation='relu' if k < depth else None,
                kernel_initializer=normal))
class DeepMLP(d2l.Classifier):
    """A deep MLP whose weights have the standard deviation std(n_in, n_out)."""
    def __init__(self, std, lr, depth=10, width=256, rngs=None):
        super().__init__()
        self.save_hyperparameters(ignore=['std', 'rngs'])
        rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
        sizes = [784] + [width] * depth + [10]
        layers = []
        for n_in, n_out in zip(sizes[:-1], sizes[1:]):
            normal = nnx.initializers.normal(std(n_in, n_out))
            layers += [nnx.Linear(n_in, n_out, kernel_init=normal, rngs=rngs),
                       nnx.relu]
        self.net = nnx.Sequential(*layers[:-1])  # No ReLU after the logits

    def forward(self, X):
        return self.net(X.reshape((X.shape[0], -1)))  # Flatten each image
class DeepMLP(d2l.Classifier):
    """A deep MLP whose weights have the standard deviation std(n_in, n_out)."""
    def __init__(self, std, lr, depth=10, width=256):
        super().__init__()
        self.save_hyperparameters(ignore=['std'])
        sizes = [784] + [width] * depth + [10]
        self.net = nn.Sequential()
        for k, (n_in, n_out) in enumerate(zip(sizes[:-1], sizes[1:])):
            self.net.add(nn.Dense(
                n_out, activation='relu' if k < depth else None,
                weight_initializer=init.Normal(std(n_in, n_out))))
        self.net.initialize()

三次运行共享完全相同的架构和超参数,仅改变 std(n_in, n_out)。下面对比它们的训练曲线和最终验证准确率。

inits = {'N(0, 0.01²)': lambda n_in, n_out: 0.01,
         'Xavier': lambda n_in, n_out: (2 / (n_in + n_out)) ** 0.5,
         'He': lambda n_in, n_out: (2 / n_in) ** 0.5}
data = d2l.FashionMNIST(batch_size=256)
losses = {}
for name, std in inits.items():
    trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
    trainer.board.display = False
    trainer.fit(DeepMLP(std, lr=0.05), data)
    losses[name] = trainer.history['train_loss']
    print(f'{name}: validation accuracy {trainer.history["val_acc"][-1]:.2f}')
d2l.plot(list(range(1, 11)), list(losses.values()), 'epoch', 'training loss',
         legend=list(losses), figsize=(4.5, 3))
N(0, 0.01²): validation accuracy 0.10
Xavier: validation accuracy 0.84
He: validation accuracy 0.87

N(0, 0.01²): validation accuracy 0.10
Xavier: validation accuracy 0.85
He: validation accuracy 0.85

N(0, 0.01²): validation accuracy 0.10
Xavier: validation accuracy 0.81
He: validation accuracy 0.86

N(0, 0.01²): validation accuracy 0.10
Xavier: validation accuracy 0.84
He: validation accuracy 0.86

10 轮训练曲线与上述方差分析高度吻合:

  • 在 \(\mathcal{N}(0, 0.01^2)\) 下,第 10 层激活值(\(\sim 10^{-19}\))与第 1 层梯度(\(\sim 10^{-17}\))完全消失,训练损失停在 \(\log 10 \approx 2.30\),验证准确率停在 \(10\%\)。
  • 在 Xavier 下,每个 ReLU 层损失因子 \(2\),使信号衰减为原来的 \(2^{-10} \approx 10^{-3}\),导致第 1 轮起步偏慢,随后才恢复到 \(80\%\) 以上的准确率。
  • 在 He 初始化下,全部 10 层的激活值与梯度都保持在 \(1\) 的量级,训练损失从第 1 轮起即顺畅下降。

不过,初始化并非深度的全部答案。方差论证仅描述第 \(0\) 步的网络:一旦 SGD 移动了权重,就没有什么能保证 式 4.4.3 中的每层倍率仍接近 \(1\)。因此,数十乃至数百层的网络依赖贯穿整个训练过程的机制:规范化层(7.3 节)在每一步重新缩放激活值,残差连接(7.4 节)为信号和梯度提供绕过各层的通道,梯度裁剪(8.4 节)则限制偶发的梯度爆炸。好的初始化让训练顺利起步,而这些机制在之后持续维系信号尺度。

4.4.3 隐藏单元间的对称性

为什么初始权重必须随机,而不能把 \(\mathbf{W}^{(1)}\) 的每个元素都设为确定性常数 \(c = \sqrt{2 / n_{\textrm{in}}}\)?因为同一层中的隐藏单元具有置换对称性:若 \(\mathbf{W}^{(1)}\) 的所有列初始相同(且 \(\mathbf{W}^{(2)}\) 的所有行初始相同),每个隐藏单元就会算出相同的前向激活值、收到相同的反向梯度,并在每次 SGD 更新中迈出完全相同的步子,使含 256 个单元的隐藏层永久退化为单个有效神经元。下面在 16 单元层上验证:常数 He 尺度权重会产生完全相同的梯度列(单元间差异为 0.00),而随机 He 尺度权重则让每个单元获得不同的梯度方向:

def hidden_grad(W1, W2, X, y):
    """Gradient of the squared loss with respect to the hidden weights."""
    W1 = W1.clone().requires_grad_(True)
    L = ((torch.relu(X @ W1) @ W2 - y) ** 2).mean() / 2
    L.backward()
    return W1.grad

d, h = 20, 16
X, y = torch.randn(64, d), torch.randn(64, 1)
c, c_out = (2 / d) ** 0.5, (1 / h) ** 0.5
inits = {'constant': (torch.full((d, h), c), torch.full((h, 1), c_out)),
         'random': (c * torch.randn(d, h), c_out * torch.randn(h, 1))}
for name, (W1, W2) in inits.items():
    G = hidden_grad(W1, W2, X, y)
    print(f'{name}: largest difference between two hidden units '
          f'{float((G - G[:, :1]).abs().max()):.2f}')
constant: largest difference between two hidden units 0.00
random: largest difference between two hidden units 0.16
def hidden_grad(W1, W2, X, y):
    """Gradient of the squared loss with respect to the hidden weights."""
    W1 = tf.Variable(W1)
    with tf.GradientTape() as tape:
        L = tf.reduce_mean((tf.nn.relu(X @ W1) @ W2 - y) ** 2) / 2
    return tape.gradient(L, W1)

d, h = 20, 16
X, y = tf.random.normal((64, d)), tf.random.normal((64, 1))
c, c_out = (2 / d) ** 0.5, (1 / h) ** 0.5
inits = {'constant': (tf.fill((d, h), c), tf.fill((h, 1), c_out)),
         'random': (c * tf.random.normal((d, h)),
                    c_out * tf.random.normal((h, 1)))}
for name, (W1, W2) in inits.items():
    G = hidden_grad(W1, W2, X, y)
    print(f'{name}: largest difference between two hidden units '
          f'{float(tf.reduce_max(tf.abs(G - G[:, :1]))):.2f}')
constant: largest difference between two hidden units 0.00
random: largest difference between two hidden units 0.21
def hidden_grad(W1, W2, X, y):
    """Gradient of the squared loss with respect to the hidden weights."""
    L = lambda W1: ((jax.nn.relu(X @ W1) @ W2 - y) ** 2).mean() / 2
    return jax.grad(L)(W1)

d, h = 20, 16
X = jax.random.normal(d2l.get_key(), (64, d))
y = jax.random.normal(d2l.get_key(), (64, 1))
c, c_out = (2 / d) ** 0.5, (1 / h) ** 0.5
inits = {'constant': (jnp.full((d, h), c), jnp.full((h, 1), c_out)),
         'random': (c * jax.random.normal(d2l.get_key(), (d, h)),
                    c_out * jax.random.normal(d2l.get_key(), (h, 1)))}
for name, (W1, W2) in inits.items():
    G = hidden_grad(W1, W2, X, y)
    print(f'{name}: largest difference between two hidden units '
          f'{float(jnp.abs(G - G[:, :1]).max()):.2f}')
constant: largest difference between two hidden units 0.00
random: largest difference between two hidden units 0.09
def hidden_grad(W1, W2, X, y):
    """Gradient of the squared loss with respect to the hidden weights."""
    W1 = W1.copy()
    W1.attach_grad()
    with autograd.record():
        L = ((npx.relu(X @ W1) @ W2 - y) ** 2).mean() / 2
    L.backward()
    return W1.grad

d, h = 20, 16
X, y = mnp.random.normal(size=(64, d)), mnp.random.normal(size=(64, 1))
c, c_out = (2 / d) ** 0.5, (1 / h) ** 0.5
inits = {'constant': (mnp.full((d, h), c), mnp.full((h, 1), c_out)),
         'random': (c * mnp.random.normal(size=(d, h)),
                    c_out * mnp.random.normal(size=(h, 1)))}
for name, (W1, W2) in inits.items():
    G = hidden_grad(W1, W2, X, y)
    print(f'{name}: largest difference between two hidden units '
          f'{float(mnp.abs(G - G[:, :1]).max()):.2f}')
constant: largest difference between two hidden units 0.00
random: largest difference between two hidden units 0.20

4.4.4 小结

在宽度为 \(h\)、初始权重方差为 \(\tau^2\) 的 \(K\) 层 MLP 中,每一层大约将激活值和梯度的均方值乘以 \(h\tau^2\,\mathbb{E}[\phi'(z)^2]\);除非该因子接近 \(1\),否则信号会随深度指数级消失或爆炸。Xavier 初始化令 \(\tau^2 = 2/(n_{\textrm{in}} + n_{\textrm{out}})\) 以平衡线性层和 \(\tanh\) 层的前向与反向方差;He 初始化将方差加倍至 \(\tau^2 = 2/n_{\textrm{in}}\) 以抵消 ReLU 将负半轴置零的影响,使深层 ReLU 堆叠从第 1 轮起就能顺畅训练。由于同层隐藏单元具有置换对称性,权重还必须独立随机采样而不能设为常数,否则所有单元在整个训练期间都会收到相同的梯度与更新。在第 \(0\) 步之后,更深的架构会将方差保持初始化与规范化层和残差连接配合使用,在权重演化过程中持续维持信号尺度。

4.4.5 练习

  1. 谱范数上界。对单个样本(写成列向量),式 4.4.1 将第 \(k\) 层上方的梯度 \(\mathbf{g}'\) 乘以矩阵 \(\mathbf{M}^{(k)} = \mathbf{W}^{(k)} \operatorname{diag}\bigl(\phi'(\mathbf{z}^{(k)})\bigr)\),其中 \(\operatorname{diag}(\cdot)\) 将向量元素置于零矩阵的对角线上,因此 式 4.4.2 中的梯度等于 \(K - 1 - k\) 个这类矩阵连乘再乘以顶层梯度。谱范数(最大奇异值)满足次乘性:\(\|\mathbf{A}\mathbf{B}\|_2 \le \|\mathbf{A}\|_2 \|\mathbf{B}\|_2\)。
    1. 根据定义 \(\|\mathbf{A}\|_2 = \max_{\mathbf{x} \neq 0} \|\mathbf{A}\mathbf{x}\| / \|\mathbf{x}\|\) 证明次乘性。
    2. 用各因子的范数 \(\|\mathbf{M}^{(k)}\|_2\) 给出梯度范数的上界。这些范数满足什么条件时,该上界不会随深度呈几何级数增长?
    3. 该不等式只是上界。解释为何上一问的条件能排除梯度爆炸却无法排除梯度消失,并给出两个等号成立的 \(2 \times 2\) 矩阵,使其乘积的谱范数严格小于 1。
  2. 其他对称性。置换隐藏单元并非唯一不改变 MLP 函数的参数变换。考虑单隐藏层 MLP,其中隐藏单元 \(j\) 的输入权重为 \(\mathbf{w}_j\)、偏置为 \(b_j\)、输出权重为 \(\mathbf{v}_j\)。
    1. 证明对 \(\alpha > 0\) 有 \(\textrm{ReLU}(\alpha z) = \alpha\, \textrm{ReLU}(z)\),并据此说明将 \((\mathbf{w}_j, b_j, \mathbf{v}_j)\) 替换为 \((\alpha \mathbf{w}_j, \alpha b_j, \mathbf{v}_j / \alpha)\) 不改变 ReLU 网络的函数。
    2. 找出一种单个隐藏单元的参数变换,使 \(\tanh\) 网络的函数保持不变。
    3. 相同的隐藏单元是置换变换的不动点,从该不动点出发的梯度下降会一直停留在那里。找出在上一问变换下保持不变的单元参数,并证明若将 \(\tanh\) 网络的所有权重和偏置初始化为零,梯度下降在每一步都只会更新输出偏置。
    改编自 Simon Prince,Understanding Deep Learning,习题 3.5、4.3 和 7.15。
  3. 扇入缩放与平均扇入扇出缩放。仿照 He 等 (2015年),考虑 \(K\) 层线性网络,其中第 \(k\) 层将 \(n_{k-1}\) 个输入映射到 \(n_k\) 个输出,权重方差为 \(\tau_k^2\)。由 4.4.2.1 节 的计算可知,第 \(k\) 层将前向信号方差乘以 \(n_{k-1}\tau_k^2\),将反向信号方差乘以 \(n_k\tau_k^2\)。
    1. 在每层令 \(\tau_k^2 = 1/n_{k-1}\)。证明前向方差保持不变,且在任意深度下反向方差的总变化因子均为 \(n_K / n_0\)。
    2. 令各层宽度交替为 \(100, 400, 100, 400, \ldots\),且每层使用 Xavier 初始化。计算一对 \(100 \to 400 \to 100\) 层将前向方差乘以的因子,以及经过 50 对后的总因子。
    3. 两条规则中,哪一条能对任意宽度序列都将前向与反向方差保持在初始值的与深度无关的常数倍以内?
  4. ReLU 下的方差。● 4.4.2.2 节 中的推导追踪均方值 \(\mathbb{E}[\textrm{ReLU}(z)^2]\) 而非方差,因为下一层的预激活值 \(o = \sum_i x_i w_i\)(输入 \(x_i = \textrm{ReLU}(z_i)\),权重独立且零均值)无论 \(x_i\) 的均值为何,均满足 \(\textrm{Var}[o] = n_\textrm{in}\tau^2 \mathbb{E}[x_i^2]\)。
    1. 对 \(z \sim \mathcal{N}(0, \nu^2)\),计算 \(\mathbb{E}[\textrm{ReLU}(z)]\) 和 \(\textrm{Var}[\textrm{ReLU}(z)]\),并证明其方差等于 \(\left(\tfrac{1}{2} - \tfrac{1}{2\pi}\right)\nu^2\) 而非 \(\tfrac{1}{2}\nu^2\)。
    2. 一种容易诱人误用的捷径是在 Xavier 推导中用 \(\textrm{Var}[x_i]\) 代替 \(\mathbb{E}[x_i^2]\)。证明该捷径会给出 \(\tau^2 = 2 / \bigl(n_\textrm{in}(1 - 1/\pi)\bigr)\) 而非 \(2/n_\textrm{in}\),并计算按此初始化的每层 ReLU 实际将均方值乘以的因子以及 50 层的总因子。
  5. [code] tanh 网络。● 将 4.4.2.3 节 中的 ReLU 换成 \(\tanh\),使用 Xavier 初始化和 50 层网络重复测量。此时每层将输入均方值 \(m\) 映射到 \(m' = \mathbb{E}[\tanh(z)^2]\),其中 \(z\) 近似服从 \(\mathcal{N}(0, m)\)。
    1. 利用小 \(z\) 时的近似 \(\tanh(z)^2 \approx z^2 - \tfrac{2}{3}z^4\) 证明 \(m' \approx m - 2m^2\)。经过多层后,均方值是保持恒定、呈几何衰减,还是衰减得更慢?证明当 \(k\) 较大时第 \(k\) 层的均方值约为 \(1/(2k)\)。
    2. 在对数坐标上绘制实测均方值随层数的变化以验证该预测。梯度又会如何变化?