def associative_scan(combine, elems):
"""All prefixes of elems under an associative combine; time is axis 1."""
s = 1
# Autograd keeps the tensors of every round for the backward pass
while s < elems[0].shape[1]: # Combine every position with the one s back
earlier = tuple(x[:, :-s] for x in elems)
later = tuple(x[:, s:] for x in elems)
elems = tuple(torch.cat([x[:, :s], y], 1)
for x, y in zip(elems, combine(earlier, later)))
s *= 2
return elems
def linear_scan(a, b, h0=None):
"""All states of h_t = a_t * h_{t-1} + b_t; time is the second axis."""
a = a.expand_as(b) # Decays may omit axes on which they do not vary
if h0 is not None: # Fold the initial state into the first step
b = torch.cat([a[:, :1] * h0.unsqueeze(1) + b[:, :1], b[:, 1:]], 1)
def combine(earlier, later):
(a1, b1), (a2, b2) = earlier, later
return a1 * a2, a2 * b1 + b2
return associative_scan(combine, (a, b))[1]12.3 线性循环与并行扫描
12.1 节 中的门控网络能将信息保持数百步,但它们依然逐词元处理序列,因为每一步的门与候选状态都依赖于上一时刻状态 \(\mathbf{h}_{t-1}\)。在长度为 \(4{,}096\) 的序列上,GRU 要串行执行 \(4{,}096\) 次更新,训练期间大部分 GPU 算力处于闲置,而 Transformer 却能通过大矩阵乘法并行处理所有位置。循环网络能否在保留 \(O(1)\) 状态自回归生成的同时,实现跨所有位置的并行训练?
可以——只要让门与候选状态仅依赖于当前输入 \(\mathbf{x}_t\),使循环关于 \(\mathbf{h}_{t-1}\) 变为线性(更准确地说是仿射)。仿射更新可以像前缀和一样按结合律复合 (Hillis 和 Steele 1986年),在 \(\lceil \log_2 T \rceil\) 轮并行计算内求得全部 \(T\) 个状态。下面我们从标量衰减出发过渡到 Feng 等 (2024年) 的极简 GRU(MinGRU),实现并行结合扫描,在字节级 WikiText-103 上评估 MinGRU,并在直至 \(16{,}384\) 词元的长度上对比顺序 GRU 与因果注意力的挂钟时间缩放。
12.3.1 线性循环
12.3.1.1 单个衰减数
从保留先前值固定比例 \(a \in (0, 1)\) 并加上输入 \(x_t\) 的标量状态 \(h_t\) 开始:
\[h_t = a\, h_{t-1} + x_t, \qquad h_0 = 0. \tag{12.3.1}\]
展开 式 12.3.1 即可用过去输入直接表示 \(h_t\):
\[h_t = \sum_{s=1}^{t} a^{t-s} x_s. \tag{12.3.2}\]
每个 \(h_t\) 都是过去输入的指数加权移动平均,半衰期为 \(\ln 2 / \ln(1/a)\) 步(\(a = 0.9\) 时为 \(\approx 7\) 步;\(a = 0.999\) 时为 \(\approx 693\) 步),且梯度 \(\partial h_t / \partial x_s = a^{t-s}\) 按完全相同的速率衰减。
12.3.1.2 输入相关的衰减
推广至带输入相关逐元素衰减 \(\mathbf{a}_t \in (0, 1)^d\) 与写入向量 \(\mathbf{b}_t \in \mathbb{R}^d\) 的向量状态 \(\mathbf{h}_t \in \mathbb{R}^d\),即得仿射循环:
\[ \mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t, \qquad \mathbf{a}_t = \mathbf{a}(\mathbf{x}_t), \quad \mathbf{b}_t = \mathbf{b}(\mathbf{x}_t). \tag{12.3.3}\]
展开 式 12.3.3 后,幂次 \(a^{t-s}\) 变为中间衰减因子的累积乘积:
\[ \mathbf{h}_t = \sum_{s=1}^{t} \Big( \prod_{r=s+1}^{t} \mathbf{a}_r \Big) \odot \mathbf{b}_s. \tag{12.3.4}\]
由于 \(\mathbf{a}_t\) 与 \(\mathbf{b}_t\) 仅依赖于 \(\mathbf{x}_t\),全部 \(T\) 个衰减向量和写入向量可在循环开始前跨整条序列并行算完。又因每个 \(\mathbf{a}_r \in (0, 1)^d\),过去的写入可以被选择性地保留(\(\mathbf{a}_r \approx \mathbf{1}\))或清空(\(\mathbf{a}_r \approx \mathbf{0}\))而永不爆炸。
12.3.1.3 极简 GRU
观察 12.1.3 节 的标准 GRU 中上一时刻状态 \(\mathbf{h}_{t-1}\) 进入的三处位置:
\[ \begin{aligned} \mathbf{z}_t &= \sigma(\mathbf{W}_{\textrm{xz}} \mathbf{x}_t + \underbrace{\mathbf{W}_{\textrm{hz}} \mathbf{h}_{t-1}}_{\textrm{(1)}} + \mathbf{b}_\textrm{z}),\\ \mathbf{r}_t &= \sigma(\mathbf{W}_{\textrm{xr}} \mathbf{x}_t + \underbrace{\mathbf{W}_{\textrm{hr}} \mathbf{h}_{t-1}}_{\textrm{(2)}} + \mathbf{b}_\textrm{r}),\\ \tilde{\mathbf{h}}_t &= \tanh\big(\mathbf{W}_{\textrm{xh}} \mathbf{x}_t + \underbrace{\mathbf{W}_{\textrm{hh}} (\mathbf{r}_t \odot \mathbf{h}_{t-1})}_{\textrm{(3)}} + \mathbf{b}_\textrm{h}\big), \end{aligned} \]
随后为 \(\mathbf{h}_t = \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t\)。去掉这三处标记的循环依赖(从而彻底省去重置门 \(\mathbf{r}_t\)),即得 Feng 等 (2024年) 的极简 GRU(minGRU):
\[ \begin{aligned} \mathbf{z}_t &= \sigma(\mathbf{W}_\textrm{z} \mathbf{x}_t + \mathbf{b}_\textrm{z}), \qquad \tilde{\mathbf{h}}_t = \tanh(\mathbf{W}_\textrm{h} \mathbf{x}_t + \mathbf{b}_\textrm{h}), \\ \mathbf{h}_t &= \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t. \end{aligned} \tag{12.3.5}\]
这正是衰减为 \(\mathbf{a}_t = \mathbf{z}_t\)、写入为 \(\mathbf{b}_t = (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t\) 的仿射循环 式 12.3.3,将每层参数量从 \(6d^2\) 削减至 \(2d^2\)。尽管单层 minGRU 无法根据 \(\mathbf{h}_{t-1}\) 中已有内容来调节门控,但堆叠多层带逐位置 MLP 的 minGRU 块可以在不牺牲跨时间并行求值的前提下恢复部分这种能力:每一层的门都能看到下一层的状态。这提供了每层一轮状态相关门控,而 GRU 在每一步都有一轮。12.7.3.5 节 将度量固定轮数无法完成的任务。
12.3.2 并行扫描
12.3.2.1 复合仿射步
朴素地为所有 \(t = 1, \ldots, T\) 求值展开和 式 12.3.4 需要 \(O(T^2)\) 次运算。我们转而利用函数复合的结合律。用有序对 \((\mathbf{a}_t, \mathbf{b}_t)\) 表示第 \(t\) 步的仿射映射 \(\mathbf{h} \mapsto \mathbf{a}_t \odot \mathbf{h} + \mathbf{b}_t\)。先执行第 1 步再执行第 2 步得到 \(\mathbf{a}_2 \odot (\mathbf{a}_1 \odot \mathbf{h} + \mathbf{b}_1) + \mathbf{b}_2\),仍是仿射映射,其系数为:
\[ (\mathbf{a}_1, \mathbf{b}_1) \bullet (\mathbf{a}_2, \mathbf{b}_2) = (\mathbf{a}_1 \odot \mathbf{a}_2,\ \mathbf{a}_2 \odot \mathbf{b}_1 + \mathbf{b}_2). \tag{12.3.6}\]
因为函数复合满足结合律,且任意一段连续步骤的复合仍是同样大小的单个 \((\mathbf{a}, \mathbf{b})\) 对,从 \(\mathbf{h}_0 = \mathbf{0}\) 出发计算 \(\mathbf{h}_1, \ldots, \mathbf{h}_T\) 就归约为在 \(\bullet\) 下的结合前缀扫描(从第 \(t\) 个前缀的第二个分量读出 \(\mathbf{h}_t\))。
12.3.2.2 倍增调度
图 12.3.1 展示了 Hillis 和 Steele (1986年) 在 \(T = 8\) 步上的并行倍增调度。在第 \(r = 0, 1, \ldots, \lceil \log_2 T \rceil - 1\) 轮中,每个位置与前移步幅 \(2^r\) 处的位置合并。经过 \(\lceil \log_2 T \rceil\) 轮后,每个位置都持有完整的前缀。
Hillis-Steele 倍增调度在 \(\lceil \log_2 T \rceil\) 轮并行计算中执行 \(O(T \log_2 T)\) 次合并,而 Blelloch (1990年) 的工作高效上扫/下扫树调度在 \(2\lceil \log_2 T \rceil\) 轮收缩计算中仅执行 \(\sim 2T\) 次合并。
我们将简洁的倍增调度写作 associative_scan。
我们调用 XLA 内置的工作高效 jax.lax.associative_scan。
12.3.2.3 实现
linear_scan 沿时间轴(轴 1)计算 式 12.3.3 的全部状态 \(\mathbf{h}_1, \ldots, \mathbf{h}_T\),并将可选初始状态 \(\mathbf{h}_0\) 折入第一步写入 \(\mathbf{b}_1 \leftarrow \mathbf{a}_1 \odot \mathbf{h}_0 + \mathbf{b}_1\)。
def linear_scan(a, b, h0=None):
"""All states of h_t = a_t * h_{t-1} + b_t; time is the second axis."""
a = jnp.broadcast_to(a, b.shape) # Decays may omit axes; broadcast them
if h0 is not None: # Fold the initial state into the first step
b = b.at[:, 0].add(a[:, 0] * h0)
def combine(earlier, later):
(a1, b1), (a2, b2) = earlier, later
return a1 * a2, a2 * b1 + b2
# Autograd keeps the intermediate results of the scan for the backward pass
return jax.lax.associative_scan(combine, (a, b), axis=1)[1]我们在非 2 的幂长度 \(T = 100\) 上将 linear_scan 与逐步顺序循环核对。
def sequential_scan(a, b):
h, states = torch.zeros_like(b[:, 0]), []
for a_t, b_t in zip(a.unbind(1), b.unbind(1)):
h = a_t * h + b_t
states.append(h)
return torch.stack(states, 1)
a, b = torch.rand(4, 100, 8), torch.randn(4, 100, 8)
print(f'max deviation: '
f'{(linear_scan(a, b) - sequential_scan(a, b)).abs().max():.1e}')max deviation: 4.8e-07
def sequential_scan(a, b):
def step(h, ab):
h = ab[0] * h + ab[1]
return h, h
# lax.scan steps through the leading axis, so time goes first
ab = (jnp.swapaxes(a, 0, 1), jnp.swapaxes(b, 0, 1))
return jnp.swapaxes(jax.lax.scan(step, jnp.zeros_like(b[:, 0]), ab)[1], 0, 1)
key_a, key_b = jax.random.split(d2l.get_key())
a = jax.random.uniform(key_a, (4, 100, 8))
b = jax.random.normal(key_b, (4, 100, 8))
print(f'max deviation: '
f'{jnp.abs(linear_scan(a, b) - sequential_scan(a, b)).max():.1e}')max deviation: 4.8e-07
并行扫描与顺序循环在 float32 舍入容差(\(< 10^{-6}\))内完全一致。
12.3.3 线性循环语言模型
12.3.3.1 文本上的 minGRU
围绕两个线性投影(\(\mathbf{W}_\textrm{z}\) 与 \(\mathbf{W}_\textrm{h}\))封装 linear_scan,即实现可无缝接入 d2l.SeqLM 的序列混合器 MinGRU 式 12.3.5。
class MinGRU(nn.Module):
"""The minimal GRU: its gate and candidate read only the input."""
def __init__(self, num_inputs, num_hiddens):
super().__init__()
self.W_z = nn.Linear(num_inputs, num_hiddens) # Update gate (decay)
self.W_h = nn.Linear(num_inputs, num_hiddens) # Candidate state
d2l.init_lecun(self)
def coefficients(self, X):
"""Decays a_t and writes b_t of the linear recurrence."""
Z = torch.sigmoid(self.W_z(X))
return Z, (1 - Z) * torch.tanh(self.W_h(X))
def forward(self, X): # X: (batch_size, num_steps, num_inputs)
return linear_scan(*self.coefficients(X))class MinGRU(nnx.Module):
"""The minimal GRU: its gate and candidate read only the input."""
def __init__(self, num_inputs, num_hiddens, *, rngs):
self.W_z = nnx.Linear(num_inputs, num_hiddens, rngs=rngs) # Decay
self.W_h = nnx.Linear(num_inputs, num_hiddens, rngs=rngs)
def coefficients(self, X):
"""Decays a_t and writes b_t of the linear recurrence."""
Z = jax.nn.sigmoid(self.W_z(X))
return Z, (1 - Z) * jnp.tanh(self.W_h(X))
def __call__(self, X): # X: (batch_size, num_steps, num_inputs)
return linear_scan(*self.coefficients(X))从门中去掉 \(\mathbf{h}_{t-1}\) 在字节级 WikiText-103 上会损失多少建模质量?采用与 12.1.4.2 节 完全相同的设置(4 块 d2l.SeqLM、128 字节窗口、1,000 步),我们先定义 text_model 与三个对比 arms:GRU(\(d = 256\),\(3.81\textrm{M}\) 参数)、等宽 minGRU(\(d = 256\),\(2.76\textrm{M}\) 参数)以及展宽至等参数量的 minGRU(minGRU, d=302,\(3.81\textrm{M}\) 参数):
torch.set_float32_matmul_precision('high') # fp32 matmuls may use tf32
def text_model(mixer, d): # 256 byte values; four blocks of width d
return d2l.SeqLM(256, d, [mixer(d) for _ in range(4)]).to(d2l.try_gpu())
gru = lambda d: d2l.Recurrent(d2l.init_lecun(nn.GRU(d, d, batch_first=True)))
min_gru = lambda d: MinGRU(d, d)
arms = {'GRU': (gru, 256), 'minGRU': (min_gru, 256),
'minGRU, d=302': (min_gru, 302)} # As many parameters as the GRUdef text_model(mixer, d): # 256 byte values; four blocks of width d
rngs = nnx.Rngs(d2l.get_key())
return d2l.SeqLM(256, d, [mixer(d, rngs) for _ in range(4)], rngs=rngs)
lecun = nnx.initializers.lecun_normal() # For the recurrent matrices
gru = lambda d, rngs: nnx.RNN(
nnx.GRUCell(d, d, recurrent_kernel_init=lecun, rngs=rngs), unroll=8)
min_gru = lambda d, rngs: MinGRU(d, d, rngs=rngs)
arms = {'GRU': (gru, 256), 'minGRU': (min_gru, 256),
'minGRU, d=302': (min_gru, 302)} # As many parameters as the GRU我们加载 128 字节 WikiText103 数据集,在全部三组上运行 d2l.text_table,并保留第一个训练好的 minGRU 模型以供探查:
data = d2l.WikiText103(batch_size=64, num_steps=128)
trained = d2l.text_table(text_model, arms, data)
model = trained['minGRU'][0] # The model we look inside below validation 0-15 16-63 64-127 ms/step
GRU 3,817,216 1.299/1.300 1.490/1.491 1.273/1.274 1.270/1.271 33/32
minGRU 2,764,544 1.343/1.348 1.520/1.520 1.319/1.323 1.317/1.324 26/26
minGRU, d=302 3,816,932 1.328/1.329 1.508/1.507 1.303/1.304 1.301/1.303 26/28
data = d2l.WikiText103(batch_size=64, num_steps=128)
trained = d2l.text_table(text_model, arms, data)
model = trained['minGRU'][0] # The model we look inside below validation 0-15 16-63 64-127 ms/step
GRU 3,814,144 1.300/1.299 1.491/1.491 1.274/1.273 1.271/1.271 16/16
minGRU 2,764,544 1.346/1.345 1.520/1.521 1.320/1.320 1.321/1.320 10/10
minGRU, d=302 3,816,932 1.330/1.330 1.510/1.508 1.305/1.306 1.305/1.304 10/10
在等宽(\(d = 256\))下,minGRU 落后 GRU \(\sim 0.05\) 奈特/字节(\(1.35\) 对比 \(1.30\));在等参数量(minGRU, d=302)下它弥补了约五分之二的差距(\(\sim 1.33\)),与 12.1.4.2 节 的朴素 \(\tanh\) RNN 并驾齐驱,同时胜过注意力基线(\(1.38\)),并且通过并行扫描而非顺序循环完成训练。
12.3.3.2 深入已训练的模型
为了检验 minGRU 对循环状态的依赖程度,我们在每一步之前将其状态清零来评估已训练的 \(d = 256\) 模型(StateReset,使 \(\mathbf{h}_t = \mathbf{b}_t\) 仅取决于当前字节)。
class StateReset(nn.Module):
"""A minGRU layer whose state is reset to zero before every step."""
def __init__(self, layer):
super().__init__()
self.layer = layer
def forward(self, X):
return self.layer.coefficients(X)[1]
layers = model.mixers
loss = np.mean(d2l.loss_by_position(model, data))
model.mixers = nn.ModuleList([StateReset(layer) for layer in layers])
reset = np.mean(d2l.loss_by_position(model, data))
model.mixers = layers
print(f'validation loss: {loss:.3f} nats per byte, '
f'with the state reset at every step: {reset:.3f}')validation loss: 1.343 nats per byte, with the state reset at every step: 2.481
class StateReset(nnx.Module):
"""A minGRU layer whose state is reset to zero before every step."""
def __init__(self, layer):
self.layer = layer
def __call__(self, X):
return self.layer.coefficients(X)[1]
layers = model.mixers
loss = np.mean(d2l.loss_by_position(model, data))
model.mixers = nnx.List([StateReset(layer) for layer in layers])
reset = np.mean(d2l.loss_by_position(model, data))
model.mixers = layers
print(f'validation loss: {loss:.3f} nats per byte, '
f'with the state reset at every step: {reset:.3f}')validation loss: 1.346 nats per byte, with the state reset at every step: 2.482
清零状态会使验证损失从 \(1.35\) 飙升至 \(2.48\) 奈特/字节(基本退回 11.2 节 中 \(2.45\) 奈特/字节的经验字节二元基线),证实超过 \(1.1\) 奈特/字节的收益来自状态承载的上下文。
我们还可以检视第一块中更新门衰减 \(\mathbf{z}_t\) 在训练前后的分布。向 d2l.SeqLM 添加 first_mixer_input 以便提取送入首个混合器的规范化词元嵌入。
@d2l.add_to_class(d2l.SeqLM)
def first_mixer_input(self, X):
"""What the first mixer reads: the normalized token embeddings."""
return self.norms[0](self.embedding(X))@d2l.add_to_class(d2l.SeqLM)
def first_mixer_input(self, X):
"""What the first mixer reads: the normalized token embeddings."""
return self.norms[0](self.embedding(X))将验证小批量送入未训练 minGRU 与已训练 model 的 first_gates,制表统计超过 \(0.5\)、\(0.9\) 与 \(0.99\) 的更新门比例:
def first_gates(model, X): # Gates of the first layer
return model.mixers[0].coefficients(model.first_mixer_input(X))[0]
X, _ = next(iter(data.val_dataloader())) # Validation text
X = X.to(next(model.parameters()).device)
with torch.inference_mode():
Z_init = first_gates(text_model(min_gru, 256), X) # Untrained
Z = first_gates(model, X)
print('gate above half-life in steps share at initialization trained')
for g in (0.5, 0.9, 0.99):
print(f'{g:10} {math.log(2) / -math.log(g):17.0f} '
f'{(Z_init > g).float().mean():23.1%} '
f'{(Z > g).float().mean():7.1%}')gate above half-life in steps share at initialization trained
0.5 1 49.0% 53.4%
0.9 7 1.3% 17.1%
0.99 69 0.0% 0.1%
def first_gates(model, X): # Gates of the first layer
return model.mixers[0].coefficients(model.first_mixer_input(X))[0]
X = jnp.asarray(next(iter(data.val_dataloader()))[0]) # Validation text
Z_init = first_gates(text_model(min_gru, 256), X) # Untrained
Z = first_gates(model, X)
print('gate above half-life in steps share at initialization trained')
for g in (0.5, 0.9, 0.99):
print(f'{g:10} {math.log(2) / -math.log(g):17.0f} '
f'{(Z_init > g).mean():23.1%} {(Z > g).mean():7.1%}')gate above half-life in steps share at initialization trained
0.5 1 49.1% 52.3%
0.9 7 1.7% 17.8%
0.99 69 0.0% 0.0%
训练使半衰期 \(\ge 7\) 字节(\(g > 0.9\))的门比例扩大了十倍以上(从 \(\sim 1\%\) 增至约 \(18\%\)),与 128 字节窗口所需的词级时间尺度相匹配;但在零偏置初始化下,几乎没有门达到 \(g > 0.99\)(半衰期 69 字节)。
12.3.4 与注意力的开销对比
12.3.4.1 工作量、深度与内存
表 12.3.1 对比了宽度为 \(d\) 的单层在 \(T\) 个词元上的渐近训练工作量、顺序深度以及自回归生成状态。
| 层类型 | 训练工作量 | 顺序步数 | 生成时内存 |
|---|---|---|---|
| GRU,逐步执行 | \(T d^2\) | \(T\) | \(d\) |
| minGRU,倍增扫描 | \(T d^2 + T d \log_2 T\) | \(\log_2 T\) | \(d\) |
| minGRU,工作高效扫描 | \(T d^2 + T d\) | \(2 \log_2 T\) | \(d\) |
| 因果注意力 | \(T d^2 + T^2 d\) | 少数几次矩阵乘法 | \(2 T d\) |
GRU 与 minGRU 都执行 \(O(Td^2)\) 投影工作量并在解码时携带 \(O(d)\) 状态向量,但 minGRU 将训练顺序深度从 \(T\) 次矩阵-向量步降至 \(O(\log_2 T)\) 轮逐元素扫描。因果注意力在训练时顺序深度为 \(O(1)\),但其注意力打分与混合工作量按 \(O(T^2 d)\) 二次增长(在 \(T \approx 4d\) 附近超过 \(8Td^2\) 投影 FLOPs),推理 KV 缓存则按 \(2Td\) 线性增长。
12.3.4.2 实测开销
为了观察这些缩放律在真实硬件上何处交叉,我们在宽度 \(d = 256\)、float16 下对一次前向加反向传播计时:令序列长度 \(T\) 从 \(512\) 扫描至 \(16{,}384\),同时保持每批总词元数恒定为 \(B \times T = 65{,}536\)。总词元数固定时,任何开销严格线性于 \(T\) 的层都会呈平坦曲线,而受 \(O(T)\) 顺序步数或 \(O(T^2)\) 两两工作量主导的层,每次 \(T\) 翻倍都会令运行时间翻倍。
d, tokens = 256, 65536 # Width; tokens per call, in sequences of length T
device, half = d2l.try_gpu(), torch.float16 # 16-bit floats throughout
timed = {'GRU': d2l.Recurrent(nn.GRU(d, d, batch_first=True)),
'minGRU': torch.compile(MinGRU(d, d)),
'attention': d2l.CausalAttention(d, num_heads=4)}
for layer in timed.values():
layer.to(device, half)
def time_call(layer, T):
"""Milliseconds for a forward and backward pass over tokens / T
sequences of length T."""
X = torch.randn(tokens // T, T, d, device=device, dtype=half,
requires_grad=True)
return 1000 * d2l.Benchmark(lambda: layer(X).float().sum().backward(),
warmup=1, repeats=3).timeclass FusedAttention(d2l.CausalAttention):
"""Causal attention through cuDNN's fused kernel."""
@staticmethod
def attend(q, k, v):
return jax.nn.dot_product_attention(q, k, v, is_causal=True,
implementation='cudnn')
d, tokens = 256, 65536 # Width; tokens per call, in sequences of length T
half, rngs = jnp.float16, nnx.Rngs(d2l.get_key()) # 16-bit floats
timed = {'GRU': nnx.RNN(nnx.GRUCell(d, d, recurrent_kernel_init=lecun,
param_dtype=half, rngs=rngs), unroll=8),
'minGRU': MinGRU(d, d, rngs=rngs),
'attention': FusedAttention(d, num_heads=4, rngs=rngs)}
for layer in timed.values(): # Every weight in 16 bits
params = nnx.state(layer, nnx.Param)
nnx.update(layer, jax.tree.map(lambda p: p.astype(half), params))
@nnx.jit
def forward_backward(layer, X):
loss = lambda layer, X: layer(X).astype(jnp.float32).sum()
return nnx.grad(loss, argnums=(0, 1))(layer, X)
def time_call(layer, T):
"""Milliseconds for a forward and backward pass over tokens / T
sequences of length T."""
X = jax.random.normal(d2l.get_key(), (tokens // T, T, d), half)
return 1000 * d2l.Benchmark(lambda: forward_backward(layer, X),
warmup=1, repeats=3).time在序列长度 \(T \in \{512, 1024, 2048, 4096, 8192, 16384\}\) 上扫描 time_call,在对数-对数坐标下对比 GRU、minGRU 与 attention 的挂钟运行时间:
lengths = [512, 1024, 2048, 4096, 8192, 16384]
times = {name: [time_call(layer, T) for T in lengths]
for name, layer in timed.items()}
print('T ', *(f'{T:>7d}' for T in lengths))
for name, ms in times.items():
print(f'{name:9s}', *(f'{t:7.1f}' for t in ms))
d2l.plot(lengths, list(times.values()), 'sequence length',
'milliseconds per call', legend=list(times), xscale='log',
yscale='log', figsize=(4.5, 3))T 512 1024 2048 4096 8192 16384
GRU 20.2 35.6 69.7 113.3 197.6 425.6
minGRU 4.0 4.3 4.5 5.0 5.2 5.6
attention 2.1 2.4 3.2 4.7 7.9 13.7
lengths = [512, 1024, 2048, 4096, 8192, 16384]
times = {name: [time_call(layer, T) for T in lengths]
for name, layer in timed.items()}
print('T ', *(f'{T:>7d}' for T in lengths))
for name, ms in times.items():
print(f'{name:9s}', *(f'{t:7.1f}' for t in ms))
d2l.plot(lengths, list(times.values()), 'sequence length',
'milliseconds per call', legend=list(times), xscale='log',
yscale='log', figsize=(4.5, 3))T 512 1024 2048 4096 8192 16384
GRU 11.6 18.6 33.5 54.0 93.8 195.3
minGRU 1.3 1.1 1.1 1.1 1.2 1.2
attention 2.9 3.0 3.9 5.9 9.8 17.2
实测缩放曲线与 表 12.3.1 高度吻合:
GRU:在每个长度下都最慢,从 \(T = 512\) 到 \(16{,}384\) 增长超过 \(15\times\),因为其 \(T\) 个顺序步无法跨时间并行。minGRU:在序列长度扩大 32 倍的全程中几乎保持平坦。attention:在 \(O(Td^2)\) 投影与内存流量占主导的 \(T \approx 2{,}048\) 以内几乎平坦,一旦 \(O(T^2 d)\) 注意力项接管便向上翘起,趋近每次翻倍耗时 \(2\times\)。
minGRU 的倍增扫描增幅不到 \(50\%\);短长度下更快的 attention 在 \(T = 4{,}096\) 附近与之交叉,到 \(T = 16{,}384\) 时落后约 \(2.5\times\)。
minGRU 的工作高效扫描始终保持平坦,在每个长度下都快于 attention,在 \(T = 16{,}384\) 处快约 \(14\times\)。
minGRU 仍欠缺一种结构化初始化并控制多时间尺度记忆的方法——这正是 12.4 节 通过连续时间状态空间模型要解决的问题。
12.3.5 小结
将上一时刻状态 \(\mathbf{h}_{t-1}\) 从循环层的门中移除,便得到仿射循环 \(\mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t\),其步骤按 \((\mathbf{a}_1, \mathbf{b}_1) \bullet (\mathbf{a}_2, \mathbf{b}_2) = (\mathbf{a}_1 \odot \mathbf{a}_2, \mathbf{a}_2 \odot \mathbf{b}_1 + \mathbf{b}_2)\) 满足结合律。结合扫描在训练时用 \(O(\log_2 T)\) 轮并行计算求得全部 \(T\) 个状态,同时在解码时保持 \(O(1)\) 状态的顺序更新。将此简化应用于 GRU 即得 MinGRU,它在字节级 WikiText-103 上追平参数量匹配的朴素 RNN(仅落后完整 GRU 约 \(0.03\) 奈特/字节),而训练至 \(16{,}384\) 词元时每词元耗时几乎恒定——比顺序 GRU 快一个数量级以上,在长上下文下也比二次注意力快数倍。
12.3.6 练习
- 复合封闭性。并行扫描不仅需要结合律:任意一段连续步骤的复合必须能用与单步同样多的数值描述,这样每次合并的开销才相同。
- 将 式 12.3.6 推广至带稠密矩阵 \(\mathbf{A}_t \in \mathbb{R}^{d \times d}\) 的循环 \(\mathbf{h}_t = \mathbf{A}_t \mathbf{h}_{t-1} + \mathbf{b}_t\),注意保持每次乘积因子的正确顺序。统计一次合并与一次顺序步的乘加次数。在 \(T = 4096\)、\(d = 64\) 处比较倍增扫描(约 \(T \log_2 T\) 次合并)与顺序循环的总工作量。这一对比对稠密转移矩阵有何启示?
- 对于标量步 \(h \mapsto \tanh(w_t h + c_t)\),证明当 \(w_1, w_2 \neq 0\) 时两步复合不能写成任意 \(w\) 与 \(c\) 的 \(h \mapsto \tanh(w h + c)\) 形式。扫描若要表示 \(k\) 步的复合,必须存储什么?
- [code] 直接路线。对于标量衰减,展开和 式 12.3.4 可以不用扫描,直接借助累积乘积 \(P_t = a_1 a_2 \cdots a_t\) 与一次累积和求值。
- 证明 \(h_t = P_t \sum_{s=1}^{t} b_s / P_s\)。用库的
cumprod与cumsum实现它,并在 32 位浮点数、衰减取 0.9 附近时与linear_scan比较。它在多大长度下失效?为何扫描在那里不会失效? - Feng 等 (2024年) 通过对衰减与写入取对数、用累积 log-sum-exp 替代求和来修复该公式。实现这一修复。它对写入的符号有何要求?作者是如何处理的?
- 证明 \(h_t = P_t \sum_{s=1}^{t} b_s / P_s\)。用库的
- [code] 候选非线性。
MinGRU在候选状态 \(\tilde{\mathbf{h}}_t\) 上保留了 \(\tanh\),而 Feng 等 (2024年) 采用线性候选。- 从 \(\mathbf{h}_0 = \mathbf{0}\) 出发,将 \(\mathbf{h}_t\) 的每个坐标写作候选 \(\tilde{\mathbf{h}}_1, \ldots, \tilde{\mathbf{h}}_t\) 的加权和。证明这些权重非负且之和至多为 1,并推导出在有无 \(\tanh\) 下对任意长度均成立的 \(|\mathbf{h}_t|\) 上界。
- 移除 \(\tanh\),用
d2l.train_text训练本节语言模型两次,并将验证损失与MinGRU的两次运行对比。差异是否大于运行间波动?将观察结果与你的上界联系起来。
- [code] 状态传递。
linear_scan接受初始状态,因此长序列可分片处理。- 将长度为 \(T\) 的序列切分为长度 \(\tau\) 的分块,从上一块的最终状态出发在每块上运行扫描,检验拼接后的状态与整条序列单次调用的结果一致。
- 现在在每个块边界处截断穿过传递状态的梯度。状态本身不变。第 \(t\) 步损失梯度中哪些贡献消失了?训练好的模型在生成文本时仍能利用哪些依赖?将其与截断随时间反向传播(8.5 节)对比。
- [code] 工作高效扫描。● 递归调度比倍增调度工作量更少:将相邻两项合并使序列减半;对减半后的序列递归扫描得到所有偶数位置前缀;再用一次合并求得其余奇数位置前缀。
- 对 \(T = 2^k\),分别统计两种调度的合并次数与合并轮数,并在 \(T = 16384\) 处与循环的 \(T - 1\) 步比较。
- 用切片实现两种调度,对照
sequential_scan检验正确性,并在 12.3.4 节 的各个长度上计时。时间之比是否跟随合并次数之比?解释为何短长度下可能不符。