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