https://pub.towardsai.net/heres-how-you-can-build-and-train-gpt-2-from-scratch-using-pyto…
- User
- Assistant
Sure! Building and training a GPT-2 model from scratch using PyTorch is a great way to deepen your understanding of transformer architectures and natural language processing. Below is a comprehensive guide to help you through the process.
GPT-2 (Generative Pretrained Transformer 2) is an autoregressive language model that excels at generating coherent and contextually relevant text. It leverages the transformer architecture, specifically the decoder part, and relies on self-attention mechanisms to model relationships within the data.
Ensure you have Python installed (preferably 3.6 or higher) and install the required libraries:
pip install torch torchvision transformers numpy
Choose a text dataset suitable for language modeling. Some popular choices include:
GPT-2 uses Byte-Pair Encoding (BPE) tokenizer.
from transformers import GPT2Tokenizer
# Load GPT-2 tokenizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
Tokenize and encode your dataset:
def encode_data(texts, tokenizer):
return tokenizer('\n\n'.join(texts), return_tensors='pt', max_length=1024, truncation=True).input_ids
# Example with a list of text documents
input_ids = encode_data(list_of_texts, tokenizer)
Set up the model's architecture parameters:
from transformers import GPT2Config
config = GPT2Config(
vocab_size=tokenizer.vocab_size,
n_positions=1024,
n_embd=768,
n_layer=12,
n_head=12
)
Create the model instance:
from transformers import GPT2LMHeadModel
model = GPT2LMHeadModel(config)
Split your data into training batches:
from torch.utils.data import DataLoader, TensorDataset
dataset = TensorDataset(input_ids)
data_loader = DataLoader(dataset, batch_size=4, shuffle=True)
Use AdamW optimizer and a learning rate scheduler:
from transformers import get_linear_schedule_with_warmup
from torch.optim import AdamW
optimizer = AdamW(model.parameters(), lr=5e-5)
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=100,
num_training_steps=len(data_loader) * epochs
)
Place the model on the GPU if available:
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
Implement the training loop:
model.train()
for epoch in range(epochs):
for batch in data_loader:
inputs = batch[0].to(device)
outputs = model(inputs, labels=inputs)
loss = outputs.loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()
print(f"Epoch {epoch+1}/{epochs} completed. Loss: {loss.item()}")
Save the trained model and tokenizer for future use:
model.save_pretrained('./gpt2-from-scratch')
tokenizer.save_pretrained('./gpt2-from-scratch')
Load the model and tokenizer:
model = GPT2LMHeadModel.from_pretrained('./gpt2-from-scratch')
tokenizer = GPT2Tokenizer.from_pretrained('./gpt2-from-scratch')
model.to(device)
Generate text:
model.eval()
input_text = "Once upon a time"
input_ids = tokenizer.encode(input_text, return_tensors='pt').to(device)
# Generate text
with torch.no_grad():
generated_ids = model.generate(
input_ids,
max_length=50,
num_return_sequences=1,
no_repeat_ngram_size=2,
early_stopping=True
)
generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
print(generated_text)
Leverage mixed precision training for faster computation and reduced memory usage:
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
for batch in data_loader:
inputs = batch[0].to(device)
with autocast():
outputs = model(inputs, labels=inputs)
loss = outputs.loss
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad()
After training, evaluate the model's ability to generate coherent text. Keep in mind:
Building GPT-2 from scratch allows you to customize the model architecture and gain a deeper understanding of its inner workings. By following the steps outlined above, you can train a GPT-2 model tailored to your specific dataset and requirements.
Feel free to ask if you need further clarification or assistance on any of the steps!