Sure! Below is a simple example of a tiny GPT-like model trained on the Tiny Shakespeare dataset. The model is very small and the training loop is designed to run quickly (around 2 minutes) on Google Colab with a GPU.
This example uses PyTorch and trains a character-level language model on Tiny Shakespeare text. It’s inspired by Andrej Karpathy’s “minGPT” style but heavily simplified for speed and clarity.
How to use:
- Open a new Google Colab notebook.
- Paste the code below into a cell.
- Run the cell (make sure the runtime is set to GPU for faster training).
# Install dependencies (if needed)
!pip install torch --quiet
import torch
import torch.nn as nn
from torch.nn import functional as F
import time
# Check device
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Using device: {device}")
# Download Tiny Shakespeare dataset
!wget -q https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
with open('input.txt', 'r', encoding='utf-8') as f:
text = f.read()
print(f"Length of dataset in characters: {len(text)}")
# Create character vocabulary
chars = sorted(list(set(text)))
vocab_size = len(chars)
print(f"Vocab size: {vocab_size}")
# Create mappings from char to int and int to char
stoi = { ch:i for i,ch in enumerate(chars) }
itos = { i:ch for i,ch in enumerate(chars) }
def encode(s):
return [stoi[c] for c in s]
def decode(l):
return ''.join([itos[i] for i in l])
data = torch.tensor(encode(text), dtype=torch.long)
# Train/val split
n = int(0.9*len(data))
train_data = data[:n]
val_data = data[n:]
# Hyperparameters
batch_size = 64
block_size = 64 # context length
max_iters = 500 # ~2 minutes on Colab GPU
eval_interval = 100
learning_rate = 3e-4
device = device
eval_iters = 50
n_embd = 128
n_head = 4
n_layer = 4
dropout = 0.1
# Data loader
def get_batch(split):
data_ = train_data if split == 'train' else val_data
ix = torch.randint(len(data_) - block_size, (batch_size,))
x = torch.stack([data_[i:i+block_size] for i in ix])
y = torch.stack([data_[i+1:i+block_size+1] for i in ix])
return x.to(device), y.to(device)
@torch.no_grad()
def estimate_loss():
out = {}
model.eval()
for split in ['train', 'val']:
losses = torch.zeros(eval_iters)
for k in range(eval_iters):
X, Y = get_batch(split)
logits, loss = model(X, Y)
losses[k] = loss.item()
out[split] = losses.mean()
model.train()
return out
# Simple GPT-like model
class Head(nn.Module):
def __init__(self, head_size):
super().__init__()
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
self.dropout = nn.Dropout(dropout)
def forward(self, x):
B,T,C = x.shape
k = self.key(x) # (B,T,head_size)
q = self.query(x) # (B,T,head_size)
wei = q @ k.transpose(-2,-1) * C**-0.5 # (B,T,T)
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
wei = F.softmax(wei, dim=-1)
wei = self.dropout(wei)
v = self.value(x) # (B,T,head_size)
out = wei @ v # (B,T,head_size)
return out
class MultiHeadAttention(nn.Module):
def __init__(self, num_heads, head_size):
super().__init__()
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
self.proj = nn.Linear(num_heads*head_size, n_embd)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.dropout(self.proj(out))
return out
class FeedForward(nn.Module):
def __init__(self, n_embd):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embd, 4*n_embd),
nn.ReLU(),
nn.Linear(4*n_embd, n_embd),
nn.Dropout(dropout),
)
def forward(self, x):
return self.net(x)
class Block(nn.Module):
def __init__(self, n_embd, n_head):
super().__init__()
head_size = n_embd // n_head
self.sa = MultiHeadAttention(n_head, head_size)
self.ffwd = FeedForward(n_embd)
self.ln1 = nn.LayerNorm(n_embd)
self.ln2 = nn.LayerNorm(n_embd)
def forward(self, x):
x = x + self.sa(self.ln1(x))
x = x + self.ffwd(self.ln2(x))
return x
class GPTLanguageModel(nn.Module):
def __init__(self):
super().__init__()
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
self.position_embedding_table = nn.Embedding(block_size, n_embd)
self.blocks = nn.Sequential(*[Block(n_embd, n_head) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(n_embd)
self.lm_head = nn.Linear(n_embd, vocab_size)
def forward(self, idx, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx) # (B,T,C)
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
x = tok_emb + pos_emb # (B,T,C)
x = self.blocks(x) # (B,T,C)
x = self.ln_f(x) # (B,T,C)
logits = self.lm_head(x) # (B,T,vocab_size)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B*T, C)
targets = targets.view(B*T)
loss = F.cross_entropy(logits, targets)
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :] # (B, vocab_size)
probs = F.softmax(logits, dim=-1) # (B, vocab_size)
next_idx = torch.multinomial(probs, num_samples=1) # (B,1)
idx = torch.cat((idx, next_idx), dim=1) # (B, T+1)
return idx
model = GPTLanguageModel().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
start_time = time.time()
for iter in range(max_iters):
xb, yb = get_batch('train')
logits, loss = model(xb, yb)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if iter % eval_interval == 0:
losses = estimate_loss()
print(f"iter {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
end_time = time.time()
print(f"Training done in {end_time - start_time:.1f} seconds")
# Generate some text
context = "ROMEO: "
context_idx = torch.tensor(encode(context), dtype=torch.long, device=device).unsqueeze(0)
generated_idx = model.generate(context_idx, max_new_tokens=200)[0].tolist()
print(decode(generated_idx))
Explanation:
- This is a tiny GPT model with 4 transformer blocks, 4 attention heads, and embedding size 128.
- It trains on Tiny Shakespeare text for 500 iterations with batch size 64 and context length 64.
- The training loop prints loss every 100 iterations.
- After training, it generates 200 characters of text starting from
"ROMEO: ".
If you want it to train even faster, you can reduce max_iters or model size, but this should be a good balance for a quick demo on Colab.
Let me know if you want me to help with anything else!