Skip to content
ImagineWorld

Training Pipeline

node_idnode-book_llm-design-patterns_chapter-06-training-pipeline
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleTraining Pipeline
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we’ll explore the key components of an LLM training pipeline, from data ingestion and preprocessing to model architecture and optimization strategies.

You’ll gain insights into implementing effective monitoring and logging systems, ensuring you can track your model’s progress and make data-driven decisions throughout the training process.

In this chapter, we’ll be covering the following topics:

  • Components of a training pipeline
  • Data input and preprocessing
  • LLM architecture design considerations
  • Loss functions and optimization strategies
  • Logging
  • Pipeline modularity and reusability
  • Scaling your training pipeline for larger models

An LLM training pipeline consists of several interconnected steps, each playing a role in the model’s development. We’ll present a basic pipeline here and explore many of these components in further depth as we progress through the chapter:

  • Dataset creation: Builds preprocessed data into a format suitable for training, often involving shuffling and batching.
  • Model architecture: Defines the structure of the LLM, including the number of layers, attention mechanisms, and other architectural choices.
  • Training loop: The core of the pipeline where the model learns from the data through forward and backward passes.
  • Optimization: Handles parameter updates based on calculated gradients and chosen optimization strategies.
  • Evaluation: Regularly assesses model performance on validation data to track progress and prevent overfitting. We will cover this topic in more detail in Chapter 14.
  • Checkpointing: Periodically saves model states to resume training or use for inference. We will cover this topic in detail in Chapter 10.
  • Logging and monitoring: Continuously tracks training metrics and resource utilization.

We’ll implement a basic LLM training pipeline using PyTorch and the Transformers library:

from torch.utils.data import DataLoader
from transformers import (
AutoTokenizer, AutoModelForCausalLM, AdamW,
get_linear_schedule_with_warmup
from datasets import load_dataset
import torch
from torch.nn import functional as F
import wandb

PyTorch is a popular deep learning framework that enables building neural networks through a dynamic computational graph, while the Transformers library implements the popular transformer architecture we discussed in Chapter 1.

The following code block demonstrates the loading of a Wikipedia dataset and the tokenization of its text content using a pre-trained GPT-2 tokenizer:

# Dataset Creation: Ingestion and Preprocessing
dataset = load_dataset("wikipedia", "20220301.en", split="train")
tokenizer = AutoTokenizer.from_pretrained("gpt2")
def preprocess_function(examples):
return tokenizer(examples["text"], truncation=True,
max_length=512, padding="max_length")
tokenized_dataset = dataset.map(preprocess_function,
batched=True, remove_columns=dataset.column_names)

In the preceding code block, we’re setting up the data ingestion and preprocessing components of our pipeline. We use the Hugging Face Datasets library to load a Wikipedia dataset, which provides a large corpus of text suitable for training an LLM. We then initialize a tokenizer based on the GPT-2 model, which will be used to preprocess our text data.

The preprocess_function defined above takes raw text examples and tokenizes them, truncating to a maximum length of 512 tokens and padding shorter sequences to this length. This ensures all our input sequences have the same length, which is necessary for efficient batch processing. We choose a max_length value of 512 as a balance between context length and memory efficiency. Longer sequences provide more context but require more memory and computation. Some recent LLM models, such as Gemini 1.5 Pro, can get as many as 2 million tokens in content length (https://cloud.google.com/vertex-ai/generative-ai/docs/long-context).

Next, we create our training DataLoader, which will handle batching and shuffling of our dataset during training:

# Dataset Creation: Loading
train_dataloader = DataLoader(
tokenized_dataset, shuffle=True, batch_size=8)

We set the batch size to 8, which is chosen as a balance between memory usage and training efficiency. Larger batch sizes can lead to faster training but require more GPU memory. For LLMs, which often have a large number of parameters, smaller batch sizes are often necessary to fit the model and data in GPU memory.

We then initialize our model architecture using the pre-trained GPT-2 model. This gives us a strong starting point for our LLM, leveraging the knowledge already captured in the pre-trained weights. Using a pre-trained model as a starting point is a common practice in transfer learning, allowing us to benefit from the general language understanding learned by the model on a large corpus of text. See the following code:

# Model Architecture
model = AutoModelForCausalLM.from_pretrained("gpt2")
# Optimization
optimizer = AdamW(model.parameters(), lr=5e-5)

As shown in the preceding code, for optimization, we use the AdamW optimizer, which is an improved version of Adam that implements weight decay correctly. We set the learning rate (lr) to 5e-5, which is a common choice for fine-tuning pre-trained models. The learning rate is a hyperparameter that determines the size of the adjustments made to the model’s weights during training, influencing how quickly and effectively the model learns.

This learning rate offers a good balance between learning speed and stability. It’s small enough to allow for fine-grained updates to the pre-trained weights, but large enough to allow meaningful learning to occur.

The subsequent code blocks outline the essential stages of training a language model, including setting up the training process, initializing a logging tool, executing the main training loop with forward and backward passes, performing evaluation to assess model performance, and saving checkpoints of the model’s parameters during training.

  1. We start by setting up the
    num_epochs = 3
    num_training_steps = num_epochs * len(train_dataloader)
    lr_scheduler = get_linear_schedule_with_warmup(
    optimizer, num_warmup_steps=100,
    num_training_steps=num_training_steps)
  2. Then, we initialize the Weights & Biases (wandb) library for experiment tracking and logging of
    wandb.init(project="llm_training", name="gpt2_finetune")
    device = torch.device("cuda" if torch.cuda.is_available()
    else "cpu")
    model.to(device)
    for epoch in range(num_epochs):
    model.train()
    for batch in train_dataloader:
    batch = {k: v.to(device) for k, v in batch.items()}
    outputs = model(batch)
    loss = outputs.loss
    loss.backward()
    optimizer.step()
    lr_scheduler.step()
    optimizer.zero_grad()
    wandb.log({"loss": loss.item()})
  3. We next implement an evaluation phase to assess the model’s performance on the
    model.eval()
    eval_loss = 0
    with torch.no_grad():
    for batch in train_dataloader: # Using training data for simplicity
    batch = {k: v.to(device) for k, v in batch.items()}
    outputs = model(batch)
    eval_loss += outputs.loss.item()
    eval_loss /= len(train_dataloader)
    wandb.log({"eval_loss": eval_loss})
  4. Finally, we save a checkpoint of the model’s state dictionary at the end of
    torch.save(model.state_dict(),
    f"model_checkpoint_epoch_{epoch}.pt")
    wandb.finish()

These snippets implement the training loop, evaluation, checkpointing, and logging components of our pipeline:

We set the number of training epochs to 3, which means the model will iterate through the entire dataset three times during training. This hyperparameter can be adjusted based on your specific needs – increasing it may lead to better model performance if the model is underfitting, and decreasing it can help prevent overfitting and reduce training time. Monitor validation loss during training to determine the optimal number of epochs for your particular dataset and model architecture.

The learning rate scheduler implements a linear decay with warmup, which helps stabilize training in the early stages and then gradually reduces the learning rate to fine-tune the model more precisely. The learning rate controls how much a model adjusts its internal parameters during training – a higher rate means bigger adjustments but potential overshooting, while a lower rate means more precise but slower learning.

We use Weights & Biases (wandb) for logging, which allows us to track our training progress in real time and compare different runs (https://wandb.ai/site). This is crucial for monitoring the training process and making informed decisions about hyperparameter tuning and model architecture changes.

The training loop iterates over our data for the specified number of epochs. In each iteration, we do the following:

  1. Move the batch to the appropriate device (GPU if available)
  2. Perform a forward pass through the model
  3. Calculate the loss
  4. Perform backpropagation
  5. Update the model parameters
  6. Update the learning rate scheduler
  7. Log the training loss

After each epoch, we perform a simple evaluation of the training data (in a real scenario, you’d use a separate validation set), log the evaluation loss, and save a checkpoint of the model. Checkpointing is needed for long-running training processes, allowing us to resume training from a saved state if needed.

As we’ve seen, the training pipeline involves several essential steps. Before the model architecture and training loop can function effectively, however, we must address data input and preprocessing, which we will discuss next.

Efficient data handling is crucial for LLM training, as we discussed in Part 1 of this book. Here, let’s explore advanced techniques for data input and preprocessing:

  1. Import the required
    from datasets import load_dataset, concatenate_datasets
    from transformers import AutoTokenizer
    from torch.utils.data import DataLoader
    import numpy as np
  2. Load and combine
    wiki_dataset = load_dataset("wikipedia", "20220301.en", split="train")
    books_dataset = load_dataset("bookcorpus", split="train")
    # Combine datasets
    combined_dataset = concatenate_
    datasets([wiki_dataset, books_dataset])
  3. Initialize the tokenizer and preprocess
    tokenizer = AutoTokenizer.from_pretrained("gpt2")
    def preprocess_function(examples):
    # Tokenize the texts
    tokenized = tokenizer(
    examples["text"], truncation=True, max_length=1024)
    # Create input_ids and attention_mask
    input_ids = tokenized["input_ids"]
    attention_mask = tokenized["attention_mask"]
    # Create labels for causal language modeling
    labels = [
    ids[1:] + [tokenizer.eos_token_id] for ids in input_ids]
    return {"input_ids": input_ids,
    "attention_mask": attention_mask, "labels": labels}
    # Apply preprocessing
    tokenized_dataset = combined_dataset.map(
    preprocess_function,
    batched=True,
    remove_columns=combined_dataset.column_names,
    num_proc=4 # Adjust based on your CPU cores
    )
  4. Create
    train_dataloader = DataLoader(
    tokenized_dataset,
    shuffle=True,
    batch_size=16,
    collate_fn=lambda x: {k: np.stack([xi[k] for xi in x])
    for k in x[0]}
    )

In this enhanced preprocessing pipeline, we’re loading multiple datasets to increase the diversity of our training data. This is needed for LLMs, as a diverse dataset helps the model learn a broader range of language patterns and knowledge.

We use a longer max_length value of 1024 tokens to provide more context to the model. This increased context length allows the model to capture longer-range dependencies in the text, which can be beneficial for many language-understanding tasks. However, it also increases memory usage and computational requirements, so there’s a trade-off to consider.

The preprocess_function now creates labels for causal language modeling by shifting the input sequences. This is a common approach for training language models, where the model’s task is to predict the next token given the previous tokens. During preprocessing, handling edge cases such as emojis, URLs, and non-standard characters can enhance model performance. Emojis can convey nuanced emotions and context, requiring appropriate encoding or tokenization to preserve their meaning without introducing noise. URLs often contain valuable information but can vary widely in structure, so they might be replaced with placeholder tokens to maintain consistency while preventing the model from overfitting to specific links. Non-standard characters, including symbols from different languages or special punctuation, need careful normalization or removal to reduce complexity and avoid confusion during training. By addressing these edge cases through strategies such as normalization, token replacement, and selective filtering, preprocessing pipelines can better prepare diverse and complex data, enhancing the robustness and accuracy of the resulting language models.

We use multiprocessing (num_proc=4) to speed up the preprocessing. The number of processes should be adjusted based on your CPU cores and available memory. Multiprocessing can significantly reduce preprocessing time, especially for large datasets.

The batch size is increased to 16, which is more suitable for larger GPU memory. The custom collate_fn in the DataLoader ensures proper batching of our preprocessed data. This function stacks the arrays for each key in the batch, creating tensor-like structures that can be efficiently processed by PyTorch.

With the data appropriately prepared, we now turn our attention to the LLM architecture design considerations, which dictate the model’s capacity to effectively learn from and understand data input.

When designing the architecture for an LLM, several factors come into play.

Here are the key factors influencing LLM architecture:

  • Vocabulary size: Determines the size of the input and output embedding layers
  • Maximum sequence length (context size): Defines the amount of preceding text the model can consider
  • Embedding dimension: Specifies the size of each token’s vector representation, influencing the model’s ability to capture information
  • Number of transformer layers: Represents the depth of the network, impacting the complexity of patterns the model can learn
  • Number of attention heads: Allows the model to attend to different parts of the input simultaneously
  • Model size (number of parameters): Overall capacity of the model, influenced by embedding dimension, number of layers, and attention heads
  • Dataset size: The amount and diversity of training data
  • Number of training steps: The duration of the optimization process
  • Computational resources: Hardware constraints that affect model size, training speed, and overall feasibility.
  • Risk of overfitting: Higher with larger models and smaller datasets
  • Data quality: The cleanliness and relevance of the training data
  • Efficiency of model architecture: Design choices that can improve performance without drastically increasing model size
  • Training algorithms: Optimization techniques and strategies
  • Data curation practices: Methods for selecting and preparing training data
  • Test time compute: Computational resources available during inference

In the following code block, we provide examples of configuring some of these factors using a GPT-2 style language model, specifying key architectural parameters.

from transformers import GPT2Config, GPT2LMHeadModel
# Define custom model configuration
config = GPT2Config(
vocab_size=50257, # GPT-2 vocabulary size
n_positions=1024, # Maximum sequence length
n_ctx=1024, # Context size
n_embd=768, # Embedding dimension
n_layer=12, # Number of transformer layers
n_head=12 # Number of attention heads
)
# Initialize the model with custom configuration
model = GPT2LMHeadModel(config)
print(f"Model parameters: {model.num_parameters():,}")

This configuration creates a GPT-2 style model with 12 layers and 12 attention heads. Let’s break down the key parameters:

  • vocab_size: Set to 50257, which is the vocabulary size of the original GPT-2 model. This determines the size of the embedding layer and the output layer.
  • n_positions and n_ctx: Both are set to 1024, matching our preprocessing step. This defines the maximum sequence length the model can handle.
  • n_embd: The embedding dimension, set to 768. This determines the size of the hidden states throughout the model.
  • n_layer: The number of transformer layers, set to 12. More layers can capture more complex patterns but increase computational requirements.
  • n_head: The number of attention heads, set to 12. Multiple attention heads allow the model to focus on different aspects of the input simultaneously.

The embedding dimension of 768 and the 12 layers provide a balanced trade-off between model capacity and computational efficiency. This configuration results in a model with about 124 million parameters, which is substantial but still trainable on common GPU hardware.

For larger models, you might increase n_layer, n_embd, and n_head. However, this would also increase the computational requirements and the risk of overfitting, especially on smaller datasets. When scaling up, consider techniques such as gradient accumulation, mixed precision training, and distributed training to manage the increased computational load.

In a broader scope, scaling laws can be considered. The scaling laws for LLMs describe how performance improves predictably as three key factors increase: model size (number of parameters), dataset size (amount of training data), and the number of training steps (optimization iterations). Specifically, larger models tend to capture more complex patterns and exhibit better generalization, larger datasets provide more diverse information for learning, and more training steps allow the model to refine its understanding and reduce errors. For optimal performance, these factors should scale proportionally – for instance, increasing the model size should be matched by a corresponding increase in dataset size and training steps. This balanced scaling ensures that each component supports the others, preventing bottlenecks such as overfitting smaller models on vast datasets or undertraining large models with insufficient data.

However, recent advancements and practical challenges have shown that simply scaling these factors is not always sufficient for continual performance improvements. Issues such as diminishing returns, where each additional parameter or data point contributes less to overall performance, have become more apparent. Additionally, the immense computational and energy resources required for training increasingly large models raise sustainability and accessibility concerns. Data quality also becomes a critical factor, as larger datasets may introduce more noise and biases, potentially degrading model performance. For more details about this, please see the article at https://www.pcgamer.com/software/ai/open-ai-co-founder-reckons-ai-training-has-hit-a-wall-forcing-ai-labs-to-train-their-models-smarter-not-just-bigger/.

To address these challenges, researchers are exploring more efficient model architectures, improved training algorithms, better data curation practices, and test time compute. See my Medium article for more details on test time compute: https://kenhuangus.medium.com/test-time-compute-3633a4c55716

At the beginning of 2025, DeepSeek (an AI startup in China) announced some model training innovations by introducing a suite of techniques aimed at significantly increasing efficiency and reducing costs, while simultaneously enhancing the model’s reasoning capabilities (https://arxiv.org/abs/2501.12948). Unlike traditional approaches that rely heavily on vast computational resources and human-supervised fine-tuning, DeepSeek leverages large-scale reinforcement learning focused on reasoning tasks, using automated reward systems rather than human feedback. Key innovations include multi-token prediction, which allows the model to learn from multiple future tokens at once, increasing sample efficiency, and speeding up training. DeepSeek also employs a mixture-of-experts architecture to activate only relevant sub-networks for each task, thus reducing computational load. By optimizing both algorithms and hardware, DeepSeek has managed to train highly capable models at a fraction of the cost and time required by competitors, setting new standards for open, efficient, and powerful AI development.

Having explored the architectural design considerations and model training innovations for LLMs — along with a code example demonstrating how to configure model training parameters — we are now ready to examine how these architectural choices are actually learned during training. In this next section, we will discuss the loss function and optimization strategies, which serve as the engine that drives the model to adjust its internal parameters based on both the training data and the architecture we have defined.

Loss functions and optimization strategies

Section titled “Loss functions and optimization strategies”

LLMs typically use cross-entropy loss for training. This approach measures the difference between the model’s predicted probability distribution of words and the actual distribution in the training data. By minimizing this loss, LLMs learn to generate more accurate and contextually appropriate text. Cross-entropy loss is particularly well-suited for language tasks due to its ability to handle the high dimensionality and discrete nature of textual data.

Let’s implement this along with some advanced optimization techniques:

  1. First, we import the required PyTorch libraries and specific modules from the Transformers library
    import torch
    from torch.optim import AdamW
    from transformers import get_linear_schedule_with_warmup
  2. Next, we configure the AdamW optimizer with a specified learning rate and
    optimizer = AdamW(model.parameters(), lr=5e-5,
    weight_decay=0.01)
  3. Then, we define a linear learning rate scheduler with a
    num_epochs = 3
    total_steps = len(train_dataloader) * num_epochs
    scheduler = get_linear_schedule_with_warmup(
    optimizer,
    num_warmup_steps=100,
    num_training_steps=total_steps
    )
  4. Subsequently, we set up the training device and initiate the main
    device = torch.device("cuda" if torch.cuda.is_available()
    else "cpu")
    model.to(device)
    for epoch in range(num_epochs):
    model.train()
    for batch in train_dataloader:
    batch = {k: torch.tensor(v).to(device)
    for k, v in batch.items()
    }
    outputs = model(batch)
    loss = outputs.loss
    loss.backward()
  5. Finally, we implement gradient clipping to prevent exploding gradients
    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    optimizer.step()
    scheduler.step()
    optimizer.zero_grad()

In this optimization setup, we use the AdamW optimizer with a learning rate of 5e-5 and weight decay of 0.01. The algorithm adapts the learning rate for each parameter based on the first and second moments of the gradients, allowing it to handle sparse gradients effectively. This makes AdamW particularly useful for training large neural networks.

The weight decay of 0.01 adds a small regularization term to the loss function, which can help prevent overfitting by penalizing large weight values.

We implement a learning rate scheduler with warmup. The warmup phase helps stabilize training in the early stages by gradually increasing the learning rate from a very small value. After the warmup phase, the learning rate decreases linearly. This schedule can help the model converge to a better optimum.

In the training loop, we implement gradient clipping with a max_norm value of 1.0. Gradient clipping prevents exploding gradients by scaling down gradient values that exceed a certain threshold. This is particularly important for LLMs, which can be prone to unstable gradients due to their depth and the long-range dependencies they capture.

In this section, we learned about AdamW optimization, learning rate scheduling with warmup, and gradient clipping for stable LLM training. Next, we talk about logging the training process, which is crucial for monitoring progress and using tools like TensorBoard to gain insights for improvement.

Effective logging can be useful for tracking the progress of LLM training.

The following code blocks demonstrate how to integrate TensorBoard for effective logging during the training of an LLM using PyTorch. Let’s break down each part.

  1. We first initialize the TensorBoard SummaryWriter for logging
    from torch.utils.tensorboard import SummaryWriter
    import time
    # Initialize TensorBoard writer
    writer = SummaryWriter()
  2. Then, we set the model to training mode, initialize variables for tracking loss, define the logging interval, and record the start time to monitor
    model.train()
    total_loss = 0
    log_interval = 100
    start_time = time.time()
  3. Then, we move on to the training loop. We process each batch by moving data to the appropriate device, performing forward and backward passes, applying gradient clipping, and updating the model’s parameters using the optimizer
    for i, batch in enumerate(train_dataloader):
    batch = {k: torch.tensor(v).to(device)
    for k, v in batch.items()}
    outputs = model(batch)
    loss = outputs.loss
    total_loss += loss.item()
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(),
    max_norm=1.0)
    optimizer.step()
    scheduler.step()
    optimizer.zero_grad()
  4. We log the training metrics to TensorBoard at specified intervals, calculate the average loss, measure the elapsed time, print the progress to the console, and reset the tracking variables for the
    if (i + 1) % log_interval == 0:
    cur_loss = total_loss / log_interval
    elapsed = time.time() - start_time
    writer.add_scalar(
    'training_loss', cur_loss, global_step=i
    )
    writer.add_scalar(
    'learning_rate', scheduler.get_last_lr()[0],
    global_step=i
    )
    print(
    f'| epoch {epoch:3d} '
    f'| {i:5d}/{len(train_dataloader):5d} batches | '
    f'lr {scheduler.get_last_lr()[0]:02.2f} | '
    f'ms/batch {elapsed * 1000 / log_interval:5.2f} | '
    f'loss {cur_loss:5.2f}'
    )
    total_loss = 0
    start_time = time.time()
    writer.close()
    This enhanced training loop uses TensorBoard for logging training loss and learning rate. TensorBoard is a powerful tool for visualizing training progress and comparing different runs. We log the following metrics:
    • Training loss: This is the average loss over the last log_interval batches. A decreasing trend in this metric indicates that the model is learning.
      • Learning rate: We log the current learning rate to visualize how it changes over time due to our learning rate scheduler.

We set log_interval to 100, meaning we log and print out progress information every 100 batches. This interval strikes a balance between getting frequent updates and not slowing down training too much with logging operations. You may need to adjust this based on your dataset size and training speed.

The output or log information includes the following:

  • Current epoch and batch number
  • Current learning rate
  • Time per batch (in milliseconds)
  • Current loss

This detailed logging allows you to monitor the training process closely, helping you identify issues such as unstable loss, learning rate problems, or unexpectedly slow training.

Modularity and reusability are fundamental principles for building efficient pipelines because they make code more maintainable, adaptable, and reliable. By breaking down a pipeline into independent, reusable modules (such as data preprocessing, model training, and evaluation components), developers can easily modify individual parts without affecting others, test each component separately, and reuse proven code across different projects.

This approach not only saves development time but also ensures consistency in operations, reduces the chance of errors, and makes it easier for teams to collaborate by working on separate modules while maintaining clear interfaces between components. In the case of training pipelines, encapsulating processes in reusable classes allows for flexible configuration, seamless integration with different datasets, and straightforward sharing of standardized implementations across multiple projects.

To make our pipeline more modular and reusable, let’s encapsulate our training process in a class:

  1. We start with
    class LLMTrainer:
    def __init__(self, model, train_dataloader, optimizer,
    scheduler, device
    ):
    self.model = model
    self.train_dataloader = train_dataloader
    self.optimizer = optimizer
    self.scheduler = scheduler
    self.device = device
    self.writer = SummaryWriter()
  2. Then, we define the train epoch function. The function sets the model to training mode and iterates over the training data, processing each batch by computing the loss, performing backpropagation with gradient clipping, and updating the model parameters using the optimizer
    def train_epoch(self):
    self.model.train()
    total_loss = 0
    log_interval = 100
    start_time = time.time()
    for i, batch in enumerate(self.train_dataloader):
    batch = {k: torch.tensor(v).to(self.device)
    for k, v in batch.items()
    }
    outputs = self.model(batch)
    loss = outputs.loss
    total_loss += loss.item()
    loss.backward()
    torch.nn.utils.clip_grad_norm_(
    self.model.parameters(), max_norm=1.0)
    self.optimizer.step()
    self.scheduler.step()
    self.optimizer.zero_grad()
  3. Next, we periodically log the training progress to both TensorBoard and the console by checking if the current batch index is a multiple of the log_interval; if it is, we calculate the average loss and elapsed time since the last log, record the training loss and learning rate to TensorBoard using the SummaryWriter, print a formatted progress update including batch number, learning rate, milliseconds per batch, and current loss to the console, and then reset the accumulated total_loss and start_time for the next logging interval:
    if (i + 1) % log_interval == 0:
    cur_loss = total_loss / log_interval
    elapsed = time.time() - start_time
    self.writer.add_scalar(
    'training_loss', cur_loss, global_step=i
    )
    self.writer.add_scalar(
    'learning_rate',
    self.scheduler.get_last_lr()[0],
    global_step=i
    )
    print(
    f'| {i:5d}/'
    f'{len(self.train_dataloader):5d} '
    f'batches | '
    f'lr '
    f'{self.scheduler.get_last_lr()'
    f'[0]:02.2f} | '
    f'ms/batch '
    f'{elapsed * 1000 / log_interval:5.2f} '
    f'| '
    f'loss '
    f'{cur_loss:5.2f}'
    )
    total_loss = 0
    start_time = time.time()
  4. Next, the train function orchestrates the training process by looping through the specified number of epochs, printing a message at the start of each epoch, invoking the train_epoch method to perform training for that epoch, and, finally, closing the writer once all epochs are completed. It serves as the main entry point for training, providing a structure where additional features such as validation and checkpointing can be integrated
    def train(self, num_epochs):
    for epoch in range(num_epochs):
    print(f'Starting epoch {epoch+1}')
    self.train_epoch()
    # Here you could add validation, checkpointing, etc.
    self.writer.close()
  5. Lastly, we instantiate the LLMTrainer class with the specified model, training data loader, optimizer, scheduler, and device. Then, the training process is started by calling the train method to execute three full training epochs, thereby initiating and managing the model’s
    trainer = LLMTrainer(model, train_dataloader,
    optimizer, scheduler, device)
    trainer.train(num_epochs=3)

This modular design offers several advantages:

  • Encapsulation: All the training logic is contained within the LLMTrainer class, making it easier to manage and understand.
  • Reusability: You can easily use this trainer for different models or datasets by creating a new instance with different parameters.
  • Extensibility: The class structure makes it easy to add new functionality. For example, you could add methods for validation, checkpointing, or early stopping.
  • Separation of concerns: The training logic is separated from the model definition and data preparation, following good software engineering principles.

The following log demonstrates the training process over 3 epochs, with periodic logging every 100 batches. Each log entry includes the current batch number, total batches, learning rate, milliseconds per batch, and the average loss:

Starting epoch 1
| 100/1000 batches | lr 0.01 | ms/batch 45.67 | loss 2.35
| 200/1000 batches | lr 0.01 | ms/batch 44.89 | loss 2.10
| 300/1000 batches | lr 0.01 | ms/batch 46.12 | loss 1.95
| 400/1000 batches | lr 0.01 | ms/batch 45.50 | loss 1.80
| 500/1000 batches | lr 0.01 | ms/batch 44.75 | loss 1.65
| 600/1000 batches | lr 0.009 | ms/batch 45.30 | loss 1.50
| 700/1000 batches | lr 0.009 | ms/batch 44.95 | loss 1.40
| 800/1000 batches | lr 0.009 | ms/batch 45.10 | loss 1.30
| 900/1000 batches | lr 0.009 | ms/batch 45.00 | loss 1.25
| 1000/1000 batches | lr 0.009 | ms/batch 44.80 | loss 1.20
Starting epoch 2
| 100/1000 batches | lr 0.009 | ms/batch 44.60 | loss 1.18
| 200/1000 batches | lr 0.009 | ms/batch 44.70 | loss 1.15
| 300/1000 batches | lr 0.009 | ms/batch 44.80 | loss 1.12
| 400/1000 batches | lr 0.008 | ms/batch 44.50 | loss 1.10
| 500/1000 batches | lr 0.008 | ms/batch 44.60 | loss 1.08
| 600/1000 batches | lr 0.008 | ms/batch 44.55 | loss 1.05
| 700/1000 batches | lr 0.008 | ms/batch 44.65 | loss 1.03
| 800/1000 batches | lr 0.007 | ms/batch 44.50 | loss 1.00
| 900/1000 batches | lr 0.007 | ms/batch 44.60 | loss 0.98
| 1000/1000 batches | lr 0.007 | ms/batch 44.55 | loss 0.95
Starting epoch 3
| 100/1000 batches | lr 0.007 | ms/batch 44.50 | loss 0.93
| 200/1000 batches | lr 0.007 | ms/batch 44.60 | loss 0.90
| 300/1000 batches | lr 0.006 | ms/batch 44.55 | loss 0.88
| 400/1000 batches | lr 0.006 | ms/batch 44.50 | loss 0.85
| 500/1000 batches | lr 0.006 | ms/batch 44.60 | loss 0.83
| 600/1000 batches | lr 0.006 | ms/batch 44.55 | loss 0.80
| 700/1000 batches | lr 0.005 | ms/batch 44.50 | loss 0.78
| 800/1000 batches | lr 0.005 | ms/batch 44.60 | loss 0.75
| 900/1000 batches | lr 0.005 | ms/batch 44.55 | loss 0.73
| 1000/1000 batches | lr 0.005 | ms/batch 44.50 | loss 0.70
Training completed. Writer closed.

Here is an explanation of the above simulated log:

  • Epoch start: Each epoch begins with a message such as Starting epoch 1, indicating the commencement of a new training cycle
  • Batch logging: Every 100 batches, the following information is logged:
    • Batch progress: Displays the current batch number out of the total batches, such as 100/1000 batches
      • Learning rate (lr): Shows the current learning rate, which may decrease over epochs due to the scheduler, such as lr 0.01
      • Milliseconds per batch (ms/batch): Indicates the time taken to process each batch, such as ms/batch 45.67
      • Loss: Represents the average loss over the last 100 batches, showing the model’s performance, such as loss 2.35
  • Learning rate schedule: Notice how the learning rate decreases over epochs, reflecting the scheduler’s adjustments to facilitate better convergence
  • Training completion: After all epochs are completed, a final message (Training completed. Writer closed.) indicates the end of the training process and the closure of the logging writer

The log provides a clear overview of the training dynamics, allowing developers and researchers to monitor the model’s learning progress, adjust hyperparameters if necessary, and ensure that the training is proceeding as expected.

Scaling your training pipeline for larger models

Section titled “Scaling your training pipeline for larger models”

To train larger models, we need to employ techniques such as gradient accumulation and mixed precision training.

To train very large language models that might not fit on a single GPU, the following code introduces a special LargeScaleLLMTrainer. It uses two main tricks to handle this:

First, gradient accumulation allows us to simulate having access to a larger GPU. Instead of updating the model’s parameters after every small batch of data, we process several small batches, accumulating their gradients along the way. Only after a predefined number of batches do we perform an actual update to the model’s parameters. This technique enables the model to learn as if it had seen a much larger batch of data, without requiring the memory capacity of an extremely large GPU.

Second, it employs mixed precision training, a technique where the computer performs many calculations using smaller, lower-precision numbers (which require less memory and are faster to compute), while reserving higher-precision numbers for situations where accuracy is critical. This approach accelerates training and reduces overall memory usage. To mitigate potential issues that can arise from using lower-precision values, GradScaler is used to maintain numerical stability during backpropagation.

The following code defines how this special trainer works, including how it processes data, calculates the loss, and updates the model’s learning using these tricks. It also still includes important steps like making sure the gradients (how the model should change) don’t get too big and logging progress so we can see how the training is going. Finally, it shows a simple example of how to use this special trainer. Now, let us break it into several parts:

  1. Let us start by importing the relevant Python package and defining
    import torch.cuda.amp as amp
    class LargeScaleLLMTrainer(LLMTrainer):
    def __init__(self, model, train_dataloader,
    optimizer, scheduler, device, accumulation_steps=4
    ):
    super().__init__(model, train_dataloader,
    optimizer, scheduler, device)
    self.accumulation_steps = accumulation_steps
    self.scaler = amp.GradScaler()
  2. We can then define the
    def train_epoch(self):
    self.model.train()
    total_loss = 0
    log_interval = 100
    start_time = time.time()
    for i, batch in enumerate(self.train_dataloader):
    batch = {
    k: torch.tensor(v).to(self.device)
    for k, v in batch.items()
    }
    with amp.autocast():
    outputs = self.model(batch)
    loss = outputs.loss / self.accumulation_steps
    self.scaler.scale(loss).backward()
  3. Then, we implement the following code block, which updates the model’s parameters, learning rate, and gradient scaler only after processing a defined number of batches (accumulation_steps), effectively simulating a larger batch size while managing
    if (i + 1) % self.accumulation_steps == 0:
    self.scaler.unscale_(self.optimizer)
    torch.nn.utils.clip_grad_norm_(
    self.model.parameters(), max_norm=1.0
    )
    self.scaler.step(self.optimizer)
    self.scaler.update()
    self.scheduler.step()
    self.optimizer.zero_grad()
    total_loss += loss.item() * self.accumulation_steps
  4. We then periodically calculate and log the average training loss and learning rate to TensorBoard, while also printing a summary of the current training progress to the console at intervals defined log_interval
    if (i + 1) % log_interval == 0:
    cur_loss = total_loss / log_interval
    elapsed = time.time() start_time
    self.writer.add_scalar('training_loss',
    cur_loss, global_step=i)
    self.writer.add_scalar('learning_rate',
    self.scheduler.get_last_lr()[0],
    global_step=i)
    print(
    f'| {i:5d}/{len(self.train_dataloader):5d}
    batches | '
    f'lr {self.scheduler.get_last_lr()[0]:02.2f}
    | '
    f'ms/batch {elapsed * 1000 /
    log_interval:5.2f} | '
    f'loss {cur_loss:5.2f}'
    )
    total_loss = 0
    start_time = time.time()
  5. We demonstrate the initialization and execution of a large-scale language model
    large_trainer = LargeScaleLLMTrainer(
    model, train_dataloader, optimizer, scheduler, device)
    large_trainer.train(num_epochs=3)
    This enhanced trainer uses two key techniques for scaling to larger models:
    • Gradient accumulation: We update weights every four batches (set by accumulation_steps). This allows us to effectively increase the batch size without increasing memory usage, which is effective for training large models on limited GPU memory. We divide the loss by accumulation_steps to maintain the same effective learning rate.
      • Mixed precision training: We use PyTorch’s Automatic Mixed Precision (AMP) to perform computations in float16, where possible, while maintaining float32 master weights. This can significantly speed up training and reduce memory usage, especially on modern GPUs with tensor cores.

GradScaler is used to prevent underflow in float16 calculations. It scales the loss to prevent small gradient values, then unscales before the optimizer step.

We still apply gradient clipping, but now it’s done after unscaling the gradients to ensure we’re clipping the true gradient values.

For even larger models, you might consider techniques such as model parallelism (splitting the model across multiple GPUs), pipeline parallelism (splitting the model into stages), or using specialized libraries such as DeepSpeed or Megatron-LM. These advanced techniques allow the training of models with billions of parameters across multiple GPUs or even multiple machines. Memory offloading can be a good alternative when GPU memory is insufficient to handle vast amounts of data and model parameters. Memory offloading involves transferring parts of the model’s data or computations to alternative memory storage, such as Non-Volatile Memory Express (NVMe) SSDs. By leveraging NVMe memory, which offers high-speed data access compared to traditional storage, systems can effectively manage and store intermediate activations, gradients, and model states that exceed GPU memory capacity. This approach allows for training larger models or using higher batch sizes without requiring immediate GPU memory expansion. However, it introduces additional latency due to data transfer between the GPU and NVMe storage, which can impact training speed. Optimizing data access patterns and utilizing efficient offloading strategies can minimize performance overhead and maintain effective training workflows when employing memory offloading techniques.

In this chapter, you learned about a practical pattern of pipeline design for training LLMs. You learned how to create efficient data preprocessing workflows, implement model architectures, and apply advanced optimization strategies. You now understand how to set up effective logging systems to track your model’s progress. You also explored techniques for building modular and reusable pipelines and discovered methods for scaling your training process to accommodate larger models. With these skills, you’re well equipped to train state-of-the-art language models efficiently and effectively.

In the next chapter, we’ll explore the hyperparameter tuning pattern.

Get This Book's PDF Version and Exclusive Extras