Code a powerful text genration model from scratch with powerful libraries and advanced…
- User
Code a powerful text genration model from scratch with powerful libraries and advanced techniques.
- Assistant
Code a powerful text genration model from scratch with powerful libraries and advanced techniques.
Text generation models have revolutionized natural language processing (NLP), enabling applications like chatbots, content creation, and machine translation. This guide will walk you through building a powerful text generation model from scratch using advanced techniques and powerful libraries like PyTorch.
We'll implement a Transformer-based language model, inspired by architectures like GPT (Generative Pre-trained Transformer), capable of generating coherent and contextually relevant text.
First, let's set up the Python environment and install the required libraries.
# Install PyTorch and TorchText
pip install torch torchvision torchtext
# For tokenization
pip install sentencepiece
Ensure that you have a CUDA-capable GPU if you plan to train the model on a GPU.
A large and diverse dataset is crucial for training a robust text generation model.
For this tutorial, we'll use the WikiText-2 dataset, which is available through torchtext. It contains a large collection of Wikipedia articles.
import torch
from torchtext.datasets import WikiText2
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
# Define the tokenizer
tokenizer = get_tokenizer('basic_english')
# Load training data
train_iter = WikiText2(split='train')
# Build the vocabulary
def yield_tokens(data_iter):
for text in data_iter:
yield tokenizer(text)
vocab = build_vocab_from_iterator(yield_tokens(train_iter), specials=["<unk>"])
vocab.set_default_index(vocab["<unk>"])
# Process raw text into tensors
def data_process(raw_text_iter):
data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter]
return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))
# Load and process datasets
train_iter, val_iter, test_iter = WikiText2()
train_data = data_process(train_iter)
val_data = data_process(val_iter)
test_data = data_process(test_iter)
We'll define a function to generate batches for training.
def batchify(data, batch_size):
# Remove extra elements so that data can be divided evenly
n_batch = data.size(0) // batch_size
data = data[:n_batch * batch_size]
# Reshape data into batch_size columns
data = data.view(batch_size, -1).t().contiguous()
return data.to(device)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
batch_size = 20
train_data = batchify(train_data, batch_size)
val_data = batchify(val_data, batch_size)
test_data = batchify(test_data, batch_size)
We'll implement a Transformer-based language model.
The Transformer architecture uses self-attention mechanisms to handle sequence data efficiently.
import torch.nn as nn
import math
class TransformerModel(nn.Module):
def __init__(self, vocab_size, embed_size, nhead, hidden_dim, num_layers, dropout=0.5):
super(TransformerModel, self).__init__()
self.model_type = 'Transformer'
self.pos_encoder = PositionalEncoding(embed_size, dropout)
encoder_layers = nn.TransformerEncoderLayer(d_model=embed_size, nhead=nhead, dim_feedforward=hidden_dim, dropout=dropout)
self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers)
self.embed_size = embed_size
self.encoder = nn.Embedding(vocab_size, embed_size)
self.decoder = nn.Linear(embed_size, vocab_size)
self.init_weights()
def init_weights(self):
initrange = 0.1
# Initialize encoder and decoder weights
self.encoder.weight.data.uniform_(-initrange, initrange)
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self, src, src_mask):
# Embed input tokens and apply positional encoding
src = self.encoder(src) * math.sqrt(self.embed_size)
src = self.pos_encoder(src)
# Pass through Transformer encoder
output = self.transformer_encoder(src, src_mask)
# Decode output to vocabulary size
output = self.decoder(output)
return output
def generate_square_subsequent_mask(self, size):
# Create a mask to prevent the model from attending to future positions
mask = (torch.triu(torch.ones(size, size)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
return mask
Positional encoding provides the model with information about the relative position of tokens in the sequence.
class PositionalEncoding(nn.Module):
def __init__(self, embed_size, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
# Create positional encoding matrix
pe = torch.zeros(max_len, embed_size)
position = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1)
div_term = torch.exp(torch.arange(0, embed_size, 2).float() * (-math.log(10000.0) / embed_size))
pe[:, 0::2] = torch.sin(position * div_term) # Apply sine to even indices
pe[:, 1::2] = torch.cos(position * div_term) # Apply cosine to odd indices
pe = pe.unsqueeze(0).transpose(0, 1) # Reshape for adding to embedding
self.register_buffer('pe', pe)
def forward(self, x):
# Add positional encoding to embedding
x = x + self.pe[:x.size(0), :]
return self.dropout(x)
embed_size = 512 # Embedding size
hidden_dim = 512 # Dimension of the feedforward network model
num_layers = 6 # Number of Transformer encoder layers
nhead = 8 # Number of heads in multi-head attention
dropout = 0.2 # Dropout probability
learning_rate = 5e-4 # Learning rate
epochs = 10 # Number of epochs
seq_length = 35 # Sequence length for training
model = TransformerModel(len(vocab), embed_size, nhead, hidden_dim, num_layers, dropout).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)
def get_batch(source, i):
seq_len = min(seq_length, len(source) - 1 - i)
data = source[i:i+seq_len]
target = source[i+1:i+1+seq_len].reshape(-1)
return data.t(), target
def train(model):
model.train()
total_loss = 0.
log_interval = 200
src_mask = model.generate_square_subsequent_mask(seq_length).to(device)
for batch, i in enumerate(range(0, train_data.size(0) - 1, seq_length)):
data, targets = get_batch(train_data, i)
optimizer.zero_grad()
if data.size(0) != seq_length:
src_mask = model.generate_square_subsequent_mask(data.size(0)).to(device)
output = model(data, src_mask)
loss = criterion(output.view(-1, len(vocab)), targets)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optimizer.step()
total_loss += loss.item()
if batch % log_interval == 0 and batch > 0:
avg_loss = total_loss / log_interval
print(f'| Batch {batch} | Loss {avg_loss:.2f} |')
total_loss = 0
def evaluate(model, data_source):
model.eval()
total_loss = 0.
src_mask = model.generate_square_subsequent_mask(seq_length).to(device)
with torch.no_grad():
for i in range(0, data_source.size(0) - 1, seq_length):
data, targets = get_batch(data_source, i)
if data.size(0) != seq_length:
src_mask = model.generate_square_subsequent_mask(data.size(0)).to(device)
output = model(data, src_mask)
output_flat = output.view(-1, len(vocab))
total_loss += len(data) * criterion(output_flat, targets).item()
return total_loss / (len(data_source) - 1)
best_val_loss = float('inf')
for epoch in range(1, epochs + 1):
print(f'Epoch {epoch}:')
train(model)
val_loss = evaluate(model, val_data)
print(f'Validation Loss: {val_loss:.2f}')
# Save the model if validation loss decreases
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save(model.state_dict(), 'best_model.pt')
scheduler.step()
After training, we can use the model to generate text.
model.load_state_dict(torch.load('best_model.pt'))
def generate_text(model, start_words, max_length=100):
model.eval()
words = tokenizer(start_words)
input_ids = [vocab[word] for word in words]
input_tensor = torch.tensor(input_ids, dtype=torch.long).unsqueeze(1).to(device)
generated_ids = input_ids[:]
with torch.no_grad():
for _ in range(max_length):
src_mask = model.generate_square_subsequent_mask(len(input_tensor)).to(device)
output = model(input_tensor, src_mask)
next_word_logits = output[-1, 0, :]
next_word_id = torch.argmax(next_word_logits).item()
generated_ids.append(next_word_id)
input_tensor = torch.cat([input_tensor, torch.tensor([[next_word_id]]).to(device)], dim=0)
generated_text = ' '.join([vocab.lookup_token(idx) for idx in generated_ids])
return generated_text
start_text = "Once upon a time"
print(generate_text(model, start_text, max_length=50))
Using SentencePiece for subword tokenization can improve the model's ability to handle rare or unknown words.
import sentencepiece as spm
# Train SentencePiece model on your dataset
# spm.SentencePieceTrainer.train(input='data.txt', model_prefix='m', vocab_size=32000)
# Load the trained model
sp = spm.SentencePieceProcessor()
sp.load('m.model')
# Tokenize text
tokens = sp.EncodeAsIds('This is a test')
Utilize mixed precision training to reduce memory usage and speed up training.
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
def train_mixed_precision(model):
model.train()
total_loss = 0.
scaler = GradScaler()
for batch, i in enumerate(range(0, train_data.size(0) - 1, seq_length)):
data, targets = get_batch(train_data, i)
optimizer.zero_grad()
with autocast():
output = model(data, src_mask)
loss = criterion(output.view(-1, len(vocab)), targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
total_loss += loss.item()
Use advanced learning rate schedulers like Cosine Annealing or OneCycleLR for potentially better convergence.
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
Implement techniques like Dropout, Label Smoothing, and Early Stopping to prevent overfitting.
Leverage multiple GPUs for faster training using PyTorch's distributed data parallelism.
from torch.nn.parallel import DistributedDataParallel as DDP
model = DDP(model)
Building a powerful text generation model involves combining advanced architectures, efficient training techniques, and careful data preparation. By leveraging the Transformer architecture and PyTorch's capabilities, you can create a model capable of generating coherent and meaningful text.
Note: This tutorial provides a foundation for building text generation models. For production-level models, consider using pre-trained architectures and fine-tuning them on your specific dataset.
Not yet included in a published release.