Skip to content
ImagineWorld

Hyperparameter Tuning

node_idnode-book_llm-design-patterns_chapter-07-hyperparameter-tuning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleHyperparameter Tuning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, you’ll learn about the hyperparameters in LLMs and strategies for optimizing them efficiently. We’ll explore both manual and automated tuning approaches, including grid search, random search, and more advanced methods, such as Bayesian optimization and population-based training. You’ll also gain insights into handling multi-objective optimization scenarios common in LLM development.

By the end, you’ll be equipped with practical tools and techniques to fine-tune your LLMs for optimal performance across various tasks and domains.

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

  • Understanding hyperparameters
  • Manual versus automated tuning
  • Grid and random search
  • Bayesian optimization
  • Population-based methods
  • Multi-objective hyperparameter optimization
  • Hyperparameter tuning at scale – challenges and solutions

Hyperparameters are settings that are set before the machine learning training process begins and are not learned from the data. They control various aspects of the learning algorithm itself, such as the model’s complexity, learning rate, and the overall training process. Data scientists manually choose and tune these hyperparameters to optimize the model’s performance.

Hyperparameters in LLMs can be broadly categorized into three groups: architectural, optimization, and regularization hyperparameters:

  • Architectural hyperparameters: These define the design and structure of the model, determining how it processes and represents data. They are critical because they directly influence the model’s capacity to learn complex patterns and relationships in the data. The right architecture balances computational efficiency with performance, enabling the model to generalize well to unseen data. Parameters within this category include the following:
    • Number of layers
      • Hidden size
      • Number of attention heads
      • Feed-forward dimension
      • Vocabulary size
  • Optimization hyperparameters: These govern how the model learns during training by adjusting the parameters to minimize the loss function. They are important because they control the rate and manner of updates, affecting convergence speed, stability, and the model’s ability to reach an optimal solution. Proper tuning ensures efficient training without divergence or underfitting. Parameters within this category include the following (we covered these in Chapter 7):
    • Learning rate
      • Batch size
      • Number of training steps
      • Warmup steps
      • Learning rate schedule
  • Regularization hyperparameters: These introduce mechanisms to prevent the model from overfitting to the training data, ensuring it generalizes to new data. They are crucial because models with high capacity can easily memorize the training data, leading to poor performance on unseen data. Regularization techniques enforce constraints that encourage simplicity and robustness. Parameters within this category include the following (see Chapter 9 for more):
    • Dropout rate
      • Weight decay
      • Label smoothing

Let’s implement a function to create an LLM with configurable hyperparameters:

from transformers import GPT2Config, GPT2LMHeadModel
def create_llm(
num_layers, hidden_size, num_heads, ff_dim, vocab_size
):
config = GPT2Config(
n_layer=num_layers,
n_embd=hidden_size,
n_head=num_heads,
n_inner=ff_dim,
vocab_size=vocab_size
)
model = GPT2LMHeadModel(config)
return model
# Example usage
model = create_llm(num_layers=12, hidden_size=768,
num_heads=12, ff_dim=3072, vocab_size=50257)
print(f"Model parameters: {model.num_parameters():,}")

In this code, we define a function, create_llm, that allows us to easily create LLMs with different architectural hyperparameters. The function takes the following parameters:

  • num_layers: The number of transformer layers in the model. More layers can capture more complex patterns, but they increase computational requirements.
  • hidden_size: The dimension of the hidden states throughout the model. This affects the model’s capacity to capture information.
  • num_heads: The number of attention heads in each layer. Multiple heads allow the model to focus on different aspects of the input simultaneously.
  • ff_dim: The dimension of the feed-forward layer in each transformer block. This is typically set to four times the hidden_size.
  • vocab_size: The size of the model’s vocabulary. This determines the size of the embedding layer and the output layer.

We use these parameters to create a GPT2Config object, which is then used to initialize a GPT2LMHeadModel. This approach allows us to easily experiment with different model architectures.

Manual tuning involves adjusting hyperparameters based on intuition, experience, and gradual experimentation. Manual tuning allows you to leverage domain knowledge to explore tailored configurations systematically, but it is time-intensive, prone to suboptimal results, and inefficient in exploring large hyperparameter spaces.

Automated tuning, on the other hand, uses algorithms to systematically explore the hyperparameter space. Automated tuning efficiently explores large hyperparameter spaces using algorithms to optimize performance, saving time and effort compared to manual tuning, but it can be computationally expensive and may require expertise to configure properly.

Manual tuning is useful when domain knowledge or intuition can guide a small, targeted search space, especially in resource-constrained settings or for simpler models. Automated tuning is better for large, complex hyperparameter spaces where systematic exploration and optimization are required, as it can find better configurations more efficiently despite higher computational costs.

Let’s implement both approaches.

First, we’ll implement manual tuning:

  1. Start with
    import numpy as np
    from transformers import Trainer, TrainingArguments
    from datasets import load_dataset
  2. Load a
    dataset = load_dataset(
    "wikitext", "wikitext-2-raw-v1", split="train")
    def tokenize_function(examples):
    return tokenizer(
    examples["text"], truncation=True, max_length=512)
    tokenized_dataset = dataset.map(tokenize_function,
    batched=True, remove_columns=dataset.column_names)
  3. Set up the manual
    manual_hyperparameters = [
    {"num_layers": 6, "hidden_size": 512, "num_heads": 8, "ff_dim": 2048},
    {"num_layers": 12, "hidden_size": 768, "num_heads": 12, "ff_dim": 3072},
    {"num_layers": 24, "hidden_size": 1024, "num_heads": 16, "ff_dim": 4096}
    ]
  4. Conduct training manual_hyperparameters
    for hp in manual_hyperparameters:
    model = create_llm(hp, vocab_size=50257)
    training_args = TrainingArguments(
    output_dir=(
    f"./results_{hp['num_layers']}_"
    f"{hp['hidden_size']}"
    ),
    num_train_epochs=3,
    per_device_train_batch_size=8,
    logging_dir=(
    f"./logs_{hp['num_layers']}_"
    f"{hp['hidden_size']}"
    ),
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
  5. Evaluate
    eval_results = trainer.evaluate()
    print(f"Hyperparameters: {hp}")
    print(f"Evaluation results: {eval_results}")

In this manual tuning example, we define a list of hyperparameter configurations to try. We then iterate through these configurations, creating a model for each, training it, and evaluating its performance. This approach allows us to systematically explore different model sizes and architectures.

The manual tuning process can be guided by domain knowledge and intuition. For example, we might start with a small model (6 layers, 512 hidden size) and gradually increase the size to see how it affects performance. We choose these specific configurations based on common practices in transformer-based models:

  • The smallest configuration (6 layers, 512 hidden size) represents a compact model suitable for faster training and deployment
  • The medium configuration (12 layers, 768 hidden size) is similar to the base GPT-2 model, known to perform well on many tasks
  • The largest configuration (24 layers, 1,024 hidden size) represents a more powerful model that might capture more complex patterns but requires more computational resources

Now, let’s implement a simple automated tuning approach using random search (we will show a more advanced random search in the next section):

  1. Add the import statement and set up the
    import random
    def random_hp_search(num_trials=10):
    best_eval_loss = float('inf')
    best_hp = None
    for _ in range(num_trials):
    hp = {
    "num_layers": random.choice([6, 12, 24]),
    "hidden_size": random.choice([512, 768, 1024]),
    "num_heads": random.choice([8, 12, 16]),
    "ff_dim": random.choice([2048, 3072, 4096])
    }
  2. model = create_llm(hp, vocab_size=50257)
    training_args = TrainingArguments(
    output_dir=f"./results_random_{_}",
    num_train_epochs=3,
    per_device_train_batch_size=8,
    logging_dir=f"./logs_random_{_}",
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
  3. Evaluate and print out
    eval_results = trainer.evaluate()
    eval_loss = eval_results['eval_loss']
    if eval_loss < best_eval_loss:
    best_eval_loss = eval_loss
    best_hp = hp
    print(
    f"Trial {_ + 1}: "
    f"Hyperparameters: {hp}, "
    f"Eval Loss: {eval_loss}"
    )
    print(
    f"Best Hyperparameters: {best_hp}, "
    f"Best Eval Loss: {best_eval_loss}"
    )
    random_hp_search()

This random search implementation randomly selects hyperparameters from predefined options for each trial (no manual intervention during trials). Predefined options refer to the specified ranges, sets, or distributions from which random values for hyperparameters are sampled during the search process. For example, discrete hyperparameters such as the number of layers might be chosen from a set [6, 12, 24], while continuous hyperparameters such as learning rate could be sampled from a uniform or log-uniform distribution, such as 10^(-5) to 10^(-3). These options define the boundaries and possible values for each hyperparameter, guiding the random sampling process.

We choose to search over a discrete set of values for each hyperparameter to limit the search space and ensure that we’re exploring configurations that are known to work well for transformer models. The number of trials (10 in this case) is a balance between exploration and computational resources. More trials increase the chance of finding a good configuration but also increase the computational cost.

In the subsequent sections, we will introduce other automated turning techniques such as grid search and more advanced random search, Bayesian optimization, the population-based method, and multi-objective hyperparameter optimization.

Grid search and random search are two common methods for hyperparameter tuning. We covered random search in the previous section. In this section, we implement grid search and a more advanced version of random search.

  1. Add the import and set up the grid
    import itertools
    def grid_search():
    hp_grid = {
    "num_layers": [6, 12, 24],
    "hidden_size": [512, 768, 1024],
    "num_heads": [8, 12, 16],
    "ff_dim": [2048, 3072, 4096]
    }
    best_eval_loss = float('inf')
    best_hp = None
  2. Train the model with the
    for hp in itertools.product(*hp_grid.values()):
    hp_dict = dict(zip(hp_grid.keys(),hp))
    model = create_llm(
    hp_dict["num_layers"],
    hp_dict["hidden_size"],
    hp_dict["num_heads"],
    hp_dict["ff_dim"],
    vocab_size=50257
    )
    training_args = TrainingArguments(
    output_dir=(
    f"./results_grid_{hp_dict['num_layers']}_"
    f"{hp_dict['hidden_size']}"
    ),
    num_train_epochs=3,
    per_device_train_batch_size=8,
    logging_dir=(
    f"./logs_grid_{hp_dict['num_layers']}_"
    f"{hp_dict['hidden_size']}"
    ),
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
  3. Evaluate and print out
    eval_results = trainer.evaluate()
    eval_loss = eval_results['eval_loss']
    if eval_loss < best_eval_loss:
    best_eval_loss = eval_loss
    best_hp = hp_dict
    print(
    f"Hyperparameters: {hp_dict}, "
    f"Eval Loss: {eval_loss}"
    )
    print(
    f"Best Hyperparameters: {best_hp}, "
    f"Best Eval Loss: {best_eval_loss}"
    )
    grid_search()

Grid search exhaustively explores all combinations of hyperparameters. This approach is thorough but can be computationally expensive, especially for LLMs with many hyperparameters. In this implementation, we’re exploring 3^4 = 81 different configurations, which could take a significant amount of time and resources.

The hyperparameter ranges are chosen to cover a reasonable space of model sizes, from relatively small (6 layers, 512 hidden size) to quite large (24 layers, 1,024 hidden size). This allows us to explore the trade-off between model size and performance.

Now, let’s implement a more sophisticated random search that also includes optimization hyperparameters:

  1. Add the import statement and set up the advanced_random_search
    import random
    def advanced_random_search(num_trials=20):
    best_eval_loss = float('inf')
    best_hp = None
    for _ in range(num_trials):
    hp = {
    "num_layers": random.choice([6, 12, 24]),
    "hidden_size": random.choice([512, 768, 1024]),
    "num_heads": random.choice([8, 12, 16]),
    "ff_dim": random.choice([2048, 3072, 4096]),
    "learning_rate": 10random.uniform(-5, -3),
    "batch_size": random.choice([8, 16, 32]),
    "num_epochs": random.randint(2, 5),
    "warmup_steps": random.randint(100, 1000),
    "weight_decay": random.uniform(0, 0.2)
    }
  2. Conduct
    model = create_llm(
    num_layers=hp['num_layers'],
    hidden_size=hp['hidden_size'],
    num_heads=hp['num_heads'], ff_dim=hp['ff_dim'],
    vocab_size=50257)
    training_args = TrainingArguments(
    output_dir=f"./results_advanced_random_{_}",
    num_train_epochs=hp['num_epochs'],
    per_device_train_batch_size=hp['batch_size'],
    learning_rate=hp['learning_rate'],
    warmup_steps=hp['warmup_steps'],
    weight_decay=hp['weight_decay'],
    logging_dir=f"./logs_advanced_random_{_}",
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
  3. Evaluate and print out
    eval_results = trainer.evaluate()
    eval_loss = eval_results['eval_loss']
    if eval_loss < best_eval_loss:
    best_eval_loss = eval_loss
    best_hp = hp
    print(
    f"Trial {_ + 1}: Hyperparameters: {hp}, "
    f"Eval Loss: {eval_loss}"
    )
    print(
    f"Best Hyperparameters: {best_hp}, "
    f"Best Eval Loss: {best_eval_loss}"
    )

This advanced random search includes both architectural and optimization hyperparameters. We use random.uniform for continuous hyperparameters (parameters that can take any real number value within a range, such as 0.001, 0.0015, or 0.002) such as learning rate and weight decay, and random.choice or random.randint for discrete hyperparameters (parameters that can only take specific predefined values or integers, such as choosing between 32, 64, and 128 for batch size or selecting from a fixed set of options).

The ranges for each hyperparameter are chosen based on common practices in LLM training (see also Chapter 7):

  • Learning rate: We use a log-uniform distribution between 1e-5 and 1e-3, as learning rates for LLMs are typically in this range
  • Batch size: We choose from 8, 16, and 32, which are common batch sizes that balance between computational efficiency and stability
  • Number of epochs: We allow 2 to 5 epochs, as LLMs often converge within a few epochs on large datasets
  • Warmup steps: We choose between 100 and 1,000 steps, which can help stabilize early training
  • Weight decay: We use a uniform distribution between 0 and 0.2, as small amounts of weight decay can help prevent overfitting

Advanced random search is better than grid search because it explores the hyperparameter space more efficiently by sampling randomly instead of exhaustively evaluating every possible combination. This flexibility allows it to focus on key hyperparameters that significantly impact performance, preventing redundant evaluations of less impactful ones. It can handle continuous parameters directly by sampling from distributions, unlike grid search, which requires discretization and exponentially grows in computational cost as the parameter space increases. By limiting the number of trials to a predefined budget, advanced random search can discover effective configurations faster and with less computational expense, making it more practical for large and complex models.

Bayesian optimization is a more sophisticated approach to hyperparameter tuning that can be particularly effective for LLMs. It uses a probabilistic model to predict the performance of different hyperparameter configurations and intelligently selects the next configuration to try.

Let’s implement Bayesian optimization using the optuna library. Optuna is an open source hyperparameter optimization framework for automating the process of finding optimal parameters for algorithms and models. It employs advanced Bayesian optimization techniques, primarily the Tree-structured Parzen Estimator (TPE) algorithm, to efficiently search complex parameter spaces:

  1. Import optuna and set up
    import optuna
    from transformers import Trainer, TrainingArguments
    import torch
    def objective(trial):
    # Define the hyperparameters to optimize
    hp = {
    "num_layers": trial.suggest_int("num_layers", 6, 24),
    "hidden_size": trial.suggest_categorical(
    "hidden_size", [512, 768, 1024]
    ,
    "num_heads": trial.suggest_categorical(
    "num_heads", [8, 12, 16]
    ),
    "ff_dim": trial.suggest_categorical(
    "ff_dim", [2048, 3072, 4096]
    ),
    "learning_rate": trial.suggest_loguniform(
    "learning_rate", 1e-5, 1e-3
    ),
    "batch_size": trial.suggest_categorical(
    "batch_size", [8, 16, 32]
    ),
    "num_epochs": trial.suggest_int("num_epochs", 2, 5),
    "warmup_steps": trial.suggest_int(
    "warmup_steps", 100, 1000),
    "weight_decay": trial.suggest_uniform( "weight_decay", 0, 0.2)
    }
    model = create_llm(
    num_layers=hp['num_layers'],
    hidden_size=hp['hidden_size'],
    num_heads=hp['num_heads'], ff_dim=hp['ff_dim'],
    vocab_size=50257
    )
  2. training_args = TrainingArguments(
    output_dir=f"./results_bayesian_{trial.number}",
    num_train_epochs=hp['num_epochs'],
    per_device_train_batch_size=hp['batch_size'],
    learning_rate=hp['learning_rate'],
    warmup_steps=hp['warmup_steps'],
    weight_decay=hp['weight_decay'],
    logging_dir=f"./logs_bayesian_{trial.number}",
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
    eval_results = trainer.evaluate()
    return eval_results['eval_loss']
  3. Run
    study = optuna.create_study(direction="minimize")
    study.optimize(objective, n_trials=20)
    print("Best trial:")
    trial = study.best_trial
    print(f"Value: {trial.value}")
    print("Params: ")
    for key, value in trial.params.items():
    print(f" {key}: {value}")

In this implementation, we define an objective function that Optuna will optimize. The function creates and trains a model with the hyperparameters suggested by Optuna and then returns the evaluation loss.

We use Optuna’s suggestion methods to define the search space:

  • suggest_int for integer hyperparameters such as num_layers and num_epochs
  • suggest_categorical for hyperparameters with discrete options such as hidden_size and num_heads
  • suggest_loguniform for the learning rate, as we want to search this space logarithmically
  • suggest_uniform for weight decay, as we want to search this space uniformly

The ranges for each hyperparameter are similar to those in our random search implementation based on common practices in LLM training.

Bayesian optimization can be more efficient than grid or random search, especially for expensive-to-evaluate functions such as training LLMs. It uses the results of previous trials to inform the selection of future trials, potentially finding good configurations more quickly.

Population-based training (PBT) is a powerful technique that combines parallel search with adaptive hyperparameter tuning during the training process. PBT is particularly effective for problems where training can be paused and resumed efficiently. This is because PBT periodically evaluates and updates hyperparameters and model weights across a population, requiring seamless pause-and-resume capabilities. This adaptability ensures optimal use of computational resources and makes PBT ideal for tasks such as neural architecture search, reinforcement learning, and hyperparameter tuning, where iterative optimization is computationally intensive.

Here, we’ll implement a simplified version of PBT to illustrate its core concepts and functionality.

We’ll start by creating a SimplePBT class that encapsulates the core functionality of the PBT algorithm. Let’s break down the implementation:

  1. First, initialize
    import random
    import copy
    class SimplePBT:
    def __init__(self, population_size=4, num_generations=5):
    self.population_size = population_size
    self.num_generations = num_generations
    self.population = []
    The SimplePBT class is initialized with two main parameters:
    • population_size: The number of different hyperparameter configurations to maintain (the default is 4)
      • num_generations: The number of iterations the PBT algorithm will run (the default is 5) The population list will store dictionaries representing each individual in the population, containing hyperparameters and their corresponding performance scores.
  2. Initialize the population: The initialize_population method creates the initial set of hyperparameter configurations:
    def initialize_population(self):
    for _ in range(self.population_size):
    hp = {
    "num_layers": random.choice([6, 12, 24]),
    "hidden_size": random.choice([512, 768, 1024]),
    "num_heads": random.choice([8, 12, 16]),
    "ff_dim": random.choice([2048, 3072, 4096]),
    "learning_rate": 10random.uniform(-5, -3),
    "batch_size": random.choice([8, 16, 32]),
    "weight_decay": random.uniform(0, 0.2)
    }
    self.population.append({"hp": hp, "score": None})
    For each individual in the population, do the following:
    • Categorical hyperparameters, which are a subset of discrete hyperparameters (e.g., num_layers, hidden_size), are randomly selected from predefined options. These hyperparameters are categorical because they represent distinct, individual choices rather than values along a continuum.
      • Continuous hyperparameters (e.g., learning_rate, weight_decay) are sampled from specified ranges. Each configuration is added to the population list with an initial score of None.
  3. Train and evaluate: The train_and_evaluate method is responsible for creating an LLM with the given hyperparameters, setting up training arguments, initializing a trainer with the model and arguments, training the model, evaluating the model, and returning the
    def train_and_evaluate(self, hp):
    model = create_llm(num_layers=hp['num_layers'],
    hidden_size=hp['hidden_size'],
    num_heads=hp['num_heads'],
    ff_dim=hp['ff_dim'], vocab_size=50257)
    training_args = TrainingArguments(
    output_dir=f"./results_pbt_{random.randint(0, 1000)}",
    num_train_epochs=3,
    per_device_train_batch_size=hp['batch_size'],
    learning_rate=hp['learning_rate'],
    weight_decay=hp['weight_decay'],
    logging_dir=f"./logs_pbt_{random.randint(0, 1000)}",
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
    eval_results = trainer.evaluate()
    return eval_results['eval_loss']
    This method assumes the existence of create_llm, TrainingArguments, and Trainer classes, which would typically be provided by a deep learning framework such as Hugging Face Transformers.
  4. Exploit and explore: The exploit_and_explore method implements the core
    def exploit_and_explore(self):
    # Sort population by score
    self.population.sort(key=lambda x: x['score'])
    # Replace bottom half with mutated versions of top half
    for i in range(self.population_size // 2):
    self.population[i + self.population_size // 2]['hp'] =\
    self.mutate(
    copy.deepcopy(self.population[i]['hp'])
    )
    It sorts the population based on their scores (a lower score indicates less loss). The bottom-performing half of the population is replaced with mutated versions of the top-performing half. This approach balances exploitation (keeping good configurations) with exploration (trying new variations).
  5. Mutate: The mutate method introduces variations in
    def mutate(self, hp):
    # Randomly mutate one hyperparameter
    param_to_mutate = random.choice(list(hp.keys()))
    if param_to_mutate in [
    'num_layers', 'hidden_size', 'num_heads', 'ff_dim',
    'batch_size'
    ]:
    hp[param_to_mutate] = random.choice(
    [6, 12, 24]
    if param_to_mutate == "num_layers" else
    [512, 768, 1024]
    if param_to_mutate == "hidden_size" else
    [8, 12, 16]
    if param_to_mutate == "num_heads" else
    [2048, 3072, 4096]
    if param_to_mutate == "ff_dim" else
    [8, 16, 32]
    )
    elif param_to_mutate == 'learning_rate':
    hp[param_to_mutate] *= random.uniform(0.8, 1.2)
    elif param_to_mutate == 'weight_decay':
    hp[param_to_mutate] = min(
    max(hp[param_to_mutate]
    + random.uniform(-0.05, 0.05), 0), 0.2
    )
    return hp
    It randomly selects one hyperparameter to mutate. For categorical parameters, it chooses a new value from predefined options. For continuous parameters like learning rate, it perturbs the current value within a certain range. For weight decay, it adds a small random value while keeping it within [0, 0.2]. This mutation strategy allows both small and large changes in the hyperparameters, promoting diverse exploration of the hyperparameter space.
  6. Run the
    def run(self):
    self.initialize_population()
    for generation in range(self.num_generations):
    print(f"Generation {generation + 1}")
    for i, individual in enumerate(self.population):
    individual['score'] = \
    self.train_and_evaluate(individual['hp'])
    print(
    f"Individual {i + 1}:
    Score = {individual['score']}"
    )
    self.exploit_and_explore()
    best_individual = min(self.population,
    key=lambda x: x['score'])
    print("\nBest Hyperparameters:")
    print(best_individual['hp'])
    print(f"Best Score: {best_individual['score']}")
    The run method orchestrates the entire PBT process:
    1. It initializes the population. 2. For each generation, it trains and evaluates each individual in the population and it performs exploitation and exploration to update the population. 3. After all generations, it prints the best hyperparameters and the score found.
  7. Use the SimplePBT class: To use the SimplePBT class, you can simply create an instance and
    # Run PBT
    pbt = SimplePBT()
    pbt.run()

This will start the PBT process with the default population size of 4 and 5 generations. You can adjust these parameters when creating the SimplePBT instance to suit your specific needs.

Multi-objective hyperparameter optimization

Section titled “Multi-objective hyperparameter optimization”

In LLM development, we often need to balance multiple objectives, such as model performance, inference speed, and model size. Let’s implement multi-objective optimization using Optuna:

  1. Add the import statement and set up
    import optuna
    def objective(trial):
    hp = {
    "num_layers": trial.suggest_int("num_layers", 6, 24),
    "hidden_size": trial.suggest_categorical(
    "hidden_size", [512, 768, 1024]),
    "num_heads": trial.suggest_categorical(
    "num_heads", [8, 12, 16]),
    "ff_dim": trial.suggest_categorical(
    "ff_dim", [2048, 3072, 4096]),
    "learning_rate": trial.suggest_loguniform(
    "learning_rate", 1e-5, 1e-3),
    "batch_size": trial.suggest_categorical(
    "batch_size", [8, 16, 32]),
    "weight_decay": trial.suggest_uniform(
    "weight_decay", 0, 0.2)
    }
    model = create_llm(
    num_layers=hp['num_layers'],
    hidden_size=hp['hidden_size'],
    num_heads=hp['num_heads'],
    ff_dim=hp['ff_dim'],
    vocab_size=50257
    )
  2. Conduct
    training_args = TrainingArguments(
    output_dir=f"./results_multi_objective_{trial.number}",
    num_train_epochs=3,
    per_device_train_batch_size=hp['batch_size'],
    learning_rate=hp['learning_rate'],
    weight_decay=hp['weight_decay'],
    logging_dir=f"./logs_multi_objective_{trial.number}",
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
  3. Carry out
    eval_results = trainer.evaluate()
    eval_loss = eval_results['eval_loss']
    # Calculate model size in MB
    model_size = sum(p.numel() for p in model.parameters())
    * 4 / 1024 / 1024 # assuming float32
    # Simulate inference time (this would be more accurate if actually measured)
    inference_time = 0.001 * hp['num_layers']
    * (hp['hidden_size'] / 512) 2
    return eval_loss, model_size, inference_time
  4. Run the
    study = optuna.create_study(
    directions=["minimize", "minimize", "minimize"])
    study.optimize(objective, n_trials=50)
    print("Pareto front:")
    for trial in study.best_trials:
    print(f"Trial {trial.number}")
    print(f" Value: Loss={trial.values[0]:.4f},
    Size={trial.values[1]:.2f}MB,
    Inference Time={trial.values[2]:.4f}s")
    print(" Params:")
    for key, value in trial.params.items():
    print(f" {key}: {value}")

In this multi-objective optimization, we’re trying to minimize three objectives simultaneously:

  • Evaluation loss (model performance)
  • Model size (in MB)
  • Inference time (simulated based on model architecture)

We use Optuna’s multi-objective optimization capability by specifying multiple directions in create_study. The optimization process will try to find the Pareto front (the set of solutions where improving any one objective necessitates degrading at least one other objective) of these objectives’ configurations, where improving one objective would necessarily worsen another.

The objective function now returns three values corresponding to our three objectives. For model size, we calculate the total number of parameters and convert it to MB. For inference time, we use a simple heuristic based on the model’s architecture in a real scenario, you would want to measure this.

This approach allows us to explore trade-offs between model performance, size, and speed. It’s particularly useful for LLM development, where we often need to balance these factors for different deployment scenarios.

Hyperparameter tuning at scale – challenges and solutions

Section titled “Hyperparameter tuning at scale – challenges and solutions”

When tuning hyperparameters for LLMs, we face several challenges:

  • Computational cost: Training LLMs is expensive, limiting the number of trials we can run
  • Long training times: Each trial can take days or weeks, making the entire process very time-consuming
  • Large search space: LLMs have many hyperparameters, creating a vast search space
  • Sensitivity to initialization: LLM performance can vary significantly with different random seeds

To address these challenges, we can employ several strategies:

  • Use smaller proxy tasks: Instead of tuning on the full task, use a smaller dataset or fewer training steps to get a quick estimate of performance
  • Leverage pre-trained models: Start from pre-trained weights and focus on tuning fine-tuning hyperparameters
  • Use multi-fidelity optimization: Start with low-fidelity evaluations (e.g., few training steps) and gradually increase fidelity for promising configurations
  • Distributed hyperparameter tuning: Use multiple machines to explore different hyperparameters in parallel

Let’s implement a simple multi-fidelity optimization approach:

  1. Add the import statement and set up
    import optuna
    def objective(trial):
    hp = {
    "num_layers": trial.suggest_int("num_layers", 6, 24),
    "hidden_size": trial.suggest_categorical(
    "hidden_size", [512, 768, 1024]),
    "num_heads": trial.suggest_categorical(
    "num_heads", [8, 12, 16]),
    "ff_dim": trial.suggest_categorical(
    "ff_dim", [2048, 3072, 4096]),
    "learning_rate": trial.suggest_loguniform(
    "learning_rate", 1e-5, 1e-3),
    "batch_size": trial.suggest_categorical(
    "batch_size", [8, 16, 32]),
    "weight_decay": trial.suggest_uniform(
    "weight_decay", 0, 0.2)
    }
    model = create_llm(
    num_layers=hp['num_layers'],
    hidden_size=hp['hidden_size'],
    num_heads=hp['num_heads'], ff_dim=hp['ff_dim'],
    vocab_size=50257)
  2. Use a multi-fidelity strategy to train, starting with a small number
    for steps in [100, 500, 2000]:
    training_args = TrainingArguments(
    output_dir= \
    f"./results_multi_fidelity_{trial.number}_
    {steps}",
    max_steps=steps,
    per_device_train_batch_size=hp['batch_size'],
    learning_rate=hp['learning_rate'],
    weight_decay=hp['weight_decay'],
    logging_dir=\
    f"./logs_multi_fidelity_{trial.number}_{steps}",
    )
    trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset,
    )
    trainer.train()
  3. eval_results = trainer.evaluate()
    eval_loss =
    eval_results = trainer.evaluate()
    eval_loss = eval_results['eval_loss']
    trial.report(eval_loss, step=steps)
  4. Prune the
    if trial.should_prune():
    raise optuna.TrialPruned()
    return eval_loss
  5. Run the
    study = optuna.create_study(
    pruner=optuna.pruners.MedianPruner())
    study.optimize(objective, n_trials=30)
    print("Best trial:")
    trial = study.best_trial
    print(f"Value: {trial.value}")
    print("Params: ")
    for key, value in trial.params.items():
    print(f" {key}: {value}")

There are a few aspects of this multi-fidelity approach that we should look at:

  • We start by training each model configuration for only 100 steps, which gives a quick initial estimate of performance
  • We then increase the number of training steps to 500 and then 2,000 for promising configurations
  • We use Optuna’s pruning mechanism to early-stop unpromising trials, saving computational resources

MedianPruner stops a trial if its performance is worse than the median of previous trials at the same step. This allows us to focus our computational resources on the most promising hyperparameter configurations.

This approach helps to address the challenges of hyperparameter tuning at scale:

  • It reduces the computational cost by quickly eliminating poor configurations
  • It shortens the overall tuning time by using shorter training runs for initial evaluation
  • It allows us to explore a larger search space by running more trials in the same amount of time

However, there are still limitations to this approach. The performance after a small number of steps may not always correlate well with the final performance, especially for LLMs that often require long training times to converge.

To further improve hyperparameter tuning at scale, consider the following advanced techniques:

  • Distributed hyperparameter tuning: This setup allows multiple machines to contribute to the same hyperparameter search, greatly speeding up
    import optuna
    def objective(trial):
    # ... (same as before) ...
    # Create a study object with MySQL storage for distributed optimization
    storage = optuna.storages.RDBStorage(
    "mysql://user:password@host/database",
    engine_kwargs={"pool_size": 20, "max_overflow": 0}
    )
    study = optuna.create_study(
    storage=storage, pruner=optuna.pruners.MedianPruner())
    # This can be run on multiple machines
    study.optimize(objective, n_trials=10)
  • Leveraging pre-trained models: This approach starts from pre-trained models and focuses on tuning the fine-tuning hyperparameters and model size, which can be more efficient than training
    from transformers import AutoModelForCausalLM, AutoTokenizer
    def create_pretrained_llm(model_name, num_layers=None):
    model = AutoModelForCausalLM.from_pretrained(model_name)
    if num_layers is not None:
    # Adjust the number of layers (this is a simplified approach)
    model.transformer.h = model.transformer.h[:num_layers]
    return model
    def objective(trial):
    hp = {
    "model_name": trial.suggest_categorical(
    "model_name",
    ["gpt2", "gpt2-medium", "gpt2-large"]),
    "num_layers": trial.suggest_int("num_layers", 6, 24),
    "learning_rate": trial.suggest_loguniform(
    "learning_rate", 1e-5, 1e-3),
    "batch_size": trial.suggest_categorical(
    "batch_size", [8, 16, 32]),
    "weight_decay": trial.suggest_uniform(
    "weight_decay", 0, 0.2)
    }
    model = create_pretrained_llm(
    hp['model_name'], hp['num_layers'])
    # ... (rest of the objective function) ...
    study = optuna.create_study(
    pruner=optuna.pruners.MedianPruner())
    study.optimize(objective, n_trials=30)
  • Bayesian optimization with Gaussian processes: For problems where we can only afford a small number of trials, Gaussian process-based Bayesian optimization can be more sample-efficient than tree-based methods such as TPE (which is
    import optuna
    sampler = optuna.samplers.GPSampler()
    study = optuna.create_study(sampler=sampler)
    study.optimize(objective, n_trials=50)
    This approach can be particularly useful for LLM tuning where each trial is very expensive.
  • Asynchronous Successive Halving Algorithm (ASHA): ASHA is a bandit-based algorithm that can be more efficient than simple
    from optuna.pruners import SuccessiveHalvingPruner
    pruner = SuccessiveHalvingPruner(
    min_resource=100, reduction_factor=3,
    min_early_stopping_rate=0)
    study = optuna.create_study(pruner=pruner)
    study.optimize(objective, n_trials=100)
    ASHA is particularly well-suited for large-scale hyperparameter optimization as it can handle asynchronous parallel optimization efficiently.

Hyperparameter tuning for LLMs presents unique challenges due to the scale and complexity of these models. By leveraging techniques such as multi-fidelity optimization, distributed tuning, and advanced algorithms such as Bayesian optimization and ASHA, we can make this process more efficient and effective. However, it’s important to remember that there’s often no one-size-fits-all solution, and the best approach may depend on your specific use case, available resources, and the characteristics of your LLM task.

In the next chapter, we’ll focus on LLM regularization.