Fine-Tuning
local graph
Chapter 10 — Fine-Tuning
Section titled “Chapter 10 — Fine-Tuning”In this design pattern, you’ll learn about effective strategies for fine-tuning pre-trained language models.
Fine-tuning LLMs addresses a fundamental optimization problem in transfer learning: Pre-training on large datasets helps LLMs learn general language skills and knowledge, but the differences between the pre-training data and the data for specific tasks can reduce performance. Fine-tuning uses a smaller, carefully chosen dataset for the task to update the model, making it better suited to the task’s needs. This process retains useful knowledge from pre-training while refining the model’s ability to perform effectively on the target task.
In this chapter, we’ll be covering the following topics:
- Implementing transfer learning and fine-tuning
- Strategies for freezing and unfreezing layers
- Learning rate scheduling
- Domain-specific techniques
- Few-shot and zero-shot fine-tuning
- Continual fine-tuning and catastrophic forgetting
Implementing transfer learning and fine-tuning
Section titled “Implementing transfer learning and fine-tuning”We will use the following code blocks to demonstrate transfer learning with GPT-2, handling model initialization, data processing, and the fine-tuning workflow. We will use the Transformers library and WikiText dataset to fine-tune a pre-trained language model:
- First, we load and initialize the GPT-2 model and tokenizer with
def load_model_and_tokenizer(model_name="gpt2"):model = GPT2LMHeadModel.from_pretrained(model_name)tokenizer = GPT2Tokenizer.from_pretrained(model_name)tokenizer.pad_token = tokenizer.eos_tokenreturn model, tokenizer
- Then, the following code block manages dataset loading and text tokenization with a sequence length
512def prepare_dataset(dataset_name="wikitext",dataset_config="wikitext-2-raw-v1"):dataset = load_dataset(dataset_name, dataset_config)return datasetdef tokenize_function(examples, tokenizer):return tokenizer(examples["text"], truncation=True,padding="max_length", max_length=512) - Finally, we set up our training configuration, initialize the trainer, and
The code sets up adef fine_tune_lm(model, tokenizer,dataset, output_dir="./fine_tuned_model"):tokenized_dataset = dataset.map(lambda examples: tokenize_function(examples, tokenizer),batched=True)training_args = TrainingArguments(output_dir=output_dir,num_train_epochs=3,per_device_train_batch_size=8,per_device_eval_batch_size=8,warmup_steps=500,weight_decay=0.01,logging_dir="./logs",)trainer = Trainer(model=model,args=training_args,train_dataset=tokenized_dataset["train"],eval_dataset=tokenized_dataset["validation"],)trainer.train()trainer.save_model()
fine_tune_lmfunction that prepares and executes language model fine-tuning. It first tokenizes the dataset using batched processing, then configures training parameters including epochs, batch sizes, warmup steps, and weight decay. Next, it initializes a trainer with the model, arguments, and datasets, runs the training process, and finally saves the fine-tuned model.
Batch size has a significant impact on both training stability and performance. Larger batch sizes allow for more parallelization and faster training on capable hardware but require more memory. They can provide more stable gradient estimates by averaging over more examples, potentially leading to better convergence. However, very large batches may generalize poorly compared to smaller ones, as they can cause the model to converge to sharper minima. Smaller batch sizes introduce more noise in gradient updates, which can help escape local minima and potentially find better solutions, but training takes longer. Finding the optimal batch size involves balancing hardware constraints, convergence stability, and generalization performance for your specific model and dataset.
When fine-tuning LLMs, we often don’t need to update all the model’s parameters. Selectively freezing and unfreezing layers can lead to more efficient and effective fine-tuning.
Strategies for freezing and unfreezing layers
Section titled “Strategies for freezing and unfreezing layers”The idea behind selectively freezing and unfreezing layers is rooted in how knowledge is structured and distributed across a deep neural network. Lower layers in LLMs tend to capture more general language representations—such as syntax, part-of-speech, and morphology—while higher layers are more specialized and task-dependent. This hierarchical organization allows us to leverage the general-purpose linguistic knowledge already encoded in the early layers while fine-tuning only the task-specific portions of the network.
By freezing the lower layers, we preserve their pre-trained capabilities and prevent catastrophic forgetting, which can occur if the entire model is updated indiscriminately on a narrow domain dataset. This also drastically reduces the number of trainable parameters, leading to lower memory usage and faster convergence. Meanwhile, selectively unfreezing the upper layers allows the model to adapt its representations for new tasks or domains without disturbing its core language understanding capabilities.
Let’s look at how we can implement this:
- First, we implement selective layer freezing by disabling gradients for all layers except the specified number of
def freeze_layers(model, num_layers_to_freeze):for param in model.base_model.parameters():param.requires_grad = Falsefor i, layer in enumerate(model.base_model.transformer.h):if i >= len(model.base_model.transformer.h) -\num_layers_to_freeze:for param in layer.parameters():param.requires_grad = True
- Then, we manage progressive layer unfreezing across
def gradual_unfreeze(model, trainer, num_epochs, total_layers):layers_per_epoch = total_layers // num_epochsfor epoch in range(num_epochs):freeze_layers(model, (epoch + 1) * layers_per_epoch)trainer.train(resume_from_checkpoint=True)
- Finally, we configure optimized training parameters for the gradual
training_args = TrainingArguments(output_dir="./fine_tuned_model",num_train_epochs=5, # Increased epochs for better learningper_device_train_batch_size=16, # Larger batch sizeper_device_eval_batch_size=16,warmup_steps=1000, # More warmup stepslearning_rate=2e-5, # Added learning rateweight_decay=0.1, # Increased weight decaylogging_dir="./logs",save_steps=500, # Added save frequencyeval_steps=500 # Added evaluation frequency)trainer = Trainer(model=model,args=training_args,train_dataset=tokenized_dataset["train"],eval_dataset=tokenized_dataset["validation"],)
This implementation introduces two key strategies:
freeze_layers: This function freezes all layers except for the lastnum_layers_to_freezegradual_unfreeze: This function gradually unfreezes layers over the course of training
The gradual unfreezing approach allows the model to adapt its higher-level features first, then progressively fine-tune lower-level features. This can lead to better performance and help prevent catastrophic forgetting.
Catastrophic forgetting is reduced because of the following reasons:
- Layer freezing preserves knowledge in earlier layers by disabling gradient updates for them, maintaining the fundamental representations learned during pre-training while only adapting task-specific later layers. This retains the model’s general knowledge while allowing adaptation to new tasks.
- Gradual unfreezing implements a staged approach where training begins with only the final layers unfrozen (which contain more task-specific representations), then progressively unfreezes earlier layers. This allows the model to adapt higher-level features first before making more fundamental changes, providing a gentle transition that helps maintain previously learned patterns.
- The training configuration supports these approaches with a carefully balanced learning rate, increased warmup steps, and higher weight decay that further prevents drastic parameter shifts. The increased epochs allow for more gradual adaptation while save and evaluation checkpoints provide monitoring to prevent overfitting during the unfreezing process.
Together, these techniques create a more controlled fine-tuning process that preserves general knowledge while effectively adapting to new tasks.
Finetuning performance can be significantly improved by applying appropriate learning rate scheduling, which we’ll visit next.
Learning rate scheduling
Section titled “Learning rate scheduling”As mentioned, proper learning rate scheduling is often used for effective fine-tuning. The following code demonstrates common learning rate scheduling techniques for LLM fine-tuning, offering both linear and cosine warmup strategies to optimize training:
- First, we set up the scheduling framework with the required imports and
from transformers import (get_linear_schedule_with_warmup,get_cosine_schedule_with_warmup)def fine_tune_with_lr_scheduling(model, tokenizer, dataset, scheduler_type="linear",num_epochs=3):tokenized_dataset = dataset.map(lambda examples: tokenize_function(examples, tokenizer),batched=True)
- Next, we configure optimized training parameters with
training_args = TrainingArguments(output_dir="./fine_tuned_model",num_train_epochs=3,per_device_train_batch_size=32, # Increased batch sizeper_device_eval_batch_size=32,weight_decay=0.1, # Increased weight decaylogging_dir="./logs",learning_rate=2e-5, # Adjusted learning ratewarmup_ratio=0.1, # Added warmup ratioeval_steps=100, # Added evaluation frequencysave_steps=100 # Added save frequency)trainer = Trainer(model=model,args=training_args,train_dataset=tokenized_dataset["train"],eval_dataset=tokenized_dataset["validation"],)
- Finally, we implement learning rate scheduling with dynamic warmup
This implementation provides two common learning rate scheduling strategies:num_training_steps = len(tokenized_dataset["train"]) //training_args.per_device_train_batch_size * num_epochsif scheduler_type == "linear":scheduler = get_linear_schedule_with_warmup(trainer.optimizer,num_warmup_steps=num_training_steps // 10, # 10% warmupnum_training_steps=num_training_steps)elif scheduler_type == "cosine":scheduler = get_cosine_schedule_with_warmup(trainer.optimizer,num_warmup_steps=num_training_steps // 10, # 10% warmupnum_training_steps=num_training_steps)else:raise ValueError("Unsupported scheduler type")
- Linear schedule with warmup: The learning rate increases linearly from
0to the initiallrduring warmup, then decreases linearly to0. We discussed this in Chapter 7 under the Loss functions and optimization strategies section. However, it is important to note that we need to use the same warmup schedule for fine-tuning as well. Warmup helps prevent sudden weight updates early in training, ensuring smoother convergence.- Cosine schedule with warmup: Similar to the linear schedule, but in this case, the decrease follows a cosine curve.
- Linear schedule with warmup: The learning rate increases linearly from
These scheduling strategies can help stabilize training and potentially lead to better convergence.
Domain-specific fine-tuning techniques
Section titled “Domain-specific fine-tuning techniques”When fine-tuning LLMs for specific domains, we often need to adapt our approach. Let’s look at an example of domain-specific fine-tuning for a scientific corpus. The following code implements domain-specific fine-tuning for scientific text using custom dataset preparation and training configuration:
- First, we set up the dataset preparation for scientific text with a specified block size and language
import torchfrom transformers import (TextDataset, DataCollatorForLanguageModeling )def prepare_scientific_dataset(file_path, tokenizer):dataset = TextDataset(tokenizer=tokenizer,file_path=file_path,block_size=128,)data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False,)return dataset, data_collator
- Next, we handle dataset preparation for both training
def fine_tune_for_scientific_domain(model, tokenizer, train_file, eval_file,output_dir="./scientific_model"):train_dataset, data_collator =prepare_scientific_dataset(train_file, tokenizer)eval_dataset, _ = prepare_scientific_dataset(eval_file, tokenizer)
- Finally, we configure optimized training parameters for scientific
training_args = TrainingArguments(output_dir=output_dir,num_train_epochs=3, # Reduced epochsper_device_train_batch_size=8, # Increased batch sizeper_device_eval_batch_size=8,warmup_steps=1000, # Increased warmupweight_decay=0.1, # Increased weight decaylearning_rate=3e-5, # Added learning ratelogging_dir="./logs",evaluation_strategy="steps", # Changed to stepseval_steps=500, # Added eval frequencysave_steps=500, # Added save frequencygradient_accumulation_steps=4 # Added gradient accumulation)
This implementation includes several domain-specific considerations:
- Custom dataset preparation: We use
TextDatasetto handle domain-specific text files - Smaller batch size: Scientific texts often have longer sequences, so we reduce the batch size
- More epochs: Domain adaptation might require more training iterations
- Regular evaluation: After each epoch, we evaluate the model to track validation loss and key domain-specific metrics, ensuring proper adaptation
When fine-tuning for specific domains, consider the following steps:
- Adapting the vocabulary for domain-specific terms
- Using domain-specific evaluation metrics
- Potentially modifying the model architecture for domain-specific features
In the following section, we’ll explore a couple of strategies for fine-tuning models with little to no labeled data from the target domain.
Few-shot and zero-shot fine-tuning
Section titled “Few-shot and zero-shot fine-tuning”Few-shot and zero-shot learning are powerful techniques for adapting LLMs to new tasks with minimal or no task-specific training data. Let’s implement a few-shot fine-tuning approach:
- We create a prompt that includes a few examples of
def prepare_few_shot_dataset(examples, tokenizer, num_shots=5):few_shot_examples = examples[:num_shots]prompt = "\n\n".join([f"Input: {ex['input']}\n"f"Output: {ex['output']}"for ex in few_shot_examples])prompt += "\n\nInput: {input}\nOutput:"def tokenize_function(example):full_prompt = prompt.format(input=example['input'])tokenized_prompt = tokenizer(full_prompt,truncation=True,padding="max_length", max_length=512)tokenized_output = tokenizer(example['output'], truncation=True,padding="max_length", max_length=512)tokenized_prompt['labels'] = \[-100] * len(tokenized_prompt['input_ids'])+ tokenized_output['input_ids']return tokenized_promptreturn examples.map(tokenize_function)
- The model is then fine-tuned on this
Thedef few_shot_fine_tune(model, tokenizer, dataset, num_shots=5, num_epochs=3):few_shot_dataset = prepare_few_shot_dataset(dataset,tokenizer, num_shots)training_args = TrainingArguments(output_dir="./few_shot_model",num_train_epochs=num_epochs,per_device_train_batch_size=4,per_device_eval_batch_size=4,warmup_steps=100,weight_decay=0.01,logging_dir="./logs",)trainer = Trainer(model=model,args=training_args,train_dataset=few_shot_dataset,)trainer.train()return trainer
few_shot_fine_tunefunction implements few-shot fine-tuning, which adapts a pre-trained model to new tasks using minimal examples. It takes a model, tokenizer, dataset, and configuration parameters (num_shots=5,num_epochs=3), then prepares a small subset of the data withprepare_few_shot_dataset, configures training withTrainingArguments(specifying output locations, batch sizes, and optimization parameters), initializes aTrainerobject with these components, executes the training process viatrainer.train(), and finally returns the trained model wrapped in theTrainerobject—all using the Hugging Face Transformers library framework commonly used for language models. - The fine-tuned model can then generalize to new instances of
# Usagemodel, tokenizer = load_model_and_tokenizer()dataset = load_dataset("your_dataset") # Load your few-shot datasetfew_shot_trainer = few_shot_fine_tune(model, tokenizer, dataset)
This implementation demonstrates few-shot fine-tuning.
For zero-shot learning, you would typically rely on the pre-trained model’s ability to understand task descriptions without any task-specific examples or fine-tuning.
Continual fine-tuning and catastrophic forgetting
Section titled “Continual fine-tuning and catastrophic forgetting”Continual fine-tuning involves adapting a model to new tasks while retaining performance on previous tasks. However, this can lead to catastrophic forgetting. Catastrophic forgetting in LLMs refers to the phenomenon where a model loses previously learned information when fine-tuned on new tasks or data without appropriate mechanisms to preserve prior knowledge.
Let’s implement a simple strategy to mitigate this:
- First, we calculate parameter importance and implement elastic weight consolidation (EWC) loss for preserving
import copydef ewc_loss(model, old_model, importance, loss):ewc_lambda = 0.01for n, p in model.named_parameters():if n in importance:loss += ewc_lambda * importance[n]* (p - old_model[n]).pow(2).sum()return lossdef compute_importance(model, dataset):importance = {}model.eval()for batch in dataset:model.zero_grad()output = model(batch)loss = output.lossloss.backward()for n, p in model.named_parameters():if p.grad is not None:if n not in importance:importance[n] = p.grad.data.clone().pow(2)else:importance[n] += p.grad.data.clone().pow(2)return importance
- We then implement the following code, which manages sequential training on multiple tasks while maintaining
def continual_fine_tune(model, tokenizer, datasets, num_epochs=3):old_model = Noneimportance = Nonefor i, dataset in enumerate(datasets):if old_model is not None:importance = compute_importance(old_model, datasets[i-1])old_model = copy.deepcopy(model)tokenized_dataset = dataset.map(lambda examples: tokenize_function(examples,tokenizer),batched=True)
- Finally, we define optimized training parameters for
training_args = TrainingArguments(output_dir=f"./continual_fine_tuned_model_task_{i+1}",num_train_epochs=8, # Increased epochsper_device_train_batch_size=20, # Increased batch sizeper_device_eval_batch_size=20,warmup_steps=2000, # Increased warmupweight_decay=0.2, # Increased weight decaylearning_rate=2e-5, # Added learning ratelogging_dir="./logs",evaluation_strategy="steps", # Added evaluation strategyeval_steps=1000, # Added evaluation frequencysave_steps=1000 # Added save frequency)
This implementation introduces several key concepts for continual fine-tuning:
- EWC: We implement a simplified version of EWC, which adds a penalty term to the loss function to prevent drastic changes to important parameters for previous tasks
- Importance computation: We calculate the importance of each parameter based on its gradient magnitude on the previous task
- Continual fine-tuning loop: We fine-tune the model on each task sequentially, using EWC to mitigate forgetting
- Evaluation on all tasks: After fine-tuning on each new task, we evaluate the model’s performance on all previous tasks to monitor forgetting
The key considerations for continual fine-tuning are as follows:
- Balance between plasticity and stability: EWC helps maintain this balance, allowing the model to learn new tasks while preserving knowledge of previous ones
- Computational overhead: Computing importance and applying EWC increases the computational cost of training
- Task similarity: The effectiveness of continual fine-tuning can depend on the similarity between tasks
Additional strategies to consider for mitigating catastrophic forgetting include the following:
- Gradient episodic memory (GEM): In this approach, a small episodic memory of data from previous tasks is stored and used to constrain the gradient updates on new tasks, as follows:
def project(gradient, memories):for memory in memories:if torch.dot(gradient, memory) < 0:gradient -= (torch.dot(gradient, memory) / torch.dot(memory, memory)) * memoryreturn gradient# This would be integrated into the training loop
- Progressive neural networks: Here, a new “column” of layers for each new task is created, while lateral connections to previously learned features are maintained.
- Learning without Forgetting (LwF): In this approach, knowledge distillation is employed to preserve the model’s performance on
def lwf_loss(model, old_model, new_data, old_data, temperature=2):# Compute standard loss on new datanew_loss = compute_loss(model, new_data)# Compute distillation loss on old dataold_outputs = old_model(old_data)new_outputs = model(old_data)distillation_loss = F.kl_div(F.log_softmax(new_outputs / temperature, dim=1),F.softmax(old_outputs / temperature, dim=1),reduction='batchmean') * (temperature 2)return new_loss + distillation_loss# This would replace the standard loss in the training loop
These advanced techniques can be particularly useful when fine-tuning LLMs across a diverse range of tasks or domains.
Summary
Section titled “Summary”Fine-tuning patterns for LLMs encompass a wide range of techniques, from basic transfer learning to advanced continual learning strategies. By mastering these patterns, you can effectively adapt pre-trained models to new tasks and domains, optimize performance, and mitigate issues such as catastrophic forgetting. As the field of LLMs continues to evolve, staying updated with the latest fine-tuning techniques will be crucial for developing state-of-the-art language models tailored to specific applications.
Here are the key takeaways from this chapter:
- Fine-tuning adapts pre-trained LLMs: Fine-tuning is the key process for adapting general-purpose, pre-trained LLMs to specific tasks and datasets, bridging the gap between general language understanding and specialized performance
- Layer management is crucial: Strategically freezing and unfreezing layers (especially gradual unfreezing) is critical for balancing the preservation of pre-trained knowledge with adaptation to the new task
- Learning rate scheduling stabilizes training: Using learning rate schedules with warmup (linear or cosine) is essential for stable and effective fine-tuning, preventing drastic early updates and promoting convergence
- Domain/task specificity matters: Techniques such as domain-specific vocabulary adaptation, custom data handling, and few-shot/zero-shot approaches are vital for maximizing performance on specialized tasks
- Catastrophic forgetting must be addressed: In continual learning scenarios, techniques such as EWC, GEM, and others are necessary to prevent the model from losing previously learned information when trained on new tasks
We will explore model pruning in the next chapter. Model pruning systematically removes redundant or less important neural connections in LLMs while preserving core functionality, essentially creating a lighter, more efficient version that maintains similar performance but requires fewer computational resources.
Get This Book's PDF Version and Exclusive Extras
|