Okay, I can provide you with an end-to-end code example for fine-tuning LLaVA-1.6-Vicuna-7B on a custom visual question answering (VQA) dataset. I'll also explain the required dataset format.
1. Dataset Preparation
The LLaVA model expects your dataset to be in a JSON format, where each entry represents a single image-question-answer interaction. Here's the structure:
[
{
"id": "unique_id_1",
"image": "path/to/image1.jpg",
"conversations": [
{
"from": "human",
"value": "Question about the image?"
},
{
"from": "gpt",
"value": "The answer to the question."
}
]
},
{
"id": "unique_id_2",
"image": "path/to/image2.jpg",
"conversations": [
{
"from": "human",
"value": "Another question about this image?"
},
{
"from": "gpt",
"value": "The corresponding answer."
}
]
}
// ... more data points
]
Explanation:
id: A unique identifier for each data point (e.g., "train_123", "val_456").
image: The path to the image file. Make sure these paths are correct relative to where you run the training script, or use absolute paths.
conversations: A list of turns in the conversation. For VQA, this will typically be a two-turn conversation:
- The first turn (
"from": "human") contains the question.
- The second turn (
"from": "gpt") contains the answer.
- The
"value" field holds the actual text of the question or answer.
Important considerations for dataset creation:
- Image Paths: Ensure that the image paths in your JSON file are correct and accessible by the training script.
- Data Splitting: Create separate JSON files for training, validation, and potentially testing. A common split is 80% training, 10% validation, and 10% testing.
- Data Cleaning: Carefully review your data for errors in questions, answers, and image paths.
- Dataset Size: The larger and more diverse your dataset, the better LLaVA will perform. However, even fine-tuning on a relatively small, high-quality dataset can yield good results.
2. Environment Setup
Before running the code, make sure you have the necessary libraries installed. You'll likely need:
pip install torch torchvision transformers datasets accelerate sentencepiece # Essential libraries
pip install -U git+https://github.com/haotian-liu/LLaVA.git # Install LLaVA from source (for latest updates)
It's highly recommended to create a virtual environment to manage your dependencies.
3. Fine-tuning Script (Conceptual Outline - Adjust Based on LLaVA's Training Scripts)
I'll provide a simplified outline. You'll need to adapt it to match the specific training scripts and configuration options provided in the LLaVA repository (likely found in their scripts/ directory). Consider this more of a conceptual guide, as the exact script names and argument structures may change.
import os
import torch
from llava.model import LlavaLlamaForCausalLM
from llava.processing import LlavaLlamaForCausalLMProcessor
from datasets import load_dataset, Dataset
from transformers import Trainer, TrainingArguments, default_data_collator
# -------------------- Configuration --------------------
MODEL_NAME = "llava-1.6-vicuna-7b"
DATA_PATH = "path/to/your/train_dataset.json" # Replace with your training data
VALIDATION_DATA_PATH = "path/to/your/validation_dataset.json" # replace with your validation data
OUTPUT_DIR = "path/to/your/output_directory"
BATCH_SIZE = 4
GRADIENT_ACCUMULATION_STEPS = 4
LEARNING_RATE = 2e-5
NUM_EPOCHS = 3
# -------------------- Load Model and Processor --------------------
processor = LlavaLlamaForCausalLMProcessor.from_pretrained(MODEL_NAME)
model = LlavaLlamaForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float16).to("cuda") # Load in float16 to save memory
model.config.use_cache = False # Disable cache for training
# -------------------- Data Preparation --------------------
def load_and_preprocess_data(data_path):
"""Loads the JSON dataset and preprocesses it for LLaVA."""
def tokenize_function(example):
conversations = example["conversations"]
image_path = example["image"]
image = Image.open(image_path).convert("RGB")
input_text = conversations[0]["value"] # Human's question
answer_text = conversations[1]["value"] # GPT's answer
prompt = f"USER: <image/>\n{input_text} ASSISTANT: {answer_text}" # LLaVA style prompt
processed_inputs = processor(images=image, text=prompt, return_tensors="pt", padding="max_length", truncation=True, max_length=512) # Adjust max_length as needed
processed_inputs = {k: v.squeeze(0) for k, v in processed_inputs.items()} # remove batch dimension
return processed_inputs
dataset = load_dataset("json", data_files=data_path)
dataset = dataset.map(tokenize_function, batched=False) # Apply tokenization to each example
dataset = dataset["train"] # Access the 'train' split
return dataset
train_dataset = load_and_preprocess_data(DATA_PATH)
eval_dataset = load_and_preprocess_data(VALIDATION_DATA_PATH)
# -------------------- Training Arguments --------------------
training_args = TrainingArguments(
output_dir=OUTPUT_DIR,
per_device_train_batch_size=BATCH_SIZE,
gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
learning_rate=LEARNING_RATE,
num_train_epochs=NUM_EPOCHS,
logging_steps=10,
save_steps=500,
evaluation_strategy="steps",
eval_steps=200,
save_total_limit=1,
remove_unused_columns=False, # Important for multimodal models
fp16=True, # Use mixed precision training for speed
dataloader_num_workers=2,
)
# -------------------- Trainer --------------------
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
data_collator=default_data_collator, # Can likely use the default
)
# -------------------- Start Training --------------------
trainer.train()
# -------------------- Save the Model --------------------
trainer.save_model(OUTPUT_DIR)
processor.save_pretrained(OUTPUT_DIR) # Save the processor as well
Explanation:
- Configuration: Set your desired model name, data paths, and training hyperparameters (batch size, learning rate, number of epochs, etc.).
- Model and Processor Loading: Load the LLaVA model and processor using
from_pretrained(). The processor handles tokenization, image resizing, and other preprocessing steps. The model is loaded to the available CUDA device if present.
- Data Preparation:
- Loads the JSON dataset.
- The
tokenize_function preprocesses each data point:
- Opens the image using the path in the JSON.
- Constructs a prompt in the format LLaVA expects (e.g.,
"USER: <image/>\nQuestion ASSISTANT: Answer").
- Uses the
processor to tokenize the prompt and prepare the image for input to the model.
- Training Arguments: Configures the training process using
TrainingArguments. Key parameters include:
output_dir: Where to save the trained model.
per_device_train_batch_size: Batch size per GPU.
gradient_accumulation_steps: Accumulate gradients to simulate a larger batch size.
learning_rate: The learning rate for the optimizer.
num_train_epochs: The number of training epochs.
fp16: Enables mixed-precision training for faster training and reduced memory usage.
remove_unused_columns=False: Important for multimodal models to prevent the trainer from removing image-related columns.
- Trainer: Creates a
Trainer instance, passing in the model, training arguments, training dataset, and a data collator. The default_data_collator is usually sufficient.
- Training: Starts the training loop with
trainer.train().
- Saving: Saves the trained model and processor to the specified output directory.
Important Notes:
- Adaptation: This is a general outline. You must adapt it to the specifics of the LLaVA repository's training scripts. Carefully examine their example training scripts (likely in the
scripts/ directory) to understand the correct argument names, data loading procedures, and any custom training loops they might use. Look for scripts related to fine-tuning or VQA.
- Memory: LLaVA models can be large. You may need to reduce the batch size, use gradient accumulation, and enable mixed-precision training (
fp16=True) to fit the model in GPU memory.
- Dataset Location: Place your training and validation JSON files in accessible locations.
- Image Handling: Ensure that the
Image.open() function can correctly open your image files.
- Evaluation: Include a validation dataset and configure
evaluation_strategy and eval_steps in TrainingArguments to monitor the model's performance during training.
4. Running the Script
-
Save the code as a Python file (e.g., train_llava.py).
-
Make sure your dataset is in the correct JSON format and located in the paths specified in the script.
-
Run the script from your terminal:
python train_llava.py
Troubleshooting:
- CUDA Errors: If you encounter CUDA errors, make sure you have a compatible version of CUDA installed and that PyTorch is using your GPU.
- Memory Errors: Reduce the batch size, use gradient accumulation, and enable mixed-precision training (
fp16=True).
- Data Loading Errors: Double-check the paths to your dataset and images. Ensure that the JSON format is correct.
- Loss Not Decreasing: Experiment with different learning rates and hyperparameters. Examine your dataset for potential issues.
This detailed guide should help you get started with fine-tuning LLaVA on your custom VQA dataset. Remember to consult the official LLaVA documentation and examples for the most up-to-date information and best practices.