Python 用pytorch从头写Transformer源码,一行一解释;机器翻译实例代码;Transformer源码解读与实战
由于篇幅所限,这里我们只提供Transformer模型的核心函数,并给出必要的代码解释。
import torch
import torch.nn as nn
import torch.nn.functional as F
class TransformerModel(nn.Module):
"""Transformer模型的简化实现。"""
def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):
super(TransformerModel, self).__init__()
self.model_type = 'Transformer'
self.pos_encoder = PositionalEncoding(ninp, dropout)
self.encoder = nn.TransformerEncoder(
EncoderLayer(ninp, nhead, nhid, dropout),
num_layers=nlayers
)
self.decoder = nn.Linear(ninp, ntoken)
self.init_weights()
self.ninp = ninp
self.nhid = nhid
self.nhead = nhead
def _generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
return mask
def init_weights(self):
initrange = 0.1
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self, src):
src = self.pos_encoder(src)
output = self.encoder(src)
output = self.decoder(output)
return F.log_softmax(output, dim=-1)
class EncoderLayer(nn.Module):
"编码器的单层组成部分"
def __init__(self, nhidden, nhead, nhid, dropout=0.5):
super(EncoderLayer, self).__init__()
self.self_attn = nn.MultiheadAttention(nhidden, nhead, dropout=dropout)
self.linear1 = nn.Linear(nhidden, nhid)
self.relu = nn.ReLU()
self.linear2 = nn.Linear(nhid, nhidden)
self.dropout = nn.Dropout(dropout)
def forward(self, src):
src = self.self_attn(src, src, src)[0]
src = self.dropout(src)
src = self.linear2(self.relu(self.linear1(src)))
src = self.dropout(src)
return src
class PositionalEncoding(nn.Module):
"位置编码"
def __init__(self, dmodel, dropout=0.1, max_len=5000):
s
评论已关闭