赞
踩
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') # 绘制单位阵热力图
import torch
from torch import nn
from d2l import torch as d2l
# 生成最后的噪声项目,五十个样本
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)
y_hat = torch.repeat_interleave(y_train.mean(), n_test)
plot_kernel_reg(y_hat) # 估计器不聪明
# 实现(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')
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]]])
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
# 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')
核K的指数 就是 att评分函数:Q和K越接近,我给你越高的分数
框架:
数学语言描述:
本节将介绍两个流行的评分函数 a a a
import math, torch
from torch import nn
from d2l import torch as d2l
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]]])
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')
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权重
解码器隐状态 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)
# 该类定义带有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]))
# 实例化带有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')
import math, torch
from torch import nn
from d2l import torch as d2l
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])
import math, torch
from torch import nn
from d2l import torch as d2l
# 基于多头注意力 对一个张量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])
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)
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)
# 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
P = P[0, :, :].unsqueeze(0).unsqueeze(0)
d2l.show_heatmaps(P, xlabel='Column (encoding dimension)',
ylabel='Row (position)', figsize=(3.5, 4), cmap='Blues')
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>)
# 对比 不同维度的 层规范化和 批量规范化 的效果
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])
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])
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
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))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。