<?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 Souvik Mandal on Medium]]></title>
        <description><![CDATA[Stories by Souvik Mandal on Medium]]></description>
        <link>https://medium.com/@mandalsouvik?source=rss-be3f74e4d188------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O-8qMqfsL76mwwps2Kq2jA.jpeg</url>
            <title>Stories by Souvik Mandal on Medium</title>
            <link>https://medium.com/@mandalsouvik?source=rss-be3f74e4d188------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:29:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mandalsouvik/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[LLM Compression Techniques]]></title>
            <link>https://itnext.io/llm-compression-techniques-49865356fa70?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/49865356fa70</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 16:14:37 GMT</pubDate>
            <atom:updated>2024-06-04T16:42:09.371Z</atom:updated>
            <content:encoded><![CDATA[<p>Large language models (LLMs) without quantization demand significant GPU memory, greatly increasing deployment costs. This overview covers model compression techniques for LLMs and explores the LLM serving engines that support these quantized methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*JoAAEIgvc1sWxJm3RVk4Fw.png" /></figure><h4>Pruning</h4><p>Pruning is removing connection from the neural network. We can remove the connections in two ways:</p><p><strong>Structured Pruning: </strong>All the incoming and outgoing connections for the selected neurons are removed.</p><p><strong>Unstructured Pruning: </strong>Connection are removed based on the selection logic. Some neuron can have all the existing connections and some neuron might not have any connection and any number in between.</p><p><strong>Selection logic</strong> can be as simple as checking the magnitude of the weights and removing the weights with magnitude close to zero.</p><p>Performance of unstructured pruning is generally better than structured pruning. We can also do more aggressive pruning with unstructured pruning while keeping the model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*_HeTeodnhi6l9cxn4Oiggw.png" /></figure><p>Sparse models will require less memory to host and certain level of pruning does not impact the test performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIH0HD_SGl4fLmeh8vqhRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*JmCIcUjwGDNUMt5TE_0hWA.png" /></figure><p>We need to implement sparse inference kernels to provide both memory reduction and acceleration of sparse models. This is why pruning is not that much popular in LLMs compared to quantization.</p><h4>Distillation</h4><p>Distillation generally involves using a larger pre-trained model’s embedding vector as target to train a smaller model.</p><p>Distilled models most of the time performs better than if we just train the model directly on the train data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxxRKpbdtuciLMqwbKwBuQ.jpeg" /></figure><h4>Quantization</h4><p>Model weights are generally stored in float16 format. Quantization is converting them from high precision format (float32, float16) to low precision format (like int8, int4).</p><p>LLMs are generally over parameterised and quantization acts as regularization, thus model performance does not degrade drastically.</p><p>Quantization also makes sense for real world edge application (personal assistant), where LLMs are more memory bound than compute bound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDuRDfsdaXgyJ4jPScDH0g.png" /><figcaption>NVIDIA A100 GPU 80GB has 312TFLOPS. With low batch size we don’t use much of that compute. Even with 128 batch size we are not using all the compute. But for each token generation we will need to access 120 gb of memory.</figcaption></figure><p>All the quantization techniques can be grouped into two categories.</p><ol><li><strong>Quantization aware training: </strong>The model is trained during quantization process, thus these methods produces more accurate models.</li><li><strong>Post training quantization: </strong>The model is directly quantized without further training. These models generally less accurate than the models produced by quantization aware training but it require very less compute to create the models.</li></ol><p>Because LLMs have large number of parameters, doing quantization aware training is generally expensive. But because they are over-parameterized even with post training quantization the performance drop is very minimal.</p><p><strong>Linear Quantization/ RTN</strong></p><p>A simple form of quantization is linear quantization or round to nearest quantization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*wKxHPlvBdFA4ASkPW2Rimg.png" /></figure><p>Here, we convert the values of a more precise format (top) to a less precise format (below).</p><p>We can define scale (s) between the two format as:</p><p>s = (r_max — r_min)/(q_max-q_min)</p><p>We can compute the r_max as:</p><p>r_max = s * (q_max — z) =&gt; z = q_max — (r_max/s)</p><p>So any higher precision point (r)can be represented as:</p><p>q = int(round(r/s + z))</p><p>Linear quantization does not work well for int8 and does not work at all in int4 for majority of the LLM use-cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1yByp6SMuTn-t6uHEUQ3g.png" /><figcaption>Source: GPTQ paper</figcaption></figure><p><strong>GPTQ</strong></p><p>GPTQ is the first post training quantization method that gives very good performance even with int4 quantization.</p><p>GPTQ quantizes the weights layer by layer such that after quantization one a layer’s weight the change in the output is minimum compared to before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*8uIrNpVHysTFcw7Lo0uttw.png" /><figcaption>W is the full precision weight and W^ is the quantized weight. We find the W^ such a way that l2 difference of the output is minimum.</figcaption></figure><p>Within the same layer, it uses Optimal Brain Quantization (OBQ) to approximate layer wise optimization to row wise optimization. With this, we can approximate the above as:</p><blockquote>sum of the squared errors, over each row of W. Then, OBQ handles each row w independently, quantizing one weight at a time while always updating all not-yet-quantized weights, in order to compensate for the error incurred by quantizing a single weight.</blockquote><p>Which weights to quantize first?</p><blockquote>weight which currently incurs the least additional quantization error. while this quite natural strategy does indeed seem to perform very well, its improvement over quantizing the weights in arbitrary order is generally small, in particular on large, heavily-parametrized layers.</blockquote><p>One problem with arbitrary order can be if there is outliers in the weights and we quantize then first for a row remaining weights will have to be update by a large value. We can update those at end to make sure this does not happens.</p><p><strong>Activation-aware Weights Quantization (AWQ)</strong></p><p>When we quantize with LLM weights with RTN method the model perforrmance decreases (perplexity increase, lower PPL is better). But if we only keep 0.1% of the weights in fp16 and quantize rest of the weights, the quantize model retains its performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq8m0FjKXrFbWrtlJBoeEw.png" /></figure><p><em>How to select which weights to keep?</em></p><p>We can consider the weights with high magnitude as important, but they give almost similar performance if we select the weights randomly. But if the weights are selected based on how much their contribution to the activation value, the selected weights seem to give the best performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-eMf8IeazJcfXGlTwjsvA.png" /></figure><p>Now, keeping the wights in mixed precision will make the inference complicated because we will require optimized kernals for matrix multiplication and so on.</p><p>This is solved by multiplying the important weights with a multiplier. The value of the multiplier is selected by applying a range of values and selecting the one with the less difference compared to the original.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GIWr_yCCFJ9i-NU02kr4g.png" /></figure><p>In the Image above, we multiply W with the multiplier (s). We then devide the input by the same multiplier (X/s) such that the overall output is not changed.</p><p>AWQ is better than GPTQ. It required less number of samples and the quantized model is less prone to overfit on the calibration dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DW8dQhBGR2CtePKjCWVRDg.png" /></figure><p>Applying AWQ quantization is very simple with <a href="https://github.com/casper-hansen/AutoAWQ/blob/main/examples/quantize.py">AutoAWQ repo</a>. AWQ quantization images are from <a href="https://www.dropbox.com/scl/fi/dtnp6h6y1mnp7g036axu6/AWQ-slide.pdf?rlkey=ffgh50hxhx8dmsnjiu8kef0ou&amp;e=2&amp;dl=0">here</a>.</p><p><em>There are other quantization methods like GGUF, EXL2 which are mainly used to run LLMs on CPU (offloading)and GPU.</em></p><p>Some observations on LLM quantization:</p><ul><li>The larger the model, the less the difference between the quantized and base models.</li><li>performance smaller model without quantization &lt; Large model with quantization running on same infra.</li><li>AWQ is generally recommended for mass serving engines.</li></ul><p>Quantized LLMs are supported in most of the popular LLM serving engines: <a href="https://github.com/vllm-project/vllm">vLLM</a>, <a href="https://github.com/PygmalionAI/aphrodite-engine">Aphrodite</a> and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*IwaJ9CC7BE1bbxV30zd-tw.png" /></figure><p><strong>Resources</strong></p><ul><li><a href="https://neuralmagic.com/wp-content/uploads/2020/10/Pruning-Ebook-2.pdf">https://neuralmagic.com/wp-content/uploads/2020/10/Pruning-Ebook-2.pdf</a></li><li><a href="https://arxiv.org/pdf/2308.07633">LLM Compression Survey</a></li><li><a href="https://arxiv.org/pdf/2307.00526">TensorGPT paper</a></li><li><a href="https://arxiv.org/pdf/2301.00774">Sparse GPT</a></li><li><a href="https://arxiv.org/pdf/2210.17323">GPTQ Paper</a></li><li><a href="https://www.dropbox.com/scl/fi/dtnp6h6y1mnp7g036axu6/AWQ-slide.pdf?rlkey=ffgh50hxhx8dmsnjiu8kef0ou&amp;e=1&amp;dl=0">AWQ Quantization</a>, <a href="https://arxiv.org/pdf/2306.00978">Paper</a></li><li><a href="https://www.reddit.com/r/LocalLLaMA/comments/1anb2fz/guide_to_choosing_quants_and_engines/">Quantization methods overview</a></li></ul><h3>Connect with me</h3><p>Feel free to drop me a message or</p><ol><li>Connect and reach out on <a href="https://www.linkedin.com/in/mandalsouvik/"><strong>LinkedIn</strong></a></li><li>Follow me on <a href="https://medium.com/@mandalsouvik"><strong>Medium</strong></a> or <a href="https://github.com/souvik3333"><strong>GitHub</strong></a></li></ol><p>Have a nice day ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49865356fa70" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/llm-compression-techniques-49865356fa70">LLM Compression Techniques</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Model Optimization: Why and How?]]></title>
            <link>https://itnext.io/deep-learning-model-optimization-why-and-how-db370b89723d?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/db370b89723d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 22:23:50 GMT</pubDate>
            <atom:updated>2023-12-09T22:23:50.967Z</atom:updated>
            <content:encoded><![CDATA[<p>Why do we need model optimization? Different methods of model optimization?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3DpEfBhSoxEZj5Eq" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Deep Learning model optimization involves methods to speed up model inference. This comes at the cost of a decrease in performance.</p><h3>Why do we need model optimization?</h3><h4>1. Foundational Models</h4><p>These days there are lots of pre-trained foundational models available in both the vision and text domain. Models like Segment Anything and DINOv2 are pretrained on millions (Segment Anything and DINOv2 are trained on 11, and 142 million data respectively) of data. In the text domain, we have Llama 2, vicuna, and so on. Finetuning them on new tasks will always give better results than training anything from scratch. However, these foundational models are generally large vision/language models. The idea here is to take advantage of the large-scale pretraining.</p><p><strong>One problem with foundational models is that they will require high resources during training even if we optimize the inference</strong>. Recently papers like LoRA (Low-Rank Adaptation of Large Language Models), QLoRA (Efficient Finetuning of Quantized LLMs), and so on have reduced the computational requirement of training those large foundational models. These papers fall inside the category called Parameter efficient finetuning methods, which is getting lots of attention because of these foundational models.</p><p>However, because of the large model size, we will not always be able to deploy them in production and need optimization methods to make the inference faster.</p><p><em>On a side note, vision language models (like CLIP, BLIP-2, and so on) can also be used as pretrained encoders depending on tasks.</em></p><h4>2. Train large then compress is better than training compressed model</h4><p>There are two aspects while comparing a large model and compression against a compressed model. Normally compressed model will complete an iteration much faster than a large model. So, <strong>will training time and compute requirements increase</strong>? Also, <strong>after the compression of the large model, how much performance is lost?</strong></p><p>There is a paper <em>Train Large, Then Compress: Rethinking Model Size for Efficient Training and Inference of Transformers </em>from UC Berkeley, which mentions wider and deeper models converge much faster than smaller models, and are much easier and more robust to compress compared to smaller models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*Xf_BfmBM_Jy3tFdXFQ4xcA.png" /><figcaption>Wider models converge faster than narrower models as a function of both gradient steps (left plot) and wall-clock time (right plot).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*fEDw4ybZS3VOKSBT-eDsdw.png" /><figcaption>Increasing Transformer model size results in lower validation error as a function of wall-clock time and better test-time accuracy for a given inference budget. The right image is from an experiment that takes ROBERTA checkpoints that have been pretrained for the same amount of wall-clock time and finetunes them on a downstream dataset (MNLI). Models are then compressed according to the inference memory budget, the best models for a given memory are ones that are trained large and then heavily compressed.</figcaption></figure><p>Along with parameter-efficient fine-tuning and the finding that large models converge faster, training time and compute requirements will not be a problem.</p><p>Also, from the Validation Accuracy vs Number of Parameter diagram, it’s clear that for a given number parameter large heavily compressed models work better than smaller and less compressed models.</p><h4>3. Training large models and then optimizing makes more sense for business</h4><p>More often than not the models need to be deployed on multiple devices like cloud deployment, and on-premise deployment. On cloud deployment, we can use larger models but for on-premise deployment, we might need to optimize based on client requirements. Training models separately and maintaining them will be more hassle than training one large performing model and optimizing it according to requirements.</p><h3>Different model optimization techniques</h3><p>Two of the most common model optimization methods are <strong>Quantization</strong> and <strong>Pruning</strong>.</p><p>Quantization stores the model weights in low-precision (fp32 to fp16/int8/bfloat16) format to accelerate matrix operations when using hardware with reduced precision and to reduce overall memory footprint. During quantization, we occasionally quantize only part of the weights and activations instead of quantizing everything.</p><p><strong>Post-training quantization</strong> is a technique to quantize (clip, scale, round, and so on) the model weights after the model has been trained.</p><p><strong>Quantization-aware training</strong> is a training method that involves simulating the quantization effects during the training phase itself. Instead of training the model with high-precision floating-point numbers, the model is trained with lower-precision representations, emulating the quantization that will be applied later during deployment. This helps the model adapt to the reduced precision and minimizes the loss of accuracy caused by quantization. Quantization-aware training is often better than post-training quantization. Also, don’t confuse this with mixed-precision training.</p><p><strong>Model pruning</strong> sets the network weights to zero which reduces the number of operations directly and reduces the memory footprint as well.</p><p>Pruning algorithms can drop individual weights or groups of weights. They are called <strong>unstructured and structured pruning</strong> respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*LZqUizE5-Yh7MMKI.png" /><figcaption>Unstructured and structured pruning. <a href="https://neuralmagic.com/blog/pruning-overview/">Image source.</a></figcaption></figure><p>Note, that model inference can be optimized with <a href="https://github.com/triton-inference-server/server">parallel model inference</a>, <a href="https://stackoverflow.com/questions/46154189/what-is-the-difference-of-static-computational-graphs-in-tensorflow-and-dynamic">converting the model to a static computational graph</a>, and so on.</p><p>We will go over how the different quantization and pruning techniques are used in a model in separate blogs.</p><h4>Resources</h4><ol><li><a href="https://arxiv.org/abs/2106.09685">LoRA Paper</a></li><li><a href="https://arxiv.org/abs/2305.14314">QLoRA Paper</a></li><li><a href="https://arxiv.org/abs/2002.11794">Train Large, Then Compress Paper</a></li><li><a href="https://neuralmagic.com/blog/pruning-overview/">Pruning Neuralmagic</a></li></ol><h4>Connect with me</h4><p>Feel free to drop me a message or</p><ol><li>Connect and reach out on <a href="https://www.linkedin.com/in/mandalsouvik/"><strong>LinkedIn</strong></a></li><li>Follow me on <a href="https://medium.com/@mandalsouvik"><strong>Medium</strong></a> or <a href="https://github.com/souvik3333"><strong>GitHub</strong></a></li></ol><p>Have a nice day ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db370b89723d" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/deep-learning-model-optimization-why-and-how-db370b89723d">Deep Learning Model Optimization: Why and How?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IMAGEBIND: One Embedding Space To Bind Them All]]></title>
            <link>https://itnext.io/imagebind-one-embedding-space-to-bind-them-all-b48c8623d39b?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/b48c8623d39b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[multimodal-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 18:06:45 GMT</pubDate>
            <atom:updated>2023-12-04T18:06:45.973Z</atom:updated>
            <content:encoded><![CDATA[<p>IMAGEBIND is an approach to learning joint embeddings across six different modalities: image, text, audio, depth, thermal, and IMU data.</p><p>The main contribution of this paper is that a combination of paired datasets is not required to train multi-modality models if only one of the common modalities is sufficient to bind all the modalities together. In this paper, they have aligned all modality&#39;s embedding to image embeddings.</p><p>This is the first model capable of binding information from six modalities.</p><h4>IMAGEBIND</h4><p>Normally, contrastive learning is used to align the embedding space of two different modalities of related examples. Let’s say we have image and text modality. We can patchify the image and pass it through a ViT, and we can take models like BERT and pass the text to get the image and text token embeddings.</p><p>We then take the class token because it will have global information about the modality. Next, we pass it through an MLP layer (projection layer) to make the class token dimension across modalities of the same dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2UV9PEWyU1E61ygqDqOng.png" /><figcaption>Image Text alignment</figcaption></figure><p>Since IMAGEBIND has six modalities, we will need six different encoders to process each type of data.</p><p>Also, previous multi-modality models mostly consisted of two modalities. The majority of them were vision-language models with image and text data. So, they were trained with paired image and text (image caption) data. But with six modalities if we look for one data point with all six modality information, very little open-source data will be available, and creating that dataset will be time-consuming.</p><blockquote>IMAGEBIND can leverage recent large scale vision-language models, and extends their zeroshot capabilities to new modalities just by using their natural pairing with images</blockquote><p>We create the dataset with each data point consisting of an image and one of the considered modalities. For example, the first data point can be (image, text), the second one (image, video), and the third one is (image, audio) pairs. For all data points, the imaging modality is common, and the image encoder is being trained. Text encoder will not be accumulating gradient in case the datapoint is (image, video) or (image, audio) and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHbyUmNGgO_1RxBLpulndg.jpeg" /><figcaption>Data processing in case we have (image, text), (image, video), (image, audio) pairs</figcaption></figure><p>Now, since the image modality is common across all data points, the only way the model can converge is if all the modalities are aligned with the image embeddings.</p><p><strong>What will happen if the model does not align all modality embeddings into image embeddings?</strong></p><p>Let&#39;s say we train with (image, text) pair, and the text/image embeddings are not aligned in the image embedding space. Instead, the image and text embeddings are aligned in text embedding space.</p><p>Then next time a different modality pair is passed eg: (image, audio) the image encoder will embed the representation in text embedding space. The audio data is never trained with text data, the audio encoder can embed either in the image or audio embedding space. So the loss with increase when training on any other modality like (image, audio). The only way to decrease this loss is to align everything into the common modality (image) embedding space.</p><p><strong>Note:</strong> Image and Video are considered a single modality in the paper and processed in the same ViT encoder. In this explanation, I will consider two different modalities. This is just easier for me to explain video as a different modality than audio, depth, thermal, and IMU data. You can think of video data, video encoder, and video pre-processing as audio data, audio encoder, and audio pre-processing or one of the other modalities. So actually the data points can be (image/video, text) or (image/video, audio), (image/video, depth), and so on.</p><h4>Downstream Tasks</h4><p><strong>Cross modality retrival</strong></p><p>We can generate the feature vector (after the projection layer) in one modality and can search against the feature vectors of other modalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DA8QHHFeETNuvoJ1rM0mIw.png" /></figure><p><strong>Embedding-Space operations-based retrieval</strong></p><p>Adding embedding of different modalities seems to generate the embedding with both types of features. For example, summing a bird in forest image embeddings with waves sound embedding will generate embeddings which is similar to a bird with waves in background image embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibnWAnqVs_fH4xG-K5GumQ.png" /></figure><p><strong>Audio to image generation</strong></p><p>Using audio embeddings with a pre-trained DALLE-2 decoder designed to work with CLIP text embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsMW572fJsKmHolsgCwejQ.png" /></figure><p><strong>Zero-Shot Classification</strong></p><p>We can do a zero-shot classification of one modality with prompts from another modality. For example, just by training on (image, text) and (image, audio), IMAGEBIND can perform zero-shot classification of audio using text prompts.</p><h4>Results</h4><p><strong>Note: </strong>For prior zero-shot classification, we need direct paired data. For example, with the CLIP model, we can do zero-shot image classification. But with IMAGEBIND we don&#39;t need direct paired data to do zero-shot classification. For example, (image, text), (image, audio) pairs are trained together but there is no (text, audio) direct pair. Now if we do zero-shot classification of audio using text prompts, the authors are calling them Emergent Zero-Shot Classification.</p><p><strong>Few-shot classification on audio and depth: </strong>A linear classifier on the fixed features for the ≥ 1-shot case.</p><blockquote>IMAGEBIND outperforms the self-supervised AudioMAE model. IMAGEBIND even outperforms a supervised AudioMAE model upto 4 shot learning showing its strong generalization.</blockquote><blockquote>We compare with the MultiMAE model trained with images, depth, and semantic segmentation masks. IMAGEBIND outperforms MultiMAE across all few-shot settings on few-shot depth classification.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8Aj33e05wsCD1S6PKrVeQ.png" /><figcaption>Few-shot classification on audio and dept</figcaption></figure><p><strong>Text Retrieval: </strong>MSR-VTT is a large-scale dataset for open-domain video captioning. The results in the table show text retrieval recall with Video (V) or Audio (A) or both (A+V) as prompts for different models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpeDutnTaoxbc076_2xmow.png" /><figcaption>text retrieval performance using audio and video</figcaption></figure><p><strong>Audio retrieval:</strong></p><blockquote>Prior work trains using paired data for that modality, e.g., AudioCLIP uses (audio, text) supervision and AVFIC uses automatically mined (audio, text) pairs.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_CEufLYEP5DEvz4yEhgKw.png" /><figcaption>zero-shot audio retrieval and classification.</figcaption></figure><h4>Implementation</h4><p>Here, I will show the implementation for three modalities (image, video, text) but this can be extended for other modalities similar way.</p><p>Let&#39;s say we have a batch consisting of two data points, [(img1, text), (img2, video)].</p><pre>import torch<br>import timm<br>import torch.nn as nn<br>import numpy as np<br><br>from transformers import BertTokenizer, BertModel<br><br># Lets create a (image, caption/text) pair<br>img1 = torch.randn(224, 224, 3)<br>text = &quot;open source is good&quot;<br><br># Lets create a (image, video) pair<br>img2 = torch.randn(224, 224, 3)<br>video = torch.randn(60, 224, 224, 3) # 2 sec video with 30 FPS</pre><p>Next, let&#39;s define the three encoders. For the image encoder, I will use Timm, for the video encoder I will use the vit-pytorch repo, and for the text encoder, I will use the huggingface.</p><pre># Insall the packages if not installed<br>!pip install timm -q<br>! pip install vit-pytorch -q</pre><p>First, define the image encoder. This is a ViT Base model which will process images of size 224,224,3. It will create patches with size 16*16 and the embedding dimension is 768. Also, let&#39;s say finally we want all the encodings to be a 512-dimensional vector. So we will define a projection layer also.</p><pre># lets initialize the image encoder to process the image data<br>img_encoder = timm.create_model(&quot;vit_base_patch16_224&quot;, pretrained=True)<br>img_proj = nn.Linear(768, 512)</pre><p>For the text encoder, we will need to initialize a tokenizer and a transformer backbone. We will use a BPE tokenizer and pretrained BERT model in this example. Finally, we will need a projection layer.</p><pre># tokenizer and text encoder<br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;)<br><br>def text_tokenize(text):<br>    # Add the class token, then tokenize a caption<br>    return tokenizer.encode(f&quot;[CLS] {text}&quot;, add_special_tokens=True)<br><br>model_name = &#39;bert-base-uncased&#39;<br>model = BertModel.from_pretrained(model_name)<br>text_proj = nn.Linear(768, 512)</pre><p>Similar to the image encoder, for video we will use a ViT model. I am not explaining how 3D volumes are processed in the transformer, you can check <a href="https://medium.com/itnext/masked-autoencoders-as-spatiotemporal-learners-7b99a70633e2">this blog for details</a>.</p><pre># video encoder: This is also a ViT<br>from vit_pytorch.vit_3d import ViT<br><br>vit_vid = ViT(<br>    image_size = 224,          # image size<br>    frames = 60,               # number of frames<br>    image_patch_size = 16,     # image patch size<br>    frame_patch_size = 15,      # frame patch size<br>    num_classes = 0,<br>    dim = 1024,<br>    depth = 6,<br>    heads = 8,<br>    mlp_dim = 2048,<br>    dropout = 0.1,<br>    emb_dropout = 0.1<br>)<br>vit_vid.mlp_head = nn.Identity() # No need for the classification head<br>video_proj = nn.Linear(1024, 512)</pre><p>Let&#39;s do the forward pass for the (image, text) data</p><pre># Process the image text pair<br>## Process the image <br>img1_embeddings = img_encoder.forward_features(img1.permute(2, 0, 1).unsqueeze(0)) # [1, 197, 768]<br>img1_cls_token = img1_embeddings[:, 0, ...] # [1, 768]<br>img1_proj = img_proj(img1_cls_token) # [1, 512]<br>## Process the text<br>input_ids = text_tokenize(text) # [101, 101, 2330, 3120, 2003, 2204, 102]<br># Convert input_ids to PyTorch tensor<br>input_ids_tensor = torch.tensor(input_ids).unsqueeze(0)  # Add batch dimension, [1, 7]<br><br># Forward pass through the BERT model<br>outputs = model(input_ids_tensor)<br>last_hidden_states = outputs.last_hidden_state<br>text_cls_token = last_hidden_states[:, 0, ...] # [1, 768]<br>text_cls_proj = text_proj(text_cls_token) # [1, 512]</pre><p>Next let&#39;s process the (image, video) pair data.</p><pre># process the image-video pair<br>## Process the video<br>video_cls_token = vit_vid(video.permute(3, 0, 1, 2).unsqueeze(0)) # B, Channels, Frames, Width, Height<br>video_cls_proj = video_proj(video_cls_token)<br>## Process the image <br>img2_embeddings = img_encoder.forward_features(img2.permute(2, 0, 1).unsqueeze(0)) # [1, 197, 768]<br>img2_cls_token = img2_embeddings[:, 0, ...] # [1, 768]<br>img2_proj = img_proj(img2_cls_token) # [1, 512]</pre><p>Create the batch by stacking the data together.</p><pre># batch: [(img1, text), (img2, video)]<br>img_embeddings = torch.vstack([img1_proj, img2_proj]) # [2, 512]<br>second_modality_embeddings = torch.vstack([text_cls_proj, video_cls_proj]) # [2, 512]</pre><p>Next, we need to compute the loss. First, let’s normalize features.</p><pre>img_embeddings = img_embeddings / img_embeddings.norm(dim=1, keepdim=True)<br>second_modality_embeddings = second_modality_embeddings / second_modality_embeddings.norm(dim=1, keepdim=True)</pre><p>Compute the cosine similarity of all the image, and text pairs and scale the similarity:</p><pre>cosine_sim = img_embeddings @ second_modality_embeddings.t()<br><br>logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))<br>logit_scale = logit_scale.exp() # log scale, learned during training<br><br>logits_per_image = logit_scale * cosine_sim<br>logits_per_text = logits_per_image.t()</pre><p>Create the GT labels. So each datapoint image should have the highest similarity with the corresponding second modality.</p><pre>labels = torch.arange(logits_per_image.shape[0], dtype=torch.long)<br>labels # [0, 1]</pre><p>Compute the loss</p><pre>total_loss = (<br>    torch.nn.functional.cross_entropy(logits_per_image, labels) +<br>    torch.nn.functional.cross_entropy(logits_per_text, labels)<br>) / 2</pre><h4>Resources</h4><ul><li><a href="https://arxiv.org/abs/2305.05665">Paper</a></li><li><a href="https://github.com/facebookresearch/ImageBind">Official repo</a></li><li><a href="https://imagebind.metademolab.com/">Official demo</a></li></ul><h4>Connect with me</h4><p>Feel free to drop me a message or</p><ol><li>Connect and reach out on <a href="https://www.linkedin.com/in/mandalsouvik/"><strong>LinkedIn</strong></a></li><li>Follow me on <a href="https://medium.com/@mandalsouvik"><strong>Medium</strong></a> or <a href="https://github.com/souvik3333"><strong>GitHub</strong></a></li></ol><p>Have a nice day ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b48c8623d39b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/imagebind-one-embedding-space-to-bind-them-all-b48c8623d39b">IMAGEBIND: One Embedding Space To Bind Them All</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vision Transformers need registers]]></title>
            <link>https://medium.com/@mandalsouvik/vision-transformers-need-registers-ca7ded042d6a?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca7ded042d6a</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 14:55:37 GMT</pubDate>
            <atom:updated>2023-11-26T14:55:37.642Z</atom:updated>
            <content:encoded><![CDATA[<p>Improving transformer attention by increasing the number of class tokens (registers).</p><p>When we train a transformer model supervised or self-supervised way the last attention layer naturally focuses on semantically consistent parts of images and often produces interpretable attention maps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwkKWh0RhXPfSk4o8NMTPw.png" /><figcaption>Attention maps from the DINOv1 paper</figcaption></figure><p>A new set of unsupervised detection algorithms generally uses these attention maps to detect objects. However, the authors have noticed that the model trained in some methods (DINOv1) works better than other methods (DINOv2) when using such detection algorithms.</p><p>Authors have observed that there are <strong>tokens with roughly 10x higher norm</strong>s. Such tokens are much less than overall tokens (around 2%).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKID-PPuf0pecBJHeJkXBg.png" /><figcaption>Norm values of the patched tokens. In DINOv1 all the matches have similar norm values but in DINOv2 there are few patches with very high norm. Notice these high norm patches are in areas that are the same as neighborhood tokens.</figcaption></figure><p>These high-norm tokens normally appear in the middle layers of the vision transformer. Also, they only appear after a sufficiently long training of a sufficiently big transformer.</p><p>Also, <strong>these outlier tokens appear in patches similar to their neighbors, meaning patches that convey little additional information</strong>. (They have done cosine similarity of the embeddings after patches are created. The outliers patches have high cosine similarity with neighborhood tokens.)</p><p>They <strong>evaluate the outlier tokens with simple linear models to understand the information they contain</strong>. They have tested against two tasks: One task is using the linear layer to predict the positional embedding (they are added before processing through the transformer). The second, task is reconstructing the patch from the corresponding token. For outlier tokens, the reconstruction accuracy is lower than other tokens. Ideally, if the tokens have local patch information these tasks should be easy to complete. Note, that the transformer is frozen and only the linear layer is trained for both tasks.</p><p>So, Compared to non-outlier tokens, outliers hold less information about their original position in the image or the original pixels in their patch. On the other hand, learning an image classifier on outlier patches yields significantly stronger accuracy than doing so on the other patches. The image level classifier needs global information on the full image to predict the proper class. So <strong>these outliers patches are dropping local patch information and trying to learn some global information</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhSDiejG11gRtFxeBLdAhQ.png" /><figcaption>Image classification via linear probing on normal and outlier patch tokens. Outlier tokens have a much higher accuracy than regular ones.</figcaption></figure><p>To test the above hypothesis they have added more class tokens (they are calling them registers!) and trained the models again. Models trained with <strong>more class tokens have no outliers tokens and significantly smoother feature maps</strong>. These new models work well with detection methods as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QRztA5SzJ4KN3ZHep2AMg.png" /><figcaption>Transformer with additional registers.</figcaption></figure><h4>Experiments with registers 📈</h4><p><strong>Effect of register tokens on token norm values</strong>: With register tokens, there are no patches with large norms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O18Em3IwO2ZgrT4Sa0sspg.png" /><figcaption>Token norms with and without registers</figcaption></figure><p><strong>Improved attention maps with registers</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuNrfVwlnbzTKv4bxUxPAQ.png" /><figcaption>Attention maps with additional registers (DINOv2 model)</figcaption></figure><p>Comparison of the attention maps of the [CLS] token and registers. <strong>Register tokens sometimes attend to different parts of the feature map.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbIaKz6j_nSKfHlhiZpD3w.png" /><figcaption>[CLS] token and register tokens attention maps</figcaption></figure><p><strong>Evaluation of the downstream performance of different models</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mB0wjedHaeZ0LixVpXOUCA.png" /></figure><blockquote>There seems to be an optimal number of registers for dense tasks, and adding one brings most of the benefit. This optimum is likely explained by the disappearance of artifacts, leading to better local features. On ImageNet, however, performance improves when using more registers. <strong>In all our experiments, we kept 4 register tokens.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OC6b7eUnfRzN_2ogfPiew.png" /><figcaption>performance on three tasks (ImageNet, ADE-20k, and NYUd) as a function of number of registers used. While one register is sufficient to remove artifacts, using more leads to improved downstream performance.</figcaption></figure><p><strong>Results improved for unsupervised object discovery</strong> on models with registers. Authors have evaluated three types of models trained with various amounts of supervision on VOC 2007, 2012, and COCO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qALDqMjElt3I_i4eJ3gWCg.png" /><figcaption>Results with unsupervised object detection.</figcaption></figure><h4>Implementation 🎡</h4><p>I will be using <a href="https://github.com/huggingface/pytorch-image-models">Timm</a> to show how to add more tokens. First, we divide the images into patches.</p><pre>import torch<br>import torch.nn as nn<br><br>from timm.models.vision_transformer import PatchEmbed, Block<br><br>patch_size = 16<br>img_size = 1024<br>in_chns = 3<br>batch_size = 2<br>embed_dim = 768<br><br>imgs = torch.randn(batch_size, in_chns, img_size, img_size)<br>proj = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chns, embed_dim=embed_dim)<br>num_patches = proj.num_patches # 4096, (1024/16)**2<br><br>proj_op = proj(imgs)<br>proj_op.shape # [2, 4096, 768]</pre><p>Let&#39;s assume we are adding 4 register tokens. There is 1 [CLS] token. Class and register tokens are the same across batches. These will be learned during training.</p><pre>num_register_tokens = 4<br><br>cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) # 1, 1, 768<br>register_tokens = nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) # 1, 4, 768</pre><p>Define positional embeddings. It can either be learned or fixed. In this example, I am showing learned positional embeddings.</p><pre>pos_embed = nn.Parameter(<br>    torch.zeros(1, num_patches + 1 + num_register_tokens, embed_dim), # num_image_patches + [CLS Token] + num_register_tokens<br>    requires_grad=False<br>) # [B, patches, embed_dim]<br></pre><p>Add positional embeddings to the patches.</p><pre>proj_op = proj_op + pos_embed[:, 1 + num_register_tokens:, :]<br>cls_token = cls_token + pos_embed[:, :1, :] # Add position info to the [CLS] token<br>register_tokens = register_tokens + pos_embed[:, 1:1+num_register_tokens, ...] # Add positional info to the registers</pre><p>Stack the class and register tokens across the batch.</p><pre>cls_tokens = cls_token.expand(proj_op.shape[0], -1, -1) # [2, 1, 768]<br>register_tokens = register_tokens.expand(proj_op.shape[0], -1, -1) # [2, 4, 768]</pre><p>Stack all the tokens together</p><pre>x = torch.cat((cls_tokens, register_tokens, proj_op), dim=1) # 4096 + 1 ([CLS]) + 4 (registers)<br>x.shape # [2, 4101, 768]</pre><p>Pass through the transformer encoder</p><pre># define the encoder config<br>depth=24<br>num_heads=16<br>mlp_ratio=4.<br>norm_layer=nn.LayerNorm<br>norm = norm_layer(embed_dim)<br><br># initialize the encoder blocks<br>blocks = nn.ModuleList([<br>            Block(embed_dim, num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer)<br>            for i in range(depth)])<br><br># process in the encoder and normalize<br>for blk in blocks:<br>    x = blk(x)<br>x = norm(x) # [2, 4101, 768]</pre><p>Apply the average pool on the class and register tokens.</p><pre>avg_pool = torch.mean(x[:, :1+num_register_tokens, ...], dim=1)<br>avg_pool.shape # [2, 768]</pre><p>Compute the logits with a linear layer.</p><pre>num_classes = 10<br>linear_head = nn.Linear(embed_dim, num_classes)<br><br>logits = linear_head(avg_pool)<br>logits.shape # [2, 10]</pre><h4>Resources</h4><ol><li><a href="https://arxiv.org/pdf/2309.16588.pdf">Paper</a></li></ol><h4>Connect with me</h4><p>Feel free to drop me a message or</p><ol><li>Connect and reach out on <a href="https://www.linkedin.com/in/mandalsouvik/"><strong>LinkedIn</strong></a></li><li>Follow me on <a href="https://medium.com/@mandalsouvik"><strong>Medium</strong></a> or <a href="https://github.com/souvik3333"><strong>GitHub</strong></a></li></ol><p>Have a nice day ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca7ded042d6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TokenLearner: What Can 8 Learned Tokens Do for Images and Videos?]]></title>
            <link>https://itnext.io/tokenlearner-60bf14248611?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/60bf14248611</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 08:47:42 GMT</pubDate>
            <atom:updated>2023-11-22T07:29:49.088Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>TokenLearner: How to </em>Reduce the Number of Tokens in Transformer</h3><p>An efficient way to reduce the number of tokens, and computation requirements with little to no decrease in performance. This paper claims to <strong><em>achieve almost identical accuracies while cutting the computation by (almost) half</em></strong><em>.</em></p><p>In the realm of vision tasks encompassing classification, detection, and segmentation, Transformers have become indispensable. However, as we delve into processing images using Transformers, a crucial initial step involves pacifying the image. Take, for instance, images sized at 1024x1024 with a patch size of 16x16; this configuration yields 4096 tokens (as used in SAM).</p><p>It’s noteworthy that the computational and memory requirements of Transformers increase quadratically with the number of tokens. Herein lies an opportunity for optimization: by reducing the number of tokens, we can significantly accelerate our training time. This becomes particularly relevant when considering downstream task-specific models, which are often fine-tuned from foundational models.</p><p>During the training of foundational models, a higher number of tokens may be justifiable due to the complexity of the task. However, when it comes to downstream tasks, there’s a notable mismatch — these tasks don’t necessarily require as many tokens to effectively address the given problem statement.</p><p>We’ll explore how reducing the number of tokens can help and delve into the techniques employed to achieve this optimization. Let’s uncover the mechanisms that make this reduction possible and its implications for enhancing the efficiency of vision-related tasks.</p><h4>TokenLearner 📗</h4><p>Let’s demystify token reduction with a straightforward example. Imagine we have four image patches, each with an embedding dimension of 8. Our goal is to cut the number of tokens in half, leaving us with two tokens, each with 8 dimensions.</p><ol><li>To achieve this, we initiate the process by applying two Multi-Layer Perceptron (MLP) layers, effectively shrinking the embedding dimension from 8 to 2. This transformation results in an array sized 4x2. Apply MLP layers and Combine as array in the visualization.</li><li>Following this, we introduce the softmax function to the first dimension of the array. The softmax step determines the weight assigned to each of the original tokens. Apply SoftMax step in the visualization.</li><li>With the softmax values in hand, we proceed to multiply them by their corresponding original tokens. This will output two new tokens each with a dimension of 8. First New Token computation step in the visualization.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KT4QSi3NqPNZI5Wz9KNWw.png" /><figcaption>TokenLearner: Computing new tokens from the initial tokens</figcaption></figure><p><strong>A crucial hyperparameter is where to place the TokenLearner module.</strong> Applying it before the first transformer block minimizes computation but decreases accuracy. Moving TokenLearner to the right improves accuracy but increases computations. Explore the results section for more details.</p><h4>TokenLearner Results 📈</h4><p>TokenLearner seems to get better performance with less computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*5r6ejK6wzUFmmao5CTO1Og.png" /><figcaption><em>Visualization of ImageNet fine-tuning accuracies of the baseline ViT models vs. TokenLearner. The X-axis is GFLOPs, which measures the amount of computation required.</em></figcaption></figure><p>The results below show, how changing the TokenLearner location accuracy and computation change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_CxG_XAmrM-x7UDUo5v0A.png" /><figcaption><em>ImageNet 5-shot accuracy (left) and FLOPS (right) per different TokenLearner locations within the model. ‘0’ means that the TokenLearner is at the very beginning of the model (before any transformer), ‘0.5’ means the middle of the model, and ‘Base’ means that there is no token learning.</em></figcaption></figure><blockquote>We found that <strong>inserting TokenLearner in the middle of the network</strong> (at 1/2) <strong>achieves almost identical accuracies, while cutting the computation by (almost) half</strong>. In addition, having the TokenLearner at the later layer (after 3/4 of the network) achieves even superior performance compared to not using the TokenLearner while performing faster, thanks to its adaptiveness.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*LwdgyNBlgl9RnQ-nEDmF-Q.png" /><figcaption>TokenLearner with ViT-L/16 and ViT-L/14. 512x512 input images were used. ViT L/16 = ViT Large with 16 patch size and ViT L/14 = ViT Large with 14 patch size. <strong>16-TL at 12</strong> means the number of tokens was 16 and TokenLearner was inserted after the 12th layer.</figcaption></figure><blockquote>Some of the models were set to use additional layers (e.g., ‘+11’), but the increase in FLOPS were negligible due to the number of tokens being small after the TokenLearner layer.</blockquote><p>If the TokenLearner is applied after the 2nd and 3rd attention layer, we can use a larger model with less computational requirement than a smaller variant without TokenLearner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*OmcYP7Rtde_gAiDekRDwrQ.png" /><figcaption>TokenLearner inserted earlier within ViT L/16. 384x384 input images used.</figcaption></figure><h4>TokenLearner Comparisons 🚨</h4><p>Authors have compared the TokenLearner with spatial pooling to reduce the number of tokens.</p><blockquote>We are able to observe that there is a benefit in token ‘learning’. The pooling-based token reduction does have computation similar to the TokenLearner, but it loses its accuracy compared to the base model.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*6CCt95WGBNeWeaL93am-VA.png" /><figcaption>TokenLearner compared against pooling-based token reduction.</figcaption></figure><h4>TokenLearner Implementation ✍️</h4><p>Consider an image with dimensions 1024 * 1024 and a patch size of 16 * 16. Each token’s embedding dimension is 768. In this scenario, the total number of tokens is calculated as (1024/16) * (1024/16) = 4096.</p><p>Tokens can be represented in batch format as [Batch, Num_Tokens, Embedding_Dims]. Alternatively, the same tokens can be expressed as [Batch, Embedding_Dims, N_H, N_W], where N_H and N_W represent the number of patches in width and height, and both are equal to the square root of Num_Tokens.</p><pre>import torch<br>import torch.nn as nn<br><br>in_chans = 3 #RGB<br>embed_dim = 768 # vector dimension in model space<br>patch_size = 16 # each image patch size 16*16<br>proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) # this will create the patch in image<br>img = torch.randn(1, 3, 1024, 1024) # dummy image<br><br>#------------ Embeddings format 2 --------------<br>x = proj(img) # [1, 768, 64, 64], [Batch, Embedding_Dims, N_H, N_W]<br>#------------ Embeddings format 1--------------<br>x = proj(img).flatten(2) # BE(HW)<br>print(x.shape) # [1, 768, 4096]</pre><p>We convert the inputs in [Batch, Num_Tokens, Embedding_Dims] format.</p><pre>if x.ndim == 4:<br>    B, E, H, W = x.shape<br>    inputs = x.view(B, E, H*W)<br>elif x.ndim == 3:<br>    inputs = x<br>else:<br>    raise ValueError(&quot;Unknown Input format&quot;)<br>inputs = inputs.permute(0, 2, 1)<br>feature_shape = inputs.shape # B(HW)E<br>print(feature_shape) # [1, 4096, 768], B(HW)E</pre><p>Normalize next on feature dimension.</p><pre>selected = inputs<br>selected = nn.LayerNorm(embed_dim)(selected) # [1, 4096, 768]</pre><p>Next, we compute the weight matrix as below with two MLP layers.</p><pre>mlp_dim: int = 64<br>dropout_rate = 0.1<br>num_tokens = 256<br>actual_out_dim = num_tokens<br><br><br>x = nn.Linear(selected.shape[2], mlp_dim, bias=True)(selected)<br>act1 = nn.GELU()(x)<br>x = nn.Dropout(p=dropout_rate)(x)<br><br><br>output = nn.Linear(mlp_dim, actual_out_dim, bias=True)(x)<br>output = nn.Dropout(p=dropout_rate)(output)<br>output.shape # [1, 4096, 256]</pre><p>Also, SoftMax is used instead of Sigmoid layer to clip the weights.</p><pre>output = output.view(<br>  feature_shape[0], -1, num_tokens)  # Shape: [bs, h*w, n_token].<br>output = output.permute(0, 2, 1)  # Shape: [bs, n_token, h*w].<br>output = F.softmax(output, dim=-1)<br>output.shape # [1, 256, 4096]</pre><p>Finally, we do the weighted sum across the old token dimension(4096 tokens).</p><pre>feat = inputs<br>feat = torch.einsum(&#39;...si,...id-&gt;...sd&#39;, (output, feat))<br>feat.shape # [1, 256, 768]</pre><h4>Adding all the bits and pieces together 🎡</h4><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class MlpBlock(nn.Module):<br>    mlp_dim: int = 64<br>    def __init__(self, out_dim: int, embed_dim: int, dropout_rate=0.1, use_bias=True, activation_fn=None):<br>        super().__init__()<br>        self.out_dim = out_dim<br>        self.dropout_rate = dropout_rate<br>        self.use_bias = use_bias<br>        self.activation_fn = nn.GELU if activation_fn is None else activation_fn<br><br>        self.mlp_1 = nn.Sequential(<br>            nn.Linear(embed_dim, self.mlp_dim, bias=self.use_bias),<br>            self.activation_fn(),<br>            nn.Dropout(p=self.dropout_rate)<br>        )<br>        self.mlp_2 = nn.Sequential(<br>            nn.Linear(self.mlp_dim, self.out_dim, bias=self.use_bias),<br>            nn.Dropout(p=self.dropout_rate)<br>        )<br><br>    def forward(self, inputs, deterministic=False):<br>        return self.mlp_2(self.mlp_1(inputs))<br><br>class TokenLearnerModuleV11(nn.Module):<br>    def __init__(self, num_tokens: int, embed_dim: int, mlp_dropout_rate: float=0.0):<br>        super().__init__()<br>        self.num_tokens = num_tokens<br>        self.embed_dim = embed_dim<br>        <br>        self.ln = nn.LayerNorm(self.embed_dim)<br>        self.mlp_block = MlpBlock(out_dim=num_tokens, embed_dim=embed_dim, dropout_rate=mlp_dropout_rate)<br><br>    def forward(self, inputs):<br>        &quot;&quot;&quot;<br>        Expects the inputs in following formats: BE(HW), [B, E, N_H, N_W]<br>        &quot;&quot;&quot;<br>        if inputs.ndim == 4:<br>            B, E, H, W = inputs.shape<br>            inputs = inputs.view(B, E, H*W)<br>        elif inputs.ndim != 3:<br>            raise ValueError(&quot;Unknown Input format&quot;)<br><br>        inputs = inputs.permute(0, 2, 1)<br>        feature_shape = inputs.shape # B(HW)E<br><br>        selected = inputs<br>        selected = self.mlp_block(self.ln(selected)) # Shape: [bs, h*w, n_token].<br>        selected = selected.permute(0, 2, 1)  # Shape: [bs, n_token, h*w].<br>        selected = F.softmax(selected, dim=-1)<br><br>        feat = inputs<br>        feat = torch.einsum(&#39;...si,...id-&gt;...sd&#39;, (selected, feat))<br><br>        return feat<br><br># Example usage<br>batch_size = 8<br>sequence_length = 4096 # 16*16<br>embedding_size = 768<br>n_tokens = 256<br><br># Input tensor, B(HW)E<br>input_tensor = torch.rand((batch_size, embedding_size, sequence_length))<br># Apply the TokenLearner<br>TokenLearnerModuleV11(num_tokens=n_tokens, embed_dim=embedding_size)(input_tensor).shape</pre><p>The authors initially implemented a different version (with 4 convolution layers) of the TokenLearner module.</p><blockquote>Instead of using 4 conv. layers with small channels to implement spatial<br> attention, this version uses a MLP with gelu inbetween. It also uses softmax instead of sigmoid. We confirmed that this version works better in general.</blockquote><p>I am adding that implementation also but you can skip this section if you want to.</p><p>Similar to what we have done before we convert the input to a fixed format ([B, E, N_H, N_W]) and normalize.</p><pre>import torch<br>import torch.nn as nn<br><br>in_chans = 3 #RGB<br>embed_dim = 768 # vector dimension in model space<br>patch_size = 16 # each image patch size 16*16<br>proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) # this will create the patch in image<br>img = torch.randn(1, 3, 1024, 1024) # dummy image<br><br>#------------ Embeddings format 2 --------------<br>x = proj(img) # [1, 768, 64, 64], [Batch, Embedding_Dims, N_H, N_W]<br>#------------ Embeddings format 1--------------<br>x = proj(img).flatten(2) # BE(HW)<br>print(x.shape) # torch.Size([1, 4096, 768])<br><br><br>if x.ndim == 4:<br>    inputs = x<br>elif x.ndim == 3:<br>    B, E, N = x.shape<br>    N_H = N_W = int(N**0.5)<br>    inputs = x.view(B, E, N_H, N_W)<br>else:<br>    raise ValueError(&quot;Unknown Input format&quot;)<br>feature_shape = inputs.shape # BHWE<br>feature_shape # [1, 768, 64, 64]</pre><p>Let’s say we want to use 256 tokens. We apply convolution to reduce the dimension of the tokens from 768 to the number of output tokens (256 in this example). We apply four consecutive convolutions.</p><pre>num_tokens = 256<br>selected = inputs<br>selected = nn.LayerNorm(feature_shape)(selected) # normalization<br><br>for _ in range(3):<br>    selected = nn.Conv2d(<br>        ip_chns,<br>        num_tokens,<br>        kernel_size=(3, 3),<br>        stride=(1, 1),<br>        padding=&#39;same&#39;,<br>        bias=False)(selected)  # Shape: [B, n_token, N_H, N_W]<br>    ip_chns = selected.shape[1] # update the input channels<br><br>    selected = nn.GELU()(selected)<br># selected shape [1, 256, 64, 64]<br># Last convolution. No acctivation after that.<br>selected = nn.Conv2d(<br>        selected.shape[1],<br>        num_tokens,<br>        kernel_size=(3, 3),<br>        stride=(1, 1),<br>        padding=&#39;same&#39;,<br>        bias=False)(selected) <br>selected.shape # [1, 256, 64, 64], Shape: [B, n_token, N_H, N_W]</pre><p>We got a weight map in the previous step.</p><pre>selected = selected.view(<br>feature_shape[0], feature_shape[2] * feature_shape[3], -1)<br>selected.shape # B, H*W, n_tokens, [1, 4096, 256]<br><br>selected = selected.permute(0, 2, 1) # B, n_tokens, H*W<br>selected.shape # [1, 256, 4096]</pre><p>The selected tensor we got in the previous step is mapping the weights of each of the old 4096 tokens into each of the new 256 tokens. Since we weights can be large (unbounded) we apply the Sigmoid function to clip the weights between 0 and 1.</p><pre>selected = nn.Sigmoid()(selected)[..., None]<br>selected.shape # [1, 256, 4096, 1], Shape: [B, n_token, h*w, 1].</pre><p>Next, we multiply with the original inputs.</p><pre>feat = inputs.view(<br>feature_shape[0], feature_shape[2] * feature_shape[3], -1)[:, None, ...]<br>feat.shape # [1, 1, 4096, 768], Shape: [B, 1, h*w, E].</pre><p>Get the final tokens:</p><pre>final_tokens = torch.mean(feat * selected, axis=2)<br>final_tokens.shape # [1, 256, 768]</pre><p>In the paper, the authors have introduced another module TokenFuser, and used TokenLearner and TokenFuser in video datasets with transformer.</p><h4>Resources</h4><ol><li><a href="https://github.com/google-research/scenic/blob/main/scenic/projects/token_learner/">Official JAX Implementation</a></li><li><a href="https://arxiv.org/abs/2106.11297">Paper</a></li></ol><h4>Connect with me</h4><p>Feel free to drop me a message or</p><ol><li>Connect and reach out on <a href="https://www.linkedin.com/in/mandalsouvik/"><strong>LinkedIn</strong></a></li><li>Follow me on <a href="https://medium.com/@mandalsouvik"><strong>Medium</strong></a> or <a href="https://github.com/souvik3333"><strong>GitHub</strong></a></li></ol><p>Have a nice day ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60bf14248611" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/tokenlearner-60bf14248611">TokenLearner: What Can 8 Learned Tokens Do for Images and Videos?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CLIP: Learning Transferable Visual Models From Natural Language Supervision]]></title>
            <link>https://itnext.io/clip-learning-transferable-visual-models-from-natural-language-supervision-29f2817f317f?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/29f2817f317f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 11:24:07 GMT</pubDate>
            <atom:updated>2023-10-01T07:27:22.215Z</atom:updated>
            <content:encoded><![CDATA[<p>CLIP (Contrastive Language Image Pre-training) paper was published in 2021 by OpenAI. This paper introduces the idea of using image caption as a soft label for the image-caption pair available on the internet.</p><p>The idea of using the internet scale dataset is taken from NLP where the GPT -3-like system was performing very well because of training on large-scale internet datasets but in the vision domain majority of the time we were using ImageNet as pre-training or pre-trained weights.</p><h4>Dataset 🎯</h4><p>The authors have created 400 million images, and text pairs from the internet data.</p><h4>Selecting a pre-training task ✍️</h4><p>Initially, the authors trained a CNN (image encoder) and transformer (text encoder) to predict the caption of an image, but they encountered many difficulties in this. Next, they tried to predict the bag-of-words encodings of the same text. This makes the model learn 3x faster in zero-shot ImageNet classification.</p><p>The main reason for this is predicting exact works for text is difficult due to the wide variety of descriptions, comments, and related text (synonyms) that co-occur with images.</p><p>The authors next tried to use contrastive objectives because constructive objectives can learn better re-presentations than their equivalent predictive objective.</p><blockquote>Although generative models of images can learn high quality image representations, they require over an order of magnitude more compute than contrastive models with the same performance (Chen et al., 2020a).</blockquote><p>Finally, they selected an easier proxy task of predicting which text as a whole paired with which image and not the exact word of that text. This gains a 4x efficiency improvement than bag-of-words prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*fHoHf3IBTJuQjMmc4e0N2A.png" /><figcaption>Efficiency of the model against multiple pre-training tasks</figcaption></figure><h4>CLIP architecture 🌎</h4><p>Given a batch of N image and text pairs, there can be N*N possible image and text pairs. Out of those pairs N pairs should have high cosine similarity and the remaining N²-N incorrect pairings should have low cosine similarity.</p><p>First, we compute the image encodings with an image encoder, which is represented as I₁ to Iₙ. Similarly, the corresponding captions are passed through the text encoder to get the text embeddings as T₁ to Tₙ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*9meFRqIb1NP46tZM66_7Fg.png" /><figcaption>CLIP Pre-Training.</figcaption></figure><p>Next, we compute the cosine similarity between the I<em>ᵢ</em> T<em>ⱼ </em>pairs and if <em>i==j</em> then the model is trained to maximize the cosine similarity it tries to minimize the cosine similarity.</p><h4>Image and Text encoders</h4><p>For the image encoders, the authors have used different variations of ResNet (ResNet-50, ResNet-101, and so on) and vision transformers (ViT-B/14, ViT-B/16, ViT-L/14).</p><p>For the ResNet models, they have added a few modifications to the originally proposed architecture like antialiased rect-2 blur pooling, and attention pooling in place of adaptive average pooling, along with the improvements from ResNet-D paper.</p><p>For the vision transformer, they added an additional layer normalization layer to the combination of patch and positional embeddings before the transformer and used a different initialization scheme. The remaining components are the same as the original ViT paper.</p><p>For the text encoder, they use the transformer with 63M parameters, 12 layers 512 wide model with 8 attention heads. They have used a lowercase byte pair encoding with 49512 vocab size. The context length is 76 tokens and [SOS] and [EOS] tokens are used as the start and end of the sentence tokens. Masked self-attention was used in the text encoder to be able to use the pre-trained language model weights.</p><p>For the final model authors have used is ViT-L, with a patch size of 14*14 and an image size of 336*336.</p><p>One interesting point is that the authors have found CLIP performance is less sensitive to the capacity of the text encoder. I think that&#39;s why they have not done much study with different text encoders.</p><h4>Linear Projection layer</h4><p>In CLIP implementation the image embedding dimension is 1024 and the text embedding dimension is 512. We apply a project layer to project the text embeddings to image embeddings. This layer does the image, and text feature alignment also.</p><h4>Training Details</h4><ol><li>The image and the text encoders are trained from scratch.</li><li>A random square crop from resized images is the only data augmentation used during training.</li><li>The temperature parameter that controls the range of the logits in softmax was directly optimized during training as log parameterized multiplicative scalar.</li><li>They have trained the model for 32 epochs.</li><li>Since the models are trained from scratch they have trained the model for 1 epoch and scaled the hyper-parameters accordingly for larger models.</li><li>A batch size of 32768 was used along with gradient checkpointing. There will be similar text (or caption) in a batch. The large batch size should minimize the error contributed by this (This is similar to SimCLR).</li></ol><h3>Understanding bits and pieces along with code 🎡</h3><p>Let&#39;s first get the image encoder. We will use the standard torchvision resnet34 without any changes mentioned before.</p><pre>import torch.nn as nn<br>from torchvision.models import resnet34, ResNet34_Weights<br><br># image encoder<br>visual_encoder = resnet34(weights=ResNet34_Weights.IMAGENET1K_V1)<br>visual_encoder.fc = nn.Identity() # remove the last linear layer</pre><p>Let&#39;s create a fake image and pass it through the image encoder. In the original paper, most of the model extracts features of dim 1024 but in this example, we have image feature dimension 512.</p><pre>import torch<br><br>img = torch.randn(2, 3, 224, 224) # B, C, H, W<br>img_features = visual_encoder(img) <br>img_features.shape # (2, 512)</pre><p>Let&#39;s create the text encoder next, which is a Transformer.</p><pre>class Transformer(nn.Module):<br>    def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):<br>        &quot;&quot;&quot;<br>        Transformer for text encoder.<br>        Args:<br>            width: token embeddings dimension<br>            layers: number of transformer attention blocks<br>            heads: number of attention heads<br>            attn_mask: causal attention mask<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.width = width<br>        self.layers = layers<br>        self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])<br><br>    def forward(self, x: torch.Tensor):<br>        return self.resblocks(x)</pre><p>We will have to implement the ResidualAttentionBlock. It will consist of the attention layer and the multi-layer perceptron layer (MLP layer). Note, that one change here is the initial normalization (ln_1)to normalize the inputs along with the post-normalization (ln_2).</p><pre>from collections import OrderedDict<br><br>class ResidualAttentionBlock(nn.Module):<br>    def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):<br>        super().__init__()<br><br>        self.attn = nn.MultiheadAttention(d_model, n_head)<br>        self.ln_1 = nn.LayerNorm(d_model) # This is the additional normalization layer different from the original transformer paper<br>        self.mlp = nn.Sequential(OrderedDict([<br>            (&quot;c_fc&quot;, nn.Linear(d_model, d_model * 4)),<br>            (&quot;gelu&quot;, nn.GELU()),<br>            (&quot;c_proj&quot;, nn.Linear(d_model * 4, d_model))<br>        ]))<br>        self.ln_2 = nn.LayerNorm(d_model)<br>        self.attn_mask = attn_mask<br><br>    def attention(self, x: torch.Tensor):<br>        self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None<br>        return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]<br><br>    def forward(self, x: torch.Tensor):<br>        x = x + self.attention(self.ln_1(x))<br>        x = x + self.mlp(self.ln_2(x))<br>        return x </pre><p>Let’s create the config for the transformer</p><pre>transformer_width = 512 # token embeddings dim<br>transformer_layers = 12 # total attention blocks<br>transformer_heads = 8 # number heads in multihead attention block<br>context_length = 77 # max number of tokens</pre><p>We will also need to create the mask array for the attention.</p><pre>mask = torch.empty(context_length, context_length)<br>mask.fill_(float(&quot;-inf&quot;))<br>mask.triu_(1)  # zero out the lower diagonal</pre><p>For example, if the context length is 7 then we will have a mask as follows. The idea here is to ignore the future tokens and only use the previous tokens for attention. This is called causal masking.</p><pre>tensor([[0., -inf, -inf, -inf, -inf, -inf, -inf],<br>        [0., 0., -inf, -inf, -inf, -inf, -inf],<br>        [0., 0., 0., -inf, -inf, -inf, -inf],<br>        [0., 0., 0., 0., -inf, -inf, -inf],<br>        [0., 0., 0., 0., 0., -inf, -inf],<br>        [0., 0., 0., 0., 0., 0., -inf],<br>        [0., 0., 0., 0., 0., 0., 0.]])</pre><p>Let’s create the text encoding transformer.</p><pre>transformer = Transformer(<br>    width=transformer_width,<br>    layers=transformer_layers,<br>    heads=transformer_heads,<br>    attn_mask=mask<br>)</pre><p><strong>Byte Pair Encoding</strong> is used as a tokenizer for CLIP. BPE builds a vocabulary dynamically as part of the tokenization process starting with vocab consisting of characters only. Then it iteratively merges the most frequent character sequences into longer subword units. This process continues for a predefined number of iterations or until a stopping criterion is met. To tokenize a text using BPE, you break the text into a sequence of overlapping subword units found in the learned vocabulary.</p><p>Suppose we have a small corpus of text:</p><pre>1. &quot;apple pie&quot;<br>2. &quot;apple juice&quot;<br>3. &quot;banana pie&quot;</pre><p>We start with an initial vocabulary that includes individual characters: Vocabulary: {‘a’, ‘p’, ‘l’, ‘e’, ‘ ‘, ‘b’, ’n’, ‘i’, ‘u’, ‘c’} . Now, we iteratively apply BPE:</p><p><strong><em>Iter: 1</em></strong></p><p>We count character sequences and find that “ap” is the most frequent, so we merge it: Vocabulary: {‘ap’, ‘p’, ‘l’, ‘e’, ‘ ‘, ‘b’, ’n’, ‘i’, ‘u’, ‘c’}</p><p><strong><em>Iter: 2</em></strong></p><p>We count character sequences again and find that “ple” is the most frequent, so we merge it: Vocabulary: {‘ap’, ‘p’, ‘le’, ‘ ‘, ‘b’, ’n’, ‘i’, ‘u’, ‘c’}</p><p><strong><em>Iter: 3</em></strong></p><p>We continue the process, merging the next most frequent sequences, and so on: Vocabulary: {‘ap’, ‘p’, ‘le’, ‘ ‘, ‘b’, ’n’, ‘i’, ‘u’, ‘c’, ‘pie’, ‘ban’, ‘ana’, ‘juice’}</p><p><strong><em>Tokenization</em></strong></p><p>Now, let’s tokenize the phrase apple pie using this BPE vocabulary: Tokenization: [‘ap’, ‘le’, ‘ ‘, ‘pie’]</p><p>Now if we use the tokenizer trained on the CLIP dataset and tokenize apple pie we will get [3055, 5319]. Note these are not embeddings, these are the index of the subword in the vocab. Now we need to project these indexes to the corresponding embedding. We do this as</p><pre>token_embedding = nn.Embedding(vocab_size, transformer_width)</pre><p>These token embeddings (projection from the index to embeddings) are learned during training. vocab_size is the total number of subwords/ vocabulary size and transformer_width is the text embedding dimension.</p><p>Now, given a sentence, we first get the indices of all the subwords in the vocab.</p><pre>from tokenizer import SimpleTokenizer # From the CLIP repo<br>tokenizer = SimpleTokenizer()<br><br>text = [&quot;A long time ago, in a galaxy far, far away...&quot;, &quot;The quick brown fox jumps over the lazy dog.&quot;]<br>bpe_enc_text = tokenizer.encode(text[0])<br>bpe_enc_text # [320, 1538, 788, 1468, 267, 530, 320, 6545, 2384, 267, 2384, 1520, 678]</pre><p>Now, there are two tokens &lt;|startoftext|&gt; and &lt;|endoftext|&gt; which we add to the encoded tokens.</p><pre>sot_token = tokenizer.encoder[&quot;&lt;|startoftext|&gt;&quot;]<br>eot_token = tokenizer.encoder[&quot;&lt;|endoftext|&gt;&quot;]<br>sot_token, eot_token # 49406, 49407</pre><p>Adding the tokens</p><pre>all_tokens = [[sot_token] + tokenizer.encode(text) + [eot_token] for text in text]<br>all_tokens # [[49406,   320,   1538,   788,   1468,   267,   530,   320,   6545,   2384,   267,   2384,   1520,   678,   49407]]</pre><p>Now, the context length is 77 but we have only 15 tokens. We pad the remaining tokens with 0 and if the sentence is longer than context length length we crop to context length.</p><pre>result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)<br><br>for i, tokens in enumerate(all_tokens): # go through each sentence<br>        if len(tokens) &gt; context_length: # if the sentence is longer than the context length<br>            tokens = tokens[:context_length] # take the first context_length tokens<br>            tokens[-1] = eot_token # replace the last token with the end of text token<br>        result[i, :len(tokens)] = torch.tensor(tokens)<br><br># tensor([[49406,   320,  1538,   788,  1468,   267,   530,   320,  6545,  2384,<br>#            267,  2384,  1520,   678, 49407,     0,     0,     0,     0,     0,<br>#              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,<br>#              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,<br>#              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,<br>#              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,<br>#              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,<br>#              0,     0,     0,     0,     0,     0,     0]])<br># shape [2x77] I have only shown the results of first sentence here</pre><p>Next, we project from the indices to the embedding dimension</p><pre>embed_text = token_embedding(result)<br>embed_text.shape # torch.Size([2, 77, 512])</pre><p>Next, we add the positional embeddings</p><pre>x = embed_text + positional_embedding<br>x.shape # torch.Size([2, 77, 512])</pre><p>Pass it through the text encoder</p><pre>x = transformer(x.permute(1, 0, 2)) #Batch, Context_Length, Embed_dim (BCE) -&gt; CBE. This is how the transformer process the data<br>x.shape # [77, 2, 512]</pre><p>Revert back to the original orientation and normalize</p><pre>ln_final = nn.LayerNorm(transformer_width)<br><br>x = x.permute(1, 0, 2)  # CBE -&gt; BCE<br>x = ln_final(x)<br>x.shape # [2, 77, 512]</pre><p>Next, we project the text embedding dimension to the dimension we get from the image encoder.</p><pre>embed_dim = 512 # vision encoder output dimension<br># here I have replaced torch.empty with torch.randn so that we dont get all zero output<br>text_projection = nn.Parameter(torch.randn(transformer_width, embed_dim)) # linear projection layer</pre><p>Take the features from the eot embedding.</p><pre>encodded_text = x[torch.arange(result.shape[0]), result.argmax(dim=-1)] @ text_projection<br>encodded_text.shape # torch.Size([2, 512])</pre><p>Normalized features</p><pre>image_features = img_features / img_features.norm(dim=1, keepdim=True)<br>text_features = encodded_text / encodded_text.norm(dim=1, keepdim=True)</pre><p>Compute the cosine similarity of all the image, and text pairs and scale the similarity:</p><pre>cosine_sim = image_features @ text_features.t()<br><br>logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))<br>logit_scale = logit_scale.exp() # log scale, learned during training<br><br>logits_per_image = logit_scale * cosine_sim<br>logits_per_text = logits_per_image.t()</pre><p>Create the labels</p><pre>labels = torch.arange(logits_per_image.shape[0], dtype=torch.long)<br>labels # diagonal elements are the correct pairs</pre><p>Compute the loss</p><pre>total_loss = (<br>    torch.nn.functional.cross_entropy(logits_per_image, labels) +<br>    torch.nn.functional.cross_entropy(logits_per_text, labels)<br>) / 2</pre><p>During inference, we compute the argmax of logits_per_image to compute the corresponding text given a list of text (We can do zero-shot classification with this).</p><pre>text_indices = logits_per_image.argmax(dim=1)</pre><h4>Zero-Shot Classification Downstream task</h4><p>Given a list of possible classes and an image, we first create a list of text from the list of classes.</p><p>For example, for class names: [‘cat’, ‘dog’], we will create text as [‘a photo of a cat’, ‘a photo of a dog’]. Essentially we are converting ina photo of a {cls_name} format.</p><blockquote>Usually the text is a full sentence describing the image in some way. To help bridge this distribution gap, we found that using the prompt template “A photo of a {label}.” to be a good default that helps specify the text is about the content of the image. This often improves performance over the baseline of using only the label text. For instance, just using this prompt improves accuracy on ImageNet by 1.3%.</blockquote><p>Then we pass these texts through the text encoder and the image through the image encoder. The text with the highest cosine similarity with the image will be the predicted class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*HtHlF38d0J0KplOmjlhxLw.png" /><figcaption>Zero-Shot classification with CLIP</figcaption></figure><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*QOrEuRvUWrDm8dK7TdFVUw.png" /><figcaption>Across a 27-dataset eval suite, a zero-shot CLIP classifier outperforms a fully supervised linear classifier fitted on ResNet-50 features on 16 datasets, including ImageNet.</figcaption></figure><p>That&#39;s it for this paper. Hope you have enjoyed it. If you want to discuss a paper, do reach out to me on <a href="https://www.linkedin.com/in/souvikmandal">Linkedin</a>. Have a nice day.</p><p><strong>Resources</strong></p><ol><li><a href="https://arxiv.org/abs/2103.00020"><em>CLIP Paper</em></a></li><li><a href="https://github.com/openai/CLIP"><em>CLIP Implementation</em></a></li><li><a href="https://huggingface.co/learn/nlp-course/chapter6/5?fw=pt"><em>Byte Pair Encoding</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29f2817f317f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/clip-learning-transferable-visual-models-from-natural-language-supervision-29f2817f317f">CLIP: Learning Transferable Visual Models From Natural Language Supervision</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Masked Autoencoders As Spatiotemporal Learners]]></title>
            <link>https://itnext.io/masked-autoencoders-as-spatiotemporal-learners-7b99a70633e2?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b99a70633e2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 13:41:38 GMT</pubDate>
            <atom:updated>2023-08-23T13:41:38.538Z</atom:updated>
            <content:encoded><![CDATA[<p>This paper shows the results and findings of applying MAE on a video dataset. The same concepts should be applicable to other 3-dimensional data like point clouds, and volumetric medical images (CT Scans).</p><p>This paper was published in Oct 2022 by some of the same authors as MAE. This blog will be an extension of my previous blog where we discussed MAE, please check out that blog if you are not familiar with masked auto-encoders.</p><p><a href="https://itnext.io/masked-autoencoders-are-scalable-vision-learners-122a75b54470">Masked Autoencoders Are Scalable Vision Learners</a></p><h4>3D Volumetric/ Spatiotemporal data</h4><p>From 2D data we have patches based on 2D patches, for the video dataset we can think of them as a stack of multiple 2D data creating a 3D volume. So the dimension we are stacking the frame will be the time axis (T in Figure 1), and the other two are the spatial axis (width and height).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*HUIMmi8QL63wdJBO0zTOPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*ywykRFuR3pxog9wU7stz4w.png" /><figcaption>Figure 1: Left Image: 2D image, Right Image: 3D volumetric data or spatiotemporal data</figcaption></figure><p>So, for 3D volumes, we have patches which are also 3D volumes. This is just adding one extra dimension to our previous code for 2D MAE.</p><pre>import torch<br>import torch.nn as nn<br>from einops.layers.torch import Rearrange<br>from einops import rearrange<br><br># B, C, D, H, W<br>img = torch.randn(2, 3, 16, 224, 224)<br><br>patch_h = 2<br>patch_w = 16<br>patch_d = 16<br>patch_dim = patch_h * patch_w * patch_d * 3 # Channels=3<br>embed_dim = 1024<br><br>img_patch_embedding = (<br>    nn.Sequential(<br>        Rearrange(<br>            &quot;b c (d p1) (h p2) (w p3) -&gt; b d h w (p1 p2 p3 c)&quot;,<br>            p1=patch_d,<br>            p2=patch_h,<br>            p3=patch_w,<br>        ),<br>        nn.LayerNorm(patch_dim),<br>        nn.Linear(patch_dim, embed_dim),<br>        nn.LayerNorm(embed_dim),<br>    )<br>)<br><br>img_patches = rearrange(img_patch_embedding(img), &quot;b ... d -&gt; b (...) d&quot;)<br>img_patches.shape # Batch, NUM_patches, Embedding_dim</pre><p>During training the authors used 16 frames, each of size 224*224 to create the 3D array. The patch size that they have considered is 2*16*16</p><p>Now once we have the tokens from the patches we will have to update our positional encoding such that they have temporal information also.</p><p>Let’s first create 1D positional embeddings. 1D positional embedding we compute with the following equations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*q_gNXqjt8x_5u79R.png" /><figcaption>Positional embedding equations</figcaption></figure><p>We can implement that below</p><pre>import numpy as np<br>from typing import Optional<br><br>def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):<br>    &quot;&quot;&quot;<br>    embed_dim: output dimension for each position<br>    pos: a list of positions to be encoded: size (M,)<br>    out: (M, D)<br>    &quot;&quot;&quot;<br>    assert embed_dim % 2 == 0<br>    # get the index of all the even and odd index positions<br>    omega = np.arange(embed_dim // 2, dtype=float)<br>    omega /= embed_dim / 2.0 #(div each i with d_model/2)<br>    omega = 1. / 10000**omega   # (D/2,)<br><br>    pos = pos.reshape(-1)   # (M,) List of positions<br>    out = np.einsum(&#39;m,d-&gt;md&#39;, pos, omega)   # (M, D/2), outer product<br><br>    emb_sin = np.sin(out)  # (M, D/2)<br>    emb_cos = np.cos(out)  # (M, D/2)<br><br>    emb = np.concatenate([emb_sin, emb_cos], axis=1)<br>    return emb</pre><p>For a 2D image, we will have both each patch will have both x position and y position compared to 1D inputs (like words in a sentence).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*vMtio8rJ_6JGP4Oz1peq5g.png" /><figcaption>1D and 2D positional embeddings</figcaption></figure><p>Now, to compute the positional embeddings of the (0, 0) patch we can compute the positional embedding as Concatenate(PE(pos=0), PE(pos=0)). Basically, we use the same equation twice first with the x and then with the y index for each patch. Then, concatenate them to get the final embedding. For patch (0,1) it will be (PE(pos=0), PE(pos=1)). Now since we are concatenating the x and y representation each of them will contribute only half of the representation. So, In the case of a 2D image if embed_dim is 256 the first 128 will come from PE(pos=x_index) and the last 128 will come from PE(pos=y_index). For 3D we just add one more dimension and each contributes 1/3 of the embedding dim.</p><pre>def get_sincos_pos_embed_from_grid(embed_dim: int, grid: np.ndarray):<br>    ndim = grid.shape[0]<br>    assert embed_dim % 2 == 0 if ndim ==2 else embed_dim % 3 == 0, f&quot;For 2D and 3D embed dim should be divisible by 2 and 3&quot;<br><br>    if ndim==3:<br>        emb_d = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[0]) # 1/3 in-case of 3D<br>        emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[1]) # (D*H*W, embedding_dim/3)<br>        emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[2])<br>        emb = np.concatenate([emb_d, emb_h, emb_w], axis=1)  # (D*H*W, embedding_dim)<br>    else:<br>        # use half of dimensions to encode grid_h<br>        emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])  # 1/2 in-case of 2D<br>        emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])  # (H*W, embedding_dim/2)<br>        emb = np.concatenate([emb_h, emb_w], axis=1)  # (H*W, embedding_dim)<br>    return emb<br><br>def get_sincos_pos_embed(<br>        embed_dim: int, <br>        grid_width: int, <br>        grid_height: int, <br>        grid_depth: Optional[int] = None,<br>        cls_token: bool = False<br>):<br>    &quot;&quot;&quot;<br>    grid_size: int of the grid height and width<br>    return:<br>    pos_embed: [grid_width*grid_height, embed_dim] or <br>    [1+grid_width*grid_height*grid_depth, embed_dim] (w/ or w/o cls_token)<br>    &quot;&quot;&quot;<br>    grid_h = np.arange(grid_height, dtype=float)<br>    grid_w = np.arange(grid_width, dtype=float)<br>    if grid_depth: # 3D <br>        grid_d = np.arange(grid_depth, dtype=float)<br>        grid = np.meshgrid(grid_d, grid_h, grid_w)  # zyx<br>        grid = np.stack(grid, axis=0) # 3, grid_depth, grid_height, grid_width<br>        grid = grid.reshape([3, 1, grid_depth, grid_height, grid_width])<br>        pos_embed = get_sincos_pos_embed_from_grid(embed_dim, grid)<br>    else: # 2D<br>        grid = np.meshgrid(grid_h, grid_w)  # here h goes first<br>        grid = np.stack(grid, axis=0)<br>        grid = grid.reshape([2, 1, grid_height, grid_width])<br>        pos_embed = get_sincos_pos_embed_from_grid(embed_dim, grid)<br>    if cls_token:<br>        pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)<br>    return pos_embed</pre><p>The remaining parts of the implementation (The encoder and decoder are both ViT encoders, masking strategy is random masking) are the same as the original MAE implementation. Please check the MAE blog for the details.</p><p><strong>The loss function</strong> is also the same as before: The average of the <strong>mean squared error</strong> between the predicted and the ground truth for the masked patches.</p><h4>Some Interesting observations</h4><ol><li><strong>The masking ratio in the video is 90%</strong>. For the image in the original paper, the authors have mentioned the masking ratio for the image is 75%. The information redundancy in the video is even more than in images, also most of the available videos will not be of fast motion so across frames changes will not be significant.</li><li><strong>Random patch masking work best, compared to space-only, time-only, and block masking.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAOPtgeU0WDsI8Ix7moCsw.png" /><figcaption>Figure 2: (a) Random Patch masking (b) Space-only masking (c) Time-only masking (d) Block masking</figcaption></figure><p>Random masking randomly selects some percentage of the total patches to drop out.</p><p>Space-only masking selects some patch locations in the X-Y dimension and then drops all the corresponding patches across time (Basically that spatial coordinate is completely masked).</p><p>Time only selects a few time instances and drops all the patches on the X-Y dimension, basically dropping all the patches at a certain time.</p><p>Block masking selects single or multiple blocks (each block can consist of single or multiple patches). This block selection can be based on size and aspect ratio. For example, the size of the dropped blocks can be between 50%-80% of the original image and the aspect ratio can be 0.75–1.4. This way we will have blocks of multiple sizes and aspect ratios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*eut8CR8GWzN_Nfxo_FAd4g.png" /><figcaption>Figure 3: From patches block selection. Three blocks are selected of different aspect ratios and locations. The same idea extends to 3D blocks.</figcaption></figure><p>The results of different masking strategies are shown in Figure 4 (a).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*U4SM4sA0MIM3jsB-nF_Xqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*eYbrcAWYXgJQM96NIHs6Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*B3dy_RTMBGcMuqytQ_TtMQ.png" /><figcaption>Figure 4 (a) Performance vs Masking strategy (b) Target vs Performance (c) Transforms vs Performance</figcaption></figure><p>3. Like the image domain here (video) the reconstruction target is the original image pixels. <strong>Using per-patch normalized pixels improves the results by 0.6%</strong>. Per-patch normalization will increase the contrast locally which improves the results (Figure 4 (b)).</p><p>4. Even <strong>without any augmentation other than Center Crop the method performs well</strong> like in images. But one thing to note here is that video data can have natural augmentation like blur, jitter, and brightness change. So for other volumetric data augmentation might improve results (Figure 4(c)).</p><p>5. Since 90% of the patches are dropped, processing time in the encoder and decoder is very fast. <strong>The data loading becomes the bottleneck.</strong> The authors have <strong>adopted a repeated sampling strategy</strong>[2] to increase the batch size without increasing data reading time. Repeated sampling is basically when we load a batch of data like normal training, then we apply multiple sets of augmentation on the batch. So, we have three set transforms and a batch size of 4 then after applying the transform, we will have an effective batch size of 12. This method does not also increase the data loading time.</p><p>6. Small decoder width and depth reduce the performance model after linear probing. In the case of images, this does not change much even with smaller dimensions of decoder embeddings and a smaller number of decoder blocks. Authors hypothesized that <strong>high-dimension video data is more complex and requires more decoding capability</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*0JlgHJW4QkWTTUuEi8-xLg.png" /><figcaption>(a) Decoder embedding dim vs. Accuracy (b) Decoder depth vs. Accuracy</figcaption></figure><p>7. The training time improvement comes in two ways: One is because of dropping 90% of the 3D only 1/10 of the data is processed by the encoder which decreases the processing time and memory consumption. Because of less memory usage, we can use batch augmentation without increasing data reading time which will further decrease training time.</p><blockquote>the MAE pre-training can achieve a theoretically 7.7× reduction in computation vs. encoding all tokens.</blockquote><p>8. The authors have applied the MAE trained on Video dataset K400 on images. <strong>They have deflated the patch embeddings by summing them in the time dimension</strong>. On ImageNet1K classification this method got 83.7 Accuracy (Scratch training got 82.6 accuracies).</p><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBDzHKqYpLGH9ZTfGeopxQ.png" /></figure><p>Performance on downstream tasks like action recognition also gives better/similar results than the supervised method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlFWnDFFAOXbcALE-xS71Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFQFZMKr9s985fn8hLbGxw.png" /><figcaption>Model output with 90% masking on the Kinetics-400 dataset. The original video (top), masked video (middle), and MAE output (bottom) for each sample are shown.</figcaption></figure><p>Thanks for reading this blog. Hope you have enjoyed it. If you want to discuss any paper do reach out on my <a href="https://www.linkedin.com/in/mandalsouvik/">LinkedIn</a>. Have a nice day.</p><h4>Resources</h4><ol><li><a href="https://arxiv.org/abs/2205.09113">This Paper</a></li><li><a href="https://arxiv.org/abs/1901.09335">Repeated Sampling</a></li><li><a href="https://arxiv.org/abs/2111.06377">masked auto-encoders</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b99a70633e2" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/masked-autoencoders-as-spatiotemporal-learners-7b99a70633e2">Masked Autoencoders As Spatiotemporal Learners</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I-JEPA: Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture]]></title>
            <link>https://itnext.io/i-jepa-self-supervised-learning-from-images-with-a-joint-embedding-predictive-architecture-e896c73e011a?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/e896c73e011a</guid>
            <category><![CDATA[self-supervised-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 22:54:33 GMT</pubDate>
            <atom:updated>2023-08-11T22:54:33.389Z</atom:updated>
            <content:encoded><![CDATA[<p>This paper from Meta proposes a self-supervised technique which tries to learn highly semantic image features without relying on hand-crafted augmentations. The main idea of this paper is to give a context block predict representation of various target blocks. This method got +7.9 top 1 accuracy than masked auto-encoders on ImageNet-1k dataset.</p><h4>Types of self supervised architectures 🚀</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPDc8ctD0q1eQU8nhyon6g.png" /><figcaption>Figure 1: Different types of self-supervised method</figcaption></figure><p>Based on how the image representations are compared and generated, self-supervised models can be divided into three categories:</p><ol><li><strong>Joint Embedding Architecture (JEA)<br></strong>Joint Embedding Architectures learn to predict similar embeddings for compatible inputs x, y and dis-similar embeddings for in-compatible inputs.<br>One such example is SimCLR, where different sets of transforms are applied to the same image to generate compatible input pairs. For the in-compatible inputs model, two different images are used.<br>In the Figure 1 x-encoder and y-encoder can be two different encoders, or they can one one encoder with weight sharing mechanism.<br>The main challenge of JEA is representation collapse, where the encoder produces same representation regardless of the input. This can be solved in a few ways, like different sized encoders for x-encoder and y-encoder, explicitly push apart embeddings of negative pairs.</li><li><strong>Generative Architecture<br></strong>Generative architectures learn to reconstruct a signal y from a compatible signal x using a decoder network that is conditioned on additional variables z.<br>Masked auto-encoders (MAE) are one such example of this. In the case of MAE, we mask out part of an image and pass only the un-masked parts of the image through the encoder. Then in the decoder, we pass the mask token (learned during training and defines which part is reconstructed) for the masked parts along with the un-masked features learned from the encoder to predict the masked part of the original image. So the masked image is the input x , masked tokens are the additional condition z and the masked part of the original image is the signal y we are trying to predict.<br>Representation collapse is not a problem here.</li><li><strong>Joint-Embedding Predictive Architecture (JEPA)<br></strong>Joint-Embedding Predictive Architectures are similar to generative architecture; the only difference is that loss is computed on the embeddings space and not on the input space.<br>JEPAs learn to predict the embeddings of a signal y from a compatible signal x, using a predictor network that is conditioned on an additional<br>(possibly latent) variable z to facilitate prediction.<br>One benefit of this type of method over JEA is that JEPAs do<br>not seek representations invariant to a set of hand-crafted<br>data augmentations. In JEA, when we apply two different sets of transforms, the model is forced to learn that given change rotation, angle, and noise we should get the same embeddings. JEPA tries to predict multiple areas/regions given a context region which should force the model to learn more semantic information, and no need to choose which all transforms should we select. This type of method also suffers from representations collapse.<br><strong>This paper is a varient of this type of method. </strong>They solve the representation collapse by using asymmetric encoders (encoders of different sizes.)</li></ol><h3>Image-based Joint-Embedding Predictive Architecture (I-JEPA) 💥</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*OeVD2Or5t6h5Rzn1px3J7Q.png" /><figcaption>Figure 2: I-JEPA architecture</figcaption></figure><p>There are three main components in the I-JEPA: Context selection, target selection, and predictor. The context, target encoders and predictor are Vision Transformer (ViT) architecture.</p><h4>Context Selection 🎧</h4><p>For context, the authors select a random large square block with a scale in the range of (0.85, 1.0). Here scale means the size compared to the original image. This means the context block can be from 85% of the image to the full image.</p><p>This context block will also consist of multiple patches. The patches that overlap with the target blocks are removed from the context block <strong>before processing through the context encoder</strong>. The context encoder is a ViT encoder.</p><h4>Target Selection 🎯</h4><p>The targets are the feature representations of different image blocks (or patches). Given an input image, it is converted into a sequence of non-overlapping patches. Then they are passed through the target encoder to get the feature representations. Each block of the image will have the corresponding feature representations. In Figure 3, there are 25 non-overlapping patches on the original image. Then we pass them through the target encoder to get the feature representation of the 25 tokens.</p><p>We select some of the neighbourhood patch representations to create a target. In Figure 2, the red target representation consists of 4 patch’s representations and the same for the yellow target. There is an overlapping patch between red and yellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bq68F8viM-0MgF7RgMTjXQ.jpeg" /><figcaption>Figure 3: Target selection from the Input Image</figcaption></figure><p>Authors have mentioned they normally select 4 target blocks. Each target block consists of patches with a random aspect ratio between (0.75, 1.5) and random scale (0.15, 0.2). The target encoder is a ViT encoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baeYNo4MWH7v0ZUUop0MGQ.png" /><figcaption><em>Examples of context and target-masking strategy.</em></figcaption></figure><h4>Predictor</h4><p>We learn a mask token during training (This is similar to &lt;SoS&gt; and &lt;EoS&gt; tokens in NLP and is learned during training). For each of the patch we want to predict, we add the corresponding positional encodings to this mask token. For M number of target blocks prediction, predictor is called M times with encoded context and (mask token + positional embeddings) for all of the patches as inputs.</p><p>The overall architecture is shown in Figure 2.</p><h4>Loss</h4><p>The loss is the L2 distance between the predicted patch-level representations and the target patch-level representation.</p><p>The context encoder weights are updated through the gradients from the loss, but the target encoder weights are updated through an exponential<br>moving average of the context-encoder parameters. Generally, the exponential moving average target-encoder works really well for training JEAs with Vision Transformers.</p><h4>Results</h4><p>To check the model has learned good semantic features from images during pre-training, authors have reported results on various image classification tasks using the linear probing and partial fine-tuning protocols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*QmGOVGti1eyRwqi0cbN8Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*skkFPyQNUIkMZkHMKdZCSg.png" /><figcaption>Linear Probing results. Left Image: The models are pre-trained on ImageNet-1K dataset then a linear classifier is trained on top of the frozen encoder. Right Image: Pre-Training hours for I-JEPA is lower than other methods.</figcaption></figure><p>In the case of Semi-Supervised training (First pre-training, then linear probing or fine-tuning), this paper produces better results. For each model best of the linear-probing and finetuning is taken. Also, the model is fine-tuned on 1% of the ImageNet-1K dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*yLn9EoMKAw_07XlSqw60mg.png" /><figcaption>I-JEPA produces better results on downstream classification task with less number of epochs (less training time) on ImageNet-1K dataset</figcaption></figure><blockquote>Linear evaluation on downstream image classification tasks. I-JEPA significantly outperforms previous methods that also do not use augmentations (MAE and data2vec), and decreases the gap with the best view-invariance-based methods that leverage hand-crafted data augmentations during pre-training.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*EEs3ZZJo66OxAXZyKEkHyw.png" /><figcaption><em>Linear-probe transfer for image classification</em></figcaption></figure><blockquote>Linear evaluation on downstream low-level tasks consisting of object counting (Clevr/Count) and depth prediction (Clevr/Dist). The IJEPA method effectively captures low-level image features during pretraining and outperforms view-invariance based methods on tasks such object counting and depth prediction.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*uUncRL2m1RdPCKbo6q1-GA.png" /><figcaption><em>Linear-probe transfer for low-level tasks</em></figcaption></figure><blockquote>We also find I-JEPA to benefit from pretraining with larger datasets.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_Jn3NzApGgt27Q0iTJAnA.png" /><figcaption><em>Evaluating impact of pre-training dataset size and model size on transfer tasks.</em></figcaption></figure><h4>❓Why does this work</h4><p>One of the reasons this works is because it works on the latent space than pixel space. When predicting in latent space, each of the missing pieces is some high level features or objects. This makes much more sense to mask out objects or high level features and trying to predict them with a context because this masking idea came from NLP where we predict a masked token/word based on the neighbourhood tokens/words. In the image domain, words should be mapped to objects, not pixels, since pixels do not have much semantic information individually as words do. When we pass this through the encoder, we get high level features from the object and redundant pixel level information is generally removed. This is the reason this works well.</p><p>Hope you enjoyed this paper. Have a nice day.</p><p><strong>Resources:</strong></p><ol><li><a href="https://github.com/facebookresearch/ijepa/tree/main">GitHub</a></li><li><a href="https://arxiv.org/abs/2301.08243">Paper</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e896c73e011a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/i-jepa-self-supervised-learning-from-images-with-a-joint-embedding-predictive-architecture-e896c73e011a">I-JEPA: Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DETR: End-to-End Object Detection with Transformers (Part 1)]]></title>
            <link>https://itnext.io/detr-end-to-end-object-detection-with-transformers-part-1-4a7ec4e386f7?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a7ec4e386f7</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 13:15:29 GMT</pubDate>
            <atom:updated>2023-08-08T13:15:29.996Z</atom:updated>
            <content:encoded><![CDATA[<p>Detection is the most complicated task compared to classification or segmentation due to multiple layers like region proposal layer, anchor boxes generator, RoI align layer, non-max suppression, classification, and regression head. <strong>DE</strong>tection <strong>TR</strong>ansformer solves this problem using a CNN encoder and a Transformer encoder, decoder architecture.</p><p>For the detection task, one of the main problems is removing near identical bounding boxes (prediction boxes with high IoU among themselves). Most current detectors use post-processing, such as non-maximal suppression, to address this issue, but direct set predictions are post-processing free.</p><h3>DETR architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrOYGYqM9bqndmErcJf-LA.png" /><figcaption>DETR architecture</figcaption></figure><p>DETR have three main components: CNN Backbone, Transformer Encoder, Transformer Decoder.</p><h4>Backbone:</h4><p>This is a CNN backbone like ResNet-50, ResNet-101. This is used to generate low resolution feature maps. If an initial image is of [3, H0, W0] dimensions encoder reduces it to [C, H, W].</p><p>If we are using resnet50 the width and heights are scaled down by a scale of 32.</p><pre>import torch<br>import torch.nn as nn<br>from torchvision.models import resnet50</pre><pre>backbone = resnet50()</pre><pre>img = torch.randn(2, 3, 512, 512)</pre><pre>features = backbone.conv1(img)<br>features = backbone.bn1(features)<br>features = backbone.relu(features)<br>features = backbone.maxpool(features)</pre><pre>features = backbone.layer1(features)<br>features = backbone.layer2(features)<br>features = backbone.layer3(features)<br>features = backbone.layer4(features)</pre><pre>features.shape # torch.Size([2, 2048, 16, 16]),  512/32 = 16</pre><p>Once we get the feature vector from the CNN backbone, <strong>a 1x1 convolution is applied to reduce the channels from C (</strong><strong>2048 for </strong><strong>resnet50) to d (</strong><strong>256)</strong>. So, the feature map shape will be [d, H, W].</p><pre>conv = nn.Conv2d(2048, 256, 1)</pre><pre>down_features = conv(features)<br>down_features.shape # torch.Size([2, 256, 16, 16])</pre><h4>Transformer</h4><p>I won’t go into the details of Transformer architecture here. I will discuss the changes they did to a standard Transformer architecture. If you want to brush up on Transformer architecture go through this once:</p><p><a href="https://itnext.io/attention-is-all-you-need-e8109d2693e">Attention is all you need!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*q9X0hPl0M2zPsR6SLgXWsA.png" /><figcaption>Transformer architecture in DETR</figcaption></figure><h4>:=: Similarities and dis-similarities with traditional transformer</h4><p>If we compare the transformer architecture used in DETR (above image), there are lots of similarities like it takes the image features (similar to token or word embeddings in attention is all you need). It will add the positional encodings and pass through the encoder. Encoder will have self-attention and MLP layers and normalisation and Residual connections.</p><p>Now in the Encoder part <em>two things that are different from standard architecture is how positional encodings are computed and if you notice carefully the positional encodings are not being added to the values.</em></p><h4>💭 why the positional encodings are not being added to the values?</h4><p>One of the author mentioned in GitHub[1]</p><blockquote>we follow the standard practice, see Transformer XL or Stand-alone self-attention in vision, in adding positional encoding to queries and keys only, except in our case it is absolute and not relative.</blockquote><p>Though ViT does apply positional encoding to value vector also. Value vectors supposed to have features of a token or image patch. So, if it works without positional encoding here, is that step not necessary for vision transformer?</p><p>For positional encodings DETR have added both fixed and learnable encodings. Learnable is same as other papers. For fixed positional encodings the encoding depends on the feature size and the padding of the corresponding image.</p><h4>How do we handle the paddings?</h4><p>When training models in image data we need to make the image of same size to make same number of patches. But images might will not be of same size. One way to solve this is to pad the image.</p><p>But padded parts of the image does not have any information so doing attention on those patches are not required. This is why to keep track which parts of the features maps are coming from such padded patches and we skip then when doing attention.</p><p>Lets say we have two image of different size.</p><pre>img1 = torch.ones((3, 512, 512)) * 0.5<br>img2 = torch.ones((3, 256, 380)) * 0.5</pre><pre>import matplotlib.pyplot as plt</pre><pre>plt.subplot(1,2,1)<br>plt.imshow(img1.permute(1,2,0).numpy())<br>plt.subplot(1,2,2)<br>plt.imshow(img2.permute(1,2,0).numpy())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*pYvGSJV3qm-Emvi556uCbA.png" /><figcaption>Dummy images with different shapes.</figcaption></figure><p>Pad the small image to create a batch.</p><pre>from util.misc import nested_tensor_from_tensor_list<br># nested_tensor_from_tensor_list function just checks the largest <br># size along each dimension and pad the other images to the same size<br># I have added the code reference in the resources</pre><pre>img = nested_tensor_from_tensor_list([img1, img2])</pre><pre># view the image<br>plt.subplot(1,2,1)<br>plt.imshow(img.tensors[0].permute(1,2,0).numpy())<br>plt.subplot(1,2,2)<br>plt.imshow(img.tensors[1].permute(1,2,0).numpy())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*dbpLdIMDGv5FTdZYMVSOTQ.png" /><figcaption>The small images are padded with zeros on bottom right</figcaption></figure><p>It will return two masks corresponding to the two images. These masks will have True at (x,y) location if it was padded on that location else it will be False. So, for the first image we will have a mask with everything set to False.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*cCd3r7le7ebxNlSfqr6bKw.png" /><figcaption>Padding mask. True if padding was applied on that pixel else False.</figcaption></figure><p>Not the padding mask is with respect to the image size but we need to know which pixels in the features map came from the padded region. We interpolate the initial mask vector to the shape of the output from the backbone.</p><pre>mask = torch.nn.functional.interpolate(<br>img.mask[None].float(), size=down_features.shape[-2:]).to(torch.bool)[0]</pre><pre>mask.shape # torch.Size([2, 16, 16])</pre><pre>plt.subplot(1,2,1)<br>plt.imshow(mask[0].numpy(), cmap=&quot;gray&quot;)<br>plt.subplot(1,2,2)<br>plt.imshow(mask[1].numpy(), cmap=&quot;gray&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*_pArT0g5Ub6EDTeM9oLq_w.png" /><figcaption>Padding mask on the feature maps</figcaption></figure><h4>❓How do we compute positional encoding for an 2D vector</h4><p>Positional encoding are used to given information about the location of a word/patch in a sentence/ image. But because image patches are 2D we need to give both x and y information and someway add that to the embeddings (Positional encodings are generally added to the word/patch embeddings).</p><p>Here each location on the feature map acts as a token or patch embeddings. The feature vector size is 2, 256, 16, 16 for a batch size of 2. So, here we have total 16*16 tokens and each tokens embedding size is 256 which is same as channel dimension.</p><pre>tokens = down_features.flatten(2).permute(2, 0, 1) <br># [256, 2, 256] num_patches, B, embedding_dim</pre><p>Now we need to add positional information following way: for each of the 16*16 location on the feature map we create a 256 dim vector and first 128 of the vector will have x location information and the next 128 will have y location information.</p><p>First we use the padding mask to get a indices of each location in the feature map. Note if some value is padded it will have the same value as the previous location. We create the encodings for both x and y direction.</p><pre>not_mask = ~mask<br>y_embed = not_mask.cumsum(1, dtype=torch.float32)<br>x_embed = not_mask.cumsum(2, dtype=torch.float32)<br>y_embed.shape, x_embed.shape # torch.Size([2, 16, 16]), torch.Size([2, 16, 16])</pre><p>This results in something similar to a mesh-grid which have information about the padding. Next, we normalize the values between 0,1. And finally scale to 2*pi .</p><pre>eps = 1e-6<br>y_embed = y_embed / (y_embed[:, -1:, :] + eps) * 2 * math.pi # [2, 16, 16]<br>x_embed = x_embed / (x_embed[:, :, -1:] + eps) * 2 * math.pi # [2, 16, 16]</pre><p>This y_embed and x_embed the the y and x positions of each of the locations in the feature map. Now remember the positional encoding function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*aiqA-hNyHUf_CCUU.png" /><figcaption><a href="https://medium.com/@mandalsouvik/transformer-positional-embeddings-f73fee304900">Positional embeddings</a></figcaption></figure><pre>num_pos_feats = 128 # 128 because this is half of the token embeddings dim (256)<br>temperature = 10000<br>dim_t = torch.arange(num_pos_feats, dtype=torch.float32) <br># dim_t is all the i&#39;s in the above equation<br>dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats)</pre><p>The dim_t is the divisor part of the above equations. Now the position is already computed before. We can get the positional embeddings for x and y locations separately.</p><pre>pos_x = x_embed[:, :, :, None] / dim_t # [2, 16, 16, 128]<br>pos_y = y_embed[:, :, :, None] / dim_t # [2, 16, 16, 128]<br><br># apply sin to even and cosine to odd indices<br>pos_x = torch.stack(<br>(pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()<br>), dim=4).flatten(3) # [2, 16, 16, 128]<br>pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)</pre><p>Next we concat the pos_x and pos_y to get the final positional embeddings.</p><pre>pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) # torch.Size([2, 256, 16, 16])</pre><p>Finally we have the positional embeddings of same size as the word embeddings and with x, and y index information. Remaining part of the encoder is same as normal transformer encoder. Only note is that positional encodings are not added to the values. Also we can normalize the information before the attention and MLP layers or after them (Default is after).</p><pre>class TransformerEncoderLayer(nn.Module):<br><br>    def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,<br>                 activation=&quot;relu&quot;, normalize_before=False):<br>        super().__init__()<br>        self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)<br>        # Implementation of Feedforward model<br>        self.linear1 = nn.Linear(d_model, dim_feedforward)<br>        self.dropout = nn.Dropout(dropout)<br>        self.linear2 = nn.Linear(dim_feedforward, d_model)<br><br>        self.norm1 = nn.LayerNorm(d_model)<br>        self.norm2 = nn.LayerNorm(d_model)<br>        self.dropout1 = nn.Dropout(dropout)<br>        self.dropout2 = nn.Dropout(dropout)<br><br>        self.activation = _get_activation_fn(activation)<br>        self.normalize_before = normalize_before<br><br>    def with_pos_embed(self, tensor, pos: Optional[Tensor]):<br>        return tensor if pos is None else tensor + pos<br><br>    def forward_post(self,<br>                     src,<br>                     src_mask: Optional[Tensor] = None,<br>                     src_key_padding_mask: Optional[Tensor] = None,<br>                     pos: Optional[Tensor] = None):<br>        # Positional embeddings not added to the values<br>        q = k = self.with_pos_embed(src, pos)<br>        # key_padding_mask=src_key_padding_mask this is the padding mask which <br>        # is used to skip the padded patches<br>        src2 = self.self_attn(q, k, value=src, attn_mask=src_mask,<br>                              key_padding_mask=src_key_padding_mask)[0]<br>        # Skip connection<br>        src = src + self.dropout1(src2)<br>        # normalization<br>        src = self.norm1(src)<br>        # feed forward MLP network<br>        src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))<br>        # skip connection<br>        src = src + self.dropout2(src2)<br>        # normalization<br>        src = self.norm2(src)<br>        return src<br><br>    def forward_pre(self, src,<br>                    src_mask: Optional[Tensor] = None,<br>                    src_key_padding_mask: Optional[Tensor] = None,<br>                    pos: Optional[Tensor] = None):<br>        src2 = self.norm1(src)<br>        q = k = self.with_pos_embed(src2, pos)<br>        src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask,<br>                              key_padding_mask=src_key_padding_mask)[0]<br>        src = src + self.dropout1(src2)<br>        src2 = self.norm2(src)<br>        src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))<br>        src = src + self.dropout2(src2)<br>        return src<br><br>    def forward(self, src,<br>                src_mask: Optional[Tensor] = None,<br>                src_key_padding_mask: Optional[Tensor] = None,<br>                pos: Optional[Tensor] = None):<br>        if self.normalize_before:<br>            return self.forward_pre(src, src_mask, src_key_padding_mask, pos)<br>        return self.forward_post(src, src_mask, src_key_padding_mask, pos)</pre><p>Transformer encoder implementation</p><pre>def _get_clones(module, N):<br>    return nn.ModuleList([copy.deepcopy(module) for i in range(N)])<br><br>class TransformerEncoder(nn.Module):<br><br>    def __init__(self, encoder_layer, num_layers, norm=None):<br>        super().__init__()<br>        self.layers = _get_clones(encoder_layer, num_layers)<br>        self.num_layers = num_layers<br>        self.norm = norm <br>        # if we are using normalize before then this should be <br>        # set to layer norm because for the Encoder layer normalization<br>        # did not happen<br><br>    def forward(self, src,<br>                mask: Optional[Tensor] = None,<br>                src_key_padding_mask: Optional[Tensor] = None,<br>                pos: Optional[Tensor] = None):<br>        output = src<br><br>        for layer in self.layers:<br>            output = layer(output, src_mask=mask,<br>                           src_key_padding_mask=src_key_padding_mask, pos=pos)<br><br>        if self.norm is not None:<br>            output = self.norm(output)<br><br>        return output</pre><p>Finally the transformer code (The decoder part we will discuss in the next blog):</p><pre>class Transformer(nn.Module):<br><br>    def __init__(self, d_model=512, nhead=8, num_encoder_layers=6,<br>                 num_decoder_layers=6, dim_feedforward=2048, dropout=0.1,<br>                 activation=&quot;relu&quot;, normalize_before=False,<br>                 return_intermediate_dec=False):<br>        super().__init__()<br><br>        encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward,<br>                                                dropout, activation, normalize_before)<br>        encoder_norm = nn.LayerNorm(d_model) if normalize_before else None<br>        self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)<br><br>        decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward,<br>                                                dropout, activation, normalize_before)<br>        decoder_norm = nn.LayerNorm(d_model)<br>        self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm,<br>                                          return_intermediate=return_intermediate_dec)<br><br>        self._reset_parameters()<br><br>        self.d_model = d_model<br>        self.nhead = nhead<br><br>    def _reset_parameters(self):<br>        for p in self.parameters():<br>            if p.dim() &gt; 1:<br>                nn.init.xavier_uniform_(p)<br><br>    def forward(self, src, mask, query_embed, pos_embed):<br>        # src is the tensor extracted by the backbone<br>        # mask is the padding mask tensor<br>        # flatten NxCxHxW to HWxNxC<br>        bs, c, h, w = src.shape<br>        src = src.flatten(2).permute(2, 0, 1) # [L, B, embed_dim]<br>        pos_embed = pos_embed.flatten(2).permute(2, 0, 1) <br>        mask = mask.flatten(1)<br>        <br>        memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed)<br>        <br>        # This part we will understand during the decoder part<br>        query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1) # [100, embed_dim] -&gt; [100, B, embed_dim]<br>        tgt = torch.zeros_like(query_embed)<br>        hs = self.decoder(tgt, memory, memory_key_padding_mask=mask,<br>                          pos=pos_embed, query_pos=query_embed)<br>        return hs.transpose(1, 2), memory.permute(1, 2, 0).view(bs, c, h, w)</pre><p>Hope you enjoyed this part. We will discuss the decoder part, loss function and results in the next blog.</p><p><strong>Resources:</strong></p><ol><li><a href="https://github.com/facebookresearch/detr">https://github.com/facebookresearch/detr</a></li><li><a href="https://arxiv.org/abs/2005.12872">DETR Paper</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a7ec4e386f7" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/detr-end-to-end-object-detection-with-transformers-part-1-4a7ec4e386f7">DETR: End-to-End Object Detection with Transformers (Part 1)</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Masked Autoencoders Are Scalable Vision Learners]]></title>
            <link>https://itnext.io/masked-autoencoders-are-scalable-vision-learners-122a75b54470?source=rss-be3f74e4d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/122a75b54470</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Souvik Mandal]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 19:30:59 GMT</pubDate>
            <atom:updated>2023-07-16T19:30:59.934Z</atom:updated>
            <content:encoded><![CDATA[<p>This paper is from Facebook AI Research (FAIR) published in 2021. This paper introduced a novel architecture Masked Autoencoders or MAEs for training models self-supervised way. The training methodology is mainly targeted towards vision transformers (ViT) like architectures.</p><p>META Research (not Facebook anymore 😛) has recently released Segment Anything. That model uses a pre-trained backbone trained with this method.</p><p>This architecture produces better results than existing methods with much less time (3x faster). Let’s understand <strong><em>why</em></strong> and <strong><em>how</em></strong> it works.</p><h4>MAE architecture</h4><p>We will first go through a high-level overview of the architecture and the method. Then, we will go into one component at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNY53pVHP29XeQWdfAeLeA.jpeg" /><figcaption>Masked autoencoder Training Process. Note during Add back the masked tokens we also rearragne the patches such that they follow the original order.</figcaption></figure><ol><li>First, we create patches from the image. Each of the patches can be think as a single word in the case of NLP training. Next, we randomly drop out 75% of the patches. This patch drop is randomly selected.</li><li>Now, for the encoder, we only pass the patches that were not dropped in the last step. Because we are not processing all the patches it makes the training process much faster (because majority of the patches are dropped).</li><li>Note, the non-masked patches that go into the encoder, also do not follow any order. We add the positional embeddings before masking such that even if we do any permutation on the input patches model will always have idea about the positional information about the patches.</li><li>Once we have the features from the transformer encoder for non-masked patches, we add back the masked patches information. These masked patches that we add back in a special way, and they are called mask token. This mask token is learned during training and same for all the patches that are dropped.</li><li>Also, we rearrange the patches such that they are in the original order (before random drop out of patches and random patches stacking). Actually, we keep trac of the indices of the non-masked patches in the original image and we put them in the correct places and fill the rest of the empty locations (corresponding to the masked patches) with the mask tokens.</li><li>Next, we pass them through the decoder. Transformer encoder is the encoder from the ViT. No change in architecture done for the decoder also. To refresh your knowledge of ViT, you may want to read this blog post.</li></ol><p><a href="https://medium.com/mlearning-ai/an-image-is-worth-16x16-words-transformers-for-image-recognition-at-scale-51f3561a9f96">An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</a></p><p>7. Once we have the decoders outputs, we reconstruct each of the patches from the corresponding tokens.</p><p>MAE network consists of an asymmetric encoder-decoder architecture. Asymmetric encoder-decoder architectures are where the length of encoder and decoders are different. The encoder operates only on the subset of the image patches (patches that are not masked). The decoder reconstructs the original image from the latent representation and mask tokens.</p><p>In case of MAE the encoder is larger, the embedding dimension of each of the patches for the encoder if 768 but for decoder it is 512. Also, the decoder uses 8 decoder blocks (depth) but the encoder uses 24 encoder blocks. Because of smaller decoder and encoder processing a smaller number of patches the training is super faster.</p><h4>Where the idea of masked autoencoders came from? 💭</h4><p>If you are following the research in vision transformers one of the main problems with them is large training data requirements to perform well. With same amount of small dataset CNNs still performs better. Getting large, labelled data is a problem.</p><p>Transformer idea came from NLP. If we check, there how this problem is fixed there: Self-Supervised pretraining. They remove part of a sentence and try to predict this based on the available parts of the sentence. With this simple per-training method people are training NLP models with trillions of parameters (GPT-4 rumors to have 1.8 trillion of parameters 😶).</p><h4>How is it different from Denoising auto-encoders (<em>DAE</em>)? 🤔</h4><p>Removing some of the patches and not processing them in encoder and processing everything in decoder is what the main concept of MAE. DAE corrupts the image (by adding noise, changing contrast, dropping color channel and so on) and try to predict the uncorrected image. You can thing MAE as a special form of DAE but not the other way around.</p><h4>Why so many patches are dropped? 😱</h4><p>Other questions that creep up is why so many patches are dropped. (Around 75% of the patches are dropped). This is normally not the case with NLP.</p><p>Answer is that language models are highly semantic and information dense. Just pick up any sentence in this blog and see if you remove randomly 75% of the data will you be able to predict what the remaining parts trying to say. So, for NLP dropping few words and trying to predict them is hard enough that model will need to learn cross relation across words.</p><p>Images have high special redundancy. A missing patch can be easily recovered with just interpolation with the neighborhood patches. See the image below, you can remove lots of patches from the road and will still be able to reconstruct with just interpolation.</p><blockquote>This strategy (large proportion of patch dropout) largely reduces redundancy and creates a challenging selfsupervisory task that requires holistic understanding beyond low-level image statistics.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PnIkj4anrlMzGnRW" /><figcaption>Random Image to understand the redundancy in images. Photo by <a href="https://unsplash.com/@iangvalerio?utm_source=medium&amp;utm_medium=referral">Ian Valerio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Why asymmetric encoder-decoder architecture? 📗</h4><p>Based on the previous discussion we know that image have very redundant information and decoder is basically reconstructing the latent space information (fancy term meaning the features extracted by the encoder) to input level or pixel space. So, the decoder requires low level semantic information to generate so not complicated task thus small size is fine.</p><p>Also, if you see in the encoder, we are only processing the remaining patches after masking, but in decoder we are processing all the patches. So, having small decoder and large encoder will speed-up the training process that equal size encoder-decoder. This asymmetric nature of the model consumes less memory than traditional encoder-decoder models.</p><h4>Loss Function</h4><p>Mean squared error is used to train the MAE. We only compute the loss for the masked patches and not on the non-masked patches.</p><h4>Results:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*cg1YESxQ2DD7jHzzseFA1g.png" /><figcaption>The pre-training data is the ImageNet-1K training set. All self-supervised methods are evaluated by end-to-end fine-tuning. The best for each column is underlined. All results are on an image size of 224, except for ViT-H with an extra result on 448.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*FHEXp2ZzWB2kowR_XRT75Q.png" /><figcaption>MAE pre-training vs. supervised pre-training, evaluated by fine-tuning in ImageNet-1K (224 size). Compared with the original ViT results trained in IN1K or JFT300M.</figcaption></figure><h4>Understanding bits and pieces along with code 🎡</h4><p>Finally let&#39;s go through the fine-grained details of the implementation.</p><p>Let’s take an image, resize it to a fixed size and create non overlapping patches.</p><pre>import numpy as np<br><br>import torch<br>import torch.nn as nn<br><br>from PIL import Image<br>import matplotlib.pyplot as plt<br><br># load a image and resize it to 224x224<br>image = Image.open(&quot;/content/dog_img.jpg&quot;).convert(&quot;RGB&quot;).resize((224,224))<br>plt.imshow(image)<br>plt.axis(&quot;off&quot;)</pre><p>Define some of the parameters.</p><pre>img_size = image.size # (224, 224): image size<br>in_chans = len(image.mode) # input image channels: 3<br><br>patch_size = (16, 16) # width and height of each of the patches</pre><p>Visualize the patches in the image</p><pre># Show the patches in the images<br>image = np.array(image)<br>cell_width, cell_height = patch_size<br><br>for i in range(1, 16):<br>    x = i * cell_width<br>    image[:, x - 1:x + 1] = [255, 0, 0]<br><br>for i in range(1, 16):<br>    y = i * cell_height<br>    image[y - 1:y + 1, :] = [255, 0, 0]<br><br>plt.imshow(image)<br>plt.axis(&quot;off&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*bH4qLyJCbRMoQ6lNpQJQHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*AV_D0CeLbEcgHHoeoLBQbg.png" /><figcaption>Original Image and Creating patches each with size 16x16</figcaption></figure><p>Next, we will create the feature embeddings from each of the patches. In the MAE paper, the default patch dimension is 768. We are using a 2D convolution to slide over the patches and output the feature embeddings. See the kernel size and stride are same as patch size.</p><pre># some preprocessing convert the image to Batch, Channel, Width, Height format.<br># Ideally we should do all the transforms, normalization in this point<br># but I am not doing them here<br>image = torch.from_numpy(np.array(image))<br>img_t = image.permute(2, 0, 1) # C, W, H (3, 224, 224)<br>img_t = img_t.unsqueeze(0) # B, C, W, H  (1, 3, 224, 224)<br><br><br># conv 2d layer to converts the patches into embeddings<br>proj = nn.Conv2d(<br>    in_chans,<br>    embed_dim,<br>    kernel_size=patch_size,<br>    stride=patch_size,<br>)<br>proj_op = proj(img_t.float())<br>proj_op.shape # C, embed_dim, 14, 14 (1, 768, 14, 14)</pre><p>Reshape the output to Batch, Number_of_patches, embedding_dims.</p><pre># B, embed_dim, W, H -&gt; B, patches, embed_dim<br>proj_op = proj_op.flatten(2).transpose(1, 2) # 1, 196, 768</pre><p>So, we finally got 196 patches and each patch has 768 feature dimensions. In the MAE authors have used learned positional embeddings in the encoder.</p><pre>num_patches = np.prod( tuple([s // p for s, p in zip(img_size, patch_size)])) <br># total number of patches = 14*14<br>num_patches # 196<br><br>pos_embed = nn.Parameter(<br>    torch.zeros(1, num_patches + 1, embed_dim), # +1 for the cls token<br>    requires_grad=False<br>) # B, patches, embed_dim, (1, 197, 768)</pre><p>Add the positional encodings without the class token’s positional encoding.</p><pre># add pos embed without the cls token<br>proj_op = proj_op + pos_embed[:, 1:, :]<br>proj_op.shape # 1, 196, 768</pre><p>Let’s do the random masking next. We will use 75% masking ratio. Since we have 196 patches, we will only keep 49 patches after masking.</p><pre>mask_ratio = 0.75<br><br>B, L, D = proj_op.shape  # batch, length, dim (1, 196, 768)<br>len_keep = int(L * (1 - mask_ratio)) # 49</pre><p>We will create a random noise torch tensor of shape batch, num_patches. Next, we will keep the indices of the first 49 indices in ascending order. For example, if we have a single data point and assume we are creating 5 patches from each image (instead of 196 patches) we can have a noise tensor like [0.6, 0.9, 0.4, 0.7, 0.8] Now let’s say we want to keep 3 patches data instead of 49. We will keep the patches at following indices [2 ,0 ,3] and mask out the remaining.</p><pre># create the random noise tensor<br>noise = torch.rand(B, L, device=proj_op.device) # noise in [0, 1]<br>noise.shape # torch.Size([1, 196])<br><br># sort in non-decreasing order such that the indices will lowest values<br># in the noise tensor will be fast<br>ids_shuffle = torch.argsort(noise, dim=1)<br>ids_shuffle.shape # torch.Size([1, 196])<br><br># take the indices of the first 49 for each of the image<br>ids_keep = ids_shuffle[:, :len_keep]</pre><p>Once we know which patch’s embeddings, we are keeping we will take the embeddings. Going with the smaller example, if we have a proj_op as follows.</p><pre>[[[0.1, 0.2, 0.3],<br>  [0.4, 0.5, 0.6],<br>  [0.7, 0.8, 0.9],<br>  [1.0, 1.1, 1.2],<br>  [1.3, 1.4, 1.5]],</pre><p>Since we are selecting the following patches [2 ,0 ,3] our non-masked embeddings will be as follows.</p><pre>[[[0.7 ,0.8 ,0.9],<br> [0.1 ,0.2 ,0.3],<br> [1.0   ,1.1   ,1.2]]</pre><p>We do this following way.</p><pre>x_masked = torch.gather(proj_op, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))<br>x_masked.shape # [1, 49, 768]</pre><p>We also add the class token here:</p><pre># class token is learned during training. Checkout the ViT blog to check it in details.<br>cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) # 1, 1, 768<br><br># add positional encodings<br>cls_token = cls_token + pos_embed[:, :1, :]<br># class token is same for all the batches<br>cls_tokens = cls_token.expand(x_masked.shape[0], -1, -1) # 1, 1, 768, since one img in this batch<br># concat the class and patch tokens<br>x = torch.cat((cls_tokens, x_masked), dim=1) # 1, 50, 768</pre><p>We pass the final output x to the transformer encoder.</p><pre>from timm.models.vision_transformer import PatchEmbed, Block<br><br># define the encoder config<br>depth=24<br>num_heads=16<br>mlp_ratio=4.<br>norm_layer=nn.LayerNorm<br>norm = norm_layer(embed_dim)<br><br># initialize the encoder blocks<br>blocks = nn.ModuleList([<br>            Block(embed_dim, num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer)<br>            for i in range(depth)])<br><br># process in the encoder and normalize<br>for blk in blocks:<br>    x = blk(x)<br>x = norm(x) # [2, 50, 768]</pre><p>Now remember we downsample the embeddings from 768 to 512 for decoder.</p><pre>decoder_embed_dim = 512<br>decoder_embed = nn.Linear(embed_dim, decoder_embed_dim, bias=True)<br><br>x = decoder_embed(x) # 2, 50, 512</pre><p>We also define the mask token which is filled for all the masked patches. Similar to cls token this one is also learned during training and shared across batches and masked patches. This represents one masked patch in a batch.</p><pre>mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim)) # 1, 1, 512</pre><p>So, we have total 196 patches and have processed only 49 patches (without the cls token). We will copy the mask token 196–49 = 147 time for all the masked patches.</p><pre>mask_tokens = mask_token.repeat(B, 147, 1) # repeating across batches and patches<br>mask_tokens.shape # 2, 147, 512</pre><p>Now, we need to put the encoder processed tokens and the masked tokens in the original order. Again, going back to the smaller example, if we sort the noise tensor [0.6, 0.9, 0.4, 0.7, 0.8] we will have [2, 0, 3, 4, 1] . After processing through the encoder, we have following output for the first 3 selected patches (patches in indices [2, 0, 3])</p><pre># I have added 1 to the inputs pf the encoder to show this will change<br># while the input is processed in the encoder<br>[[[1.7 ,1.8 ,1.9],<br> [1.1 ,1.2 ,1.3], <br> [2.0   ,2.1   ,2.2]]</pre><p>Let’s add the mask tokens for the remaining two patches [ [1.7 ,1.8 ,1.9], [1.1 ,1.2 ,1.3], [2.0 ,2.1 ,2.2], mask_token, mask_token]. We need to convert this tensor to following format [ [1.1 ,1.2 ,1.3], mask_token, [1.7 ,1.8 ,1.9], [2.0 ,2.1 ,2.2], mask_token].</p><p>If we sort the sorted indices tensor we will have [1, 4, 0, 2, 3] . Now if we use these indices to populate from the mask concatenated tensor list ([ [1.7 ,1.8 ,1.9], [1.1 ,1.2 ,1.3], [2.0 ,2.1 ,2.2], mask_token, mask_token]) we will get the result we want ([ [1.1 ,1.2 ,1.3], mask_token, [1.7 ,1.8 ,1.9], [2.0 ,2.1 ,2.2], mask_token]).</p><p>We do the same as follows:</p><pre># sort noise for each sample<br>ids_restore = torch.argsort(ids_shuffle, dim=1)<br>ids_restore.shape # [1, 196]<br><br># concat the mask tokens for the masked patches<br>x_ = torch.cat([x[:, 1:, :], mask_tokens], dim=1)  # no cls token (1, 196, 512)<br># shuffle to original order<br>x_ = torch.gather(x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2]))<br><br># add the class token<br>x = torch.cat([x[:, :1, :], x_], dim=1) </pre><p>Add decoder positional encodings:</p><pre>decoder_pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, decoder_embed_dim), requires_grad=False)  # fixed sin-cos embedding<br>x = x + decoder_pos_embed</pre><p>Define the decoder:</p><pre>decoder_depth=8<br>decoder_num_heads=16<br><br>decoder_blocks = nn.ModuleList([<br>Block(decoder_embed_dim, decoder_num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer)<br>for i in range(decoder_depth)])<br>decoder_norm = norm_layer(decoder_embed_dim)</pre><p>Process the data through the decoder</p><pre>for blk in decoder_blocks:<br>    x = blk(x)<br>x = decoder_norm(x) # [1, 197, 512]</pre><p>We need to rescale the feature embeddings from each of the patch to patch_height, patch_width * channel. This is the image reconstruction step.</p><pre># define the layer <br>decoder_pred = nn.Linear(decoder_embed_dim, patch_size[0]**2 * in_chans, bias=True) # decoder to patch<br># scale back to 768<br>x = decoder_pred(x) # [1, 197, 768]</pre><p>Remove the class token:</p><pre>x = x[:, 1:, :]</pre><p>From the input side we patchify the image to compute the loss.</p><pre>patch_size = 16<br>num_patches =14<br>imgs = torch.randn(2, 3, 224, 224)<br>x = img_t.reshape(<br>shape=(imgs.shape[0], 3, <br>num_patches, patch_size, num_patches, patch_size)<br>) # [1, 3, 14, 16, 14, 16]<br><br>x = torch.einsum(&#39;nchpwq-&gt;nhwpqc&#39;, x) # change the channel axis: 1, 14, 14, 16, 16, 3<br>pached_img =  x.reshape(shape=(B, num_patches**2 , patch_size**2 * 3))</pre><p>Now out ground truth(pached_img) and prediction (x) is of same shape. But we only want to compute the loss on the masked patches. We do this in a similar way we get shuffle the patches bac to original order before decoder.</p><pre># create a tensor with 1 if it is masked else 0 if not masked<br># initially set every thing to masked.<br>masked = torch.ones([B, L], device=proj_op.device)<br># set the first len_keep number of values to 0 because len_keep are not masked<br>masked[:, :len_keep] = 0<br># unshuffle to get the binary mask<br>masked = torch.gather(masked, dim=1, index=ids_restore)</pre><p>next we compute the loss</p><pre>loss = (x - pached_img) ** 2<br>loss = loss.mean(dim=-1)  # [B, num_patches], mean loss per patch<br><br>loss = (loss * mask).sum() / mask.sum()  # mean loss on removed patches<br></pre><p>That’s it for this blog. Have a nice day.</p><p>Resources:</p><ol><li><a href="https://arxiv.org/abs/2111.06377">paper</a></li><li><a href="https://www.reddit.com/r/LocalLLaMA/comments/14wbmio/gpt4_details_leaked/">GPT-4</a></li><li><a href="https://medium.com/mlearning-ai/an-image-is-worth-16x16-words-transformers-for-image-recognition-at-scale-51f3561a9f96">An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale | by Souvik Mandal | MLearning.ai | Medium</a></li><li><a href="https://medium.com/mlearning-ai/demystifying-the-attention-logic-of-transformers-unraveling-the-intuition-and-implementation-fa6e3cf05a79">Demystifying the Attention Logic of Transformers: Unraveling the Intuition and Implementation by visualization | by Souvik Mandal | MLearning.ai | Jun, 2023 | Medium</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122a75b54470" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/masked-autoencoders-are-scalable-vision-learners-122a75b54470">Masked Autoencoders Are Scalable Vision Learners</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>