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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.optim as optim
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import tiktoken
|
| 6 |
+
from datasets import load_dataset
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import numpy as np
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# Define hyperparameters
|
| 13 |
+
vocab_size = 50257
|
| 14 |
+
n_heads = 8
|
| 15 |
+
n_layers = 6
|
| 16 |
+
head_size = 64
|
| 17 |
+
n_embd = 512
|
| 18 |
+
block_size = 128
|
| 19 |
+
dropout = 0.1
|
| 20 |
+
learning_rate = 3e-4
|
| 21 |
+
weight_decay = 0.1
|
| 22 |
+
|
| 23 |
+
# Set Hugging Face cache directories on the external disk
|
| 24 |
+
os.environ['HF_HOME'] = '/media/adrian/FamilyBackup/adrian_ai_workspace/hf_cache'
|
| 25 |
+
os.environ['HF_DATASETS_CACHE'] = '/media/adrian/FamilyBackup/adrian_ai_workspace/datasets_cache'
|
| 26 |
+
|
| 27 |
+
# Load the BookCorpus dataset and ensure it's cached on the external disk
|
| 28 |
+
dataset = load_dataset("bookcorpus", cache_dir='/media/adrian/FamilyBackup/adrian_ai_workspace/')
|
| 29 |
+
|
| 30 |
+
# Keep only 10% of the dataset
|
| 31 |
+
total_samples = len(dataset["train"])
|
| 32 |
+
one_percent_samples = int(total_samples * 0.001)
|
| 33 |
+
dataset_subset = dataset["train"].select(range(one_percent_samples)) # Select only the first 1%
|
| 34 |
+
|
| 35 |
+
# Split the subset into train (90%) and test (10%)
|
| 36 |
+
split_dataset = dataset_subset.train_test_split(test_size=0.1) # 10% for testing
|
| 37 |
+
train_dataset = split_dataset["train"]
|
| 38 |
+
test_dataset = split_dataset["test"]
|
| 39 |
+
|
| 40 |
+
# Print the size of the train and the test sets
|
| 41 |
+
print(f"Train size: {len(train_dataset)}")
|
| 42 |
+
print(f"Test size: {len(test_dataset)}")
|
| 43 |
+
|
| 44 |
+
# Initialize the tiktoken encoder
|
| 45 |
+
enc = tiktoken.get_encoding("gpt2")
|
| 46 |
+
|
| 47 |
+
# Define the tokenization function
|
| 48 |
+
def tokenize_function(examples):
|
| 49 |
+
return {
|
| 50 |
+
"input_ids": [enc.encode(text) for text in examples["text"]],
|
| 51 |
+
"attention_mask": [[1] * len(enc.encode(text)) for text in examples["text"]]
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# Function to pad or truncate sequences
|
| 55 |
+
def pad_or_truncate(batch):
|
| 56 |
+
max_length = 512
|
| 57 |
+
for key in ['input_ids', 'attention_mask']:
|
| 58 |
+
batch[key] = [
|
| 59 |
+
seq[:max_length] + [0] * (max_length - len(seq)) if len(seq) < max_length else seq[:max_length]
|
| 60 |
+
for seq in batch[key]
|
| 61 |
+
]
|
| 62 |
+
return batch
|
| 63 |
+
|
| 64 |
+
# Tokenize and process the datasets
|
| 65 |
+
def process_dataset(dataset, split_name):
|
| 66 |
+
# Tokenize
|
| 67 |
+
tokenized_dataset = dataset.map(
|
| 68 |
+
tokenize_function,
|
| 69 |
+
batched=True,
|
| 70 |
+
num_proc=20,
|
| 71 |
+
remove_columns=dataset.column_names
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Pad or truncate
|
| 75 |
+
processed_dataset = tokenized_dataset.map(
|
| 76 |
+
pad_or_truncate,
|
| 77 |
+
batched=True,
|
| 78 |
+
num_proc=20,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# Set format to PyTorch tensors
|
| 82 |
+
processed_dataset.set_format(type="torch", columns=["input_ids", "attention_mask"])
|
| 83 |
+
|
| 84 |
+
return processed_dataset
|
| 85 |
+
|
| 86 |
+
# Process both train and test datasets
|
| 87 |
+
train_dataset = process_dataset(train_dataset, "train")
|
| 88 |
+
test_dataset = process_dataset(test_dataset, "test")
|
| 89 |
+
|
| 90 |
+
# Print some examples
|
| 91 |
+
print(f"Example train data: {train_dataset[0]}")
|
| 92 |
+
print(f"Example test data: {test_dataset[0]}")
|
| 93 |
+
|
| 94 |
+
# Create DataLoaders
|
| 95 |
+
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=8, shuffle=True)
|
| 96 |
+
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=8, shuffle=False)
|
| 97 |
+
|
| 98 |
+
# Print an example batch
|
| 99 |
+
for batch in train_loader:
|
| 100 |
+
print(f"Batch input ids shape: {batch['input_ids'].shape}")
|
| 101 |
+
print(f"Batch attention mask shape: {batch['attention_mask'].shape}")
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
# Print an example batch
|
| 105 |
+
for batch in train_loader:
|
| 106 |
+
print(f"Batch input ids shape: {batch['input_ids'].shape}")
|
| 107 |
+
print(f"Batch attention mask shape: {batch['attention_mask'].shape}")
|
| 108 |
+
break
|
| 109 |
+
|
| 110 |
+
# Define model
|
| 111 |
+
class Head(nn.Module):
|
| 112 |
+
""" One head of self-attention """
|
| 113 |
+
def __init__(self, head_size, n_embd, block_size, dropout):
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.key = nn.Linear(n_embd, head_size, bias=False)
|
| 116 |
+
self.query = nn.Linear(n_embd, head_size, bias=False)
|
| 117 |
+
self.value = nn.Linear(n_embd, head_size, bias=False)
|
| 118 |
+
self.register_buffer("tril", torch.tril(torch.ones(block_size, block_size)))
|
| 119 |
+
|
| 120 |
+
self.dropout = nn.Dropout(dropout)
|
| 121 |
+
|
| 122 |
+
def forward(self, x):
|
| 123 |
+
B, T, C = x.shape
|
| 124 |
+
k = self.key(x)
|
| 125 |
+
q = self.query(x)
|
| 126 |
+
v = self.value(x)
|
| 127 |
+
|
| 128 |
+
assert C == self.key.in_features, f"Input size {C} doesn't match expected size {self.key.in_features}"
|
| 129 |
+
|
| 130 |
+
wei = q @ k.transpose(-2, -1) * k.shape[-1]**-0.5
|
| 131 |
+
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
|
| 132 |
+
wei = F.softmax(wei, dim=-1)
|
| 133 |
+
wei = self.dropout(wei)
|
| 134 |
+
|
| 135 |
+
out = wei @ v
|
| 136 |
+
return out
|
| 137 |
+
|
| 138 |
+
class MultiHeadAttention(nn.Module):
|
| 139 |
+
""" Multiple heads of self-attention in parallel """
|
| 140 |
+
|
| 141 |
+
def __init__(self, n_heads, head_size, n_embd, dropout):
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.heads = nn.ModuleList([Head(head_size, n_embd, block_size, dropout) for _ in range(n_heads)])
|
| 144 |
+
self.proj = nn.Linear(n_heads * head_size, n_embd)
|
| 145 |
+
self.dropout = nn.Dropout(dropout)
|
| 146 |
+
|
| 147 |
+
def forward(self, x):
|
| 148 |
+
# Collects the outputs from each head
|
| 149 |
+
head_outputs = [head(x) for head in self.heads]
|
| 150 |
+
# Concatenate the outputs
|
| 151 |
+
concatenated = torch.cat(head_outputs, dim=-1)
|
| 152 |
+
# Apply linear transformation and dropout
|
| 153 |
+
out = self.proj(concatenated)
|
| 154 |
+
out = self.dropout(out)
|
| 155 |
+
return out
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class FeedForward(nn.Module):
|
| 159 |
+
""" A simple linear layer followed by non-linearity """
|
| 160 |
+
|
| 161 |
+
def __init__(self, n_embd, dropout=0.1, expansion_factor=4):
|
| 162 |
+
super().__init__()
|
| 163 |
+
self.net = nn.Sequential(
|
| 164 |
+
nn.Linear(n_embd, expansion_factor * n_embd),
|
| 165 |
+
nn.ReLU(),
|
| 166 |
+
nn.Linear(expansion_factor * n_embd, n_embd),
|
| 167 |
+
nn.Dropout(dropout),
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def forward(self, x):
|
| 171 |
+
return self.net(x)
|
| 172 |
+
|
| 173 |
+
class Block(nn.Module):
|
| 174 |
+
""" Transformer block: communication followed by computation """
|
| 175 |
+
|
| 176 |
+
def __init__(self, n_embd, n_head, dropout=0.1):
|
| 177 |
+
# n_embed: embedding dimension, n_head: the number of heads we'd like
|
| 178 |
+
super().__init__()
|
| 179 |
+
head_size = n_embd // n_head
|
| 180 |
+
self.sa = MultiHeadAttention(n_head, head_size, n_embd, dropout)
|
| 181 |
+
self.ffwd = FeedForward(n_embd, dropout)
|
| 182 |
+
self.ln1 = nn.LayerNorm(n_embd)
|
| 183 |
+
self.ln2 = nn.LayerNorm(n_embd)
|
| 184 |
+
|
| 185 |
+
def forward(self, x):
|
| 186 |
+
x = x + self.sa(self.ln1(x))
|
| 187 |
+
x = x + self.ffwd(self.ln2(x))
|
| 188 |
+
return x
|
| 189 |
+
|
| 190 |
+
class GPTLanguageModel(nn.Module):
|
| 191 |
+
def __init__(self, vocab_size, n_embd, block_size, n_layer, n_head, device="cpu"):
|
| 192 |
+
super().__init__()
|
| 193 |
+
self.device = device
|
| 194 |
+
self.block_size = block_size
|
| 195 |
+
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
|
| 196 |
+
self.position_embedding_table = nn.Embedding(block_size, n_embd)
|
| 197 |
+
self.blocks = nn.Sequential(*[Block(n_embd, n_head) for _ in range(n_layer)])
|
| 198 |
+
self.ln_f = nn.LayerNorm(n_embd)
|
| 199 |
+
self.lm_head = nn.Linear(n_embd, vocab_size)
|
| 200 |
+
self.apply(self._init_weights)
|
| 201 |
+
|
| 202 |
+
def _init_weights(self, module):
|
| 203 |
+
if isinstance(module, nn.Linear):
|
| 204 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 205 |
+
if module.bias is not None:
|
| 206 |
+
nn.init.zeros_(module.bias)
|
| 207 |
+
elif isinstance(module, nn.Embedding):
|
| 208 |
+
nn.init.normal_(module.weight, mean=0.1, std=0.02)
|
| 209 |
+
|
| 210 |
+
def forward(self, idx, targets=None):
|
| 211 |
+
B, T = idx.shape
|
| 212 |
+
|
| 213 |
+
# Truncate sequence length to block_size
|
| 214 |
+
T = min(T, self.block_size)
|
| 215 |
+
idx = idx[:, :T]
|
| 216 |
+
|
| 217 |
+
# Get token embeddings for input indices
|
| 218 |
+
tok_emb = self.token_embedding_table(idx) # (B, T, C)
|
| 219 |
+
|
| 220 |
+
# Get position embeddings (truncate to match input length)
|
| 221 |
+
pos_emb = self.position_embedding_table(torch.arange(T, device=idx.device)) # (T, C)
|
| 222 |
+
|
| 223 |
+
# Combine token and position embeddings
|
| 224 |
+
x = tok_emb + pos_emb.unsqueeze(0) # (B, T, C)
|
| 225 |
+
|
| 226 |
+
# Apply transformer blocks
|
| 227 |
+
x = self.blocks(x) # (B, T, C)
|
| 228 |
+
|
| 229 |
+
# Final layer normalization
|
| 230 |
+
x = self.ln_f(x) # (B, T, C)
|
| 231 |
+
|
| 232 |
+
# Get logits for vocabulary prediction
|
| 233 |
+
logits = self.lm_head(x) # (B, T, vocab_size)
|
| 234 |
+
|
| 235 |
+
# Optionally calculate loss if targets are provided
|
| 236 |
+
loss = None
|
| 237 |
+
if targets is not None:
|
| 238 |
+
# Ensure targets are the same size as logits
|
| 239 |
+
targets = targets[:, :T]
|
| 240 |
+
B, T, C = logits.shape
|
| 241 |
+
logits = logits.reshape(B*T, C)
|
| 242 |
+
targets = targets.reshape(B*T)
|
| 243 |
+
loss = F.cross_entropy(logits, targets)
|
| 244 |
+
|
| 245 |
+
return logits, loss
|
| 246 |
+
|
| 247 |
+
@torch.no_grad()
|
| 248 |
+
def generate(self, idx, max_new_tokens):
|
| 249 |
+
for _ in range(max_new_tokens):
|
| 250 |
+
idx_cond = idx[:, -self.block_size:] # Crop to the last block_size tokens
|
| 251 |
+
logits, _ = self(idx_cond) # Get Predictions
|
| 252 |
+
logits = logits[:, -1, :] # Focus on the last time step
|
| 253 |
+
probs = F.softmax(logits, dim=-1) # Get probabilities
|
| 254 |
+
idx_next = torch.multinomial(probs, num_samples=1) # Samples from the distribution
|
| 255 |
+
idx = torch.cat((idx, idx_next), dim=1) # Append sampled index
|
| 256 |
+
return idx
|
| 257 |
+
|
| 258 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
| 259 |
+
print (f"Using device: {device}")
|
| 260 |
+
|
| 261 |
+
# Instantiate the model
|
| 262 |
+
model = GPTLanguageModel(vocab_size, n_embd, block_size, n_layers, n_heads, device=device)
|
| 263 |
+
|
| 264 |
+
# Move the model to the GPU (if available)
|
| 265 |
+
model = model.to(device)
|
| 266 |
+
|
| 267 |
+
# Define criterion and optimizer
|
| 268 |
+
criterion = nn.CrossEntropyLoss()
|
| 269 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
| 270 |
+
|
| 271 |
+
# Training loop with progress reporting
|
| 272 |
+
def batch_gh(model, criterion, optimizer, train_loader, test_loader, epochs):
|
| 273 |
+
train_losses = np.zeros(epochs)
|
| 274 |
+
test_losses = np.zeros(epochs)
|
| 275 |
+
|
| 276 |
+
for it in range(epochs):
|
| 277 |
+
model.train() # Set model to training mode
|
| 278 |
+
t0 = datetime.now()
|
| 279 |
+
train_loss = []
|
| 280 |
+
|
| 281 |
+
for i, batch in enumerate(train_loader):
|
| 282 |
+
inputs = batch["input_ids"].to(device)
|
| 283 |
+
attention_mask = batch["attention_mask"].to(device)
|
| 284 |
+
|
| 285 |
+
# Create targets by shifting inputs by one position
|
| 286 |
+
targets = inputs[:, 1:].contiguous()
|
| 287 |
+
inputs = inputs[:, :-1].contiguous()
|
| 288 |
+
|
| 289 |
+
# Zero parameter gradients
|
| 290 |
+
optimizer.zero_grad()
|
| 291 |
+
|
| 292 |
+
# Forward pass
|
| 293 |
+
outputs, loss = model(inputs, targets)
|
| 294 |
+
|
| 295 |
+
# Backward and optimize
|
| 296 |
+
loss.backward()
|
| 297 |
+
optimizer.step()
|
| 298 |
+
|
| 299 |
+
train_loss.append(loss.item())
|
| 300 |
+
|
| 301 |
+
# Print progress every 100 batches
|
| 302 |
+
if (i + 1) % 100 == 0:
|
| 303 |
+
print(f'Epoch {it + 1}/{epochs}, Batch {i + 1}/{len(train_loader)}, Loss: {loss.item():.4f}')
|
| 304 |
+
|
| 305 |
+
# Get average train_loss
|
| 306 |
+
train_loss = np.mean(train_loss)
|
| 307 |
+
|
| 308 |
+
model.eval() # Set model to evaluation mode
|
| 309 |
+
test_loss = []
|
| 310 |
+
with torch.no_grad():
|
| 311 |
+
for batch in test_loader:
|
| 312 |
+
inputs = batch["input_ids"].to(device)
|
| 313 |
+
attention_mask = batch["attention_mask"].to(device)
|
| 314 |
+
|
| 315 |
+
# Create targets by shifting inputs by one position
|
| 316 |
+
targets = inputs[:, 1:].contiguous()
|
| 317 |
+
inputs = inputs[:, :-1].contiguous()
|
| 318 |
+
|
| 319 |
+
outputs, loss = model(inputs, targets)
|
| 320 |
+
test_loss.append(loss.item())
|
| 321 |
+
|
| 322 |
+
test_loss = np.mean(test_loss)
|
| 323 |
+
|
| 324 |
+
# Save losses
|
| 325 |
+
train_losses[it] = train_loss
|
| 326 |
+
test_losses[it] = test_loss
|
| 327 |
+
|
| 328 |
+
dt = datetime.now() - t0
|
| 329 |
+
print(f'Epoch {it + 1}/{epochs}, Train Loss: {train_loss:.4f}, '
|
| 330 |
+
f'Test Loss: {test_loss:.4f}, Duration: {dt}')
|
| 331 |
+
|
| 332 |
+
return train_losses, test_losses
|
| 333 |
+
|
| 334 |
+
# Run the training
|
| 335 |
+
train_losses, test_losses = batch_gh(model, criterion, optimizer, train_loader, test_loader, epochs=2)
|
| 336 |
+
|
| 337 |
+
# Plot loss
|
| 338 |
+
plt.plot(train_losses, label="train_loss")
|
| 339 |
+
plt.plot(test_losses, label="test_loss")
|
| 340 |
+
plt.legend()
|
| 341 |
+
plt.show()
|
| 342 |
+
|
| 343 |
+
# Save model weights
|
| 344 |
+
model_save_path = "/home/adrian/Documents/StoryCrafterLLM/model_weights.pth"
|
| 345 |
+
torch.save(model.state_dict(), model_save_path)
|
| 346 |
+
print(f"Model saved to {model_save_path}")
|