Fine Tuning Vlm Dpo Smolvlm Instruct
Fine-tuning SmolVLM using direct preference optimization (DPO) with TRL on a consumer GPU
Authored by: Sergio Paniego
In this recipe, we’ll guide you through fine-tuning a smol 🤏 Vision Language Model (VLM) with Direct Preference Optimization (DPO) using the Transformer Reinforcement Learning (TRL) library to demonstrate how you can tailor VLMs to suit your specific needs, even when working with consumer-grade GPUs.
We’ll fine-tune SmolVLM using a preference dataset to help the model align with desired outputs. SmolVLM is a highly performant and memory-efficient model, making it an ideal choice for this task. If you’re new to Preference Optimization for language or vision-language models, check out this blog for an in-depth introduction.
The dataset we’ll use is HuggingFaceH4/rlaif-v_formatted, which contains pairs of prompt + image along with a chosen and rejected answer for each pair. The goal of this fine-tuning process is to make the model consistently prefer the chosen answers from the dataset, reducing hallucinations.
This notebook has been tested using an NVIDIA L4 GPU.
1. Install Dependencies
Let’s start by installing the essential libraries we’ll need for fine-tuning! 🚀
Authenticate with your Hugging Face account to save and share your model directly from this notebook 🗝️.
2. Load Dataset 📁
We’ll work with the HuggingFaceH4/rlaif-v_formatted dataset, which provides pairs of prompt + image along with a chosen and rejected answers for each pair. This structured format is ideal for training models with Direct Preference Optimization (DPO).
The dataset is already preformatted for this task. If you’re working with a custom dataset, you’ll need to preprocess it into the same format.
In this example, we'll use a subset of the dataset to demonstrate the process. However, in a real-world scenario, you should utilize the full dataset for better performance.
We will ensure all the images are RGB formatted:
Let’s explore an example from the dataset to better understand its structure and the type of data we’re working with.
{'chosen': [{'content': [{'text': "Yes, the grass in the image appears to be brown. This could indicate that the photo was taken during a dry season or in a region that experiences arid conditions. The brown grass contrasts with the grayish color of the elephant and provides a natural background that highlights the elephant's presence in its environment.",
, 'type': 'text'}],
, 'role': 'assistant'}],
, 'rejected': [{'content': [{'text': 'Yes, the grass in the image appears to be brown. This could be due to a number of reasons such as the season (it might be a dry season), the type of grass, or the specific conditions of the environment where the photo was taken. The brown grass contrasts with the grayish color of the elephant and the white branches of the thorny tree, making it a prominent feature of the landscape.',
, 'type': 'text'}],
, 'role': 'assistant'}],
, 'images': [<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x333>],
, 'prompt': [{'content': [{'text': None, 'type': 'image'},
, {'text': 'Does the grass have brown color?', 'type': 'text'}],
, 'role': 'user'}]} 3. Fine-Tune the Model using TRL
3.1 Load the Quantized Model for Training ⚙️
Let's first load a quantized version of the SmolVLM-Instruct model using bitsandbytes, and let's also load the processor. We'll use SmolVLM-Instruct.
3.2 Set Up QLoRA and DPOConfig 🚀
In this step, we’ll configure QLoRA for our training setup. QLoRA is a powerful fine-tuning technique designed to reduce the memory footprint, making it possible to fine-tune large models efficiently, even on limited hardware.
QLoRA builds upon traditional LoRA (Low-Rank Adaptation) by introducing quantization for the adapter weights. This enhancement leads to significantly lower memory usage and faster training, making it an ideal choice for resource-constrained environments.
trainable params: 11,269,248 || all params: 2,257,542,128 || trainable%: 0.4992
Next, we will configure the training options using DPOConfig.
We will define the training arguments for Direct Preference Optimization (DPO) with the DPOTrainer class from the TRL library.
DPO uses labeled preference data to guide the model toward generating responses that align with preferences. TRL's DPOTrainer will tokenize the dataset before training and save it to disk. This process can consume significant disk space, depending on the amount of data used for training. Plan accordingly to avoid running out of storage.
This step may take a while, so feel free to relax and enjoy the process! 😄
Time to train the model! 🎉
Let's save the results 💾
4. Testing the Fine-Tuned Model 🔍
With our Vision Language Model (VLM) fine-tuned, it’s time to evaluate its performance! In this section, we’ll test the model using examples from the HuggingFaceH4/rlaif-v_formatted dataset. Let’s dive into the results and assess how well the model aligns with the preferred responses! 🚀
Before we begin, let’s clean up the GPU memory to ensure smooth and optimal performance. 🧹
GPU allocated memory: 1.64 GB GPU reserved memory: 2.01 GB
We will reload the base model using the same pipeline as before.
We will attach the trained adapter to the pretrained model. This adapter contains the fine-tuning adjustments made during training, enabling the base model to leverage the new knowledge while keeping its core parameters intact. By integrating the adapter, we enhance the model's capabilities without altering its original structure.
Let's evaluate the model on an unseen sample.
{'chosen': [{'content': [{'text': "In the image, there's a dynamic scene at what appears to be a beach or surfing location. The main focus is on a person skillfully riding a wave on a surfboard. This individual is dressed in a yellow shirt and seems to be enjoying the activity. In addition to the surfer, there are other elements in the scene such as waves breaking and creating white foam, indicating the active nature of the water. Nearby, there's another surfboard floating on the surface of the water, suggesting that more people might be participating in surfing or waiting for their turn. The overall atmosphere conveys a sense of fun, adventure, and connection with nature.",
, 'type': 'text'}],
, 'role': 'assistant'}],
, 'rejected': [{'content': [{'text': 'In the image, there is a man enthusiastically surfing on a wave in the ocean. He is wearing a yellow shirt and short pants, adding a vibrant color contrast to the scene. The surfer is skillfully balancing himself on his surfboard as he rides the wave. Additionally, there are other surfers and surfboards scattered throughout the water, indicating that this might be a popular spot for surfing. The overall atmosphere suggests an active and fun beach day with people enjoying the watersport.',
, 'type': 'text'}],
, 'role': 'assistant'}],
, 'images': [<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=640x428>],
, 'prompt': [{'content': [{'text': None, 'type': 'image'},
, {'text': 'Provide an intricate description of every entity in the image.',
, 'type': 'text'}],
, 'role': 'user'}]} Let’s create a common function that we can call with different samples to streamline the testing process. This function will allow us to evaluate the model’s performance on multiple examples efficiently without needing to rewrite code for each one. By using this reusable function, we can quickly assess how well the model performs across a variety of inputs.
Now, we’re ready to call the function and evaluate the model! 🚀
" The image depicts a scene of a person surfing in the ocean. The central figure is a man standing on a surfboard, facing the camera with a joyful expression. He is wearing a bright green rash guard and dark-colored board shorts. The surfboard is white and blue, indicating it is a beginner-friendly board suitable for learning to surf.\n\nSurrounding the man, there are several other individuals in the water. Two people are visible in the background, swimming near the shore. The water is moderately choppy, with small waves breaking on the shore. The waves are white and foamy, indicating they are relatively small and gentle.\n\nIn the background, there is a distant coastline with a few buildings and structures visible. The sky is clear, with a few faint clouds visible. The overall setting appears to be a beach or coastal area, with the ocean and waves as the primary focus.\n\nThe image captures a moment of joy and accomplishment, as the surfer is enjoying the experience of surfing. The man's posture and expression suggest he is having a great time, and the overall scene conveys a sense of adventure and excitement.\n\n### Analysis and Description:\n1. **Surfer**: The man is the central figure in the image, standing on a surfboard and facing the camera. He is wearing a rash guard and board shorts, typical attire for surfing.\n2. **Surfboard**: The surfboard is white and blue, indicating it is a beginner-friendly board suitable for learning to surf.\n3. **Waves**: The waves are small and gentle, breaking on the shore.\n4. **Coastline**: The background features a distant coastline with a few buildings and structures visible.\n5. **Sky**: The sky is clear, with a few faint clouds visible.\n\n### Relevant Knowledge:\n- **Surfing**: Surfing is a water sport that involves standing on a surfboard and riding the waves. It is a popular activity in coastal areas, requiring balance, coordination, and a certain level of skill.\n- **Rash guard**: A rash guard is a short-sleeved, moisture-wicking garment worn by surfers to protect their skin from the sun and the elements.\n- **Board shorts**: Board shorts are a type of swimwear designed to be comfortable and supportive for extended periods in the water.\n\n### Conclusion:\nThe image captures a moment of joy and accomplishment in the sport of surfing. The surfer is enjoying the experience, and the overall setting suggests a beach or coastal area. The image provides a glimpse into the excitement and adventure of surfing, highlighting the skill and enjoyment involved in the sport."
The model is now able to generate responses based on the provided image and prompt. For tasks like this, it’s useful to compare your model's performance against a benchmark to see how much it has improved and how it stacks up against other options. For more information and details on this comparison, check out this post.
💻 I’ve developed an example application to test the model, which you can find here.
Since here we only run an example training with a subset of the dataset, for the Space I've used the official Hugging Face DPO fine tuned model. You can easily compare it with another Space featuring the pre-trained model, available here.
5. Continuing the Learning Journey 🧑🎓️
Expand your knowledge of Vision Language Models and related tools with these resources:
-
Multimodal Recipes in the Cookbook: Discover practical recipes for multimodal models, including Retrieval-Augmented Generation (RAG) pipelines and fine-tuning. We’ve already published a recipe for fine-tuning a smol VLM with TRL using SFT, which complements this guide perfectly—check it out for additional details.
-
TRL Community Tutorials: Explore a rich collection of tutorials that dive into the intricacies of TRL and its real-world applications.
You can also revisit the Continuing the Learning Journey section in Fine-Tuning a Vision Language Model (Qwen2-VL-7B) with the Hugging Face Ecosystem (TRL).
These resources will help deepen your knowledge and expertise in multimodal learning.