10.1 注意力提示
- att有价值
- 人类对att的使用
10.1.1 生物学中的注意力
- 心理学中的双组件
- 非自主性提示
- 自主性提示
10.1.2 查询、键和值
- 非自主性提示:使用 FC 或者是 非参数化的最大汇聚层或平均汇聚层
- 自主性提示 与 att,att包含了自主性提示
10.1.3 att的可视化
import torch
from d2l import torch as d2l
# 以后调用该函数来显示att权重
def show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5),
cmap='Reds'):
"""显示矩阵热图"""
d2l.use_svg_display()
num_rows, num_cols = matrices.shape[0], matrices.shape[1] # 获取矩阵的行和列
fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,
sharex=True, sharey=True, squeeze=False)
# print(fig, axes)
for i, (row_axes, row_matrices) in enumerate(zip(axes, matrices)):
for j, (ax, matrix) in enumerate(zip(row_axes, row_matrices)):
pcm = ax.imshow(matrix.detach().numpy(), cmap=cmap)
if i == num_rows - 1:
ax.set_xlabel(xlabel)
if j == 0:
ax.set_ylabel(ylabel)
if titles:
ax.set_title(titles[j])
fig.colorbar(pcm, ax=axes, shrink=0.6)
# 简单的例子演示
attention_weights = torch.eye(10).reshape((1, 1, 10, 10)) # 十行十列单位阵
show_heatmaps(attention_weights, xlabel='Keys', ylabel='Queries') # 绘制单位阵热力图
# 测试(课后小练习)
import torch.nn.functional as f
attention_weights = torch.randn(10, 10)
att = f.softmax(attention_weights, dim=1).reshape((1, 1, 10, 10))
show_heatmaps(att, xlabel='Keys', ylabel='Queries') # 绘制单位阵热力图
10.2 注意力汇聚:Nadaraya-Watson核回归
import torch
from torch import nn
from d2l import torch as d2l
10.2.1 生成数据集
# 生成最后的噪声项目,五十个样本
n_train = 50
x_train, _ = torch.sort(torch.rand(n_train) * 5)
x_train
tensor([0.0192, 0.1770, 0.1844, 0.3110, 0.4857, 0.5581, 0.5631, 0.5808, 0.7043,
0.7353, 0.7895, 0.9371, 1.0185, 1.0930, 1.1639, 1.2625, 1.2696, 1.2705,
1.5598, 1.6579, 1.8110, 1.8339, 1.8593, 1.9037, 1.9275, 2.1895, 2.3213,
2.5673, 2.9432, 3.1474, 3.1801, 3.2326, 3.2604, 3.2654, 3.3072, 3.3636,
3.4699, 3.6697, 3.7435, 3.7690, 4.1530, 4.2052, 4.2895, 4.3577, 4.4203,
4.4391, 4.5694, 4.6161, 4.6794, 4.8771])
# 生成训练集和测试集分别50个
def f(x):
return 2 * torch.sin(x) + x ** 0.8
y_train = f(x_train) + torch.normal(0.0, 0.5, (n_train,)) # 训练样本的输出
x_test = torch.arange(0, 5, 0.1)
y_truth = f(x_test)
n_test = len(x_test)
n_test
50
# 绘制函数,绘制所有的训练样本
def plot_kernel_reg(y_hat):
d2l.plot(x_test, [y_truth, y_hat], 'x', 'y', legend=['Truth', 'Pred'],
xlim=[0, 5], ylim=[-1, 5])
d2l.plt.plot(x_train, y_train, 'o', alpha=0.5)
10.2.2 平均汇聚——最简单的估计器(平均汇聚)
y_hat = torch.repeat_interleave(y_train.mean(), n_test)
plot_kernel_reg(y_hat) # 估计器不聪明
10.2.3 非参数注意力汇聚
- Nadaraya-Watson 核回归
- 测试值(x_test)+训练数据(x+y) → \rightarrow → 预测结果y_hat → \rightarrow → 比对 y_hat 和 y_truth
# 实现(10.2.6)
# x_repeat: (n_test, n_train)
x_repeat = x_test.repeat_interleave(n_train).reshape((-1, n_train))
# print(x_repeat)
# x_train包含着键,attention_weights:(n_test, n_train)
# 每一行都包含着 在给定的每个查询的值(y_train)之间分配的注意力全中
attention_weights = nn.functional.softmax(-(x_repeat - x_train) ** 2 / 2, dim=1)
# y_hat的每个元素都是值得加权平均值,其中的权重都是注意力权重
y_hat = torch.matmul(attention_weights, y_train)
plot_kernel_reg(y_hat)
# 查看att权重热力图
d2l.show_heatmaps(attention_weights.unsqueeze(0).unsqueeze(0),
xlabel='Sorted training inputs',
ylabel='Sorted testing inputs')
10.2.4 带参数注意力汇聚
- 多了一个参数 w w w,通过训练来学习到它
批量矩阵乘法
x = torch.ones((2, 1, 4))
y = torch.ones((2, 4, 6))
# print(x, y, sep = '\n\n')
torch.bmm(x, y).shape
torch.Size([2, 1, 6])
# att机制的背景中使用小批量矩阵乘法
weights = torch.ones((2, 10)) * 0.1
values = torch.arange(20.0).reshape((2, 10))
torch.bmm(weights.unsqueeze(1), values.unsqueeze(-1))
tensor([[[ 4.5000]],
[[14.5000]]])
定义模型
- Nadaraya-Watson核回归的带参数版本
- Q: x_test
- K: x_train
- V: y_train
class NWkernelRegression(nn.Module):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.w = nn.Parameter(torch.rand((1,), requires_grad=True)) # 定义权重参数w
def forward(self, queries, keys, values):
# queries和attention_weights形状为:查询个数,“键-值”对个数
queries = queries.repeat_interleave(keys.shape[1]).reshape((-1, keys.shape[1]))
self.attention_weights = nn.functional.softmax(
-((queries - keys) * self.w) ** 2 / 2, dim=1)
# values: (查询个数,“键-值”对个数)
return torch.bmm(self.attention_weights.unsqueeze(1),
values.unsqueeze(-1)).reshape(-1)
训练
- 书上的图有问题
# x_tile: (n_train, n_train),每一行都包含相同的训练输入
x_tile = x_train.repeat((n_train, 1))
# y_tile: (n_train, n_train), 每一行都包含着相同的训练输出
y_tile = y_train.repeat((n_train, 1))
# keys: (n_train, n_train-1),注意看如何选择除掉自己以外的元素
keys = x_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))
# values: (n_train, n_train-1)
values = y_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))
# 训练 带参数的注意力汇聚模型时,使用MSELoss函数和sgd优化方法
net = NWkernelRegression() # 初始化模型
loss = nn.MSELoss(reduction='none') # 设置loss函数
trainer = torch.optim.SGD(net.parameters(), lr=0.5) # 设置优化器
animator = d2l.Animator(xlabel='epoch', ylabel='loss', xlim=[1, 5]) # 画图的对象
for epoch in range(5):
trainer.zero_grad() # 每一轮优化器梯度清空
l = loss(net(x_train, keys, values), y_train) # loss函数求损失
l.sum().backward() # 反向传播
trainer.step() # 更新网络参数
animator.add(epoch + 1, float(l.sum())) # 绘制
print(f'epoch {epoch + 1}, loss {float(l.sum()): .6f}') # 打印出来
epoch 5, loss 11.000541
可视化att——绘制预测结果的线
- 书上的图应该是搞错了的!
# keys: (n_test, n_train), 每一行包含着相同的训练输入(例如,相同的键)
keys = x_train.repeat((n_test, 1))
# values:(n_test, n_train)
values = y_train.repeat((n_test, 1))
y_hat = net(x_test, keys, values).unsqueeze(1).detach()
# detach()或者data用于切断反向传播
plot_kernel_reg(y_hat)
d2l.show_heatmaps(net.attention_weights.unsqueeze(0).unsqueeze(0),
xlabel='Sorted training inputs',
ylabel='Sorted testing inputs')
10.3 注意力评分函数
-
核K的指数 就是 att评分函数:Q和K越接近,我给你越高的分数
-
框架:
-
数学语言描述:
-
本节将介绍两个流行的评分函数 a a a
import math, torch
from torch import nn
from d2l import torch as d2l
10.3.1 掩蔽softmax操作
- softmax操作用于输出一个概率分布作为att权重
- 使用掩蔽softmax将任何超出有效长度的位置掩蔽为0
def masked_softmax(x, valid_lens):
"""在最后一个轴上掩蔽元素来执行softmax操作"""
# x: 3D张量,valid_lens: 1D或2D张量
if valid_lens is None:
return nn.functional.softmax(x, dim=-1)
else:
shape = x.shape
if valid_lens.dim() == 1:
valid_lens = torch.repeat_interleave(valid_lens, shape[1])
else:
valid_lens = valid_lens.reshape(-1)
# 最后一轴上被掩蔽的元素使用一个非常大的负值替换,使其softmax输出为0
x = d2l.sequence_mask(x.reshape(-1, shape[-1]), valid_lens, value=-1e6)
return nn.functional.softmax(x.reshape(shape), dim=-1)
# 测试:
masked_softmax(torch.rand(2, 2, 4), torch.tensor([2, 3]))
tensor([[[0.5854, 0.4146, 0.0000, 0.0000],
[0.6562, 0.3438, 0.0000, 0.0000]],
[[0.2221, 0.4473, 0.3306, 0.0000],
[0.2206, 0.3608, 0.4186, 0.0000]]])
# 测试2: 指定每一行的有效长度
masked_softmax(torch.rand(2, 2, 4), torch.tensor([[1, 3], [2, 4]]))
tensor([[[1.0000, 0.0000, 0.0000, 0.0000],
[0.3615, 0.3240, 0.3145, 0.0000]],
[[0.6594, 0.3406, 0.0000, 0.0000],
[0.2539, 0.2029, 0.2850, 0.2581]]])
10.3.2 加性att(第一个流行的评分函数)
class AdditiveAttention(nn.Module):
"""加性注意力"""
def __init__(self, key_size, query_size, num_hiddens, dropout, **kwargs):
super(AdditiveAttention, self).__init__(**kwargs)
self.w_k = nn.Linear(key_size, num_hiddens, bias=False)
self.w_q = nn.Linear(query_size, num_hiddens, bias=False)
self.w_v = nn.Linear(num_hiddens, 1, bias=False)
self.dropout = nn.Dropout(dropout)
def forward(self, queris, keys, values, valid_lens):
queris, keys = self.w_q(queris), self.w_k(keys)
# 维度扩展后,queries维度:(batch_size, 查询的个数,1,num_hiddens)
# key的形状, (batch_size, 1, "键-值"对的个数,num_hiddens)
# 使用广播方式求和
features = queris.unsqueeze(2) + keys.unsqueeze(1) # 维度扩展后,广播求和
features = torch.tanh(features)
# self.w_v仅有一个输出,因此从形状中移除最后那个维度
# scores: (batch_size, 查询的个数,“键-值”对的个数)
scores = self.w_v(features).squeeze(-1)
self.attention_weights = masked_softmax(scores, valid_lens) # 掩蔽softrmax操作
# values: (batch_size, "键-值"对的个数,值得维度)
return torch.bmm(self.dropout(self.attention_weights), values)
# 测试(Q和K的维度可以不同)
queries, keys = torch.normal(0, 1, (2, 1, 20)), torch.ones((2, 10, 2))
# values的小批量,两个值矩阵是相同的
values = torch.arange(40, dtype=torch.float32).reshape(1, 10, 4).repeat(2, 1, 1)
# values: (2 x 10 x 4)
valid_lens = torch.tensor([2, 6])
attention = AdditiveAttention(key_size=2, query_size=20, num_hiddens=8,
dropout=0.1)
attention.eval() # 开启为预测模式(评估模式)
attention(queries, keys, values, valid_lens) # (1 * 2 * 4)
tensor([[[ 2.0000, 3.0000, 4.0000, 5.0000]],
[[10.0000, 11.0000, 12.0000, 13.0000]]], grad_fn=<BmmBackward0>)
# 可视化分析
# 本例每个键相同,因此att权重是均匀的,由指定的有效长度决定:(2,6)
d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
xlabel='Keys', ylabel='Queries')
10.3.3 缩放点积att(第二个流行的评分函数)
class DotProductAttention(nn.Module):
"""缩放点积注意力"""
def __init__(self, dropout, **kwargs):
super(DotProductAttention, self).__init__(**kwargs)
self.dropout = nn.Dropout(dropout)
# queries: (batch_size, 查询的个数, d)
# keys: (batch_size, “键-值”对的个数,d)
# values: (batch_size, "键-值"对的个数,值的维度)
# valid_lens: (batch_size,) 或者 (batch_size, 查询的个数)
def forward(self, queries, keys, values, valid_lens=None):
d = queries.shape[-1]
# 设置transpose_b = True 为了交换 keys 的最后两个维度
scores = torch.bmm(queries, keys.transpose(1,2)) / math.sqrt(d)
self.attention_weights = masked_softmax(scores, valid_lens)
return torch.bmm(self.dropout(self.attention_weights), values)
queries = torch.normal(0, 1, (2, 1, 2)) # 点积,所以必须使得特征维度相同
attention = DotProductAttention(dropout=0.5)
attention.eval()
attention(queries, keys, values, valid_lens)
tensor([[[ 2.0000, 3.0000, 4.0000, 5.0000]],
[[10.0000, 11.0000, 12.0000, 13.0000]]])
d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
xlabel='Keys', ylabel='Queries')
# 最终获得均匀的att权重
- 注意力汇聚的输出计算 本质上是 V V V的加权平均
- 注意不同的 att评分函数 的效果
- 加性att评分函数:查询和键是不同长度的矢量时;
- 缩放点积att评分函数:查询和键 的长度相同。
10.4 Bahdanau注意力
- 学习对齐想法 的启发
- 一个 没有严格单向对齐限制的 可微注意力模型
10.4.1 模型
-
解码器隐状态 s t ′ − 1 s_{t^\prime-1} st′−1 是 Q Q Q
-
编码器隐状态 h t h_t ht 是 K K K和 V V V
-
α \alpha α 是 加性att打分函数
-
原来的架构
-
现在架构
import torch
from torch import nn
from d2l import torch as d2l
D:\ana3\envs\nlp_prac\lib\site-packages\numpy\_distributor_init.py:32: UserWarning: loaded more than 1 DLL from .libs:
D:\ana3\envs\nlp_prac\lib\site-packages\numpy\.libs\libopenblas.IPBC74C7KURV7CB2PKT5Z5FNR3SIBV4J.gfortran-win_amd64.dll
D:\ana3\envs\nlp_prac\lib\site-packages\numpy\.libs\libopenblas.XWYDX2IKJW2NMTWSFYNGFUWKQU3LYTCZ.gfortran-win_amd64.dll
stacklevel=1)
10.4.2 定义注意力解码器
# 该类定义带有att机制解码器的基本接口
class AttentionDecoder(d2l.Decoder):
def __init__(self, **kwargs):
super(AttentionDecoder, self).__init__(**kwargs)
@property
def attention_weights(self):
raise NotImplementedError
# 该类中实现 带有Bahdanau注意力的 rnn解码器
class Seq2SeqAttentionDecoder(AttentionDecoder):
def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
dropout=0, **kwargs):
super(Seq2SeqAttentionDecoder, self).__init__(**kwargs) # 实例化父类
self.attention = d2l.AdditiveAttention( # att机制
num_hiddens, num_hiddens, num_hiddens, dropout)
self.embedding = nn.Embedding(vocab_size, embed_size) # 词嵌入
self.rnn = nn.GRU( # rnn层
embed_size + num_hiddens, num_hiddens, num_layers, dropout=dropout)
self.dense = nn.Linear(num_hiddens, vocab_size) # softmax输出层
def init_state(self, enc_outputs, enc_valid_lens, *args): # 接收编码器输出
# outputs: (batch_size, num_steps, num_hiddens)
# hidden_state: (num_layers, batch_size, num_hiddens)
outputs, hidden_state = enc_outputs
return (outputs.permute(1, 0, 2), hidden_state, enc_valid_lens)
def forward(self, X, state):
# enc_ouputs: (batch_size, num_steps, num_hiddens)
# hidden_state: (num_layers, batch_size, num_hiddens)
enc_outputs, hidden_state, enc_valid_lens = state
# x: (num_steps, batch_size, embed_size)
X = self.embedding(X).permute(1, 0, 2)
outputs, self._attention_weights = [], []
for x in X:
# query: (batch_size, 1, num_hiddens)
query = torch.unsqueeze(hidden_state[-1], dim=1)
# context: (batch_size, l, num_hiddens)
context = self.attention(query, enc_outputs, enc_outputs, enc_valid_lens) # 更新
# 在特征维度上连结
x = torch.cat((context, torch.unsqueeze(x, dim=1)), dim=-1)
# x变为:(1, batch_size, embed_size+num_hiddens)
out, hidden_state = self.rnn(x.permute(1, 0, 2), hidden_state)
outputs.append(out)
self._attention_weights.append(self.attention.attention_weights)
# FC变换后,outputs: (num_steps, batch_size, vocab_size)
outputs = self.dense(torch.cat(outputs, dim=0))
return outputs.permute(1, 0, 2), [enc_outputs, hidden_state, enc_valid_lens]
@property
def attention_weights(self):
return self._attention_weights
# 测试:7个时间步,4个序列输入的小批量测试Bahdanau att解码器
encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8,num_hiddens=16, num_layers=2)
encoder.eval()
decoder = Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)
decoder.eval()
x = torch.zeros((4, 7), dtype=torch.long) # x: (batch_size, num_steps)
state = decoder.init_state(encoder(x), None)
output, state = decoder(x, state)
output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape
(torch.Size([4, 7, 10]), 3, torch.Size([4, 7, 16]), 2, torch.Size([4, 16]))
10.4.3 训练
# 实例化带有Bahdanau att 的编码器 和 解码器
from d2l import torch as d2l
embed_size, num_hiddens, num_layers, dropout = 64, 32, 2, 0.3
batch_size, num_steps = 128, 10
lr, num_epochs, device = 0.005, 300, d2l.try_gpu()
train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)
encoder = d2l.Seq2SeqEncoder(
len(src_vocab), embed_size, num_hiddens, num_layers, dropout)
decoder = Seq2SeqAttentionDecoder(
len(tgt_vocab), embed_size, num_hiddens, num_layers, dropout)
net = d2l.EncoderDecoder(encoder, decoder)
d2l.train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)
loss 0.023, 12540.9 tokens/sec on cuda:0
# 将几个句子翻译成法语后并计算它们的BLEU分数
engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
for eng, fra in zip(engs, fras):
translation, dec_attention_weight_seq = d2l.predict_seq2seq(
net, eng, src_vocab, tgt_vocab, num_steps, device, True)
print(f'{eng} => {translation}, ',
f'bleu {d2l.bleu(translation, fra, k=2):.3f}')
go . => va !, bleu 1.000
i lost . => j'ai perdu ., bleu 1.000
he's calm . => il est bon ., bleu 0.658
i'm home . => je suis chez moi ., bleu 1.000
attention_weights = torch.cat([step[0][0][0] for step in dec_attention_weight_seq],0).reshape((
1, 1, -1, num_steps))
# 可视化 att 权重
d2l.show_heatmaps(attention_weights[:, :, :, :len(engs[-1].split()) + 1].cpu(),
xlabel='Key positions', ylabel='Query positions')
10.5 多头注意力
- 使用 FC层 实现 可学习的线性变换的多头注意力
10.5.1 模型
- 数学形式化语言:
import math, torch
from torch import nn
from d2l import torch as d2l
10.5.2 实现
- 第一维相同时,可以 并行计算 h h h个头
- p o p_o po 是通过参数 num_hiddens 指定的
class MutiHeadAttention(nn.Module):
"""多头注意力"""
def __init__(self, key_size, query_size, value_size, num_hiddens,
num_heads, dropout, bias=False, **kwargs):
super(MutiHeadAttention, self).__init__(**kwargs)
self.num_heads = num_heads
self.attention = d2l.DotProductAttention(dropout)
self.W_q = nn.Linear(query_size, num_hiddens, bias=bias)
self.W_k = nn.Linear(key_size, num_hiddens, bias=bias)
self.W_v = nn.Linear(value_size, num_hiddens, bias=bias)
self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=bias)
def forward(self, queries, keys, values, valid_lens):
# q,k,v的形状:
# (batch_size, 查询或者“键-值”对的个数,num_hiddens)
# valid_lens:(batch_size,)或(batch_size, 查询的个数)
# 经过变换后,输出q,k,v的形状:
# (batch_size * num_heads, 查询或者“键-值”对的个数,num_hiddens/num_heads)
queries = transpose_qkv(self.W_q(queries), self.num_heads)
keys = transpose_qkv(self.W_k(keys), self.num_heads)
values = transpose_qkv(self.W_v(values), self.num_heads)
if valid_lens is not None:
# 在轴0上将第一项(标量或矢量)复制num_heads次
# 然后如此复制第二项,然后诸如此类
valid_lens = torch.repeat_interleave(
valid_lens, repeats=self.num_heads, dim=0)
# output: (batch_size * num_heads, 查询的个数,num_hiddens/num_heads)
output = self.attention(queries, keys, values, valid_lens)
# output_concat:(batch_size, 查询的个数,num_hiddens)
output_concat = transpose_output(output, self.num_heads)
return self.W_o(output_concat)
# 定义下面两个转置函数
def transpose_qkv(x, num_heads):
"""多注意力头的并行计算而变换形状"""
# 输入x: (batch_size, 查询或者“键-值”对的个数,num_hiddens)
# 输出x:(batch_size, 查询或者“键-值”对的个数,num_heads, num_hiddens/num_heads)
x = x.reshape(x.shape[0], x.shape[1], num_heads, -1) # 这里自动计算最后一维
# 输出x:(batch_size, num_heads, 查询或者“键-值”对的个数, num_hiddens/num_heads
x = x.permute(0, 2, 1, 3)
# 最终输出:
#(batch_size * num_heads, 查询或者“键-值”对的个数,num_hiddens/num_heads)
return x.reshape(-1, x.shape[2], x.shape[3])
def transpose_output(x, num_heads):
"""逆转transpose_qkv函数的操作"""
x = x.reshape(-1, num_heads, x.shape[1], x.shape[2])
x = x.permute(0, 2, 1, 3)
return x.reshape(x.shape[0], x.shape[1], -1)
# 使用键和值相同的例子测试MultiHeadAttention类,
# 输出:(batch_size, num_queries, num_hiddens)
num_hiddens, num_heads = 100, 5
attention = MutiHeadAttention(num_hiddens, num_hiddens, num_hiddens, # k, q, v相同
num_hiddens, num_heads, 0.5)
attention.eval()
MutiHeadAttention(
(attention): DotProductAttention(
(dropout): Dropout(p=0.5, inplace=False)
)
(W_q): Linear(in_features=100, out_features=100, bias=False)
(W_k): Linear(in_features=100, out_features=100, bias=False)
(W_v): Linear(in_features=100, out_features=100, bias=False)
(W_o): Linear(in_features=100, out_features=100, bias=False)
)
batch_size, num_queries = 2, 4
num_kvpairs, valid_lens = 6, torch.tensor([3, 2])
x = torch.ones((batch_size, num_queries, num_hiddens))
y = torch.ones((batch_size, num_kvpairs, num_hiddens))
attention(x, y, y, valid_lens).shape
torch.Size([2, 4, 100])
10.6 自注意力和位置编码
- 关键点:每个 Q Q Q都会关注 所有的键-值对 并生成 一个att输出;
- self-att 又称为 内部att
import math, torch
from torch import nn
from d2l import torch as d2l
10.6.1 self-att
# 基于多头注意力 对一个张量x完成 self-att的计算
# x:(batch_size, num_steps/词元序列的长度,d)
num_hiddens, num_heads = 100, 5
attention = d2l.MultiHeadAttention(num_hiddens, num_hiddens, num_hiddens,# k q v
num_hiddens, num_heads, 0.5) # d
attention.eval()
MultiHeadAttention(
(attention): DotProductAttention(
(dropout): Dropout(p=0.5, inplace=False)
)
(W_q): Linear(in_features=100, out_features=100, bias=False)
(W_k): Linear(in_features=100, out_features=100, bias=False)
(W_v): Linear(in_features=100, out_features=100, bias=False)
(W_o): Linear(in_features=100, out_features=100, bias=False)
)
batch_size, num_queries, valid_lens = 2, 4, torch.tensor([3, 2])
x = torch.ones((batch_size, num_queries, num_hiddens))
attention(x, x, x, valid_lens).shape
torch.Size([2, 4, 100])
10.6.2 比较 cnn、rnn 和 self-att
-
CNN
-
k = 3 , n = 5 k=3,n=5 k=3,n=5, 感受野为: 5 5 5, 计算: O ( k n d 2 ) O(knd^2) O(knd2), 最大路径长度: O ( n / k ) O(n/k) O(n/k)
-
输入输出通道数量为 d d d, 仅 O ( 1 ) O(1) O(1)个顺序操作,可并行
-
RNN
-
d ∗ d d*d d∗d权重矩阵 和 d d d维隐状态的乘法计算复杂度为: O ( d 2 ) O(d_2) O(d2)
-
序列长度: n = 5 n=5 n=5,rnn计算复杂度: O ( n d 2 ) O(nd^2) O(nd2)
-
O ( n ) O(n) O(n)个顺序操作,无法并行,最大路径长度: O ( n ) O(n) O(n)
-
self-att
-
q,k,v: n × d n\times d n×d矩阵
-
计算复杂性: O ( n 2 d ) O(n^2d) O(n2d)
-
仅 O ( 1 ) O(1) O(1)个顺序操作,可并行计算,最大路径长度: O ( 1 ) O(1) O(1)
10.6.3 位置编码
- 绝对的/相对的位置信息(顺序信息)
- 基于正弦函数和余弦函数的 固定位置编码
class PositionalEncoding(nn.Module):
"""位置编码"""
def __init__(self, num_hiddens, dropout, max_len=1000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(dropout)
# 创建一个足够长的P
self.P = torch.zeros((1, max_len, num_hiddens))
x = torch.arange(max_len, dtype=torch.float32).reshape(
-1, 1) / torch.pow(10000, torch.arange(
0, num_hiddens, 2, dtype=torch.float32) / num_hiddens)
self.P[:, :, 0::2] = torch.sin(x) # 注意这里的切片方式
self.P[:, :, 1::2] = torch.cos(x)
def forward(self, x):
x = x + self.P[:, :x.shape[1], :].to(device)
return self.dropout(x)
- 矩阵P中,行:词元在序列中的位置;列:位置编码的不同维度
- 第6、7列的频率(震荡周期)高于8、9列
# d2l.set_figsize((16, 9))
encoding_dim, num_steps = 32, 60 # 注意这里不要少写一个s
pos_encoding = PositionalEncoding(encoding_dim, 0)
pos_encoding.eval()
x = pos_encoding(torch.zeros((1, num_steps, encoding_dim)).to(device))
P = pos_encoding.P[:, :x.shape[1], :]
d2l.plot(torch.arange(num_steps), P[0, :, 6:10].T, xlabel='Row (position)',
figsize=(6, 2.5), legend=['Col %d' % d for d in torch.arange(6, 10)])
绝对位置信息
- 观察 沿着编码维度单调降低的频率 与 绝对位置信息 的关系
- 注意 每个数字的最低位,连续每两个数字的次最低位、每四个数字的次次最低位 是分别交替的
for i in range(8):
print(f'{i}的二进制是:{i:>03b}') # 实际上是二进制进位逻辑
0的二进制是:000
1的二进制是:001
2的二进制是:010
3的二进制是:011
4的二进制是:100
5的二进制是:101
6的二进制是:110
7的二进制是:111
- 二进制中,高比特位的交替频率低于 较低比特位;
- 位置编码 使用三角函数在编码维度上降低频率;
- 由于后者输出是float类型,因此此类连续表示法比二进制表示法省空间( 不 随 着 行 的 增 加 而 增 加 值 的 长 度 \color {#EE1000}{不随着行的增加而增加值的长度} 不随着行的增加而增加值的长度)
P = P[0, :, :].unsqueeze(0).unsqueeze(0)
d2l.show_heatmaps(P, xlabel='Column (encoding dimension)',
ylabel='Row (position)', figsize=(3.5, 4), cmap='Blues')
相对位置信息
10.7 Transformer
- trans完全基于self-att,无CNN和RNN
- trans最初应用于文本数据上的seq2sed学习,目前推广到DL,如语言、视觉、语音和RL
10.7.1 模型
trans 编码器:
- 多个相同的层 叠加,每个层包括两个子层:
- 子层1:多头注意力
- 子层2:基于位置的前馈网络
- 编码器的self-att,qkv都来自前一个编码器层的输出
- 每个子层 采用 残差连接
- 对于序列中任何位置的任何输入,残差连接满足 x ⃗ + s u b l a y e r ( x ⃗ ) ∈ R d \vec{x}+sublayer(\vec{x})\in R^d x+sublayer(x)∈Rd
- 输入序列对应的每个位置,tans编码器都将输出 一个d维表示向量
trans解码器:
- 多个层 叠加而成,包括了残差连接和层规范化
- 另外第三个子层:编码器-解码器注意力层:
- Q来自前一个解码器层的输出
- K和V来自整个编码器的输出
- 解码器的self-att:KQV都来自上一个解码器层的输出
- 这种masked att保留了自回归属性:解码器中每个位置仅考虑该位置之前的所有位置,即确保了预测仅依赖于已生成的输出词元
接下来实现trans剩余部分(缩放点积多头 att 和 位置编码 已有)
10.7.2 基于位置的前馈网络
- 基于位置(positionwise)的前馈网络 对 序列中的所有位置的表示 进行变换时使用的是 同一个MLP
- 下面的实现为:输入x(batch_size, 时间步数/序列长度,隐单元数或特征维度) − - −二层感知机转换为 → \rightarrow → (batch_size, 时间步数,ffn_num_outpus)的输出张量。
class PositionWiseFFN(nn.Module):
"""基于位置的前馈网络"""
def __init__(self, ffn_num_input, ffn_num_hiddens, ffn_num_outputs, **kwargs):
super(PositionWiseFFN, self).__init__(**kwargs)
self.dense1 = nn.Linear(ffn_num_input, ffn_num_hiddens)
self.relu = nn.ReLU()
self.dense2 = nn.Linear(ffn_num_hiddens, ffn_num_outputs)
def forward(self, x):
return self.dense2(self.relu(self.dense1(x)))
# 用MLP对所有位置上的输入进行变换,输入相同时,它们的输出也是相同的
ffn = PositionWiseFFN(4, 4, 8)
ffn.eval()
ffn(torch.ones((2, 3, 4)))[0]
tensor([[ 0.0225, 0.4650, 0.2784, -0.4973, -0.2292, -0.4735, -0.0819, -0.1855],
[ 0.0225, 0.4650, 0.2784, -0.4973, -0.2292, -0.4735, -0.0819, -0.1855],
[ 0.0225, 0.4650, 0.2784, -0.4973, -0.2292, -0.4735, -0.0819, -0.1855]],
grad_fn=<SelectBackward0>)
10.7.3 残差连接 和 层 规范化
- 回顾
- 层规范化 基于 特征维度 进行规范化 (NLP效果更好)
- 批量规范化:每一层神经网络的输入保持相同分布(CV中效果更好)
# 对比 不同维度的 层规范化和 批量规范化 的效果
ln = nn.LayerNorm(2)
bn = nn.BatchNorm1d(2)
x = torch.tensor([[1, 2], [2, 3]], dtype=torch.float32)
# 训练模式下计算x的 均值和方差
print('layer norm: ', ln(x), '\nbatch norm', bn(x))
layer norm: tensor([[-1.0000, 1.0000],
[-1.0000, 1.0000]], grad_fn=<NativeLayerNormBackward0>)
batch norm tensor([[-1.0000, -1.0000],
[ 1.0000, 1.0000]], grad_fn=<NativeBatchNormBackward0>)
# 使用 resnet 和 norm技术 来实现 AddNorm 类。
# dropout 也被作为 正则化方法使用
class AddNorm(nn.Module):
"""resnet + layer norm"""
def __init__(self, normalized_shape, dropout, **kwargs):
super(AddNorm, self).__init__(**kwargs)
self.dropout = nn.Dropout(dropout)
self.ln = nn.LayerNorm(normalized_shape)
def forward(self, x, y):
return self.ln(self.dropout(y) + x)
add_norm = AddNorm([3, 4], 0.5)
add_norm.eval()
add_norm(torch.ones((2, 3, 4)), torch.ones((2, 3, 4))).shape
torch.Size([2, 3, 4])
10.7.4 编码器
- 实现两个子层(都使用了 resnet 和 层规范化):
- 多头 self-att
- 基于位置 的前馈网络
class EncoderBlock(nn.Module):
"""trans 编码器块"""
def __init__(self, key_size, query_size, value_size, num_hiddens,
norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,
dropout, use_bias=False, **kwargs):
super(EncoderBlock, self).__init__(**kwargs)
self.attention = d2l.MultiHeadAttention( # 多头 att
key_size, query_size, value_size, num_hiddens, num_heads, dropout,
use_bias)
self.addnorm1 = AddNorm(norm_shape, dropout) # resnet + layer norm
self.ffn = PositionWiseFFN(ffn_num_input, ffn_num_hiddens, num_hiddens) # FFN
self.addnorm2 = AddNorm(norm_shape, dropout) # resnet + layer norm
def forward(self, x, valid_lens):
y = self.addnorm1(x, self.attention(x, x, x, valid_lens)) # self-att
return self.addnorm2(y, self.ffn(y))
# 测试:trans编码器的任何层都不会改变其输入的形状
x = torch.ones((2, 100, 24)) # 两个样本,没有个样本100个序列长度
valid_lens = torch.tensor([3, 2]) # 每个样本的有效长度
encoder_blk = EncoderBlock(24, 24, 24, 24, [100, 24], 24, 48, 8, 0.5)
encoder_blk.eval()
encoder_blk(x, valid_lens).shape
torch.Size([2, 100, 24])
# trans编码器代码:堆叠了num_layers个 EncoderBlock类的实例
# 通过 学习 得到的输入的嵌入表示的值 需要先乘以 嵌入维度的平方根 进行重新缩放,
# 然后再与位置编码相加
class TransformerEncoder(d2l.Encoder):
"""trans 编码器"""
def __init__(self, vocab_size, key_size, query_size, value_size,
num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens,
num_heads, num_layers, dropout, use_bias=False, **kwargs):
super(TransformerEncoder, self).__init__(**kwargs)
self.num_hiddens = num_hiddens
self.embedding = nn.Embedding(vocab_size, num_hiddens)
self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)
self.blks = nn.Sequential()
for i in range(num_layers):
self.blks.add_module('block' + str(i),
EncoderBlock(key_size, query_size, value_size, num_hiddens,
norm_shape, ffn_num_input, ffn_num_hiddens,
num_heads, dropout, use_bias))
def forward(self, x, valid_lens, *args):
# 位置编码值:-1~1, 故嵌入值 乘以 嵌入维度的平方根 进行缩放
# 然后再与 位置编码 相加
x = self.pos_encoding(self.embedding(x) * math.sqrt(self.num_hiddens))
self.attention_weights = [None] * len(self.blks)
for i, blk in enumerate(self.blks):
x = blk(x, valid_lens)
self.attention_weights[i] = blk.attention.attention.attention_weights
return x
# 指定 超参数 创建 一个两层的trans编码器,其输出:(batch_size, num_steps, num_hiddens)
encoder = TransformerEncoder(
200, 24, 24, 24, 24, [100, 24], 24, 48, 8, 2, 0.5)
encoder.eval()
encoder(torch.ones((2, 100), dtype=torch.long), valid_lens).shape
torch.Size([2, 100, 24])
10.7.5 解码器
-
DecoderBlock类的三个子层(也都被resnet和紧随的layer norm所围绕):
-
解码器自注意力
-
“编码器-解码器”注意力
-
基于位置的前馈网络
-
第一子层:掩蔽多头解码器自注意力层中,QKV都来自上一个解码器层的输出
-
针对seq2seq模型:训练时的输出序列均已知,而预测时序列是逐个生成的
-
故生成的词元才能用于 解码器的自注意力 中(自回归的属性)
class DecoderBlock(nn.Module):
"""解码器的第i个块"""
def __init__(self, key_size, query_size, value_size, num_hiddens,
norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,
dropout, i, **kwargs):
super(DecoderBlock, self).__init__(**kwargs)
self.i = i
self.attention1 = d2l.MultiHeadAttention(
key_size, query_size, value_size, num_hiddens, num_heads, dropout)
self.addnorm1 = AddNorm(norm_shape, dropout)
self.attention2 = d2l.MultiHeadAttention(
key_size, query_size, value_size, num_hiddens, num_heads, dropout)
self.addnorm2 = AddNorm(norm_shape, dropout)
self.ffn = PositionWiseFFN(ffn_num_input, ffn_num_hiddens, num_hiddens)
self.addnorm3 = AddNorm(norm_shape, dropout)
def forward(self, x, state):
enc_ouputs, enc_valid_lens = state[0], state[1]
# 训练阶段,输出序列的所有词元 都在 同一时间 处理
# 因此state[2][self.i] 初始化为 None
# 预测阶段,输出序列是通过 词元 一个接一个解码的
# 因此State[2][self.i]包含着 直到当前时间步第i个块 解码的输出表示
if state[2][self.i] is None:
key_values = x
else:
key_values = torch.cat((state[2][self.i], x), axis = 1)
state[2][self.i] = key_values
if self.training:
batch_size, num_steps, _ = x.shape
# dec_valid_lens的开头: (batch_size, num_steps)
# 其中每一行是[1,2,…,num_steps]
dec_valid_lens = torch.arange(
1, num_steps + 1, device=x.device).repeat(batch_size, 1)
else:
dec_valid_lens = None
# 自注意力
x2 = self.attention1(x, key_values, key_values, dec_valid_lens)
y = self.addnorm1(x, x2)
# 编码器-解码器注意力
# enc_outputs 的开头:(batch_size, num_steps, num_hiddens)
y2 = self.attention2(y, enc_ouputs, enc_ouputs, enc_valid_lens)
z = self.addnorm2(y, y2)
return self.addnorm3(z, self.ffn(z)), state
# 为了便于在“解码器-编码器”att 中进行 缩放点积计算 和 resnet 中进行加法计算
# 编码器和解码器的特征维度都是 num_hiddens
decoder_blk = DecoderBlock(24, 24, 24, 24, [100, 24], 24, 48, 8, 0.5, 0)
decoder_blk.eval()
x = torch.ones((2, 100, 24))
state = [encoder_blk(x, valid_lens), valid_lens, [None]]
decoder_blk(x, state)[0].shape # 维度和x相同
torch.Size([2, 100, 24])
# 构建由 num_layers 个DecoderBlock 实例组成的 完整trans解码器
# 最后FC计算 所有vocab_size个可能的输出词元 的预测值
class TransformerDecoder(d2l.AttentionDecoder):
def __init__(self, vocab_size, key_size, query_size, value_size,
num_hiddens, norm_shape, ffn_num_input, ffn_num_hiddens,
num_heads, num_layers, dropout, **kwargs):
super(TransformerDecoder, self).__init__(**kwargs)
self.num_hiddens = num_hiddens
self.num_layers = num_layers
self.embedding = nn.Embedding(vocab_size, num_hiddens)
self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)
self.blks = nn.Sequential()
for i in range(num_layers):
self.blks.add_module("block" + str(i),
DecoderBlock(key_size, query_size, value_size, num_hiddens,
norm_shape, ffn_num_input, ffn_num_hiddens,
num_heads, dropout, i))
self.dense = nn.Linear(num_hiddens, vocab_size)
def init_state(self, enc_outputs, enc_valid_lens, *args):
return [enc_outputs, enc_valid_lens, [None] * self.num_layers]
def forward(self, x, state):
x = self.pos_encoding(self.embedding(x) * math.sqrt(self.num_hiddens))
self._attention_weights = [[None] * len(self.blks) for _ in range(2)]
for i, blk in enumerate(self.blks):
x, state = blk(x, state)
# 解码器 self att 权重
self._attention_weights[0][i] = blk.attention1.attention.attention_weights
# “解码器-编码器”self-att 权重
self._attention_weights[1][i] = blk.attention2.attention.attention_weights
return self.dense(x), state
@property
def attention_weights(self):
return self._attention_weights
10.7.6 训练
- 依照trans架构实例化“编码器-解码器”模型
- 编码器和解码器都指定为2层,都是用4头注意力
- seq2seq学习,在“英-法”机器翻译数据集上训练trans模型
num_hiddens, num_layers, dropout, batch_size, num_steps = 32, 2, 0.2, 64, 10
lr, num_epochs, device = 0.005, 250, d2l.try_gpu()
ffn_num_input, ffn_num_hiddens, num_heads = 32, 64, 4
key_size, query_size, value_size = 32, 32, 32
norm_shape = [32]
train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)
encoder = TransformerEncoder(
len(src_vocab), key_size, query_size, value_size, num_hiddens,
norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,
num_layers, dropout)
decoder = TransformerDecoder(
len(tgt_vocab), key_size, query_size, value_size, num_hiddens,
norm_shape, ffn_num_input, ffn_num_hiddens, num_heads,
num_layers, dropout)
net = d2l.EncoderDecoder(encoder, decoder)
d2l.train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)
loss 0.044, 8681.7 tokens/sec on cuda:0
# 训练完后,使用 trans模型 将 一些英语句子 翻译成 法语,计算BLEU分数
engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
for eng, fra in zip(engs, fras):
translation, dec_attention_weight_seq = d2l.predict_seq2seq(
net, eng, src_vocab, tgt_vocab, num_steps, device, True)
print(f'{eng} => {translation}, '
f'bleu{d2l.bleu(translation, fra, k=2):.3f}')
# AC! 全部 100%
go . => va !, bleu1.000
i lost . => j'ai perdu ., bleu1.000
he's calm . => il est calme ., bleu1.000
i'm home . => je suis chez moi ., bleu1.000
# 可视化 trans 的 att权重
# 编码器 self-att 形状为:
#(编码器层数,注意力头数, num_steps或查询的数目,num_steps或“键-值”对的数目)
enc_attention_weights = torch.cat(net.encoder.attention_weights, 0).reshape((
num_layers, num_heads, -1, num_steps))
enc_attention_weights.shape
torch.Size([2, 4, 10, 10])
# 编码器的 self-att中,QK都来自相同的input序列
# 由于填充词元不携带信息,
# 故要指定 input序列的有效长度 可避免 Q与使用的填充词元的位置 计算注意力。
# 以下呈现 两层多头注意力的权重,
# 其中每个att头 都根据 QKV的不同的表示子空间 来表示 不同的注意力。
d2l.show_heatmaps(
enc_attention_weights.cpu(), xlabel='Key positions',
ylabel='Query positions', titles=['Head %d' % i for i in range(1, 5)],
figsize=(7, 3.5))
import pandas as pd
# 为了可视化 解码器的self-att权重 和 “编码器-解码器”的att权重 需要做以下工作:
# 例如: 用0填充被掩蔽住的att权重
# 这两种权重都有相同的Q,即以 序列开始词元(BOS)打头,然后与 后续输出的词元 共同组成。
dec_attention_weights_2d = [head[0].tolist()
for step in dec_attention_weight_seq
for attn in step for blk in attn for head in blk]
dec_attention_weights_filled = torch.tensor(
pd.DataFrame(dec_attention_weights_2d).fillna(0.0).values)
dec_attention_weights = dec_attention_weights_filled.reshape((-1, 2, num_layers,
num_heads, num_steps))
dec_attention_weights, dec_inter_attention_weights = dec_attention_weights.permute(1, 2, 3, 0, 4)
dec_attention_weights.shape, dec_inter_attention_weights.shape
(torch.Size([2, 4, 6, 10]), torch.Size([2, 4, 6, 10]))
# 由于解码器self-att的 AR属性,Q不会对 当前位置之后逇“K-V”对进行 att计算
d2l.show_heatmaps(
dec_attention_weights[:,:,:,:len(translation.split()) + 1],
xlabel='Key positions', ylabel='Query positions',
titles=['Head %d' % i for i in range(1, 5)], figsize=(7, 3.5))
# 与 编码器的self-att 类似,
# 通过指定 输入序列的有效长度,输出序列的Q 不会与 输入序列中填充位置的词元 进行att计算
d2l.show_heatmaps(
dec_attention_weights, xlabel='Key positions',
ylabel='Query positions', titles=['Head %d' % i for i in range(1, 5)],
figsize=(7, 3.5))
在后面,trans编码器和trans解码器可单独用于不同的DL任务中
总结
- trans是编码器-解码器架构的一个实践;
- 实际中,编码器和解码器可以单独使用
- trans中,多头self-att 用于表示 输入和输出序列;其中 解码器 通过掩蔽机制来保留AR属性
- trans中的 resnet 和 layer norm 是训练 非常深度模型 的重要工具
- trans模型中的 Positionwise FFN(feed-forward network) 使用 同一个MLP, 作用是对 所有序列位置的表示 进行转换。