Implementing the Transformer model from the "Attention is All You Need" paper using PyTorch involves creating the key components of the Transformer: the scaled dot-product attention, multi-head attention, positional encoding, the encoder, and the decoder. Here is a simplified version of how to implement a basic Transformer model using PyTorch.
Please note that for brevity, this example will focus primarily on the self-attention and multi-head attention components, which are central to the Transformer architecture.
import torch
import torch.nn as nn
import numpy as np
class ScaledDotProductAttention(nn.Module):
def __init__(self, temperature):
super().__init__()
self.temperature = temperature
def forward(self, q, k, v, mask=None):
attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
if mask is not None:
attn = attn.masked_fill(mask == 0, -1e9)
attn = torch.softmax(attn, dim=-1)
output = torch.matmul(attn, v)
return output, attn
class MultiHeadAttention(nn.Module):
def __init__(self, n_head, d_model, d_k, d_v):
super().__init__()
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.w_qs = nn.Linear(d_model, n_head * d_k)
self.w_ks = nn.Linear(d_model, n_head * d_k)
self.w_vs = nn.Linear(d_model, n_head * d_v)
self.fc = nn.Linear(n_head * d_v, d_model)
self.attention = ScaledDotProductAttention(temperature=d_k**0.5)
self.layer_norm = nn.LayerNorm(d_model)
def forward(self, q, k, v, mask=None):
d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
sz_b, len_q, len_k, len_v = q.size(0), q.size(1), k.size(1), v.size(1)
residual = q
q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
if mask is not None:
mask = mask.unsqueeze(1)
q, attn = self.attention(q, k, v, mask=mask)
q = q.transpose(1, 2).contiguous().view(sz_b, len_q, -1)
q = self.fc(q)
q = self.layer_norm(q + residual)
return q, attn
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-np.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
return x + self.pe[:, :x.size(1)]
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, n_head, d_inner, dropout=0.1):
super().__init__()
self.attention = MultiHeadAttention(n_head, d_model, d_model//n_head, d_model//n_head)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(d_model)
self.positionwise_ff = nn.Sequential(
nn.Linear(d_model, d_inner),
nn.ReLU(),
nn.Linear(d_inner, d_model),
nn.Dropout(dropout)
)
def forward(self, enc_input, mask=None):
enc_output, attn = self.attention(enc_input, enc_input, enc_input, mask=mask)
enc_output = self.positionwise_ff(enc_output)
enc_output = self.layer_norm(enc_output)
return enc_output, attn
class TransformerEncoder(nn.Module):
def __init__(self, n_layers, d_model, n_head, d_inner, input_dim, dropout=0.1):
super().__init__()
self.position_enc = PositionalEncoding(d_model)
self.layer_stack = nn.ModuleList([
TransformerEncoderLayer(d_model, n_head, d_inner, dropout=dropout)
for _ in range(n_layers)
])
self.input_projection = nn.Linear(input_dim, d_model)
def forward(self, enc_input, mask=None, return_attns=False):
enc_output = self.input_projection(enc_input)
enc_output = self.position_enc(enc_output)
enc_slf_attn_list = []
for enc_layer in self.layer_stack:
enc_output, enc_slf_attn = enc_layer(enc_output, mask=mask)
if return_attns:
enc_slf_attn_list.append(enc_slf_attn)
if return_attns:
return enc_output, enc_slf_attn_list
return enc_output,
# Example usage:
# Define model parameters
d_model = 512
n_heads = 8
d_inner = 2048
n_layers = 6
input_dim = 512
# Instantiate the Transformer Encoder
transformer_encoder = TransformerEncoder(n_layers, d_model, n_heads, d_inner, input_dim)
# Dummy input
input_data = torch.rand(64, 10, input_dim) # batch_size x seq_len x input_dim
# Forward pass
output, attn = transformer_encoder(input_data, return_attns=True)
print(output.shape) # Should output: (64, 10, 512)
This implementation highlights the key components, focusing on a single Transformer encoder block. The code includes:
- Scaled Dot-Product Attention: A module for computing attention scores.
- Multi-Head Attention: Utilizes multiple self-attention mechanisms in parallel.
- Positional Encoding: Adds positional information to token embeddings.
- Transformer Encoder Layer: Combines the attention mechanism with a feedforward neural network and layer normalization.
- Transformer Encoder: Stacks multiple encoder layers and utilizes positional encodings.
Keep in mind that to create a full Transformer as described in the paper, you’d also need to implement the decoder, plus additional logic for tasks like machine translation to handle input-output sequences. Additionally, configurations like dropout rates, dimensions, and layer numbers should be adjusted based on specific needs and available computational resources.