Visual Question Answering
Visual Question Answering (VQA) is the task of answering open-ended questions based on an image. The input to models supporting this task is typically a combination of an image and a question, and the output is an answer expressed in natural language.
Some noteworthy use case examples for VQA include:
Accessibility applications for visually impaired individuals.
Education: posing questions about visual materials presented in lectures or textbooks. VQA can also be utilized in interactive museum exhibits or historical sites.
Customer service and e-commerce: VQA can enhance user experience by letting users ask questions about products.
Image retrieval: VQA models can be used to retrieve images with specific characteristics. For example, the user can ask “Is there a dog?” to find all images with dogs from a set of images.
In this guide you’ll learn how to:
Fine-tune a classification VQA model, specifically ViLT, on the
Graphcore/vqa
dataset.Use your fine-tuned ViLT for inference.
Run zero-shot VQA inference with a generative model, like BLIP-2.
Fine-tuning ViLT
ViLT model incorporates text embeddings into a Vision Transformer (ViT), allowing it to have a minimal design for Vision-and-Language Pre-training (VLP). This model can be used for several downstream tasks. For the VQA task, a classifier head is placed on top (a linear layer on top of the final hidden state of the [CLS]
token) and randomly initialized. Visual Question Answering is thus treated as a classification problem.
More recent models, such as BLIP, BLIP-2, and InstructBLIP, treat VQA as a generative task. Later in this guide we illustrate how to use them for zero-shot VQA inference.
Before you begin, make sure you have all the necessary libraries installed.
Copied
We encourage you to share your model with the community. Log in to your BOINC AI account to upload it to the 🌍 Hub. When prompted, enter your token to log in:
Copied
Let’s define the model checkpoint as a global variable.
Copied
Load the data
For illustration purposes, in this guide we use a very small sample of the annotated visual question answering Graphcore/vqa
dataset. You can find the full dataset on 🌍 Hub.
As an alternative to the Graphcore/vqa
dataset, you can download the same data manually from the official VQA dataset page. If you prefer to follow the tutorial with your custom data, check out how to Create an image dataset guide in the 🌍 Datasets documentation.
Let’s load the first 200 examples from the validation split and explore the dataset’s features:
Copied
Let’s take a look at an example to understand the dataset’s features:
Copied
The features relevant to the task include:
question
: the question to be answered from the imageimage_id
: the path to the image the question refers tolabel
: the annotations
We can remove the rest of the features as they won’t be necessary:
Copied
As you can see, the label
feature contains several answers to the same question (called ids
here) collected by different human annotators. This is because the answer to a question can be subjective. In this case, the question is “where is he looking?“. Some people annotated this with “down”, others with “at table”, another one with “skateboard”, etc.
Take a look at the image and consider which answer would you give:
Copied
Due to the questions’ and answers’ ambiguity, datasets like this are treated as a multi-label classification problem (as multiple answers are possibly valid). Moreover, rather than just creating a one-hot encoded vector, one creates a soft encoding, based on the number of times a certain answer appeared in the annotations.
For instance, in the example above, because the answer “down” is selected way more often than other answers, it has a score (called weight
in the dataset) of 1.0, and the rest of the answers have scores < 1.0.
To later instantiate the model with an appropriate classification head, let’s create two dictionaries: one that maps the label name to an integer and vice versa:
Copied
Now that we have the mappings, we can replace the string answers with their ids, and flatten the dataset for a more convenient further preprocessing.
Copied
Preprocessing data
The next step is to load a ViLT processor to prepare the image and text data for the model. ViltProcessor wraps a BERT tokenizer and ViLT image processor into a convenient single processor:
Copied
To preprocess the data we need to encode the images and questions using the ViltProcessor. The processor will use the BertTokenizerFast to tokenize the text and create input_ids
, attention_mask
and token_type_ids
for the text data. As for images, the processor will leverage ViltImageProcessor to resize and normalize the image, and create pixel_values
and pixel_mask
.
All these preprocessing steps are done under the hood, we only need to call the processor
. However, we still need to prepare the target labels. In this representation, each element corresponds to a possible answer (label). For correct answers, the element holds their respective score (weight), while the remaining elements are set to zero.
The following function applies the processor
to the images and questions and formats the labels as described above:
Copied
To apply the preprocessing function over the entire dataset, use 🌍 Datasets map
function. You can speed up map
by setting batched=True
to process multiple elements of the dataset at once. At this point, feel free to remove the columns you don’t need.
Copied
As a final step, create a batch of examples using DefaultDataCollator:
Copied
Train the model
You’re ready to start training your model now! Load ViLT with ViltForQuestionAnswering. Specify the number of labels along with the label mappings:
Copied
At this point, only three steps remain:
Define your training hyperparameters in TrainingArguments:
Copied
Pass the training arguments to Trainer along with the model, dataset, processor, and data collator.
Copied
Call train() to finetune your model.
Copied
Once training is completed, share your model to the Hub with the push_to_hub() method to share your final model on the 🌍 Hub:
Copied
Inference
Now that you have fine-tuned a ViLT model, and uploaded it to the 🌍 Hub, you can use it for inference. The simplest way to try out your fine-tuned model for inference is to use it in a Pipeline.
Copied
The model in this guide has only been trained on 200 examples, so don’t expect a lot from it. Let’s see if it at least learned something from the data and take the first example from the dataset to illustrate inference:
Copied
Even though not very confident, the model indeed has learned something. With more examples and longer training, you’ll get far better results!
You can also manually replicate the results of the pipeline if you’d like:
Take an image and a question, prepare them for the model using the processor from your model.
Forward the result or preprocessing through the model.
From the logits, get the most likely answer’s id, and find the actual answer in the
id2label
.
Copied
Zero-shot VQA
The previous model treated VQA as a classification task. Some recent models, such as BLIP, BLIP-2, and InstructBLIP approach VQA as a generative task. Let’s take BLIP-2 as an example. It introduced a new visual-language pre-training paradigm in which any combination of pre-trained vision encoder and LLM can be used (learn more in the BLIP-2 blog post). This enables achieving state-of-the-art results on multiple visual-language tasks including visual question answering.
Let’s illustrate how you can use this model for VQA. First, let’s load the model. Here we’ll explicitly send the model to a GPU, if available, which we didn’t need to do earlier when training, as Trainer handles this automatically:
Copied
The model takes image and text as input, so let’s use the exact same image/question pair from the first example in the VQA dataset:
Copied
To use BLIP-2 for visual question answering task, the textual prompt has to follow a specific format: Question: {} Answer:
.
Copied
Now we need to preprocess the image/prompt with the model’s processor, pass the processed input through the model, and decode the output:
Copied
As you can see, the model recognized the crowd, and the direction of the face (looking down), however, it seems to miss the fact the crowd is behind the skater. Still, in cases where acquiring human-annotated datasets is not feasible, this approach can quickly produce useful results.
Last updated