<?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 Arunim on Medium]]></title>
        <description><![CDATA[Stories by Arunim on Medium]]></description>
        <link>https://medium.com/@arunim756?source=rss-675374b48244------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SH-33l4kcEV8wfMO</url>
            <title>Stories by Arunim on Medium</title>
            <link>https://medium.com/@arunim756?source=rss-675374b48244------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arunim756/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[Mixture of Experts: From Intuition to Training Reality]]></title>
            <link>https://medium.com/@arunim756/mixture-of-experts-from-intuition-to-training-reality-70c5b873333b?source=rss-675374b48244------2</link>
            <guid isPermaLink="false">https://medium.com/p/70c5b873333b</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mixture-of-experts-ai]]></category>
            <dc:creator><![CDATA[Arunim]]></dc:creator>
            <pubDate>Sat, 02 May 2026 18:32:13 GMT</pubDate>
            <atom:updated>2026-05-02T18:32:13.823Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This blog is based on what I learnt from the <a href="https://youtu.be/LPv1KfUXLCo?si=ujfbVhh9GBOfBepw">Stanford CS336N Lecture 4 on Mixture of Experts</a>, along with the key papers explained in the <a href="https://huggingface.co/blog/moe">Hugging Face MOE Blog</a>, that shaped the field. If you want to follow along with the primary sources, video lecture and its<a href="https://github.com/stanford-cs336/spring2025-lectures/blob/main/nonexecutable/2025%20Lecture%204%20-%20MoEs.pdf"> corresponding course material</a>s are great starting points.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2cNcdVPgkOysSbaFf4UKg.png" /></figure><h3>What Even is a Mixture of Experts?</h3><p>The basic concept behind an MOE is relatively simple: instead of running every input through one big Feed Forward Layer Network (FFN), you run it through one of many smaller feedforward layer networks (which are actually called experts), depending on what the input looks like. A lightweight learned “router”, which is just a linear layer, looks at the token embeddings and decides which expert (or experts) should process it.</p><p>MOEs are mainly categorized in two ways:</p><ol><li><strong>Dense MOE</strong>: Every token is processed by all the experts, and the outputs are combined using a weighted sum. This is conceptually the cleanest and direct version of MOE, but it mainly defeats the real purpose of an MOE, i.e, a larger model but fewer computations.</li><li><strong>Sparse MOE</strong>: Each token is routed to only a small subset of experts, typically Top-1 or Top-2, and only those experts do the computations. The rest of the experts sit idle. This is actually what modern LLMs use during MOE computations, because it lets you massively increase the number of parameters in a model without proportionally increasing the FLOPs per token.</li></ol><p>Notice the power of Sparse MOE here: no matter how many experts you add, your per-token compute stays fixed. Routing each token to just 2 out of 64 experts, and adding more experts costs you <em>nothing</em> in FLOPs. You are getting a much larger model for essentially free, paying only in memory and not in computation.</p><p><a href="https://arxiv.org/pdf/1701.06538"><em>Shazeer et al. (2017) — “Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer”</em></a><em> </em>made this practical for the deep learning era, by introducing the Sparsely-Gated MOE layer. They trained LSTM-based models with up to <strong>137 billion parameters</strong> by stacking sparse MOE Layers between recurrent layers, demonstrating that you could scale parameter counts massively without the compute cost blowing up. (See Image Below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*3QZk1jrFyOspOmn0zukpaQ.png" /><figcaption>Taken from the paper <a href="https://arxiv.org/pdf/1701.06538"><em>Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer</em></a></figcaption></figure><h3>Why are MOEs Getting Popular (And why Are They So Hard?)</h3><p>Now, let me show you exactly why MoEs are getting so much attention, and the reasons are hard to ignore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ailUpH1S2qpIyrUnmntYSw.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2101.03961">Switch Transformers Paper</a></figcaption></figure><p><strong>Same FLOPs, better performance: </strong>Fedus et al. (2022) proposed <a href="https://arxiv.org/pdf/2101.03961"><em>Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity</em></a>,<em> </em>where they ran a clean experiment. Keeping the FLOP budget the same, vary the number of experts and observe the performance changes. What they observed (<strong>as given in the image above</strong>) is that as the number of experts increases consistently, the test loss reduces. The test loss curve (left) reduces monotonically from 1e to 256e experts, and the training curves (right) show Switch-Base 128e experts separating cleanly from T5-Base(bottom curve) across 4 x 10^(5) steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*fLP1rtPxoP1cN_WgbwWcbg.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2101.03961">Switch Transformers Paper</a></figcaption></figure><p><strong>Faster to Train:</strong> As we can see in the above image, Switch-Base with 64 experts reaches the same perplexity as T5-Base in one-seventh the training time, a roughly 7x wall-clock speedup. Later, <a href="https://arxiv.org/pdf/2409.02060">OLMoE</a> (Muennighoff et al., 2024) further validated this efficiency advantage, showing that MoE models train approximately 2x faster wall-clock than dense models with the same number of active parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*LvOgZ2p_rOeWNW_6hU9IpQ.png" /><figcaption>Taken from the Slide</figcaption></figure><p><strong>Competitive at the frontier: </strong>DeepSeek-V2 (236B total, 21B active) (<strong>see image above</strong>), DeepSeek-V3, Mixtral 8×22B, Llama 4 Maverick: essentially every top open model right now is an MoE. DeepSeek-V3 benchmarks above GPT-4o on MATH 500, MMLU-Pro, and Codeforces. The parameter-to-performance ratio is just hard to beat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*8H5CPxS8TxSv4me3NOEswA.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2006.16668">GShard Paper</a></figcaption></figure><p><strong>Naturally parallelizable (see image above):</strong> Each expert is an independent FFN. On a multi-GPU setup, you can place each expert on a different device and route tokens across hardware. This is expert parallelism, and it combines with data and model parallelism in ways that standard transformers can’t exploit. <a href="https://arxiv.org/pdf/2006.16668">GShard (Lepikhin et al., 2020)</a> scaled this to 600B parameter models across 2048 TPUs by tiling MoE layers across devices with all-to-all communication between them.</p><h4>But Why So Hard?</h4><p>Even though with so many advantages, MOEs have been historically avoided by a lot of practitioners for good reasons.</p><p><strong>Infrastucture Complexity: </strong>The efficiency gains from MoE only show up when you have enough GPUs to store all the experts in memory at once. In a data-parallel setup, each machine holds the full model, which means holding all expert weights, even if only a fraction is used per forward pass. As Fedus et al. explain, sparsity is good when many accelerators can collectively host the total parameter budget. Single-GPU or small-cluster training doesn’t get you much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*n2jccyJQA6HefKDtD14w8g.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2202.08906">ST-MOE Paper</a></figcaption></figure><p><strong>Training instability(see image above):</strong> Sparse models suffer from training instabilities that do not appear in dense transformers. <a href="https://arxiv.org/pdf/2202.08906">Zoph et al. (2022) — ST-MoE</a> documented loss spikes that can derail training entirely; they found that sparse models were unstable in roughly 1 out of every 3 runs. Their fix was a new auxiliary loss called the <strong>router z-loss</strong>, which stabilizes training without hurting model quality (More about this later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*3y1XRU4dsy53LrwJSivBhw.png" /><figcaption>Taken from Slide</figcaption></figure><p><strong>Heuristic training objectives:</strong> The fundamental problem with sparse routing is that the top-k selection is not differentiable. You cannot just backpropagate through a hard argmax. And the solutions that are used in practice are auxiliary balancing losses, which are admittedly heuristic, stitched onto the main objective rather than derived from first principles.</p><h3>What does an MOE Actually Look Like?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EGWr2QhXKUSL90pSzBUUA.png" /><figcaption>MOE Layer from the <a href="https://arxiv.org/pdf/2101.03961">Switch Transformer</a></figcaption></figure><p>Now let’s look at how MoE layers actually replace the standard layers inside a model.</p><h4><strong>Replacing the MLP:</strong></h4><p>The standard design, used in Switch Transformer, GShard, ST-MoE, Mistral, DeepSeek, and basically everything in practice today, replaces the feedforward sublayer in each transformer block with a sparse MoE layer. The attention sublayer is unchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*nvQlYSdbg1hFJdjl2BXX2g.png" /></figure><p>The above image shows what a Dense Transformer Block looks like. And now you replace FFN Layer with Sparse MoE (Router + N FFN Experts), you get an MoE block (see Image below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*ejxMGqaVMeEZ0uNcF-5hVg.png" /></figure><p>Each token’s representation is fed into the router, which produces a distribution over experts (p1, p2, p3, …, pN). The token is dispatched to the top-K experts (usually K=1 or 2), their outputs are weighted by the gating scores, and the result is summed and passed through the residual connection. We can look into it mathematically later in the section when we talk about how we train MoEs.</p><h4>Replacing the Attention (Less Common):</h4><p>A less explored variant applied the MoE idea to the attention heads rather than the FFN only. <a href="https://arxiv.org/pdf/2404.07413">JetMoE</a> and <a href="https://arxiv.org/pdf/2306.04640">ModuleFormer</a> explored this idea. Instead of just one Multi-head attention block, you have multiple attention modules, and a router sends each token to a subset of them. The primary motivation is computational efficiency, activating only a subset of the attention experts per token, which reduces the inference cost significantly. JetMoE activates 2 of 8 attention experts, thus cutting inference compute by roughly 70% compared to Llama2–7B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*DAaLrNCWLPneO15pgzJTdg.png" /><figcaption>Taken from JetMoE paper</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMUwpiSvgbUuDuy1_0CKCg.png" /><figcaption>Taken from ModuleFormer paper</figcaption></figure><h3>What Varies in an MoE?</h3><p>There are three main parameters in MoE which defines most of its design space:</p><ol><li><strong><em>Routing Function</em></strong></li><li><strong><em>Expert Sizes</em></strong></li><li><strong><em>Training Objective</em></strong></li></ol><h4>Routing Function</h4><p>The routing function decides which expert processes which token. Nearly all modern systems boil down to “compute a score for each expert, pick the top-K”. But the mechanism behind the scoring and the direction of the choice vary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NYsOSanNfL7MGFkbU9QTA.png" /><figcaption>Taken from Slide</figcaption></figure><p><strong>Token-to-expert routing (token choice):</strong></p><p>Each token independently computes affinity scores for all experts and picks its top-k. This is the most used approach. Used in Switch Transformer (K=1), GShard (K=2), Mixtral (K=2), Grok (K=2), DBRX (K=4), Qwen (K=4), DeepSeek (K=7).</p><p><strong>Expert-to-token routing (expert choice):</strong></p><p>Each expert selects its Top-K tokens from the batch. This naturally balances load, every expert gets exactly the same number of tokens, but introduces a new problem, which is, some tokens might not get even selected by any expert and thus is not widely used.</p><p><strong>Global Routing via Optimization:</strong></p><p>Rather than local greedy decisions, frame routing as a global linear assignment and solve it optimally over the entire batch. BASE (Lewis et al., 2021) explored this. It eliminates load imbalance by construction, but is computationally heavier and has not displaced Top-K in mainstream models.</p><p><strong>Hash Routing:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiB3FT7z631n92S0g2j6oA.png" /><figcaption>Taken from Hash Layers For Large Sparse Models paper</figcaption></figure><p><a href="https://arxiv.org/pdf/2106.04426">Roller et al. (2021)</a> introduced the hash routing technique. Assign tokens to experts based on a hash of the token index. No learned parameters, perfectly balanced, but obviously cannot adapt to input content.</p><p><strong>Reinforcement Learning:</strong></p><p>One of the most common ideas to train a router, which could have come to your mind, is using Reinforcement Learning. Treat routing as a discrete decision and train the router with REINFORCE.</p><p><a href="https://arxiv.org/pdf/1511.06297">Bengio et al. (2016) “Conditional Computation in Neural Networks for Faster Models”</a> explicitly cast routing as an RL problem early on. <a href="https://arxiv.org/pdf/2202.01169">Clark et al. (2022) “Unified Scaling Laws for Routed Language Models”</a> revisited this in the context of large transformer-based language models and found that RL-based routing (RL-R) is of comparable effectiveness to standard top-k routing, but not dramatically better, while being considerably more complex. High gradient variance and implementation difficulty have kept RL-based routing from becoming standard.</p><p>Empirically, token-choice top-k routing consistently outperforms expert-choice routing in OlMoE ablations across training and validation metrics (Muennighoff et al., 2024, Section 4.1.4). Both routing types were compared under the same compute: 8 experts per MoE layer, with token choice activating 2 experts per token and expert choice using an equivalent capacity factor of 2.</p><h4>Expert Sizes</h4><p>The number of experts and their size is a separate axis of variation from the routing. Let me explain some of the variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUL8Ya6nrk9nfpz7X8nunA.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2401.06066">DeepSeekMoE paper</a></figcaption></figure><p><strong>Shared Experts &amp; Shared Experts Isolation:</strong></p><p>A few expert slots are always active for every token, regardless of the routing. These handle computation that is universally needed, freeing the routed experts to specialize.</p><p>For example, suppose you have N experts. Some are designated “shared” (always active), but the router still sees all N experts and can pick any one of them for top-k routing. So a shared expert might get selected by the router on top of being always on, meaning it processes the token twice, or wastes a routing slot on something that was going to run anyway.</p><p>That&#39;s why we have Shared Expert Isolation.</p><p>The pool of tokens is split into two completely separate groups:</p><ol><li><strong>Shared Experts (e.g. 2)</strong>: Always run, every token, no routing involved</li><li><strong>Routed Experts (e.g., 62)</strong>: The router picks top-K only from this group (not from the shared experts group).</li></ol><p>Thus, the router never even sees the shared experts, and thus, shared experts are isolated from the routing decision entirely.</p><p><strong>Fine-Grained Expert Segmentation(DeepSeek MoE):</strong></p><p>Rather than N experts each of size d_ffn, use 2N experts of size d_ffn/2. You route to 2k of the smaller experts. This increases routing granularity without increasing the per-token compute.</p><p>DeepSeek’s Ablation Studies show that Shared Experts and Fine Grained Expert Segmentation actually contribute to improvement in the overall performance (see image below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsGcW4dybkZNOBW6u0LpDw.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2401.06066">DeepSeekMoE paper</a></figcaption></figure><p>Let me show you how different recent MoE models set up their MoE parameters in their architecture, and this I found really interesting from the slide because it clearly shows the diversity and patterns across these parameters associated with MoE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdAhWEisrbajSuGWfhIu9g.png" /><figcaption>Taken from Slide</figcaption></figure><blockquote>The largest GLaM has 1.2 trillion parameters, which is approximately 7x larger than GPT-3. It consumes only 1/3 of the energy used to train GPT-3 and requires half of the computation flops for inference, while still achieving better overall zero-shot and one-shot performance across 29 NLP tasks.</blockquote><blockquote>(Taken from <a href="https://arxiv.org/abs/2112.06905">GLaM paper</a>)</blockquote><p>Now, after all this information about MoEs, you might have a clearer picture of just how fascinating they really are, and why they have become a cornerstone of SOTA LLM architectures. But there is still a crucial piece of the puzzle we haven’t touched, and that is how these giants are actually trained. And that&#39;s precisely where things get mathematically interesting. So tighten your seat belts, because we are about to dive in.</p><h3>How Do We Train MoEs?</h3><p>The fundamental challenge of training an MoE is that the router needs to learn which experts to activate for each token, and doing this efficiently, without collapsing to the same few experts or wasting compute, is harder than it sounds. The following approaches have been tried to tackle this:</p><p><strong>Approach 1: Reinforcement Learning</strong></p><p>Treat each routing decision as an action, use the task loss as a reward signal, and then train the router with REINFORCE.</p><p>In practice, the gradient variance from REINFORCE is high, the implementation is complex, and the improvement over simpler approaches is marginal. Thus, as of today, no major production model uses MoE where RL is used for routing.</p><p><strong>Approach 2: Stochastic Perturbation</strong></p><p>To understand why Stochastic Perturbation is needed, let’s first look at how the standard Top-K routing mechanism works, and where it falls short.</p><p>Suppose we have a token <em>U(t,l)</em> at layer <em>l</em>. So for each token <em>U(t,l)</em> at layer <em>l</em>, we compute an affinity score <em>S(i,t)</em> with every expert <em>i</em> by taking the dot product of the token embedding with a learned expert embedding <em>E(i,l) </em>(come from the learned Weight Matrix for routing), then normalizing across all experts via <em>Softmax</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*iIXk9YOOMWFaSEiz49WBOw.png" /></figure><p>This will give us the score of each expert for the <em>U(t,l) </em>token. And this will tell us <strong><em>how relevant the expert i, is for this token?</em></strong></p><p>But we don&#39;t want to activate all N experts, that defeats the purpose of sparsity. So we apply a hard Top-K filter. Only the K expert with the highest scores survives, and everyone else gets zeroed out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*sNN5MinVXtzsXmvdeTqMJw.png" /></figure><p>These <em>G(i,t) </em>values are the gates, sparse non-negative weights that sum to approximately 1.</p><blockquote><strong>Food for thought:</strong></blockquote><blockquote>Why am I saying approximately 1, why not exactly 1 ?, comment your answer down below</blockquote><p>Finally, the output of the MoE layer is just the gated weighted sum of the selected expert’s outputs, with a residual connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*G2MA7MC6k2ctmXG7HbVw-Q.png" /></figure><p>Thus, only the K non-zero gates actually trigger their FFN, and the rest are multiplied by zero and never computed. That&#39;s exactly where the efficiency of Sparse MoE comes from.</p><p>This is the classic Top-K routing mechanism. But there’s a subtle problem here; nothing in this formulation forces the router to distribute tokens evenly across the experts. So in practice, what happens is that the router quickly learns to favor a few popular experts and ignores the rest entirely, meaning most of your experts never get trained properly. This is called <strong>expert collapse</strong>, and it’s precisely what Stochastic Perturbation was designed to fix.</p><p>So, to start, let&#39;s first focus on the selection step itself.</p><p>Suppose we have scores for all the experts; so instead of simply zeroing out the non-selected ones, we send them to -infinity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*pd_lqwqp7xmf4mEVq59AlQ.png" /></figure><p>Sending non-selected ones to -infinity rather than 0 is a deliberate choice because after applying softmax, the -infinity terms will go to zero, thus the gates are exactly zero for non-selected experts.</p><p>But what are these scores <em>Vi </em>actually computed from? This is where the noise comes in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*6YQJP_SnGOdbecxkQeUSAg.png" /></figure><ol><li><em>(x . Wg)_i</em> is simply the learned score for expert <em>i.</em></li><li><em>StandardNormal() </em>is a fresh Gaussian noise per expert per forward pass.</li><li><em>Softplus((x . Wnoise)_i) </em>is a learned, input-dependent noise magnitude. The model doesn&#39;t use a fixed noise level; it learns how much noise to inject, and that amount depends on the token itself.</li></ol><p>After calculating <em>H(x)_i </em>, the final Gating weights/scores are calculated using the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*smBAnENasrG4mSyN-1CF4Q.png" /></figure><p>The noisy scores go into KeepTopK, the losers get sent to -infinity, and Softmax converts the survivors into clean gating weights.</p><p>If it’s not immediately obvious how noise solves the collapse problem, here’s the intuition.</p><p>Without noise, the router is fully deterministic; the same token will always go to the same experts, every single time. The strong experts get stronger, the weak ones never get selected, and the gap only widens over time. This is a self-reinforcing cycle.</p><p>Now add noise. By injecting a small random perturbation into every expert’s score before the TopK selection, we are slightly shuffling the score distribution on every forward pass. An expert who would have ranked 4th might now rank 2nd. An expert who always “won” might occasionally lose.</p><p>This randomness <strong>breaks the self-reinforcing cycle; </strong>borderline experts get selected occasionally, receive gradients, and get a chance to specialize. Over many training steps, this pressure nudges the router toward more balanced expert utilization.</p><p>And crucially, the noise magnitude isn’t fixed, it’s learned and input-dependent via <em>Softplus((x⋅Wnoise)_i)</em>. The model figures out how much exploration is appropriate, rather than having it hardcoded.</p><p><strong>Approach 3: Heuristic Load Balancing Loss</strong></p><p>This is the dominant approach in practice, and the reasoning is elegantly pragmatic.</p><p>As we know, TopK selection itself is not differentiable, but the softmax probabilities before the selection are. So instead of trying to push gradients through the hard selection step, we sidestep it entirely. We define a separate auxiliary loss that operates purely on the differentiable softmax outputs and encourages them to spread evenly across all the experts.</p><p>The Switch Transformer formalization of this idea is clean. Given N experts, and a batch B with T tokens, the auxiliary loss is the scaled dot product between two vectors f and P:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*42oaK0Pvd3bxlo8_G_QIlw.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*625J6kmLhUEsNi0E9voVEw.png" /><figcaption>It was relatively easier to render it in latex and attach screenshot here. lol 😃</figcaption></figure><p>The gradients of this loss with respect to <em>Pi </em>is proportional to <em>fi. </em>The more tokens an expert receives, the stronger the downward pressure on its router probabilities. This creates a self-correcting feedback loop that counteracts the collapse tendency.</p><p>Without any load balancing, the training dynamics become severely uneven. Overloaded experts receive stronger, lower-variance gradient estimates and converge quickly. Underloaded experts receive fewer tokens, leading to higher-variance, noisier gradients, and thus their performance worsens. The router then correctly learns to avoid these poorly performing experts, thus reducing their token count further, which worsens their gradients further. This is how it becomes a self-reinforcing cycle. The result is expert collapse, and most of the model’s capacity is simply wasted.</p><p>There is a real cost to this approach. The auxiliary loss is a competing objective =&gt; set alpha too high, and you hurt model quality, set it too low, and experts collapse. So you are always trading off. But the collapse without it is severe enough that no serious MoE implementation skips it.</p><h4>Beyond Switch Transformer: Other Variants Worth Knowing</h4><p>These techniques collectively define the standard toolkit for MoE training stability. But the story doesn&#39;t end here: modern production models have built on top of these foundations in interesting ways. Let&#39;s take a quick look at how some of the latest MoE models are using these losses, and where the field is pushing beyond standard practice. (This section is for those who want to deep dive further, but if you don&#39;t want to, you can directly jump to the next section “Training MoEs: The Systems Side”)</p><p><strong>DeepSeek V2 — Three Balancing Terms</strong></p><p>DeepSeekV2 designs three auxiliary losses:</p><ol><li><strong>Expert Level Balance</strong>: The Expert level balance is the same idea as Switch Transformer</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*d2wOISDaHgFWgBLMcIBg6Q.png" /></figure><p>2. <strong>Device Level Balance</strong>: The device-level term is the more interesting addition. All routed experts are partitioned into D groups, each deployed on a single device, and the device-level loss penalizes imbalanced computation across devices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*m7EMN-0sHHdCzuY9hkqLlg.png" /></figure><p>where <em>fi′</em>​ and <em>Pi′</em>​ aggregate the token fractions and routing probabilities across all experts on device <em>i</em>. The motivation is practical. In distributed training, even if experts are individually balanced, one device might still get hammered if all its experts happen to be popular. This term directly prevents that.</p><p>3. <strong>Communication Balance Loss</strong>: Even with device-level balance, there is a subtler problem. If tokens from multiple devices all get routed to experts on the same device, that device faces a sudden surge in incoming communication, creating a congestion bottleneck even if the compute load looks balanced. The communication balance loss directly penalizes this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*489ciQPPJsDyeV9CGJvgow.png" /></figure><p>where <em>fi’</em> and <em>Pi’</em> now measure the incoming token traffic to each device rather than the outgoing dispatch. The device-level balance loss ensures balanced <em>sending </em>from each device, while the communication balance loss ensures balanced <em>receiving; </em>they solve two sides of the same distributed <br>training problem.</p><p><strong>DeepSeekV3 — Auxilliary-Loss-Free-Balancing</strong></p><p>DeepSeek V3 pioneers an auxiliary-loss-free load-balancing strategy. A bias term <em>bi</em>​ is introduced for each expert; the routing <strong>decision </strong>uses the biased score to select which experts to activate, but the actual gating weights use the original unbiased score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*C4IDcNHFUvlm-VlffMd-JQ.png" /></figure><p>The biases update online after each batch; overloaded experts get their bias decreased, underloaded experts get it increased. This removes auxiliary losses that directly penalize expert usage, leaving the gating mechanism free to learn solely from the main optimization objective.</p><p>That said, DeepSeek V3 still adds a complementary sequence-wise auxiliary loss to prevent extreme imbalance within individual sequences, so the “auxiliary-loss-free” label refers specifically to the removal of the global expert-level penalty, not to auxiliary losses entirely.</p><p><strong>Router Z-Loss — A Separate Stability Problem</strong></p><p>Separately from load balancing, Zoph et al. (2022) identified that sparse models suffer from instability due to exponential functions in routing that amplify small numerical errors. The router z-loss mitigates this by penalizing large logit magnitudes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*9gHYTH81zzXLlpPohWMD-A.png" /></figure><p>The router z-loss stabilizes the model without any quality degradation; in fact, a slight quality boost is observed in some settings. The total training loss in a well-configured MoE then becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*MkKRcAF9ZojWdz4IMRRJXQ.png" /></figure><h3><strong>Training MoEs: The Systems Side</strong></h3><p>The systems side of MoE training is where a lot of the practical complexity lives. Getting the math right is only half the battle; you also need to figure out how to distribute these models across hardware efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*G0WB9goIAAJcpJm1oWLw5w.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2101.03961">Switch Transformers Paper</a></figcaption></figure><p><strong>Data Parallelism</strong></p><p>The standard approach, every device holds a full copy of the model and processes different batches of data. For MoEs, this means every device must hold <em>all</em> expert weights. If you have 256 experts and each has 1B parameters, that’s a 256B parameter load per device. Infeasible on current hardware. Data parallelism alone doesn’t scale for large MoEs.</p><p><strong>Model Parallelism</strong></p><p>Split the model across devices, different layers on different devices, or tensor parallelism within a layer. MoE layers can be tensor-parallelized within each expert, but this requires additional collective operations inside the MoE sublayer, adding communication overhead on top of the routing overhead that already exists.</p><p><strong>Expert Parallelism</strong></p><p>The natural fit for MoEs. Each expert lives on a different device. When a token is routed to expert <em>i</em>, it’s dispatched via an all-to-all communication operation to the device hosting that expert, processed locally, and the output is sent back via another all-to-all. GShard was the first large-scale demonstration of this, scaling MoE models beyond 600 billion parameters across 2048 TPU cores.</p><p>The two all-to-all operations are unavoidable overhead. In practice, communication time can account for more than 50% of overall training time without careful optimization. DeepSeek V2 addressed this with device-limited routing, restricting each token to route to at most <em>M</em> devices, which directly bounds the communication cost. They found that when <em>M≥3</em>, the device-limited routing achieves performance roughly aligned with unrestricted top-K routing.</p><p><strong>Efficient Sparse Matrix Multiplication</strong></p><p>Token dispatching is irregular; different experts receive different numbers of tokens per batch, which doesn’t map cleanly onto standard dense matrix multiplications. The naive fix is padding every expert’s batch to a fixed size, which is wasteful when routing is imbalanced. MegaBlocks solves this by reformulating MoE computation in terms of block-sparse operations and developing new GPU kernels that handle this dynamism directly, never dropping tokens, and achieving end-to-end training speedups of up to 40% over prior approaches. It’s the kernel library underlying OLMoE, Mixtral, and several other open MoEs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZzkFOfEwC1OJRstg.png" /><figcaption>Taken from <a href="https://huggingface.co/blog/moe">Hugging Face MOE Blog</a></figcaption></figure><p><strong>A Side Note: Why MoE Models Can Be Mysteriously Stochastic</strong></p><p>There was public speculation that GPT-4’s unusual non-determinism, giving different outputs to the same input, even at temperature 0, might be caused by an MoE architecture. The mechanism is real: under capacity constraints, sparse MoE approaches route tokens in groups of a fixed size. When groups contain tokens from different users’ requests, those tokens compete for available spots in expert buffers. This means the model is no longer deterministic at the sequence level, only at the batch level. In plain terms: your token might get dropped depending on what other queries happen to be running at the same time. Same input, different batch, different token dropped → different output. This hypothesis was put forward as a clearer explanation than the commonly cited reason of non-deterministic floating-point operations in CUDA. It illustrates how MoE behavior depends on inference infrastructure in ways that dense models simply don’t.</p><p><strong>Wrapping Up</strong></p><p>We have covered a lot of ground. From the basic intuition of sparse expert routing, to the challenge of training through non-differentiable TopK, to auxiliary losses, z-loss, DeepSeek’s bias-based balancing, and the systems-level machinery that makes all of this actually run at scale.</p><p>The key takeaway is that MoEs are not just a clever architecture trick; they represent a fundamentally different philosophy of model scaling: <em>scale parameters, not compute</em>. And as the field pushes toward ever-larger models, MoEs are only going to become more central to how we build them.</p><p>There’s still a lot being actively researched here: better routing algorithms, more stable training, more efficient kernels, and the open question of whether expert specialization is actually doing what we think it is. It’s a rich space, and we are still in the early innings.</p><p>If you made it this far, thanks for reading. Hope this gave you a solid mental model of what MoEs are, why they are hard to train, and how the field has approached solving that.</p><h3><strong>References</strong></h3><ol><li>Stanford CS336N: <a href="https://www.youtube.com/watch?v=SQ3fZ1sAqXI&amp;list=PLoROMvodv4rOY23Y0BoGoBGgQ1zmU_MT_">https://www.youtube.com/watch?v=SQ3fZ1sAqXI&amp;list=PLoROMvodv4rOY23Y0BoGoBGgQ1zmU_MT_</a></li><li>Hugging Face MOE Blog: <a href="https://huggingface.co/blog/moe">https://huggingface.co/blog/moe</a></li><li>Mixture of Experts (MoE), Visually Explained: <a href="https://www.youtube.com/watch?v=0QQlYR1r6pQ&amp;t=335s&amp;pp=ygUSbWl4dHVyZSBvZiBleHBlcnRz">https://www.youtube.com/watch?v=0QQlYR1r6pQ&amp;t=335s&amp;pp=ygUSbWl4dHVyZSBvZiBleHBlcnRz</a></li><li>Mixture of Experts: How LLMs get bigger without getting slower: <a href="https://youtu.be/7yR5ScbK1qk?si=hGScXFqp9_Qk_Jmd">https://youtu.be/7yR5ScbK1qk?si=hGScXFqp9_Qk_Jmd</a></li><li><a href="https://www.youtube.com/watch?v=Fg8urTOImpY">Writing Mixture of Experts LLMs from Scratch in PyTorch</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70c5b873333b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From LayerNorm to RMSNorm: The Math behind Smarter Normalization]]></title>
            <link>https://medium.com/@arunim756/from-layernorm-to-rmsnorm-the-math-behind-smarter-normalization-ab66e3ec87cb?source=rss-675374b48244------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab66e3ec87cb</guid>
            <category><![CDATA[layer-normalization]]></category>
            <category><![CDATA[rms-normalization]]></category>
            <category><![CDATA[normalization]]></category>
            <dc:creator><![CDATA[Arunim]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 19:05:59 GMT</pubDate>
            <atom:updated>2026-04-25T19:05:59.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*l0hY5hvcAm9IjLk8KuO8Ww.png" /></figure><p>Training a deep neural network is, at its core, a battle against instability. As gradients flow backward through backpropagation across millions or billions of layers, they can vanish into nothing (problem of <strong>Vanishing Gradient Descent) </strong>or explode into chaos (problem of <strong>Exploding Gradient Descent)</strong>. The activations at each layer shift and scale in unpredictable ways, making it very difficult for the optimizer to find a stable learning signal. This problem is tackled by one of the most fundamental techniques in deep learning called <strong>Normalization</strong>, which helps stabilize gradients and makes the model converge significantly faster during training.</p><p>The three most popular normalization methods used in neural networks today are <strong>Batch Normalization (BN)</strong>, <strong>Layer Normalization (LN)</strong>, and <strong>RMS Normalization (RMSNorm)</strong>.</p><p>During the training of language models, Layer Normalization proved to be really effective because, unlike Batch Normalization, it doesn’t depend on having a batch of examples to compute its statistics. But LayerNorm wasn’t perfect. In 2019, Biao Zhang and Rico Sennrich identified some fundamental flaws in it, which eventually led to the birth of RMSNorm, the normalization method used in almost every major language model today, including<strong> LLaMA</strong>, <strong>Mistral</strong>, and <strong>Gemma</strong>.</p><p>In this post, I am going to walk through how Layer Normalization works, what its flaws were, and how RMSNorm fixes them with a beautifully simple idea. But before diving into that, let’s first understand why we need normalization at all.</p><h3><strong>Why Normalization Exists at all</strong></h3><p>Before talking about which normalization to use, it helps to understand why we need normalization at all in the first place.</p><p>As a neural network trains, the distribution of activations in each layer shifts as new data continues to flow in. The weights in layer <em>L</em> update, which changes the input to layer <em>L+1, </em>which means layer <em>L+1</em> now has to constantly adapt to a moving target, and so does every layer downstream from it. This phenomenon is called <strong>Internal Covariate Shift</strong>, and it was one of the primary motivating problems that led to Batch Normalization back in 2015.</p><p>Beyond covariate shift, there is the raw problem of scale. If the activations in a layer grow very large, the gradients during backpropagation can explode. If they shrink too small, gradients vanish. Either way, training becomes painfully slow or completely broken.</p><p>Normalization solves both of these problems by forcing activations to remain within a controlled range at each layer, giving the optimizer a stable, predictable surface to work on.</p><h3><strong>Why LayerNorm Became the Default and Why That Changed</strong></h3><p>Layer Normalization, introduced by Ba et al. in 2016, modified the core idea of Batch Normalization by changing what dimension you normalize across. Instead of normalizing across the batch (in batch normalization), LayerNorm normalizes across the feature dimensions, meaning each individual training example is normalized independently, using its own statistics.</p><p>This makes LayerNorm completely independent of batch size, thus perfectly suited for Transformers and consistent between training and inference.</p><h4>Math Behind Layernorm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*PV2LeZv-DzHPrV30RHD7EA.png" /></figure><p>Given an input vector <strong>x</strong> of dimension <em>d</em> (the hidden representation at a particular layer for a single token), let’s take <em>d</em> = 5 for our example. So our input vector has 5 features: a1, a2, a3, a4, a5. LayerNorm computes the following statistics:</p><p><strong>Step 1: Compute the mean</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*QPnB8PYM6TIhr8krh5Dm6g.png" /></figure><p>As shown in the diagram, the mean is calculated <strong>separately for each sample</strong> in the batch. So for sample x1, the mean is:</p><p>μ1 = (a1 + a2 + a3 + a4 + a5) / 5</p><p>And similarly, μ2 and μ3 are computed independently for samples x2 and x3. This is the key difference from Batch Normalization: each sample gets its own statistics, computed from its own features.</p><p><strong>Step 2: Compute the variance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*xuBylLjkWriF7QIJ7nwRAA.png" /></figure><p>Again, variance is computed independently for each sample. For sample x1, each xᵢ in the formula is replaced by aᵢ (where i goes from 1 to 5), and μ is μ1. The same process repeats for x2 and x3 with their respective means.</p><p><strong>Step 3: Normalize</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*X5kHe1JAoe09Aw1XRswn7A.png" /></figure><p>Here ε is a very small constant (typically around 10⁻⁸) added purely for numerical stability, so that we never accidentally divide by zero in cases where the variance is extremely small.</p><p><strong>Step 4: Scale and Shift</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*DCpVmHpPqUz1UtlZGTdlxg.png" /></figure><p>γ and β are <strong>learnable parameters</strong>, both of the same dimension as the input vector <strong>x</strong>. γ is called the <em>gain</em> (or scale), and β is called the <em>bias</em> (or shift). The reason these exist is important; after normalization, all our activations are forced into a standard distribution. But what if the network <em>needs</em> a different scale or means to represent something meaningful? γ and β give the network the freedom to undo the normalization if that is what the task requires. They are learned during training just like any other weight.</p><p>Putting it all together, the full LayerNorm operation can be written compactly as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*LRy9lTVezFGg8cBWYxi3EA.png" /></figure><p>where ⊙ denotes element-wise multiplication. It looks dense, but it is just the four steps we walked through above, collapsed into a single expression.</p><p><strong>What is LayerNorm actually doing?</strong></p><p>If you strip away the math, LayerNorm is performing exactly two distinct operations on your activation vector:</p><ol><li><strong>Re-centering</strong> — It subtracts the mean μ, shifting the entire distribution so it is centered at zero.</li><li><strong>Re-scaling</strong> — It divides by the standard deviation σ, compressing or stretching the distribution so it has unit variance.</li></ol><p>Then, γ and β let the network move away from that standardized distribution if needed.</p><p>Both of these operations happen in every single forward pass, for every token, at every layer. LayerNorm was the standard, and it worked well. But this two-step process, re-centering <em>and</em> re-scaling, is exactly what Biao Zhang looked at in 2019 and asked a very uncomfortable question: <em>do we actually need both of these, or is one of them doing all the real work?</em></p><p>That question is what leads us to RMSNorm.</p><h3>RMSNorm: Normalization without the Mean</h3><p>Root Mean Square Normalization (RMSNorm) strips LayerNorm down to its essential ingredient: re-scaling. So basically, what Biao Zhang observed was that the main reason behind the success of LayerNorm is its re-scaling property and not the re-centering one. He puts it very clearly in the paper:</p><blockquote>“A well-known explanation of the success of LayerNorm is its re-centering and re-scaling invariance property. The former enables the model to be insensitive to shift noises on both inputs and weights, and the latter keeps the output representations intact when both inputs and weights are randomly scaled. In this paper, we hypothesize that the re-scaling invariance is the reason for success of LayerNorm, rather than re-centering invariance.”</blockquote><p>In other words, re-centering is doing far less work than we thought. So why pay the computational cost for it?</p><p><strong>The Math Behind RMSNorm</strong></p><p>Given an input vector <strong>x</strong> of dimension <em>d</em>, RMSNorm computes the following:</p><p><strong>Step 1: Compute the RMS</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*l_bwpd-EqTScIJOS2MqmTA.png" /></figure><p>Notice what is missing: there is no mean subtraction anywhere. We are simply computing the average of the squared values directly, not the average of the <em>mean-centered</em> squared values. This is the Root Mean Square, not the standard deviation. That one difference is the entire idea.</p><p><strong>Step 2: Normalize</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*wpza2NgBJP7fHtBVaGKx_Q.png" /></figure><p><strong>Step 3: Scale</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*qqPU1fIcKEn_qgntY7yPOg.png" /></figure><p>Notice there is no β term here. Since we are not re-centering the distribution, there is no need for a learnable shift parameter. The only learnable parameters are the gain vector γ, cutting the parameter count exactly in half compared to LayerNorm.</p><p>Putting it together, the full RMSNorm operation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*vQcoWUC5X4MpzpRdRgG44w.png" /></figure><p><strong>The Geometric Intuition</strong></p><p>Here is a clean way to think about what these two normalization methods are really doing.</p><p>Imagine your activation vector <strong>x</strong> as an arrow in <em>d</em>-dimensional space. It has a <strong>direction</strong>, which features are active relative to others, and a <strong>magnitude, </strong>indicating<strong> </strong>how large the overall activation is.</p><ul><li><strong>LayerNorm</strong> both <em>repositions</em> the arrow (subtracts the mean, shifting its center of mass to the origin) and <em>rescales</em> it (divides by standard deviation, normalizing its spread).</li><li><strong>RMSNorm</strong> only <em>rescales</em> the arrow (divides by RMS, normalizing its overall magnitude). It leaves the relative positioning completely untouched.</li></ul><p>RMSNorm is essentially making a bet: the <em>direction</em> of the activation vector already carries all the useful information, and all you need to do is normalize the <em>magnitude</em> to keep training stable. Where the arrow is centered does not matter, only how long it is.</p><p>And as the experiments in the original paper showed, that bet pays off.</p><h3>Where Exactly Does RMSNorm Live in a Transformer?</h3><p>In the original <em>Attention Is All You Need</em> transformer, LayerNorm was applied <em>after</em> the attention or feed-forward sublayer (Post-LN). Modern transformers overwhelmingly use <strong>Pre-LN</strong> (or Pre-RMSNorm), normalizing the input <em>before</em> it enters the sublayer, with a residual connection bypassing the normalization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*20jNbdcYChFd7TXl_cGGbg.png" /><figcaption>Source: <a href="https://github.com/hkproj/pytorch-llama/blob/main/Slides.pdf">https://github.com/hkproj/pytorch-llama/blob/main/Slides.pdf</a></figcaption></figure><p>This Pre-Norm arrangement, combined with RMSNorm, is what you find in LLaMA 2, LLaMA 3, Mistral, Gemma, and most other modern open-source language models.</p><h3><strong>RMSNorm Implementation (PyTorch)</strong></h3><p>Now let’s see how cleanly this translates into code. Here is the implementation of RMSNorm in PyTorch, which I am using in my LLM build:</p><pre>class RMSNorm(nn.Module):<br>    <br>    def __init__(self,dim:int, eps: float = 1e-6):<br>        super().__init__()<br>        self.eps = eps<br>        ## The gamma parameter<br>        self.weight = nn.Parameter(torch.ones(dim))<br>        <br>    def _norm(self, x: torch.Tensor):<br>        # (B,seq_len,dim) * (B,seq_len,1) -&gt; (b,seq_len,dim)<br>        # rsqrt: 1/sqrt(x)<br>        return x * torch.rsqrt(x.pow(2).mean(-1,keepdim=True) + self.eps)<br>    <br>    def forward(self, x: torch.Tensor):<br>        # (dim) * (b,seq_len,dim) =&gt; (b,seq_len,dim)<br>        return self.weight * self._norm(x.float()).type_as(x) # </pre><p>The __init__ method only initializes two things, eps (our ε from the formula, for numerical stability) and self.weight (our learnable γ, initialized to ones). Notice there is <strong>no bias parameter, </strong>exactly as we discussed, RMSNorm has no β.</p><p>The real work happens in _norm. Let&#39;s break it down left to right:</p><ul><li>x.pow(2) → squares every element of x, giving us x²</li><li>.mean(-1, keepdim=True) —&gt; takes the mean across the last dimension (the feature dimension <em>d</em>), giving us the mean of x². It keepdim=True keeps the shape compatible for broadcasting.</li><li>+ self.eps —&gt; adds ε for numerical stability</li><li>torch.rsqrt(...) —&gt; computes 1/√(mean(x²) + ε), which is exactly 1/RMS(x)</li><li>x * torch.rsqrt(...) → multiplies x by 1/RMS(x), which is the normalization step</li></ul><p>In the forward method, self.weight * self._norm(x) is just the final scale step, element-wise multiplication of the normalized output with our learnable γ. The .type_as(x) at the end ensures the output dtype matches the input, since we cast to float inside _norm for numerical precision.</p><p>The entire RMSNorm operation, which we spent several paragraphs understanding mathematically, comes down to essentially a <strong>few</strong> <strong>meaningful lines of code</strong>. No mean computation, no shift parameter, no extra overhead. That simplicity is exactly the point.</p><p><strong>References</strong></p><ol><li>Batch Normalization: <a href="https://arxiv.org/abs/1502.03167">https://arxiv.org/abs/1502.03167</a></li><li>Layer Normalization: <a href="https://arxiv.org/abs/1607.06450">https://arxiv.org/abs/1607.06450</a></li><li>RMS Normalization: <a href="https://arxiv.org/abs/1910.07467">https://arxiv.org/abs/1910.07467</a></li><li>RMSNorm in LLama: <a href="https://www.youtube.com/watch?v=Mn_9W1nCFLo">https://www.youtube.com/watch?v=Mn_9W1nCFLo</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab66e3ec87cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Attention, is All You Need]]></title>
            <link>https://medium.com/@arunim756/why-attention-is-all-you-need-c78c2f466b61?source=rss-675374b48244------2</link>
            <guid isPermaLink="false">https://medium.com/p/c78c2f466b61</guid>
            <dc:creator><![CDATA[Arunim]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 10:27:11 GMT</pubDate>
            <atom:updated>2024-10-06T10:27:11.549Z</atom:updated>
            <content:encoded><![CDATA[<h4>Breaking down the Transformer Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlnWbjwDVtOoMmOnn72EUg.png" /><figcaption>ChatGPT generated image</figcaption></figure><p>Transformers, first introduced in the groundbreaking 2017 paper <em>“</em><a href="https://arxiv.org/pdf/1706.03762"><strong><em>Attention is All You Need</em></strong></a><em>”</em> 🌟, have revolutionized the world of natural language processing (NLP) and deep learning 🤖📚. This visionary work, authored by “<em>Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin”</em>, redefined how we handle sequential data by discarding the need for recurrent networks. Instead, it leveraged the power of attention mechanisms 🎯, offering a faster and more efficient approach. With this innovation, the Transformer model quickly surpassed traditional methods in key tasks like translation and text generation 🌐📝, laying the foundation for modern NLP giants like BERT and GPT 🚀.</p><p>In this blog series, I’ll guide you through the heart of the Transformer architecture, breaking down its magic ✨ step by step. In the first post, we’ll dive deep into the encoder 🧠, unraveling how embeddings and self-attention come together to create meaning from raw data 📊. In the second post, we’ll explore the decoder 📝, focusing on how it crafts coherent and context-aware sequences using cross-attention 🔄. Lastly, we’ll tie everything together with a practical walkthrough of the training and inference process ⚙️, accompanied by real-world code examples 💻.</p><p>Get ready to uncover the intricacies of a model that’s reshaping the future of AI 🌍 — each post will take you deeper into this transformative technology! 💡</p><h3><strong>Table of Contents:</strong></h3><ol><li><a href="#0d62"><strong>Why Transformers outperform previous sequence-based models</strong></a></li><li><a href="#8c07"><strong>Transformers: Meet the Game-Changer in AI 🔥</strong></a></li><li><a href="#f40b"><strong>Inside the Encoder: Crafting Contextualized Representations</strong></a></li><li><a href="#3709"><strong>Input Embeddings</strong></a></li><li><a href="#912f"><strong>Positional Encoding: Adding Order to the Chaos</strong></a></li><li><a href="#e3d6"><strong>Decoding Self-Attention: The Core of Transformers</strong></a></li><li><a href="#5599"><strong>Multi-Head Attention: A Deep Dive into Enhanced Context Understanding</strong></a></li><li><a href="#6106"><strong>Feed-Forward Neural Network: Adding Depth to the Encoder</strong></a></li><li><a href="#94c6"><strong>Residual Connections and Layer Normalization</strong></a></li><li><a href="#85b5"><strong>The Journey of the Embeddings Inside the Encoder</strong></a></li><li><a href="#f71e"><strong>The Power of the Encoder Unlocked: A Journey Through Transformers with More to Come!</strong></a></li></ol><h3>Why Transformers outperform previous sequence-based models</h3><p><strong>Recurrent Neural Networks (RNNs)</strong> and <strong>Long Short-Term Memory Networks (LSTMs)</strong> have long been popular choices for handling sequence-based tasks, but they come with several notable limitations:</p><ol><li><strong>Slow Training due to the sequential nature of these models</strong>: A major drawback of these models is their inherently sequential nature. At each time step ‘t’, the model’s output depends on the previous time step ‘t-1’. This sequential dependency significantly slows down training, especially for long sequences, as computations must be done one step at a time.</li><li><strong>Capturing and Retaining the semantic information in very long sequences</strong>: RNN and LSTM models struggle to capture and retain the relationships between distant words in the sequence, often resulting in the “vanishing gradient” problem where gradients diminish over time in long-range sequences, leading to poor learning of long-range dependencies.</li><li><strong>Parallelization Problems</strong>: Because of the sequential nature of the models, parallelizing the training and inference process is also very difficult, leading to inefficiencies in scaling models.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*3PNhBfBE-vTGjNpw" /><figcaption>Generated using HuggingChat Image Generator Assistant. Sharing the link to the conversation for your curiosity😉. <a href="https://hf.co/chat/r/3Uz1Vuo?leafId=6e84d0d8-4278-4ed1-9d50-6ea2856cb38c">https://hf.co/chat/r/3Uz1Vuo?leafId=6e84d0d8-4278-4ed1-9d50-6ea2856cb38c</a></figcaption></figure><p>Transformers solve these issues through the <strong>attention</strong> mechanism, <strong>1)</strong> which allows the model to simultaneously consider all positions in the sequence rather than processing one step at a time. <strong>2)</strong> By doing so, Transformers can capture global and local dependencies between words, regardless of their distance in the sequence, without suffering from vanishing gradients. The attention mechanism efficiently weighs the importance of each token relative to the others, allowing the model to understand the context better. <strong>3)</strong> Furthermore, Transformers leverage parallelization by simultaneously processing all tokens in the sequence, leading to faster training and the ability to handle much larger datasets (<strong><em>to give an idea, </em></strong><a href="https://skylion007.github.io/OpenWebTextCorpus/"><strong><em>Open WebText</em></strong></a><strong><em> data is around 40GB of text data generated from around 8 million documents</em></strong>), a significant advantage over RNNs and LSTMs.</p><h3>Transformers: Meet the Game-Changer in AI 🔥</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*619ripspyFiTira83DBIsA.png" /><figcaption><strong>From Attention is all you need paper</strong></figcaption></figure><p>According to “<strong><em>Attention is all you need.</em></strong>” authors,</p><blockquote><strong>In this work, we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state-of-the-art translation quality after being trained for as little as twelve hours on eight P100 GPUs.</strong></blockquote><blockquote><strong>The Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence aligned RNNs or convolution.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Q6Q372_RHz2SM3wKS1j_Cg.gif" /><figcaption>From The Boys Series (one of my favourite ones 😉, have you watched it?)</figcaption></figure><p>Relax; obviously, it’s not that easy to understand just by glancing at the architecture and reading a definition. There’s much more to it behind the actual working of the architecture than you can see. But don’t worry — everything will become crystal clear once I guide you through this intricate (and somewhat intimidating❤️) model step by step. 🧠💡 Let’s dive deep into the heart of this architectural beast and decode every piece of it. By the end, this “hell” of a model will feel like home! 😊🏠</p><p>First, let me explain the statements easily, made by the authors:</p><blockquote><strong>In this work, we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output.</strong></blockquote><p>The authors introduced a new “<strong><em>Transformer</em></strong>“ model, which does not use recurrence like traditional RNNs and LSTMs. Instead, it uses an attention mechanism that connects or relates all words (or tokens in NLP terminology) in the input and output sequences, capturing global dependencies more effectively and efficiently.</p><blockquote><strong>The Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence aligned RNNs or convolution.</strong></blockquote><p>Transformer is the first <strong><em>transduction</em></strong> model (which transforms input data into output data, like translation tasks or speech recognition tasks) that doesn’t rely on recurrent and convolutional structures. Instead, it uses self-attention to make the model understand which input parts are most relevant when generating the output.</p><p>I hope I am successful in my first task of explaining the definition of a Transformer more understandably. 😇</p><p><strong>Now, let me give you an overview of what’s happening inside the architecture. After that, we can dive deeper into each of the components independently and explore them in depth.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*pAdvyYLY_5ugo0o2xH4Dgg.png" /><figcaption><strong>Encoder And Decoder</strong></figcaption></figure><p>You can see two models inside this architecture: the “<strong>Encoder</strong>” and the “<strong>Decoder</strong>.”</p><h4>“<strong>Encoder</strong>”</h4><p>is a model made up of “<strong>N</strong>” layers of <strong>Encoder Blocks</strong> that process the input sequence (input sentence) and generate a set of context-rich representations, which we call as <strong><em>Contextualized Embeddings</em></strong>. Each encoder block has three main sub-layers (sub-components):</p><ol><li><strong>Self-Attention</strong>: This helps the encoder examine all tokens(words) in the input sequence to determine their relationships and importance among each other. It creates attention scores(0 to 1) between tokens of the same sequence to create a weighted representation of the input.</li></ol><p>Attention score is a very clever way of <strong><em>quantifying</em></strong> the relationship between the tokens in an input sentence. For example, in the sentence,</p><blockquote><strong>The vibrant butterfly fluttered over the colorful flowers.</strong></blockquote><p>The attention score between the tokens(or words) “<strong><em>vibrant</em></strong>” and “<strong><em>butterfly</em></strong>” might be around <strong><em>0.8</em></strong>, showing that these tokens have a very high relationship. However, the attention score between “<strong><em>vibrant</em></strong>” and “<strong><em>flowers</em></strong>” will be around <strong><em>0.2</em></strong>, signifying a low relationship with each other. Thus, you can see that the self-attention mechanism helps the encoder to understand the context, semantic meaning, and relationship between the tokens beautifully. For your information, Attention scores are calculated for every pair of tokens(words) in the sentence, providing a comprehensive understanding of their interactions. We will see about this in the later section of this blog.</p><p>2. <strong>Feed Forward Neural Network</strong>: Self-Attention layer is followed by a <strong>Feed Forward Neural Network (FFN)</strong> which is applied independently to each token. This network consists of two linear transformations with a ReLU activation in between. After the attention mechanism, the FFN processes each token’s representation individually, adding non-linearity and transforming the data into higher-dimensional spaces. It’s crucial for capturing complex patterns and relationships, ensuring richer representations of the input.</p><p>The output of each encoder layer is then passed to the next encoder layer, allowing for deeper contextual understanding.</p><p>3. <strong>Residual Connections and Layer Normalization:</strong></p><p><strong>Residual Connections</strong> are skip connections that allow the input of a layer to bypass the transformations and directly add to the layer’s output. This helps prevent the vanishing gradient problem by ensuring that the gradient can flow easily through the network, enabling deeper networks to be trained effectively.</p><p><strong>Layer Normalization</strong> is a technique that normalizes the activations of the neurons within each layer, ensuring that the input to the next layer has a consistent distribution. It helps improve convergence and training stability by reducing internal covariate shifts.</p><h4>“Decoder”</h4><p>is a model made up of “<strong>N</strong>” layers of <strong>Decoder Blocks</strong> that generate the output sequence based on the representations produced by the encoder. Each decoder block contains similar layers as the encoder with a little twist 😏</p><ol><li><strong>Masked Self-Attention</strong>: Masked self-attention ensures that, during training, the decoder can only attend to previous tokens and not future ones in the sequence. This prevents the model from &quot;cheating&quot; by not seeing future tokens when generating the current word, ensuring outputs are generated step by step. More on that in my next blog.😉</li><li><strong>Cross Attention: </strong>Cross-attention occurs in the decoder, where the model attends to the encoder’s output representations while generating each token. This lets the decoder focus on relevant parts of the input sequence, ensuring that the generated output aligns with the input context.</li><li><strong>Feed Forward Neural Network</strong>: Same as the encoder.</li></ol><p>So, combining all the above information. First, the input sentence is tokenized and transformed into input embeddings using an embedding layer. To account for the relative positions of tokens within the sentence, <strong>positional embeddings</strong> are added to these input embeddings. At this point, the embeddings contain token and positional information but lack semantic and contextual understanding.</p><p>The <strong>encoder</strong> then processes these embeddings, transforming them into <strong>contextualized embeddings</strong> that capture the meaning and relationships within the sentence. These contextualized embeddings are passed to the <strong>decoder</strong>, which further processes them, generating <strong>output embeddings</strong>. Finally, these output embeddings are fed into a final output layer, producing a probability distribution over the vocabulary, enabling the model to predict the most likely next tokens in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*6HjroZGSLlTU3cGIECaShQ.png" /><figcaption><strong>Overview of the Transformer Architecture (Inference)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*K_HDjbJq0Q0nmHs2.gif" /></figure><p>Oh wow, what a ride this architecture has been! We’ve unraveled so much about the Transformer, yet this is only the beginning. Before we continue, just take a breath, sip some water, stretch your legs, and maybe even go for a quick walk — because what’s coming next is where the true brilliance unfolds. For all the true ML enthusiasts out there who are craving more depth and more insight, this is where we roll up our sleeves and dive into the heart of the Transformer.</p><p>For a quick and intuitive overview of the Transformer architecture, I highly recommend watching these beautifully crafted videos by <a href="https://www.youtube.com/@3blue1brown"><strong><em>3Blue1Brown</em></strong></a><em>, </em>where the architecture of Transformers is explained with stunning clarity and visual elegance. Once you’ve absorbed the big picture, come back here to dive deeper into each of the components, where I’ll provide even more insights, examples, and step-by-step explanations to solidify your understanding. 😉</p><p>Trust me, this journey is only getting more exciting, and I’ve got plenty more to share that will tie everything together. 😏</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwjZofJX0v4M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwjZofJX0v4M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwjZofJX0v4M%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd01a7c0f1f22487251dfed5cd803b0c/href">https://medium.com/media/fd01a7c0f1f22487251dfed5cd803b0c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeMlx5fFNoYc%3Fstart%3D1136%26feature%3Doembed%26start%3D1136&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeMlx5fFNoYc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeMlx5fFNoYc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0260ab3a0ef526d527218e4303efb73e/href">https://medium.com/media/0260ab3a0ef526d527218e4303efb73e/href</a></iframe><p>Now that we’ve set the stage, let’s delve into the first crucial component of the Transformer: the <strong>Encoder</strong>.</p><h3>Inside the Encoder: Crafting Contextualized Representations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*_RObq-G05dAjISix4ylGMA.png" /><figcaption><strong>The Encoder</strong></figcaption></figure><p>Now, it’s time to take a deeper, more technical dive into the <strong>encoder</strong>. From this point forward, I’ll guide you through each step of the process — from how the input is converted into <strong>embeddings</strong> to how the encoder produces its final <strong>contextualized output</strong>. We’ll break down the key components and mechanisms that power the encoder, ensuring a clear understanding of how it transforms input data. So, get ready as we explore the encoder’s workings in greater detail, laying the foundation for everything that follows in the Transformer architecture. So, without further ado, let’s dive right in.</p><h4>Input Embeddings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*z5-dQXOH68YMQCekVAzniA.png" /></figure><p>First, let’s understand what is an <strong>Embedding Layer</strong>.</p><p>An Embedding Layer is essentially what we call as a <strong>lookup table</strong> that stores a <strong>fixed dictionary of embeddings</strong> for each token in the <a href="#9e4f">vocabulary</a>. When the input tokens are passed in, the embedding layer retrieves the corresponding embeddings for each token.</p><p>Now, let’s see how the embedding layer is used in the creation of input embeddings. Earlier, I mentioned that the input text is first broken down into <strong>tokens</strong>, which are then converted into <strong>input IDs</strong> — essentially, numerical representations that map each token to its corresponding entry in the vocabulary. However, the encoder doesn’t work directly with these raw numbers. Instead, these <strong>input IDs</strong> are transformed into dense, high-dimensional vectors using an <strong>Embedding layer</strong>. This layer converts each token ID into a <strong>d_model</strong> dimensional vector, and these vectors are learned during the training process. In this way, each token is represented as a dense vector in a continuous vector space.</p><p>To enhance your understanding, please refer to the picture below. As you examine the diagram, read the accompanying text to see how the <strong>embedding layer</strong> creates <strong>input embeddings</strong>. This visual representation will clarify how input IDs are transformed into dense vectors in a continuous vector space, illustrating the embedding layer’s role in the encoder’s architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJihd1W6wtH3BSp-RgditQ.png" /><figcaption>Image from Author</figcaption></figure><p>This architecture is used in both the encoder and decoder to create the input embeddings.</p><p>However, there is a limitation with these embeddings — they do not account for the <strong>relative positions</strong> of tokens within the input sentence. This can negatively impact the model’s performance, as understanding the order of words is crucial. This is where <strong>Positional Embeddings</strong> come into play, adding information about the position of each token to help the model capture the sequence structure effectively.</p><h4>Positional Encoding: Adding Order to the Chaos</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*yZi4evZNcbNkcTmqcz0XhA.png" /></figure><p>For a model to understand the meaning of a sentence, the position of each token is crucial, as word order can dramatically change the meaning of a sequence. For example: “Rahul is playing football” or “Football is playing Rahul”. Although it&#39;s very logical, the later sentence does not make any sense, but the transformer model would see both sentences as the same if positional encoding is not used.</p><p>In traditional models like RNNs, this was handled naturally by processing tokens sequentially. <strong>However, the transformer processes all tokens in parallel, which means it needs an explicit way to know the position of each token in the sequence.</strong></p><p>Thus, to incorporate this issue, positional encoding is added to each token’s input embeddings. These positional encodings are fixed vectors (<strong><em>which</em></strong> <strong><em>means that this does not change during the entire training process</em></strong>) that indicate the position of a token in the sequence.</p><p><strong>Now, the main question is, how is it created, and what is the intuition behind its procedure?</strong></p><p>Let&#39;s first understand its intuition.</p><p>The positional information added would be beneficial only if it satisfies the following conditions:</p><ol><li>It should be unique for every position.</li><li>It should be deterministic or based on some underlying rule that the model can capture easily.</li><li>It should allow us to estimate the distance between the positions of two tokens.</li><li>Works with sequences longer than encountered before in the training process.</li></ol><p>So, to satisfy all these conditions, <em>“Attention is all you need” </em>authors came up with a brilliant idea. They presented in the paper that sinusoidal position embeddings satisfy all the above criteria. They used the following function to create the positional embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*Dum1hGhBvI49xF9P8IIeRg.png" /><figcaption>Attention is all you need Paper</figcaption></figure><p>where <em>‘pos’ </em>is the position of a token and <em>‘i’ </em>is the dimension. The functions shown above are used to create positional embeddings that satisfy all the criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Wu5lWA7FNnbTarpXgvrx7Q.png" /></figure><p>Thus, the <strong>positional embeddings</strong> are combined with the <strong>token embeddings</strong>, as illustrated in the figure above, to form the final <strong>Encoder Input Embeddings</strong>. This addition ensures that the model not only captures the meaning of each token but also its position within the sequence. These enriched embeddings are then fed into the encoder, allowing the model to process both the content and structure of the input sentence.</p><p>However, to fully grasp the concept, you may benefit from additional information or visual aids. I highly recommend watching this video, which provides an intuitive explanation of why this particular function is chosen, supported by excellent visualizations. It will help clarify the reasoning behind <strong>Positional Embeddings</strong> in a more engaging and understandable way.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FT3OT8kqoqjc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DT3OT8kqoqjc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FT3OT8kqoqjc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/35aefb94a6c786abf7aa24f5ae41c18d/href">https://medium.com/media/35aefb94a6c786abf7aa24f5ae41c18d/href</a></iframe><blockquote>Now that we’ve explored <strong>Positional Embeddings</strong> and how the encoder’s input is crafted, get ready for the real magic behind Transformers: <strong>Self-Attention</strong>.😉 This is where the model truly shines, as it learns to focus on different parts of a sequence to capture hidden relationships and meanings. Curious how it works? Trust me, this is one of the most exciting concepts in machine learning today. And once we unravel the power of self-attention, we’ll take it a step further with <strong>Multi-Head Attention</strong>, which amplifies this process by allowing the model to look at multiple aspects of the sentence simultaneously.</blockquote><p>Before diving into <strong>Self-Attention</strong>, it’s important to understand a key concept: the <strong>Dot Product</strong> between two embeddings. If you’re already familiar with this, feel free to skip ahead, but understanding it will make the upcoming explanation clearer.</p><p>Consider the following sentences:</p><ol><li><strong><em>The sky turned a brilliant shade of orange as the sun set over the horizon.</em></strong></li><li><strong><em>As the sun dipped below the horizon, the sky was painted in vibrant hues of orange.</em></strong></li></ol><p>By reading, we know they have similar meanings, but how do we quantify this similarity? That’s where the <strong>Dot Product</strong> comes in. It’s a mathematical operation that calculates the similarity between vectors by multiplying their corresponding elements and summing the results. To calculate the dot product between sentences, we first convert the sentences into their corresponding vectors — these are the <strong>Encoder Input Embeddings </strong>we talked about earlier. The higher the dot product between their embeddings, the more semantically similar the sentences are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAQ1k-M-Qe4WpFD7_P0BYQ.png" /><figcaption><strong>Dot Product Calculation</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POw3MTXPjvEpM_26VT1Sgg.png" /><figcaption><strong>Relation of the angle and dot product between the vectors</strong></figcaption></figure><p>Well, now this concept is discussed, we can start with the Self-Attention.</p><h3>Decoding Self-Attention: The Core of Transformers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Hy2e8HQPrrZZUFxGCHfX1g.png" /><figcaption>Attention is all you need Paper</figcaption></figure><p>Oh boy, we’ve arrived at the heart of the Transformer model — <strong>attention</strong>. This magical mechanism is what allows Transformers to shine in everything from language translation to text generation. It’s a powerful tool that captures relationships between words — near and far — with incredible efficiency. So, what exactly happens under the hood? Let’s break it down.</p><p>To truly understand how attention works, let’s break it down step by step using a clear and simple example. I’ll guide you through each component+ and each mathematical operation that takes place in the attention mechanism. The deeper you go, the more fascinating it gets 😉 — so stay with me, and let’s dive into this powerful concept that lies at the heart of Transformers. Trust me, by the end of this, the magic behind attention will become crystal clear! 😃</p><p>Consider this simple sentence</p><blockquote><strong>The stars twinkled brightly in the night sky</strong></blockquote><p>In essence, attention computes embeddings for each token in the input sentence and then <strong>assigns weights to these token vectors based on their contextual relevance, </strong>which is finally used to create contextualized embeddings. This dynamic weighting enables the model to focus on the most important parts of the sentence. To illustrate this process more clearly, let me guide you through a flowchart that visually represents how attention operates in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6SMdjOvZLI_CGdLEDdxPg.png" /></figure><p>Now, let’s see what the phrase “<strong><em>weigh word vectors according to the context</em></strong>” actually means. Let’s look inside the box in the above figure step by step.</p><p><strong>Step 1:</strong></p><p>We will first calculate the similarity scores between each pair of vectors using the dot product formula discussed above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHZPNk2_vYL2LJnyaBHv5A.png" /><figcaption>Step1</figcaption></figure><p>This will give a vector of similarity scores for each of the embeddings of tokens v(i).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxFMpJ6S5J_IIL3iEVuzTw.png" /></figure><p>Sim(i) is a vector of similarity scores for vector v(i), where each element in this vector represents the similarity score of other vectors with vector v(i), including itself.</p><p><strong>Step 2:</strong></p><p>Now, to get the similarity scores as a probability distribution such that the Sim(i) vector has elements in the range 0 to 1, we will apply the softmax function to this vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ie0VBOi1c7lZRiivIlYnpw.png" /><figcaption>Step 2</figcaption></figure><p>Applying the softmax function will give us a probability distribution W(i) where each element of W(i) represents a similarity score between 0 to 1. And because this is a probability distribution, the sum of all the elements of W(i) will be 1.</p><p><strong>Step 3:</strong></p><p>Now, we will weigh the original token(word) vectors using the probability distribution above. So, this probability distribution will act as weights where we can quantify how much a neighboring vector of v(i) is impacting v(i).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiLyFZQH8zeh6uKQkVWd2w.png" /><figcaption>Step 3</figcaption></figure><p>By applying the probability distribution as weights to the original word vectors, we create a rich, contextualized representation of each token. This, in essence, is the magic of self-attention — where each word in the sentence weighs the importance of every other word in relation to itself. The result? A dynamic, insightful understanding of the sentence as a whole. That’s the brilliance behind “<strong>self</strong>” in self-attention: every token is in a conversation with its peers, grasping the context, meaning, and nuances, making the entire sentence more than just the sum of its parts!</p><p>I have attached the complete figure to show the whole view of the self-attention mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*JX_ONrEfdGWnXi07LwvcEA.png" /></figure><p>So, this was a basic example to get a feel of how self-attention works. Now, let’s take it up a notch! I’ll transform this simplified flowchart into something that closely mirrors the actual self-attention mechanism used in transformers. As you continue, compare the following flowcharts with the one above to see how they connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iHfSlFqUjMC5WIfAx6yhA.png" /><figcaption><strong>Self-Attention</strong></figcaption></figure><p>If you’re already familiar with the structure of self-attention, you’ll notice that the flowchart we’ve explored bears a strong resemblance to the actual self-attention mechanism. Now that we’ve grasped the essence of how it operates, you might be wondering — what’s next? Does it end here? Not quite! Let’s think about it for a moment.</p><p>Here’s a question for you: Do you feel like something’s missing from the figure? Take a guess!</p><p>If you have thought about it and guessed correctly, kudos to you, my friend! 😱🔥</p><p>We know that this is a layer in the transformer architecture. And when we talk about layers, there’s something crucial we can’t overlook —<strong> learnable weights!</strong> But where are they? If you’re wondering why they’re not in the diagram, you’re absolutely on the right track. So, let’s add those weights to complete our self-attention mechanism!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYDNV042IawOJdA33XrGMw.png" /><figcaption><strong>Self-Attention with learnable weights</strong></figcaption></figure><p><strong>Wq, Wk, and Wv are linear layers for queries, keys, and values, respectively.</strong></p><p>This is it — the complete self-attention mechanism! Now, we can confidently say that we truly understand how self-attention works. One last thing to mention: you might have come across terms like <strong>queries</strong>, <strong>keys</strong>, and <strong>values</strong> in self-attention diagrams. Don’t be intimidated by them — they’re simply the copy of token (word) vectors.</p><p>But here’s something exciting to keep in mind: what we’ve covered is the self-attention mechanism for the encoder. In the decoder, things get even more interesting with <em>cross-attention</em>, where the <strong>keys</strong> and <strong>values</strong> come from the encoder, and the <strong>queries</strong> come from the output sequence. It might sound a bit complex now, but don’t worry — it’ll make perfect sense when we dive into the decoder in the next blog!</p><p>I am attaching a figure below to compare the simplified self-attention figure with the actual one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOCV4hGkNCMdJT7jbHOnnA.png" /><figcaption><strong>Comparison Figure</strong></figcaption></figure><p>In the actual self-attention mechanism, you’ll notice two additional components: “<strong>Scale</strong>” and “<strong>Mask (optional).</strong>”</p><p>The <strong>Scale</strong> operation is used to divide the similarity scores by a constant (typically the square root of the dimension of the embedding vectors(d_model). This helps to keep the similarity scores within a range that computers can handle efficiently. Without scaling, the dot product can result in very large values, which might cause instability or ambiguous results due to numerical limitations.</p><p>The <strong>Mask (optional)</strong> is mainly used in the decoder’s cross-attention to prevent the model from attending to future tokens when generating the output sequence. However, since this concept is more relevant to the decoder, we’ll explore it further in the next blog, so don’t worry about it just yet.</p><p>Let’s take a look at the actual formula for attention — an equation you may have come across before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*bd8YU2Ys4UxRR_OZgfvSFA.png" /></figure><p>When you compare this equation with the self-attention figure, it starts to make complete sense. First, it performs matrix multiplication between the <strong>Query</strong> and <strong>Key</strong> matrices to compute similarity scores. Then, the result is divided by the square root of the embedding dimension (denoted as √dk) to ensure scaling. After that, a <strong>softmax</strong> function is applied to convert these scores into a probability distribution. Finally, this distribution is multiplied by the <strong>Value</strong> matrix, giving us the attention output.</p><p>This breakdown shows how self-attention works both mathematically and conceptually.</p><p>Let’s dive into one last exciting illustration to solidify your understanding! In this example, I’ll not only walk you through the self-attention calculation but also reveal how the shapes of tensors transform as they move through the attention layers. Trust me, watching these tensor dimensions evolve will give you a much clearer and more fascinating view of how everything fits together — so get ready to see the magic unfold!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWzx_VZikDx-EU43nWVidA.png" /></figure><p>In this illustration, the key focus is on how the dimensions of tensors evolve as they pass through the attention mechanism, which is crucial for grasping the flow of computations. Instead of concentrating on the numerical values, observe how the input embeddings are transformed into higher-dimensional tensor shapes at different stages. The attention matrix, in particular, plays a vital role, where you’ll notice the diagonal elements are all 1, and the matrix is symmetric — this is a natural consequence of how self-attention works. Ultimately, this process produces contextualized embeddings, which carry richer information about the relationships between words in the sentence.</p><blockquote>The self-attention mechanism we’ve discussed so far forms the foundation of how transformers process and weigh input tokens. However, in the actual transformer architecture, we use a more advanced version called <strong>multi-head attention</strong>. Multi-head attention builds on self-attention by applying the attention mechanism multiple times in parallel, each with different learned weights. This allows the model to capture different aspects of the relationships between tokens, attending to various parts of the input sequence simultaneously. By combining these multiple “heads” of attention, the transformer can represent more complex patterns and gain deeper contextual understanding, making it much more powerful than using a single attention mechanism.</blockquote><h4>Multi-Head Attention: A Deep Dive into Enhanced Context Understanding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*Ep41vdy2zFfxDqQXDUyl0Q.png" /></figure><p>Imagine you’re reading a book with a group of friends, and each friend has a different focus. One friend is paying attention to the characters, another is focusing on the environment, and a third is tracking the plot. When you all discuss the book, each of you brings a unique perspective, and together, your collective understanding is much deeper and more comprehensive than if only one of you had read it alone.</p><p>This is exactly what multi-head attention does! Each “head” in multi-head attention pays attention to different parts of the sentence or context. One head might be focusing on how the subject relates to the verb, while another is more interested in the relationship between adjectives and nouns. These heads work in parallel, processing the same information but from different angles.</p><p>In the end, these different “attention heads” are combined (just like how your friends share their different insights) to create a richer and more complete understanding of the input. This allows the transformer to grasp complex relationships in language, making it super powerful for tasks like translation, summarization, and more!</p><p>Let’s now explore multi-head attention with the aid of flowcharts and visualizations for a clearer understanding.</p><p>To fully leverage multi-head attention, the first step is to split the queries, keys, and values tensors into multiple heads, as depicted in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9atbundRSg4fE-3z1A9GLw.png" /></figure><p>We start with an input sequence consisting of 6 tokens, each with an embedding dimension of 12 (d_model). As usual, we pass the queries, keys, and values through linear layers. The key difference here is that we split these tensors into multiple heads, specifically 3 heads in this example. This is a straightforward operation, achieved by reshaping the tensors from a shape of (6, 12) to (3, 6, 4). But why are we doing it? Think of it this way: previously, we had just 1 query, 1 key, and 1 value tensor. But now, after splitting, we have 3 separate query tensors, 3 key tensors, and 3 value tensors. Each of these tensors still represents the same sequence length of 6 tokens but with a smaller embedding dimension of 4 for each head. This allows each head to attend to different parts of the input, capturing more nuanced information across multiple subspaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3w5HUe1vvAXfez3eCIMoMw.png" /></figure><p>Now, the 3 separate query, key, and value tensors will be fed into the self-attention mechanism. Here’s something important to remember: even though I mentioned there are 3 separate tensors for each query, key, and value, they are actually still part of a single tensor. Each of these tensors has the shape (3, 6, 4), meaning we’re applying 3 self-attention mechanisms at once, all within this single tensor. This is where the magic of multi-head attention comes into play — 3 different attention heads are processed in parallel, enhancing the model’s ability to capture various aspects of the input, all in one go. This is the power of Multi-Head Attention.</p><p>After applying the 3 self-attention mechanisms, we get 3 outputs — one from each head. And here’s the best part: the outputs are already concatenated within the tensor, so we don’t need to explicitly concatenate them ourselves. The resulting tensor still has the shape (3, 6, 4). Finally, we reshape this output back to the original input embedding shape, (6, 12).</p><p>But here’s something important we are missing. We have done calculations for 3 different heads, got 3 different head outputs, and reshaped them to finally get a tensor of input embedding shape. But we didn&#39;t combine the information gathered from 3 different heads.</p><p>Reading this, you might have a question, which I also had when I was studying multi-head attention; we have combined 3 different head outputs by concatenation and reshaping them into a shape of (6,12). Then why are we saying we have to combine information from 3 different heads? If you have this question, great! Here’s the answer:</p><blockquote>When we split the queries, keys, and values into multiple heads, each head is handling a smaller dimensional space (for example, (dmodel​/h)(12/3 = 4 in our case), where h is the number of heads). After the attention mechanism, we concatenate the heads back together, but this operation alone doesn’t incorporate any learnable transformations across all heads.</blockquote><blockquote>By applying a final linear layer “Wo”, we combine the outputs of all heads into a single learned representation while also ensuring that the dimensionality remains consistent (i.e., the output tensor matches the original input embeddings with shape (sequence_length,d_model). This linear transformation adds learnable weights, allowing the model to fine-tune and integrate the information gathered from different attention heads, making it more expressive and powerful.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_c6hNHwkuepvBY26Ss6rQ.png" /></figure><p>Now, let’s take a look at the equation for Multi-Head Attention, as given by the authors of <em>Attention Is All You Need</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*Ptoy4NY_F7qLLPlygJwCMQ.png" /></figure><p>You’ll notice that “<strong><em>head(i)</em></strong>” in the equation represents one individual attention mechanism. But what’s important to clarify here is how the query, key, and value projections (denoted as Wq, Wk, and Wv​) are handled for each head.</p><p>In the original paper, the authors applied separate Wq, Wk, and Wv​ matrices for each attention head. However, in my explanation, I described a method where the query, key, and value tensors are first passed through one set of Wq, Wk, and Wv, and then split into multiple heads. This approach is followed by many tutorials in sources like Medium, Towards Data Science, and even YouTube.</p><p>Both methods achieve the same goal — allowing the model to perform multiple attention mechanisms in parallel — though they slightly differ in implementation. Based on what I’ve observed, either method seems to yield similar results in practice, so both are valid approaches for training.</p><p>If you have any other insights or a different perspective on this, feel free to share in the comments — I’d be happy to learn from your thoughts!</p><h3>Feed-Forward Neural Network: Adding Depth to the Encoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*35UapJWqZHkfUifmPRON1A.png" /></figure><p>With Multi-Head Attention complete, we move to the next key component in the encoder: the Feed-Forward Neural Network (FFNN).</p><p>This layer follows the attention mechanism. The FFNN consists of two fully connected layers with a ReLU activation function in between. The first layer expands the dimensionality, and the second layer projects it back down to the original embedding size.-</p><p>The purpose of the FFNN is to further transform the token representations that the attention mechanism outputs, adding a layer of non-linearity and depth to help the model capture more complex patterns in the data. Even though it’s a simple and straightforward mechanism, it plays a crucial role in refining the embeddings and improving the model’s expressive power.</p><h3>Residual Connections and Layer Normalization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*7Gy7KVo0pXtU_NycNVrQsQ.png" /></figure><p>Residual connections and layer normalization are critical components in the Transformer architecture that ensure stable and efficient learning.</p><p>The purpose of <strong>residual connections</strong> is to allow the model to “skip” layers by adding the input of a layer directly to its output. This prevents the degradation of information across deep networks, helping maintain gradients during backpropagation, especially in very deep models.</p><p><strong>Layer normalization</strong>, on the other hand, stabilizes the output at each layer by normalizing the summed inputs to have zero mean and unit variance. This ensures that each layer’s inputs are well-scaled, making the training process smoother and faster. Together, these two techniques allow for faster convergence and better performance, contributing to the overall robustness of the model. While diving deeper into layer normalization could reveal its intricate workings and benefits, such as how it mitigates issues related to <strong>internal covariate shift</strong>, it’s important to maintain a balance in our blog’s content. I want to provide you with a solid understanding without overwhelming you with too much information at once. Therefore, let’s touch upon its importance here and keep the discussion light while inviting you to explore its depths in my next blog. So stay tuned for that! 😉</p><h3>The Journey of the Embeddings Inside the Encoder</h3><p>Now that we’ve dissected each component of the encoder, let’s step back and view the entire landscape, bringing together all the elements to provide a comprehensive understanding of how the flow of embeddings takes place in an encoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwAuh17OABtJStUkNrGsJw.png" /><figcaption><strong>Information Flow inside the Encoder</strong></figcaption></figure><h3>The Power of the Encoder Unlocked: A Journey Through Transformers with More to Come!</h3><p>As we’ve peeled back the layers of the transformer encoder, from embeddings to feed-forward networks, we’ve witnessed the magic of how these intricate pieces work together to transform raw data into meaningful insights. ✨ The synergy between self-attention and positional encoding is nothing short of revolutionary, reshaping the future of AI and NLP.</p><p><em>“Every great journey begins with a single step, and the encoder was just the first stride.”</em> 🚀 But don’t close the book yet — we’re just getting started! In my next blog, we’ll unlock the secrets of the <strong>decoder</strong>, where the real magic of generating outputs unfolds. Get ready for an adventure filled with even more mind-blowing concepts and AI wizardry. 🧠✨</p><p>Stay curious, because the best is yet to come! 🔑</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3WuXIe9LFL_kDtAsL8bQA.png" /></figure><h3><strong>Explanation of some words</strong></h3><ol><li><strong>Vocabulary:</strong></li></ol><p>When processing text data, the Transformer doesn’t work directly with raw words or sentences. Instead, it first breaks the input into smaller pieces, often called <em>tokens.</em> The vocabulary is the collection of all these tokens that the model has been trained on or can handle during inference. Each token in the vocabulary has a unique numerical ID that maps to an embedding, which is a dense vector representation that the Transformer processes.</p><p>For example, in NLP, a typical vocabulary might contain common words like “apple,” “run,” “the,” and special tokens like [PAD], [CLS], or [SEP], as well as subword units like “un-” or “-ing” to handle rarer or unseen words. These tokens help the model understand the structure and meaning of input text, even when some words aren’t directly in the vocabulary.</p><h3><strong>References</strong></h3><ol><li><a href="https://www.youtube.com/watch?v=bCz4OMemCcA">https://www.youtube.com/watch?v=bCz4OMemCcA</a></li><li><a href="https://www.youtube.com/watch?v=zxQyTK8quyY">https://www.youtube.com/watch?v=zxQyTK8quyY</a></li><li><a href="https://www.youtube.com/watch?v=csWluHwfsB8">https://www.youtube.com/watch?v=csWluHwfsB8</a></li><li><a href="https://www.youtube.com/watch?v=QCJQG4DuHT0&amp;list=PLTl9hO2Oobd97qfWC40gOSU8C0iu0m2l4">https://www.youtube.com/watch?v=QCJQG4DuHT0&amp;list=PLTl9hO2Oobd97qfWC40gOSU8C0iu0m2l4</a></li><li><a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></li><li><a href="https://www.youtube.com/watch?v=IGu7ivuy1Ag">https://www.youtube.com/watch?v=IGu7ivuy1Ag</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c78c2f466b61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Analytics Internship Experience at American Express]]></title>
            <link>https://medium.com/@arunim756/advanced-analytics-internship-experience-at-american-express-511a465810ae?source=rss-675374b48244------2</link>
            <guid isPermaLink="false">https://medium.com/p/511a465810ae</guid>
            <category><![CDATA[internship-experience]]></category>
            <category><![CDATA[amex]]></category>
            <dc:creator><![CDATA[Arunim]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 16:04:32 GMT</pubDate>
            <atom:updated>2023-07-30T16:04:32.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qgf8c4aRm7qV5gaVAdyTAw.jpeg" /></figure><h4>Introduction</h4><p>Imagine spending a summer immersed in the dynamic world of advanced analytics at one of the leading financial services companies in the world. That’s precisely what I experienced during my internship at American Express. In this blog post, I am excited to share my transformative journey, where data-driven decision-making and innovation intersected and my skills as an analytics enthusiast flourished.</p><h4><strong>How I got an internship offer?</strong></h4><p>During my fourth semester at IIT-ISM Dhanbad, the time for internships began, and many famous companies visited our campus. I was thrilled and applied to renowned organizations like Microsoft, Nimbleedge, Trilogy Innovations, Sprinklr, Goldman Sachs, and more. American Express stood out with an exciting MIS-Advanced Analytics profile. To secure the internship, I went through a tough on-campus selection process, which included coding tests, resume shortlisting, and multiple rounds of interviews.</p><p>I felt both excited and nervous as I prepared intensely, revisiting machine learning concepts and improving my skills. When the interviews finally came, I faced them with a mix of nervousness and determination. After all the rounds, my friend Shivankar, the single point of contact (SPOC), called with the incredible news that I had secured the coveted internship opportunity at American Express. I couldn’t believe it and felt so happy and grateful for the chance. This experience taught me the importance of perseverance and dedication 🤩.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*18wrHQJg9WXpwvocFS_YaQ.gif" /></figure><h4>Inside American Express: Empowering Financial Services Innovation</h4><p>American Express, often referred to as Amex is a global financial services company renowned for its extensive range of payment solutions, travel services, and financial products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*FJOCl7xuzxNIeqlu.jpg" /></figure><p>Founded in 1850, American Express has evolved into a trusted brand recognized worldwide. It operates as a major issuer of credit cards, offering various card types tailored to meet the diverse needs of consumers, small businesses, and corporate clients. Additionally, American Express provides merchant services, enabling businesses to accept electronic payments securely. With a strong emphasis on customer service, American Express strives to deliver exceptional experiences and benefits to its cardholders, including rewards programs, travel perks, and personalized financial solutions. Through its continuous innovation and commitment to excellence, American Express remains at the forefront of the financial services industry, empowering individuals and businesses to navigate the world of commerce confidently.</p><blockquote>In the following sections, I will now take you on a virtual tour of my internship at American Express, sharing the remarkable project I was involved in, the outstanding team I worked with, the invaluable lessons I learned, and the personal and technical growth that occurred along the way. Join me as we dive into the heart of advanced analytics and uncover the transformative power it holds within the financial services industry.</blockquote><h4><strong>Received my Laptop from American Express</strong></h4><p>During my sixth semester, while I was busy with end-semester exams, I got a surprising call from a delivery person saying that my Amex laptop had been delivered to my home address. Even though I was in college in Dhanbad, I felt really excited about opening it. I immediately called my mom, and she suggested that I should unbox the package myself when I go back home. After finishing my exams, I eagerly went back home, and as soon as I arrived, I opened the package to see what was inside. When I saw my company laptop, I was incredibly happy and couldn’t contain my excitement. I even took some pictures to remember and cherish the special moment. Attached is an image of the laptop that brought immense anticipation and promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*8YSQ_qo7JgEmQB7l_YdUPQ.png" /></figure><h4>Day One: The Gateway to My Amex Adventure Begins 🤩</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_3MU3SncOOQeQ97uvs4jw.jpeg" /></figure><p>During my first day of internship at the American Express campus building in Gurgaon, I experienced a blend of excitement and nervousness on my first day. Dressed in a formal white shirt, complemented by a red tie, dark blue trousers, and polished formal shoes, I truly felt immersed in corporate life. Stepping into the reception area, my attention was immediately drawn to a striking blue curtain hanging from the ceiling, beautifully adorned with the letters “AMEX.”</p><p>Upon reaching the reception desk, I received my official AMEX ID, complete with a passport-size photo and a unique identification number. I found a comfortable sofa to wait for my mentor, Mohit Vasuja, feeling a bit anxious. When Mohit finally arrived, I greeted him with a polite “Good Morning, Mohit Sir,” as it was customary to address seniors as “Sir” or “Ma’am” in my college 😅. However, Mohit kindly asked me to call him by his first name, highlighting the more relaxed and collaborative culture at American Express.</p><p>While we were talking, our team director, Geetika Puri, passed by, and Mohit introduced me to her. I shook hands with Geetika and greeted her with a friendly “Good Morning, Geetika Ma’am.” Oops, I made the same mistake again by using “Ma’am” 😅. Nevertheless, Mohit assured me that it was okay and that I would quickly adapt to the less formal environment at American Express.</p><h4><strong>My reaction when I entered the office floor</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4DxI8f8I4hwAsiao" /></figure><p>Under Mohit’s guidance, he led me to our office floor, where our team worked on exciting projects. Before entering, we had to show our ID cards for identification. Inside, I was impressed by what I saw. The floor had a sleek and smooth mat covering, creating a welcoming atmosphere. On the right-hand side, there was a small cafeteria offering refreshments for our team. The neatly arranged cubicles with spacious monitors made it easy for everyone to be productive. The walls were adorned with exquisite pictures, adding elegance to the space (I will attach one of them at the end 😁). The vibrant colors throughout the floor made it feel like a dream come true for someone like me, experiencing corporate life for the first time 😍.</p><p>After arriving at my designated area, I waited for my team members to join me, as we had arrived early. During this time, I explored the entire floor. I found additional meeting rooms, ready to host important discussions. One of my favorite spots quickly became the small coffee vending machine, offering unlimited coffee and various biscuit packets for snacking anytime 😁. Moreover, the cafeteria had an impressive vending machine operated through a phone app and Bluetooth, providing easy access to a variety of drinks, chocolates, chips, and more.</p><h4><strong>Team Introductions and Memorable Tea Talks</strong></h4><p>When my team members arrived, Mohit kindly introduced me to each of them. Although I was initially nervous, they understood I was an intern and made me feel comfortable. We shook hands and had lively discussions. As time passed, my shyness disappeared, and I actively participated, enjoying the interaction. They invited me to join them for tea at a nearby shop, which I gladly accepted as a tea enthusiast 😍. During the tea break, our conversations became deeper, and they generously shared insights and valuable advice to help me make the most of my internship.</p><p>Later, I met fellow interns Aakash Rana and Yatharth Manik, and our sense of camaraderie grew stronger in the presence of our supportive team. Mohit then took Aakash and me to a meeting room, where he showed us how to access essential tools for our internship. After the productive session, we had lunch at the cafeteria on the ground floor. The cafeteria had a convenient app-based ordering system, offering one complimentary meal, snack, and beverage. The enjoyable lunch and engaging conversations further solidified our sense of belonging within the team.</p><p>After lunch, we had orientation sessions and meetings with individuals from different countries. Throughout the day, I bonded with my team members individually. As the day came to an end, one of my teammates told me about the office cab system, providing free rides to our homes. With a two-hour commute, I registered for the cab booking app and eagerly awaited its activation after 24 hours. Saying goodbye to my colleagues, I headed home via the Delhi metro.</p><p>And that marked the end of an eventful and fulfilling first day of my internship at American Express 🤩😍.</p><h4>Empowering Customer Experience: My Internship Project — Bad Demand Analysis</h4><p>During my entire internship at American Express, I had the invaluable opportunity to collaborate with Abhishek Kumar, my esteemed mentor, on a project known as “Bad Demand Analysis.” The project focused on addressing challenges faced by customers as they sought resolutions through American Express digital channels like websites and apps. Unfortunately, they encountered issues that led them to contact the American Express contact center, leading us to term these queries as “Bad demands.” Our mission was clear — to delve into these customer calls and employ advanced analytics concepts like Natural Language Processing (NLP) to identify the root causes behind these challenges. Our ultimate aim was to propose effective solutions to enhance the digital channels and elevate the overall customer experience.</p><p>Immersed in data analytics, we meticulously analyzed customer calls, diligently unraveling the intricacies of their problems. Armed with the power of NLP techniques, we deciphered the exact nature and underlying reasons behind these Bad demands, extracting invaluable insights. Empowered with this knowledge, we devised innovative solutions to optimize and refine the digital channels, ultimately streamlining the customer experience.</p><p>Over two enriching months, our dedication propelled us forward, uncovering improvement opportunities in how customers interacted with American Express. It was a captivating story of using data-driven insights and innovative strategies to empower customer experiences, elevating the standard of service that American Express proudly delivers. This extraordinary experience has enriched my skillset and instilled a lasting sense of fulfillment and pride as a contributor to enhancing customer satisfaction at American Express.</p><h4>Learning Experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HYjp4NTbMosalSp9.jpg" /></figure><p>During my internship at American Express, I had the privilege of experiencing many opportunities for personal and professional growth. The learnings I acquired throughout this transformative journey were nothing short of invaluable, and I cannot express enough gratitude to American Express for providing me with such an enriching and fulfilling experience.</p><ol><li><strong>Enhancing Communication Skills:</strong></li></ol><p>During my internship at American Express, I realized the significance of effective communication in a professional setting. Engaging in team meetings and presenting project updates honed my ability to articulate ideas clearly and concisely. Receiving feedback helped refine my communication style, making it more impactful and influential. These newfound skills empower me to be a more confident communicator, a trait I’ll carry forward in my career.</p><p><strong>2. Collaboration with a Team:</strong></p><p>Working with my team at American Express was an enlightening experience. Embracing different perspectives and valuing diverse ideas fostered a creative and supportive work environment. Collaborating on a group project allowed us to harness each team member’s strengths, leading to innovative solutions and efficient problem-solving. Open communication and active listening were pivotal in creating a cohesive and synergistic team.</p><p>3. <strong>Project and Time Management Skills:</strong></p><p>Throughout my internship, I honed essential project and time management skills. Juggling various tasks and deadlines taught me to prioritize tasks effectively and stay organized. Setting clear objectives and breaking down projects into manageable steps ensured smoother workflow and timely completion. These skills proved instrumental in handling multiple responsibilities efficiently.</p><p><strong>4. New Approaches to NLP Problem Statements:</strong></p><p>Diving into Natural Language Processing (NLP) challenges exposed me to cutting-edge approaches in the field. Analyzing customer calls using NLP concepts provided me with valuable insights. Leveraging novel techniques opened up exciting possibilities for future NLP projects.</p><p><strong>5. Big Data Systems Language like SQL:</strong></p><p>Working with big data systems and mastering SQL was a rewarding experience. Extracting, transforming, and analyzing vast datasets enabled better decision-making and actionable insights. Proficiency in SQL empowered me to handle complex data queries efficiently and contribute significantly to data-driven projects.</p><h4>The Team</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDHvcWme8arbWeYwqqCweg.jpeg" /></figure><p>My team at American Express was a vibrant and dynamic group of individuals, each possessing unique talents and expertise. I was part of an incredibly supportive team that played a pivotal role in my growth. They were dedicated to helping me improve not only my technical skills but also my communication abilities. From the outset, I felt welcomed and included; everyone’s friendly and approachable demeanor made me feel at home.</p><p>From a technical perspective, my team encouraged me to explore new perspectives for problem statements in Natural Language Processing (NLP), introducing me to innovative approaches that expanded my problem-solving horizons. Their valuable insights led me to discover new algorithms in NLP, resulting in better results for our project. Their consistent appreciation of my efforts boosted my motivation, driving me to deliver exceptional work.</p><p>Beyond technical mentorship, my team played an integral role in enhancing my personal development, particularly in the realm of communication skills. Observing them during friendly meets and corporate gatherings taught me invaluable lessons in active listening and responding thoughtfully. Engaging in various activities like table tennis and brainstorming games during our friendly meets fostered a sense of camaraderie, making my internship experience productive and enjoyable.</p><p>In essence, the unwavering support and guidance from my team at American Express made my internship journey truly fulfilling. Their mentorship, coupled with a nurturing and collaborative environment, not only sharpened my technical prowess but also equipped me with essential life skills that will undoubtedly shape my future endeavors. I am immensely grateful for the enriching experience and the lasting bonds forged with my exceptional team members.</p><h4>An Unforgettable Journey at American Express</h4><p>As I conclude my blog, I am deeply grateful for the remarkable experience at American Express. The unwavering support from my team and mentors nurtured my personal and professional growth. The camaraderie we shared during friendly meets and the invaluable lessons from my talented colleagues left an indelible mark. Thank you to the entire American Express family for this transformative journey and belief in my potential, shaping me into a more confident individual.</p><p>Thank you, dear readers, for accompanying me on this journey. I hope that my experiences at American Express have provided you with insights into the significance of support, collaboration, and personal growth in a professional environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfI2rBg8mAh-GZpBhlK3SQ.jpeg" /><figcaption><strong>Embrace the possibilities, chase your dreams.</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511a465810ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Machine Learning]]></title>
            <link>https://medium.com/@arunim756/getting-started-with-machine-learning-98e368db5f0f?source=rss-675374b48244------2</link>
            <guid isPermaLink="false">https://medium.com/p/98e368db5f0f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai-vs-dl-vs-ml]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Arunim]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 03:02:54 GMT</pubDate>
            <atom:updated>2023-03-23T03:02:54.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGgoHc3guPkrdBrcdY5MNw.jpeg" /></figure><p><strong>Why Is Machine Learning So Popular Nowadays?</strong></p><p>I know that you must have heard these words like AI, ML, Deep Learning, Data Science, Data Analyst, Data Visualization, etc. almost all around you. I know that you are very curious to know what these words really relate to. That’s why you are here.</p><p>But why they are so much used in almost every technology that you have encountered? This is all about the data. Due to advancements in technology, the amount of data generation has increased exponentially. All the companies generate millions of GBs of data every year. The crucial part for these companies is to use these data to visualize and analyze the behaviors of the market, customers, or whatnot. This leads to new ways to approach complex problems in the market and make optimal decisions for the companies.</p><p>Let’s now start our discussion on machine learning.</p><h3><strong>What is Machine Learning?</strong></h3><p><em>Before starting, I would like to tell you that machine learning is not much difficult as you think. It&#39;s just like a human brain. If you are studying any concept related to ML, just think of it as a human brain and take analogies from that. This way, you will clearly understand the topics much faster.</em></p><p>Machine Learning involves various algorithms which use statistical techniques to analyze and identify patterns in data and then use these patterns to make predictions or decisions on new, unseen data.</p><blockquote>“Machine Learning is a field of study that gives computer the ability to learn without being explicitly programmed.” — by Arthur Samuel(1959)</blockquote><p>Well, a little bit confusing these statements are, right?</p><p>No problem, in a couple of minutes, you are going to understand what these lines actually mean.</p><h3><strong>Understanding ML with an example</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZYa6TuXbvWxrcbXUWeYnA.png" /><figcaption><strong>MNIST Dataset</strong></figcaption></figure><p>Let’s take an example of identifying or classifying an image of a handwritten digit into one of 10 classes(here numbers) representing integer values from 0 to 9.</p><p><strong>Task:</strong></p><p>Identify the number written in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*CIOBUceZIv6WU0-xN2j6eQ.png" /></figure><p><strong><em>How will the human brain work here?</em></strong></p><p><a href="https://www.facebook.com/NeuroNewsResearch/videos/neurons-forming-connections/2728173180533218/">Neurons Forming Connections | Neurons Forming Connections Join our insider group Neuroscience News and Research group. | By Neuroscience News and Research | Facebook</a></p><p>From early childhood, we have seen thousands of numbers written in hundreds of handwritings. During this learning time, the brain analyzed the structures, shapes, and sizes of these numbers and stored this information inside, in the form of activations(connections) among the neurons. These activations are then used by the brain to identify those curves and shapes in the images of numbers and then classify(identify) the number correctly. All this processing of information and classification happens in just a couple of milliseconds.</p><p><strong><em>Now, let’s understand how will the Machine work here.</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3JQ3hYko51Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3JQ3hYko51Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3JQ3hYko51Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b1bf97321cdaee3ec8cbc094c1f3038/href">https://medium.com/media/0b1bf97321cdaee3ec8cbc094c1f3038/href</a></iframe><p>Well similarly to the brain, neural networks (or consider some kind of machine) are provided with a large number of images of handwritten digits(to provide experience with images). They first convert these images into some magic numbers (i.e. pixels) and then input these numbers into their neurons to train them such that they examine and store special patterns from them.</p><p>After the training is done, when an image of the handwritten digit is shown to these networks, the neurons diagnose the pattern of the structure and output the number that is written in the image correctly.</p><p>Now I hope you got a simple overview of a working machine-learning algorithm.</p><p>Now let&#39;s take this understanding a bit level up and talk in technical terms, used in Machine Learning.</p><h3><strong>Basic Working Principles Of Any Machine Learning Algorithm</strong></h3><p>Machine learning (ML) algorithms are computer programs that adapt and evolve based on the data they process to produce predetermined outcomes. They are essentially mathematical models that “learn” by being fed data — often referred to as “training data.”</p><p>These algorithms are mainly divided into two phases :</p><ol><li><strong>Training Phase</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*POVJuoy1SpIsVb9GSut0_A.jpeg" /></figure><p>The training phase in machine learning is a crucial step in the process of building and fine-tuning(optimizing) a machine learning model(algorithm).</p><p>During this phase, the model is fed with some data that consists of <strong>labeled examples</strong> (or you can say, training data just like the example of the large number of handwritten images fed to the machine as discussed above). The training data consists of <strong>input features</strong> <strong>or variables</strong> and corresponding <strong>output labels</strong>. The goal of the training phase is to teach the model(algorithm) to recognize the patterns or relationships between the input features and the corresponding output labels so that it can make accurate predictions on <strong>new, unseen</strong> data. This is done by adjusting the model’s <strong>hidden parameters</strong> based on the training data to <strong>minimize</strong> the <strong>error</strong> between the predicted output and the actual output.</p><p>Hmm, if you didn&#39;t get what these terms are, don&#39;t worry, I got you. If you got it, you can skip this example.</p><p>To better understand this let&#39;s take a simple but practical example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*wjKQHABGEc7f50BAEZ5spw.png" /></figure><p>Consider this weather dataset.</p><p><strong>About the dataset : </strong>Each row in the above dataset refers to a day with features such as “<em>outlook</em>”, “<em>temperature</em>”, “<em>humidity</em>”, and “<em>windy</em>”.</p><p>Forex: From the first row, we can say that a day is sunny (<em>outlook</em>), having a hot <em>temperature</em>, and high <em>humidity</em> but no <em>winds</em>.</p><p>These above are the input features or variables.</p><p>“<em>Play </em>“ is the output feature or label here. This feature represents that on a day with a given set of input features, whether we are going to play or not.</p><p>Forex: In the first row, the day is sunny, hot, and has high humidity but no winds. Thus I don&#39;t want to play on this day given the description of the weather on that particular day.</p><p><strong>Training a model: </strong>Now, after building a machine learning model, we are ready to provide the above training dataset to the model with the corresponding labels. The model will then get automatically trained to predict whether we are going to play on a day with a given set of weather conditions.</p><p><em>How magical is that, now the machine can tell whether I want to play or not. That&#39;s the power of machine learning.</em></p><p>2. <strong>Testing Phase</strong></p><p>The testing phase is the stage where the trained model is evaluated on a set of data that it has not seen previously, to assess(evaluate) its performance and generalization ability(i.e. able to predict output labels correctly for the new and unseen data). This process helps to understand if the model has learned to generalize the patterns present in the training data or if it has just memorized the training data without being able to perform well on new, unseen data. The testing set is representative of the real-world data the model is expected to encounter. It&#39;s just like after studying for a specific subject for weeks, you have to appear for the exams. Studying is the training here. Exams are the testing here. If you just mugged the formulas and concepts during studying then you will not be able to perform well in exams.</p><p>The performance of the model is typically measured using metrics such as accuracy, precision, recall, F1 score, and others. They help to compare the predicted output of the model with the actual output of the testing set. Based on these metrics, performance is evaluated and adjustments are made to improve the model’s accuracy and generalization ability.</p><p><em>This is the basis of all the machine learning algorithms you will see anywhere. If you understood this, then kudos to you! You have just accomplished the first level of understanding of machine learning. If you are confused anywhere, just sit back and relax. Nothing is learned in one go. Read it again and I am sure you will get it this time.</em></p><h3><strong>Types Of Machine Learning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IscoIpyQPFPh12Ug7mOj9Q.jpeg" /></figure><p>Now let’s talk about different types of machine learning algorithms.</p><h3><strong>Supervised Learning :</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*gEHPVtv1BGKftTR3U8g2OQ.png" /></figure><p>Supervised Learning is a type of Machine Learning algorithm in which the computer/machine is fed with a training dataset containing input features and corresponding label outputs and they have to be trained on this specific type of dataset to predict the label outputs.</p><p>The term “supervised” refers to the fact that during the training phase, the algorithm is guided by the correct answers or target values(just like a teacher) to learn how to predict the correct output for new, unseen data.</p><p>Its main goal is to learn a function that can map(searching relationships) between inputs and outputs. This process is done by adjusting the model’s internal parameters to minimize the error between its predicted output and the actual output.</p><p>Supervised learning is further divided into two types of algorithms:</p><p><strong>a. Regression: </strong>In Regression, the output or target values that the model has to predict are <strong>continuous</strong> numerical values, based on a set of input features.</p><p>You probably thinking about what the term “continuous” means.</p><p>“Continuous” numerical values are the values that can take on any real number within a certain given range or interval. This means there are an infinite number of continuous values within a given range.</p><p>Forex: In the range from 0 to 9, continuous values can be 0.51,4.78,2.82,5.82, etc.</p><p>Regression can be used in various types of examples such as predicting the cost of a house based on its location, size, lawn, #bedrooms(number of bedrooms), or you can predict the stock market prices of different shares, etc.</p><p><strong>b. Classification: </strong>In Classification, the target values that the model has to predict are <strong>discrete</strong> numerical values, based on a set of input features.</p><p>“Discrete” numerical values are the values that can take only a finite or countable number of values in a given range.</p><p>Forex: In the range from 0 to 9, discrete values are 0,1,2,3,4,5,6,7,8,9.</p><p>The classification task is used to predict the category or class of a data point into one of the predefined categories or classes.</p><p>Forex: Just as we have taken an example of handwritten images above, the model has to classify the number written in an image into one of 0 to 9 numbers (classes).</p><p>Classification can be used to predict whether an email is spam or not, based on the email content and sender information, or whether precipitation will take place today based on the current weather conditions.</p><h3><strong>Unsupervised Learning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-f9DTG1VZ5bwdDQ5jchSw.png" /></figure><p>Unlike Supervised Learning, Unsupervised Learning is a type of ML algorithm where it is trained on an unlabeled dataset without any predefined outputs or target values.</p><p>The term “unsupervised” refers to the fact that during the training phase, the model is not guided by any predefined outputs. Instead, the model is left alone to discover the relationships between the data and output interesting structures and patterns in the data.</p><p>Its main goal is to discover the patterns or structures in the data without any external guidance, by finding the similarities or differences between data points and grouping them into clusters.</p><p>Unsupervised learning can be harder than supervised learning, as the removal of target values means the problem has become less defined. The model has a less focused idea of what type of patterns and relationships to look for. Imagine it like when you learn some Physics or Maths concept from your teacher(supervision), it becomes easy to understand but when you have to understand them all on your own(no supervision) then it becomes a bit difficult.</p><p>Unsupervised Learning includes various types of algorithms. Some of them are:</p><p><strong>a. Clustering:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cRbLt-FeMsOIGneTjNl0aA.png" /><figcaption>Intuitive example for the human brain</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7iUQffLYHgI-9cJrtyjlw.png" /><figcaption>A formal and actual example used in this type of learning</figcaption></figure><p>Clustering is an algorithm that is used to cluster similar data points together, based on some kind of similarity measures or metrics. Its objective is to find groups or clusters of data points that are similar to each other and different from other clusters.</p><p>As the data is not labeled, we are not restricted to choosing the number of clusters that we want to make for the data. So it&#39;s like a model parameter that we have to optimize using efficient model selection and testing.</p><p>Clustering examples include customer segmentation based on past buying behavior, anomaly detection, image segmentation, etc.</p><p><strong>b. Dimensionality Reduction:</strong></p><p>Dimensionality reduction algorithms aim to reduce the number of features in a dataset while preserving as much information as possible. This is useful when dealing with high-dimensional data(when containing a large number of input features), as it can be difficult to analyze and visualize. Examples of dimensionality reduction algorithms include principal component analysis (PCA) and t-SNE.</p><p><em>If you don&#39;t get it, don&#39;t worry. This concept is actually a bit more conceptual and not easy to understand. If you want to study it in depth, I will give you links at the last where you can find clearer explanations of these types of difficult and confusing topics with brilliant examples.</em></p><p><strong>c. Associative Rule Learning:</strong></p><p>Association rule learning algorithms aim to find relationships between different variables in a dataset. For example, a retailer might use association rule learning to discover that customers who buy diapers are also likely to buy baby food. This can be used for market basket analysis and recommendation systems.</p><h3><strong>Semi-Supervised Learning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKMk3KflwBsBiRYrn6ZrSQ.png" /></figure><p>Semi-Supervised Learning is a special type of machine learning which is a combination of supervised learning and unsupervised learning.</p><p>The model is trained on a dataset that contains a mixture of labeled and unlabeled data. The labeled data provides the algorithm with some ideas and the correct output for a given input while the unlabeled data provides additional information that can help the algorithm better understand the underlying structure of the data.</p><p>Its main advantage is that it can be used to achieve higher accuracy than supervised learning with a much smaller labeled dataset. That is because the model can learn from much larger unlabeled data which can help it to better understand the patterns and relationships among the data which it may have missed.</p><h3><strong>Reinforcement Learning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jApvWKcacTfxLZcZ3uopTw.png" /></figure><p><em>(If you have studied psychology, then you must have known the term reinforcement learning. If yes, let&#39;s discuss this in terms of machine learning)</em></p><p>Reinforcement Learning is by far the most interesting and complex form of machine learning. It&#39;s a type of machine-learning algorithm that involves an agent and its environment. The agent learns by interacting with its environment and receiving rewards or punishments based on its actions.</p><p>During the learning phase, the agent is presented with a problem or task and it must decide what action it should take for that task based on the current state of the environment. The agent’s actions lead to change in the environment and the agent receives a feedback signal in the form of a reward or penalty based on the outcome of its action.</p><p>Thus, we can say that its main goal is to learn the optimal strategy for maximizing its long-term rewards, which leads to an exploration of different types of actions by the agent to achieve the best outcome.</p><p>Well if you didn&#39;t get quite much from the above explanation, then let&#39;s take some practical examples from everyday life.</p><p>Let’s take an example from Pavlov’s theory of reinforcement learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*U3kuOdYt7kXh6skQ-A2t8w.png" /></figure><p>Pavlov presented his dog with food which is an unconditioned stimulus(don’t worry about the term) and the dog reacted to this with salivation in its mouth.</p><p>Then Pavlov whistled but this time, there was no salivation shown by the dog.</p><p>Then Pavlov paired the whistle with food and every time he whistled, he gave the dog food(reward) which results in salivation.</p><p>Now, the dog is trained and whenever he whistled, the dog responded by salivation even if the food was not given that&#39;s because the dog was reinforced(trained) that whenever he whistles, the dog is given food.</p><p>Reinforcement learning is greatly used in games where they have surpassed human intelligence and play those games well. They can also be used in self-driving cars.</p><p>Here comes the end of different types of the machine learning topic. Well a lot of learning did happen above, right?</p><p>We first learned why and what is machine learning, then moved on to the different types of machine learning in great detail.</p><p>But I want to discuss a main topic which everyone is confused about. You must have heard about the terms Deep Learning and Artificial Intelligence as well. It also should have come to your mind whether these all are the same thing or if is there any difference exists among them. It&#39;s very important to clarify this confusion now.</p><h3>AI vs ML vs Deep Learning</h3><p>Most people think that these terms are all the same and that we can use them interchangeably anywhere. But this is a wrong statement. Let&#39;s clear out this confusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*GLuyMxA0uy4BXnu8RY-mDA.png" /></figure><p><strong>Artificial Intelligence: </strong>AI is a broad concept that encompasses(comprises) different types of techniques for creating intelligent machines/models that can perform tasks that require human intelligence such as visual perception, speech recognition, decision-making, etc. It covers everything that makes machines behave just like a human brain.</p><p><strong>Machine Learning: </strong>Machine Learning (ML) is a subset of AI that involves the use of statistical algorithms to allow machines to learn relationships and patterns from the data, improve their performance and make predictions without being explicitly programmed.</p><p><strong>Deep Learning: </strong>Deep Learning (DL) is a subset of ML that involves the use of neural networks to process and analyze large amounts of complex data like images, speech, etc. They achieve a significantly higher accuracy where the ML algorithms have poorly performed.</p><h3>Final Notes</h3><p>We have learned a lot many things in this article related to Machine Learning. I hope I have developed a new connection to your neurons about what machine learning is all about. I now hope that you can now interpret the definitions of machine learning that I used above.</p><p>This is my first article. If there is anything that you guys need to add to this article, feel free to message me, and don&#39;t hesitate. I would love to hear from you guys. Thank you for reading this article. If you have reached here, then hurray! You have taken the first step in pursuing a machine learning carrier. If you find this article helpful, then you can message me on what more topics shall I write an article about. Any suggestions are welcome. More articles are coming. Stay tuned for that!</p><p>Ending with a final quote:</p><blockquote>“AI is the new electricity. Just as electricity transformed almost everything 100 years ago, today I actually have a hard time thinking of an industry that I don’t think AI will transform in the next several years.” — by Andrew Ng</blockquote><h3><strong>References</strong></h3><ol><li><a href="https://in.coursera.org/specializations/machine-learning-introduction">Machine Learning Specialization by Coursera</a></li><li><a href="https://in.coursera.org/specializations/deep-learning">Deep Learning Specialization by Coursera</a></li><li><a href="https://www.youtube.com/@krishnaik06/featured">Krish Naik Youtube Channel</a></li><li><a href="https://www.slideshare.net/ArunimBasak1/machine-learning-roadmappdf">Machine Learning Roadmap</a></li><li><a href="https://www.jovian.com/">Jovian</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98e368db5f0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>