<?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 Gagan Ajjikuttira on Medium]]></title>
        <description><![CDATA[Stories by Gagan Ajjikuttira on Medium]]></description>
        <link>https://medium.com/@gaganganapathy?source=rss-45afc0d3f4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zseA9n-mpHSxgRvXTzQYGw.jpeg</url>
            <title>Stories by Gagan Ajjikuttira on Medium</title>
            <link>https://medium.com/@gaganganapathy?source=rss-45afc0d3f4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gaganganapathy/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[Understanding post-training of LLMs: RLHF]]></title>
            <link>https://ai.plainenglish.io/understanding-post-training-of-llms-rlhf-ed5ede07d071?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed5ede07d071</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[post-training]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 05:20:32 GMT</pubDate>
            <atom:updated>2026-02-24T05:09:09.563Z</atom:updated>
            <content:encoded><![CDATA[<p>In the write-up we’ll look into what RLHF <em>(Reinforcement Learning from Human Feedback)</em> is really doing, and its conceptual comparison with <a href="https://medium.com/@gaganganapathy/understanding-post-training-of-llms-dpo-e3978d43aeb0">DPO</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eO6vosi8f74tIZ0hYuOQow.png" /></figure><p>Assume we’re at a step where we’ve performed SFT on the base model and it is able to produce decent answers. With RLHF, the goal is similar to DPO, induce the concept of taste that allows the model to produce better answers based on some human grading / preferences.</p><p><strong>There are two stages in the RLHF loop:</strong></p><ul><li>Train a reward model</li><li>Reinforcement learning (PPO)</li></ul><h4>Stage 1: Train a reward model</h4><p>In this stage, we collect human comparisons:</p><pre>Prompt<br>Answer A<br>Answer B<br><br>Human says: A is better</pre><p>Now instead of training the LLM directly like in DPO, you train a separate neural network that takes in (prompt, answer) and outputs a scalar reward score.</p><p>The model learns that higher score == more human-preferred answer. The goal here is to approximate human judgement.</p><p><strong>How is this done exactly?</strong></p><p>To be more clear, in classical RLHF, there are two model different models after SFT:</p><ul><li>The <strong><em>policy model</em></strong> (the LLM you want to improve)</li><li>The <strong><em>reward model</em></strong> (a separate network the scores answers)</li></ul><p>Usually, the architecture of the reward model starts with the same pre-trained backbone as the SFT model. But instead of predicting next tokens, it adds a single linear head that outputs a scalar<em> (the reward)</em>.</p><p><strong>How is the reward model trained?</strong></p><p>For each comparison, we compute the following:</p><pre>reward(prompt, chosen_answer) --&gt; r_chosen<br>reward(prompt, rejected_answer) --&gt; r_rejected</pre><p>We essentially want (r_chosen &gt; r_rejected), so similar to the ranking idea we in DPO we apply a logistic loss:</p><pre>L = -log_probs(r_chosen - r_rejected)</pre><p>So the reward model here learns to assign higher reward to the answers human prefer. We train the reward model until it reasonably captures human taste.</p><h4>Stage 2: Reinforcement learning (PPO)</h4><p>Up until now, we have two models the SFT LLM and the trained reward model.</p><p>Next we want to tweak the SFT LLM using the reward model to generate answers that get higher reward scores.</p><p>The overall RL loop put simply is:</p><ol><li>Generate answer from policy model.</li><li>Compute reward using reward model.</li><li>Update policy model to make high-reward answers more likely.</li></ol><p>Repeat thousands of times.</p><p><strong>Let’s dive a bit deeper into the 3rd point above:</strong></p><p>Suppose the policy model generates answer Y and the reward model gives R(X, Y) = 2.5, we want to increase P_policy(Y | X). So the objective here is to maximize the expected reward. <em>(here X is the prompt)</em></p><p>But there’s a problem — if we only maximize reward the model might drift too far from the original behavior, diversity might collapse and it could start exploiting reward model loopholes<em> (reward hacking).</em></p><p>So we need to add some penalty, to make sure it stays close to the reference model. So the final objective we update the policy is — to maximize reward but don’t drift too far.</p><pre>Objective = reward − penalty</pre><p><strong>What exactly is this penalty?</strong></p><pre>Penalty = β × KL(policy || reference)</pre><p>Here KL is the measure of how different one probability distribution is from another. So essentially we’re measuring how the policy model’s distribution over answers differs from the reference model’s.</p><p>Intuition:</p><ul><li>KL = how much did we change the model’s behavior?</li></ul><p>And β controls the balance between how much should the reward push the model towards high-scoring answers and how much should KL pull the model back towards original SFT behavior.</p><p><strong>(Optional) How is the update made to the model?</strong></p><p>For a prompt X, the policy generated an answer Y. And then we compute a score:</p><pre>J = R(X, Y) - β × KL(policy || reference)</pre><p>Here J is just a number, we want to maximize this number. In deep learning, to maximize something, we take the gradient of it w.r.t to the model parameters and step in that direction<em> (back-prop). </em>But how do you produce a gradient out of a number?</p><p>There is a famous policy gradient trick! This allows us to define the gradient of the reward as follows:</p><pre>Gradient of reward = reward x gradient of logP_policy(Y)</pre><p><strong>What this means intuitively?</strong></p><p>Suppose the model sampled answer Y and reward = +3. The update is proportional to:</p><pre>~ +3 x gradient of logP_policy(Y)</pre><p>Since, gradient of logP increases probability of Y → high reward increases the probability of that answer.</p><p>Now for the gradient of the KL term:</p><pre>KL = sum over answers y of logP_policy(Y) x (logP_policy(Y) / logP_ref(Y))<br><br>&quot;&quot;&quot;<br>In words -- for every possible answer, take:<br><br>the probability the policy assigns to that answer<br>×<br>the log of (policy probability divided by reference probability)<br>&quot;&quot;&quot;<br></pre><p>This can also we written as:</p><pre><br>KL = sum over y of logP_policy(Y) × [ logP_policy(Y) − logP_ref(Y) ]</pre><p>As an approximation, we can consider KL to be :</p><pre>KL ~ average of (logP_policy(Y) − logP_ref(Y))</pre><p>Since, reference model is frozen the derivative w.r.t to policy model weights is zero. So the gradient of the KL term is simply:</p><pre>grad(KL) = β x gradient of logP_policy(Y)</pre><p>Coming back to the gradient of the complete reward equation (J):</p><pre>grad(J) = reward x grad(logP_policy(Y)) - β x grad(logP_policy(Y))<br><br>grad(J) = (reward - β) x grad(logP_policy(Y))<br><br>grad(J) = A x grad(logP_policy(Y))</pre><p>Here A is the adjusted reward effectively when updating the model parameters.</p><h4>Compare this back to how SFT does the update:</h4><p>In SFT:</p><pre>We use grad(logP_policy(correct_answer))</pre><p>In RLHF:</p><pre>We use A x grad(logP_policy(sampled_answer))</pre><p>So in essence, RLHF is just SFT but the weight in front of the gradient depends on the reward.</p><h4>How RLHF compares with DPO:</h4><p>At a high level, both RLHF and DPO are trying to do the same thing: reshape a language model so that it prefers answers humans prefer, while staying close to its original (SFT) behavior. The difference is in <em>how</em> they get there.</p><p>RLHF takes an indirect route. It first trains a separate reward model to mimic human judgments. Then it treats the language model like a policy in reinforcement learning and updates it to maximize that reward, while adding a KL penalty so the model doesn’t drift too far from the reference model. In other words, RLHF learns a “judge” and then trains the model to please that judge.</p><p><strong>DPO starts from a key insight about RLHF</strong>: if you solved the RLHF objective perfectly, the new model would simply increase the log-probability of high-reward answers relative to the reference model, and decrease it for low-reward ones. That means reward differences ultimately translate into log-probability differences. So instead of training a reward model and running an RL loop, DPO directly enforces this relative log-probability condition using preference pairs. It skips the “learn a judge” step and directly reshapes the probabilities in the direction the judge would have pushed them.</p><p>I wouldn’t dive into when to use RLHF over DPO and vice-versa, that’s a potential topic you could read up on after this.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community.</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed5ede07d071" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/understanding-post-training-of-llms-rlhf-ed5ede07d071">Understanding post-training of LLMs: RLHF</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding post-training of LLMs: DPO]]></title>
            <link>https://ai.plainenglish.io/understanding-post-training-of-llms-dpo-e3978d43aeb0?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3978d43aeb0</guid>
            <category><![CDATA[post-training]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 00:03:02 GMT</pubDate>
            <atom:updated>2026-02-17T00:03:02.048Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m hoping you read the <a href="https://medium.com/@gaganganapathy/understanding-post-training-of-llms-sft-db493262539f">post</a> about SFT, if not would highly recommend doing that first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pdo6lFaTQrD0uWhZNXcVmg.png" /></figure><h4>So why is SFT not enough?</h4><p>Imagine your dataset contains the following:</p><pre>Prompt:<br>&quot;Is lying ever acceptable?&quot;<br><br>Responses:<br>1. Careful nuanced ethical answer<br>2. Slightly shallow but acceptable answer<br>3. Overconfident incorrect answer</pre><p>SFT pushes the probability mass toward the average of these. It cannot learn if Response 1 is better than Response 2. It just learns to imitate what appears.</p><h3>Preference optimization:</h3><p>In simple words, instead of training on (prompt → single good answer), we train on (prompt, chosen_answer, rejected_answer)</p><p>Now the objective becomes:</p><ul><li>Increase the probability of chosen</li><li>Decrease the probability of rejected</li></ul><h4>There are two main approaches for doing this:</h4><ol><li><strong><em>RLHF</em></strong></li></ol><ul><li>You train a reward model</li><li>Generate responses</li><li>Use PPO to maximize the reward</li></ul><p>2.<strong><em> DPO (Direct preference optimization)</em></strong></p><ul><li>This is the modern approach, no reward models</li><li>No PPO, No sampling loop</li></ul><h4>What DPO actually changes in the model</h4><p>SFT:</p><ul><li>Teaches format</li><li>Teaches compliance</li></ul><p>DPO:</p><ul><li>Teaches taste, ranking</li><li>Teaches subtle preference shifts</li></ul><h4>Intuition behind DPO:</h4><p>To start off, what are we even trying to do? So you have:</p><ul><li>A model that generates answers</li><li>A dataset where humans said: “Between these two answers, this one is better”</li></ul><p>That’s it. For Example:</p><p>If the given prompt is:</p><blockquote>Should I lie to protect someone’s feelings?</blockquote><p>Two model answers:</p><ul><li>A: Yes, lying is fine if it helps.</li><li>B: It depends. Honesty matters, but sometimes gentle phrasing is better.</li></ul><blockquote>Humans say: B is better than A.</blockquote><p>We want the model to, <strong><em>Prefer B</em></strong> and <strong><em>Avoid A</em></strong></p><p>That’s the entire goal of DPO. Learning the preference here, which means shifting the probabilities towards B than A.</p><h4>How is this dataset built in the first place?</h4><ol><li>Take a base model</li><li>For each prompt, generate multiple responses (sample 2–8 outputs)</li><li>Human annotators rank them</li></ol><p>So for a prompt, if the model outputs A, B, C. Human might rank them as B &gt; A &gt; C. Now we create pairs: (B, A), (B, C), (A, C) — this becomes your preference dataset.</p><p><strong><em>But you might think wouldn’t it always generate the same responses? Since the prompt is the same?</em></strong></p><p>During preference data collection, we might vary the temperature, top-p sampling etc to introduce some randomness across the outputs.</p><h4>Let’s dive into the math a little</h4><p>Stuff we already know from SFT — for any prompt X and answer Y, we can compute the sum of log-probabilities of answer tokens. We do that both the trainable and the reference model.</p><pre>logP_train(Y | X) # The model we&#39;re trying to train here<br>logP_ref(Y | X) # The reference model </pre><p>In DPO, we want to increase the probability of the chosen answer (Y+) and reduce the probability for the rejected answer (Y-). That way, the trainable model prefers answer Y+ instead of Y-.</p><p>In probability terms:</p><pre>P_train(Y+ | X) &gt; P_train(Y- | X)<br><br># Since log preserves order, we look at:<br><br>log(P_train(Y+ | X)) | log(P_train(Y- | X))</pre><p>But that’s not enough — we need to anchor these probabilities to the reference model.</p><h4>Why though?</h4><p>Suppose we define the loss as:</p><pre>A+ − A− = log(P_train​(y+)) − log(P_train​(y−))</pre><p>And we train to maximize this value, we push logP(y+) higher and logP(y-) lower. Sounds fine, right? Here’s the problem:</p><p><strong>Problem 1: The model can drift wildly</strong></p><p>The model could increase, logP(y+) a lot and decrease logP(y-) massively. But in doing so, it might:</p><ul><li>Ruin probabilities of unrelated answers</li><li>Collapse diversity</li><li>Become overly confident</li><li>Destroy previous good behavior</li></ul><p>There is <strong>no constraint</strong> keeping it near reasonable behavior. It can potentially distort the entire distribution just to satisfy local comparisions.</p><p><strong>Problem 2: Scale is arbitrary</strong></p><p>Probabilities live in a huge high-dimensional space. If you don’t anchor, the model could increase logP(y+) for every possible answer. Or shift everything up/down together. There is no baseline telling it what “reasonable” looks like.</p><h4>What does the anchor do?</h4><p>We define:</p><pre>A(y) = log(P_train(y)) - log(P_ref(y))</pre><p>This measures, <strong>how much did we change this answer compared to the original model.</strong></p><p>So now we train on:</p><pre>A+ - A- = (log(P_train(y+)) - log(P_ref(y+)) - (log(P_train(y-)) - log(P_ref(y-))</pre><p>We essentially, improve relative to how the original model scored it. It cannot inflate probabilities globally.</p><ul><li>w/o the anchor: “The model can cheat by shifting everything”</li><li>w/ the anchor: “The model must genuienly improve chosen relative to rejected, compared to its original behavior”</li></ul><p>Next, we will learn how this compares to RLHF</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3978d43aeb0" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/understanding-post-training-of-llms-dpo-e3978d43aeb0">Understanding post-training of LLMs: DPO</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding post-training of LLMs: SFT]]></title>
            <link>https://ai.plainenglish.io/understanding-post-training-of-llms-sft-db493262539f?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/db493262539f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[post-training]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 00:01:57 GMT</pubDate>
            <atom:updated>2026-02-17T00:01:57.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*2QR8OVMf7q6at7qMXT797A.png" /></figure><h3>In a gist:</h3><p>Post-training is all about guiding the model to be a better assistant, its not adding any new knowledge or making the model smarter. Its about format alignment<em> (follow instructions)</em>, behavior shaping <em>(helpful &gt; harmful)</em> and preference modeling <em>(choosing better responses)</em></p><p>There are two key techniques used here:</p><ul><li>SFT (Supervised fine-tuning) — imitate good behavior</li><li>RLHF / DPO (Preference optimization) — choose better of two outputs</li></ul><blockquote>Pre-training learns knowledge, Post-training learns taste</blockquote><h3><strong>Supervised fine-tuning (SFT)</strong></h3><p>This process simply put is to continue training the pre-trained model using labeled (prompt → ideal response) examples.<strong><em> That’s it</em></strong>.</p><p>But what makes it powerful is <em>where</em> and <em>how</em> that training signal is applied.</p><p>Let’s recall how pre-training works — its aim is to increase the probability of the next correct token given previous tokens.</p><h4>What changes in SFT?</h4><p>In SFT, we structure the input like this:</p><pre>&lt;Instruction&gt; Write a haiku about GPUs.<br>&lt;Response&gt; Silicon dreams hum..</pre><p>And we train the model to predict only the response tokens. Mathematically, its the same objective. Nothing fancy changed. Same cross-entropy, Same gradient descent, Same backprop. Only the data distribution shifted.</p><p>So with steering the distribution, we’re making behave in a certain way <em>( like an assistant, in the case of chat applications). </em>It is essentially changing how the knowledge the model has is accessed and expressed.</p><h4>Overfitting?</h4><p>These SFT datasets are tiny compared to pre-training, so overfitting to those patterns happens easily. So SFT can make the model overly verbose, reduce diversity and increase hallucinations (confidence bias). This is why preferences optimization comes next.</p><h4>How does SFT affect the model weights?</h4><p>Vanilla SFT updates all the model weights, there is no restriction on which parts it might update. But in practice, the certain parts of the model are frozen (with LoRA), which only updates parts of the model.</p><p><strong>What is LoRA you might ask:</strong></p><p>Instead of updating the full weight matrix (W). Essentially trying to modifying the behavior without re-writing the core knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhTNROpkPTiUWGxVaFL6IQ.png" /><figcaption>chatgpt</figcaption></figure><blockquote>Only low-rank adapter learn</blockquote><h4>What Does “Low-Rank Adapters Learn” Mean?</h4><p>Let’s take a normal linear layer — for a 4k model the d x d would 4096 x 4096 ~ 16M parameters to train for just one projection.</p><p>In full fine-tuning — every entry in this matrix can change independently. That’s super flexible, but also very expensive and unstable.</p><p>What LoRA does is — it learns a sub-space of this matrix by freezing W and learning delta-W ~ AB (where A = d x r, B = r x d) where r &lt;&lt; d. This is huge reduction in the trainable params.</p><p>If r = 16, 4096 x 16 + 16 x 4096 ~130k params.</p><p>A rank of matrix roughly indicates how many independent directions of transformation it can represent. A full d x d matrix can represent transformations in all d dimensions. But a product AB where the inner dimension is r has rank at-most r.</p><p>So effectively, you’re saying, we will only allow weight updates that lie in a small sub-space. And surprisingly that enough to dramatically change behavior.</p><h4>Why Freeze the Base Model?</h4><p>Two main reasons:</p><ul><li><strong>Stability</strong>: Full fine-tuning can destroy pre-trained knowledge. Cause catastrophic forgetting. Overfit on tiny datasets. LoRA protects the backbone.</li><li><strong>Efficiency</strong>: Store only adapter weights. Swap behavior easily.</li></ul><h4>Where is LoRA generally applied?</h4><p>Most commonly, applied to the attention layers. Applying to Q, K, V, and sometimes O. Since, attention layers control information routing and shape how token influence each other — its the best place to strongly influence behavior.</p><p><strong>The intuition behind it:</strong></p><p>Very roughly — attention is where the information routing happens, and MLP layer is where the feature transformation / computation happens.</p><p><strong>For light instruction tuning — modify Q + V — why?</strong></p><ul><li>Q (query) controls “what information am I looking for?”</li><li>V (value) controls — “what information gets written forward?”</li></ul><p>So tweaking Q and V — ensures we slightly change what token we attend to and what information is passed forward. But we don’t completely re-write how attention works.</p><p>Because instructions following is mostly, pattern recognition, format imitation. You’re teaching: “When you see X, respond in Y style”. That lives in the routing layers.</p><p><strong>For strong behavior change — modify Q + K + V + O — why?</strong></p><ul><li>Q: what to look for</li><li>K: how tokens advertise themselves</li><li>V: what gets written</li><li>O: how attended information gets integrated</li></ul><p>This lets you reshape the entire attention mechanism.</p><p><strong>Domain shift — modify the MLP layer — why?</strong></p><p>This where the non-linear transformation happens. MLPs are believed to store facts, concepts, high-level features, compositional representations.</p><p>So, if you want to teach legal style, adapt to medical domain, or introduce new abstraction patterns — modify the MLP. Since, domain shift is not just about routing information, its about changing the internal feature space.</p><p>Here we’re updating how the model thinks, not just what is pays attention to.</p><p><strong>For an extreme shift — full fine tune</strong></p><p>This is when you want a coding model from a chat model, or a reasoning model from a base LLM.</p><h4>So where does behavior live?</h4><ul><li>Style, safety, formatting → mostly attention</li><li>Knowledge, abstractions, deep reasoning → mostly MLP</li><li>Global personality → higher layers</li><li>Syntax &amp; language basics → early layers</li></ul><p>Next up, we will learn about preference optimization (DPO).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db493262539f" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/understanding-post-training-of-llms-sft-db493262539f">Understanding post-training of LLMs: SFT</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Interpretability: Coding the GPT-2 attention layer]]></title>
            <link>https://ai.plainenglish.io/llm-interpretability-coding-the-gpt-2-attention-layer-6a77ef946dad?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a77ef946dad</guid>
            <category><![CDATA[interpretability]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Sun, 21 Sep 2025 00:09:55 GMT</pubDate>
            <atom:updated>2025-09-21T23:46:18.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WQQNn67Lz3D-kRIWmsQSg.png" /><figcaption><a href="https://shorturl.at/qJ6gc">https://shorturl.at/qJ6gc</a></figcaption></figure><p>Okay, now that you have the intuition for how a single head attention works, lets shake things up a bit with multiple heads, shall we?</p><p>I think Neel Nanda <a href="https://youtu.be/dsjUDacBw8o?si=vf1ciN0xAmXO4q4d">here</a> does a fabulous job at implementing the attention layer for GPT-2. In this article, I will try to break it down in the most easiest way possible, building on top of the intuition we learned from the <a href="https://medium.com/@gaganganapathy/llm-interpretability-coding-simple-attention-8e922adfb68a">previous article</a>.</p><p>In practice, models use multiple attention heads within a single transformer block. If you asked why is that, then here’s a quick reasoning as to why ..</p><p>In more complex sentences there are different things you might show attention on for example:</p><blockquote>“The capital city of France, Paris is extremely crowded during the summers”</blockquote><p>You can see there are different useful relationships inside the same sentence. <em>One head alone can only focus on a single kind of pattern</em>. Some example of the different strategies different heads can learn as they’re trained:</p><p><strong>Entity ← → Definition head:</strong></p><ul><li>Might connect <em>“Paris”</em> strongly to <em>“capital city of France”</em>.</li><li>This helps the model recognize Paris as the capital, not just a random city.</li></ul><p><strong>Modifier ← → Noun head:</strong></p><ul><li>Might connect <em>“crowded”</em> back to <em>“Paris”</em>.</li><li>Ensures the model understands it’s Paris that’s crowded, not “France” or “summers.”</li></ul><p>And so on ..</p><p><strong>Each head has its own query/key/value projections</strong> → they’re like different sets of glasses the model puts on. After all heads do their job, their results are combined, so the model gets a rich, multi-view representation of the sentence.</p><p>If I’ve convinced you why you need multiple attention heads, lets move on and understand how you could implement it. <strong><em>I’ve kept the steps exactly similar to how the simple attention was implemented so that you can draw parallels and compare them side-by-side ..</em></strong></p><h3>Defining Q/K/V projection weight matrices:</h3><p>For a single attention head, we used a projection matrix W_Q of shape [d_model x d_model] , now with some N number of heads, we introduce a dimensionality for each head called d_head. Considering this, we can create the projection matrices with shape — [n_heads x d_model x d_head] where n_heads x d_head = d_model .</p><blockquote>Pause, and take a moment to fully understand this ..</blockquote><p>In <em>very</em> simple terms, we’ve split the d_model dimension into n_heads partitions.</p><p>Let’s cross-check this with the actual GPT-2 model internals .. you see W_Q is [12 x 768 x 64] where n_heads = 12 , d_model = 768 , d_head = 64 and yup you guessed it right (64 x 12 = 768) :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*v-Lpd7-sEfVLcncYmfGsPw.png" /></figure><pre>self.W_Q = nn.Parameter(torch.empty((n_heads, d_model, d_head)))<br>self.W_K = nn.Parameter(torch.empty((n_heads, d_model, d_head)))<br>self.W_V = nn.Parameter(torch.empty((n_heads, d_model, d_head)))</pre><h3>Defining biases for these projection weights:</h3><p>When you think about initializing the bias matrices, we need to think about its shape. Let’s understand the intuition behind it ..</p><pre>out = W x inp + b<br><br>W   --&gt; is the projection weight matrix (W_Q, W_K .. )<br>inp --&gt; is the actual input matrix we get after embedding <br>        and any information that being passed from one transformer block<br>        to another.</pre><p>This is a simple linear function that we perform to get the output with weights and biases. Let’s look at their shapes …</p><pre>W       --&gt; [n_heads, d_model, d_head]<br>inp     --&gt; [batch, pos, d_model]<br><br>------------------------------------<br>W x inp --&gt; [batch, pos, n_heads, d_head]<br><br>b       --&gt; ??        </pre><p>Therefore, the bias vector should be of shape [n_heads x d_head] . Why ?</p><p>The bias only needs to shift each head’s query vector, not depend on the input dimension d_model .</p><ul><li>Each query vector output has size d_head</li><li>There are n_heads separate projections.</li><li>Therefore, each head needs its own bias vector of size d_head</li></ul><p>So stacking them together gives a tensor of shape [n_heads x d_head]</p><pre>self.b_Q = nn.Parameter(torch.zeros((n_heads, d_head)))<br><br># NOTE: define similarly for b_K and b_V</pre><h3>Step 1: Make Queries, Keys, Values</h3><p>Now that we have the matrices to learn attention patterns setup, let’s use them with the input to perform the linear projection W x inp + b as shown above :</p><blockquote>NOTE: Read up a little about einsum, its super useful and neat for transformations!</blockquote><pre>q = einsum(<br>    &quot;&quot;&quot;<br>    batch query_pos d_model,<br>    n_heads d_model d_head<br>    -&gt;<br>    batch query_pos n_heads d_head<br>    &quot;&quot;&quot;,<br>    inp, self.W_Q<br>) + self.b_Q<br><br># NOTE: do similarly for Key (k) &amp; Value (v) ..</pre><p>Einsum lets us define the transformation we want in plain english, simply defining the dimensions we need to tranform. Very similar to how we intuitively look at input &amp; output dimensions. The following is exactly the shapes as mentioned in the linear function above!</p><h3>Step 2: Compute attention scores</h3><p>Attention scores if you remember from the single head implementation — where each word’s <strong>Query</strong> is compared against every other word’s <strong>Key</strong> using dot products. We do that same using einsum …</p><pre>attn_scores = einsum(<br>    &quot;&quot;&quot;<br>    batch query_pos n_heads d_head,<br>    batch key_pos   n_heads d_head<br>    -&gt;<br>    batch n_heads query_pos key_pos<br>    &quot;&quot;&quot;,<br>    q, k<br>)<br><br># NOTE: query_pos and key_pos are the same value wise, <br>#       naming them differently for clarity</pre><h3>Step 3. Scale the scores</h3><p>Prevent scores from exploding as a result of the dot-prodcuts .. <em>(don’t worry about this too much)</em></p><pre>attn_scores = attn_scores / math.sqrt(d_head)</pre><h3>Step 4: Apply a causal mask</h3><p>Ensuring we build the attention pattern only using the words seen in the past and block all the words after the current word. So we first we build an upper-triangular matrix and set all the values with some super small value like -inf so that after softmax its probability becomes zero.</p><pre>attn_scores = apply_causal_mask(attn_scores)<br><br>def apply_causal_mask(self, attn_scores):<br>    # attn_scores: [batch, n_heads, query_pos, key_pos]<br>    mask = torch.triu(torch.ones(<br>                        attn_scores.size(-2), # query_pos<br>                        attn_scores.size(-1), # key_pos <br>                        device=attn_scores.device<br>                      ), diagonal=1).bool()<br>    attn_scores.masked_fill_(mask, float(&#39;-inf&#39;))<br>    return attn_scores</pre><h3>Step 5. Turn scores into probabilities</h3><pre>attn_pattern = attn_scores.softmax(dim=-1)</pre><p>Now we turn those raw scores into <strong>probabilities</strong> that add up to 1. Each row is: “How much attention should I give to each word in the sentence?”</p><ul><li>Example: “Paris” might attend 80% to “France” and 20% to “city”.</li></ul><h3>Step 6. Mix the Values</h3><pre>z = einsum(<br>    &quot;&quot;&quot;<br>    batch n_heads query_pos key_pos,<br>    batch key_pos n_heads d_head<br>    -&gt;<br>    batch query_pos n_heads d_head<br>    &quot;&quot;&quot;,<br>    pattern, v<br>)</pre><p>Let’s slow this one down, because this einsum is the <em>heart</em> of how attention actually gathers information ..</p><pre>pattern --&gt; [batch, n_heads, query_pos, key_pos]<br># For every batch, every head, and every query position, <br># it holds the attention weight assigned to each key position<br><br># Intuition: How much query token q (in head h) should look at key token k?<br><br><br>v       --&gt; [batch, key_pos, n_heads, d_head]<br># For every batch, every key position, and every head, <br># it holds the value vector of length d_head.<br><br># Intuition: the information available at key token k in head h<br><br><br>z       --&gt; [batch, query_pos, n_heads, d_head]<br># Intuition: For every query position q and every head h, you get <br># one aggregated value vector - a weighted average of all the values <br># it decided to look at.</pre><p>Here we essentially use the attention pattern and mix it with the <strong>values (v). </strong>The output <strong>(z) </strong>is the <strong>per-head context vector per query token </strong>i.e <strong>its the “answer” each attention head produces before the results of different heads are combined.</strong></p><p>Next is the combine step so that we blend the heads together into a single vector of size d_model instead of having N heads each with information stored in dimension d_head → i.e we want an output tensor of shape [batch, pos, d_model] so the model can keep working in its original hidden space.</p><p>This “blending” needs to be learned so we defined an output projection. Each head gives you a different perspective. This is just a learned way of combining those perspectives back into one vector, again so that the model can keep working in its original hidden space.</p><pre>&quot;&quot;&quot;<br>Goal of the combine step:<br>  <br>  Combine [batch query_pos n_heads d_head] --&gt; [batch query_pos d_model]<br><br>&quot;&quot;&quot;<br><br>self.W_O = nn.Parameter(torch.empty((n_heads, d_head, d_model)))<br>self.b_O = nn.Parameter(torch.zeros((d_model)))<br><br>&quot;&quot;&quot;<br>NOTE:<br><br>Since, z --&gt; batch query_pos n_heads d_head<br>we need to project it to d_model, so W_O --&gt; n_heads d_head d_model<br><br>batch query_pos n_heads d_head<br>                n_heads d_head d_model --&gt; batch query_pos d_model<br><br>&quot;&quot;&quot; <br><br>attn_out = einsum(<br>    &quot;&quot;&quot;<br>    batch query_pos n_heads d_head,<br>    n_heads d_head d_model<br>    -&gt;<br>    batch query_pos d_model<br>    &quot;&quot;&quot;,<br>    z, self.W_O<br>) + self.b_O</pre><p>The following steps keep repeating for number of transformer blocks in the model .. <a href="https://colab.research.google.com/drive/1Jo8VoR9vx4Y_s9mjNjRdk0gyMw58do1P?usp=sharing">Here</a> is the full code for reference.</p><p>I might’ve dumped a little too much on you in this article, but take your time to fully grasp the underlying concept of attention. Once you get it, there’s no going back :)</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a77ef946dad" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/llm-interpretability-coding-the-gpt-2-attention-layer-6a77ef946dad">LLM Interpretability: Coding the GPT-2 attention layer</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Interpretability: Coding Simple Attention]]></title>
            <link>https://ai.plainenglish.io/llm-interpretability-coding-simple-attention-8e922adfb68a?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e922adfb68a</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[interpretability]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 05:59:02 GMT</pubDate>
            <atom:updated>2025-09-21T23:46:12.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*F8Ec_Vu6tUscLGbwDQfd7A.png" /></figure><p>Building on some of the intuition from the last article, lets actually code up a simple attention head — because just the theory won’t cut it.</p><p>TLDR;</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class SimpleAttention(nn.Module):<br>    def __init__(self, d_model=4):  <br>        &quot;&quot;&quot;<br>        d_model: <br>          Size of the word vectors (like [1,0], [0,1] in our toy example).<br>          In GPT-2 this is 768, but here we keep it tiny.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        <br>        # Each head learns its own projection matrices W_Q, W_K, W_V<br>        # (here just single linear layers with no bias for simplicity).<br>        self.W_Q = nn.Linear(d_model, d_model, bias=False)<br>        self.W_K = nn.Linear(d_model, d_model, bias=False)<br>        self.W_V = nn.Linear(d_model, d_model, bias=False)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        x: [batch, seq_len, d_model]<br>        Example: if seq_len=3 (&quot;The cat sat&quot;), d_model=4<br>        &quot;&quot;&quot;<br>        # 1. Make Queries, Keys, Values<br>        Q = self.W_Q(x)   # shape: [batch, seq_len, d_model]<br>        K = self.W_K(x)   # same shape<br>        V = self.W_V(x)   # same shape<br><br>        # 2. Compute raw attention scores = Q @ K^T<br>        # (dot product between each query and all keys)<br>        # Shape: [batch, seq_len, seq_len]<br>        scores = torch.matmul(Q, K.transpose(-2, -1))<br><br>        # 3. Scale scores to keep softmax stable (like divide by sqrt(d_head))<br>        d_k = K.size(-1)<br>        scores = scores / (d_k ** 0.5)<br><br>        # 4. Causal mask (no peeking into the future!)<br>        # Mask out positions j &gt; i<br>        seq_len = x.size(1)<br>        mask = torch.triu(torch.ones(seq_len, seq_len), diagonal=1).bool()<br>        scores = scores.masked_fill(mask, float(&#39;-inf&#39;))<br><br>        # 5. Softmax → attention weights (probabilities)<br>        attn_weights = F.softmax(scores, dim=-1)  # [batch, seq_len, seq_len]<br><br>        # 6. Weighted sum of Values<br>        # Each row of attn_weights mixes all the V&#39;s<br>        out = torch.matmul(attn_weights, V)  # [batch, seq_len, d_model]<br><br>        return out, attn_weights</pre><blockquote>NOTE: This an extremely simplified implementation of an attention-head, which exactly mimics the operations we did in the previous article by hand.</blockquote><p><strong>All examples below for the sentence:</strong> <em>“The capital city of France, Paris is extremely crowded during the summers”</em></p><h3>Let’s start with the constructor:</h3><pre>self.W_Q = nn.Linear(d_model, d_model, bias=False)<br>self.W_K = nn.Linear(d_model, d_model, bias=False)<br>self.W_V = nn.Linear(d_model, d_model, bias=False)</pre><p>We start by defining learnable parameters for each of the Q/K/V vectors. We defined a matrix W_Qof shape d_model x d_model similarly for W_K and W_V</p><h3>Step 1: Make Queries, Keys, Values</h3><p>Getting the Q/K/V values. The tranformation is as follows:</p><pre>Q = self.W_Q(inp)<br><br># inp x W_Q --&gt; Q<br># [batch, seq_len, d_model] × [d_model, d_model] --&gt; [batch, seq_len, d_model]</pre><p>We make <strong>three different versions / perspectives </strong>of the current word.</p><h3>Step 2. Compute attention scores</h3><pre># [batch, seq_len, d_model] x [batch, d_model, seq_len] -&gt; [batch, seq_len, seq_len]<br>scores = torch.matmul(Q, K.transpose(-2, -1))</pre><p>Each word’s <strong>Query</strong> is compared against every other word’s <strong>Key</strong> using dot products. This gives us a big table of <strong>“attention scores”</strong>: how strongly one word thinks another word might be relevant.</p><ul><li>Example: “Paris” might give a strong score to “France”.</li></ul><h3>Step 3. Scale the scores</h3><p>If numbers get too big, the softmax later would blow up. So we divide by the square root of the vector size to keep things balanced. Think of this like normalizing grades so no one test / perspective dominates unfairly.</p><h3>Step 4. Apply a causal mask</h3><pre># Sets the upper-triangle of a matrix of shape (seq_len x seq_len) to True<br>mask = torch.triu(torch.ones(seq_len, seq_len), diagonal=1).bool()<br><br>&quot;&quot;&quot; <br>mask:<br><br>0 1 1 1<br>0 0 1 1<br>0 0 0 1<br>0 0 0 0<br>&quot;&quot;&quot;<br><br>scores = scores.masked_fill(mask, float(&#39;-inf&#39;))<br><br># The mask blocks out all those “future” positions <br># by setting their scores to -inf (which later turns <br># them into zero probability after softmax).</pre><p>When processing a sentence left-to-right (like in language modeling), a word <strong>can’t peek at future words</strong>.</p><h3>Step 5. Turn scores into probabilities</h3><pre># score shape: [batch, seq_len, seq_len]<br>attn_weights = F.softmax(scores, dim=-1)</pre><p>Now we turn those raw scores into <strong>probabilities</strong> that add up to 1. Each row is: “How much attention should I give to each word in the sentence?”</p><ul><li>Example: “Paris” might attend 80% to “France” and 20% to “city”.</li></ul><h3>Step 6. Mix the Values</h3><pre># attn_weights: [batch, seq_len, seq_len]<br># V: [batch, seq_len, d_model]<br><br>out = torch.matmul(attn_weights, V)<br># out: [batch, seq_len, d_model]</pre><p>Finally, each word collects information from the <strong>Values (V)</strong> of other words, weighted by the attention probabilities. This produces a new representation for each word that is <strong>aware of the context</strong>.</p><ul><li>Example: The vector for “Paris” now carries extra info that it’s a city in “France”.</li></ul><p>This should be it for this article … I’d suggest opening the <a href="https://medium.com/@gaganganapathy/llm-interpretability-attention-0e47dd96dbf4">previous article</a> as a reference and try to draw parallels between the toy-example and the explanation / code given here to fully grasp the implementation.</p><p>Next up, we will take a stab at the Attention implementation by Neel Nanda in his <a href="https://youtu.be/dsjUDacBw8o?si=qrz1ob2lNpl35Ge1">transformer walkthrough pt 2</a>. video — which is little complicated but the underlying concept is the same.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e922adfb68a" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/llm-interpretability-coding-simple-attention-8e922adfb68a">LLM Interpretability: Coding Simple Attention</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Interpretability: Attention]]></title>
            <link>https://ai.plainenglish.io/llm-interpretability-attention-0e47dd96dbf4?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e47dd96dbf4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[interpretability]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 02:56:18 GMT</pubDate>
            <atom:updated>2025-09-21T23:46:07.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMXsG0zA_h7M6ljKJLaOSg.png" /></figure><p>Reading up on things after writing the last article, have changed the course of how I wish to purse interpretability — mainly because of <a href="https://www.alignmentforum.org/posts/jP9KDyMkchuv6tHwm/how-to-become-a-mechanistic-interpretability-researcher#Stage_1__Learning_the_Ropes">this</a> new resource posted by Neel Nanda. This guide serves as a refreshed version on how to get started with mech-interp. Following this, I spent some time learning bits of linear algebra from <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab">3blue1brown</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EzbFEpyINlZ_jPhhQohzw.png" /><figcaption><a href="https://www.alignmentforum.org/posts/jP9KDyMkchuv6tHwm/how-to-become-a-mechanistic-interpretability-researcher#Stage_1__Learning_the_Ropes">https://www.alignmentforum.org/posts/jP9KDyMkchuv6tHwm/how-to-become-a-mechanistic-interpretability-researcher#Stage_1__Learning_the_Ropes</a></figcaption></figure><p>I’d definitely recommend the entire 16 video series. I finally now know what those eigen-things mean <em>lol</em>. Jumping off from there, I realized it might be a good idea to dive deeper into first understanding the internals of a model like GPT-2 — because if you’re trying to tear it apart and understand it you better know what to tear apart first?</p><p>Neel Nanda again, has this incredibly valuable walkthrough on transformers. Reiterating through that would add no value so I’d recommend you <a href="https://www.youtube.com/watch?v=bOYE6E8JrtU">watch</a> it by yourself. Following which, I moved onto part 2 which is about implementing GPT-2 from scratch!</p><p>I particularly want to write about how the video implemented the attention mechanism. Mostly doing this so that I remember stuff, so if it helps you understand better (its a win-win). Took me a couple of hours of racking my brain around why is attention the way it is and why is it implemented such, so if you’re curious too, stick around.</p><blockquote>NOTE: This guide won’t go too deep into the math of why it works, but is mostly around the intuition you can gather from the concept of attention and how to simply understand the implementation.</blockquote><p>Let’s begin.</p><h3>So what are we exactly solving with attention?</h3><p>Imagine you’re reading sentence:</p><blockquote>“The cat chased the mouse because it was hungry.”</blockquote><p>When you get to the word “it”, your brain asks:</p><ul><li>Does “it” refer to the <strong>cat</strong> or the <strong>mouse</strong>?</li></ul><p>To figure it out, you <em>look back</em> at earlier words and decide which one is most relevant. This is exactly what attention does: <strong>it lets the model decide which earlier words matter most for the current word.</strong></p><h3>Let’s introduce some terminology now</h3><p>The three magic ingredients are (Query, Key &amp; Value). You’ll hear these everywhere when you’re reading about attention and its critical you understand them clearly.</p><p>Query (Q) → “What I’m looking for” → comes from the current word.</p><p>Key (K) → “What I can offer?” → comes from each source word.</p><p>Value (V) → “The actual info to copy” → also comes from the source word.</p><blockquote><em>I’m sure none of these made sense, but fly with me for now ..</em></blockquote><p>In simple words, <strong>Query</strong> learns the context of what the <em>current word</em> is trying to understand, <strong>Key</strong> learns the signal each other word sends about what it offers. <em>(Value is the actual content representation that can be copied over if needed — don’t worry about this for now)</em></p><p>Let’s take an example for clarity:</p><blockquote>Sentence: <em>“The cat chased the mouse because it was hungry.”</em></blockquote><p>When the model is processing the word “it”:</p><ul><li>Query = “I need to know who <em>it</em> refers to.”</li><li>Keys = signals from earlier words (“cat” → “animal/subject,” “mouse” → “animal/object”).</li><li>Values = the actual word embeddings carrying info about “cat” or “mouse.”</li></ul><blockquote>Result = Attention will weight “cat” more, so “it” inherits info from “cat.”</blockquote><h4>What is the intuition here?</h4><p>Splitting Q/K/V lets the model separate roles:</p><ul><li>Queries specialize in asking <em>different types of questions</em>.</li><li>Keys specialize in advertising <em>different features</em>.</li><li>Values specialize in carrying <em>the content to pass along</em>.</li></ul><h3>Next, let’s use this concept on a toy model</h3><p>We will use three words “The”, “cat”, “sat” and only use a single attention head work though this example. Each word embedding will only be of size 2 — so the d_model=2 (model dimension)</p><h4>Step 1: Represent the words</h4><pre>&quot;The&quot; = [1, 0]<br>&quot;cat&quot; = [0, 1]<br>&quot;sat&quot; = [1, 1]</pre><h4>Step 2: Make Q, K, V</h4><p>Each head has its own little matrices to turn words into Queries, Keys, and Values.</p><p>Let’s keep it super simple and say they’re <strong>identity</strong> for now (so Q = K = V = the same as the word vector).</p><pre>Q(&quot;The&quot;)  = [1, 0]   K(&quot;The&quot;) = [1, 0]   V(&quot;The&quot;) = [1, 0]<br>Q(&quot;cat&quot;)  = [0, 1]   K(&quot;cat&quot;) = [0, 1]   V(&quot;cat&quot;) = [0, 1]<br>Q(&quot;sat&quot;)  = [1, 1]   K(&quot;sat&quot;) = [1, 1]   V(&quot;sat&quot;) = [1, 1]</pre><h4>Step 3: Compute attention scores</h4><p>For each <strong>current word</strong> (destination), take its <strong>Query (Q) </strong>and dot it with every <strong>Key (K) </strong>which is the source.</p><p>Example for “sat”:</p><pre>Q(&quot;sat&quot;) = [1, 1]<br><br>dot(Q, K(&quot;The&quot;)) = [1, 1] dot-product [1, 0] = 1<br>dot(Q, K(&quot;cat&quot;)) = [1, 1] dot-product [0, 1] = 1<br>dot(Q, K(&quot;sat&quot;)) = [1, 1] dot-product [1, 1] = 2<br><br>The scores are [1, 1, 2]</pre><h4>Step 4: Use Softmax to get a probability distribution (attention weights)</h4><pre>softmax([1, 1, 2])  <br>= [ e^1, e^1, e^2 ] / (e^1 + e^1 + e^2)<br>≈ [2.7, 2.7, 7.4] / 12.8<br>≈ [0.21, 0.21, 0.58]</pre><p>What this mean is that “sat” pays:</p><ul><li>21% attention to “The”</li><li>21% to “cat”</li><li>58% to itself. <em>(quite a narc, jk)</em></li></ul><h4>Step 5: Weighted sum of Values</h4><p>Now mix the Value vectors with these weights:</p><pre>= 0.21 * &quot;The&quot; + 0.21 * &quot;cat&quot; + 0.58 * &quot;sat&quot;<br>= 0.21 * [1, 0] + 0.21 * [0, 1] + 0.58 * [1, 1]<br>= [0.21, 0] + [0, 0.21] + [0.58, 0.58]<br>= [0.79, 0.79] </pre><p>That becomes &quot;sat&quot;’s <strong>new representation</strong> after attention! Phew, we just did attention by hand.</p><h3>Multi-head attention</h3><p>In practice, multiple attention heads are used. Now you may ask, why? Generally, in more complex sentences there are different things you might show attention on for example:</p><blockquote>“The capital city of France, Paris is extremely crowded during the summers”</blockquote><p>Now you see there are different useful relationships inside the same sentence. One head alone can only focus on a single kind of pattern. Some example of the different strategies different heads can learn as they’re trained:</p><p><strong>Entity ← → Definition head:</strong></p><ul><li>Might connect <em>“Paris”</em> strongly to <em>“capital city of France”</em>.</li><li>This helps the model recognize Paris as the capital, not just a random city.</li></ul><p><strong>Modifier ← → Noun head:</strong></p><ul><li>Might connect <em>“crowded”</em> back to <em>“Paris”</em>.</li><li>Ensures the model understands it’s Paris that’s crowded, not “France” or “summers.”</li></ul><p>And so on ..</p><p><strong>Each head has its own query/key/value projections</strong> → they’re like different sets of glasses the model puts on. After all heads do their job, their results are combined, so the model gets a rich, multi-view representation of the sentence.</p><p>Hopefully, this clears out any ambiguity around attention and gave you the intuition. Next, let’s code an attention class to apply this intuition.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e47dd96dbf4" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/llm-interpretability-attention-0e47dd96dbf4">LLM Interpretability: Attention</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Interpretability: Logit Lens]]></title>
            <link>https://ai.plainenglish.io/llm-interpretability-logit-lens-743bbdd670b4?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/743bbdd670b4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm-interpretability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 22:57:33 GMT</pubDate>
            <atom:updated>2025-09-21T23:45:54.318Z</atom:updated>
            <content:encoded><![CDATA[<p>Hopefully you made it through the 35 page paper from the getting started article ! Next up, let’s get our hands dirty with some actual code …</p><p>Just re-iterating on the motive behind these articles — it is not to help you explain the actual topics in MI, but to help you get you the balling rolling and possibly give you a insight into what approach has helped me understand this topic better <em>(more importantly it is just a way for me to document my journey around this topic)</em></p><p>So, its week 3 and ChatGPT suggested I read up <strong><em>“Eliciting Latent Predictions from Transformers with the Tuned Lens” </em></strong>(<a href="https://arxiv.org/pdf/2303.08112">link</a>) — honestly halfway through the paper I really lost track of what the authors were trying to say. Things became way too technical. I was able to digest bits and pieces here and there with constant help from chatGPT. But in the end, I felt I like I needed something more fundamental. This paper in a gist is about a new approach called “Tuned Lens” which is an enhanced version of Logit-lens. Both aim to answer the question of whats goes inside the transformer layers as it prodocues the output token.</p><p>Since, this paper went straight above my head, I decided to learn the basic version first, which is <strong><em>logit-lens. </em></strong>That’s when I stumbled upon this incredible <a href="https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens">article</a> by <em>nostalgebraist</em> on interpreting GPT-2. The article also attached a collab notebook explaining the how the visualizations in the article were made.</p><p>I don’t want to re-iterate what’s in the article, but in a gist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fA2Iwebe5O2huac-IGFrpg.png" /><figcaption><a href="https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens">https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens</a></figcaption></figure><p>Once I read the article, I wanted to actually go ahead see it in action. The colab notebook was a little too messy and unorganized for me to really understand what was going on. And the code was a bit outdated. Below is a more modern approach to simply implement logit-lens which most definitely is similar to the one in the article, <em>however 100x more readable and intuitive</em> :)</p><h4><strong>On a very high-level there are only three-steps:</strong></h4><ol><li>Load your pre-trained model and its corresponding tokenizer</li><li>Use model hidden-states to get the logits for every layer.</li></ol><blockquote>A logit is essentially a “raw score” or “confidence level” that the model assigns to each possible word in its vocabulary.</blockquote><p>3. Get the top token from each layer’s logits.</p><h4>Step 1: Load your pre-trained model and its corresponding tokenizer</h4><pre>from transformers import GPT2LMHeadModel, GPT2TokenizerFast<br><br>def load_model(model_name=&quot;gpt2&quot;):<br>    &quot;&quot;&quot;<br>    Loads a pre-trained GPT-2 model and its corresponding tokenizer.<br><br>    Args:<br>        model_name (str): Name of the GPT-2 model variant to load <br>                          (e.g., &quot;gpt2&quot;, &quot;gpt2-medium&quot;).<br>    &quot;&quot;&quot;<br>    tokenizer = GPT2TokenizerFast.from_pretrained(model_name)<br>    # Load the GPT-2 language model with hidden states output enabled<br>    model = GPT2LMHeadModel.from_pretrained(model_name, <br>                                            output_hidden_states=True)<br>    # Set the model to evaluation mode (disables dropout, etc.)<br>    model.eval()<br>    return tokenizer, model</pre><p>The above should be quite self-explanatory, nothing special happening here — just loading the tokenizer and the model with hidden states enabled.</p><h4>Step 2: Use model hidden-states to get the logits for every layer.</h4><pre>import torch <br><br>def run_logit_lens(model, tokenizer, text, max_tokens=200, device=&quot;cpu&quot;):<br>  # Tokenize the input text and convert to tensor, truncate if too long<br>  inputs = tokenizer(text, return_tensors=&quot;pt&quot;, <br>                      truncation=True, max_length=max_tokens)<br>  <br>  # Move input IDs to the specified device (CPU or GPU)<br>  input_ids = inputs[&quot;input_ids&quot;].to(device)<br><br>  with torch.no_grad():  # Disable gradient calculation for inference<br>      outputs = model(input_ids)  # Run the model to get outputs<br><br>      hidden_states = outputs.hidden_states<br>      embedding_matrix = model.transformer.wte.weight<br><br>      # Project each layer&#39;s hidden states into the <br>      # vocabulary space to get logits per layer<br>      logits_per_layer = project_hidden_states(hidden_states, embedding_matrix)<br><br>  # Return the input IDs and the logits <br>  # for each layer (for logit lens analysis)<br>  return input_ids, logits_per_layer</pre><p>Here we run the model on the inputs and then use the model’s hidden states along with the embedding matrix to get the logits for every layer.</p><p><strong>How the information flows through the layers:</strong></p><pre>Input: &quot;The Eiffel Tower is located in the city of&quot;<br>    ↓<br>Layer 0: (Embedding): Converts words to numbers<br>    ↓<br>Layer 1: Basic pattern recognition (grammar, word relationships)<br>    ↓<br>Layer 2: Slightly more complex patterns<br>    ↓<br>Layer 3: Even more sophisticated understanding<br>    ↓<br>... (continues through Layer 12)<br>    ↓<br>Final Output: Prediction for the next word</pre><p>This is exactly, what we’re trying to understand by peeping into the hidden states for each layer. (By layer we’re referring to each <strong><em>Transformer decoder layers</em></strong> in the model .. GPT-2 has 12 decoder layers as seen above)</p><p><strong>You must wonder what exactly does the hidden state look like?</strong></p><p>For all the discussion from here on, we will consider GPT-2 as our reference. Adding a breakpoint, we see the following:</p><pre>(Pdb) len(hidden_states)<br>13<br><br>(Pdb) hidden_states[0].shape<br>torch.Size([1, 11, 768])<br><br>(Pdb) embedding_matrix.shape<br>torch.Size([50257, 768])</pre><p>Let’s understand this a bit more — the length of the hidden states = embedding layer + 12 decoder layers, hence 13.</p><p>Each hidden layer holds a matrix of shape (1, 11, 768) — <strong>[ batch, sequence_len, hidden_dimension ] </strong>— what is implies is that each position in the sequence gets represented by 768 numbers that encode the model’s current understanding.</p><p>Next, we look at the <strong>embedding matrix </strong>— 50257 is the size of the vocabulary and 768 is again the hidden representations of each token. <strong><em>Think of it like a giant look-up table.</em></strong></p><p><strong>Coming to the meat of the problem here, how to you actually get the logits at each layer?</strong></p><pre>def project_hidden_states(hidden_states, embedding_matrix):<br>    &quot;&quot;&quot;<br>    Project hidden states into vocab space (logit lens).<br>    <br>    Args:<br>        hidden_states: list of tensors<br>        embedding_matrix: token embeddings<br>    Returns:<br>        List of logits (layer × [batch, seq, vocab])<br>    &quot;&quot;&quot;<br>    logits_per_layer = []<br>    for h in hidden_states:<br>        logits = h @ embedding_matrix.T<br>        logits_per_layer.append(logits)<br>    <br>    return logits_per_layer</pre><p><strong>So to recap:</strong></p><p>hidden state (h) — [ 1, 11, 768 ]</p><p>embedding_matrix — [ 50257, 768 ]</p><p><strong>Now if we do the following:</strong></p><pre>h @ embedding_matrix.T<br><br># Following a matrix multiplication of h and transpose of the embedding matrix<br># [batch, seq, hidden_dim] @ [vocab, hidden_dim].T -&gt; [batch, seq, vocab]</pre><p>We get a matrix of shape — [ 1, 11, 50257 ] — this gives me the score or logits for that layer.</p><h4>Step 3: Get the top token from each layer’s logits</h4><p>Now that we have the confidence score for each token in the vocabulary per layer, we can just pick the top most token which is the prediction of the model for the next word!</p><pre>def top_tokens_from_logits(logits, tokenizer, top_k=1):<br>    &quot;&quot;&quot;<br>        Return top-k tokens at each layer for each position<br>    &quot;&quot;&quot;<br>    all_layers = []<br>    for layer_logits in logits:<br>        # topk returns the values of the top k tokens, <br>        # and the indices of the top k tokens<br>        topk = torch.topk(layer_logits, top_k, dim=-1)<br><br>        # convert the indices to tokens, since layer_logits <br>        # is of shape (batch, seq, vocab) so we need to <br>        # convert the indices to tokens<br>        decoded = [<br>          tokenizer.convert_ids_to_tokens([<br>              tok.item() for tok in row<br>          ]) for row in topk.indices[0]]<br><br><br>        # decoded is a list of top preds from <br>        # each layer (it is of length seq_len)<br>        all_layers.append(decoded)<br><br>    return all_layers</pre><p>Next up, we can plot this information however we want, plotting it as a heat-map of each layer vs input is most commonly since its the most intuitive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVwqgI0TUOMWwW0ug3nGYw.png" /></figure><h4>How to interpret the following heat-map:</h4><p>Looking at the bottom-most row (which is a bit slanted), we see the input tokens the model uses. We can skip layer-0 since that’s just the embedding layer’s output.</p><p>Things become interesting as we progress from layer 1 to 12. The final cell for each column represents what the model predicted as the next token. For example if you look at the last row and and last column you see <strong>“Paris”</strong> which is the result of the consuming the entire input sequence which is <strong>“The Eiffel Tower is located in the city of”.</strong></p><p>I don’t want to go too deep into the analysis of this heat-map, I would really suggest reading <em>nostalgebraist’s </em><a href="https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens">article</a> for that instead and build on top of the code given here.</p><p>Hope this article helped you kickstart your journey into MI as well. We’ve barely even scratched the tip, I’m hoping to cover implementation of other techniques as I read more papers and blogs out there.</p><p>Here is the <a href="https://colab.research.google.com/drive/1gdGGtLiiVY66Ud1JeuKxA__tsqtzHuRM?usp=sharing">notebook</a> with all the above methods glued together. Find a more detailed version of the notebook <a href="https://colab.research.google.com/drive/1JnwU1nwShUgtuJxBHAvtO3ive8M7ipra?usp=sharing">here</a> — this will help get into the depths of analyzing the transformer layers as well along with its thinking process.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743bbdd670b4" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/llm-interpretability-logit-lens-743bbdd670b4">LLM Interpretability: Logit Lens</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Interpretability: Getting started]]></title>
            <link>https://ai.plainenglish.io/llm-interpretability-getting-started-852dd1c88867?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/852dd1c88867</guid>
            <category><![CDATA[model-interpretability]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[interpretability]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 19:11:59 GMT</pubDate>
            <atom:updated>2025-09-21T23:45:49.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-B6DG9ucxb5rYkZwLmzzQ.png" /><figcaption><a href="https://www.anthropic.com/research/tracing-thoughts-language-model">https://www.anthropic.com/research/tracing-thoughts-language-model</a></figcaption></figure><p>I’ll keep this first one short — I’m sure you know what interpretability is given you’re reading this <em>(but if not, please refer to the extensive literature written by Neel Nanda on this topic </em><a href="https://www.neelnanda.io/mechanistic-interpretability/getting-started"><em>here</em></a><em>)</em></p><p>This series is essentially me documenting my journey exploring the field of mechanistic interpretability (MI). I have zero experience in research let alone in MI, so this might be a good reference for anyone else trying to do the same and is not quite sure how to get started.</p><p>Well, its only been a couple of weeks of me venturing into this, so I don’t guarantee utmost depth in these articles. More so, it is quite possible I might venture into some direction that most MI experts might consider moot or outdated. <em>But, I’m a noob here (and hopefully so are you) so it doesn’t matter.</em></p><p>I did start off with the get started guide by Neel Nanda (linked above), although, I just found myself clicking on way too many links and going deep into the href tree … couldn’t quite start anywhere concretely. The guide is extremely comprehensive not to diss that, but didn’t quite work for me <em>(hope it does for you)</em></p><p>So, what do I do next, ask ChatGPT! I believe reading research papers would work for me so I asked it to build me a 8–10 week plan, one paper a week to study. I can mostly read on the weekends, so this worked best. <em>I usually end up taking two weekends for a paper, but hopefully I get to a point where I can finish a single paper in a weekend.</em></p><p>Starting off, I would recommend getting some air around what’s been happening in the field of MI and what have people tried. The paper I’m going to suggest will give you an idea of some of the most commonly used techniques, lingo and the know-how of some of the thought-processes around getting started with MI.</p><p>The paper: <strong><em>“A Practical Review of Mechanistic Interpretability for Transformer-Based Language Models” </em></strong><em>(</em><a href="https://arxiv.org/abs/2407.02646"><em>link</em></a><em>)</em></p><p><strong>Todos:</strong></p><ol><li>Take your time to read this one</li><li>Build some mental models around the commonly used phrases and ideas mentioned in the paper</li><li>On a note-pad, keep a running list of ANY research ideas you would think of as you read the paper. (This can be super random and need not make any sense). Following is a list of ideas that I came up with:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Bm-gf3knxFiOBgUZDr7wg.png" /><figcaption>(again .. these are just notes / random thoughts)</figcaption></figure><blockquote>The only reason I suggest this is, it makes you actively think about the gaps in the area even though they might necessarily make sense now, but eventually you’ll be able to refine your thoughts as we read more papers.</blockquote><p>This should be it for this one, we will look at a very basic technique called Logit-Lens in the next one.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=852dd1c88867" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/llm-interpretability-getting-started-852dd1c88867">LLM Interpretability: Getting started</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS : Currying]]></title>
            <link>https://medium.com/@gaganganapathy/js-currying-2b525ebdafd6?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b525ebdafd6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[currying]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Sun, 14 Jun 2020 17:29:49 GMT</pubDate>
            <atom:updated>2020-06-15T04:59:11.505Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS : Currying</h3><p>Before, I begin with this topic, I assume you are aware of JavaScript ES6 Syntax i.e how to use the rest operator and functions like bind() and have a good grasp on the concept of closures in JavaScript.</p><p>Currying transforms your normal f(a, b, c) type function into a f(a)(b)(c) type callable function, sounds interesting isn’t it? (you might wanna read ahead even if it doesn’t) 😛</p><blockquote>Also, note currying is not a JavaScript concept, you can implement this in other programming languages as well !</blockquote><h4>Let’s look a simple case to understand how it works :</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0356cb8bbd7bbd12344099ab7720fac/href">https://medium.com/media/d0356cb8bbd7bbd12344099ab7720fac/href</a></iframe><blockquote><strong>Basically, for every argument you return a new function storing all the previous arguments in your lexical context when calling the next function.</strong></blockquote><p><a href="#">Meaning :</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9254335025ffc6032ea775efbb77f9ac/href">https://medium.com/media/9254335025ffc6032ea775efbb77f9ac/href</a></iframe><p>But, we should be able to write a general method to accept a function with known arity (number of arguments) because implementing the curry as above could be really tedious giving your function func has a lot of arguments.</p><p><strong>Let us implement a general </strong><strong>curry function :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe84502f3ec61d2caa62a6e665ae9bf/href">https://medium.com/media/8fe84502f3ec61d2caa62a6e665ae9bf/href</a></iframe><h4><a href="#">Lets understand it step by step</a></h4><h4>Step 1 :</h4><p>args.length &gt;= arity</p><p>If you look closely, the number of functions we need to return when currying is equal to the number of arguments passed so this is really clever way to keep track of when we need to call func .</p><p>You can see — f(a, b, c) is transformed to f(a)(b)(c) which is nothing but 3 functions called back to back.</p><h4>Step 2 :</h4><p>return build.bind(null, ...args)</p><p>Seeing the rest operator things start to look a bit intimidating and does not immediately strike as to what is its purpose exactly!</p><p>First of all, we’re using ES6 fat arrow syntax for function so we don’t worry about passing in the this it gets it automatically from the enclosing scope.</p><p>That out of the way, let us looking to how we can preserve the previously used arguments and concatenate with currently passed ones i.e</p><pre>const f = g(1);</pre><pre>const h = f(2); // called with 1 preserved in context</pre><p>Ok, so keeping that in mind,</p><pre>const add = (a, b) =&gt; a + b;</pre><pre>const curryAdd = curry(add);</pre><p>Now, let us examine what curryAdd stores in it’s variable — it stores the returned function build(...args) where args = [1] now.</p><p>Let us store const b1 = curryAdd(1);</p><p>Now, b1 is called asb1(2) which returns a bounded function using bind() with initial arguments ...args (which is nothing but the previously passed arguments) and is 1 in our example.</p><p>Point to be noted here is that, it again returns a bounded function of build() itself with the initial arguments equal to the enclosing function’s arguments.</p><p>And then when b1(2) is called, keeping in mind there is an initial argument 1 — we see our args = [1, 2] .</p><h4><strong>Quick example how bind works here :</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b0c6ad5a7b0417b9ac4f52b40537261/href">https://medium.com/media/9b0c6ad5a7b0417b9ac4f52b40537261/href</a></iframe><p>You can see how the initial argument 1 is passed along the the argument 2 with which it is later invoked with.</p><blockquote>Read how .bind() works, if you’re confused about initial arguments - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind">read here</a></blockquote><h4><a href="#"><strong>Coming back to the general implementation :</strong></a></h4><h4>Step 3 :</h4><p>You see args = [1, 2] meaning it’s length is now equal to the arity of our add function and this indicates we can now call our function func with all the passed arguments.</p><p>we simply invoke our function as func(...args) and return it’s value.</p><h4>What’s the use of currying though ?</h4><p>Since, we know currying creates partial functions we can take advantage of that :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4d10dc2d5d808e3abd6b443953e1ec9/href">https://medium.com/media/f4d10dc2d5d808e3abd6b443953e1ec9/href</a></iframe><p>Great! You made it to the end of this blog! I hope you have a good idea of how currying works and can be implemented and most importantly how it can be used in real life applications!</p><p>And as always, let me know in the comments if you find anything incorrect or if there is anything you’d like to add! Cheers! 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b525ebdafd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS : Implementing Auto-complete]]></title>
            <link>https://medium.com/weekly-webtips/js-implementing-auto-complete-f4c5a5d5c009?source=rss-45afc0d3f4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c5a5d5c009</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[autocomplete]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Gagan Ajjikuttira]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 11:29:58 GMT</pubDate>
            <atom:updated>2020-06-12T17:31:15.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS: Implementing Auto-complete</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*a0HV-l41vj4LRSRGOrfqVw.gif" /><figcaption>Demo of the app: <a href="https://jsfiddle.net/h1pet9am/">https://jsfiddle.net/h1pet9am/</a></figcaption></figure><p>Have you always wondered, how auto completion works, well it is super complex in real life with machine learning and a whole bunch of stuff happening in the backend which I obviously cannot build all by myself! 😛</p><p>So, I decided to build a pretty similar working prototype which searches an English word dictionary of about <strong>102k words </strong>(because that’s all I could find 😥) to produce auto-completion suggestions..</p><p>You might be seeing that, there is no correlation among the words obviously because there is no machine learning being used, but the main goal here to be able to complete the unfinished word (independently i.e irrespective of what was typed before).</p><p>Well, more than completion I was more curious about how the <strong>back-text</strong> (the transparent ghost text that completes your query) worked and how would I blend my word suggestion into the input box itself.</p><p>List of words from <a href="https://raw.githubusercontent.com/matthewreagan/WebstersEnglishDictionary/master/dictionary_compact.json">here</a>. Repository consisting of the words <a href="https://github.com/matthewreagan/WebstersEnglishDictionary">here</a>.</p><p>In order to get better suggestions, I have used a <strong>popularity measure </strong>based on the frequency of usage of English words found <a href="https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english-no-swears.txt">here</a>. (repository <a href="https://github.com/first20hours/google-10000-english">here</a>). The only problem is, it hosts only about 10k words, which is not very bad!</p><h3>Prerequisites before proceeding ahead to the code section:</h3><ul><li>Knowledge of JavaScript ES6 syntax (classes, async/await)</li><li>Trie data structure</li><li>Adding event listeners to DOM</li><li>Knowledge about debounce. If not read <a href="https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf">here</a>.</li></ul><h4><a href="#">Now, we’re good to go ahead and code this out!</a></h4><h3>Step 1: Data structure</h3><p>Which data structure do we choose and why? Considering our corpus of words can be really huge (only about 102k for now) a linear search for prefixes won’t be feasible and would disrupt the user experience of your application.</p><p>A well-known data structure used for searching and matching strings is a Trie Tree. An important thing to note here would be to monitor the space constraint because in the worst-case considering our words only have lowercase a to z character can consume about :</p><p><strong>O(26 * average_length_of_words * number_of_words)</strong></p><p>[depending on the implementation of your trie]</p><p>But, the upside is the time complexity can be fairly low — equal to the length of the query string itself.</p><p><strong>O(length_of_query)</strong></p><h3>Let’s code this out:</h3><p>We shall create Trie class consisting of methods to add new words and produce suggestions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9adbd9928c028475872337413bdbd63/href">https://medium.com/media/e9adbd9928c028475872337413bdbd63/href</a></iframe><p><strong>Let’s look at the method to add new words:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c872a2163c3c68e41ff8d840413e69/href">https://medium.com/media/32c872a2163c3c68e41ff8d840413e69/href</a></iframe><p><strong>Let’s look at the structure more closely:</strong></p><p>Consider the words ant &amp; and added to the tree, this is how it’ll look :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c891ef29cb358b359e05cdce5e5f0e9c/href">https://medium.com/media/c891ef29cb358b359e05cdce5e5f0e9c/href</a></iframe><p><strong>Next, we need a method to find a word in the tree:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c884f416cedbe2ad8e9c184ffdca99ec/href">https://medium.com/media/c884f416cedbe2ad8e9c184ffdca99ec/href</a></iframe><p><strong>Next, we shall use the above </strong><strong>find function in-order to produce suggestions:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*rmZiEhCehBOMueOkKrQ84Q.png" /></figure><p>We need to traverse the search space where our suggestions lie and recursively build the word. We can use a depth-first search to simply traverse over each node and keep concatenating the letters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47cfae6639facf896f57aa685dd4d711/href">https://medium.com/media/47cfae6639facf896f57aa685dd4d711/href</a></iframe><p>We can keep a control on the number of child nodes to traverse on the first node using the CHILDREN argument, to prevent from traversing a very large space as the search space could be very large for huge word corpuses.</p><p>That’s all about coding our data structure, let us now use it display suggestions!</p><p><strong>Let us use this basic HTML to render the input box:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7126e2acfcdc2ead444f3be660bc863/href">https://medium.com/media/f7126e2acfcdc2ead444f3be660bc863/href</a></iframe><p>I haven’t included the styles here (you can see the fiddle <a href="https://jsfiddle.net/h1pet9am/">here</a> to view the entire source code).</p><h4>NOTE:</h4><p>The filenames in the above gists are not be taken literally, we only have 2 files — index.html and index.js all the JS code goes in this file itself.</p><p>Now, in our file index.js which also contains our Trie class, we shall add event listeners to handle input into our search bar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e717097c892f9f66ebcbbbc835b79708/href">https://medium.com/media/e717097c892f9f66ebcbbbc835b79708/href</a></iframe><p>Moving on, assuming you are aware of what debounce is (in short — our main() function is called when the user isn’t typing for 250ms).</p><p><a href="#"><strong>Reason for adding a debounce to our </strong></a><a href="#"><strong>main() method:</strong></a></p><p>The main() method is responsible for pulling out the suggestions every time there is a change in the search bar text, but the user would only want the suggestion to appear when the user waits for the short (200–250ms) time while typing. This not only improves the user experience but also reduces unnecessary functions calls to the main() method.</p><p><strong>Let’s look at the </strong><strong>main() function:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a8c27b0a0e882b4457baedde716ac30/href">https://medium.com/media/8a8c27b0a0e882b4457baedde716ac30/href</a></iframe><p>Here, popularity is a measure of the frequency of the words in general for example the word the usually has more frequency than xylophone right?</p><p>So, the method getBestMatch() just loops through the suggestions and picks the word with the highest frequency.</p><h4>Lets us understand the code with a diagram:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*zr_0J-PXDfje8NSbbp0iTw.png" /></figure><p>You can see here, ghost which is the suggestion is nothing but a span element placed at the distance equal to the content width of your query!</p><h3><strong>How do you get the width used by the content?</strong></h3><p>Have another div with is invisible somewhere in the DOM into which you can write the content of the query and measure the clientWidth !</p><pre><strong>HTML:</strong><br>&lt;div id=&#39;fake-div&#39; class=&#39;div&#39;&gt;&lt;/div&gt;</pre><pre><strong>JS:</strong><br>const $fakeDiv = document.getElementById(&#39;fake-div&#39;);</pre><pre>const query = e.target.textContent.toLowerCase();<br>$fakeDiv.innerText = query;</pre><pre><strong>CONTENT WIDTH</strong> = $fakeDiv.clientWidth</pre><p>Simple right! Now just place the ghost $span at the right position…</p><p>Since, the ghost $span needs to look similar to the text input in the $input div, we need to mimic few of the CSS properties of $input div and to get the CSS properties of the $input div we can do this :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8e3b85d50cce7fd0695e8f1d285280a/href">https://medium.com/media/a8e3b85d50cce7fd0695e8f1d285280a/href</a></iframe><p>Now, to set the style.left of the $span we just do :</p><pre><strong>LINE 33 : (main.js) GIST</strong></pre><pre>$span.style.left = r.left + $fakeDiv.clientWidth + &#39;px&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*BS0u0Tax43gu7sRgSnIEkw.png" /></figure><p>Just one thing left to do now! Fill in the input bar if the user wants to use the given suggestion, i.e if the user presses the RIGHT ARROW key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4d4a847f044a63bb94fc15cb476885/href">https://medium.com/media/0e4d4a847f044a63bb94fc15cb476885/href</a></iframe><p>Great! You made it to the end of this blog! Please note, I might have skipped on a few things such as fetching data from the URLs given and focused more on the topic concerned, you can find them in the link to the source code below.</p><p>You can play with the source code <a href="https://jsfiddle.net/h1pet9am/">here</a>.</p><p>And as always, let me know in the comments if you find anything incorrect or if there is anything you’d like to add! Cheers! 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c5a5d5c009" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/js-implementing-auto-complete-f4c5a5d5c009">JS : Implementing Auto-complete</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>