Certainly! Building a mini transformer model for translating English to German with a limited vocabulary is a great way to understand the fundamentals of transformer architectures. Below is a complete Python script using PyTorch that accomplishes this task.
Overview
- Dependencies: We'll use
torch for building and training the model.
- Data Preparation: Define a small dataset with limited vocabulary.
- Vocabulary and Tokenization: Create word-to-index and index-to-word mappings.
- Model Definition: Implement a basic Transformer model with encoder and decoder.
- Training: Train the model on the dataset.
- Evaluation: Test the model with an example.
Let's dive into each step.
Complete Python Code
import torch
import torch.nn as nn
import torch.optim as optim
import math
import copy
import time
# Device configuration
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#############################################
# 1. Data Preparation
#############################################
# Define the limited vocabulary
src_vocab = ["hello", "my", "name", "is", "chris", "banana"]
tgt_vocab = ["hallo", "mein", "name", "ist", "chris", "banane"]
# Add special tokens
SRC_PAD_IDX = len(src_vocab)
TGT_PAD_IDX = len(tgt_vocab)
src_vocab.append("<pad>")
tgt_vocab.append("<pad>")
SRC_SOS_IDX = len(src_vocab)
TGT_SOS_IDX = len(tgt_vocab)
src_vocab.append("<sos>")
tgt_vocab.append("<sos>")
SRC_EOS_IDX = len(src_vocab)
TGT_EOS_IDX = len(tgt_vocab)
src_vocab.append("<eos>")
tgt_vocab.append("<eos>")
SRC_VOCAB_SIZE = len(src_vocab)
TGT_VOCAB_SIZE = len(tgt_vocab)
# Create word to index and index to word mappings
src_word2idx = {word: idx for idx, word in enumerate(src_vocab)}
src_idx2word = {idx: word for idx, word in enumerate(src_vocab)}
tgt_word2idx = {word: idx for idx, word in enumerate(tgt_vocab)}
tgt_idx2word = {idx: word for idx, word in enumerate(tgt_vocab)}
# Example sentence pair
# English: "hello my name is chris"
# German: "hallo mein name ist chris"
# Including "banana" as an extra word
pairs = [
(["hello", "my", "name", "is", "chris"], ["hallo", "mein", "name", "ist", "chris"]),
(["hello", "banana"], ["hallo", "banane"]),
(["banana", "my", "name"], ["banane", "mein", "name"]),
(["my", "banana", "is"], ["mein", "banane", "ist"]),
(["chris", "banana"], ["chris", "banane"]),
# Add more pairs if needed
]
# Function to convert words to indices
def encode_sentence(sentence, word2idx):
return [word2idx["<sos>"]] + [word2idx[word] for word in sentence] + [word2idx["<eos>"]]
def decode_sentence(indices, idx2word):
# Exclude <sos> and <eos>
words = []
for idx in indices:
if idx2word[idx] == "<eos>":
break
if idx2word[idx] not in ["<sos>", "<eos>"]:
words.append(idx2word[idx])
return ' '.join(words)
# Encode all pairs
encoded_pairs = []
for src, tgt in pairs:
encoded_src = encode_sentence(src, src_word2idx)
encoded_tgt = encode_sentence(tgt, tgt_word2idx)
encoded_pairs.append((encoded_src, encoded_tgt))
#############################################
# 2. Create Batches and Padding
#############################################
def pad_sequences(sequences, max_len, pad_value):
return sequences + [pad_value]*(max_len - len(sequences))
# Since the dataset is small, we'll use batch size = 1
def get_batches(pairs):
for src, tgt in pairs:
yield src, tgt
#############################################
# 3. Define the Transformer Model
#############################################
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=100):
super(PositionalEncoding, self).__init__()
# Create a long enough P
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() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
if d_model %2 ==1:
pe[:,1::2] = torch.cos(position * div_term[:pe[:,1::2].shape[1]])
else:
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0,1) # Shape: (max_len, 1, d_model)
self.register_buffer('pe', pe)
def forward(self, x):
# x shape: (seq_len, batch_size, d_model)
x = x + self.pe[:x.size(0), :]
return x
class TransformerModel(nn.Module):
def __init__(self, src_vocab_size, tgt_vocab_size, d_model=32, nhead=2, num_encoder_layers=2, num_decoder_layers=2, dim_feedforward=64, dropout=0.1):
super(TransformerModel, self).__init__()
self.src_embedding = nn.Embedding(src_vocab_size, d_model)
self.tgt_embedding = nn.Embedding(tgt_vocab_size, d_model)
self.positional_encoding = PositionalEncoding(d_model)
self.transformer = nn.Transformer(d_model, nhead, num_encoder_layers, num_decoder_layers, dim_feedforward, dropout)
self.fc_out = nn.Linear(d_model, tgt_vocab_size)
self.d_model = d_model
def forward(self, src, tgt, src_mask, tgt_mask, src_padding_mask, tgt_padding_mask, memory_key_padding_mask):
# src: (S, N)
# tgt: (T, N)
src_emb = self.src_embedding(src) * math.sqrt(self.d_model) # (S, N, D)
tgt_emb = self.tgt_embedding(tgt) * math.sqrt(self.d_model) # (T, N, D)
src_emb = self.positional_encoding(src_emb)
tgt_emb = self.positional_encoding(tgt_emb)
output = self.transformer(src_emb, tgt_emb, src_mask, tgt_mask,
None, src_padding_mask, tgt_padding_mask, memory_key_padding_mask)
output = self.fc_out(output) # (T, N, tgt_vocab_size)
return output
#############################################
# 4. Training Setup
#############################################
# Hyperparameters
D_MODEL = 32
NHEAD = 2
NUM_ENCODER_LAYERS = 2
NUM_DECODER_LAYERS = 2
DIM_FEEDFORWARD = 64
DROPOUT = 0.1
NUM_EPOCHS = 300
LEARNING_RATE = 0.001
model = TransformerModel(SRC_VOCAB_SIZE, TGT_VOCAB_SIZE, D_MODEL, NHEAD, NUM_ENCODER_LAYERS, NUM_DECODER_LAYERS, DIM_FEEDFORWARD, DROPOUT).to(DEVICE)
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
criterion = nn.CrossEntropyLoss(ignore_index=TGT_PAD_IDX)
# Function to generate square subsequent mask
def generate_square_subsequent_mask(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
# Function to create padding masks
def create_padding_mask(seq, pad_idx):
return (seq == pad_idx).transpose(0,1) # (N, S)
#############################################
# 5. Training Loop
#############################################
for epoch in range(1, NUM_EPOCHS+1):
model.train()
epoch_loss = 0
for src, tgt in get_batches(encoded_pairs):
src = torch.tensor(src, dtype=torch.long).unsqueeze(1).to(DEVICE) # (S, 1)
tgt = torch.tensor(tgt, dtype=torch.long).unsqueeze(1).to(DEVICE) # (T, 1)
tgt_input = tgt[:-1, :] # remove <eos>
targets = tgt[1:, :].reshape(-1) # shift left
src_mask = torch.zeros((src.size(0), src.size(0))).type(torch.bool).to(DEVICE)
tgt_seq_len = tgt_input.size(0)
tgt_mask = generate_square_subsequent_mask(tgt_seq_len).to(DEVICE)
src_padding_mask = create_padding_mask(src, SRC_PAD_IDX).to(DEVICE)
tgt_padding_mask = create_padding_mask(tgt_input, TGT_PAD_IDX).to(DEVICE)
memory_key_padding_mask = src_padding_mask
optimizer.zero_grad()
output = model(src, tgt_input, src_mask, tgt_mask,
src_padding_mask, tgt_padding_mask, memory_key_padding_mask)
output = output.reshape(-1, TGT_VOCAB_SIZE)
loss = criterion(output, targets)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
if epoch % 50 ==0 or epoch==1:
print(f'Epoch {epoch}, Loss: {epoch_loss/len(encoded_pairs):.4f}')
#############################################
# 6. Evaluation
#############################################
def translate(model, sentence, src_word2idx, tgt_idx2word, max_len=10):
model.eval()
tokens = encode_sentence(sentence, src_word2idx)
src = torch.tensor(tokens, dtype=torch.long).unsqueeze(1).to(DEVICE) # (S, 1)
src_mask = torch.zeros((src.size(0), src.size(0))).type(torch.bool).to(DEVICE)
src_padding_mask = create_padding_mask(src, SRC_PAD_IDX).to(DEVICE)
memory = model.transformer.encoder(model.positional_encoding(model.src_embedding(src) * math.sqrt(D_MODEL)), src_mask, src_padding_mask)
ys = torch.tensor([[tgt_word2idx["<sos>"]]], dtype=torch.long).to(DEVICE) # (1,1)
for i in range(max_len):
tgt_mask = generate_square_subsequent_mask(ys.size(0)).to(DEVICE)
tgt_padding_mask = create_padding_mask(ys, TGT_PAD_IDX).to(DEVICE)
out = model.transformer.decoder(model.positional_encoding(model.tgt_embedding(ys) * math.sqrt(D_MODEL)),
memory, tgt_mask, None, tgt_padding_mask, src_padding_mask)
out = model.fc_out(out)
prob = out[-1,0,:]
next_word = prob.argmax().item()
ys = torch.cat([ys, torch.tensor([[next_word]], device=DEVICE)], dim=0)
if next_word == tgt_word2idx["<eos>"]:
break
return decode_sentence(ys.cpu().numpy(), tgt_idx2word)
# Test examples
test_sentences = [
["hello", "my", "name", "is", "chris"],
["hello", "banana"],
["banana", "my", "name"],
["my", "banana", "is"],
["chris", "banana"],
]
for sentence in test_sentences:
translation = translate(model, sentence, src_word2idx, tgt_idx2word)
print(f'Input: {" ".join(sentence)}\nTranslated: {translation}\n')
Explanation of the Code
-
Data Preparation:
- Vocabulary: We define a limited set of English (
src_vocab) and German (tgt_vocab) words. Special tokens like <pad>, <sos> (start of sentence), and <eos> (end of sentence) are added to handle padding and sequence boundaries.
- Sentence Pairs: A small set of English-German sentence pairs is created, including the word "banana" to demonstrate the model's ability to handle an extra word.
- Encoding: Sentences are converted into sequences of indices based on the vocabulary mappings.
-
Model Definition:
- Positional Encoding: Since transformers don't have inherent positional information, positional encodings are added to give the model a sense of word order.
- TransformerModel Class: This class encapsulates the transformer architecture, including embedding layers for source and target languages, positional encodings, the transformer itself, and a final linear layer to project the transformer outputs to the target vocabulary size.
-
Training Setup:
- Hyperparameters: Basic settings like embedding dimensions, number of heads, layers, etc., are defined.
- Loss and Optimizer: Cross-entropy loss is used, ignoring the padding index, and the Adam optimizer is employed for training.
-
Training Loop:
- For each epoch, the model processes each sentence pair, computes the loss, and updates the model parameters. Progress is printed every 50 epochs.
-
Evaluation:
- The
translate function takes an English sentence, encodes it, and generates the German translation by iteratively predicting the next word until <eos> is generated or the maximum length is reached.
- Several test sentences are translated and printed to demonstrate the model's performance.
Running the Code
To run this script:
-
Prerequisites:
-
Ensure you have Python installed (preferably 3.6 or higher).
-
Install PyTorch. You can install it via pip:
pip install torch
Make sure to install the version compatible with your system and CUDA (if using GPU).
-
Execute:
-
Save the script to a file, say mini_transformer.py.
-
Run the script:
python mini_transformer.py
-
The training progress will be displayed, and after training, the translations of the test sentences will be printed.
Notes
- Dataset Size: The dataset here is extremely small. In real-world scenarios, transformers require large amounts of data to perform well. This example serves educational purposes.
- Model Complexity: The transformer parameters are kept minimal (
d_model=32, nhead=2, etc.) to ensure quick training on limited data. Increasing these might benefit model capacity but require more data and computation.
- Further Improvements:
- More Data: Adding more sentence pairs can help the model generalize better.
- Batching: Implement batching for more efficient training.
- Evaluation Metrics: Incorporate metrics like BLEU scores for more quantitative evaluation.
- Beam Search: Implement beam search during translation for better performance.
This script provides a foundational understanding of how transformers can be implemented for sequence-to-sequence tasks like translation, even with a constrained vocabulary.