<?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 Nilesh Vijayrania on Medium]]></title>
        <description><![CDATA[Stories by Nilesh Vijayrania on Medium]]></description>
        <link>https://medium.com/@nilesh0109?source=rss-ae2c3b0d24ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qrSOi3ypJHuFCUUOOk7UmA.jpeg</url>
            <title>Stories by Nilesh Vijayrania on Medium</title>
            <link>https://medium.com/@nilesh0109?source=rss-ae2c3b0d24ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:06:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nilesh0109/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[Non-Linear Augmentations For Deep Learning]]></title>
            <link>https://medium.com/data-science/non-linear-augmentations-for-deep-leaning-4ba99baaaaca?source=rss-ae2c3b0d24ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ba99baaaaca</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[fisheye]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nilesh Vijayrania]]></dc:creator>
            <pubDate>Sat, 13 Mar 2021 20:23:36 GMT</pubDate>
            <atom:updated>2021-03-14T06:44:21.225Z</atom:updated>
            <content:encoded><![CDATA[<h4>Augment your data with fisheye view in pytorch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxVP_n2_easpp98OrSE7jA.jpeg" /><figcaption>Fisheye Effect. Image from <a href="https://unsplash.com/@wilhelmgunkel">wilhelmgunkel</a> on unsplash</figcaption></figure><p>In recent years, deep learning has made tremendous progress in developing systems that can learn from carefully labelled data. But, the deep learning models are very data-hungry and requires a massive amount of labels for training and getting a huge number of labels is challenging depending upon the nature of the labels. An alternative to manually labelling more data is to use data augmentations on the existing dataset to automatically generate new labelled data for the model and extend the existing training dataset. Some of the popular data augmentations for image data are flipping, cropping, rotation, scaling, shearing, color channel distortion, blurring etc. In this post, I am covering two augmentations for image data that are not very popular in deep learning but may be useful for extending your dataset.</p><p>Augmentations such as rotation, shearing, scaling are all affine transformations that transform the image linearly. In contrast to the linear transformations, the following two transformations which I am covering in this post are non-linear.</p><ul><li>Fisheye Transformation</li><li>Horizontal Wave Transformation</li></ul><h3>Fisheye Transformation</h3><p>Fisheye is a non-linear transformation which for a given center pixel, distorts the pixels in the image based on the distance from the given center pixel. Essentially, pixels closer to the center receives a lot less distortion compared to the pixels which are far away. The fisheye transformation takes two parameters, center and the distortion factor. The center defines the center of the transformation and the distortion factor controls the amount of distortion used for the transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*MDKyVXGdmvT0ZQ6IvroOuQ.png" /><figcaption><strong>Fisheye Transformation:</strong> Result of Fisheye Transformation(right) when applied on a checkerboard image(left). Fisheye transformation distorts the image pixels weighted by the euclidean distance from the given center of the transformation.(Image By Author)</figcaption></figure><p>The figure above shows the effect of fisheye transformation over a checkerboard image with the center focused around the midpoint of the image.</p><p>Mathematically, the fisheye transformation function for a given pixel (x,y) is given by the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*yX-UeYuoGX_4UEakgMm6kA.png" /></figure><p>Where &lt;c_x,c_y&gt; represents the center of the transformation and “d” represents the distortion factor.&lt;T(x),T(y)&gt; are transformed values of pixel &lt;x,y&gt;.</p><p>Please note that for all the input image pixels locations are normalized into a grid such that the top-left pixel represents the location &lt;−1,−1&gt; and the bottom-right pixel represents the location&lt;1,1&gt;.&lt;0,0&gt; represents the exact center pixel of the image. So the range of x-axis and y-axis is from -1 to 1. For the above image, the distortion factor(d) is set to 0.25 and the center is randomly sampled from the interval [-0.5, 0.5].</p><h3>Horizontal Wave Transformation</h3><p>Horizontal wave transformation is another non-linear transformation that distorts the pixels in the shape of the horizontal cosine wave of a given amplitude and frequency. It takes two parameters, amplitude and frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*x7ytLw_yErlHQQCbOTfDMA.png" /><figcaption><strong>Horizontal Wave Transformation:</strong> Result(right) of Horizontal WaveTransformation applied on a checkerboard image(left). Horizontal wave transformation transforms the given image in the shape of the cosine wave of given amplitude and frequency.(Image By Author)</figcaption></figure><p>The figure above shows the effect of horizontal wave transformation over a checkerboard image.</p><p>Mathematically, the horizontal wave transformation function for a given pixel (x,y) is given by the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*3yCDPcn6bR9I6O54jXOKag.png" /></figure><p>Where “a” is the given amplitude of the cosine wave and “f” is the pre-specified frequency.&lt;T(x), T(y)&gt; are transformed values of pixel &lt;x, y&gt;. Note that, the horizontal wave does not cause any distortion to the x coordinate of the pixel. Similar to the fisheye transformation example, the range of x and y is from -1 to 1. The value of “a” is 0.2 and “f” is 20 for the example above.</p><h3>Implementation</h3><p>In this section, I will cover the vectorized implementation of the two transformations in PyTorch. I prefer vectorization because it computes the transformation really fast than the expensive <em>for</em> loops. Let’s start with the fisheye transformation first.</p><pre>def get_of_fisheye(H, W, center, magnitude):  <br>  xx, yy = torch.linspace(-1, 1, W), torch.linspace(-1, 1, H)  <br>  gridy, gridx  = torch.meshgrid(yy, xx). //create identity grid<br>  grid = torch.stack([gridx, gridy], dim=-1)  <br>  d = center - grid      //calculate the distance(cx - x, cy - y)<br>  d_sum = torch.sqrt((d**2).sum(axis=-1)) //sqrt((cx-x)^2+(cy-y)^2)<br>  grid += d * d_sum.unsqueeze(-1) * magnitude <br>  return grid.unsqueeze(0)</pre><pre>fisheye_grid = get_of_fisheye(H, W, torch.tensor([0,0]), 0.4)<br>fisheye_output = F.grid_sample(imgs, fisheye_grid)</pre><p>The code above performs the following 4 steps to transform the image.</p><ol><li>Create an identity grid of shape (H, W, 2 ) with x and y ranging from-1 to 1(line 2–4).</li><li>Calculate the distance of each pixel(dist) in the grid to the given center pixel(line 5).</li><li>Compute the Euclidean distance(d) of each pixel with the center pixel(line 6).</li><li>Compute dist * d * magnitude and add to the original grid(line 7).</li><li>Transform the image using the grid_sample function of PyTorch(line 9–10).</li></ol><p>Similarly, the following code transforms the image using horizontal wave transformation.</p><pre>def get_of_horizontalwave(H, W, center, magnitude):  <br>  xx, yy = torch.linspace(-1, 1, W), torch.linspace(-1, 1, H)  <br>  gridy, gridx  = torch.meshgrid(yy, xx). //create identity grid<br>  grid = torch.stack([gridx, gridy], dim=-1)  <br>  dy = amplitude * torch.cos(freq * grid[:,:,0]) //calculate dy<br>  grid[:,:,1] += dy<br>  return grid.unsqueeze(0)</pre><pre>hwave_grid = get_of_horizontalwave(H, W, 10, 0.1)<br>hwave_output = F.grid_sample(imgs, hwave_grid)</pre><p>For convenience, I have compiled the whole code in the following gist which covers both the augmentations and applies them on a checkerboard image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f1358ef6395fb0e67550f043e9cbf19/href">https://medium.com/media/6f1358ef6395fb0e67550f043e9cbf19/href</a></iframe><h3>Summary</h3><ul><li>This post introduces two non-linear augmentations namely fisheye and horizontal wave transformation for augmenting the image data.</li><li>Fisheye is a non-linear transformation that transforms the pixel based on the euclidean distance from the fixed center pixel.</li><li>Horizontal Wave transformation is another non-linear transformation that distorts the pixels in the shape of the horizontal cosine wave.</li><li>The vectorized implementation of both the augmentation is included in the post. Link: <a href="https://gist.github.com/nilesh0109/f98eed779844c6b570740d5ef78868a3">https://gist.github.com/nilesh0109/f98eed779844c6b570740d5ef78868a3</a></li></ul><p>That was a small introductory post for newer augmentations in deep learning. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ba99baaaaca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/non-linear-augmentations-for-deep-leaning-4ba99baaaaca">Non-Linear Augmentations For Deep Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands on Review: BYOL(Bootstrap Your Own Latent)]]></title>
            <link>https://medium.com/data-science/hands-on-review-byol-bootstrap-your-own-latent-67e4c5744e1b?source=rss-ae2c3b0d24ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/67e4c5744e1b</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[self-supervised-learning]]></category>
            <category><![CDATA[representation-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[semantic-segmentation]]></category>
            <dc:creator><![CDATA[Nilesh Vijayrania]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 14:29:29 GMT</pubDate>
            <atom:updated>2021-01-02T15:49:25.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>First Hand Review: BYOL(Bootstrap Your Own Latent)</h3><p>Lately, Self-supervised learning methods have become the cornerstone for unsupervised visual representation learning. One such method <strong>B</strong>ootstrap <strong>Y</strong>our <strong>O</strong>wn <strong>L</strong>atent(BYOL) which is introduced recently is reviewed in this post. I have already covered other interesting self-supervised learning methods based on contrastive learning that came before BYOL such as SimCLR, MoCo, etc. in another post thoroughly and should be considered for understanding the fundamentals of this post. Please find them <a href="https://towardsdatascience.com/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd">here</a>.</p><p>Unlike other contrastive learning methods, BYOL achieves state-of-the-art performance without using any negative samples. Fundamentally, like a siamese network, BYOL uses two same encoder networks referred to as online and target network for obtaining representations and reduces the contrastive loss between the two representations.</p><p><strong>Network Architecture</strong></p><p>The architecture of the BYOL network is shown below. θ and ϵ represent online and target network parameters respectively and f_θ and f_ϵ are online and target encoders respectively. Target network weights are slowly moving average of the online network weights i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*nmEvSQloYDAZlU0YD-aj6A.png" /></figure><p>Idea is to train the online network f_θ in the first step and use those learned representations for downstream tasks and fine-tune them further using labelled data in the second step. The first step i.e. BYOL could be summarized in the following 5 straightforward steps.</p><ol><li>Given an input image x, two views of the same image v and v’ are generated by applying two random augmentations to x.</li><li>Given v and v’ to online and target encoders in order, vector representations y_θ and y’_ϵ are obtained.</li><li>Now, these representations are projected to another subspace z. These projected representations are indicated by z_θ and z’_ϵ in the image below.</li><li>Since the target network is the slow moving average of the online network, the online representations should be predictive of the target representations, i.e. z_θ should predict z’_ϵ and hence another predictor(q_θ) is put on top of z_θ.</li><li>Contrastive loss is reduced between &lt;q_θ(z_θ), z’_ϵ&gt;.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGCoNeLy-i7zz0LqGPOtSw.png" /><figcaption>Image Credits: <a href="https://arxiv.org/abs/2006.07733">Grill, Jean-Bastien, et al. “Bootstrap your own latent: A new approach to self-supervised learning.” <em>arXiv preprint arXiv:2006.07733</em> (2020).</a></figcaption></figure><p>Mathematically, Contrastive loss is computed as mean squared error between q_θ(z_θ) and z’_ϵ. Before computing the mean squared error, the labels z’_ϵ and targets q_θ(z_θ) are L2-normalized. The equation is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*NlGGtDA-wSW-oxbelCxQxg.png" /><figcaption>contrastive loss</figcaption></figure><p>z`_ϵ bar , is the L2 normalized z`_ϵ and q_θ(z_θ) bar is L2 normalized q_θ(z_θ).</p><p><strong>Why BYOL?</strong></p><p>The First question is, why and where one should use BYOL?</p><p>BYOL method helps in learning useful representations for a variety of downstream computer vision tasks such as object recognition, object detection, semantic segmentation, etc. Once these representations are learned in BYOL way, they could be used with any standard object classification model such as Resnet, VGGnet, or any semantic segmentation network such as FCN8s, deeplabv3, etc or any other task-specific network and it gets to a better result than training these networks from scratch. This is the major reason behind the popularity of BYOL. The below graph shows that the BYOL representations learned using Imagenet images beats all previous unsupervised learning methods and achieves classification accuracy of 74.1% with Resnet50 under linear evaluation protocol. In case you are not sure about Linear evaluation protocol, it is described in my last <a href="https://towardsdatascience.com/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd">post</a> in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*IcdCLjvGO4ksVnWWvHx92g.png" /><figcaption>BYOL results under linear evaluation protocol. Image Credits: <a href="https://arxiv.org/abs/2006.07733">Grill, Jean-Bastien</a></figcaption></figure><p>The power of BYOL is leveraged more efficiently in dense prediction tasks where generally only a few labels are available due to the complex and costly task of data labelling. When BYOL is used for one such task namely semantic segmentation using cityscapes dataset with FCN8s network along with Resnet50 backbone, it outperforms the version of the network trained from scratch i.e. with random weights. The below graph compares the performance of 3 main networks on the cityscapes dataset.</p><ul><li>Resnet50 trained from Imagenet weights and fine-tuned using 3k cityscapes labelled images(dotted red line).</li><li>Resnet50 trained from random weights using 3k cityscapes images only(dotted black line).</li><li>Resnet50 pre-trained on BYOL using 20k unlabelled cityscapes images, then fine-tuned using 3k cityscapes image(solid blue line).</li></ul><p>The below graph clearly shows that the BYOL significantly helps in learning useful representations for this task and hints that it should be considered as a pre-training step for other computer vision industrial applications where Imagenet weights could not be used due to licensing regulations and lots of unlabelled data is present for unsupervised training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwgQWhD-JpcHCQyMbP6yQQ.png" /><figcaption>BYOL gain(Graph by author)</figcaption></figure><p><strong>Implementation Details</strong></p><p>For Image augmentations, the following set of augmentations are used. First, a random crop is selected from the image and resized to 224x224. Then random horizontal flip is applied, followed by random color distortion and random grayscale conversion. Random color distortion consists of a random sequence of brightness, contrast, saturation, hue adjustments. The following code snippet implements the BYOL augmentation pipeline in PyTorch..</p><pre>from torchvision import transforms as tfms</pre><pre>byol_tfms = tfms.Compose([<br>    tfms.RandomResizedCrop(size=512, scale=(0.3, 1)),<br>    tfms.RandomHorizontalFlip(),<br>    tfms.ToPILImage(),<br>    tfms.RandomApply([<br>            tfms.ColorJitter(0.4, 0.4, 0.4, 0.1)<br>    ], p=0.8),<br>   tfms.RandomGrayscale(p=0.2),<br>   tfms.ToTensor()</pre><pre>])</pre><p>In the actual BYOL implementations, Resnet50 is used as an encoder network. For the projection MLP, the 2048 dimensional feature vector is projected onto 4096-dimensional vector space first with Batch norm followed by ReLU non-linear activation and then it is reduced to the 256-dimensional feature vector. The same architecture is used for the predictor network. Below PyTorch snippet implements the Resnet50 based BYOL network, but it could also be used in conjunction with any arbitrary encoder network such as VGG, InceptionNet, etc. without any significant change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/471734f412abd9238cd5ae825b649e8e/href">https://medium.com/media/471734f412abd9238cd5ae825b649e8e/href</a></iframe><p><strong>Why BYOL works the way it works</strong></p><p>Another interesting fact is, although a collapsed solution exists for the task curated for BYOL, the model avoids it safely and the actual reason for it is unknown. Collapsed solution means, the model might get away by learning a constant vector for any view of any image and gets to zero loss, but it does not happen.</p><p>The authors of the original paper[1], conjecture that it might be due to the complex network(Deep Resnet with skip connections) used in the backbone, the model never gets to the straightforward collapsed solution. But in another recent paper SimSiam[2] Chen, Xineli and He, found out it is not the complex network architecture but the “stop-gradient” operation that makes the model to avoid the collapsed representations. “stop-gradient” means that the network never gets to update the weights of the target network directly through gradients and hence never gets to the collapsed solution. They also show that there isn’t any need for a momentum target network to avoid collapsed representation but it certainly gives better representations for downstream tasks if used.</p><p>That was the quick summary of BYOL along with code in PyTorch. For full implementation, this GitHub repo <a href="https://github.com/nilesh0109/self-supervised-sem-seg">https://github.com/nilesh0109/self-supervised-sem-seg</a> could be referred.</p><p>Below is the list of references used in this post.</p><ol><li>Grill, Jean-Bastien, et al. “Bootstrap your own latent: A new approach to self-supervised learning.” <em>arXiv preprint arXiv:2006.07733</em> (2020).</li><li>Chen, Xinlei, and Kaiming He. “Exploring Simple Siamese Representation Learning.” <em>arXiv preprint arXiv:2011.10566</em> (2020).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67e4c5744e1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/hands-on-review-byol-bootstrap-your-own-latent-67e4c5744e1b">Hands on Review: BYOL(Bootstrap Your Own Latent)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Neural Network Training In Pytorch]]></title>
            <link>https://medium.com/data-science/distributed-neural-network-training-in-pytorch-5e766e2a9e62?source=rss-ae2c3b0d24ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e766e2a9e62</guid>
            <category><![CDATA[distributeddataparallel]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[distributed-training]]></category>
            <dc:creator><![CDATA[Nilesh Vijayrania]]></dc:creator>
            <pubDate>Fri, 25 Dec 2020 07:43:15 GMT</pubDate>
            <atom:updated>2020-12-27T17:40:47.660Z</atom:updated>
            <content:encoded><![CDATA[<p>With several advancements in Deep Learning, complex networks such as giant transformer networks, wider and deeper Resnets, etc. have evolved which keeps a larger memory footprint. More often than not, while training these networks, deep learning practitioners need to use multiple GPUs to train them efficiently. In this post, I am going to walk you through, how distributed neural network training could be set up over a GPU cluster using PyTorch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3CWKINHKijm2uGPcQcJtQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nanadua11">Nana Dua</a> on<a href="https://unsplash.com/photos/nqCEPrvnLKQ"> Unsplash</a></figcaption></figure><p>Usually, distributed training comes into the picture in two use-cases.</p><ol><li><strong>Model Splitting across GPUs:</strong> When the model is so large that it cannot fit into a single GPU’s memory, you need to split parts of the model across different GPUs.</li><li><strong>Batch Splitting</strong> <strong>across GPUs</strong>.When the mini-batch is so large that it cannot fit into a single GPU’s memory, you need to split the mini-batch across different GPUs.</li></ol><h3><strong>Model Splitting across GPUs:</strong></h3><p>Splitting the model across GPUs is straightforward and doesn’t require much code change. While setting up the network itself, parts of the model could be moved to specific GPUs. Afterwards while forward propagating the data through the network, the data needs to be moved to the corresponding GPU as well. Below is the PyTorch snippet doing the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68423af7bf12a3f59c2b61653465679d/href">https://medium.com/media/68423af7bf12a3f59c2b61653465679d/href</a></iframe><h3>Batch Splitting across GPUs:</h3><p>There are 3 ways to split batch across GPUs.</p><ol><li>Accumulating Gradients</li><li>Using nn.DataParallel</li><li>Using nn.DistributedDataParallel</li></ol><h3><strong>Accumulating Gradients</strong></h3><p>The easiest way to split batches across GPUs is to <strong>accumulate gradients</strong>. Suppose, the batch size that we want to train with is 256, but only 32 batch size could fit into one GPU memory. We could perform 8(=256/32) gradient descend iterations without performing the optimization step and keep on adding the calculated gradients via loss.backward() step. Once we accumulate gradients of 256 data points, we perform the optimization step i.e. calling optimizer.step(). Below is the PyTorch snippet for implementing accumulating gradients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc945c9c85e8c80951427c1940f8914c/href">https://medium.com/media/cc945c9c85e8c80951427c1940f8914c/href</a></iframe><p><strong>Pros:</strong></p><ul><li>Doesn’t require multiple GPUs for large batch training. This method enables large batch training even with a single GPU.</li></ul><p><strong>Cons:</strong></p><ul><li>Takes significantly more time than training parallelly on multiple GPUs.</li></ul><h3>Using nn.DataParallel</h3><p>If you have access to multiple GPUs, it would make sense to hand different batch splits to different GPUs, do gradient calculation on different GPUs, and then accumulate the gradients to perform gradient descend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IA3JaoSzp10SHSCYRZ1IfQ.png" /><figcaption>forward and backward pass for multi-gpu training(Image Credits: <a href="https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255">Hugging Face</a>)</figcaption></figure><p>Basically, the given input is split across the GPUs by chunking in the batch dimension. In the forward pass, the model is replicated on each device, and each replica handles a portion of the batch. During the backward pass, gradients from each replica are summed to produce the resultant gradient and applied on the master gpu(GPU-1 in the image above) to update the model weights. In the next iteration, this updated model on master GPU, is again replicated on each GPU device.</p><p>In PyTorch, it takes one line to enable distributed training using nn.DataParallel. The model just needs to be wrapped in nn.DataParallel.</p><pre>model = torch.nn.DataParallel(model)<br>...<br>...<br>loss = ...<br>loss.backward()</pre><p><strong>Pros:</strong></p><ul><li>Parallelizes NN training over multiple GPUs and hence it reduces the training time in comparison with accumulating gradients.</li><li>Good for quick prototyping because the code change is minimal.</li></ul><p><strong>Cons:</strong></p><ul><li>nn.DataParallel uses a single process multi-threading method to train the same model on different GPUs. It keeps the main process on one GPU and runs a different thread on other GPUs. Since multi-threading in python suffers from GIL(Global Interpreter Lock) issues, this restricts fully parallelized distributed training setup.</li></ul><h3>Using DistributedDataParallel</h3><p>Unlike nn.DataParallel, DistributedDataParallel uses multi-processing to spawn separate processes on separate GPUs and leverage the full parallelism across GPUs. But setting up DistributedDataParallel pipeline is more complex than nn.DataParallel and requires the following steps(but not necessarily in this order).</p><ol><li>Wrap the model in torch.nn.Parallel.DistributedDataParallel .</li><li>Setup the Dataloader to use distributedSampler to distribute samples efficiently across all GPUs. Pytorch provides torch.utils.data.Distributed.DistributedSampler for it.</li><li>Setup the distributed backend to manage the synchronization of GPUs. torch.distributed.init_process_group(backend=&#39;nccl&#39;). <br>There are different backends(<em>nccl, gloo</em>, <em>mpi</em>, <em>tcp</em>) provided by pytorch for distributed training. As a rule of thumb, <strong>use <em>nccl</em> for distributed training over GPUs</strong> and <strong><em>gloo</em> for distributed training over CPUs</strong>. Read more about them here <a href="https://pytorch.org/tutorials/intermediate/dist_tuto.html#advanced-topics">https://pytorch.org/tutorials/intermediate/dist_tuto.html#advanced-topics</a></li><li>Launch the separate processes on each GPU. use torch.distributed.launch utility function for the same. Suppose we have 4 GPUs on the cluster node over which we would like to use for setting up distributed training. Following shell command could be used to do that.</li></ol><pre>python -m torch.distributed.launch --nproc_per_node=4 <br>--nnodes=1 --node_rank=0<br>--master_port=1234 train.py &lt;OTHER TRAINING ARGS&gt;</pre><p>While setting up the launch script, we have to provide a free port(1234 in this case) over the node where the master process would be running and used to communicate with other GPUs.</p><p>Below is the complete PyTorch gist covering all the steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3585b0174a03571544e98b1f5e024d03/href">https://medium.com/media/3585b0174a03571544e98b1f5e024d03/href</a></iframe><p>Notice that the above-mentioned utility call(last commented line in the above gist) is for a single node over a GPU cluster. In case you want to use a multi-node setup, additionally, you have to choose a node as the master node and provide the master_addr argument while setting up the launch utility as follows. Suppose we have 2 nodes with 4 GPU each and the first node with the ip address “192.168.1.1” is the master node. We have to start the launch script on each node separately as follows.</p><p>On first node, run</p><pre>python -m torch.distributed.launch --nproc_per_node=4 <br>--nnodes=1 --node_rank=0<br>--master_addr=&quot;192.168.1.1&quot; --master_port=1234 train.py &lt;OTHER TRAINING ARGS&gt;</pre><p>On second node, run</p><pre>python -m torch.distributed.launch --nproc_per_node=4 <br>--nnodes=1 --node_rank=1<br>--master_addr=&quot;192.168.1.1&quot; --master_port=1234 train.py &lt;OTHER TRAINING ARGS&gt;</pre><p><strong>Other Utility Functions:</strong></p><p>While evaluating the model or generating the logs, it is required to collect current batch statistics such as losses, accuracy, etc. from all GPUs and collate them at one machine to log. Following methods are provided by PyTorch for syncing variables across all the GPUs.</p><ul><li>torch.distributed.gather(input_tensor, gather_list, dst) : Collect the specified<em> input_tensor </em>from all devices and place them on the <em>dst</em> device in <em>gather_list</em>.</li><li>torch.distributed.all_gather(tensor_list, input_tensor) : Collect the specified input_tensor from all devices and place them in tensor_list variable on all devices.</li><li>torch.distributed.reduce(input_tensor, dst, reduce_op=ReduceOp.SUM): Collect the input_tensor from all devices and reduce them using the specified reduce operation such as sum, mean, etc. The final result is placed on the <em>dst </em>device<em>.</em></li><li>torch.distributed.all_reduce(input_tensor, reduce_op=ReduceOp.SUM) : Same as reduce operation but the final result is copied to all devices.</li></ul><p>For more details about parameters and methods, read the torch.distributed package. <a href="https://pytorch.org/docs/stable/distributed.html">https://pytorch.org/docs/stable/distributed.html</a></p><p>As an example, the below code takes the loss values from all GPUs and reduces them to the master device(cuda:0).</p><pre>#In continuation with distributedDataParallel.py above</pre><pre>def get_reduced_loss(loss, dest_device):<br>  loss_tensor = loss.clone()<br>  torch.distributed.reduce(loss_tensor, dst=dest_device)<br>  return loss_tensor</pre><pre>if args.local_rank==0:<br>  loss_tensor = get_reduced_loss(loss.detach(), 0)<br>  print(f&#39;Current batch Loss = {loss_tensor.item()}&#39;</pre><p><strong>Pros:</strong></p><ul><li>The same code setup could be used for a single GPU without any code change. A single GPU setting would require only the launch script with the appropriate setting.</li></ul><p><strong>cons:</strong></p><ul><li>Layers such as BatchNorm which uses whole batch statistics in their computations, can’t carry out the operation independently on each GPU using only a split of the batch. PyTorch provides SyncBatchNorm as a replacement/wrapper module for BatchNorm which calculates the batch statistics using the whole batch divided across GPUs. See the sample code below for usage of SyncBatchNorm .</li></ul><pre>network = .... #some network with BatchNorm layers in it</pre><pre>sync_bn_network <strong>=</strong> nn<strong>.</strong>SyncBatchNorm<strong>.</strong>convert_sync_batchnorm(network)<br>ddp_network <strong>=</strong> nn<strong>.</strong>parallel<strong>.</strong>DistributedDataParallel(<br>                                 sync_bn_network,<br>                                 device_ids<strong>=</strong>[args<strong>.</strong>local_rank],                output_device<strong>=</strong>args<strong>.</strong>local_rank)</pre><h3><strong>Summary</strong></h3><ul><li>For splitting the model across GPUs, split the model into sub_modules and push each sub_module to separate GPU.</li><li>For splitting the batch across GPUs, use either of accumulating gradients, nn.DataParallel or nn.DistributedDataParallel.</li><li>For quick prototyping, nn.DataParallel could be preferred.</li><li>For training a large model and to leverage full parallel training across multiple GPUs, nn.DistributedDataParallel should be used.</li><li>While using nn.DistributedDataParallel, replace, or wrap nn.BatchNorm layer with nn.SyncBatchNorm.</li></ul><p>Below is the list of references used for writing this post.</p><ol><li><a href="https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255">https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255</a></li><li><a href="https://pytorch.org/docs/stable/distributed.html">https://pytorch.org/docs/stable/distributed.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e766e2a9e62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/distributed-neural-network-training-in-pytorch-5e766e2a9e62">Distributed Neural Network Training In Pytorch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Camera Image Perspective Transformation to different plane using OpenCV]]></title>
            <link>https://nilesh0109.medium.com/camera-image-perspective-transformation-to-different-plane-using-opencv-5e389dd56527?source=rss-ae2c3b0d24ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e389dd56527</guid>
            <category><![CDATA[homography]]></category>
            <category><![CDATA[photography]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[opencv]]></category>
            <dc:creator><![CDATA[Nilesh Vijayrania]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 10:06:04 GMT</pubDate>
            <atom:updated>2020-12-26T03:05:33.926Z</atom:updated>
            <content:encoded><![CDATA[<h4>Objects In Mirror Are Closer Than They Appear</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wsXofcyz5tyQZWXhP7zMuw.jpeg" /><figcaption>Image Taken from: <a href="https://btgconsulting.biz/2019/12/10/warning-dates-on-the-calendar-are-closer-than-they-appear/">https://btgconsulting.biz/2019/12/10/warning-dates-on-the-calendar-are-closer-than-they-appear/</a></figcaption></figure><p>“Objects In Mirror Are Closer Than They Appear”. I am sure, most of you, would have seen this disclaimer. Ever Wondered Why? Read along to find out!</p><p>Due to several advancements in camera technology, cameras are capable of clicking shots at various angles and views. Different angles for instance high-angle by drones, Bird’s Eye, side view, etc., or different camera lenses such as fisheye lens, project the scene on the camera image plane differently than the actual position of the object in the world. This phenomenon is termed as Perspective distortion in photography.</p><p>The disclaimer “Objects In Mirror Are Closer Than They Appear”, is always on the sideview mirror which is mostly tilted and slightly curved. Due to this curvature, Perspective distortion takes place in the image we see in the mirror.</p><p>Formally, <strong>perspective distortion</strong> is a warping or transformation of an object and its surrounding area that differs significantly from what the object would look like with normal focal length, due to the relative scale of nearby and distant features. In this post, I will cover how we can correct these distortions to find out the actual position of the object in the world, given the 2D camera image of it(under a specific assumptions).</p><p>First, we have to understand, how the 3d object in the world, is projected onto the image plane in the camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wGsRhelBo7Y_V07qcIOQUw.png" /><figcaption><a href="https://lhoangan.github.io/camera-params/">Image Source</a></figcaption></figure><p>Fundamentally, through the camera pinhole, light is cast on the object. This light when reflected from the object, is projected on the image plane which is present inside the camera and gives the inverted image. To get the actual view, this image plane is inverted(virtual image plane in image above).</p><p>Without going into mathematical details, the object’s coordinates in the 3d world, are converted into a 2d image plane using trigonometry(shown below, read more here <a href="https://lhoangan.github.io/camera-params/">https://lhoangan.github.io/camera-params/</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*I8PAxSK4Q8C2eazSLDKW7Q.png" /><figcaption>Image Source: Opencv documentation</figcaption></figure><p>Mathematically, the 3d coordinates are multipled by a 3x4 matrix(called the perspective matrix) to get the 2d coordinates in the image plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*qa6PAz2cvcJQDxs0gHNmZg.gif" /><figcaption>Eq 1: 3d points to 2d conversion(Source: Image by author)</figcaption></figure><p>Point (x, y, z) in the 3d world coordinate system is converted to point (u, v) on 2d camera image plane using the 3x4 perspective matrix.</p><p>But in this post, we would like to find a matrix to go from the 2d image plane to world coordinates. Intuitively, it is not possible, because in the 2d image plane, we lose the 3rd dimension and it is not possible to recover the 3rd dimension without any extra knowledge(that’s why RGB-D camera exits). Also mathematically, the 3x4 projection matrix is not square and hence not invertible.</p><p><strong>But if we are only interested in the (x, y) world coordinates of the object for a fixed z, it is possible to find those</strong>. For example, if we have a security camera at the top of the lift and we would like to know the actual position of the person on the floor(considering fixed z=0 as floor plane) from the camera image, it would be possible. There are two approaches to do that.</p><ol><li><strong>Using the inverse Perspective Matrix</strong></li></ol><p>If the plane at which (x, y) world coordinates are desired, is at z=0 of the system, then any point on the floor plane will have coordinates &lt;x, y, 0&gt; and this effectively nullifies the effect of the third column of the perspective matrix from eq 1. Now the perspective matrix P could be reduced to a 3x3 matrix and hence becomes invertible(shown below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*IZ1PyNSUJZHaCsuOIfIKVg.png" /><figcaption>(Source: Image by Author)</figcaption></figure><p>Now to get the (x, y) from (u, v), we only need to find the inverse of 3x3 perspective matrix P and we can find the corresponding point on floor plane from image plane.</p><p>But what if we want to find the (x, y) coordinate on any arbitrary plane where z is not equal to 0. We could use Homography to achieve that.</p><p><strong>2. Using Homography Matrix</strong></p><p>Homography Matrix relates the transformation from one plane to another. Essentially, if we have &lt;u, v&gt; point in one plane and &lt;x, y&gt; in another plane, then the transformation from &lt;u, v&gt; to &lt;x, y&gt; could be written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*bGx6sLPBFnkQ0I1PcYKyyQ.png" /><figcaption>Eq 2. Homography matrix H(Source: Image by Author)</figcaption></figure><p>where H is the 3x3 homography matrix.</p><p>But to get the homography matrix, we must need at least 4 points in one plane and their corresponding mapping points in the other plane.</p><p>Given the perspective matrix P, we can easily find the 4 corresponding points between any 3d world plane(keeping fixed z) and 2d plane using eq 1.</p><p>In OpenCV, you could use cv2.findHomography function to find the homography matrix, by giving 4 or more points in the source and destination plane.</p><p>Below is the code gist using OpenCV.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92b12c3159181dc6c4d318e1b74c2f7f/href">https://medium.com/media/92b12c3159181dc6c4d318e1b74c2f7f/href</a></iframe><p>Once you get the homography matrix, eq 2 could be used to move from the image plane to the desired plane.</p><p>A point of caution is, these methods don’t imply anything about the position along the z-axis in world coordinate and considers it fixed.</p><p><strong>TL; DR:</strong></p><ul><li>For Perspective transformation from the Image plane to a fixed plane in world coordinates, two methods could be used.</li><li>If the equation of the plane is z=0, the 3x4 perspective matrix could be reduced to a 3x3 matrix by ignoring the 3rd column entirely and the inverse of this 3x3 matrix could be used.</li><li>For any other arbitrary plane, the homography matrix should be used. To find the homography matrix, at least 4 corresponding points in both planes are required by cv.findhomography method.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e389dd56527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Supervised Learning Methods for Computer Vision]]></title>
            <link>https://medium.com/data-science/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd?source=rss-ae2c3b0d24ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/c25ec10a91bd</guid>
            <category><![CDATA[self-supervised-learning]]></category>
            <category><![CDATA[representation-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Nilesh Vijayrania]]></dc:creator>
            <pubDate>Tue, 15 Dec 2020 14:14:27 GMT</pubDate>
            <atom:updated>2021-01-02T14:58:20.355Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What is Self-supervised Learning?</strong></h4><p>Self-supervised Learning is an unsupervised learning method where the supervised learning task is created out of the unlabelled input data.</p><p>This task could be as simple as given the upper-half of the image, predict the lower-half of the same image, or given the grayscale version of the colored image, predict the RGB channels of the same image, etc.</p><figure><img alt="Learn from yourself" src="https://cdn-images-1.medium.com/max/716/1*lavhAToKGO9Bo4j3U7n4TA.jpeg" /><figcaption>Image by Author</figcaption></figure><p><strong>Why Self-supervised Learning?</strong></p><p>Supervised learning requires usually a lot of labelled data. Getting good quality labelled data is an expensive and time-consuming task specially for a complex task such as object detection, instance segmentation where more detailed annotations are desired. On the other hand, the unlabelled data is readily available in abundance. The motivation behind Self-supervised learning is to learn useful representations of the data from unlabelled pool of data using self-supervision first and then fine-tune the representations with few labels for the supervised downstream task. The downstream task could be as simple as image classification or complex task such as semantic segmentation, object detection, etc.</p><p>Lately, in natural language processing, Transformer models have achieved a lot of success. Transformers like Bert[1], T5[2], etc. applied the idea of self-supervision to NLP tasks. They first train the model with large unlabelled data and then fine-tuning the model with few labelled data examples. Similar self-supervised learning methods have been researched for computer vision as well and in this post, I will try to cover a few of those.</p><p>The fundamental idea for self-supervised learning is to create some auxiliary pre-text task for the model from the input data itself such that while solving the auxiliary task, the model learns the underlying structure of the data(for instance the structure of the object in case of image data). Many self-supervised learning methods have been researched but contrastive learning methods seem to be work better than others for computer vision, hence in this post, I would concentrate on contrastive learning-based self-supervised learning methods</p><p><strong>What is Contrastive Learning?</strong></p><p>suppose we have a function f(represented by any deep network Resnet50 for example), given an input x, it gives us the features f(x) as output.</p><p>Contrastive Learning states that for any positive pairs x1 and x2, the respective outputs f(x1) and f(x2) should be similar to each other and for a negative input x3, f(x1) and f(x2) both should be dissimilar to f(x3).</p><figure><img alt="Contrastive Learning" src="https://cdn-images-1.medium.com/max/753/1*fdAU4VJtnclv0rGrfzUu4g.png" /><figcaption>Contrastive Learning Idea (Image by Author)</figcaption></figure><p>The positive pair could be two crops of same image(lets say top-left and bottom right), two frames of same video file, two augmented views(horizontally flipped version for instance) of same image, etc. and respective negatives could be a crop from different image, frame from different video, augmented view of different image, etc.</p><p>The idea of contrastive learning was first introduced in this paper “<a href="https://arxiv.org/abs/1807.03748">Representation learning with contrastive predictive coding</a>”[3] by Aaron van den Oord et al. from DeepMind. The formulated contrastive learning task gave a strong basis for learning useful representations of the image data which is described next.</p><h3>Contrastive Predictive Coding(CPC)</h3><p>The central idea of CPC is to first divide the whole image into a coarse grid and given the upper few rows of the image, the task is to predict the lower rows of the same image. The motivation is, to accomplish this task, the model has to learn the structure of the object in the image(<em>for example seeing the face of a dog, the model should predict that it would have 4 legs</em>) and this would give us a useful representations for downstream tasks.</p><p>The whole auxiliary task could be summarized in 3 steps.</p><ol><li>Given the 256 x 256 image, divide it into a 7x7 grid with each cell of size 64px and 32px overlap with neighboring cells.</li><li>Use an encoder model(g_enc) such as Resnet-50 to encode each grid cell into a 1024 dimension vector. The whole image is now transformed into 7x7x1024 tensor.</li><li>Given the top 3 rows of the transformed grid(7x7x1024 tensors), generate the last 3 rows of it(i.e. 3x3x1024 tensor). An auto-regressive generative model g_ar(PixelCNN for instance) is used for predicting the bottom 3 rows. PixelCNN in itself needs a separate post and is kept outside the scope of this article. In a 3000 ft overview, PixelCNN creates a context vector c_t from the given 3 top rows and sequentially predicts the bottom tows(z_t+2, z_t+3, z_t+4 from the figure below).</li></ol><p>The below image depicts the task pictorially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*TofsYD68wREzt9Keuu0now.png" /><figcaption>Image Credits: Aaron van den Oord et al. <a href="https://arxiv.org/abs/1807.03748">Representation learning with contrastive predictive coding</a>[3]</figcaption></figure><p>To train this model effectively, a loss function is required to enforce the similarity between positive pairs(correct patch prediction) and negative pairs(incorrect patch). For calculating the loss, the set <em>X</em> of N patches is used where <em>X</em> is the set of <em>N-1</em> negative samples and 1 positive sample(correct path). The <em>N-1 </em>negatives are sampled randomly from all available patches of the same image(expect the correct patch) and different images in the batch. This loss is termed as InfoNCE loss where NCE stands for Noise Contrastive and it is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*6LCZvT6jJVuZpmErjSgMRQ.png" /><figcaption>InfoNCE loss[4]</figcaption></figure><p>Here q is the network prediction, k+ is the positive patch(correct patch) and k- represents a set of N-1 negative patches. Note that k+, k- and q, all are in representation space i.e. output of g_enc and not into original image space.</p><p>In simple terms, the formula is equivalent to the log_softmax function. To calculate the similarity, the dot product is used. Take a dot product of all N samples with the prediction q and then calculate the log of softmax of the similarity score of the positive sample with the prediction q.</p><p>In order to validate the richness of the representations learnt by CPC, a <strong>linear evaluation protocol</strong> is used. A linear classifier is trained on top of the output of the frozen encoder model(g_enc) using the Imagenet dataset and then it is evaluated for the classification accuracy of the learnt classifier model on the Imagenet Val/Test set. Note that during this whole training process of the linear classifier, the backbone model(g_enc) is fixed and is not trained at all. The table below shows that the classification accuracy of CPC representations outperformed all the other methods introduced before CPC with 48.7% top-1 acc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*eV_ro_d1GgwCmed3SWgGJg.png" /><figcaption>Imagenet Top-1% Accuracy of the Linear Classifier Trained on top of CPC representations[3]</figcaption></figure><p>Although CPC outperformed other unsupervised learning methods for representation learning, the classification accuracy was still very far from the supervised counterpart(Resnet-50 with 100% labels on the Imagenet has 76.5% top-1 accuracy). This idea of image crop discrimination was extended to instance discrimination and tightened the gap between self-supervised learning and supervised learning methods.</p><h3><strong>Instance Discrimination Methods</strong></h3><p>Instance Discrimination applies the concept of contrastive learning to whole image instance. Instance Discrimination method constraints that two augmented versions of the same image(positive pair) should have similar representations and two augmented versions of the different image(negative pair) should have different representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_76TAj0aS5PUImFm_omqBA.png" /><figcaption>Instance Discrimination. Image Credits: Deep Unsupervised Learning — P. Abbeel, P. Chen, J. Ho, A. Srinivas, A. Li, W. Yan — L7 Self-Supervised Learning</figcaption></figure><p>Two papers <strong>MoCo</strong> and <strong>SimCLR</strong> worked on the idea of instance discrimination around the same time. Their main objective is, under a certain kind of image augmentations, the learnt representations should be invariant. These certain image augmentations include horizontal flip, a random crop of a certain size, color channel distortion, gaussian blur, etc. Intuitively, these augmentations although change the input image, but does not change the class of the input image(a cat would be a cat after flipping and cropping as well) and hence their representations should also not change.</p><p>The whole method is as follows.</p><ol><li>Given an image, create an image pair&lt;x1, x2&gt; with two randomly augmented versions of this image. Sample N-2 negative samples by randomly taking an augmented version of any other image in the dataset.</li><li>Pass this image pair to the encoder model(g_enc), and get the representations. Also, obtain the representations of the N-2 negatives.</li><li>Similar to CPC, apply InfoNCE loss to induce similarity between positive pairs and dissimilarity between negative pairs.</li></ol><p>The major difference between SimCLR and MoCo is how they handle the negative samples.</p><h3>SimCLR</h3><p>SimCLR considers all the images in the current batch as negative samples. Trained in this way, SimCLR representations achieve a top-1% accuracy of 69.3% on the Imagenet with the linear evaluation protocol described in the CPC section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*-804ozRWp0Mmmd0LvZIN1A.png" /><figcaption>SimCLR linear classifier result on Imagenet[5]</figcaption></figure><p>In practice, InfoNCE loss performance is dependent upon the number of negatives and it requires a high number of negatives while calculating the loss term. Hence, simCLR is trained with a high number of batches(as big as 8k) for best results which are very computationally demanding and require multi-GPU training. This is considered as the main drawback of simCLR method.</p><h3>Momentum Contrast(MoCo)</h3><p>Momentum Contrast(MoCo) on the other hand, keeps a separate buffer of negatives(as high as 8k) and uses them for calculating the InfoNCE loss. This allows them to train MoCo with smaller batch sizes without compromising on accuracy.</p><p>MoCo keeps all recent mini-batches in fixed-size buffer for negatives(shown as x_0, x_1,x_2 in below image). To achieve superior results, a momentum encoder(<strong>Θ_k</strong>) is used which has exact architecture as the encoder (<strong>Θ_q</strong>)but the weights are slowly moving towards the actual encoder(shown below in the image).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*LiFISdNYgO-T38rz8KihFw.png" /><figcaption>Momentum encoder Update step[4]</figcaption></figure><p>The only role of the momentum encoder is to generate representations(k_0, k_1, k_2… in the image below) out of the negative samples. Mind that momentum encoder does not update the weights through backpropagation which makes the method more memory efficient and allows to keep a large buffer of negatives in memory. <br>Now in a short summary, given the first input x_query, the encoder generates the representations q, which is matched against another augmented version of the same image x_query(not shown in the image below) and also matched with the N negatives provided by the momentum encoder. Then the loss term is calculated using InfoNCE loss described in CPC section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*5C0hQvRvTr3qgWJbLDWzIg.png" /><figcaption>Image credits: He, Kaiming, et al. “Momentum contrast for unsupervised visual representation learning.”[4]</figcaption></figure><p>It might be difficult for the readers to understand the relevance of momentum encoder and application of MoCo only through the post, so please for more details, I highly recommend reading the <a href="https://arxiv.org/abs/2002.05709">original paper</a> . I have just covered the main highlights of the idea.</p><p>In the second version of MoCo, the representations attained 71.1% accuracy on the Imagenet under linear evaluation protocol which went further close to the supervised Resnet-50 model(76.5%).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*rtPKRA8vV5biaXWU90RgGQ.png" /><figcaption>MoCo linear classifier result on Imagenet[6]</figcaption></figure><h3>Bootstrap your own Latent(BYOL)</h3><p>Although MoCo showed good results but the dependency on negative samples has complicated the method. Recently BYOL[7] was introduced based on the instance discrimination method and it has shown that using two networks similar to MoCo, better visual representations could be learnt even without negatives. Their method achieves 74.3% top-1 classification accuracy on ImageNet under linear evaluation protocol using Resnet50 and further reduces the gap with their supervised counterpart using wider and deeper Resnets. The results are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*6nah3xfeUKiJgX72JPcN4g.png" /><figcaption>Image Credits: Bootstrap your own latent-a new approach to self-supervised learning[7]</figcaption></figure><p>The actual BYOL training method is worthy of a separate post and I would leave it for future posts.</p><p>[UPDATE]: Post for BYOL <a href="https://nilesh0109.medium.com/hands-on-review-byol-bootstrap-your-own-latent-67e4c5744e1b">https://nilesh0109.medium.com/hands-on-review-byol-bootstrap-your-own-latent-67e4c5744e1b</a></p><p><strong>TL; DR:</strong></p><ul><li>Self-supervised learning is a representation learning method where a supervised task is created out of the unlabelled data.</li><li>Self-supervised learning is used to reduce the data labelling cost and leverage the unlabelled data pool.</li><li>Some of the popular self-supervised tasks are based on contrastive learning. Examples of contrastive learning methods are BYOL, MoCo, SimCLR, etc.</li></ul><p>Below is the list of references used for writing this post.</p><ol><li>Devlin, Jacob, et al. “Bert: Pre-training of deep bidirectional transformers for language understanding.” <em>arXiv preprint arXiv:1810.04805</em> (2018).</li><li>Raffel, Colin, et al. “Exploring the limits of transfer learning with a unified text-to-text transformer.” <em>arXiv preprint arXiv:1910.10683</em> (2019).</li><li>Oord, Aaron van den, Yazhe Li, and Oriol Vinyals. “Representation learning with contrastive predictive coding.” <em>arXiv preprint arXiv:1807.03748</em> (2018).</li><li>He, Kaiming, et al. “Momentum contrast for unsupervised visual representation learning.” <em>Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition</em>. 2020.</li><li>Chen, T., Kornblith, S., Norouzi, M., &amp; Hinton, G. (2020). A simple framework for contrastive learning of visual representations. <em>arXiv preprint arXiv:2002.05709</em>.</li><li>Chen, X., Fan, H., Girshick, R., &amp; He, K. (2020). Improved baselines with momentum contrastive learning. <em>arXiv preprint arXiv:2003.04297</em></li><li>Grill, Jean-Bastien, et al. “Bootstrap your own latent-a new approach to self-supervised learning.” <em>Advances in Neural Information Processing Systems</em> 33 (2020).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c25ec10a91bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd">Self-Supervised Learning Methods for Computer Vision</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Normalization Layers in Deep Learning]]></title>
            <link>https://medium.com/data-science/different-normalization-layers-in-deep-learning-1a7214ff71d6?source=rss-ae2c3b0d24ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a7214ff71d6</guid>
            <category><![CDATA[batch-normalization]]></category>
            <category><![CDATA[weight-standardization]]></category>
            <category><![CDATA[weight-normalization]]></category>
            <category><![CDATA[layer-normalization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nilesh Vijayrania]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 12:35:45 GMT</pubDate>
            <atom:updated>2021-03-14T10:19:58.994Z</atom:updated>
            <content:encoded><![CDATA[<h4>Weight Standardization — An Alternative to Batch Normalization</h4><p>Presently Deep Learning has been revolutionizing many subfields such as natural language processing, computer vision, robotics, etc. Deep learning certainly involves training carefully designed deep neural networks and various design decisions impact the training regime of these deep networks. Some of these design decisions include</p><ul><li>Type of network layer to use such as convolution layer, linear layer, recurrent layer, etc. in the network, and how many layers deep should our network be?</li><li>What kind of normalization layer we should use if at all?</li><li>What should be the correct loss function to optimize for?</li></ul><p>Majorly these design decisions depend upon the underlying task we are trying to solve and require a deeper understanding of the different options we have at hand. In this post, I will focus on the second point “different Normalization Layers in Deep Learning”. Broadly I would cover the following methods.</p><ul><li>Batch Normalization</li><li>Weight Normalization</li><li>Layer Normalization</li><li>Group Normalization</li><li>Weight Standarization</li></ul><h3><strong>Batch Normalization(BN)</strong></h3><p>Batch Normalization focuses on standardizing the inputs to any particular layer(i.e. activations from previous layers). Standardizing the inputs mean that inputs to any layer in the network should have approximately zero mean and unit variance. Mathematically, BN layer transforms each input in the current mini-batch by subtracting the input mean in the current mini-batch and dividing it by the standard deviation.</p><p>But each layer doesn’t need to expect inputs with zero mean and unit variance, but instead, probably the model might perform better with some other mean and variance. Hence the BN layer also introduces two learnable parameters γ and β.</p><p>The whole layer operation is as follows. It takes an input x_i and transforms it into y_i as described in the below table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*rwQgG3lrQFfjWac8k14SbA.png" /><figcaption>Credits: <a href="https://arxiv.org/abs/1502.03167">Ioffe and Szegedy, Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift</a></figcaption></figure><p>The question is how BN helps NN training? Intuitively, In gradient descent, the network calculates the gradient based on the current inputs to any layer and reduce the weights in the direction indicated by the gradient. But since the layers are stacked one after the other, the data distribution of input to any particular layer changes too much due to slight update in weights of earlier layer, and hence the current gradient might produce suboptimal signals for the network. But BN restricts the distribution of the input data to any particular layer(i.e. the activations from the previous layer) in the network, which helps the network to produce better gradients for weights update. Hence BN often provides a much stable and accelerated training regime.</p><p>However below are the few cons of Batch Normalization.</p><ul><li>BN calculates the batch statistics(Mini-batch mean and variance) in every training iteration, therefore it requires larger batch sizes while training so that it can effectively approximate the population mean and variance from the mini-batch. This makes BN harder to train networks for application such as object detection, semantic segmentation, etc because they generally work with high input resolution(often as big as 1024x 2048) and training with larger batch sizes is not computationally feasible.</li><li>BN does not work well with RNNs. The problem is RNNs have a recurrent connection to previous timestamps and would require a separate β and γ for each timestep in the BN layer which instead adds additional complexity and makes it harder to use BN with RNNs.</li><li>Different training and test calculation: During test(or inference) time, the BN layer doesn’t calculate the mean and variance from the test data mini-batch(steps 1 and 2 from the algorithm table above) but uses the fixed mean and variance calculated from the training data. This requires cautious while using BN and introduces additional complexity. In pytorch model.eval() makes sure to set the model in evaluation model and hence the BN layer leverages this to use fixed mean and variance from pre-calculated from training data.</li></ul><h3><strong>Weight Normalization</strong></h3><p>Due to the disadvantages of Batch Normalization, T. Saliman and P. Kingma proposed Weight Normalization. Their idea is to decouple the length from the direction of the weight vector and hence reparameterize the network to speed up the training.</p><p>What does reparameterization mean for Weight Normalization?</p><p>The authors of the <a href="https://arxiv.org/pdf/1602.07868.pdf">Weight Normalization paper</a> suggested using two parameters g(for length of the weight vector) and v(the direction of the weight vector) instead of w for gradient descent in the following manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*a8GI_2ebfdesktj6Aj25cA.png" /></figure><p>Weight Normalization speeds up the training similar to batch normalization and unlike BN, it is applicable to RNNs as well. But the training of deep networks with Weight Normalization is significantly less stable compared to Batch Normalization and hence it is not widely used in practice.</p><h3>Layer Normalization(LN)</h3><p>Inspired by the results of Batch Normalization, Geoffrey Hinton et al. proposed<a href="https://arxiv.org/abs/1607.06450"> Layer Normalization</a> which normalizes the activations along the feature direction instead of mini-batch direction. This overcomes the cons of BN by removing the dependency on batches and makes it easier to apply for RNNs as well.</p><p>In essence, Layer Normalization normalizes each feature of the activations to zero mean and unit variance.</p><h3>Group Normalization(GN)</h3><p>Similar to layer Normalization, Group Normalization is also applied along the feature direction but unlike LN, it divides the features into certain groups and normalizes each group separately. In practice, Group normalization performs better than layer normalization, and its parameter <em>num_groups</em> is tuned as a hyperparameter.</p><p>If you find BN, LN, GN confusing, the below image summarizes them very precisely. Given the activation of shape (N, C, H, W), BN normalizes the N direction, LN and GN normalize the C direction but GN additionally divides the C channels into groups and normalizes the groups individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*xf37Ts0mdBGiS-keOwviOQ.png" /><figcaption>Image Credits: <a href="https://arxiv.org/abs/1903.10520">Siyuan Qiao et al.: Weight Standardization</a></figcaption></figure><p>Lets next understand what weight Standardization is.</p><p><strong>Weight Standardization(WS)</strong></p><p>Weight Standardization is transforming the weights of any layer to have zero mean and unit variance. This layer could be a convolution layer, RNN layer or linear layer, etc. For any given layer with shape(N, *) where * represents 1 or more dimensions, weight standardization, transforms the weights along the * dimension(s).</p><p>Below is the sample code for implementing weight standardization for the 2D conv layer in pytorch.</p><pre>class Conv2d(nn.Conv2d):<br>  def __init__(self, in_channels, out_channels, kernel, **kwargs):<br>    super().__init__(in_channels, out_channels, kernel, **kwargs)<br>  <br>  def forward(self, x):        <br>    weight = self.weight<br>    weight_mean = weight.mean(dim=(1,2,3), keepdim=True)<br>    std = weight.std(dim=(1,2,3) + 1e-5<br>    weight = (weight - weight_mean)/ std<br>    return F.conv2d(x, weight, self.bias, self.stride, self.padding, self.dilation, self.groups)</pre><p>The basic idea is to only transform the weights during the forward pass and calculate activations accordingly. Pytorch will handle the backward pass out of the box. Similarly, it could be implemented for the linear layer as well.</p><p>Recently, Siyun Qiao et al. introduced Weight Standardization in their paper <a href="https://arxiv.org/pdf/1903.10520.pdf">“Micro-Batch Training with Batch-Channel Normalization and Weight Standardization”</a> and found that group normalization when mixed with weight standardization, could outperform or perform equally well as BN even with batch size as small as 1. Shown below in the graph, the authors trained GN, BN, combination of GN+WS with Resnet50 and Resnet101 on Imagenet classification and MS COCO object detection task and found that GN+WS consistently outperforms the BN version even with much smaller batches than BN uses. This has attracted attention in dense prediction tasks such as semantic segmentation, instance segmentation which are usually not trainable with larger batch sizes due to memory constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awMWlEvsYdaImYg1NnmY5g.png" /><figcaption>Image Credits: Siyuan Qiao et al. Weight Standardization. GN+WS effect on classification and object detection task[4]</figcaption></figure><p>In conclusion, Normalization layers in the model often helps to speed up and stabilize the learning process. If training with large batches isn’t an issue and if the network doesn’t have any recurrent connections, Batch Normalization could be used. For training with smaller batches or complex layer such as LSTM, GRU, Group Normalization with Weight Standardization could be tried instead of Batch Normalization.</p><p>One important thing to note is, in practice the normalization layers are used in between the Linear/Conv/RNN layer and the ReLU non-linearity(or hyperbolic tangent etc) so that when the activations reach the Non-linear activation function, the activations are equally centered around zero. This would potentially avoid the dead neurons which never get activated due to wrong random initialization and hence can improve training.</p><p>Below is the list of references used for this post and should be considered for further experiment details.</p><ol><li>Ioffe, Sergey, and Christian Szegedy. “Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift.” <em>arXiv preprint arXiv:1502.03167</em> (2015).</li><li>Salimans, Tim, and Durk P. Kingma. &quot;Weight normalization: A simple reparameterization to accelerate training of deep neural networks.&quot; <em>Advances in neural information processing systems</em> 29 (2016): 901-909.</li><li>Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. “Layer normalization.” <em>arXiv preprint arXiv:1607.06450</em> (2016).</li><li>Qiao, Siyuan, et al. “Weight standardization.” <em>arXiv preprint arXiv:1903.10520</em> (2019)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a7214ff71d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/different-normalization-layers-in-deep-learning-1a7214ff71d6">Different Normalization Layers in Deep Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>