<?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 Ruhaan838 on Medium]]></title>
        <description><![CDATA[Stories by Ruhaan838 on Medium]]></description>
        <link>https://medium.com/@ruhaan838?source=rss-4c6876ef79ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Ruhaan838 on Medium</title>
            <link>https://medium.com/@ruhaan838?source=rss-4c6876ef79ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:55:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ruhaan838/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[Role of  Positional Embedding]]></title>
            <link>https://ruhaan838.medium.com/role-of-positional-embedding-dfaacf6387a5?source=rss-4c6876ef79ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfaacf6387a5</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[attention-is-all-you-need]]></category>
            <category><![CDATA[positional-embedding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ruhaan838]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 09:58:03 GMT</pubDate>
            <atom:updated>2025-01-14T09:58:03.857Z</atom:updated>
            <content:encoded><![CDATA[<h3>Role of Positional Embedding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*V9LadppRsgHy-ld8" /><figcaption><a href="https://community.intel.com/t5/Blogs/Tech-Innovation/Artificial-Intelligence-AI/Is-Positional-Encoding-Required-In-All-Language-Models/post/1450078">Source</a></figcaption></figure><h3>Introduction</h3><p>It has been too many years since the <a href="https://arxiv.org/pdf/1706.03762">Transformer</a> came out and its revaluation of the AI world, especially Natural Language processing.<br>In that paper, they proposed the <strong>Positional Embedding </strong>that comes before the <strong>Encoder</strong> and <strong>Decoder, </strong>In this blog we try to look into what Positional Embedding deeply<strong>, why we need that</strong>, and how it <strong>affects learning </strong>of<strong> </strong>the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*RNlJFTBQi6rJh-aNcpFNGQ.png" /><figcaption><a href="https://arxiv.org/pdf/1706.03762">Source</a></figcaption></figure><h3>A Problem without Positional Embedding</h3><ul><li>In a paper they mention this line —</li></ul><blockquote>“ Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence.”</blockquote><p>Since Transformers are not used by any kind of <strong>recurrence </strong>or any kind of <strong>convolution </strong>so if we need to tell the model which word has its position also need to tell the model its <strong>relative and absolute position</strong> without this model can’t understand the meaning of the sentence for example the sentence: “You Seek Love. It’s All Any Of Us Want.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPjvAGYwrV2wLm2qbcvwHQ.png" /><figcaption>Image by Author — Token get from <a href="https://tiktokenizer.vercel.app/?model=text-embedding-ada-002">“TikTokenizer”</a></figcaption></figure><p>As we see in the <strong>image </strong>if we change the position of the words it makes no sense, if we pass this without any kind of position to the model it <strong>considers that as the same thing but that is different</strong>. The <strong>human brain can interpret the position</strong> of the <strong>word like that it needs to tell the model</strong> what are the position of the <strong>word and the relation between</strong> them we need to give a model to some kind of position.</p><h3>Solution With Sinosodial Positional Embedding</h3><p>In the paper that proposed the Positional Embedding concept with the <strong>Sinosodial equation</strong>. Given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*Mf3dBBfoWexX8p9G8T8dPQ.png" /><figcaption><a href="https://arxiv.org/pdf/1706.03762">Source</a></figcaption></figure><p>Let’s review what this equation is trying to say.</p><p>for our example the sentence <strong>“You Seek Love. It’s All Any Of Us Want.”</strong> the <strong>number or token</strong> representation of this sentence is <strong>“22336, 30839, 10919, 13, 1102, 596, 2052, 5884, 5046, 4073, 4194, 29923, 1210”.</strong></p><blockquote><em>For position 0 token is “22336”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*PTVoaB4EqKQdFqHrJsEqsA.png" /><figcaption><strong>position 0 token is “22336”</strong></figcaption></figure><blockquote>For Position 1 token is “30839”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*PPPwN7zCb1LrPOcJltlpMw.png" /><figcaption><strong>position 1 token is “30839”</strong></figcaption></figure><p>As we can see it gives the different vectors for each position for tokens that are nearly represented. <br>How does this help to give a sense of the position:<br>let&#39;s assume that the token “30839” is changing its position so that the vector representation of that token is changed.</p><h3>Why Sinusoidal function?</h3><p>The paper mentions that “they also use the <strong>learnable Positional Embedding</strong>” but both perform the same.</p><blockquote>We also experimented with using learned positional embeddings instead, and found that the two versions produced nearly identical results . We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*C7rzjOlv3lLLZO7a0VdqGA.png" /><figcaption><strong>Visual representation of the Positional Embedding</strong></figcaption></figure><h4>“You Seek Love. It’s All Any Of Us Want” visual representation of the sentence in 3D space</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ymnZsXmfzY8_QFPHIoNqRw.gif" /><figcaption>“You Seek Love. It’s All Any Of Us Want” visual representation of the sentence in 3D space</figcaption></figure><h4>“You Love Seek. Us Of All It’s Any Want.” visual representation of the sentence in 3D space</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TSAi_kfERA2-YdauYVVTzQ.gif" /><figcaption>“You Love Seek. Us Of All It’s Any Want.” visual representation of the sentence in 3D space</figcaption></figure><p><strong>we can see how both representations are different from each other due to the Sinusoidal function.</strong></p><h3>Coding Positional Embedding using PyTorch</h3><pre>import torch<br>from torch import nn<br>import math<br><br>class PositionalEmbedding(nn.Module):<br>    def __init__(self, d_model:int, seq_len:int):<br>        super().__init__()<br>        self.d_model = d_model<br>        <br>        pe = torch.zeros(seq_len, d_model) <br>        pos = torch.arange(0, seq_len).float().unsqueeze(1) # (seq_len, 1)<br>        div = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.) / d_model)) # 10000 ** (2 * i / d_model) -&gt; (0 &lt; i &lt; d_model)<br>        <br>        pe[:, 0::2] = torch.sin(pos * div) # sin(div) for even position<br>        pe[:, 1::2] = torch.cos(pos * div) # cos(div) for odd position<br>        <br>        pe = pe.unsqueeze(0) # add the batch_dim<br>        <br>        self.register_buffer(&#39;pe&#39;, pe) # we have regiter that for make PE non learnable <br>    <br>    def forward(self, x):<br>        x = x + (self.pe[:, :x.shape[1], :].requires_grad_(False))<br>        return x</pre><h3>Explanation</h3><h4>Create the Tensor of the tokens that are given.</h4><pre>words = [22336, 30839, 10919, 13, 1102, 596, 2052, 5884, 5046, 4073, 4194, 29923, 1210] <br>words = torch.tensor(words, dtype=torch.float32)<br>seq_len = len(words)<br>d_model = 8<br>final = torch.zeros(d_model, seq_len)<br>final[0] = words<br>for i in range(1, d_model):<br>    final[i] = torch.randint(1,10,(seq_len,))<br>words = final.T</pre><pre>#words output <br>tensor([[[2.2336e+04, 8.0000e+00, 5.0000e+00, 8.0000e+00, 4.0000e+00, 9.0000e+00, 7.0000e+00, 6.0000e+00],<br>         [3.0840e+04, 7.5403e+00, 5.0998e+00, 4.9950e+00, 4.0100e+00, 2.9999e+00, 6.0010e+00, 6.0000e+00],<br>         [1.0920e+04, 5.5839e+00, 6.1987e+00, 4.9801e+00, 1.0200e+00, 1.9998e+00, 6.0020e+00, 4.0000e+00],<br>         [1.3141e+01, 4.0100e+00, 1.2955e+00, 4.9553e+00, 3.0300e+00, 6.9995e+00, 9.0030e+00, 9.0000e+00],<br>         [1.1012e+03, 3.3464e+00, 6.3894e+00, 8.9211e+00, 7.0400e+00, 4.9992e+00, 3.0040e+00, 7.0000e+00],<br>         [5.9504e+02, 7.2837e+00, 2.4794e+00, 5.8776e+00, 4.0500e+00, 4.9988e+00, 2.0050e+00, 6.0000e+00],<br>         [2.0517e+03, 4.9602e+00, 2.5646e+00, 9.8253e+00, 1.0600e+00, 9.9982e+00, 7.0060e+00, 7.0000e+00],<br>         [5.8847e+03, 6.7539e+00, 8.6442e+00, 9.7648e+00, 5.0699e+00, 1.9976e+00, 9.0070e+00, 5.0000e+00],<br>         [5.0470e+03, 8.5450e-01, 7.7174e+00, 1.6967e+00, 2.0799e+00, 4.9968e+00, 4.0080e+00, 1.0000e+01],<br>         [4.0734e+03, 3.0889e+00, 9.7833e+00, 4.6216e+00, 8.0899e+00, 6.9960e+00, 4.0090e+00, 6.0000e+00],<br>         [4.1935e+03, 5.1609e+00, 4.8415e+00, 6.5403e+00, 2.0998e+00, 4.9950e+00, 9.0100e+00, 6.9999e+00],<br>         [2.9922e+04, 1.0044e+00, 4.8912e+00, 2.4536e+00, 1.1098e+00, 3.9940e+00, 3.0110e+00, 6.9999e+00],<br>         [1.2095e+03, 8.8439e+00, 7.9320e+00, 3.3624e+00, 7.1197e+00, 8.9928e+00, 4.0120e+00, 6.9999e+00]]])</pre><h4>Create the positional embedding (Sinosdual).</h4><pre>pe = torch.zeros(seq_len, d_model)<br>pos = torch.arange(0, seq_len).float().unsqueeze(1)<br>div = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.) / d_model))<br>pe[:, 0::2] = torch.sin(pos * div)<br>pe[:, 1::2] = torch.cos(pos * div)</pre><pre>#pe output<br>tensor([[[ 0.0000e+00,  1.0000e+00,  0.0000e+00,  1.0000e+00,  0.0000e+00, 1.0000e+00,  0.0000e+00,  1.0000e+00],<br>         [ 8.4147e-01,  5.4030e-01,  9.9833e-02,  9.9500e-01,  9.9998e-03, 9.9995e-01,  1.0000e-03,  1.0000e+00],<br>         [ 9.0930e-01, -4.1615e-01,  1.9867e-01,  9.8007e-01,  1.9999e-02, 9.9980e-01,  2.0000e-03,  1.0000e+00],<br>         [ 1.4112e-01, -9.8999e-01,  2.9552e-01,  9.5534e-01,  2.9995e-02, 9.9955e-01,  3.0000e-03,  1.0000e+00],<br>         [-7.5680e-01, -6.5364e-01,  3.8942e-01,  9.2106e-01,  3.9989e-02, 9.9920e-01,  4.0000e-03,  9.9999e-01],<br>         [-9.5892e-01,  2.8366e-01,  4.7943e-01,  8.7758e-01,  4.9979e-02, 9.9875e-01,  5.0000e-03,  9.9999e-01],<br>         [-2.7942e-01,  9.6017e-01,  5.6464e-01,  8.2534e-01,  5.9964e-02, 9.9820e-01,  6.0000e-03,  9.9998e-01],<br>         [ 6.5699e-01,  7.5390e-01,  6.4422e-01,  7.6484e-01,  6.9943e-02, 9.9755e-01,  6.9999e-03,  9.9998e-01],<br>         [ 9.8936e-01, -1.4550e-01,  7.1736e-01,  6.9671e-01,  7.9915e-02, 9.9680e-01,  7.9999e-03,  9.9997e-01],<br>         [ 4.1212e-01, -9.1113e-01,  7.8333e-01,  6.2161e-01,  8.9879e-02, 9.9595e-01,  8.9999e-03,  9.9996e-01],<br>         [-5.4402e-01, -8.3907e-01,  8.4147e-01,  5.4030e-01,  9.9833e-02, 9.9500e-01,  9.9998e-03,  9.9995e-01],<br>         [-9.9999e-01,  4.4257e-03,  8.9121e-01,  4.5360e-01,  1.0978e-01, 9.9396e-01,  1.1000e-02,  9.9994e-01],<br>         [-5.3657e-01,  8.4385e-01,  9.3204e-01,  3.6236e-01,  1.1971e-01, 9.9281e-01,  1.2000e-02,  9.9993e-01]]])</pre><p>as we see for the token 0 we calculate the Positional Embedding manually they are correct as per the output we can see.</p><h4>Apply to the words</h4><pre>pe = pe.unsqueeze(0) # apply the batch dim<br>words = words.unsqueeze(0) # apply the batch dim<br>word = words + (pe[:, :words.shape[1], :])</pre><pre>#word output <br>tensor([[[2.2336e+04, 1.0000e+01, 2.0000e+00, 9.0000e+00, 5.0000e+00, 1.0000e+01, 7.0000e+00, 9.0000e+00],<br>         [3.0840e+04, 4.5403e+00, 4.0998e+00, 3.9950e+00, 8.0100e+00, 4.9999e+00, 1.0010e+00, 1.0000e+01],<br>         [1.0920e+04, 8.5839e+00, 6.1987e+00, 7.9801e+00, 7.0200e+00, 2.9998e+00, 5.0020e+00, 3.0000e+00],<br>         [1.3141e+01, 6.0100e+00, 6.2955e+00, 9.9553e+00, 7.0300e+00, 6.9995e+00, 7.0030e+00, 3.0000e+00],<br>         [1.1012e+03, 7.3464e+00, 8.3894e+00, 5.9211e+00, 5.0400e+00, 5.9992e+00, 5.0040e+00, 7.0000e+00],<br>         [5.9504e+02, 5.2837e+00, 1.4794e+00, 9.8776e+00, 8.0500e+00, 4.9988e+00, 8.0050e+00, 9.0000e+00],<br>         [2.0517e+03, 1.9602e+00, 6.5646e+00, 3.8253e+00, 9.0600e+00, 3.9982e+00, 5.0060e+00, 7.0000e+00],<br>         [5.8847e+03, 1.7539e+00, 6.6442e+00, 2.7648e+00, 5.0699e+00, 8.9976e+00, 3.0070e+00, 3.0000e+00],<br>         [5.0470e+03, 3.8545e+00, 1.7174e+00, 3.6967e+00, 5.0799e+00, 5.9968e+00, 6.0080e+00, 2.0000e+00],<br>         [4.0734e+03, 6.0889e+00, 4.7833e+00, 9.6216e+00, 8.0899e+00, 9.9960e+00, 5.0090e+00, 6.0000e+00],<br>         [4.1935e+03, 4.1609e+00, 6.8415e+00, 2.5403e+00, 3.0998e+00, 9.9950e+00, 3.0100e+00, 5.9999e+00],<br>         [2.9922e+04, 2.0044e+00, 6.8912e+00, 3.4536e+00, 8.1098e+00, 9.9940e+00, 5.0110e+00, 2.9999e+00],<br>         [1.2095e+03, 1.8439e+00, 9.9320e+00, 7.3624e+00, 8.1197e+00, 1.9928e+00, 6.0120e+00, 7.9999e+00]]])</pre><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XGdKHCkibjNG4yy-.png" /><figcaption><a href="https://pub.towardsai.net/the-quest-to-have-endless-conversations-with-llama-and-chatgpt-%EF%B8%8F-81360b9b34b2">Source</a></figcaption></figure><p>Positional embeddings allow Transformers to capture sequence order, which is a very important feature in tasks such as translation and summarization. They are simple and effective.</p><h3>References</h3><ul><li><a href="https://arxiv.org/pdf/1706.03762"><strong>Attention is all you need</strong></a></li><li><a href="https://kazemnejad.com/blog/transformer_architecture_positional_encoding/">Amirhossein Kazemnejad’s Blog</a></li><li><a href="https://ut.philkr.net/deeplearning/pdf/transformers/positional_embeddings.pdf">Some random Presentation</a></li></ul><blockquote><strong>Thank you and please motivate me to give one upvote, Clap</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfaacf6387a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why We Need “Distributed Training” in Deep Learning? ]]></title>
            <link>https://ruhaan838.medium.com/why-we-need-distributed-training-in-deep-learning-bf48031c3d98?source=rss-4c6876ef79ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf48031c3d98</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ruhaan838]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 12:30:23 GMT</pubDate>
            <atom:updated>2024-12-13T12:30:23.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*cRi4Fz4WsWzJoYI0.jpg" /><figcaption>(<a href="https://stock.adobe.com/in/search?k=%22high+demand%22&amp;asset_id=1034805999"><strong>Source</strong></a><strong>)</strong></figcaption></figure><h3>Why do We Need “Distributed Training” in Deep Learning? 🤔</h3><h3>💪 Motivation</h3><p>We know that in the age of the internet, we have a much larger amount of data, and if we need to train our <strong>AI model on that large amount of data</strong>, we need more <strong>complex models</strong>. If your data and model are too complex, then we must have a <strong>great and powerful device</strong> for it so that we can train those AI models. To solve that problem, either we can build a more powerful device or use “<strong>Distributed training” </strong>across all devices.</p><h3>👋 Introduction</h3><p>So, what is Distributed Training? How does it work?</p><h4>What is Distributed training?</h4><p>Consider you have a Large amount of Data, for example, the entire Internet, and you have to train your LLM on it. To train this model on a single GPU it’s quite more difficult. <strong>There are some challenges that you may face</strong>:</p><ol><li>The model may not fit into a single GPU. <strong>(Large model)</strong></li><li>Due to the large dataset, you choose the bigger batch size but GPU has limited Memory so you can’t. <strong>(Larger Dataset)</strong></li><li>Models take too much time to train because of the larger dataset. Probably Months, Years, etc. <strong>(Smaller Device)</strong></li></ol><h4>How does it work?</h4><p>You can <strong>scale</strong> your training process using <em>2 methods</em></p><ol><li>Vertically scaling.</li><li>Horizontal scaling.</li></ol><blockquote><strong><em>1. Vertically scaling</em></strong></blockquote><p>So <strong>vertically scaling is too simple</strong>, you have <strong>12GB RAM GPU</strong> increase the RAM to <strong>32GB RAM</strong>. Quite simply no need to change our original code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*qdlj8QAeBdb0ctEDxuR7GQ.png" /><figcaption>Vertical scaling — (Image by Author)</figcaption></figure><blockquote><strong><em>2. Horizontal scaling</em></strong></blockquote><p>So, Horizontal scaling has two types and it requires some sort of code changes.</p><ol><li>Data parallelism</li><li>Model parallelism</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0spsIuMBXiupg-53pQLEg.png" /><figcaption>Horizontal scaling — (Image by Author)</figcaption></figure><p>So, rather than change the configuration of the original device build the eco-system of the same device and train the model.</p><h3>📊 Data Parallelism vs 🖥️ Model Parallelism</h3><h4>1. Data Parallelism</h4><p>So, Data Parallelism works when your <strong>model can fit into a single GPU</strong>, then we distribute our <strong>data to multiple GPUs</strong>. With each of the GPUs processing a subset of the dataset and performing the <strong>forward and backward</strong> pass.</p><figure><img alt="Data Parallelism Diagram" src="https://cdn-images-1.medium.com/max/1024/1*_wxTNphhyYr6GFyAL5IbQQ.png" /><figcaption>Data Parallelism — (Image by Author)</figcaption></figure><p>As we can see in the Image we have <strong>4 GPUs</strong> with the same <strong>configurations</strong> and we can fit our model into <strong>1</strong> <strong>GPU</strong> so we divide the <strong>Dataset</strong> into <strong>SubDataset. </strong>In this process, we <strong>synchronize the gradients during the backward pass</strong>.</p><h4>⚙️ Perform the Distributed Data Parallel</h4><blockquote><em>Step-1: Initialized the model parameters on the Main GPU</em></blockquote><p>We initialized the model parameter randomly on the Main GPU where we are putting our code. We forward those initial values and parameters to the next GPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*jQIpFIRwwlBAqvwTYdq1AQ.png" /><figcaption>Step-1: Initialized the paramerters and forward to the other GPUs</figcaption></figure><blockquote><em>Step-2: Calculate the local gradient across all GPUs</em></blockquote><p>Each machine computes its gradient and accumulates that gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*OardDNDF6B7-6zDLhWTfZg.png" /><figcaption>Step-2: Local gredient caculation</figcaption></figure><blockquote><em>Step-3: Cumulate local gradient to Main GPU</em></blockquote><p>Now, we accumulate the gradient to the Main GPU. Next, we distribute this summed gradient to all GPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aY50j4Sxlbo46Gr4fWfIQ.png" /><figcaption>Step-3: Sum the all gradients.</figcaption></figure><blockquote><em>Step-4: Reset the gradient after updating the parameters.</em></blockquote><p>Last but not least the main process is to update the parameters and set the gradient to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*_6pgfiunW2L67YXmkKdCAA.png" /><figcaption>Step-4: update the parameters and set the grad to zero.</figcaption></figure><p>There are 2 main processes for sharing gradients. It’s called the <strong><em>“Collective Communication Primitives”. </em></strong>CCP allows us to communicate with different devices.</p><blockquote>Point-to-point: We distribute the gradient line.<br>Collective Communication Broadcast: We select one machine and its job is to share the gradients, while the main GPU distributes the gradients.</blockquote><h4>2. Model Parallelism</h4><p>So, Model Parallelism is Quite different from Data Parallelism. In Data Parallelism our model fits into one GPU. But <strong>what if?</strong> We have this strange problem that <strong>we can’t able to load our entire model into one GPU</strong>. <br>At this time the Model parallelism is very helpful. Model Parallelism allows us to Distribute our model into multiple GPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJlEpM_6wqBAG1-A4uq-hw.png" /><figcaption>Model Parallelism — (Image by Author)</figcaption></figure><p>So, Model parallelism is <strong>useful</strong> when your<strong> model is too large for your GPU</strong>. In that case, we <strong>distribute</strong> our model into multiple GPUs. The <strong>GPUs 1, 2, 3, and 4 contain Layers 1, 2, 3, and 4</strong> of a model. After distributing the Layers we performed the <strong>forward and backward pass</strong> for each layer in a synchronized manner.</p><h3>📈 Advantages and 📉Disadvantages</h3><p>Some of the advantages and Disadvantages of the Distributed training and also there is the advantage of Data Parallelism and Model Parallelism also disadvantage there.</p><h4>Advantages of Distributed Traning</h4><ul><li>So, In Distributed Training, if your task is too <strong>expensive for your GPU</strong> it solves that problem.</li><li>Also, allows you to train the <strong>large Model on a Large dataset</strong>.</li><li>Help to achieve the best results by adjusting the Perfect Hyperparameters.</li></ul><h4>Disadvantages of Distributed Traning</h4><ul><li>At some point what if? Our one <strong>Machine has failed</strong> if we don’t take care of that we<strong> lose the whole process</strong>.</li><li>Sometimes it’s too complicated to code the Data Parallelism and Model Parallelism. <strong>(not more thanks to Pytorch)</strong></li><li>Takes too much time just sharing the gradients and it slows down the process of training.</li></ul><h3>🙇🏻‍♂️Conclusion</h3><p>At some point “<strong>Distributed training”</strong> is not useful but it is necessary to train the larger and bigger and bigger model we must have some kind of mechanism that allows us to train the model with a limited amount of storage use case, also we can apply the “<strong>Quantization”</strong> that helps a lot for optimizing the model.</p><blockquote><em>🙏🏻 Special thanks to </em><a href="https://www.youtube.com/@umarjamilai"><strong><em>Umar Jamil</em></strong></a><em> without their </em><a href="https://youtu.be/toUSzwR0EV8?si=wiWHrbQS7Hrzj_kM"><strong><em>video</em></strong></a><em> this blog is never possible.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf48031c3d98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linformer: Making Transformers Linear, Efficient, and Scalable]]></title>
            <link>https://ruhaan838.medium.com/linformer-making-transformers-linear-efficient-and-scalable-84f21880ea02?source=rss-4c6876ef79ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/84f21880ea02</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <dc:creator><![CDATA[Ruhaan838]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 11:09:19 GMT</pubDate>
            <atom:updated>2024-12-08T11:09:19.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>💪 Motivation</h3><p>We all know the Transformer revolutionized the AI world after the Paper came <em>Attention is all you need</em>, The Model Transformer can perform very long sequence tasks and make fewer errors than other models like RNN, CNN, etc. The Major problem with the Transformer is that it requires a lot of computation power.</p><h3><strong>👋 Introduction</strong></h3><p>So, our traditional transformer Proposed in <em>Attention is all you need</em>. The paper solves the biggest problem of RNN (Recurrent Neural Network), <strong>gradient vanishing</strong>, but the Transformer requires too much time and computation to train and evaluate. To solve this problem the Linformer is come out, The model proposed by “<strong><em>Sinong Wang, Belinda Z. Li, Madian Khabsa, Han Fang, and Hao Ma”</em></strong> In the paper,</p><blockquote><a href="https://arxiv.org/pdf/2006.04768">Linformer: Self-Attention with Linear Complexity<br>Sinong Wang, Belinda Z. Li, Madian Khabsa, Han Fang, Hao Ma Facebook AI, Seattle, WA</a></blockquote><p>So the Linformer allows you to compute the Attention with sequence length.</p><h3><strong>🪫 Power Hunger: Transformer</strong></h3><p>The Transformer has too much Power hunger. It uses the NxN matrix multiplication where the N is too large, like 512, 1024, etc. so the NxN matrix multiplication happens too many times which is too expensive to the device, and takes a lot of memory and time. To solve this so many papers came out one of these is <strong>Linformer</strong>.</p><h3>💡 Linformer Self-Attention vs Traditional Self-Attention</h3><p>Let’s look at the high-level comparison between the Linformer vs Traditional Transformer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gFiZFFDSuJWhYnUAJiYYA.png" /><figcaption>Fig.1: Multihead Attention and Linformer Multihead Attention (<a href="https://arxiv.org/pdf/2006.04768"><strong>Source</strong></a><strong>)</strong></figcaption></figure><h4>Transformer High-Level Flow</h4><p>On the top of Fig.1, we show the traditional equation of the Transformer&#39;s multihead attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-b8zIXKa8YW3xxRzWNDA-w.png" /><figcaption>Fig.2: (left) Scaled Dot-Product Attention. (right) Multi-head attention consists of several attention layers running in parallel. (<a href="https://arxiv.org/pdf/1706.03762"><strong>Source</strong></a>)</figcaption></figure><p>The input first passes through the linear projection and next calculates the scaled Dot-Product Attention (Self-Attention).</p><p>We perform this operation for D_model / head_size. Then concat this all Self-Attention block and again pass through the linear block.</p><h4>Linformer Idea</h4><p>At the bottom of Fig.1, there is the equation for performing the linear Self-Attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CWFDL5AM5oYY6NrJzcvWw.png" /><figcaption>Fig.3: Visual Representation of Fig.1 bottom equation (<a href="https://arxiv.org/pdf/2006.04768"><strong>Source</strong></a>)</figcaption></figure><p>So in simple words, the informer has two special shared parameters which are called “<strong>two linear projection matrices</strong>” These parameters are learnable the dimensions of these parameters are “<strong><em>k x n”,</em></strong> Throughout the blog these parameters are called the “<strong><em>E</em> and <em>F</em></strong><em>”</em> are the distribute over the Key and Value.</p><p>The first project is the original <strong><em>“n x d”</em></strong> Key and value to the <strong><em>“k x d”</em></strong> and then applying the Attention like the Traditional Transformer as shown in Fig. 3.</p><h3>❓How does the Linformer calculate the Attention?</h3><p>To calculate the Linformer Attention first project the original “<strong><em>n x d” </em></strong>— dimensional key and value layer <em>Wk(Ki) </em>and <em>Wv(Vi) </em>into <strong><em>“k x d”</em></strong> dimensional projected key and value layers.</p><p>Note the Fig.1 bottom equation requires the <em>O(nk) </em>time and space complexity. If we select the projected dimension <em>k </em>such that <em>k &lt;&lt; n </em>then we can reduce the amount of memory and time.</p><h3>🌐 Parameter Sharing</h3><p>One thing that Linformer&#39;s paper authors describe is that share parameters for the linear projection matrics<em> Ei, Fi </em>across the layers and heads, there are 3 ways to do that.</p><ul><li><strong>Headwise sharing: </strong>For each layer define the <em>E</em> and <em>F</em> same such as <em>Ei = E </em>and <em>Fi = F </em>for all heads <em>i.</em></li><li><strong>Key-value sharing:</strong> For each layer define the E as a primary parameter <em>Ei = Fi = E </em>for each key-value projection for all heads <em>i</em>.</li><li><strong>Layerwise sharing:</strong> For each layer use the single matrix E across all layers.</li></ul><h3>🧑🏻‍💻 Some Coding Guidelines</h3><p>“<em>See 🐈‍⬛ </em><a href="https://github.com/Ruhaan838/Linformer-pytorch"><em>GitHub</em></a><em> for the full code”</em></p><p>So in this, I try to make the Attention mechanism more simple reliable, and much more readable so you can relate this to the equations.</p><h4>Linformer Self Attention</h4><pre>class LinearSelfAttention(nn.Module):<br>    def __init__(self, d_model:int, seq_len:int, k:int, d_k:int, headwise_sharing:bool=True, key_val_sharing:bool=False, dropout:float=0.2):<br>        &quot;&quot;&quot;LinearSelfAttention args<br><br>        Args:<br>            d_model (int): eg. 512, 1024 ...<br>            seq_len (int): eg. 6, 1000, 20000 ...<br>            k (int): Reduction Term as per the paper<br>            d_k (int): d_model // head<br>            dropout (float, optional): Dropout Rate. Defaults to 0.2.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        <br>        self.d_model = d_model<br>        self.seq_len = seq_len<br>        self.k = k<br>        self.d_k = d_k<br>        self.dropout = nn.Dropout(dropout)<br>        self.headwise_sharing = headwise_sharing<br>        self.key_val_sharing = key_val_sharing<br><br>        self.E = nn.Linear(seq_len, k)<br>        self.F = nn.Linear(seq_len, k) if headwise_sharing else self.E if key_val_sharing else None<br>        <br>        assert(self.F is not None), &quot;At least one sharing is require to perform the Linear Attention.&quot;<br>    <br>    def forward(self, q, k, v, mask=None):<br>        <br>        K = k.transpose(-1, -2)<br>        K_ = self.E(K)<br>        <br>        attention = (q @ K_) / math.sqrt(self.d_k)<br><br>        if mask:<br>            mask = torch.triu(torch.ones((self.seq_len, self.k))).bool().to(q.device)<br>            attention.masked_fill_(mask == 0, -1e9)<br>        <br>        attention = attention.softmax(dim=-1)<br>        <br>        attention = self.dropout(attention)<br>        <br>        V = v.transpose(-1, -2)<br>        V_ = self.F(V)<br>        V_ = V_.transpose(-1, -2)<br>        return attention @ V_ </pre><h4>Multihead Attention</h4><pre>class MultiHeadAttention(nn.Module):<br>    def __init__(self, d_model:int, seq_len:int, k:int, head:int, <br>                 headwise_sharing:bool=True, key_val_sharing:bool=False ,dropout:float=0.2):<br>        &quot;&quot;&quot;MultiHeadAttention<br><br>        Args:<br>            d_model (int)<br>            seq_len (int)<br>            k (int) <br>            head (int) <br>            dropout (float, optional). Defaults to 0.2.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        <br>        assert d_model % head == 0, &quot;D_model is must divided by the head&quot;<br>        <br>        self.d_model = d_model<br>        self.seq_len = seq_len<br>        self.k = k<br>        self.head = head<br>        self.d_k = d_model // head<br>        <br>        self.Wk = nn.Linear(d_model, d_model, bias=False)<br>        self.Wq = nn.Linear(d_model, d_model, bias=False)<br>        self.Wv = nn.Linear(d_model, d_model, bias=False)<br>        <br>        self.Wo = nn.Linear(d_model, d_model, bias=False)<br>        <br>        self.self_attention = LinearSelfAttention(self.d_k, seq_len, k, self.d_k, headwise_sharing, key_val_sharing, dropout)<br>        <br>    def forward(self, q, k, v, mask=None):<br><br>        q = self.Wq(q)<br>        k = self.Wk(k)<br>        v = self.Wv(v)<br>        <br>        query = q.view(q.shape[0], q.shape[1], self.head, self.d_k).transpose(1, 2) <br>        key = k.view(k.shape[0], v.shape[1], self.head, self.d_k).transpose(1, 2)<br>        value = v.view(v.shape[0], v.shape[1], self.head, self.d_k).transpose(1, 2)<br><br>        attention_score = self.self_attention(query, key, value, mask)<br>        <br>        x = attention_score.transpose(1, 2).contiguous().view(attention_score.shape[0], -1, self.head*self.d_k)<br>        <br>        return self.Wo(x)<br><br>if __name__ == &quot;__main__&quot;:   <br>    m = MultiHeadAttention(512, 6, 256, 8, True, False)<br>    mask = torch.triu(torch.ones((1, 1, 256)), diagonal=1)<br>    mask = mask == 0<br>    a = torch.randn(1, 6, 512)<br>    print(m(a, a, a, mask).size())</pre><h3>🧾 Result (from paper)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUM4Rza684jJewCsdNpahQ.png" /><figcaption>inference time vs. sequence length for various Linformer models (<a href="https://arxiv.org/pdf/2006.04768"><strong>Source</strong></a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTopI6rNFYQMX1QvfA5ouw.png" /><figcaption>Inference-time efficiency improvements of the Linformer over the Transformer, across various projected dimensions k and sequence lengths n. The left table shows time saved. The right table shows the memory saved. (<a href="https://arxiv.org/pdf/2006.04768"><strong>Source</strong></a>)</figcaption></figure><p>Here the results clearly show that the D_model is not affecting the time complexity of the model. The model is run at a constant time over changes in the D_model.</p><h3>🔖 Reference and links</h3><ul><li><a href="https://arxiv.org/pdf/2006.04768">Linformer: Self-Attention with Linear Complexity</a></li><li><a href="https://arxiv.org/pdf/1706.03762">Attention Is All You Need</a></li><li>Special Thanks to <a href="https://github.com/hkproj">hkproj</a> 🙏🏻</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84f21880ea02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>