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.

In [1]:
import torch
import torch.nn as nn
In [2]:
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 [3]:
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 [4]:
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 [5]:
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 [6]:
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 [7]:
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 [8]:
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
}
In [9]:
# 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 [10]:
import tiktoken
tokenizer_gpt2 = tiktoken.get_encoding("gpt2")

# Load the verdict.
with open('the-verdict.txt', 'r', encoding='utf8') as f:
  text_data = f.read()

# Count characters and tokens.
print("# chars:", len(text_data))
print("# tokens:", len(tokenizer_gpt2.encode(text_data)))

# 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)
# chars: 20479
# tokens: 5145
Training data length: 18431
Test data length: 2048
In [11]:
# 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 [12]:
# 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 [13]:
# 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
    #for input_batch, target_batch in loader:
    #    loss = get_batch_loss(input_batch, target_batch, model, device)
    #    total_loss += loss
    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 [14]:
# 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 id 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 [15]:
# 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 [16]:
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 [17]:
# 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 [18]:
# 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 [19]:
# Load model and optimizer state.
device = "cuda" if torch.cuda.is_available() else "cpu"
model_and_optimizer_state = torch.load("model_and_optimizer.pth", map_location=device)
model = GPTModel(GPT_CONFIG_124M)
model.to(device)
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
In [20]:
# 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.
# NOTE: For this exercise, we train for just one more run.
num_epochs=1
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
)
Epoch 001, Step 00000
	Training loss: 0.2516915798187256
	Validation loss: 6.532669544219971	
Epoch 001, Step 00005
	Training loss: 0.25435277819633484
	Validation loss: 6.63294792175293	

Every effort moves you?"     I glanced after him, and uncertain. Stroud so when she began to stammer something about her poverty. I remember getting off a prodigious phrase about the sketch of the donkey. "There were days when I