<?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 Tarique Anwar on Medium]]></title>
        <description><![CDATA[Stories by Tarique Anwar on Medium]]></description>
        <link>https://medium.com/@tariqanwarph?source=rss-51a892d92c1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SGfdWw0krDF21Oi3.jpg</url>
            <title>Stories by Tarique Anwar on Medium</title>
            <link>https://medium.com/@tariqanwarph?source=rss-51a892d92c1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:24:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tariqanwarph/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[Activation function and GLU variants for Transformer models]]></title>
            <link>https://medium.com/@tariqanwarph/activation-function-and-glu-variants-for-transformer-models-a4fcbe85323f?source=rss-51a892d92c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4fcbe85323f</guid>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tarique Anwar]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 06:30:01 GMT</pubDate>
            <atom:updated>2022-04-26T17:59:56.915Z</atom:updated>
            <content:encoded><![CDATA[<p>Characterizing the first week of April 2022 as <strong>happening</strong> in the field of AI and Deep Learning would be an understatement. Within the same week, Google and OpenAI showcased their models <strong>PaLM⁶</strong> and <strong>DALLE 2.</strong></p><p><strong>PaLM</strong> is a 540 billion parameter transformer-based language model seemingly capable of a state-of-the-art performance on a multitude of tasks in natural language. In addition to those, breakthrough capabilities are also demonstrated in reasoning tasks. <strong>DALLE 2</strong> is an AI model which can create realistic images and art from a description in natural language, the architecture of which is also based on a transformer.</p><p>The results of both these models are nothing short of astonishing and if you haven’t already, do check them out.</p><p>Now, this article is not about those models, their overall architecture or wonderful results, but just on a very small but important aspect of these or any deep learning models, the <strong>activation function</strong>. Also, we will look into how variants of <strong>Gated Linear Units (GLU)</strong> (I’ll define this later) improve these models. I’ll assume that you have seen activation functions(<strong>sigmoid</strong> and <strong>ReLU</strong>) in practice and how it is applied in a perceptron of a neural network.</p><h3>Sigmoid and ReLU</h3><p>Activation functions are a way to introduce nonlinearity to neural networks. Without this non-linearity, the overall learned function would be linear which cannot account for the complex nonlinear relationships that a neural network needs to learn.</p><p>In the initial days of deep learning, the <strong>sigmoid</strong> was used as an activation function with its functional form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*x3t0jxiGN530kMrSsu4M7g.png" /></figure><p>But it came with its own issues, primarily which were outright failure to converge or very slow convergence.</p><p><strong>ReLU</strong> or Rectified Linear unit seemed to ‘rectify’ those issues and has been the standard ever since. The functional form of <strong>ReLU</strong> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*HRj5TWPKD8rT5Dz04DYaQA.png" /></figure><p>The main reason for ReLu being used is that it is simple, fast, and empirically it seems to work well.</p><p>But with the emergence of Transformer based models, different variants of activation functions and GLU have been experimented with and do seem to perform better. Some of them are:</p><ul><li><strong>GeLU²</strong></li><li><strong>Swish¹</strong></li><li><strong>GLU³</strong></li><li><strong>GEGLU⁴</strong></li><li><strong>SwiGLU⁴</strong></li></ul><p>We will go over some of these in detail but before that let’s see where exactly are these activations utilized in a Transformer architecture.</p><h3>Feed Forward Layer in a Transformer</h3><p>The Transformer⁵ alternates between a multi-head attention layer and what is called position-wise feed-forward networks(FFN). The encoder architecture from the original transformer paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*KyqdUzEHXZNtvGh-HYrWGg.png" /><figcaption>The encoder in a Transformer architecture</figcaption></figure><p>I will not be going into the details of the attention layer since it&#39;s not important for our discussion. I will provide links below to some excellent resources if you want to get into the details of it.</p><p>Now, we will simplify and just look at the Attention and FFN layer.</p><p>The attention layer takes in a sequence of vectors (Input embeddings) and outputs a similar length sequence of vectors. The FFN takes the vectors and passes them through two linear learned transformations (represented by matrices <strong>W₁</strong> and <strong>W₂</strong> and bias <strong>b₁</strong> and <strong>b₂</strong>). A ReLU activation function is applied between the two linear transformations (in other words matrix multiplications).</p><p>Functionally it can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*y778pJY5GSUGQ_18movbPA.png" /></figure><p>In the original transformer paper, the author described the above operation as two convolutions with kernel size 1. The dimensionality of input and output remains the same.</p><p>In subsequent implementations, It was further refined to a version without bias with no loss in performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*yjEtjU6XT20QK9u2DRKDng.png" /></figure><p>Visualizing the simplified pass from text through the self-attention block to FFN and output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*yQhAGoC5PIPXtew6FCEJ4w.png" /></figure><p>I have made some simplification in the embedding layer and also not shown the Add and Norm layer in the pass above to make it simpler. But this captures essentially what occurs and where the activation function, in this case, ReLU is being used.</p><p><strong>ReLU</strong> was still being used in the original transformer paper but subsequently, we have seen some other activations being utilized. Two of the most used ones are:</p><h3>GELU</h3><p>The functional form of a Gaussian error linear unit is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*fCesYsEIZ3StikGQ1v346g.png" /></figure><p>where erf is the Gaussian error function given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*NDcqDgvEZvPb4FfThJm_XA.png" /></figure><p>Now, if all these equations don’t make a lot of sense, let&#39;s visualize them graphically. A graph of <strong>GELU </strong>with <strong>ReLU </strong>is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*2peVOHqeoVB_XEG_rOfjvA.png" /></figure><p><strong>GELU</strong> combines the effect of the dropout, zone out, and ReLUs. ReLU and dropout yield a neuron’s output to zero or one with ReLU performing this deterministically and dropout doing this stochastically. So in this setting inputs have a higher probability of being dropped as x decreases so the transformation applied to x is stochastic and depends on the input as well. <strong>GELU</strong> overcomes the limitation of <strong>ReLU</strong> being non-differentiable at zero.</p><p>Across several experiments with MNIST, CIFAR-10, and other datasets as showcased in the paper, <strong>GELU</strong> outperforms other activation functions in terms of test accuracy while it also bears semblance to <strong>ReLU.</strong></p><p><strong>GELU</strong> is the activation that has been used in the <strong>GPT</strong> large language models by OpenAI. So as shown earlier in the feed-forward pass, <strong>GELU</strong> was used in place of the <strong>ReLU.</strong></p><h3>Swish</h3><p>The functional form of <strong>Swish¹</strong> is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*0fGSoYXKyilCO05uTg7n2A.png" /></figure><p>Here β is a parameter that can be trained.</p><p>Graphing out <strong>Swish </strong>w.r.t <strong>ReLU </strong>for different values of β:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*GGr1tWQ2vyiq1cjdEMIcxw.png" /></figure><p>As we see that with an increasing value of β, <strong>Swish</strong> resemblance becomes closer to <strong>ReLU. Swish</strong> can be loosely viewed as a smooth function that non-linearly interpolates between the linear function and the ReLU function. The degree of interpolation can be controlled by the model if β is set as a trainable parameter.</p><p>Like <strong>GELU, Swish</strong> is also differentiable at zero.</p><p>Swish was found using automatic search techniques to discover novel activation functions with strong empirical performance. Replacing Swish with ReLU in deeper models with various experiments done on CIFAR, Imagenet, and Machine translation tasks yielded better results.</p><h3>Gated Linear Units</h3><p>GLUs were introduced in a language modeling paper, which is a neural network layer defined as the component-wise product of two linear transformations(matrix multiplication) of the input one of which was Sigmoid activated. This was the first time a non-recurrent approach was competitive with strong recurrent models on some large-scale language tasks before the advent of transformers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*OAXVJZDNbThZWXAkKqVf2A.png" /></figure><p>Here we see we have two trainable matrices <strong>W</strong> and <strong>V</strong> with <strong>V</strong> being used to calculate the gated unit. The gate provides an additional filter after the activation which can be learned during training and depends on the input itself. The ⊗ operation is the element-wise multiplication.</p><p>Visualizing GLU in terms of matrix operations without the bias matrices <strong>b</strong> and <strong>c</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*5EKhmH8ilnAbTuqiJ-FQ8w.png" /></figure><p>We see that the overlapping matrix entries as shown in the last operation above are multiplied together so the output of <strong>xV+c </strong>acts as a filter for the other half of the operation. So depending on what the matrix values are in the filter, those same entries become prominent or are diminished from the sigmoid activation matrix.</p><h4>ReGLU, GEGLU and SwiGLU</h4><p>Instead of sigmoid, we can use other activations as well in the GLU. <strong>ReGLU, GEGLU, </strong>and <strong>SwiGLU</strong> are exactly as the name suggests, the sigmoid being replaced with those activations respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*YGsIApL8dGD-oThkjkG_Mw.png" /></figure><p>As we saw earlier, the <strong>FFN </strong>of a transformer using <strong>ReLU </strong>activation<strong> </strong>was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*ZZrO3hZfpYT1VjBGTaw54A.png" /></figure><p>Replacing the <strong>ReLU </strong>part in <strong>FFN </strong>with the <strong>GLU </strong>variants we’ll have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*BL3LzYA3jAxOqY9NcFgEoA.png" /></figure><p>We observe that all these layers have three weight matrices(<strong>W, V,</strong> and <strong>W₂</strong>), as opposed to two in the original FFN. So, to keep the amount of computation constant, the number of hidden units(the second dimension of <strong>W and V,</strong> and the first dimension of <strong>W₂</strong>) is reduced by a factor of <strong>2/3 </strong>and then the comparison is made on the performance.</p><p>These GLU variants performed better in many downstream language understanding tasks and these were simple architectural changes without any computational drawbacks. As to why they seem to perform better, we have a quote from the paper,</p><blockquote><strong><em>We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence.</em></strong></blockquote><p>Owing to these results and a significant increase in quality compared to standard <strong>ReLU</strong>, <strong>GeLU</strong>, or <strong>Swish</strong> activations, the authors of the <strong>PaLM⁶</strong> model decided to use <strong>SwiGLU</strong> activation for Multilayer perceptron(MLP) intermediate activations.</p><h3>What’s next?</h3><p>ReLU is still one of the most used activation function as it is fast, simple, and works well for a whole range of tasks. But with <strong>GELU</strong> and <strong>Swish,</strong> we have viable alternatives with complementing properties that seem to work better in a lot of tasks. Combining these activations with GLU and using them in the <strong>FFN</strong> of a transformer’s attention layer leads to quality improvements over the typically used <strong>ReLU</strong> or <strong>GELU</strong> activations.</p><p>If anything, this highlights the importance of a carefully chosen activation function to the overall performance of the model in terms of training time and evaluation metrics on test data.</p><p>Have we arrived at the perfect activation(at least for transformer models) in these <strong>GLU</strong> variants? I strongly believe, <strong>not</strong>.</p><p>Is there a perfect activation function that would work well for all kinds of models?</p><p>Or maybe there would be an entirely novel way to introduce non-linearity and emulate the properties of an activation function that won’t depend entirely on the person training the model.</p><p>With new methods being tried out and experimented with, maybe we will find out.</p><p>If you’re interested in the transformer architecture, links to some amazing resources along with the original paper are below:</p><p><a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></p><p><a href="https://jalammar.github.io/illustrated-transformer/">https://jalammar.github.io/illustrated-transformer/</a></p><p><a href="https://medium.com/towards-data-science/attn-illustrated-attention-5ec4ad276ee3">https://medium.com/towards-data-science/attn-illustrated-attention-5ec4ad276ee3</a></p><h3>References</h3><p>[1] Ramachandran, P., Zoph, B., &amp; Le, Q. V. (2017). <a href="https://arxiv.org/pdf/1710.05941.pdf">Searching for Activation Functions.</a></p><p>[2] Hendrycks, D., &amp; Gimpel, K. (2016). <a href="https://arxiv.org/pdf/1606.08415.pdf">Gaussian Error Linear Units (GELUs)</a>.</p><p>[3] Dauphin, Y. N., Fan, A., Auli, M., &amp; Grangier, D. (2016). <a href="https://arxiv.org/pdf/1612.08083.pdf">Language Modeling with Gated Convolutional Networks</a>.</p><p>[4] Shazeer, N. (2020). <a href="https://arxiv.org/pdf/2002.05202.pdf">GLU Variants Improve Transformer</a>.</p><p>[5] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., &amp; Polosukhin, I. (2017). <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a>.</p><p>[6] Chowdhery et. al . <a href="https://arxiv.org/pdf/2204.02311.pdf">PaLM: Scaling Language Modeling with Pathways</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4fcbe85323f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>