In [1]:
import torch
import torch.nn as nn
In [2]:
torch.cuda.is_available()
Out[2]:
True
In [3]:
class LayerNorm(nn.Module):
    def __init__(self, embed_dim):
        super().__init__()
        self.epsilon = 1e-5 # Prevents divide-by-zero errors.

        # These trainable parameters allow the model to scale and
        # shift this layers output beyond strict normalization if
        # that improves model performance.
        self.scale = nn.Parameter(torch.ones(embed_dim))
        self.shift = nn.Parameter(torch.zeros(embed_dim))

    def forward(self, X):
        mean = X.mean(dim=-1, keepdim=True)

        # We use a biased variance because in practice embedding
        # dimensions are so large that the difference is negligible,
        # plus this ensures compatibility with historical open-weight
        # GPT models.
        var = X.var(dim=-1, keepdim=True, unbiased=False)

        normed_X = (X - mean) / torch.sqrt(var + self.epsilon)
        normed_X = normed_X * self.scale + self.shift
        return normed_X
In [4]:
class GELU(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, X):
        sqrt_2_over_pi = torch.sqrt(torch.tensor(2 / torch.pi))
        result = 0.5 * X * (1 + torch.tanh(sqrt_2_over_pi * (X + 0.044715 * torch.pow(X,3))))
        return result
In [5]:
class FeedForward(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        embed_dim = cfg["emb_dim"]
        embed_dim_x4 = embed_dim * 4
        self.layers = nn.Sequential(
            nn.Linear(embed_dim, embed_dim_x4),
            GELU(),
            nn.Linear(embed_dim_x4, embed_dim)
        )

    def forward(self, X):
        result = self.layers(X)
        return result
In [6]:
class MultiHeadAttention(nn.Module):
    def __init__(self, input_dim, output_dim, context_length, dropout_pct, num_heads, use_bias=False):
        super().__init__()

        assert output_dim % num_heads == 0, "output_dim must be a multiple of num_heads"
        self.num_heads = num_heads
        self.head_dim = output_dim // num_heads
        self.output_dim = output_dim
        
        self.W_q = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.W_k = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.W_v = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.output_proj = nn.Linear(output_dim, output_dim)
        
        self.dropout = torch.nn.Dropout(dropout_pct)
        ones = torch.ones(context_length, context_length)
        self.register_buffer("mask", torch.triu(ones, diagonal=1).bool())

    def forward(self, batch):
        num_samples, num_tokens, token_dim = batch.shape
        queries = self.W_q(batch)
        keys = self.W_k(batch)
        values = self.W_v(batch)

        queries = queries.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        keys = keys.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        values = values.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        
        attn_scores = queries @ keys.transpose(2, 3)
        attn_scores.masked_fill_(self.mask[:num_tokens, :num_tokens], -torch.inf)
        
        attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
        attn_weights = self.dropout(attn_weights)
        
        context_vectors = attn_weights @ values
        context_vectors = context_vectors.transpose(1, 2)
        context_vectors = context_vectors.contiguous().view(num_samples, num_tokens, self.output_dim)
        
        output = self.output_proj(context_vectors)
        return output
In [7]:
class TransformerBlock(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.attention = MultiHeadAttention(
            input_dim      = config["emb_dim"],
            output_dim     = config["emb_dim"],
            context_length = config["context_length"],
            num_heads      = config["n_heads"],
            dropout_pct    = config["drop_rate"],
            use_bias       = config["qkv_bias"]
        )
        self.feed_forward = FeedForward(config)
        self.norm1 = LayerNorm(config["emb_dim"])
        self.norm2 = LayerNorm(config["emb_dim"])
        self.dropout = nn.Dropout(config["drop_rate"])

    def forward(self, batch):
        shortcut = batch
        output = self.norm1(batch)
        output = self.attention(output)
        output = self.dropout(output)
        output = output + shortcut

        shortcut = output
        output = self.norm2(output)
        output = self.feed_forward(output)
        output = self.dropout(output)
        output = output + shortcut

        return output
In [8]:
class GPTModel(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
        self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
        self.dropout = nn.Dropout(cfg["drop_rate"])
        self.xform_blocks = nn.Sequential(
            *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])]
        )
        self.final_norm = LayerNorm(cfg["emb_dim"])
        self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias = False)

    def forward(self, input_tokens):
        batch_size, num_tokens = input_tokens.shape

        token_embeds = self.tok_emb(input_tokens)
        pos_embeds = self.pos_emb(torch.arange(num_tokens, device=input_tokens.device))
        X = token_embeds + pos_embeds
        X = self.dropout(X)
        X = self.xform_blocks(X)
        X = self.final_norm(X)

        logits = self.out_head(X)
        return logits
In [9]:
GPT_CONFIG_124M = {
    "vocab_size": 50257,
    "context_length": 256, # Reduced for training ease on local hardware.
    "emb_dim": 768,
    "n_heads": 12,
    "n_layers": 12, 
    "drop_rate": 0.1,
    "qkv_bias": False
}
torch.manual_seed(123)
model = GPTModel(GPT_CONFIG_124M)
model.eval()
print("Model initialized.")
Model initialized.
In [10]:
def generate_text_simple(model, tokens, max_output_tokens, max_context_length):
    for _ in range(max_output_tokens):
        # Crop tokens to maximum context length and get logits.
        tokens_context = tokens[:, -max_context_length:]
        logits = model(tokens_context)

        # Go from [batch_size, num_tokens, embed_dim] to [batch_size, embed_dim],
        # only retaining the last token from each batch.
        logits = logits[:, -1, :]

        # Determine the next token and append it.
        probas = torch.softmax(logits, dim=-1)
        next_tokens = torch.argmax(probas, dim=-1, keepdim=True)
        tokens = torch.cat([tokens, next_tokens], dim=-1)

    return tokens
In [11]:
import tiktoken
tokenizer_gpt2 = tiktoken.get_encoding("gpt2")
In [12]:
# This is a helper function for testing purposes. It takes
# some text and returns the tokens wrapped up within a
# batch. This makes it easy to use little bits of test
# text with functions that expect to receive a batch of
# tokenized samples.
def text_to_token_ids(text, tokenizer):
    encoded = tokenizer.encode(text, allowed_special={'<|endoftext|>'})
    
    # unsqueeze() wraps the tokens in a batch.
    encoded_tensor = torch.tensor(encoded).unsqueeze(0)
    return encoded_tensor

# This is the same idea as the preceding function, just
# in the other direction. It takes a batch of tokens
# and returns a string.
def token_ids_to_text(tokens, tokenizer):
     # squeeze() removes the first dimension which represents the batch.
    decoded_text = tokenizer.decode(tokens.squeeze(0).tolist())
    return decoded_text
In [13]:
start_context = "Every effort moves you"
token_ids = generate_text_simple(
    model=model,
    tokens=text_to_token_ids(start_context, tokenizer_gpt2),
    max_output_tokens=10,
    max_context_length=GPT_CONFIG_124M["context_length"]
)
print("Output text:\n", token_ids_to_text(token_ids, tokenizer_gpt2))
# Expected output: Every effort moves you rentingetic wasnم refres RexMeCHicular stren
Output text:
 Every effort moves you rentingetic wasnم refres RexMeCHicular stren

We will use cross entropy loss to train our model. Imagine a batch of 2 samples, each containing 2 tokens, with a dictionary size of 100 tokens. The model will output a batch of 2 samples, each containing 2 vectors that are 100 elements long — so 4 vectors in total. And the first thing we will do is take the softmax for each vector. As a result, the vector elements will specify the probability that the corresponding dictionary token is the right one to emit.

Let's consider the second vector. Suppose that the correct next token for this vector is "dog," and that happens to correspond to item 42 in the dictionary. So we look at vector 2, element 42, and see a value of 0.005. That means the model thinks there is a 0.5% chance that token 42 — "dog" — is the right next token for this vector. Of course, that means the model is very wrong: the right next token is "dog," so the probability here should be 100%.

How wrong is the model? Consider if it were perfect: vector 2 would have a 1.0 in element 42, the "dog" slot. Instead, it had a 0.005. It's good to take the log() of these values, because that magnifies the impact of mistakes so the model learns faster. For example, a probability of 1 yields a score of $\log(1) = 0$, meaning "not wrong at all." By contrast, for this vector, our model's actual score is $\log(0.005) = -5.298$.

Our strategy is to have a list of target tokens that correspond to each input token. We can then efficiently compare the model's output against this "answer key" in the following way:

  1. In each output vector, get the softmax-ed probability value in the position for the corresponding target token.
  2. Arrange these values in a single vector.
  3. Calculate the log() for each of these values.
  4. Calculate the average of all of these values and invert the sign (positive "loss" is the convention).

Visually, it looks something like the following diagram: image.png

In [14]:
# Build a batch of two input samples, each three tokens long.
inputs1 = text_to_token_ids("every effort moves", tokenizer_gpt2)
inputs2 = text_to_token_ids("I really like", tokenizer_gpt2)
inputs = torch.stack((inputs1, inputs2)).squeeze(1)
inputs
Out[14]:
tensor([[16833,  3626,  6100],
        [   40,  1107,   588]])
In [15]:
# Build a matching batch of targets: the sequence of tokens for
# each sample, advanced by one token.
targets1 = text_to_token_ids(" effort moves you", tokenizer_gpt2)
targets2 = text_to_token_ids(" really like chocolate", tokenizer_gpt2)
targets = torch.stack((targets1, targets2)).squeeze(1)
targets
Out[15]:
tensor([[ 3626,  6100,   345],
        [ 1107,   588, 11311]])

image.png

In [16]:
# We'll run our model without gradient calculation for efficiency. We calculate gradients
# for training, but we don't need them for inference. 
with torch.no_grad():
    logits = model(inputs)

# Then we'll use softmax to turn the model's output ("logits") into a
# probability distribution.
probas = torch.softmax(logits, dim=-1)
probas.shape
Out[16]:
torch.Size([2, 3, 50257])
In [17]:
# For a given sample and output probability vector (which corresponds to an input token), here is
# how we lookup the target token id.
sample_id = 0
proba_id = 0
target_id = targets[sample_id, proba_id]
target_id
Out[17]:
tensor(3626)
In [18]:
# Now we can lookup the probability the model calculated for the target token.
target_proba = probas[sample_id, proba_id, target_id]
target_proba
Out[18]:
tensor(7.4540e-05)
In [19]:
# That's how we do it for a single input token. We can use loops
# to find all of the target probabilities generated for each input token.
# Remember, for each input token, the model generates probabilities for every
# potential output token. We are just interested in the probability of the
# *correct* output token: that's our target probability.
target_probas = []
for sample_id in range(probas.shape[0]):
    for proba_id in range(probas.shape[1]):
        target_id = targets[sample_id, proba_id]
        target_proba = probas[sample_id, proba_id, target_id]
        target_probas.append(target_proba)

target_probas
Out[19]:
[tensor(7.4540e-05),
 tensor(3.1061e-05),
 tensor(1.1563e-05),
 tensor(1.0337e-05),
 tensor(5.6776e-05),
 tensor(4.7559e-06)]
In [20]:
# If we flatten our probability and target tensors, we can build our list of 
# of target probabilities in a single line using a Python list comprehension.
flat_probas = probas.flatten(0, 1)
flat_targets = targets.flatten(0, 1)
print("Shape for probas and targets:", flat_probas.shape, flat_targets.shape)

target_probas = [flat_probas[proba, target] for proba, target in zip(range(flat_probas.shape[0]), flat_targets)]
target_probas
Shape for probas and targets: torch.Size([6, 50257]) torch.Size([6])
Out[20]:
[tensor(7.4540e-05),
 tensor(3.1061e-05),
 tensor(1.1563e-05),
 tensor(1.0337e-05),
 tensor(5.6776e-05),
 tensor(4.7559e-06)]
In [21]:
# Now we can take the log of each target probability.
log_target_probas = torch.log(torch.tensor(target_probas))
log_target_probas
Out[21]:
tensor([ -9.5042, -10.3796, -11.3677, -11.4798,  -9.7764, -12.2561])
In [22]:
# Next we take the average of all target probabilities.
average_log_target_probas = torch.mean(log_target_probas)
average_log_target_probas
Out[22]:
tensor(-10.7940)
In [23]:
# Finally, we invert the sign to get our cross entropy loss.
cross_entropy_loss = average_log_target_probas * -1
cross_entropy_loss

# Expected to be: tensor(10.7940)
Out[23]:
tensor(10.7940)
In [24]:
# Another interesting measure is perplexity. This is e^cross_entropy_loss.
# Intuitively, it tells us how many tokens the model thinks *might* be the next
# token. A perplexity of 1 means the model is *dead certain* that one token is
# the correct next token. A perplexity of 10,000 means the model thinks the next
# token could be any one of 10,000 potential tokens.
perplexity = torch.exp(cross_entropy_loss)
perplexity
Out[24]:
tensor(48725.8203)
In [25]:
# Having done all that ourselves, we can appreciate what torch's cross entropy loss function
# provides for us.
flat_logits = logits.flatten(0, 1)
torch.nn.functional.cross_entropy(flat_logits, flat_targets)

# Expected to be the same as our calculation: tensor(10.7940)
Out[25]:
tensor(10.7940)
In [26]:
# Load the verdict.
with open('the-verdict.txt', 'r', encoding='utf8') as f:
  text_data = f.read()
In [27]:
# Count characters and tokens.
print("# chars:", len(text_data))
print("# tokens:", len(tokenizer_gpt2.encode(text_data)))
# chars: 20479
# tokens: 5145
In [28]:
# Split data (not tokens) 90/10 into training and validation sets.
split = len(text_data) * 9 // 10
train_data = text_data[:split]
val_data = text_data[split:]
print("Training data length:", len(train_data))
print("Test data length:", len(val_data))
assert len(train_data) + len(val_data) == len(text_data)
Training data length: 18431
Test data length: 2048
In [29]:
# Data set and data loader from chapter 2.
from torch.utils.data import Dataset, DataLoader

class GPTDatasetV1(Dataset):
    def __init__(self, txt, tokenizer, max_length, stride):
        self.input_samples = []
        self.target_samples = []

        tokens = tokenizer.encode(txt)
        num_tokens = len(tokens)
        max_length_plus = max_length + 1
        assert max_length_plus <= num_tokens, "Need at least one more token than max length."
        
        self.num_samples = 0
        idx = 0
        while idx + max_length_plus <= num_tokens:
        #for i in range(0, num_tokens - max_length, stride):
            #j = i + 1
            #input_sample = tokens[i:i+max_length]
            #target_sample = tokens[j:j+max_length]
            input_sample = tokens[idx:idx+max_length]
            jdx = idx + 1
            target_sample = tokens[jdx:jdx+max_length]
            self.input_samples.append(torch.tensor(input_sample))
            self.target_samples.append(torch.tensor(target_sample))
            self.num_samples += 1
            idx += stride

    def __len__(self):
        return self.num_samples

    def __getitem__(self, idx):
        return self.input_samples[idx], self.target_samples[idx]

def create_dataloader_v1(txt, batch_size=4, max_length=256,
                         stride=128, shuffle=True, drop_last=True,
                         num_workers=0):
    tokenizer = tiktoken.get_encoding("gpt2")
    dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)
    dataloader = DataLoader(
        dataset=dataset,
        batch_size=batch_size,
        shuffle=shuffle,
        drop_last=drop_last,
        num_workers=num_workers
    )

    return dataloader
In [30]:
# Use chapter 2 data loaders to create training and validation data loaders.
# Training loader should drop last and shuffle, validation loader shouldn't.
# Both should have a batch size of 2. Max length and stride length should be
# equal and come from the config dict.

train_loader = create_dataloader_v1(
    train_data,
    batch_size=2,
    max_length=GPT_CONFIG_124M["context_length"],
    stride=GPT_CONFIG_124M["context_length"],
    shuffle=True,
    drop_last=True,
    num_workers=0,
)

val_loader = create_dataloader_v1(
    val_data,
    batch_size=2,
    max_length=GPT_CONFIG_124M["context_length"],
    stride=GPT_CONFIG_124M["context_length"],
    shuffle=False,
    drop_last=False,
    num_workers=0,
)
In [31]:
# Iterate through each data loader and print size of each output (input and target),
# verify that shapes look good.
print("Training batches:")
for input_batch, target_batch in train_loader:
    print(f"    input: {input_batch.shape}, target: {target_batch.shape}")

print("\nValidation batches:")
for input_batch, target_batch in val_loader:
    print(f"    input: {input_batch.shape}, target: {target_batch.shape}")
Training batches:
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
    input: torch.Size([2, 256]), target: torch.Size([2, 256])

Validation batches:
    input: torch.Size([2, 256]), target: torch.Size([2, 256])
In [32]:
# Create a function to calculate the cross entropy loss, given an input batch, a target batch,
# a model, and the device. We move the batches to the device first to allow for GPU training.
def get_batch_loss(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)
    flat_logits = logits.flatten(0, 1)
    flat_targets = target_batch.flatten(0, 1)

    loss = torch.nn.functional.cross_entropy(flat_logits, flat_targets)
    return loss
In [104]:
# Use the previous function to calculate loss for all data in a loader, given a model, a device,
# and an optional number of batches. If a batch number isn't provided, use all available batches
# in the loader (if the loader is empty the result is `nan`), otherwise use whichever is less:
# the available batches or the requested batches. The result is the average of loss across
# all batches.
def get_loader_loss(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 = get_batch_loss(input_batch, target_batch, model, device)
        total_loss += loss

    avg_loss = total_loss / num_batches
    return avg_loss
In [34]:
# Report the training and validation loss for the model as it is right now. Use a cuda device if
# available, otherwise a cpu. Save time by disabling gradient calculation since it's not necessary.
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
with torch.no_grad():
    avg_train_loss = get_loader_loss(train_loader, model, device)
    avg_val_loss = get_loader_loss(val_loader, model, device)
print("Average training data loss:", avg_train_loss)
print("Average validation data loss:", avg_val_loss)
Average training data loss: tensor(10.9876, device='cuda:0')
Average validation data loss: tensor(10.9811, device='cuda:0')
In [35]:
# Returns the training loss and validation loss of the model using the
# provided loaders and device. The evaluation iteration is a number
# specifying how many batches to evaluate in each loader. Uses the model
# in evaluation mode (so without things like dropout) for stability
# and reproducibility.
def evaluate_model(model, train_loader, val_loader, device, eval_iter):
    model.eval()
    with torch.no_grad():
        train_loss = get_loader_loss(train_loader, model, device, eval_iter)
        val_loss = get_loader_loss(val_loader, model, device, eval_iter)
    model.train()
    return train_loss, val_loss
In [36]:
avg_train_loss, avg_val_loss = evaluate_model(model, train_loader, val_loader, device, 10)
print("Average training data loss:", avg_train_loss)
print("Average validation data loss:", avg_val_loss)
Average training data loss: tensor(10.9876, device='cuda:0')
Average validation data loss: tensor(10.9811, device='cuda:0')
In [37]:
# Given a starting context, generates and prints sample output using the provided
# model, tokenizer, and device. Temporarily disables dropout and gradient calculation
# for stability and efficiency. Use the simple text generator, with the context size
# being the max supported by the model (determined by the shape of the position embeddings
# tensor). On print-out, newlines will be replaced with spaces for clarity.
def generate_and_print_sample(model, tokenizer, device, start_context, max_output_tokens=50):
    model.eval()
    context_size = model.pos_emb.weight.shape[0]
    tokens = text_to_token_ids(start_context, tokenizer)
    tokens = tokens.to(device)
    with torch.no_grad():
        output_tokens = generate_text_simple(model, tokens, max_output_tokens, context_size)
    model.train()
    output_text = token_ids_to_text(output_tokens, tokenizer)
    output_text = output_text.replace("\n", " ")
    print(output_text)
In [38]:
generate_and_print_sample(model, tokenizer_gpt2, device, "Every step moves")
Every step moves Admir disproportionate Stores instability firepower ChaseLab interruption Cleveland expression Floating hedge reflection attachedPrivacy deductedObject desks appalled Selferey comparing reactionsSavereating Witt convictions Gilltml peOLDScopeinia234 detachedbit powder severed fishissy Correction guaranteeingidden iPad spaces Griff Investigator hostilities Worse boolean
In [39]:
# Now we train the model. We will train the model for a specified number of epochs.
# Each epoch sets the model to training mode, then iterates through the training
# batches and does the typical loop: zero out the optimizer's gradient's, get the model's
# loss on a forward pass, perform a backward pass, and update the model's weights by stepping
# the optimizer. Based on the evaluation frequency, the model will also be evaluated
# against the validation data, and progress will be printed out.
def train_model_simple(model, train_loader, val_loader,
                       optimizer, device, num_epochs,
                       eval_freq, eval_iter, start_context, tokenizer):
    train_losses, val_losses, tokens_seen = [], [], []
    current_step = -1
    num_tokens_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 = get_batch_loss(input_batch, target_batch, model, device)
            loss.backward()
            optimizer.step()
            current_step += 1
            num_tokens_seen += input_batch.numel()

            if current_step % eval_freq == 0:
                train_loss, val_loss = evaluate_model(model, train_loader, val_loader, device, eval_iter)
                print(f"Epoch {current_epoch:03}, Step {current_step:05}\n\tTraining loss: {train_loss}\n\tValidation loss: {val_loss}\t")
                train_losses.append(train_loss)
                val_losses.append(val_loss)
                tokens_seen.append(num_tokens_seen)

        # Print sample output once per epoch
        print()
        generate_and_print_sample(model, tokenizer, device, start_context)
        print()

    return train_losses, val_losses, tokens_seen
In [40]:
# Now we can actually train our model! Note that this will produce slightly different
# output than Raschka obtained if it runs on CUDA because of a different RNG stream.
torch.manual_seed(123)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = GPTModel(GPT_CONFIG_124M)
model.to(device)
print("Model device:", next(model.parameters()).device)
optimizer = torch.optim.AdamW(model.parameters(), lr=0.0004, weight_decay=0.1)
num_epochs=10
eval_freq=5
eval_iter=5
start_context="Every effort moves you"
tokenizer = tiktoken.get_encoding("gpt2")
train_losses, val_losses, tokens_seen = train_model_simple(
    model, train_loader, val_loader, optimizer, 
    device, num_epochs, eval_freq, eval_iter,
    start_context, tokenizer
)
Model device: cuda:0
Epoch 001, Step 00000
	Training loss: 9.815638542175293
	Validation loss: 9.9244384765625	
Epoch 001, Step 00005
	Training loss: 8.068862915039062
	Validation loss: 8.336977005004883	

Every effort moves you,.                                                

Epoch 002, Step 00010
	Training loss: 6.623260021209717
	Validation loss: 7.051217079162598	
Epoch 002, Step 00015
	Training loss: 6.0451555252075195
	Validation loss: 6.601138591766357	

Every effort moves you, and,, and,, and,,,, and,.                                   

Epoch 003, Step 00020
	Training loss: 5.528307914733887
	Validation loss: 6.522822380065918	
Epoch 003, Step 00025
	Training loss: 5.381830215454102
	Validation loss: 6.391748428344727	

Every effort moves you.                                                 

Epoch 004, Step 00030
	Training loss: 4.865167140960693
	Validation loss: 6.259573936462402	
Epoch 004, Step 00035
	Training loss: 4.635066509246826
	Validation loss: 6.2958149909973145	

Every effort moves you of the "I the picture.                    "I"I the the picture.              

Epoch 005, Step 00040
	Training loss: 3.943211317062378
	Validation loss: 6.180148124694824	

Every effort moves you know the                                                

Epoch 006, Step 00045
	Training loss: 3.55232310295105
	Validation loss: 6.177870750427246	
Epoch 006, Step 00050
	Training loss: 2.975649118423462
	Validation loss: 6.134241104125977	

Every effort moves you know it was not that the picture.  "I had the last word.           "I turned back his head to the donkey.  "I looked, and I had a little his

Epoch 007, Step 00055
	Training loss: 2.8590247631073
	Validation loss: 6.166060924530029	
Epoch 007, Step 00060
	Training loss: 2.1389667987823486
	Validation loss: 6.147772789001465	

Every effort moves you know," was not that my dear, and he had been the picture was a so that he was a little to me to have to see a smile behind his pictures.      "I looked, and were, and I was

Epoch 008, Step 00065
	Training loss: 1.6992119550704956
	Validation loss: 6.187326908111572	
Epoch 008, Step 00070
	Training loss: 1.3999236822128296
	Validation loss: 6.23293399810791	

Every effort moves you?"  "Yes--quite insensible to the irony. She wanted him vindicated--and by me!"  He laughed again, and threw back his head to look up at the sketch of the donkey. "There were days when I

Epoch 009, Step 00075
	Training loss: 1.0710867643356323
	Validation loss: 6.282141208648682	
Epoch 009, Step 00080
	Training loss: 0.8080324530601501
	Validation loss: 6.304718017578125	

Every effort moves you?"  "Yes--quite insensible to the irony. She wanted him vindicated--and by me!"  He laughed again, and threw back his head to look up at the honour being _mine_--because he's the first

Epoch 010, Step 00085
	Training loss: 0.5882498025894165
	Validation loss: 6.409276485443115	

Every effort moves you?"  "Yes--quite insensible to the irony. She wanted him vindicated--and by me!"  He laughed again, and threw back his head to look up at the sketch of the donkey. "There were days when I

In [41]:
# We'll run it one more time, strictly on the CPU, which is agonizingly slow
# by comparison. But we should get the same results as Raschka now. It's a good
# correctness check.
torch.manual_seed(123)
device = "cpu"
model = GPTModel(GPT_CONFIG_124M)
model.to(device)
print("Model device:", next(model.parameters()).device)
optimizer = torch.optim.AdamW(model.parameters(), lr=0.0004, weight_decay=0.1)
num_epochs=10
eval_freq=5
eval_iter=5
start_context="Every effort moves you"
tokenizer = tiktoken.get_encoding("gpt2")
train_losses, val_losses, tokens_seen = train_model_simple(
    model, train_loader, val_loader, optimizer, 
    device, num_epochs, eval_freq, eval_iter,
    start_context, tokenizer
)
Model device: cpu
Epoch 001, Step 00000
	Training loss: 9.78100299835205
	Validation loss: 9.932807922363281	
Epoch 001, Step 00005
	Training loss: 8.110532760620117
	Validation loss: 8.338573455810547	

Every effort moves you,,,,,,,,,,,,.                                     

Epoch 002, Step 00010
	Training loss: 6.660930633544922
	Validation loss: 7.047985076904297	
Epoch 002, Step 00015
	Training loss: 5.96102237701416
	Validation loss: 6.61604118347168	

Every effort moves you, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and, and,, and, and,

Epoch 003, Step 00020
	Training loss: 5.726132869720459
	Validation loss: 6.600389003753662	
Epoch 003, Step 00025
	Training loss: 5.201076507568359
	Validation loss: 6.347813129425049	

Every effort moves you, and I had been.                                            

Epoch 004, Step 00030
	Training loss: 4.417184352874756
	Validation loss: 6.278294563293457	
Epoch 004, Step 00035
	Training loss: 4.068655490875244
	Validation loss: 6.225797653198242	

Every effort moves you know the                          "I he had the donkey and I had the and I had the donkey and down the room, I had

Epoch 005, Step 00040
	Training loss: 3.7320594787597656
	Validation loss: 6.1600470542907715	

Every effort moves you know it was not that the picture--I had the fact by the last I had been--his, and in the            "Oh, and he said, and down the room, and in

Epoch 006, Step 00045
	Training loss: 2.8500430583953857
	Validation loss: 6.17864465713501	
Epoch 006, Step 00050
	Training loss: 2.427326202392578
	Validation loss: 6.140961647033691	

Every effort moves you know," was one of the picture. The--I had a little of a little: "Yes, and in fact, and in the picture was, and I had been at my elbow and as his pictures, and down the room, I had

Epoch 007, Step 00055
	Training loss: 2.104304790496826
	Validation loss: 6.134012222290039	
Epoch 007, Step 00060
	Training loss: 1.8819363117218018
	Validation loss: 6.233464241027832	

Every effort moves you know," was one of the picture for nothing--I told Mrs.  "I was no--as! The women had been, in the moment--as Jack himself, as once one had been the donkey, and were, and in his

Epoch 008, Step 00065
	Training loss: 1.3204452991485596
	Validation loss: 6.238315105438232	
Epoch 008, Step 00070
	Training loss: 0.9851565361022949
	Validation loss: 6.242359638214111	

Every effort moves you know," was one of the axioms he had been the tips of a self-confident moustache, I felt to see a smile behind his close grayish beard--as if he had the donkey. "strongest," as his

Epoch 009, Step 00075
	Training loss: 0.7165045738220215
	Validation loss: 6.292903423309326	
Epoch 009, Step 00080
	Training loss: 0.5412572622299194
	Validation loss: 6.3931403160095215	

Every effort moves you?"  "Yes--quite insensible to the irony. She wanted him vindicated--and by me!"  He laughed again, and threw back the window-curtains, I had the donkey. "There were days when I

Epoch 010, Step 00085
	Training loss: 0.39095428586006165
	Validation loss: 6.452146530151367	

Every effort moves you know," was one of the axioms he laid down across the Sevres and silver of an exquisitely appointed luncheon-table, when, on a later day, I had again run over from Monte Carlo; and Mrs. Gis

In [42]:
# Plot the results. We can see evidence of memorization because
# traing loss drops while validation loss stalls dramatically after
# the second epoch. This is to be expected when working with such a
# tiny data set.
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def plot_losses(epochs_seen, tokens_seen, train_losses, val_losses):
    fig, ax1 = plt.subplots(figsize=(5, 3))
    ax1.plot(epochs_seen, train_losses, label="Training loss")
    ax1.plot(
        epochs_seen, val_losses, linestyle="-.", label="Validation loss"
    )
    ax1.set_xlabel("Epochs")
    ax1.set_ylabel("Loss")
    ax1.legend(loc="upper right")
    ax1.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax2 = ax1.twiny()
    ax2.plot(tokens_seen, train_losses, alpha=0)
    ax2.set_xlabel("Tokens seen")
    fig.tight_layout()
    plt.show()

epochs_tensor = torch.linspace(0, num_epochs, len(train_losses))
plot_losses(epochs_tensor, tokens_seen, train_losses, val_losses)
No description has been provided for this image
In [43]:
# Explore decoding strategies on the CPU in eval mode. Start
# with the as-is text generation method.
model.to("cpu")
model.eval()
tokenizer = tiktoken.get_encoding("gpt2")
tokens = text_to_token_ids("Every effort moves you", tokenizer)
token_ids = generate_text_simple(
    model,
    tokens,
    25,
    GPT_CONFIG_124M["context_length"]
)
text = token_ids_to_text(token_ids, tokenizer)
text
Out[43]:
'Every effort moves you know," was one of the axioms he laid down across the Sevres and silver of an exquisitely appointed lun'
In [44]:
# We will explore temperature scaling using this dictionary and its inverse.
vocab = {
    "closer": 0,
    "every": 1,
    "effort": 2,
    "forward": 3,
    "inches": 4,
    "moves": 5, 
    "pizza": 6,
    "toward": 7,
    "you": 8,
}
inverse_vocab = { val : key for key, val in vocab.items()}
inverse_vocab
Out[44]:
{0: 'closer',
 1: 'every',
 2: 'effort',
 3: 'forward',
 4: 'inches',
 5: 'moves',
 6: 'pizza',
 7: 'toward',
 8: 'you'}
In [45]:
# Assume the model generated these logits.
next_token_logits = torch.tensor(
    [4.51, 0.89, -1.90, 6.75, 1.63, -1.62, -1.89, 6.28, 1.79]
)
In [46]:
# Our current approach is greedy decoding: softmax and argmax.
probas = torch.softmax(next_token_logits, dim=-1)
next_token_id = torch.argmax(probas).item()
print(next_token_id, " = ", inverse_vocab[next_token_id])
3  =  forward
In [47]:
# Instead of argmax we can use multinomial, which samples according to
# probability.
torch.manual_seed(123)
next_token_id = torch.multinomial(probas, 1).item()
print(next_token_id, " = ", inverse_vocab[next_token_id])
3  =  forward
In [48]:
# We got the same result. Let's run this a thousand times and see what
# we get.
def print_sampled_tokens(probas):
    samples = torch.tensor([torch.multinomial(probas, 1).item() for _ in range(1000)])
    token_counts = torch.bincount(samples)

    for k, v in enumerate(token_counts):
        text = inverse_vocab[k]
        print(f"{k:02d}: {text} x {v}")

torch.manual_seed(123)
print_sampled_tokens(probas)
00: closer x 73
01: every x 0
02: effort x 0
03: forward x 582
04: inches x 2
05: moves x 0
06: pizza x 0
07: toward x 343
In [49]:
# We can use temperature scaling to modulate the randomness in the results. We
# divide the logits by a number greater than 1 to make the distribution more
# uniform; dividing by a number less than 1 will make the distribution more spiky.
def softmax_with_temperature(logits, temperature):
    assert temperature > 0, "Temperature must be greater than zero."
    scaled_logits = logits / temperature
    probas = torch.softmax(scaled_logits, dim=-1)
    return probas
In [50]:
# Plot a three way histogram showing our original distribution, then two
# temperature variations.
temperatures = [1, 0.1, 5]
scaled_probas = [softmax_with_temperature(next_token_logits, T)
                for T in temperatures]
x = torch.arange(len(vocab))
bar_width = 0.15
fig, ax = plt.subplots(figsize=(5, 3))
for i, T in enumerate(temperatures):
    rects = ax.bar(x + i * bar_width, scaled_probas[i], 
                   bar_width, label=f'Temperature = {T}')
ax.set_ylabel('Probability')
ax.set_xticks(x)
ax.set_xticklabels(vocab.keys(), rotation=90)
ax.legend()
plt.tight_layout()
plt.show()
No description has been provided for this image

Exercise 5.1¶

Use the print_sampled_tokens function to print the sampling frequencies of the softmax probabilities scaled with the temperatures shown in figure 5.14. How often is the word pizza sampled in each case? Can you think of a faster and more accurate way to determine how often the word pizza is sampled?

In [51]:
# The slow way and innacurate way: do a bunch of trial prints and observe.
for temp, probas in zip(temperatures, scaled_probas):
    print("\nTemperature:", temp)
    print_sampled_tokens(probas)
Temperature: 1
00: closer x 82
01: every x 1
02: effort x 0
03: forward x 558
04: inches x 3
05: moves x 0
06: pizza x 0
07: toward x 350
08: you x 6

Temperature: 0.1
00: closer x 0
01: every x 0
02: effort x 0
03: forward x 991
04: inches x 0
05: moves x 0
06: pizza x 0
07: toward x 9

Temperature: 5
00: closer x 164
01: every x 73
02: effort x 53
03: forward x 234
04: inches x 75
05: moves x 46
06: pizza x 40
07: toward x 230
08: you x 85
In [52]:
# The fast way and accurate way: calculate the expected percentages.
scaled_probas_tensor = torch.stack(scaled_probas)
pizza_tensor = torch.zeros(len(vocab))
pizza_tensor[vocab["pizza"]] = 1
pizza_freqs = scaled_probas_tensor @ pizza_tensor
for temp, freq in zip(temperatures, pizza_freqs):
    print(f"Temp: {temp:.1f}, Pizza Freq: {freq*100:.2f}%")
Temp: 1.0, Pizza Freq: 0.01%
Temp: 0.1, Pizza Freq: 0.00%
Temp: 5.0, Pizza Freq: 4.30%
In [53]:
# Next we'll setup top-k sampling, where we set every logit except for the
# top k (for whatever k) equal to negative infinity before taking
# the softmax.
values, indices = torch.sort(next_token_logits, descending=True)
print("Values:", values)
print("Indices:", indices)
Values: tensor([ 6.7500,  6.2800,  4.5100,  1.7900,  1.6300,  0.8900, -1.6200, -1.8900,
        -1.9000])
Indices: tensor([3, 7, 0, 8, 4, 1, 5, 6, 2])
In [54]:
# Here are the top 3 logits.
next_token_logits[indices[:3]]
Out[54]:
tensor([6.7500, 6.2800, 4.5100])
In [55]:
# And here are all logits less than the top 3.
next_token_logits[indices[3:]]
Out[55]:
tensor([ 1.7900,  1.6300,  0.8900, -1.6200, -1.8900, -1.9000])
In [56]:
# Set all logits less than the top 3 equal to negative infinity.
inf_masked_logits = next_token_logits.clone()
inf_masked_logits[indices[3:]] = -torch.inf
inf_masked_logits
Out[56]:
tensor([4.5100,   -inf,   -inf, 6.7500,   -inf,   -inf,   -inf, 6.2800,   -inf])
In [57]:
# Now take the softmax to get our top-3 probabilities.
probas_top_3 = torch.softmax(inf_masked_logits, dim=-1)
probas_top_3
Out[57]:
tensor([0.0615, 0.0000, 0.0000, 0.5775, 0.0000, 0.0000, 0.0000, 0.3610, 0.0000])
In [58]:
print_sampled_tokens(probas_top_3)
00: closer x 60
01: every x 0
02: effort x 0
03: forward x 584
04: inches x 0
05: moves x 0
06: pizza x 0
07: toward x 356
In [59]:
# Torch has topk and where functions to make this easier.
k = 3
top_k_values, top_k_indices = torch.topk(next_token_logits, k)
top_k_logits = torch.where(
    next_token_logits < top_k_values[-1], # Less the than smallest top logit.
    -torch.inf, # Value if condition is true.
    next_token_logits # Value otherwise.
)
top_k_logits
Out[59]:
tensor([4.5100,   -inf,   -inf, 6.7500,   -inf,   -inf,   -inf, 6.2800,   -inf])
In [60]:
# Get the probabilities.
top_k_probas = torch.softmax(top_k_logits, 0)
top_k_probas
Out[60]:
tensor([0.0615, 0.0000, 0.0000, 0.5775, 0.0000, 0.0000, 0.0000, 0.3610, 0.0000])
In [61]:
# A quick aside about tensor manipulation: suppose we have this batch of 2
# samples of 4 tokens with an embedding dimension of 8.
t = torch.rand(2, 4, 8)
t
Out[61]:
tensor([[[0.1166, 0.7223, 0.2459, 0.0129, 0.5075, 0.4476, 0.1848, 0.2775],
         [0.3587, 0.7585, 0.5119, 0.4953, 0.9441, 0.2335, 0.5217, 0.9173],
         [0.1069, 0.1756, 0.9672, 0.9200, 0.2716, 0.5565, 0.5613, 0.7281],
         [0.6341, 0.8901, 0.0741, 0.6779, 0.2827, 0.7569, 0.7925, 0.2928]],

        [[0.2471, 0.3283, 0.3815, 0.6807, 0.9154, 0.6920, 0.3562, 0.8748],
         [0.9562, 0.7091, 0.8102, 0.0827, 0.6582, 0.5763, 0.0785, 0.8769],
         [0.3546, 0.6332, 0.0909, 0.4419, 0.3788, 0.5920, 0.4493, 0.5724],
         [0.9215, 0.2607, 0.5940, 0.7679, 0.6715, 0.8199, 0.6893, 0.7272]]])
In [62]:
# Now we get the top 3.
vals, _ = torch.topk(t, 3)
vals
Out[62]:
tensor([[[0.7223, 0.5075, 0.4476],
         [0.9441, 0.9173, 0.7585],
         [0.9672, 0.9200, 0.7281],
         [0.8901, 0.7925, 0.7569]],

        [[0.9154, 0.8748, 0.6920],
         [0.9562, 0.8769, 0.8102],
         [0.6332, 0.5920, 0.5724],
         [0.9215, 0.8199, 0.7679]]])
In [63]:
# We want to get the lowest of the top 3 values for each sample. This
# naive indexing won't work, it just returns the last batch.
vals[-1]
Out[63]:
tensor([[0.9154, 0.8748, 0.6920],
        [0.9562, 0.8769, 0.8102],
        [0.6332, 0.5920, 0.5724],
        [0.9215, 0.8199, 0.7679]])
In [64]:
# We have to specify that we don't want the last element of the first or
# second dimension, but only the third.
vals[:, :, -1]
Out[64]:
tensor([[0.4476, 0.7585, 0.7281, 0.7569],
        [0.6920, 0.8102, 0.5724, 0.7679]])
In [65]:
# This dropped a dimension and changed the shape. We can use unsqueeze to fix that.
vals[:,:,-1].unsqueeze(2)
Out[65]:
tensor([[[0.4476],
         [0.7585],
         [0.7281],
         [0.7569]],

        [[0.6920],
         [0.8102],
         [0.5724],
         [0.7679]]])
In [66]:
# Finally, we can use ... to say "take everything up to the specified dimension".
vals[..., -1].unsqueeze(2)
Out[66]:
tensor([[[0.4476],
         [0.7585],
         [0.7281],
         [0.7569]],

        [[0.6920],
         [0.8102],
         [0.5724],
         [0.7679]]])
In [67]:
# An updated generation function. For a given model and token batch,
# returns the original tokens with new tokens generated up to the
# maximum specified. Will only consider the most recent tokens (as
# determined by the context size) during generation. Will stop
# generation early if the provided end-of-sequence token is
# encountered. Applies top-k selection and then temperature
# scaling if requested.
def generate(model, tokens_batch, max_new_tokens, context_size,
             temperature=0.0, top_k=None, eos_id=None):

    # Track finished state for each sample, True means we will just pad out with the
    # end-of-sequence token for that output sample until done.
    finished = torch.zeros((tokens_batch.shape[0], 1), dtype=torch.bool, device=tokens_batch.device)

    for _ in range(max_new_tokens):
        # If we are completely finished, stop.
        if torch.all(finished):
            break

        # Only consider the previous N tokens.
        tokens_batch_context = tokens_batch[:, -context_size:]

        # Get logits without gradient calculation.
        with torch.no_grad():
            logits = model(tokens_batch_context)

        # Get the last logits vector in each sample.
        logits = logits[:,-1,:]

        # Do top-k sampling if specified.
        if top_k is not None:
            # Put a -inf tensor on the same device as the logits.
            neg_inf = torch.tensor(-torch.inf).to(logits.device)
            top_k_values, _ = torch.topk(logits, top_k)
            logits = torch.where(
                logits < top_k_values[...,-1].unsqueeze(1),
                neg_inf,
                logits
            )

        # Do multinomial selection and temperature scaling if specified.
        if temperature > 0.0:
            logits /= temperature
            probas = torch.softmax(logits, dim=-1)
            next_tokens = torch.multinomial(probas, 1)

        # Otherwise do greedy sampling.
        else:
            next_tokens = torch.argmax(logits, dim=-1, keepdim=True)

        # Check for stop token and finished state.
        if eos_id is not None:
            finished |= (next_tokens == eos_id)
            next_tokens = torch.where(finished, eos_id, next_tokens)

        tokens_batch = torch.concat((tokens_batch, next_tokens), dim=-1)

    return tokens_batch
In [68]:
tokens1 = text_to_token_ids("Every step moves you closer to", tokenizer_gpt2)
tokens2 = text_to_token_ids("I really love to eat chocolate", tokenizer_gpt2)
tokens = torch.stack((tokens1, tokens2)).squeeze(1)

result = generate(
    model=model,
    tokens_batch=tokens,
    max_new_tokens=16,
    context_size=8,
    temperature=5,
    top_k=3,
    eos_id=None
)

print(tokens)
print(result)
for output in result:
    print(">", token_ids_to_text(output, tokenizer_gpt2))
tensor([[ 6109,  2239,  6100,   345,  5699,   284],
        [   40,  1107,  1842,   284,  4483, 11311]])
tensor([[ 6109,  2239,  6100,   345,  5699,   284,   670,   319,   438, 18108,
         26269,   326,   339,   550,   587,   465,   898,  5975,    13,   198,
          5297,   438],
        [   40,  1107,  1842,   284,  4483, 11311,   832,   616,  5975,    13,
           402,  1617,   339,   550,  5975,   339,   326,   339,   438,  1169,
           691,   284]])
> Every step moves you closer to work on--had lent that he had been his own surprise.
Yes--
> I really love to eat chocolate through my surprise. Graft he had surprise he that he--the only to
In [69]:
# Check our work against Raschka.
torch.manual_seed(123)
token_ids = generate(
    model=model,
    tokens_batch=text_to_token_ids("Every effort moves you", tokenizer),
    max_new_tokens=15,
    context_size=GPT_CONFIG_124M["context_length"],
    top_k=25,
    temperature=1.4
)
print("Output text:\n", token_ids_to_text(token_ids, tokenizer))

# Expected result: Every effort moves you stand to work on surprise, a one of us had gone with random-
Output text:
 Every effort moves you stand to work on surprise, a one of us had gone with random-

Exercise 5.2¶

Play around with different temperatures and top-k settings. Based on your observations, can you think of applications where lower temperature and top-k settings are desired? Likewise, can you think of applications where higher temperature and top-k settings are preferred? (It’s recommended to also revisit this exercise at the end of the chapter after loading the pretrained weights from OpenAI.)

Lower temperature and top-k settings seems to be approximately the same thing has more memorization. When would I want the model to memorize and regurgitate? When I want it to follow instructions, write code — that sort of thing. At the opposite end of the spectrum, when I want more creativity, that's when I want more temperature and top-k.

Exercise 5.3¶

What are the different combinations of settings for the generate function to force deterministic behavior, that is, disabling the random sampling such that it always produces the same outputs similar to the generate_simple function?

If top-k is none and we don't do any temperature scaling we should get deterministic behavior. Also if top-k is 1, we should get deterministic behavior.

In [70]:
# Save the model weights.
torch.save(model.state_dict(), "model.pth")
In [71]:
# Load the model weights.
device = "cuda" if torch.cuda.is_available() else "cpu"
model = GPTModel(GPT_CONFIG_124M)
model.load_state_dict(torch.load("model.pth", map_location=device))
model.eval() # Best practice for inference.
print("Model parameters:", sum([p.numel() for p in model.parameters()]))
Model parameters: 162419712
In [72]:
# Save both model and optimizer state.
torch.save({
    "model_state_dict": model.state_dict(),
    "optimizer_state_dict": optimizer.state_dict(),
}, "model_and_optimizer.pth")
In [73]:
# Load model and optimizer state.
model_and_optimizer_state = torch.load("model_and_optimizer.pth", map_location=device)
model = GPTModel(GPT_CONFIG_124M)
model.load_state_dict(model_and_optimizer_state["model_state_dict"])
optimizer = torch.optim.AdamW(model.parameters(), lr=0.0004, weight_decay=0.1)
optimizer.load_state_dict(model_and_optimizer_state["optimizer_state_dict"])
model.train() # Get ready for additional training.
print("Model parameters:", sum([p.numel() for p in model.parameters()]))
Model parameters: 162419712

Exercise 5.4¶

After saving the weights, load the model and optimizer in a new Python session or Jupyter notebook file and continue pretraining it for one more epoch using the train_model_simple function.

I completed this exercise in llm_from_scratch_chap05_ex4.ipynb and got the following output:

Epoch 001, Step 00000
	Training loss: 0.28175944089889526
	Validation loss: 6.545217514038086	
Epoch 001, Step 00005
	Training loss: 0.2002061903476715
	Validation loss: 6.582545280456543	

Every effort moves you?"     I glanced after him, struck by his last word. Victor Grindle was, in fact, becoming the man of the moment--as Jack himself, one might put it, had been the man of the hour. The
In [75]:
# Run Raschka's code to download and load the gpt2 weights.
from gpt_download import download_and_load_gpt2
settings, params = download_and_load_gpt2(
    model_size="124M", models_dir="gpt2"
)
checkpoint: 100%|███████████████████████████████████████████████████████████████████| 77.0/77.0 [00:00<00:00, 536kiB/s]
encoder.json: 100%|██████████████████████████████████████████████████████████████| 1.04M/1.04M [00:00<00:00, 3.35MiB/s]
hparams.json: 100%|█████████████████████████████████████████████████████████████████| 90.0/90.0 [00:00<00:00, 519kiB/s]
model.ckpt.data-00000-of-00001: 100%|██████████████████████████████████████████████| 498M/498M [00:13<00:00, 36.6MiB/s]
model.ckpt.index: 100%|██████████████████████████████████████████████████████████| 5.21k/5.21k [00:00<00:00, 42.4MiB/s]
model.ckpt.meta: 100%|█████████████████████████████████████████████████████████████| 471k/471k [00:00<00:00, 2.06MiB/s]
vocab.bpe: 100%|███████████████████████████████████████████████████████████████████| 456k/456k [00:00<00:00, 1.76MiB/s]
In [76]:
settings
Out[76]:
{'n_vocab': 50257, 'n_ctx': 1024, 'n_embd': 768, 'n_head': 12, 'n_layer': 12}
In [77]:
params.keys()
Out[77]:
dict_keys(['blocks', 'b', 'g', 'wpe', 'wte'])
In [79]:
# Setup new config.
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},
}
model_name = "gpt2-small (124M)"
NEW_CONFIG = GPT_CONFIG_124M.copy()
NEW_CONFIG.update(model_configs[model_name])
NEW_CONFIG.update({"context_length": 1024})
NEW_CONFIG.update({"qkv_bias": True})
In [81]:
# Create a model with the new config.
gpt2 = GPTModel(NEW_CONFIG)
gpt2.eval()

# This is Raschka's function to assign data with a warning in the event of shape
# mismatches.
def assign(left, right):
    if left.shape != right.shape:
        raise ValueError(f"Shape mismatch. Left: {left.shape}, "
                          "Right: {right.shape}"
        )
    return torch.nn.Parameter(torch.tensor(right))
In [92]:
# And this is Raschka's function to read the gpt2 weights into our model,
# lightly adapted to suit the code which I authored.
# In his words it was a "lot of guesswork." So I'm just copy-pasting it.
# I would write it from scratch myself (as I've done with most of the rest
# of the code), but I don't think there's a pot of gold at the end of that
# particular rainbow.
import numpy as np

def load_weights_into_gpt(gpt, params):
    gpt.pos_emb.weight = assign(gpt.pos_emb.weight, params['wpe'])
    gpt.tok_emb.weight = assign(gpt.tok_emb.weight, params['wte'])

    for b in range(len(params["blocks"])):
        q_w, k_w, v_w = np.split(
            (params["blocks"][b]["attn"]["c_attn"])["w"], 3, axis=-1)
        gpt.xform_blocks[b].attention.W_q.weight = assign(
            gpt.xform_blocks[b].attention.W_q.weight, q_w.T)
        gpt.xform_blocks[b].attention.W_k.weight = assign(
            gpt.xform_blocks[b].attention.W_k.weight, k_w.T)
        gpt.xform_blocks[b].attention.W_v.weight = assign(
            gpt.xform_blocks[b].attention.W_v.weight, v_w.T)

        q_b, k_b, v_b = np.split(
            (params["blocks"][b]["attn"]["c_attn"])["b"], 3, axis=-1)
        gpt.xform_blocks[b].attention.W_q.bias = assign(
            gpt.xform_blocks[b].attention.W_q.bias, q_b)
        gpt.xform_blocks[b].attention.W_k.bias = assign(
            gpt.xform_blocks[b].attention.W_k.bias, k_b)
        gpt.xform_blocks[b].attention.W_v.bias = assign(
            gpt.xform_blocks[b].attention.W_v.bias, v_b)

        gpt.xform_blocks[b].attention.output_proj.weight = assign(
            gpt.xform_blocks[b].attention.output_proj.weight, 
            params["blocks"][b]["attn"]["c_proj"]["w"].T)
        gpt.xform_blocks[b].attention.output_proj.bias = assign(
            gpt.xform_blocks[b].attention.output_proj.bias, 
            params["blocks"][b]["attn"]["c_proj"]["b"])

        gpt.xform_blocks[b].feed_forward.layers[0].weight = assign(
            gpt.xform_blocks[b].feed_forward.layers[0].weight, 
            params["blocks"][b]["mlp"]["c_fc"]["w"].T)
        gpt.xform_blocks[b].feed_forward.layers[0].bias = assign(
            gpt.xform_blocks[b].feed_forward.layers[0].bias, 
            params["blocks"][b]["mlp"]["c_fc"]["b"])
        gpt.xform_blocks[b].feed_forward.layers[2].weight = assign(
            gpt.xform_blocks[b].feed_forward.layers[2].weight, 
            params["blocks"][b]["mlp"]["c_proj"]["w"].T)
        gpt.xform_blocks[b].feed_forward.layers[2].bias = assign(
            gpt.xform_blocks[b].feed_forward.layers[2].bias, 
            params["blocks"][b]["mlp"]["c_proj"]["b"])

        gpt.xform_blocks[b].norm1.scale = assign(
            gpt.xform_blocks[b].norm1.scale, 
            params["blocks"][b]["ln_1"]["g"])
        gpt.xform_blocks[b].norm1.shift = assign(
            gpt.xform_blocks[b].norm1.shift, 
            params["blocks"][b]["ln_1"]["b"])
        gpt.xform_blocks[b].norm2.scale = assign(
            gpt.xform_blocks[b].norm2.scale, 
            params["blocks"][b]["ln_2"]["g"])
        gpt.xform_blocks[b].norm2.shift = assign(
            gpt.xform_blocks[b].norm2.shift, 
            params["blocks"][b]["ln_2"]["b"])

    gpt.final_norm.scale = assign(gpt.final_norm.scale, params["g"])
    gpt.final_norm.shift = assign(gpt.final_norm.shift, params["b"])
    gpt.out_head.weight = assign(gpt.out_head.weight, params["wte"])
In [101]:
# Create a new model and load the gpt2 parameters into it. We force
# it to be on the cpu so we can compare it against Raschka's output.
device = "cpu"
load_weights_into_gpt(gpt2, params)
gpt2.to(device)
print("Parameters:", sum([p.numel() for p in gpt2.parameters()]))
Parameters: 163037184
In [102]:
# Test the gpt2 model out.
torch.manual_seed(123)
token_ids = generate(
    model=gpt2,
    tokens_batch=text_to_token_ids("Every effort moves you", tokenizer_gpt2).to(device),
    max_new_tokens=25,
    context_size=NEW_CONFIG["context_length"],
    top_k=50,
    temperature=1.5
)
print("Output text:\n", token_ids_to_text(token_ids, tokenizer_gpt2))
Output text:
 Every effort moves you toward finding an ideal new way to practice something!

What makes us want to be on top of that?


Expected output:

Output text:
 Every effort moves you toward finding an ideal new way to practice something!
What makes us want to be on top of that?

Exercise 5.5¶

Calculate the training and validation set losses of the GPTModel with the pretrained weights from OpenAI on the “The Verdict” dataset.

In [107]:
device = "cuda" if torch.cuda.is_available() else "cpu"
gpt2.to(device)
with torch.no_grad():
    avg_train_loss = get_loader_loss(train_loader, gpt2, device)
    avg_val_loss = get_loader_loss(val_loader, gpt2, device)
print("Average training data loss:", avg_train_loss)
print("Average validation data loss:", avg_val_loss)

# Raschka obtained:
# Training loss: 3.754748503367106
# Validation loss: 3.559617757797241
Average training data loss: tensor(3.7548, device='cuda:0')
Average validation data loss: tensor(3.5596, device='cuda:0')

Exercise 5.6¶

Experiment with GPT-2 models of different sizes—for example, the largest 1,558 million parameter model—and compare the generated text to the 124 million model.

In [108]:
settings, params = download_and_load_gpt2(
    model_size="1558M", models_dir="gpt2"
)
checkpoint: 100%|███████████████████████████████████████████████████████████████████| 77.0/77.0 [00:00<00:00, 615kiB/s]
encoder.json: 100%|██████████████████████████████████████████████████████████████| 1.04M/1.04M [00:00<00:00, 3.20MiB/s]
hparams.json: 100%|█████████████████████████████████████████████████████████████████| 91.0/91.0 [00:00<00:00, 940kiB/s]
model.ckpt.data-00000-of-00001: 100%|████████████████████████████████████████████| 6.23G/6.23G [02:38<00:00, 39.4MiB/s]
model.ckpt.index: 100%|███████████████████████████████████████████████████████████| 20.7k/20.7k [00:00<00:00, 128MiB/s]
model.ckpt.meta: 100%|███████████████████████████████████████████████████████████| 1.84M/1.84M [00:00<00:00, 4.29MiB/s]
vocab.bpe: 100%|███████████████████████████████████████████████████████████████████| 456k/456k [00:00<00:00, 2.11MiB/s]
In [111]:
model_name = "gpt2-xl (1558M)"
NEW_CONFIG = GPT_CONFIG_124M.copy()
NEW_CONFIG.update(model_configs[model_name])
NEW_CONFIG.update({"context_length": 1024})
NEW_CONFIG.update({"qkv_bias": True})

gpt2xl = GPTModel(NEW_CONFIG)
gpt2xl.eval()

device = "cuda" if torch.cuda.is_available() else "cpu"
load_weights_into_gpt(gpt2xl, params)
gpt2xl.to(device)
print("Parameters:", sum([p.numel() for p in gpt2.parameters()]))
Parameters: 163037184
In [112]:
torch.manual_seed(123)
token_ids = generate(
    model=gpt2xl,
    tokens_batch=text_to_token_ids("Every effort moves you", tokenizer_gpt2).to(device),
    max_new_tokens=25,
    context_size=NEW_CONFIG["context_length"],
    top_k=50,
    temperature=1.5
)
print("Output text:\n", token_ids_to_text(token_ids, tokenizer_gpt2))
Output text:
 Every effort moves you as far as the next. No amount (and I quote - "Nothing!)

Fulfills you (no matter