To fine-tune the gemma-2-2b model on a T4 GPU with 15GB VRAM and incorporate Bayesian optimization to enhance performance and model reasoning, we need to make several adjustments to your original script. Below is a comprehensive guide with the necessary modifications and explanations:
1. Adjusting for T4 GPU Constraints
The NVIDIA T4 GPU has 15GB of VRAM, which requires careful management of model parameters, batch sizes, and sequence lengths to prevent out-of-memory (OOM) errors. Here’s how to optimize your setup:
- Use 4-bit Quantization: You’re already leveraging 4-bit quantization (
load_in_4bit = True), which significantly reduces memory usage.
- Batch Size and Gradient Accumulation: Adjust these to fit within the VRAM constraints. For a T4 with 15GB VRAM, a batch size of 2 with gradient accumulation steps of 4 is reasonable.
- Sequence Length: While you’ve set
max_seq_length = 2048, depending on your specific tasks and memory usage, you might need to reduce it. However, since you’re using 4-bit quantization and efficient modules, 2048 should be manageable.
2. Incorporating Bayesian Optimization
Bayesian optimization is a powerful technique for hyperparameter tuning that can help you find the optimal set of hyperparameters to improve model performance. We can integrate Bayesian optimization using the optuna library, which is compatible with many deep learning frameworks.
3. Complete Optimized Script
Below is the optimized script tailored for a T4 GPU with 15GB VRAM and enhanced with Bayesian optimization for hyperparameter tuning:
# Install necessary packages
!pip install unsloth
# Get the latest nightly Unsloth
!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
# Install Flash Attention 2 for softcapping support
import torch
if torch.cuda.get_device_capability()[0] >= 8:
!pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
from unsloth import FastLanguageModel
import torch
# Configuration parameters
max_seq_length = 2048 # Adjust if necessary
dtype = None # Auto-detection
load_in_4bit = True # 4-bit quantization
# List of 4-bit pre-quantized models
fourbit_models = [
"unsloth/Meta-Llama-3.1-8B-bnb-4bit",
"unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
"unsloth/Meta-Llama-3.1-70B-bnb-4bit",
"unsloth/Meta-Llama-3.1-405B-bnb-4bit",
"unsloth/Mistral-Nemo-Base-2407-bnb-4bit",
"unsloth/Mistral-Nemo-Instruct-2407-bnb-4bit",
"unsloth/mistral-7b-v0.3-bnb-4bit",
"unsloth/mistral-7b-instruct-v0.3-bnb-4bit",
"unsloth/Phi-3-mini-4k-instruct",
"unsloth/Phi-3-medium-4k-instruct",
"unsloth/gemma-2-9b-bnb-4bit",
"unsloth/gemma-2-27b-bnb-4bit",
"unsloth/gemma-2-2b-bnb-4bit",
] # More models available at https://huggingface.co/unsloth
# Load the model and tokenizer
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/gemma-2-2b",
max_seq_length=max_seq_length,
dtype=dtype,
load_in_4bit=load_in_4bit,
)
# Apply PEFT (Parameter-Efficient Fine-Tuning) with LoRA
model = FastLanguageModel.get_peft_model(
model,
r=16, # LoRA rank
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
lora_alpha=16,
lora_dropout=0, # Optimized for performance
bias="none", # Optimized setting
use_gradient_checkpointing="unsloth", # Reduces memory usage
random_state=3407,
use_rslora=False, # Disable if not using rank stabilized LoRA
loftq_config=None, # Disable LoftQ if not used
)
# Prepare the Alpaca prompt formatting
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
EOS_TOKEN = tokenizer.eos_token # Essential for stopping generation
def formatting_prompts_func(examples):
instructions = examples["instruction"]
inputs = examples["input"]
outputs = examples["output"]
texts = []
for instruction, input_text, output in zip(instructions, inputs, outputs):
# Append EOS_TOKEN to prevent infinite generation
text = alpaca_prompt.format(instruction, input_text, output) + EOS_TOKEN
texts.append(text)
return {"text": texts}
# Load and preprocess the dataset
from datasets import load_dataset
dataset = load_dataset("yahma/alpaca-cleaned", split="train")
dataset = dataset.map(formatting_prompts_func, batched=True)
# Bayesian Optimization for Hyperparameter Tuning
import optuna
from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported
# Define the objective function for Optuna
def objective(trial):
# Define hyperparameters to tune
per_device_train_batch_size = trial.suggest_categorical('per_device_train_batch_size', [1, 2, 4])
gradient_accumulation_steps = trial.suggest_categorical('gradient_accumulation_steps', [2, 4, 8])
learning_rate = trial.suggest_loguniform('learning_rate', 1e-5, 1e-3)
lora_alpha = trial.suggest_categorical('lora_alpha', [8, 16, 32])
# Initialize TrainingArguments with trial parameters
training_args = TrainingArguments(
per_device_train_batch_size=per_device_train_batch_size,
gradient_accumulation_steps=gradient_accumulation_steps,
warmup_steps=5,
num_train_epochs=1, # For full training, adjust as needed
max_steps=60,
learning_rate=learning_rate,
fp16=not is_bfloat16_supported(),
bf16=is_bfloat16_supported(),
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.01,
lr_scheduler_type="linear",
seed=3407,
output_dir="outputs",
)
# Initialize the trainer with trial hyperparameters
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
dataset_text_field="text",
max_seq_length=max_seq_length,
dataset_num_proc=2,
packing=False,
args=training_args,
)
# Train the model
trainer.train()
# Evaluate the model (you can define a validation metric)
# For simplicity, we'll return the loss
eval_results = trainer.evaluate()
return eval_results["eval_loss"]
# Create and run the Optuna study
study = optuna.create_study(direction='minimize')
study.optimize(objective, n_trials=10) # Adjust n_trials as needed
# Retrieve the best hyperparameters
best_params = study.best_params
print("Best Hyperparameters:", best_params)
# Train the final model with the best hyperparameters
final_training_args = TrainingArguments(
per_device_train_batch_size=best_params['per_device_train_batch_size'],
gradient_accumulation_steps=best_params['gradient_accumulation_steps'],
warmup_steps=5,
num_train_epochs=1, # Adjust for full training
max_steps=60,
learning_rate=best_params['learning_rate'],
fp16=not is_bfloat16_supported(),
bf16=is_bfloat16_supported(),
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.01,
lr_scheduler_type="linear",
seed=3407,
output_dir="outputs_final",
)
final_trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
dataset_text_field="text",
max_seq_length=max_seq_length,
dataset_num_proc=2,
packing=False,
args=final_training_args,
)
# Start the final training
final_trainer.train()
4. Explanation of Modifications
-
Batch Size and Gradient Accumulation:
- Initial Setup: Kept batch size at 2 with gradient accumulation steps of 4.
- Bayesian Optimization: Tuned
per_device_train_batch_size and gradient_accumulation_steps to find the optimal balance between memory usage and training speed.
-
Learning Rate and LoRA Parameters:
- Optimization: Used Bayesian optimization (
optuna) to find the best learning rate and LoRA alpha value, which can significantly impact training effectiveness.
-
Hyperparameter Tuning with Optuna:
- Objective Function: Defined an objective function that trains the model and evaluates it based on validation loss.
- Study: Created an Optuna study to minimize the evaluation loss by tuning hyperparameters.
- Final Training: After finding the best hyperparameters, re-trained the model using these optimized settings.
-
Memory Management:
- 4-bit Quantization: Enabled to fit larger models within the 15GB VRAM of the T4 GPU.
- Gradient Checkpointing: Utilized to reduce memory usage during training, allowing for longer sequence lengths.
-
Bayesian Optimization Integration:
- Optuna Library: Integrated
optuna for efficient hyperparameter tuning based on Bayesian optimization principles, which uses the past evaluation results to choose the next set of hyperparameters to evaluate.
-
Validation and Evaluation:
- Evaluation Metric: Used evaluation loss as the primary metric for optimization. Depending on your requirements, you might want to include additional metrics.
5. Additional Recommendations
- Extended Training: The current setup trains for only one epoch (
num_train_epochs=1) with max_steps=60. For better performance, consider increasing these values based on your dataset size and training objectives.
- Validation Set: Incorporate a validation set to more accurately measure performance and prevent overfitting.
- Model Checkpointing: Save model checkpoints at intervals to prevent loss of progress in case of interruptions.
- Monitoring: Use tools like TensorBoard to monitor training progress and hyperparameter optimization in real-time.
6. Conclusion
By adjusting batch sizes, leveraging 4-bit quantization, and incorporating Bayesian optimization for hyperparameter tuning, this setup is optimized to run efficiently on a T4 GPU with 15GB VRAM. Bayesian optimization helps in systematically finding the best hyperparameters, leading to improved model performance and more nuanced "thought processes." Ensure you monitor GPU memory usage during training and adjust parameters accordingly to avoid OOM errors.