<?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 Andrei-Cristian Rad on Medium]]></title>
        <description><![CDATA[Stories by Andrei-Cristian Rad on Medium]]></description>
        <link>https://medium.com/@radandreicristian?source=rss-396666f53074------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eT2zhzQziSvmVIoVG1dtHw.jpeg</url>
            <title>Stories by Andrei-Cristian Rad on Medium</title>
            <link>https://medium.com/@radandreicristian?source=rss-396666f53074------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:28:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@radandreicristian/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[what to do if training on JFT-300M is not an option? convnet teachers to the rescue.]]></title>
            <link>https://radandreicristian.medium.com/what-to-do-if-training-on-jft-300m-is-not-an-option-convnet-teachers-to-the-rescue-104a7bf7dccb?source=rss-396666f53074------2</link>
            <guid isPermaLink="false">https://medium.com/p/104a7bf7dccb</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Andrei-Cristian Rad]]></dc:creator>
            <pubDate>Sun, 03 Jan 2021 14:21:18 GMT</pubDate>
            <atom:updated>2021-01-12T12:05:40.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>What if you don’t have a dataset of 300M images to train your vision transformer on? get some help from the good ol’ CNNs via distillation!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kmd6O5v98vF8j6eH" /><figcaption>Photo by <a href="https://unsplash.com/@selina_bub?utm_source=medium&amp;utm_medium=referral">Selina Bubendorfer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It seems that the title of the Transformer architecture <a href="https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf">paper</a> is resonating more and more through our minds recently. Is <em>attention </em>really all we need? For some years now, it seems clear that the NLP community believes so, with transformers being the key component of SotA architectures, in language modeling, translation or summarization tasks.</p><p>A few months ago, a <strong>transformer</strong>-based <a href="https://medium.com/analytics-vidhya/understanding-the-vision-transformer-and-counting-its-parameters-988a4ea2b8f3">architecture</a> for<strong> image classification</strong>, proposed in this <a href="https://openreview.net/forum?id=YicbFdNTTy">paper</a> by Google, has outperformed SotA CNN-based architectures. One of the inconveniences of this architecture is the (understandably) large number of parameters and resources required to train.</p><p>In a fresh <a href="https://arxiv.org/pdf/2012.12877.pdf">paper</a>, Facebook has shown that a large number of parameters and the obnoxious training resources (the unavailable JFT-300M ImageNet and the TPU grid that was used) are sufficient, yet not necessary for a good performance.</p><p>Summarily, this paper aims to reduce the total number of parameters and required training resources by compensating it with an additional <strong>distiller token</strong> and a <strong>better training strategy</strong>. The DeiT-B has the same number of parameters as ViT-B, but the two other models go towards a lower number of parameters (S-small, Ti-tiny), as opposed to the BERT-inspired ViT parameter models (L-large, H-huge). The pre-training is done using 224x224x3 RGB images, and the fine-tuning is done using 384x384x3 RGB images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*XBk7FMAArjx1OpbCQLHu9A.png" /><figcaption>DeiT models</figcaption></figure><p>The architecture of DeiT is identical to the one of the ViT, where an image is first decomposed and projected into <em>patch tokens</em>, then ran through layers of transformer encoders (which are virtually a sequence of self-attention and MLPs, as depicted in both papaers). The difference is in the newly introduced distillation token, which results in an additional component to the global loss function, based on which the weights are updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*oQGj5BilL6XeTdgXbfbnnQ.png" /><figcaption>Model architecture from the paper</figcaption></figure><p>The distillation token aims to minimize the difference between the prediction of the ViT — the <em>student </em>network — and the predictions of a SotA CNN — the <em>teacher </em>network. As the authors note, using a convolutional network as a <em>teacher </em>network helps to address the problem of inductive bias in transformer networks.</p><p>Compensating for this bias is important because transformers lack intuitive priors about the structure of the data. Oppositely, convolutional and recurrent networks have a high inductive bias, as they are aware of an “ordering rule” within the input tensor or sequence.</p><p>No inductive bias also implies that it has to look at more data to learn. Transferring part of the bias from a CNN teacher to a transformer student should, in theory, reduce the required training time, especially for pre-training.</p><p>The global loss of the DeiT architecture is a weighted sum between the cross-entropy loss from the ViT and another loss based on the distiller token.</p><p>The first variant of the loss function is inspired by the original formulae proposed in the distiller <a href="https://arxiv.org/abs/1503.02531">paper</a> and makes use of the Kullback-Leibler divergence to express the loss caused by the difference between the distributions predicted by the <em>student </em>and the <em>teacher.</em></p><p>The other variant, proposed by the authors is a simplified version, where the teacher prediction is treated the same way as the ground truth, and a cross-entropy loss function is used instead of the KL divergence. Moreover, both components are treated with equal importance, encouraging the <em>student </em>to learn equally from both sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*13sZKxq4OLmBr6ffPhG6kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*QMj6-b7wc2sYbvr6AkqqRw.png" /></figure><ul><li>λ — Balancing coefficient. Adjusts which of the two composing loss functions is more important for the overall loss.</li><li>τ — Distiller “temperature”. Adjusts how <em>soft </em>the labels are. A higher value results in a softer probability distribution of the labels. A value of 1 equals a hard distillation.</li><li>Lce and KL — The cross-entropy and the Kullback-Leibler losses.</li><li>ψ — The softmax function.</li></ul><p>Authors note that the two tokens converge towards different values, but become more and more similar with respect to the number of transformer layers. It is important to note that they do not converge further than 0.93, pointing out that there is certainly some information to be learned from both sources.</p><p>Adding the distillation token and using the hard-distillation loss, the authors reported an ImageNet top-1 accuracy of <strong>83.4% </strong>for pretraining and <strong>84.2% </strong>for fine-tuning.</p><p>Although ViT is being glorified for outperforming convolutional networks, this only happens when pre-training on large datasets, like the publically unavailable JFT-300M.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*94lC5GfN0XuGanWFVAftaA.png" /><figcaption>From the paper “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”</figcaption></figure><p>When training on smaller datasets, ViT has worse performances than the top CNNs. On the other hand, the curve of the DeiT model closely approaches the one of EfficientNet, when looking at the ImageNet1k dataset. It is clear that adding distillation (red line) has a positive impact on the accuracy while having a trivially low impact on the throughput (when compared to the model without distillation — the maroon line).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*yYmy8Jywn__B6K1rYWLs0A.png" /><figcaption>From the paper “Training data-efficient image transformers &amp; distillation through attention”</figcaption></figure><p>In order to compensate for a reduced training dataset, authors make use of data augmentation. Moreover, various optimizers and regularization techniques were tried, in order to obtain the best set of hyper-parameters, to which transformers are usually highly sensitive. The optimal configuration was obtained by using an ablation study, which can be found in the DeiT paper.</p><p>In conclusion, the DeiT setup goes around ViT’s “shortcut” (yes, pun intended) of pre-training on the JFT-300M dataset and provides more realistic and available alternatives to obtaining SotA performance on ImageNet using almost the same architecture.</p><p>A great video resource for the DeiT paper is available <a href="https://www.youtube.com/watch?v=-FbV2KgRM8A">here</a>.</p><h3>References:</h3><p>[1] H. Touvron et. al., <a href="https://arxiv.org/pdf/2012.12877.pdf">Training data-efficient image transformers &amp; distillation through attention</a> (2020)<br>[2] A. Dostovitskiy et. al., <a href="https://arxiv.org/pdf/2010.11929.pdf">An Image Is Worth 16x16 Words: Transformers for Image Recognition at Scale</a> (2020) ICLR 2021 (under review)<br>[3] G. Hinton et. al., <a href="https://arxiv.org/pdf/1503.02531.pdf">Distilling the Knowledge in a Neural Network</a> (2014), NIPS 2014 Deep Learning Workshop <br>[4] S. Abnar et. al., <a href="https://arxiv.org/pdf/2006.00555.pdf">Transferring inductive biases through knowledge distillation</a> (2020)<br>[5] A. Vaswani et. al., <a href="https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf">Attention is All You Need</a> (2017), Proceedings of NIPS2017<br>[6] J. Devlin et. al., <a href="https://arxiv.org/pdf/1810.04805.pdf">BERT: Pre-training of deep bidirectional transformers for language understanding</a> (2018)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=104a7bf7dccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Vision Transformer and Counting Its Parameters]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-the-vision-transformer-and-counting-its-parameters-988a4ea2b8f3?source=rss-396666f53074------2</link>
            <guid isPermaLink="false">https://medium.com/p/988a4ea2b8f3</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Andrei-Cristian Rad]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 08:27:37 GMT</pubDate>
            <atom:updated>2021-01-12T10:02:07.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pxLTgDV89uNmGhGZ" /><figcaption>Photo by <a href="https://unsplash.com/@simonmigaj?utm_source=medium&amp;utm_medium=referral">Simon Migaj</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, I will share my understanding of the Vision Transformer architecture. All the drawings in this post are original content, based on the knowledge from the paper and other tutorials which will be referred to where appropriate.</p><p><strong>Transformer architectures</strong> have been a major breakthrough in Natural Language Processing (NLP) tasks since being proposed in 2016. Google’s <a href="https://arxiv.org/pdf/1810.04805.pdf">BERT</a> and Open AI’s <a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">GPT-2</a> / <a href="https://arxiv.org/abs/2005.14165">GPT-3</a> architectures have been the state-of-the-art solutions for various tasks, including language modeling, text summarization, and question answering.</p><p>The aim was to prove that the recurrent neural networks can be completely replaced, and solutions can be developed using only attention mechanisms — hence the pun in the <a href="https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf">Transformer paper</a> title. Detailing the way the original Transformer architecture operates is beyond the scope of this article, but there are plenty of solid <a href="https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html">tutorials</a> and <a href="https://www.youtube.com/watch?v=4Bdc55j80l8">videos</a> that explain the way it works.</p><p>The focus of this article is presenting an overview of the Vision Transformer (ViT) architecture, proposed in a new <a href="https://openreview.net/pdf?id=YicbFdNTTy">paper</a> for Google, submitted for review for ICLR 2021. Although there were previous attempts at using attention mechanisms for computer vision tasks (<a href="https://papers.nips.cc/paper/2019/file/3416a75f4cea9109507cacd8e2f2aefc-Paper.pdf">this</a>, <a href="https://arxiv.org/pdf/1904.10509.pdf">this</a>, or <a href="https://arxiv.org/pdf/1906.02634.pdf">this</a>), ViT is the most promising architecture, both from the scalability and the efficiency point of view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*etrfupovfQO4JbBm26Y_cw.png" /><figcaption>Vision Trnasformer Architecutre</figcaption></figure><p>The architecture contains 3 main components.</p><ol><li>Patch embedding.</li><li>Feature extraction via stacked transformer encoders.</li><li>The classification head.</li></ol><p>Each component will be detailed in the next paragraphs, with the focus on the transformations and the trainable parameters. The first dimension of some tensors is <strong><em>b</em></strong>, which represents the batch size, but this and the broadcasting operations will be ignored in the comments for simplicity.</p><h3>Patch Embedding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXQ_lZn9-4X-UGkagsO0Ng.png" /><figcaption>Patch Embedding</figcaption></figure><p>In the first step, an input image of shape <strong><em>(height, width, channels)</em></strong> is embedded into a feature vector of shape <strong><em>(n+1, d)</em></strong><em>, </em>following a sequence of transformations. This corresponds to equation (1) from the paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqOzUEXMYvp7groZvs2Gtg.png" /></figure><ol><li>The image is split into <em>n </em>square patches of shape<strong> <em>(p, p, c)</em></strong>,<em> </em>where<em> p</em> is a pre-defined parameter, in raster order (left to right, up to down).</li><li>The patches are flattened, resulting in<strong> <em>n</em></strong> line vectors of shape <strong><em>(1, p²*c)</em></strong><em>.</em></li><li>The flattened patches are multiplied with a <strong>trainable </strong>embedding tensor of shape <strong>(p²*c, d)</strong>, which learns to linearly project each flat patch to dimension <strong><em>d</em></strong>. This dimension <em>d </em>is constant in the architecture and is used in most of the components. The result is <strong><em>n</em></strong><em> </em>embedded patches of shape <strong><em>(1, d).</em></strong></li><li>A learnable <em>[cls] </em>token of shape<strong> <em>(1, d)</em></strong> is prepended to the sequence of patch embeddings. The idea of this token is from the BERT paper, where only the last representation corresponding to this token (output of transformer L) is fed through the classification layers. Intuitively, this represents an aggregate of the representations of the patches.</li><li>A <strong>trainable </strong>positional embedding tensor, <strong>Eₚₒₛ</strong>, with the same shape,<strong> <em>(n+1, d)</em></strong><em>, </em>is added to the concatenated sequence of projections. This tensor learns 1D positional information for each of the patches, in order to add a spatial representation of each patch within the sequence.</li></ol><p>The result, z₀, is the first input to the stacked transformer encoders. The L stacked encoders represent the second component of the architecture. Each transformer takes as input features represented as an <strong><em>(n+1, d)</em></strong><em> </em>tensor, and produces an output of the same dimension.</p><h3>Transformer Encoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cELt46MSsAuwk6PzvDstUQ.png" /><figcaption>Transformer encoder</figcaption></figure><p>In the second step, the network learns more abstract features from the embedded patches, using a stack of L transformer encoders. This corresponds to equations (2) and (3) from the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*Ldq8m57q82BMf4yPg_nsYw.png" /></figure><p>The encoder component contains a multi-headed attention (MHA) mechanism and a 2-layer MLP, with layer normalization and residual connections in between.</p><p>Layer normalization helps to stabilize hidden state dynamics and to reduce the training time. It is done by scaling with the mean and standard deviation for each training example (as opposed to the batch norm where this is done per feature). The resulting features are multiplied with a scaling factor and added to a shifting factor, both learnable during training.</p><p>Residual connections offer gradients alternative paths, in order to solve the problem of vanishing gradients in very deep architectures.</p><p>The trainable weights in this component lie inside the MHA mechanism and the MLP weights. Since the MLP has 2 layers (hidden and output), there will be two weight matrices:</p><ul><li>Wₕ of shape <strong><em>(d, dₘₗₚ)</em></strong></li><li>Wₒ of shape <strong><em>(dₘₗₚ, d)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUx39Zt-DkLMQ7ts46kk8A.png" /><figcaption>The attention mechanism</figcaption></figure><p>The multi-head attention (MHA) step, included in each of the L stacked transformers, corresponds to equations (5), (6), (7), and (8) from the paper’s appendix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*tJC6RfUN2PJmWKBLCBJz0Q.png" /></figure><p>The hidden state from the previous encoder is split into K heads, resulting in K feature tensors of shape <strong>(n, dₕ)</strong>. From the multi-head attention intuition, multiple heads allow the mechanism to learn from different aspects of the abstract representation.</p><p>Each is multiplied with 3 trainable matrices Qi, Ki, Vi, of shape <strong>(dₕ, dₕ). </strong>This is equivalent to equation 5, as in U=<strong>(d, 3dₕ)</strong> there are exactly 3 matrices for each head, each of shape <strong>(dₕ, dₕ)</strong>.</p><p>Qi, Ki, and Vi represent the projection of the input in 3 sub-spaces. We can think of each line in Q as a learned projection of the patch we are interested in, and lines in K as other patches we compare Q to. V and K are learned to express importance, or weights, for features in V to compute the final “attention”.</p><p>Following, on each head, the scaled dot-product attention tensor <strong>(A)</strong> is computed as a softmax of the multiplication between the <strong>Ki </strong>and <strong>Qi </strong>matrices, normalized with the square root of the dimension of the head. The <em>i-</em>th row in this matrix is a probability distribution function of the attention for query <em>i</em>, meaning to keys of which other patches is the query of patch <em>i</em> most similar to.</p><p>The self-attention is the product between <strong>A </strong>and <strong>v</strong>, which has the shape <strong><em>(n+1, dₕ). </em></strong>The element at row <em>i</em> and column <em>j </em>is the weighted average of feature j by the pdf on line <em>i</em> in A.</p><p>The self-attention matrices are concatenated on the second dimension, resulting in an <strong><em>(n+1, d) </em></strong>tensor, which is then run through a single linear layer, by effectively multiplying it with a <strong><em>(d, d)</em></strong> <strong>trainable </strong>tensor. This linear layer is very important, as it allows features to be learned as aggregates from all the heads.</p><h3>Classification Head</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmFosjhGmyEVBrquRm91pA.png" /><figcaption>Classification Head</figcaption></figure><p>As stated previously, only the last representation of the <strong><em>[cls] </em></strong>token is used in the classification head. For pre-training, a 2-layer MLP is used, therefore there are two weight matrices — Wₕ of shape <strong><em>(d, dₘₗₚ)</em></strong> and Wₒ of shape <strong><em>(dₘₗₚ, d)</em></strong>. For fine-tuning, a single linear layer is used, therefore there is only a single tensor, of shape <strong><em>(d, n_cls)</em></strong><em>.</em><strong><em> </em></strong>In each case, the final output of the network is a vector of shape <strong><em>(1, n_cls)</em></strong>,<strong><em> </em></strong>containing the probabilities associated with each of the <strong><em>n_cls </em></strong>classes.</p><h3>Trainable Parameters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*wiMIbC1lNjxZGpD3G52HkQ.png" /><figcaption>Vision Transformer Paramteres [1]</figcaption></figure><p>Let us take the ViT-Base architecture and calculate the number of parameters. trainable tensor in the architecture.</p><p>In the patch embedding step, the two embedding matrices account for 786.432 parameters.</p><pre>p²*c*d + (n+1)*d = 256*3*768 + 256*768 = 786.432</pre><p>In the encoder stack, there are a total of 84.943.656 parameters.</p><pre>L*(k*d*3*dₕ + d*d + d*<em>dₘₗₚ + dₘₗₚ*d</em>) <br>= 12*(12*768*3*64 + 768*768 + 2*768*3072) <br>= 12*(1.769.472 + 589.824 + 4.718.592) <br>= 12*589.824(3+1+8)<br>= 12*589.824*12<br>= 84.934.656</pre><p>For fine-tuning (on ImageNet, for instance), there are other 768.000 parameters.</p><pre>d*ncls = 768 * 1000 = 768.000</pre><p>Adding those, we obtain around 86M, as listed in the paper.</p><h3>Results</h3><p>The ViT architecture has obtained state-of-the-art performance on ImageNet, when pre-trained on JFT-300M. However, the authors noted that the performance decreases drastically when using small datasets for pre-training, and that larger models are better suited for larger datasets. This issue most likely arises because of the lack of inductive bias in transformer networks. They are able to process any sequence, without knowing its order relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*6E0sMokCCygjtdAyvbe-5Q.png" /><figcaption>Accuracy vs. Pre-training Dataset [1]</figcaption></figure><h3>Conclusions</h3><p>For me, being able to visualize the transformations and the flow in this architecture has been of great help. Hopefully, it is the same in your case. Cheers!</p><h3>References</h3><p>[1] A. Dostovitskiy et. al., <a href="https://arxiv.org/pdf/2010.11929.pdf">An Image Is Worth 16x16 Words: Transformers for Image Recognition at Scale</a> (2020) ICLR 2021 (under review)<br>[2] A. Vaswani et. al., <a href="https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf">Attention is All You Need</a> (2017), Proceedings of NIPS2017<br>[3] J. Devlin et. al., <a href="https://arxiv.org/pdf/1810.04805.pdf">BERT: Pre-training of deep bidirectional transformers for language understanding</a> (2018)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=988a4ea2b8f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-the-vision-transformer-and-counting-its-parameters-988a4ea2b8f3">Understanding the Vision Transformer and Counting Its Parameters</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>