Introduction
Fine-tuning a Large Language Model (LLM) on instruction data while mixing in pretraining data is a nuanced process that requires careful consideration of hyperparameters, especially the learning rate and its schedule. Mixing pretraining data can help prevent catastrophic forgetting and maintain the model's general language understanding capabilities. In this guide, we'll delve into detailed recommendations for setting the learning rate and its schedule during such fine-tuning, considering different scenarios and best practices.
1. Understanding the Role of Learning Rate in Fine-tuning
The learning rate is a crucial hyperparameter that controls how much the model's weights are updated during training. In fine-tuning:
- Smaller Learning Rates are typically used compared to pretraining to make subtle adjustments without drastically altering the pretrained weights.
- Learning Rate Schedules help in gradually adjusting the learning rate during training to improve convergence and prevent oscillations.
2. General Guidelines for Setting Learning Rate
When fine-tuning on a mix of pretraining and instruction data:
-
Base Learning Rate (lr_base):
-
Warmup Phase:
- Purpose: Gradually increase the learning rate from zero to the base value to prevent sudden shocks to the pretrained weights.
- Warmup Steps (
N_{\text{warmup}}):
- Typical Proportion: 1% to 5% of total training steps.
- Linear Warmup: Learning rate increases linearly during warmup.
- Example: For 10,000 total steps:
- ( N_{\text{warmup}} = 0.01 \times 10,000 = 100 ) steps.
3. Choosing a Learning Rate Schedule
The learning rate schedule dictates how the learning rate changes after the warmup phase. Common schedules include:
-
Cosine Decay Schedule:
-
Description: The learning rate follows a half-cosine curve from the base value down to a minimum value.
-
Formula:
[
\text{lr}(t) = \frac{1}{2} \left(1 + \cos\left(\pi \times \frac{t - N_{\text{warmup}}}{N_{\text{total}} - N_{\text{warmup}}}\right)\right) \times (\text{lr}{\text{base}} - \text{lr}{\text{min}}) + \text{lr}_{\text{min}}
]
- ( t ): Current training step.
- ( N_{\text{total}} ): Total training steps.
- ( \text{lr}_{\text{min}} ): Minimum learning rate (often set to (1 \times 10^{-6}) or zero).
-
Advantages:
- Smooth decay helps in refined adjustments.
- Commonly used in pretraining, maintaining consistency.
-
Linear Decay Schedule:
-
Description: Linearly decreases the learning rate from the base value to the minimum value after warmup.
-
Formula:
[
\text{lr}(t) = \left(1 - \frac{t - N_{\text{warmup}}}{N_{\text{total}} - N_{\text{warmup}}}\right) \times (\text{lr}{\text{base}} - \text{lr}{\text{min}}) + \text{lr}_{\text{min}}
]
-
Advantages:
- Simplicity.
- Effective for shorter training durations.
-
Constant Learning Rate:
- Description: Keeps the learning rate constant after warmup.
- Use Case: Suitable for small datasets or when fine-tuning for a few epochs.
4. Mixing Pretraining and Instruction Data
When mixing datasets:
-
Proportion of Data:
- Balanced Mix: Commonly, a 50-50 mix is used, but you may adjust based on:
- Dataset Sizes: Larger instruction datasets may require a higher proportion.
- Training Goals: Emphasize instruction data for better instruction-following performance.
-
Sampling Strategy:
- Interleaved Sampling: Shuffle and mix batches from both datasets.
- Curriculum Learning: Start with more pretraining data, gradually increasing instruction data proportion.
-
Loss Scaling:
- Equal Weighting: Losses from both datasets contribute equally.
- Weighted Losses: Adjust weights if one dataset is more critical.
5. Scenario-Based Considerations
-
If Pretraining Used Cosine Schedule:
- Recommendation: Continue with a cosine decay schedule for consistency.
- Adjustments:
- Shorter total steps in fine-tuning require adjusting the decay rate.
-
If Pretraining Used a Different Schedule:
- Flexibility: You're not bound to the pretraining schedule.
- Choose Based on Fine-tuning Needs:
- Cosine Decay: Good for smooth convergence.
- Linear Decay: Effective for shorter training times.
- Empirical Testing: Try different schedules and monitor validation metrics.
6. Detailed Steps for Setting Learning Rate and Schedule
-
Estimate Total Training Steps (N_{\text{total}}):
- Formula:
[
N_{\text{total}} = \frac{\text{Total Samples} \times \text{Epochs}}{\text{Batch Size}}
]
-
Set Base Learning Rate (\text{lr}_{\text{base}}):
- Start with (1 \times 10^{-5}) or adjust using linear scaling.
-
Determine Warmup Steps (N_{\text{warmup}}):
- Typically 1% to 5% of
N_total.
-
Choose Minimum Learning Rate (\text{lr}_{\text{min}}):
- Often set to zero or a small fraction of
lr_base, e.g., (1 \times 10^{-6}).
-
Select Learning Rate Schedule:
- Use the formulas provided for either cosine decay or linear decay.
-
Implement the Schedule in Training Loop:
- Framework Tools: Use learning rate schedulers provided by deep learning frameworks (e.g., PyTorch's
lr_scheduler).
-
Mix Datasets Appropriately:
- Ensure batches contain the desired proportion of pretraining and instruction data.
-
Monitor Training:
- Metrics: Track training loss, validation loss, and specific evaluation metrics.
- Adjust if Necessary: If overfitting occurs, consider reducing learning rate or implementing early stopping.
7. Additional Recommendations
-
Gradient Clipping:
- Purpose: Prevent exploding gradients.
- Typical Value: Clip gradients at a norm of 1.0.
-
Weight Decay (L2 Regularization):
- Purpose: Prevent overfitting by penalizing large weights.
- Typical Range: (1 \times 10^{-2}) to (1 \times 10^{-1}).
-
Optimizer Choice:
- AdamW: Commonly used with appropriate beta values.
- Parameter Adjustments:
- (\beta_1 = 0.9), (\beta_2 = 0.999), (\epsilon = 1 \times 10^{-8}).
-
Batch Size and Accumulation:
- Large Batch Sizes: Improves training stability.
- Gradient Accumulation: Simulate larger batch sizes if limited by hardware.
-
Mixed Precision Training:
- Advantages: Reduced memory usage, faster computation.
- Implementation: Use frameworks' automatic mixed-precision tools (e.g., PyTorch's
autocast).
-
Logging and Checkpointing:
- Regular Checkpoints: Save model state periodically.
- Detailed Logs: Record hyperparameters, metrics, and observations.
8. Final Thoughts
Fine-tuning LLMs on a mix of pretraining and instruction data is an iterative process that may require experimentation:
- Start with Conservative Settings: Use lower learning rates and monitor performance.
- Adjust Based on Feedback: Use validation metrics to guide adjustments.
- Keep Consistency: If pretraining used a particular schedule and it worked well, it can be beneficial to maintain that consistency.
Remember, the goal is to enhance the model's ability to follow instructions without losing its general language understanding capabilities acquired during pretraining.
Example Implementation:
# Pseudo-code for setting up learning rate and schedule
# Hyperparameters
lr_base = 1e-5 # Base learning rate
lr_min = 0 # Minimum learning rate
num_training_steps = total_samples * epochs // batch_size
warmup_steps = int(0.01 * num_training_steps) # 1% of total steps
# Scheduler Setup (Using PyTorch as an example)
from transformers import get_cosine_schedule_with_warmup
optimizer = AdamW(model.parameters(), lr=lr_base, weight_decay=0.01)
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=num_training_steps
)
# Training Loop
for epoch in range(epochs):
for batch in dataloader:
# Forward pass
outputs = model(**batch)
loss = outputs.loss
# Backward pass
loss.backward()
# Optimizer step
optimizer.step()
scheduler.step() # Update learning rate
optimizer.zero_grad()
Conclusion
Setting the learning rate and its schedule during fine-tuning of LLMs on mixed data requires careful consideration of various factors, including the model's pretraining schedule, the characteristics of the datasets, and the computational resources available. By following the detailed guidelines provided, you can effectively fine-tune your LLM to achieve optimal performance on instruction tasks while preserving its foundational language understanding abilities.