# Get the fine-tuning data.
import urllib.request
import zipfile
import os
from pathlib import Path
url = "https://archive.ics.uci.edu/static/public/228/sms+spam+collection.zip"
zip_path = "sms_spam_collection.zip"
extracted_path = "sms_spam_collection"
data_file_path = Path(extracted_path) / "SMSSpamCollection.tsv"
def download_and_unzip_spam_data(
url, zip_path, extracted_path, data_file_path):
if data_file_path.exists():
print(f"{data_file_path} already exists. Skipping download "
"and extraction."
)
return
with urllib.request.urlopen(url) as response:
with open(zip_path, "wb") as out_file:
out_file.write(response.read())
with zipfile.ZipFile(zip_path, "r") as zip_ref:
zip_ref.extractall(extracted_path)
original_file_path = Path(extracted_path) / "SMSSpamCollection"
os.rename(original_file_path, data_file_path)
print(f"File downloaded and saved as {data_file_path}")
download_and_unzip_spam_data(url, zip_path, extracted_path, data_file_path)
sms_spam_collection\SMSSpamCollection.tsv already exists. Skipping download and extraction.
# Open the data.
import pandas as pd
df = pd.read_csv("sms_spam_collection/SMSSpamCollection.tsv", sep="\t", header=None, names=["Label", "Text"])
df
| Label | Text | |
|---|---|---|
| 0 | ham | Go until jurong point, crazy.. Available only ... |
| 1 | ham | Ok lar... Joking wif u oni... |
| 2 | spam | Free entry in 2 a wkly comp to win FA Cup fina... |
| 3 | ham | U dun say so early hor... U c already then say... |
| 4 | ham | Nah I don't think he goes to usf, he lives aro... |
| ... | ... | ... |
| 5567 | spam | This is the 2nd time we have tried 2 contact u... |
| 5568 | ham | Will ü b going to esplanade fr home? |
| 5569 | ham | Pity, * was in mood for that. So...any other s... |
| 5570 | ham | The guy did some bitching but I acted like i'd... |
| 5571 | ham | Rofl. Its true to its name |
5572 rows × 2 columns
# Examine label distributions.
df["Label"].value_counts()
Label ham 4825 spam 747 Name: count, dtype: int64
# Create a balanced data set: equal quantities of ham and spam.
def create_balanced_dataset(df):
spam = df[df["Label"] == "spam"]
num_spam = spam.shape[0]
rand_ham = df[df["Label"] == "ham"].sample(num_spam, random_state=123)
result = pd.concat((rand_ham, spam))
return result
balanced_df = create_balanced_dataset(df)
print(balanced_df["Label"].value_counts())
balanced_df.head()
Label ham 747 spam 747 Name: count, dtype: int64
| Label | Text | |
|---|---|---|
| 4307 | ham | Awww dat is sweet! We can think of something t... |
| 4138 | ham | Just got to <#> |
| 4831 | ham | The word "Checkmate" in chess comes from the P... |
| 4461 | ham | This is wishing you a great day. Moji told me ... |
| 5440 | ham | Thank you. do you generally date the brothas? |
# Convert label "ham" to 0 and "spam" to 1.
balanced_df["Label"] = balanced_df["Label"].map({"ham" : 0, "spam" : 1})
print(balanced_df["Label"].value_counts())
Label 0 747 1 747 Name: count, dtype: int64
# Split the data into train, validation, and test sets. Returns three
# data frames. Test fraction is inferred from train fraction and validation
# fraction.
def random_split(df_in, train_frac, validation_frac):
assert train_frac + validation_frac <= 1.0
assert train_frac > 0 and validation_frac > 0
train_threshold = int(train_frac * df_in.shape[0])
validation_threshold = int(validation_frac * df_in.shape[0]) + train_threshold
df_shuffle = df_in.sample(frac=1, random_state=123).reset_index(drop=True)
df_train = df_shuffle[:train_threshold]
df_val = df_shuffle[train_threshold:validation_threshold]
df_test = df_shuffle[validation_threshold:]
return df_train, df_val, df_test
train_df, validation_df, test_df = random_split(balanced_df, 0.7, 0.1)
# Verify we got the proportions we expected.
print(f"Train:\t\t{train_df.shape[0]}\t{train_df.shape[0] / balanced_df.shape[0]*100:.0f}%")
print(f"Validation:\t{validation_df.shape[0]}\t{validation_df.shape[0] / balanced_df.shape[0]*100:.0f}%")
print(f"Test:\t\t{test_df.shape[0]}\t{test_df.shape[0] / balanced_df.shape[0]*100:.0f}%")
total_training_data = train_df.shape[0] + validation_df.shape[0] + test_df.shape[0]
print(f"Total records:\t{total_training_data}")
assert total_training_data == balanced_df.shape[0]
Train: 1045 70% Validation: 149 10% Test: 300 20% Total records: 1494
# Save to CSV files.
train_df.to_csv("train.csv", index=None)
validation_df.to_csv("validation.csv", index=None)
test_df.to_csv("test.csv", index=None)
# We will pad text in our samples to be equal length so we can efficiently
# process them in batch with our simple sliding window technique. We will
# pad with the `<|endoftext|>` token. Let's identify it.
import tiktoken
tokenizer = tiktoken.get_encoding("gpt2")
tokenizer.encode("<|endoftext|>", allowed_special={'<|endoftext|>'})
[50256]
# Create a spam dataset which will return data padded out
# to the provided max length (or the maximum encountered in the
# data), using the provided csv file, tokenizer, and padding token.
# I am, at heart, a systems code guy.
#
# My general approach for anything
# in Python where I have a hint that performance might matter is: get
# it into NumPy/PyTorch as quickly as possible and just work with the memory
# there. So that's what this code does. It uses pandas to open the csv, stores
# the number of samples, and pulls the labels into a tensor. Then it builds
# a list-of-a-list-of-tokens for the text data. From this we can figure
# out the length of the longest token sequence, and use that as our max length
# (unless that was specified at input). We can then build a 2d tensor that is big
# enough to hold the maximum token length for each sample, and we initialize it
# with our padding token. Finally, we copy over the tokens from our token list.
import torch
from torch.utils.data import Dataset
class SpamDataset(Dataset):
def __init__(self, csv_file, tokenizer, max_length=None,
pad_token_id=50256):
csv = pd.read_csv(csv_file)
self.num_samples = csv.shape[0]
self.labels = torch.tensor(csv["Label"])
tokens_list = [tokenizer.encode(text) for text in csv["Text"]]
if max_length is None:
max_length = max(len(tokens) for tokens in tokens_list)
self.max_length = max_length
self.tokens = torch.full((self.num_samples, max_length), pad_token_id)
for i, tokens in enumerate(tokens_list):
num_tokens = min(max_length, len(tokens))
self.tokens[i, :num_tokens] = torch.tensor(tokens[:num_tokens])
# Coming from C one might wonder: why not just do self.tokens[i][:num_tokens]? The
# reason is because this does not represent naive pointer arithmetic — which is obvious
# when you think about it for two seconds. Each [] represents a hand-off between Python
# and PyTorch. As a general principle, it's better to hand PyTorch everything it needs in
# one fell swoop to give it the best chance at getting the finished answer with minimal
# work. Hence self.tokens[i, :num_tokens] is the better default choice.
return
def __getitem__(self, index):
return self.tokens[index], self.labels[index]
def __len__(self):
return self.num_samples
train_dataset = SpamDataset(
csv_file="train.csv",
max_length=None,
tokenizer=tokenizer
)
print(train_dataset.max_length)
120
val_dataset = SpamDataset(
csv_file="validation.csv",
max_length=train_dataset.max_length,
tokenizer=tokenizer
)
test_dataset = SpamDataset(
csv_file="test.csv",
max_length=train_dataset.max_length,
tokenizer=tokenizer
)
# Create training, validation, and test data loaders. The training loader will
# shuffle and drop the last incomplete batch, the validation and test loaders
# won't.
from torch.utils.data import DataLoader
num_workers = 0 # Increase this at your peril, not stable in all environments.
batch_size = 8
torch.manual_seed(123)
train_loader = DataLoader(
dataset=train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
drop_last=True
)
val_loader = DataLoader(
dataset=val_dataset,
batch_size=batch_size,
num_workers=num_workers
)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=batch_size,
num_workers=num_workers
)
# Verify correct data loader behavior by iterating over the training data loader
# and printing the dimensions of the last batch.
for tokens_batch, targets_batch in train_loader:
pass
print("Tokens batch shape:", tokens_batch.shape)
print("Targets batch shape:", targets_batch.shape)
# Expected output: torch.Size([8, 120]), torch.Size([8])
Tokens batch shape: torch.Size([8, 120]) Targets batch shape: torch.Size([8])
# Print the total number of batches in each dataset.
print("Training batches:", len(train_loader))
print("Validation batches:", len(val_loader))
print("Test batches:", len(test_loader))
# Expected output: 130, 19, 38
Training batches: 130 Validation batches: 19 Test batches: 38
# Model config info.
CHOOSE_MODEL = "gpt2-small (124M)"
INPUT_PROMPT = "Every effort moves"
BASE_CONFIG = {
"vocab_size": 50257,
"context_length": 1024,
"drop_rate": 0.0,
"qkv_bias": True
}
model_configs = {
"gpt2-small (124M)": {"emb_dim": 768, "n_layers": 12, "n_heads": 12},
"gpt2-medium (355M)": {"emb_dim": 1024, "n_layers": 24, "n_heads": 16},
"gpt2-large (774M)": {"emb_dim": 1280, "n_layers": 36, "n_heads": 20},
"gpt2-xl (1558M)": {"emb_dim": 1600, "n_layers": 48, "n_heads": 25},
}
BASE_CONFIG.update(model_configs[CHOOSE_MODEL])
from gpt_download import download_and_load_gpt2
model_size = CHOOSE_MODEL.split(" ")[-1].lstrip("(").rstrip(")")
settings, params = download_and_load_gpt2(
model_size=model_size, models_dir="gpt2"
)
File already exists and is up-to-date: gpt2\124M\checkpoint File already exists and is up-to-date: gpt2\124M\encoder.json File already exists and is up-to-date: gpt2\124M\hparams.json File already exists and is up-to-date: gpt2\124M\model.ckpt.data-00000-of-00001 File already exists and is up-to-date: gpt2\124M\model.ckpt.index File already exists and is up-to-date: gpt2\124M\model.ckpt.meta File already exists and is up-to-date: gpt2\124M\vocab.bpe
from llm_from_scratch import GPTModel, load_weights_into_gpt
model = GPTModel(BASE_CONFIG)
load_weights_into_gpt(model, params)
model.eval()
print("Total parameters", sum(p.numel() for p in model.parameters()))
Total parameters 163037184
# Test out the model.
from llm_from_scratch import generate_text_simple
from llm_from_scratch import text_to_token_ids, token_ids_to_text
text_1 = "Every effort moves you"
token_ids = generate_text_simple(
model=model,
tokens=text_to_token_ids(text_1, tokenizer),
max_output_tokens=15,
max_context_length=BASE_CONFIG["context_length"]
)
print(token_ids_to_text(token_ids, tokenizer))
# Expected output:
# Every effort moves you forward.
# The first step is to understand the importance of your work
Every effort moves you forward. The first step is to understand the importance of your work
# See if it already works for spam classification.
text_2 = (
"Is the following text 'spam'? Answer with 'yes' or 'no':"
" 'You are a winner you have been specially"
" selected to receive $1000 cash or a $2000 award.'"
)
token_ids = generate_text_simple(
model=model,
tokens=text_to_token_ids(text_2, tokenizer),
max_output_tokens=23,
max_context_length=BASE_CONFIG["context_length"]
)
print(token_ids_to_text(token_ids, tokenizer))
# Expected output (spoiler: it can't classify spam)
# Is the following text 'spam'? Answer with 'yes' or 'no': 'You are a winner
# you have been specially selected to receive $1000 cash
# or a $2000 award.'
# The following text 'spam'? Answer with 'yes' or 'no': 'You are a winner
Is the following text 'spam'? Answer with 'yes' or 'no': 'You are a winner you have been specially selected to receive $1000 cash or a $2000 award.' The following text 'spam'? Answer with 'yes' or 'no': 'You are a winner
# Explore the model architecture.
model
GPTModel(
(tok_emb): Embedding(50257, 768)
(pos_emb): Embedding(1024, 768)
(dropout): Dropout(p=0.0, inplace=False)
(xform_blocks): Sequential(
(0): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(1): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(2): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(3): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(4): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(5): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(6): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(7): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(8): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(9): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(10): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
(11): TransformerBlock(
(attention): MultiHeadAttention(
(W_q): Linear(in_features=768, out_features=768, bias=True)
(W_k): Linear(in_features=768, out_features=768, bias=True)
(W_v): Linear(in_features=768, out_features=768, bias=True)
(output_proj): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(feed_forward): FeedForward(
(layers): Sequential(
(0): Linear(in_features=768, out_features=3072, bias=True)
(1): GELU()
(2): Linear(in_features=3072, out_features=768, bias=True)
)
)
(norm1): LayerNorm()
(norm2): LayerNorm()
(dropout): Dropout(p=0.0, inplace=False)
)
)
(final_norm): LayerNorm()
(out_head): Linear(in_features=768, out_features=50257, bias=False)
)
# Prepare for fine tuning.
import torch.nn as nn
# "Freeze" the weights by disabling gradient tracking for all parameters.
for param in model.parameters():
param.requires_grad_(False)
# Replace the final layer — the output head — with almost the exact same thing, except that
# its output dimension is 2, which is equal to the number of classes ("ham" and "spam"). We
# also use a bias term.
torch.manual_seed(123)
num_classes = 2
model.out_head = nn.Linear(BASE_CONFIG["emb_dim"], num_classes, bias = True)
# The new output layer will be trainable. Also make the last layer norm and transformer block
# trainable, since this has been empirically demonstrated to improve performance.
for param in model.final_norm.parameters():
param.requires_grad_(True)
for param in model.xform_blocks[-1].parameters():
param.requires_grad_(True)
# Create input tokens saying "Do you have time" to verify the model still works even though
# it's "frozen."
input_tokens = text_to_token_ids("Do you have time", tokenizer)
print("Inputs:", input_tokens)
print("Input dimensions:", input_tokens.shape)
Inputs: tensor([[5211, 345, 423, 640]]) Input dimensions: torch.Size([1, 4])
# Pass the tokens to the model without gradient tracking and see the results.
with torch.no_grad():
output_tokens = model(input_tokens)
print("Outputs:\n", output_tokens)
print("Outputs dimensions:", output_tokens.shape)
Outputs:
tensor([[[-1.5854, 0.9904],
[-3.7235, 7.4548],
[-2.2661, 6.6049],
[-3.5983, 3.9902]]])
Outputs dimensions: torch.Size([1, 4, 2])
# We will focus on the last output token of the tensor, since this corresponds
# to the last *input* token, which is the *only* token which pays attention to
# all other tokens. It will therefore have the most information about whether
# our message was ham or spam.
# Go from [batch_size, num_tokens, embed_dim] to [batch_size, embed_dim],
# only retaining the last token from each batch.
print("Last output token", output_tokens[:, -1, :])
Last output token tensor([[-3.5983, 3.9902]])
# Implement model evaluation functions. It's the same basic idea we're already using,
# just with an output dimension of 2 instead of ~50k.
# Explore this with the last token output logits already obtained.
probas = torch.softmax(output_tokens[:, -1, :], dim=-1)
label = torch.argmax(probas)
print("Class label:", label.item())
# Expected result: 1
Class label: 1
# Note that softmax() isn't necessary because we are essentially greedy sampling.
label = torch.argmax(output_tokens[:, -1, :], dim=-1)
print("Class label:", label.item())
Class label: 1
# Our actual function will be very much like `get_loader_loss()` from chapter 5,
# lightly modified to implement the previous logic and with the batch loss calculation
# inlined rather than broken out into a separate function call.
def calc_accuracy_loader(loader, model, device, num_batches=None):
model.eval()
if len(loader) == 0:
return float('nan')
if num_batches is None:
num_batches = len(loader)
else:
num_batches = min(num_batches, len(loader))
total_correct = 0
total_samples = 0
data_iter = iter(loader)
for _ in range(num_batches):
input_batch, target_batch = next(data_iter)
input_batch = input_batch.to(device)
target_batch = target_batch.to(device)
with torch.no_grad():
logits = model(input_batch)
last_logits = logits[:, -1, :].squeeze(0)
predictions = torch.argmax(last_logits, dim=-1)
correct = (predictions == target_batch).sum().item()
total_correct += correct
total_samples += input_batch.shape[0]
pct_correct = total_correct / total_samples
return pct_correct
# Test it out directly with Raschka's code. We use the cpu so we can precisely compare our
# outcomes against his.
device = "cpu"
model.to(device)
torch.manual_seed(123)
train_accuracy = calc_accuracy_loader(
train_loader, model, device, num_batches=10
)
val_accuracy = calc_accuracy_loader(
val_loader, model, device, num_batches=10
)
test_accuracy = calc_accuracy_loader(
test_loader, model, device, num_batches=10
)
print(f"Training accuracy: {train_accuracy*100:.2f}%")
print(f"Validation accuracy: {val_accuracy*100:.2f}%")
print(f"Test accuracy: {test_accuracy*100:.2f}%")
Training accuracy: 46.25% Validation accuracy: 45.00% Test accuracy: 48.75%
# Our loss function is nearly unmodified, just focusing on the last token's logits.
# We continue to use cross entropy loss — classification accuracy is not itself nicely
# differentiable, so we stick with good ol' CEL.
def calc_loss_batch(input_batch, target_batch, model, device):
# Note that these are not in-place operations!
input_batch = input_batch.to(device)
target_batch = target_batch.to(device)
logits = model(input_batch)
last_logits = logits[:, -1, :]
loss = torch.nn.functional.cross_entropy(last_logits, target_batch)
return loss
# Our loader loss calculation is essentially unmodified from chapter 5.
def calc_loss_loader(loader, model, device, num_batches=None):
if len(loader) == 0:
return float('nan')
if num_batches is None:
num_batches = len(loader)
else:
num_batches = min(num_batches, len(loader))
total_loss = 0
data_iter = iter(loader)
for _ in range(num_batches):
input_batch, target_batch = next(data_iter)
loss = calc_loss_batch(input_batch, target_batch, model, device)
total_loss += loss.item() # Don't accumulate a tensor (and maybe an autograd graph), just a scalar.
avg_loss = total_loss / num_batches
return avg_loss
# Use Raschka's evaluation code.
with torch.no_grad():
train_loss = calc_loss_loader(
train_loader, model, device, num_batches=5
)
val_loss = calc_loss_loader(val_loader, model, device, num_batches=5)
test_loss = calc_loss_loader(test_loader, model, device, num_batches=5)
print(f"Training loss: {train_loss:.3f}")
print(f"Validation loss: {val_loss:.3f}")
print(f"Test loss: {test_loss:.3f}")
Training loss: 2.453 Validation loss: 2.583 Test loss: 2.322
# We'll use the same model evaluation function from chapter 5.
def evaluate_model(model, train_loader, val_loader, device, eval_iter):
model.eval()
with torch.no_grad():
train_loss = calc_loss_loader(train_loader, model, device, eval_iter)
val_loss = calc_loss_loader(val_loader, model, device, eval_iter)
model.train()
return train_loss, val_loss
# Training loop is same as `train_model_simple` from chapter 5, it just tracks examples seen
# instead of tokens seen and reports accuracy instead of printing tokens.
def train_classifier_simple(model, train_loader, val_loader, optimizer, device, num_epochs, eval_freq, eval_iter):
train_losses, val_losses, train_accs, val_accs, examples_seen = [], [], [], [], []
current_step = -1
num_examples_seen = 0
for epoch in range(num_epochs):
current_epoch = epoch + 1
model.train()
for input_batch, target_batch in train_loader:
optimizer.zero_grad()
loss = calc_loss_batch(input_batch, target_batch, model, device)
loss.backward()
optimizer.step()
current_step += 1
num_examples_seen += input_batch.shape[0]
if current_step % eval_freq == 0:
train_loss, val_loss = evaluate_model(model, train_loader, val_loader, device, eval_iter)
train_losses.append(train_loss)
val_losses.append(val_loss)
examples_seen.append(num_examples_seen)
print(f"Epoch {current_epoch:03}, Step {current_step:05}\n\tTraining loss: {train_loss:.3f}\n\tValidation loss: {val_loss:.3f}\t")
# Print accuracy once per epoch
print()
train_acc = calc_accuracy_loader(train_loader, model, device, num_batches=eval_iter)
val_acc = calc_accuracy_loader(val_loader, model, device, num_batches=eval_iter)
print(f"Training accuracy: {train_acc*100:.2f}% | Validation accuracy: {val_acc*100:.2f}%")
print()
train_accs.append(train_acc)
val_accs.append(val_acc)
return train_losses, val_losses, train_accs, val_accs, examples_seen
import time
start_time = time.time()
torch.manual_seed(123)
optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5, weight_decay=0.1)
num_epochs = 5
train_losses, val_losses, train_accs, val_accs, examples_seen = train_classifier_simple(
model, train_loader, val_loader, optimizer,
device, num_epochs, eval_freq=50, eval_iter=5
)
end_time = time.time()
execution_time_in_minutes = (end_time - start_time) / 60
print(f"Training completed in {execution_time_in_minutes:.2f} minutes.")
Epoch 001, Step 00000 Training loss: 2.153 Validation loss: 2.392 Epoch 001, Step 00050 Training loss: 0.617 Validation loss: 0.637 Epoch 001, Step 00100 Training loss: 0.523 Validation loss: 0.557 Training accuracy: 70.00% | Validation accuracy: 72.50% Epoch 002, Step 00150 Training loss: 0.561 Validation loss: 0.489 Epoch 002, Step 00200 Training loss: 0.419 Validation loss: 0.397 Epoch 002, Step 00250 Training loss: 0.409 Validation loss: 0.353 Training accuracy: 82.50% | Validation accuracy: 85.00% Epoch 003, Step 00300 Training loss: 0.333 Validation loss: 0.320 Epoch 003, Step 00350 Training loss: 0.340 Validation loss: 0.306 Training accuracy: 90.00% | Validation accuracy: 90.00% Epoch 004, Step 00400 Training loss: 0.136 Validation loss: 0.200 Epoch 004, Step 00450 Training loss: 0.153 Validation loss: 0.132 Epoch 004, Step 00500 Training loss: 0.222 Validation loss: 0.137 Training accuracy: 100.00% | Validation accuracy: 97.50% Epoch 005, Step 00550 Training loss: 0.207 Validation loss: 0.143 Epoch 005, Step 00600 Training loss: 0.083 Validation loss: 0.074 Training accuracy: 100.00% | Validation accuracy: 97.50% Training completed in 6.76 minutes.
# Then plot training and validation loss vs epochs (lower x axis)
# and examples seen (upper x axis)
import matplotlib.pyplot as plt
def plot_values(epochs_seen, examples_seen, train_values, val_values, label="Loss"):
# This ratio is used to convert between expochs and examples.
ratio = (examples_seen[-1]/epochs_seen[-1]).item()
_, ax = plt.subplots()
ax.set_xlabel("Epochs seen")
ax.set_ylabel(label)
topx = ax.secondary_xaxis("top", (lambda x: x*ratio, lambda x: x/ratio))
topx.set_xlabel("Examples seen")
ax.plot(epochs_seen, train_values, label="Train")
ax.plot(epochs_seen, val_values, label="Validation", ls="--")
ax.legend()
plt.show()
return
num_steps = len(train_losses)
epochs_tensor = torch.linspace(0, num_epochs, num_steps)
examples_seen_tensor = torch.linspace(0, examples_seen[-1], num_steps)
plot_values(epochs_tensor, examples_seen_tensor, train_losses, val_losses)
# Now plot accuracies.
epochs_tensor = torch.linspace(0, num_epochs, len(train_accs))
examples_seen_tensor = torch.linspace(0, examples_seen[-1], len(train_accs))
plot_values(
epochs_tensor, examples_seen_tensor, train_accs, val_accs,
label="Accuracy"
)
# Now calculate the entire accuracy for the training, validation, and test data loaders
# and report.
torch.manual_seed(123)
train_accuracy = calc_accuracy_loader(train_loader, model, device)
val_accuracy = calc_accuracy_loader(val_loader, model, device)
test_accuracy = calc_accuracy_loader(test_loader, model, device)
print(f"Training accuracy: {train_accuracy*100:.2f}%")
print(f"Validation accuracy: {val_accuracy*100:.2f}%")
print(f"Test accuracy: {test_accuracy*100:.2f}%")
Training accuracy: 97.21% Validation accuracy: 97.32% Test accuracy: 95.67%
Exercise 6.1 Increasing the context length¶
Pad the inputs to the maximum number of tokens the model supports and observe how it affects the predictive performance.
# We'll need to train and evaluate a new model on newly defined datasets &
# dataloaders. If we re-use the model as-is and just change the data, we'll see
# horrible results because we'll have almost 10x'd the amount of data the model is
# seeing vs. what it was trained to see. Also if we continue training on our already
# trained model we won't make an apples-to-apples comparison and will see misleadingly
# high accuracy.
max_pad_train_dataset = SpamDataset(
csv_file="train.csv",
max_length=1024, # The context length of gpt2 small
tokenizer=tokenizer
)
max_pad_val_dataset = SpamDataset(
csv_file="validation.csv",
max_length=1024, # The context length of gpt2 small
tokenizer=tokenizer
)
max_pad_test_dataset = SpamDataset(
csv_file="test.csv",
max_length=1024, # The context length of gpt2 small
tokenizer=tokenizer
)
max_pad_train_loader = DataLoader(
dataset=max_pad_train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
drop_last=True
)
max_pad_val_loader = DataLoader(
dataset=max_pad_val_dataset,
batch_size=batch_size,
num_workers=num_workers
)
max_pad_test_loader = DataLoader(
dataset=max_pad_test_dataset,
batch_size=batch_size,
num_workers=num_workers
)
# We don't have a complete list of results to match for correctness
# so let's take advantage of the GPU and make this go a lot faster.
cuda_device = "cuda" if torch.cuda.is_available() else "cpu"
max_pad_model = GPTModel(BASE_CONFIG)
load_weights_into_gpt(max_pad_model, params)
# "Freeze" the weights.
for param in max_pad_model.parameters():
param.requires_grad_(False)
# Replace the final layer and make last layer norm and transformer block trainable.
max_pad_model.out_head = nn.Linear(BASE_CONFIG["emb_dim"], num_classes, bias = True)
for param in max_pad_model.final_norm.parameters():
param.requires_grad_(True)
for param in max_pad_model.xform_blocks[-1].parameters():
param.requires_grad_(True)
max_pad_model.to(cuda_device) # Recommended to move to GPU before creating optimizer.
max_pad_optimizer = torch.optim.AdamW(max_pad_model.parameters(), lr=5e-5, weight_decay=0.1)
num_epochs = 5
torch.manual_seed(123)
start_time = time.time()
train_losses, val_losses, train_accs, val_accs, examples_seen = train_classifier_simple(
max_pad_model, max_pad_train_loader, max_pad_val_loader, max_pad_optimizer,
cuda_device, num_epochs, eval_freq=50, eval_iter=5
)
end_time = time.time()
execution_time_in_minutes = (end_time - start_time) / 60
print(f"Training completed in {execution_time_in_minutes:.2f} minutes.")
train_accuracy = calc_accuracy_loader(max_pad_train_loader, max_pad_model, cuda_device)
val_accuracy = calc_accuracy_loader(max_pad_val_loader, max_pad_model, cuda_device)
test_accuracy = calc_accuracy_loader(max_pad_test_loader, max_pad_model, cuda_device)
print(f"Training accuracy: {train_accuracy*100:.2f}%")
print(f"Validation accuracy: {val_accuracy*100:.2f}%")
print(f"Test accuracy: {test_accuracy*100:.2f}%")
Epoch 001, Step 00000 Training loss: 0.878 Validation loss: 0.825 Epoch 001, Step 00050 Training loss: 0.648 Validation loss: 0.662 Epoch 001, Step 00100 Training loss: 0.458 Validation loss: 0.551 Training accuracy: 85.00% | Validation accuracy: 82.50% Epoch 002, Step 00150 Training loss: 0.396 Validation loss: 0.383 Epoch 002, Step 00200 Training loss: 0.225 Validation loss: 0.293 Epoch 002, Step 00250 Training loss: 0.196 Validation loss: 0.351 Training accuracy: 90.00% | Validation accuracy: 87.50% Epoch 003, Step 00300 Training loss: 0.333 Validation loss: 0.287 Epoch 003, Step 00350 Training loss: 0.285 Validation loss: 0.499 Training accuracy: 97.50% | Validation accuracy: 90.00% Epoch 004, Step 00400 Training loss: 0.173 Validation loss: 0.281 Epoch 004, Step 00450 Training loss: 0.190 Validation loss: 0.260 Epoch 004, Step 00500 Training loss: 0.090 Validation loss: 0.288 Training accuracy: 92.50% | Validation accuracy: 90.00% Epoch 005, Step 00550 Training loss: 0.106 Validation loss: 0.287 Epoch 005, Step 00600 Training loss: 0.176 Validation loss: 0.275 Training accuracy: 100.00% | Validation accuracy: 87.50% Training completed in 6.68 minutes. Training accuracy: 95.87% Validation accuracy: 95.30% Test accuracy: 94.67%
We can see that worse results are obtained. Intuitively, that's because the signal has been "diluted" with a ton of padding tokens that add zero information. Moving to the GPU and achieving roughly the same execution time also suggests that, apples-to-apples, it takes much longer to train. So: not a good strategy.
# Here we evict the padded model and optimizer to free up VRAM.
import gc
del max_pad_model, max_pad_optimizer
gc.collect()
torch.cuda.empty_cache()
Exercise 6.2 Fine-tuning the whole model¶
Instead of fine-tuning just the final transformer block, fine-tune the entire model and assess the effect on predictive performance.
# For this we will once again create another model, but structured much
# like our original model and without any freezing whatsoever.
full_model = GPTModel(BASE_CONFIG)
load_weights_into_gpt(full_model, params)
# Replace the final layer.
full_model.out_head = nn.Linear(BASE_CONFIG["emb_dim"], num_classes, bias = True)
full_model.to(cuda_device) # Recommended to move to GPU before creating optimizer.
full_optimizer = torch.optim.AdamW(full_model.parameters(), lr=5e-5, weight_decay=0.1)
num_epochs = 5
torch.manual_seed(123)
start_time = time.time()
train_losses, val_losses, train_accs, val_accs, examples_seen = train_classifier_simple(
full_model, train_loader, val_loader, full_optimizer,
cuda_device, num_epochs, eval_freq=50, eval_iter=5
)
end_time = time.time()
execution_time_in_minutes = (end_time - start_time) / 60
print(f"Training completed in {execution_time_in_minutes:.2f} minutes.")
train_accuracy = calc_accuracy_loader(train_loader, full_model, cuda_device)
val_accuracy = calc_accuracy_loader(val_loader, full_model, cuda_device)
test_accuracy = calc_accuracy_loader(test_loader, full_model, cuda_device)
print(f"Training accuracy: {train_accuracy*100:.2f}%")
print(f"Validation accuracy: {val_accuracy*100:.2f}%")
print(f"Test accuracy: {test_accuracy*100:.2f}%")
Epoch 001, Step 00000 Training loss: 2.163 Validation loss: 2.495 Epoch 001, Step 00050 Training loss: 0.139 Validation loss: 0.149 Epoch 001, Step 00100 Training loss: 0.031 Validation loss: 0.082 Training accuracy: 100.00% | Validation accuracy: 100.00% Epoch 002, Step 00150 Training loss: 0.041 Validation loss: 0.098 Epoch 002, Step 00200 Training loss: 0.022 Validation loss: 0.064 Epoch 002, Step 00250 Training loss: 0.008 Validation loss: 0.049 Training accuracy: 97.50% | Validation accuracy: 95.00% Epoch 003, Step 00300 Training loss: 0.053 Validation loss: 0.046 Epoch 003, Step 00350 Training loss: 0.002 Validation loss: 0.008 Training accuracy: 100.00% | Validation accuracy: 100.00% Epoch 004, Step 00400 Training loss: 0.005 Validation loss: 0.012 Epoch 004, Step 00450 Training loss: 0.002 Validation loss: 0.012 Epoch 004, Step 00500 Training loss: 0.001 Validation loss: 0.004 Training accuracy: 100.00% | Validation accuracy: 100.00% Epoch 005, Step 00550 Training loss: 0.000 Validation loss: 0.002 Epoch 005, Step 00600 Training loss: 0.000 Validation loss: 0.003 Training accuracy: 100.00% | Validation accuracy: 100.00% Training completed in 1.70 minutes. Training accuracy: 100.00% Validation accuracy: 98.66% Test accuracy: 98.67%
This training takes longer (the scale of the difference is not so obvious since the original model was trained on CPU while this is trained on GPU), but it does improve accuracy by a few percent. Is this worth it? Probably yes, since training is a one time cost, while increased accuracy is free at runtime.
# Now evict the fully-trained model from VRAM.
del full_model, full_optimizer
gc.collect()
torch.cuda.empty_cache()
# Now put our original classifier model to use.
def classify_review(text, model, tokenizer, device, max_length=None, pad_token_id=50256):
# eval mode
model.eval()
# encode text and get max context length from shape of model's position embeddings weight matrix.
input_tokens = tokenizer.encode(text)
max_context_length = model.pos_emb.weight.shape[0]
if max_length is not None:
max_context_length = min(max_context_length, max_length)
# truncate inputs that are longer than max context length
input_tokens = input_tokens[:max_context_length]
# pad tokens with pad token up to max context length
num_pad_tokens = max_context_length - len(input_tokens)
input_tokens += [pad_token_id] * num_pad_tokens
# create a tensor that wraps the inputs, puts them on the right device, and is unsqueezed to look like a batch
input_tokens_tensor = torch.tensor(input_tokens, device=device).unsqueeze(0)
# turn off torch grad tracking and get logits and predicted label using the usual greedy sampling
with torch.no_grad():
logits = model(input_tokens_tensor)
last_logits = logits[:, -1, :]
predicted_label = torch.argmax(last_logits)
return "spam" if predicted_label == 1 else "not spam"
# Now test the classifier with Raschka's examples. The first is spam, the second not.
text_1 = (
"You are a winner you have been specially"
" selected to receive $1000 cash or a $2000 award."
)
print(classify_review(
text_1, model, tokenizer, device, max_length=train_dataset.max_length
))
text_2 = (
"Hey, just wanted to check if we're still on"
" for dinner tonight? Let me know!"
)
print(classify_review(
text_2, model, tokenizer, device, max_length=train_dataset.max_length
))
spam not spam
# Now save the model.
torch.save(model.state_dict(), "review_classifier.pth")
# And load it.
model_state_dict = torch.load("review_classifier.pth", map_location=device)
model.load_state_dict(model_state_dict)
print("Parameters:", sum(p.numel() for p in model.parameters()))
Parameters: 124441346
Exercise 6.3 Fine-tuning the first vs. last token¶
Try fine-tuning the first output token. Notice the changes in predictive performance compared to fine-tuning the last output token.
# For this we will once again create another model, structured identically to
# our original model. Then we will re-define the batch loss and loader
# accuracy functions — which should get picked up by our current training
# function — to look at the first token's output logits.
def calc_loss_batch(input_batch, target_batch, model, device):
input_batch = input_batch.to(device)
target_batch = target_batch.to(device)
logits = model(input_batch)
# Look at first output logits.
first_logits = logits[:, 0, :]
loss = torch.nn.functional.cross_entropy(first_logits, target_batch)
return loss
def calc_accuracy_loader(loader, model, device, num_batches=None):
model.eval()
if len(loader) == 0:
return float('nan')
if num_batches is None:
num_batches = len(loader)
else:
num_batches = min(num_batches, len(loader))
total_correct = 0
total_samples = 0
data_iter = iter(loader)
for _ in range(num_batches):
input_batch, target_batch = next(data_iter)
input_batch = input_batch.to(device)
target_batch = target_batch.to(device)
with torch.no_grad():
logits = model(input_batch)
# Look at first output logits.
first_logits = logits[:, 0, :].squeeze(0)
predictions = torch.argmax(first_logits, dim=-1)
correct = (predictions == target_batch).sum().item()
total_correct += correct
total_samples += input_batch.shape[0]
pct_correct = total_correct / total_samples
return pct_correct
# Load the model and freeze the weights.
alt_model = GPTModel(BASE_CONFIG)
load_weights_into_gpt(alt_model, params)
for param in alt_model.parameters():
param.requires_grad_(False)
# Replace the final layer and make the last layer norm and transformer block trainable.
torch.manual_seed(123)
num_classes = 2
alt_model.out_head = nn.Linear(BASE_CONFIG["emb_dim"], num_classes, bias = True)
for param in alt_model.final_norm.parameters():
param.requires_grad_(True)
for param in alt_model.xform_blocks[-1].parameters():
param.requires_grad_(True)
# Move to GPU before creating optimizer, then start training and print results.
alt_model.to(cuda_device)
alt_optimizer = torch.optim.AdamW(alt_model.parameters(), lr=5e-5, weight_decay=0.1)
num_epochs = 5
start_time = time.time()
train_losses, val_losses, train_accs, val_accs, examples_seen = train_classifier_simple(
alt_model, train_loader, val_loader, alt_optimizer,
cuda_device, num_epochs, eval_freq=50, eval_iter=5
)
end_time = time.time()
execution_time_in_minutes = (end_time - start_time) / 60
print(f"Training completed in {execution_time_in_minutes:.2f} minutes.")
# Evaluate accuracy and print results.
train_accuracy = calc_accuracy_loader(train_loader, alt_model, cuda_device)
val_accuracy = calc_accuracy_loader(val_loader, alt_model, cuda_device)
test_accuracy = calc_accuracy_loader(test_loader, alt_model, cuda_device)
print(f"Training accuracy: {train_accuracy*100:.2f}%")
print(f"Validation accuracy: {val_accuracy*100:.2f}%")
print(f"Test accuracy: {test_accuracy*100:.2f}%")
# Now evict the alternative model from VRAM.
del alt_model, alt_optimizer
gc.collect()
torch.cuda.empty_cache()
Epoch 001, Step 00000 Training loss: 1.277 Validation loss: 1.353 Epoch 001, Step 00050 Training loss: 0.680 Validation loss: 0.701 Epoch 001, Step 00100 Training loss: 0.651 Validation loss: 0.695 Training accuracy: 72.50% | Validation accuracy: 52.50% Epoch 002, Step 00150 Training loss: 0.623 Validation loss: 0.692 Epoch 002, Step 00200 Training loss: 0.695 Validation loss: 0.708 Epoch 002, Step 00250 Training loss: 0.626 Validation loss: 0.676 Training accuracy: 62.50% | Validation accuracy: 50.00% Epoch 003, Step 00300 Training loss: 0.535 Validation loss: 0.673 Epoch 003, Step 00350 Training loss: 0.615 Validation loss: 0.694 Training accuracy: 72.50% | Validation accuracy: 52.50% Epoch 004, Step 00400 Training loss: 0.506 Validation loss: 0.641 Epoch 004, Step 00450 Training loss: 0.475 Validation loss: 0.669 Epoch 004, Step 00500 Training loss: 0.447 Validation loss: 0.634 Training accuracy: 85.00% | Validation accuracy: 65.00% Epoch 005, Step 00550 Training loss: 0.519 Validation loss: 0.618 Epoch 005, Step 00600 Training loss: 0.460 Validation loss: 0.625 Training accuracy: 75.00% | Validation accuracy: 67.50% Training completed in 0.62 minutes. Training accuracy: 78.08% Validation accuracy: 76.51% Test accuracy: 77.00%
First of all: what a difference a GPU makes. It takes about 1/10th the time to train the same model that we first created.
Second: it's not surprising that this model performs much worse. Causal attention means the first token pays zero attention to any other token. You're effectively asking the model to determine whether or not something is spam based on the first word (fragment). I'm actually shocked it's performing as well as it does.