{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# For tips on running notebooks in Google Colab, see\n# https://codelin.vip/beginner/colab\n%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "TorchMultimodal Tutorial: Finetuning FLAVA\n==========================================\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multimodal AI has recently become very popular owing to its ubiquitous\nnature, from use cases like image captioning and visual search to more\nrecent applications like image generation from text. **TorchMultimodal\nis a library powered by Pytorch consisting of building blocks and end to\nend examples, aiming to enable and accelerate research in\nmultimodality**.\n\nIn this tutorial, we will demonstrate how to use a **pretrained SoTA\nmodel called** [FLAVA](https://arxiv.org/pdf/2112.04482.pdf) **from\nTorchMultimodal library to finetune on a multimodal task i.e. visual\nquestion answering** (VQA). The model consists of two unimodal\ntransformer based encoders for text and image and a multimodal encoder\nto combine the two embeddings. It is pretrained using contrastive, image\ntext matching and text, image and multimodal masking losses.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Installation\n============\n\nWe will use TextVQA dataset and `bert tokenizer` from Hugging Face for\nthis tutorial. So you need to install datasets and transformers in\naddition to TorchMultimodal.\n\n```{=html}\n
NOTE:
\n```\n```{=html}\n
\n```\n```{=html}\n

When running this tutorial in Google Colab, install the required packages bycreating a new cell and running the following commands:

!pip install torchmultimodal-nightly\n!pip install datasets\n!pip install transformers

\n```\n```{=html}\n
\n```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Steps\n=====\n\n1. Download the Hugging Face dataset to a directory on your computer by\n running the following command:\n\n ``` {.}\n wget http://dl.fbaipublicfiles.com/pythia/data/vocab.tar.gz \n tar xf vocab.tar.gz\n ```\n\n ```{=html}\n
NOTE:
\n ```\n ```{=html}\n
\n ```\n ```{=html}\n

If you are running this tutorial in Google Colab, run these commandsin a new cell and prepend these commands with an exclamation mark (!)

\n ```\n ```{=html}\n
\n ```\n\n2. For this tutorial, we treat VQA as a classification task where the\n inputs are images and question (text) and the output is an answer\n class. So we need to download the vocab file with answer classes and\n create the answer to label mapping.\n\n We also load the [textvqa\n dataset](https://arxiv.org/pdf/1904.08920.pdf) containing 34602\n training samples (images,questions and answers) from Hugging Face\n\nWe see there are 3997 answer classes including a class representing\nunknown answers.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "with open(\"data/vocabs/answers_textvqa_more_than_1.txt\") as f:\n vocab = f.readlines()\n\nanswer_to_idx = {}\nfor idx, entry in enumerate(vocab):\n answer_to_idx[entry.strip(\"\\n\")] = idx\nprint(len(vocab))\nprint(vocab[:5])\n\nfrom datasets import load_dataset\ndataset = load_dataset(\"textvqa\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lets display a sample entry from the dataset:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np \nidx = 5 \nprint(\"Question: \", dataset[\"train\"][idx][\"question\"]) \nprint(\"Answers: \" ,dataset[\"train\"][idx][\"answers\"])\nim = np.asarray(dataset[\"train\"][idx][\"image\"].resize((500,500)))\nplt.imshow(im)\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3\\. Next, we write the transform function to convert the image and text\ninto Tensors consumable by our model - For images, we use the transforms\nfrom torchvision to convert to Tensor and resize to uniform sizes - For\ntext, we tokenize (and pad) them using the `BertTokenizer` from Hugging\nFace -For answers (i.e. labels), we take the most frequently occurring\nanswer as the label to train with:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import torch\nfrom torchvision import transforms\nfrom collections import defaultdict\nfrom transformers import BertTokenizer\nfrom functools import partial\n\ndef transform(tokenizer, input):\n batch = {}\n image_transform = transforms.Compose([transforms.ToTensor(), transforms.Resize([224,224])])\n image = image_transform(input[\"image\"][0].convert(\"RGB\"))\n batch[\"image\"] = [image]\n\n tokenized=tokenizer(input[\"question\"],return_tensors='pt',padding=\"max_length\",max_length=512)\n batch.update(tokenized)\n\n\n ans_to_count = defaultdict(int)\n for ans in input[\"answers\"][0]:\n ans_to_count[ans] += 1\n max_value = max(ans_to_count, key=ans_to_count.get)\n ans_idx = answer_to_idx.get(max_value,0)\n batch[\"answers\"] = torch.as_tensor([ans_idx])\n return batch\n\ntokenizer=BertTokenizer.from_pretrained(\"bert-base-uncased\",padding=\"max_length\",max_length=512)\ntransform=partial(transform,tokenizer)\ndataset.set_transform(transform)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "4\\. Finally, we import the `flava_model_for_classification` from\n`torchmultimodal`. It loads the pretrained FLAVA checkpoint by default\nand includes a classification head.\n\nThe model forward function passes the image through the visual encoder\nand the question through the text encoder. The image and question\nembeddings are then passed through the multimodal encoder. The final\nembedding corresponding to the CLS token is passed through a MLP head\nwhich finally gives the probability distribution over each possible\nanswers.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from torchmultimodal.models.flava.model import flava_model_for_classification\nmodel = flava_model_for_classification(num_classes=len(vocab))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "5\\. We put together the dataset and model in a toy training loop to\ndemonstrate how to train the model for 3 iterations:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from torch import nn\nBATCH_SIZE = 2\nMAX_STEPS = 3\nfrom torch.utils.data import DataLoader\n\ntrain_dataloader = DataLoader(dataset[\"train\"], batch_size= BATCH_SIZE)\noptimizer = torch.optim.AdamW(model.parameters())\n\n\nepochs = 1\nfor _ in range(epochs):\n for idx, batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n out = model(text = batch[\"input_ids\"], image = batch[\"image\"], labels = batch[\"answers\"])\n loss = out.loss\n loss.backward()\n optimizer.step()\n print(f\"Loss at step {idx} = {loss}\")\n if idx >= MAX_STEPS-1:\n break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conclusion\n==========\n\nThis tutorial introduced the basics around how to finetune on a\nmultimodal task using FLAVA from TorchMultimodal. Please also check out\nother examples from the library like\n[MDETR](https://github.com/facebookresearch/multimodal/tree/main/torchmultimodal/models/mdetr)\nwhich is a multimodal model for object detection and\n[Omnivore](https://github.com/facebookresearch/multimodal/blob/main/torchmultimodal/models/omnivore.py)\nwhich is multitask model spanning image, video and 3d classification.\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 0 }