<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nate Nethercott on Medium]]></title>
        <description><![CDATA[Stories by Nate Nethercott on Medium]]></description>
        <link>https://medium.com/@natenethercott?source=rss-81a068d2ffd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EIPow9rsODLRHLq5jv_ypg.png</url>
            <title>Stories by Nate Nethercott on Medium</title>
            <link>https://medium.com/@natenethercott?source=rss-81a068d2ffd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:07:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@natenethercott/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vision-language models from scratch in colab]]></title>
            <link>https://medium.com/@natenethercott/vision-language-models-from-scratch-in-colab-cd073a753b8a?source=rss-81a068d2ffd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd073a753b8a</guid>
            <category><![CDATA[multimodal-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nate Nethercott]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 05:37:34 GMT</pubDate>
            <atom:updated>2025-03-05T23:12:54.818Z</atom:updated>
            <content:encoded><![CDATA[<p>Experiences on training Multimodal LLMs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*0mu494NJMnK5MlZn443zMA.png" /></figure><p>Models like GPT-4o and Gemini have become even more popular over this past year with their new image-text capabilities. By accepting queries which combine natural language and images, these multimodal llms let us describe a wide range of phenomena in the world around us and open the door to more human-like interactions.</p><p>In this article we will run through how you can train your own vision-language model (VLM) at home today. We will quickly review VLM theory to give you a basis for understand the code, discuss the power of the hugging face 🤗 ecosystem, and finally train our own tiny VLM.</p><p><a href="https://colab.research.google.com/drive/1Za-6K1vJ22DSSkJaJ8e0GUd9-4tChmWw?usp=sharing">Find the colab notebook here.</a></p><blockquote><strong>Note:</strong> When we say “multimodal” we mean 2 or more “modes”; the main ones being text, image, and audio. For the sake of this article, the main modalities were going to be focusing on are images and natural language.</blockquote><h3>Some theory</h3><p>I’m going to assume you have an understanding of the transformer architecture, and more generally, how LLMs work since its roughly the same principle for vision-language models.</p><p>Architecturally, VLMs consist of:</p><ul><li><strong>a pretrained vision encoder </strong>(CLIP, Siglip, DINO, etc.)</li><li><strong>a pretrained LLM</strong></li><li><strong>*a projection layer </strong>or <strong>cross attention blocks</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WHPsgbUp3tNX_v4q.jpg" /><figcaption>figure from: <a href="https://huggingface.co/blog/vlms">https://huggingface.co/blog/vlms</a></figcaption></figure><p>During training both the vision encoder and LLM are kept frozen while the projection layer learns to align the visual concepts with the LLM’s embedding space. We take directly the outputs from our vision encoder and map them to the same dimension as token embeddings we can pass the concatenated [image, text] sequence to the LLM.</p><p>If you want to get technical, we can actually jointly train both the vision backbone and LLM from scratch in what’s known as “early fusion” but companies like Meta have invested millions of dollars training models like Llama so we might as well take advantage of that ;)</p><p>For people who like math, we’re trying to maximize something like this when we do <strong>supervised fine tuning (SFT)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NHeoeJYi2AJrtiK9.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*d2XR7M-Jr_wJaCCi.png" /></figure><p>The only difference between vanilla LLM training and training VLMs is that text is conditioned on a “prompt” consisting of image tokens. We also don’t consider loss for the next-token-prediction in the image patches — they’re just there to guide our text outputs. In this sense its the same as basic instruction tuning !</p><p>A <em>really really </em>basic connector/projection layer between the image and text would be a linear layer followed by an activation. In this case our “image tokens” as mentioned above would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/0*u83333PPsyS2oSEG.png" /></figure><p>Here <em>N</em> indicates the number of patches the image was split into by the ViT.</p><p>Math aside, the general VLM training procedure is as follows:</p><ol><li><strong>Stage 1: </strong>pretrain the projection network on course image-text pairs</li><li><strong>Stage 1.5 (optional): </strong>incorporate more descriptive/verbose image-text pairs generated by models like GPT-4o</li><li><strong>Stage 2: </strong>unfreeze the llm and finetune on high quality instruction tuning datasets</li></ol><h3>Some code</h3><p>Once again the notebook for this article with all code for modeling and training can be found here: ➡️ <a href="https://colab.research.google.com/drive/1Za-6K1vJ22DSSkJaJ8e0GUd9-4tChmWw?usp=sharing">notebook</a></p><p>There’s really only 3 things we need focus on; manually combining image and text embeddings, properly forwarding the [image, text] inputs through the model, and text generation.</p><p>The interface we’re looking to implement is shown below:</p><pre>from abc import ABC<br>from typing import Optional <br><br>class VLMMetaArchitecture(ABC):<br>  def prepare_inputs(<br>        self, <br>        input_ids=None, <br>        attention_mask=None, <br>        inputs_embeds=None, <br>        labels=None, <br>        images=None<br>  ):<br>      &quot;&quot;&quot;<br>      Prepare the inputs for the model.<br>      &quot;&quot;&quot;<br>      raise NotImplementedError <br><br>  def forward(<br>      self,<br>      input_ids, <br>      attention_mask, <br>      position_ids, <br>      past_key_values, <br>      inputs_embeds, <br>      labels, <br>      use_cache, <br>      output_attentions, <br>      output_hidden_states, <br>      images, <br>      return_dict<br>  ):<br>      &quot;&quot;&quot;<br>      Forward pass of the model. Wrapper around huggingface AutoModelForCausalLM forward method. <br>      &quot;&quot;&quot;<br>      raise NotImplementedError<br>  <br>  @torch.no_grad()<br>  def generate(<br>      self, <br>      input_ids, <br>      images, <br>      **kwargs<br>  ):<br>      &quot;&quot;&quot;<br>      Generate text from the model. Wrapper around huggingface AutoModelForCausalLM generate method.<br>      &quot;&quot;&quot;<br>      raise NotImplementedError</pre><p>Since we’re lazy, we’re going to pretty much bootstrap huggingface’s 🤗 code for those last 2 tasks and just focus on formatting the inputs to the model.</p><p>In terms of training data, we’re using datasets like <a href="https://huggingface.co/datasets/nnethercott/Recap-DataComp-100K">this one</a> where samples are (image, caption) tuples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ix1Jb2B0Lta8TmeIhR7mtQ.png" /><figcaption>A generic image-text captioning dataset.</figcaption></figure><p>Without copy pasta-ing the whole notebook here, assume the model has a structure like:</p><pre>from torch import nn<br>from transformers import AutoTokenizer<br><br>class Connector(nn.Module):<br>    &quot;&quot;&quot;<br>    A torch module projecting image tokens into the language space <br>    &quot;&quot;&quot;<br>    def __init__(self, d_in: int, d_out: int):<br>        super().__init__()<br>        self.norm = nn.LayerNorm(d_in)  # inputs layer norm<br><br>        self.proj = nn.Sequential(<br>            nn.Linear(d_in, d_out), <br>            nn.SiLU(),                   # activation fn<br>            nn.Linear(d_out, d_out)<br>        )<br><br>    def forward(self, x: torch.FloatTensor)-&gt; torch.FloatTensor:<br>        return self.proj(self.norm(x))<br><br><br>class Model(VLMMetaArchitecture, nn.Module):<br>    &quot;&quot;&quot;<br>    A torch module for conditional text generation given images<br>    &quot;&quot;&quot;<br>    def __init__(self, vision: nn.Module, llm: nn.Module, tokenizer: AutoTokenizer):<br>        super().__init__()<br>        self.vision = vision <br>        self.llm = llm<br>        self.tokenizer = tokenizer<br>         <br>        # connector <br>        self.connector = Connector(<br>                            vision.config.hidden_dim,<br>                            llm.config.hidden_dim,<br>                          )<br>    <br>    def forward(self, x: torch.FloatTensor)-&gt; torch.FloatTensor:<br>        pass <br><br>    # `prepare_inputs`, `generate` ... </pre><p>Lets walk through step-by-step how we can project the images into the language space.</p><p>The first step is to transform the images into a batch of patch embeddings using a ViT and ;</p><pre># images: List[PIL.Image.Image]<br>vision_embeds = model.vision(images) # (bsz,n_patches,vit_hidden_size)<br>vision_embeds = model.connector(vision_embeds) #(bsz,n_patches,llm_hidden_size)</pre><p>Its that easy ! Notice how the connector module just changes the last dimension of the image patch embeddings so that they match with the llm token embedding size. Checking the docs for the AutoModelForCausalLM we can see that the forward method accepts an argument input_emebds .</p><p>Indeed, transformers are meant to operate on vectors not text. Out of convenience for users though, 🤗 added a wrapper for the token-&gt;embedding vector mapping in their LLM API design. In theory you could manually do the embedding step yourself and pass the vectors to the model and get the same logits out — in our vision-language model we’re going to exploit this since we’re effectively pretending that the vision_embeds are a series of prefix embedding vectors.</p><p>First we need to embed a couple tokens to add some structure to our prompt template. For us those are going to be “&lt;img&gt;” and “&lt;/img&gt;” which will indicate to the llm that the span between them is a visual prompt.</p><pre>bsz, seq_len, d= vision_embeds.shape <br><br># we want something like &lt;s&gt;&lt;img&gt;&lt;image-tokens&gt;&lt;/img&gt;&lt;text-tokens&gt;&lt;/s&gt;<br># embed &lt;s&gt;<br>bos_token = torch.tensor(tokenizer.bos_token_id).unsqueeze(0)<br>bos_embeds = model.embed_tokens(bos_token).repeat((bsz,1,1))<br><br># embed &lt;img&gt; and &lt;/img&gt;<br>img_token = tokenizer.encode(&quot;&lt;img&gt;&quot;, add_special_tokens=False)<br>img_token = torch.tensor(img_token, device=self.device).unsqueeze(0)<br>img_embeds = self.embed_tokens(img_token).repeat((bsz,1,1))<br><br>end_img_token = tokenizer.encode(&quot;&lt;/img&gt;&quot;, add_special_tokens=False)<br>end_img_token = torch.tensor(end_img_token, device=self.device).unsqueeze(0)<br>end_img_embeds = self.embed_tokens(end_img_token).repeat((bsz,1,1))</pre><p>The next step is to sandwich the vision_embeds with our text embeddings now (which we can do since they have the same hidden size thanks to our Connector!)</p><pre># manually embed the text <br>text_embeds = self.embed_tokens(input_ids)<br><br># stick everything together <br>inputs_embeds = torch.cat(<br>  (bos_embeds, img_embeds, vision_embeds, end_img_embeds, text_embeds), <br>   dim=1<br>)</pre><p>The very last step here is to make sure we properly modify the attention mask generated originally by the tokenizer since we just added some new tokens to the sequence:</p><pre> # attention_mask<br>_, vis_len, _ = vision_embeds.shape<br>additional_len = 1 + 1 #added &lt;img&gt; and &lt;/img&gt;<br>attention_mask = torch.cat((torch.ones((bsz, vis_len+additional_len)), attention_mask), dim=1)</pre><p>And there you go! All together this looks like:</p><pre>vision_embeds = model.vision(images) <br>vision_embeds = model.connector(vision_embeds)<br><br># bos<br>bos_token = torch.tensor(tokenizer.bos_token_id).unsqueeze(0)<br>bos_embeds = model.embed_tokens(bos_token).repeat((bsz,1,1))<br><br># embed &lt;img&gt; and &lt;/img&gt;<br>img_token = tokenizer.encode(&quot;&lt;img&gt;&quot;, add_special_tokens=False)<br>img_token = torch.tensor(img_token, device=self.device).unsqueeze(0)<br>img_embeds = self.embed_tokens(img_token).repeat((bsz,1,1))<br><br>end_img_token = tokenizer.encode(&quot;&lt;/img&gt;&quot;, add_special_tokens=False)<br>end_img_token = torch.tensor(end_img_token, device=self.device).unsqueeze(0)<br>end_img_embeds = self.embed_tokens(end_img_token).repeat((bsz,1,1))<br><br># text<br>text_embeds = self.embed_tokens(input_ids)<br>inputs_embeds = torch.cat((bos_embeds, img_embeds, vision_embeds, end_img_embeds, text_embeds[:,1:,:]), dim=1)<br><br># attention_mask<br>_, vis_len, _ = vision_embeds.shape<br>additional_len = 1 + 1 #added &lt;img&gt; and &lt;/img&gt;<br>attention_mask = torch.cat((torch.ones((bsz, vis_len+additional_len), device=self.device), attention_mask), dim=1)</pre><p>As you can see the prepare_inputs method is just a few steps of tensor manipulation to concatenate image information with token embeddings.</p><p>For more details on full run through of the code feel free to check out the notebook which has the entire pipeline end-to-end.</p><h3>Results</h3><p>So far we ran through how to preprocess the image tokens to make them work in an LLM. I’ve omitted all the code related to bootstrapping the 🤗 trainer and the training pipeline in general but rest assured its in the notebook!</p><p>To train vision-language models we need datasets with (image, text) tuples. A good example of a solid pre-training dataset is <a href="https://huggingface.co/datasets/lmms-lab/LLaVA-ReCap-558K">lmms-lab/LLaVA-ReCap-558K</a>, where you can find examples like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*fKAU8Vxo3F2WFF8DY-8MHw.jpeg" /><figcaption><em>The image shows a group of five individuals engaged in a seated meditation practice. They are arranged in a line, facing forward with their eyes closed, and their hands are positioned in a meditative gesture known as \”mudra,\” which typically involves the fingers being brought together in a specific way. The individuals appear to be of varying ages…</em></figcaption></figure><p>For all intents and purposes, training a vision-language model is exactly the same as training an LLM, both with respect to pre-training, SFT, and any reinforcement learning you want to do. As mentioned earlier, a good recipe to follow is either a 2 or 3-stage training pipeline where samples get progressively more complex and where we unfreeze the LLM in later stages.</p><p>Before training the model the LLM does not know how to interpret the vision information we injected. Its caption for the image above is a meaningless sequence of characters like:</p><pre>&quot;er ↑ (both \ndata (both  [om (both [more ][urls urls urls \nurls (ajax ↑both ][both faster \nnewmenalmedalentering slower urls faster faster urls (more faster urls.bothal  --&gt; urls&#39;&quot;</pre><p>In just 90 minutes of training in a single T4 colab session on 100K image-text pairs, however, we can already start to see massive improvements!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*LzC54K-EQrflydbCkKPmIA.png" /><figcaption>Training loss for our vision-language model</figcaption></figure><p>Looking at a few model generations (which we can do for free since we’re using 🤗’s llm generate method) we get some convincing results;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*QNX0lgTaDxz3nUZ91xHLDA.png" /><figcaption>demo 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*HlHA3sa9nyjSvtKtTC3a4w.png" /><figcaption>demo 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*Cq2D-vX8_oZmdk-oeiOu4w.png" /><figcaption>demo 3</figcaption></figure><p>Although the model is nowhere near GPT4-o levels (and hallucinates a fair bit), we managed to align vision and text with two random models we found on the hugging face hub in under 90 minutes. I think that’s pretty amazing !</p><p>If you want to explore this further some great next steps would be to play around with the choice of llm (bigger is better), consider different quantization schemes + mixed precision training, and increase the number of training steps.</p><h3>Some VLMs I love</h3><p>When writing this article and working on the notebook I took a lot of inspiration from open source vision-language models. I wanted to link those here so you can check them out too!</p><ul><li><a href="https://github.com/haotian-liu/LLaVA">LLaVA</a></li><li><a href="https://github.com/Vision-CAIR/MiniGPT-4">MiniGPT-v2</a></li><li><a href="https://github.com/cambrian-mllm/cambrian">Cambrian-1</a></li><li><a href="https://github.com/vikhyat/moondream">moondream2</a></li><li><a href="https://huggingface.co/blog/idefics2">idefics2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd073a753b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>