<?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 Melwin T Joshy on Medium]]></title>
        <description><![CDATA[Stories by Melwin T Joshy on Medium]]></description>
        <link>https://medium.com/@mxlwin?source=rss-0f353605c21e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dda5kXFGMKGWwPzL-LdLqA.png</url>
            <title>Stories by Melwin T Joshy on Medium</title>
            <link>https://medium.com/@mxlwin?source=rss-0f353605c21e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:32:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mxlwin/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 Transformers Through First Principles]]></title>
            <link>https://medium.com/@mxlwin/understanding-transformers-through-first-principles-f8ef66e02c06?source=rss-0f353605c21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8ef66e02c06</guid>
            <dc:creator><![CDATA[Melwin T Joshy]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 06:08:46 GMT</pubDate>
            <atom:updated>2026-09-03T06:08:46.492Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored by <a href="https://medium.com/u/4222017b5831">Harisankar S</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfhmywXgt3wNffhFuZS7qg.png" /></figure><p>For a while, I could describe what a Transformer does without fully understanding how it works.</p><p>I could say “it uses self-attention instead of recurrence” in a discussion and it would pass without question. But when pressed on why that mattered, I struggled to give a precise answer. I knew the terminology. I hadn’t worked through the mechanism.</p><p>That gap was worth closing. Not for the sake of appearing knowledgeable, but because using terms I couldn’t fully defend felt like a liability.So I stopped trying to memorize the Transformer diagram and started asking one question at every step:</p><blockquote><strong>What problem is this component solving?</strong></blockquote><p>That question turned out to be a much better way to understand the architecture than memorizing another diagram. And it gave the rest of the architecture a pattern I could finally see: <strong>a constraint appears, and the next design decision responds to it.</strong></p><h3>Why this is worth understanding</h3><p>You can use GPT, Claude, or any Transformer-based tool effectively without knowing any of what follows. None of it is a prerequisite for use.</p><p>It’s also worth clarifying the scope from the start: <strong>Transformer is a family of architectures, not one fixed design.</strong> The original Transformer used an encoder and a decoder; GPT-style models are decoder-only; other models, such as T5, use an encoder and a decoder.</p><p>But there’s a meaningful difference between operating a tool and having a working model of how it behaves. Understanding why attention exists, why sequence order has to be explicitly represented, why a decoder is restricted from seeing future tokens, and why training can be parallelized while generation cannot, changes how you reason about these systems’ behavior.</p><p>That’s the practical value here. It’s the difference between working with a system you can reason about and working with a system you’ve only learned to work around.</p><h3>The limitation that motivated the architecture</h3><p>Before Transformers, sequence models generally worked as follows: read a sentence one token at a time, maintain a hidden state summarizing everything processed so far, and use that hidden state to generate an output — a translation, a summary, or another downstream target.</p><p>Stated plainly, this design has an obvious constraint. A single representation is expected to carry the meaning of an entire sequence, updated incrementally at each step. As sequences grow longer, that representation comes under increasing strain, and information introduced early on becomes more likely to be diluted or overwritten before it’s needed.</p><p>A second limitation was less immediately visible, because it wasn’t a matter of accuracy but of throughput. These models processed tokens sequentially, with each step depending on the output of the last. Computation couldn’t be parallelized across the sequence, which made training on large datasets slow and expensive.</p><p>Attention mechanisms addressed the first issue by allowing the model to reference different parts of the input directly, rather than relying entirely on a single compressed state. But the underlying architecture remained recurrent. Sequential computation was still the bottleneck.</p><p>The question that followed was direct:</p><blockquote><strong>Could relationships between tokens be modeled without processing the sequence one token at a time?</strong></blockquote><p>That question leads to the first major idea in the Transformer: <strong>self-attention.</strong></p><p>But solving one problem creates others. If tokens can all interact at once, how do we decide what information matters? How do we keep the scores numerically well behaved? How does the model know the order of the tokens? And if we’re training a model to generate text, how do we stop it from looking at the answer before predicting it?</p><p>Those questions explain most of the architecture.</p><h3>The breakthrough: self-attention</h3><p><strong>Problem:</strong> a recurrent model processes tokens sequentially and forces information through a continually updated hidden state.</p><p><strong>Idea:</strong> let each token look directly at the other tokens it needs.</p><p>Here is the mechanism in its simplest form.</p><p>Consider:</p><blockquote><strong>”The animal didn’t cross the street because it was tired.”</strong></blockquote><p>When the model reaches “it”, the meaning of that token depends on information elsewhere in the sequence. Self-attention gives each token a way to incorporate information from other tokens, producing a representation that reflects its context.</p><p>A token’s embedding, on its own, is fixed and context-independent. The word “bank”, for example, carries no information about whether it refers to a riverbank or a financial institution. Self-attention allows the representation of “bank” to be influenced by the other tokens around it.</p><p>The computation happens in three steps. First, the relevance between two tokens is measured using a dot product between their Query and Key vectors. Second, those raw scores are passed through softmax, converting them into normalized attention weights. Third, those weights are used to compute a weighted sum over the Value vectors. The result is a new representation for each token, informed by whichever other tokens in the sequence were most relevant to it.</p><p>Because this computation doesn’t depend on the output of a previous token-processing step, it can be performed for every token simultaneously — which is the underlying reason Transformers can process the training sequence in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tn4xX-xmXTifwLOY6oyirQ.png" /><figcaption>Self-attention flow: comparing a query to every key, turning scores into weights with softmax, then taking a weighted sum of values</figcaption></figure><h3>Problem: attention needs a way to match and retrieve information</h3><p>Self-attention tells us that tokens can look at one another. But that still leaves a design question: <strong>what exactly should a token compare, and what information should it retrieve?</strong></p><p>That’s where Query, Key, and Value come in.</p><h4>Why Query, Key, and Value are separate</h4><p>This was a detail I initially treated as vocabulary to memorize rather than a decision to understand — three letters, three matrices, move on. That approach doesn’t hold up.</p><p>The distinction becomes clearer when Q, K, and V are understood as functional roles rather than arbitrary labels:</p><p><strong>- Query: </strong>what this token is looking for.<br><strong>- Key:</strong> what this token can be matched against.<br><strong>- Value:</strong> the information this token contributes once it is selected.</p><p>For example, when the model is processing “it” in “The animal didn’t cross the street because it was tired,” the Query represents what information “it” needs. The Keys provide representations that can be compared against that need. Once a relevant token receives a high attention weight, its Value supplies the information that gets incorporated into “it”’s representation.</p><p>You could use the same representation for all three, but that would limit what the model is able to learn. Giving Query, Key, and Value separate learned projections allows the model to represent these roles independently: what a token is searching for, what it can be matched on, and what it contributes once selected.</p><p>To achieve this, the model learns three separate transformations — Wq, Wk, and Wv — refined through backpropagation, which convert the same embedding into a task-specific Query, Key, and Value. The same input token takes on three distinct roles, each shaped by what the model is being trained to do.</p><p>This is where the mechanism stopped feeling like an arbitrary convention and started reading as a deliberate design choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7nrjwUGBPDgWKxuztvs4g.png" /><figcaption>The same embedding passed through three separate learned projections — Wq, Wk, Wv — producing a Query, Key, and Value that each do a different job</figcaption></figure><h3>Problem: raw attention scores can become too extreme</h3><p>Once Queries and Keys are compared, the resulting scores go through softmax. But large dot products can make that distribution too sharp.</p><h4>The scaling step that’s easy to overlook</h4><p>After computing the dot product between Queries and Keys, the result isn’t passed directly into softmax. It’s scaled first, divided by the square root of the √dₖ — Key vector’s dimensionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*hlZonKOSR7hZMHBijw9djQ.png" /></figure><p>This is easy to treat as a minor implementation detail. It isn’t.</p><p>As vector dimensionality grows, the dot products can have greater variance. That can produce very large positive or negative scores. Passed through softmax, large differences in scores can make the distribution extremely peaked — pushing some probabilities close to 1 and others close to 0.</p><p>That creates a training stability problem. When softmax becomes too saturated, gradients can become very small, making optimization harder. Dividing by the square root of the key dimension keeps the scale of the scores under better control before softmax is applied.</p><h3>Problem: one learned perspective isn’t enough</h3><p>A single attention operation gives the model one learned way of representing relationships between tokens. Information from earlier tokens has to be carried forward through a sequence of recurrent state updates. As sequences grow longer, information from earlier positions can become harder to preserve or use effectively.</p><p>Multi-head attention addresses this by running several self-attention operations in parallel, each with its own learned projections. This gives the model multiple learned perspectives on the same sequence.</p><p>Different heads may learn different patterns — perhaps emphasizing nearby relationships in one context and longer-range relationships in another. But these roles aren’t assigned by hand, and there is no guarantee that a particular head corresponds neatly to a human-defined concept. The important point is that multiple independently learned projections give the model multiple ways to represent relationships simultaneously.</p><p>The outputs from each head are concatenated and passed through a linear layer to restore the original dimensionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2N9goGua45J5dxurgQluQ.png" /><figcaption>Several attention heads running in parallel on the same input, each learning its own pattern, then concatenated and passed through a linear layer</figcaption></figure><h3>Problem: parallel processing removes the model’s built-in sense of order</h3><p>Self-attention gives us parallelism, but removing recurrence also removes an inherent notion of sequence order.</p><h4>Reintroducing sequence order</h4><p>Parallel processing is central to this architecture’s efficiency, but it comes at a cost: without recurrence, the model has no inherent sense of token order. “Dog bites man” and “man bites dog” contain identical tokens. Their order can completely change the meaning, and a model with no concept of position has no way to distinguish between them.</p><p>One solution, used in the original Transformer, is positional encoding: a vector, matching the embedding’s dimensionality, added to each token to represent its position in the sequence. The original paper implements this using sine and cosine functions at varying frequencies.</p><p>The specific mathematics is less important here than the outcome — the model now has access to both what a token is and where it appears, without needing to process the sequence sequentially to determine that. The original Transformer used sinusoidal positional encodings, while modern Transformer models use several different approaches to represent position.</p><h3>Problem: attention mixes information, but doesn’t do all the transformation</h3><p>Attention lets tokens exchange information. Something still needs to transform the resulting representations.</p><h4>What happens beyond attention</h4><p>Attention is not the only operation inside a Transformer block, and it’s worth being explicit about what surrounds it.</p><p>Following the attention step, each token’s representation passes through a feed-forward network. Attention mixes information <strong>across </strong>tokens; the feed-forward network then transforms each token’s representation <strong>independently</strong>, adding nonlinear capacity that attention alone doesn’t provide.</p><p>A useful way to think about the distinction is:</p><blockquote><strong>Attention asks: “Who should I listen to?</strong>”<br><strong>The feed-forward network asks: “Now that I’ve heard them, what should I do with that information?”</strong></blockquote><p>Residual connections and layer normalization surround both operations. The residual connection preserves a direct path for information through the network rather than requiring every layer to fully transform it, while layer normalization helps keep the values passing through the network within a stable range.</p><h3>Putting the pieces together</h3><p>At this point, the architecture can be read as a chain of answers to problems rather than a pile of components.</p><p>A simplified block can be thought of as:</p><p><strong>Token embeddings + positional information</strong></p><p>↓</p><p><strong>Multi-head self-attention</strong><br><em>Let each token gather information from other tokens.</em></p><p>↓</p><p><strong>Residual connection + normalization</strong></p><p>↓</p><p><strong>Feed-forward network </strong><br><em>Transform each token’s representation independently.</em></p><p>↓</p><p><strong>Residual connection + normalization</strong></p><p>↓</p><p><strong>Repeat</strong></p><p>This is a simplified view of a Transformer encoder block / decoder self-attention block; exact structure differs between encoder-only, decoder-only, and encoder-decoder architectures. Each component exists because the step before it leaves a particular problem to solve. The architecture reads less like an arbitrary diagram and more like a sequence of deliberate responses to constraints.</p><h3>Problem: training a generator can accidentally reveal the answer</h3><p>The Transformer solved the sequential-computation problem for training, but generative modeling introduces a new constraint: the model must learn to predict the next token without seeing future tokens.</p><h4>Why the decoder requires masking</h4><p>Encoders and decoders share a similar block structure but differ in behavior, and that difference is most apparent in how the decoder is trained.</p><p>During inference, the decoder is autoregressive: it generates one token, feeds that token back in as input, and generates the next. This is the basic pattern used for generative language modeling. During training, this isn’t how it operates. Instead, it uses teacher forcing — the correct target sequence, shifted by one position, is provided as input all at once, allowing every position to be trained in parallel rather than sequentially.</p><p>This introduces a risk: if the entire target sequence is visible simultaneously, the model could reference future tokens while predicting the current one. While predicting “am” in “I am a student,” for instance, it could access “student” directly. That would not constitute learning to generate language — it would amount to leaking the answer into the input.</p><p>Masked self-attention prevents this. After the attention scores are computed, a mask sets every future position to negative infinity; softmax then reduces those positions to zero. The model can attend only to prior positions and the current position, never subsequent ones.</p><p>This creates an important distinction:</p><blockquote><strong>Training can process the whole sequence in parallel. Generation still has to proceed one token at a time.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOjwdvLJoM9HUAOk8K6rrw.png" /><figcaption>A grid showing which positions each word can attend to when predicting “I am a student” — each row can only see itself and everything before it</figcaption></figure><h3>Three Transformer architectures worth distinguishing</h3><p>The word <strong>Transformer </strong>describes an architecture family, not one fixed arrangement of components.</p><h4>Original Transformer — Encoder → Decoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*rhNaRMpIZpLK2H_Z5mCFCA.png" /><figcaption>Figure from Vaswani et al., “Attention Is All You Need” (2017).</figcaption></figure><p>The Transformer introduced in <strong>Attention Is All You Need</strong> uses both an encoder and a decoder. The encoder builds contextual representations of the input sequence, while the decoder generates the output sequence. Cross-attention connects the decoder to the encoder’s output.</p><h4>GPT-style models — Decoder-only</h4><p>GPT-style language models use the decoder side of the architecture without a separate encoder. They use masked self-attention to process the sequence and predict the next token. Since there is no encoder output to attend to, they don’t use the encoder-decoder cross-attention described in the next section.</p><h4>T5-style models — Encoder → Decoder</h4><p>T5 uses the encoder-decoder arrangement. The encoder processes the input, and the decoder generates the output while using cross-attention to retrieve information from the encoder’s representations.</p><p>The important point is that <strong>“Transformer” doesn’t imply that every model contains both an encoder and a decoder.</strong> The architecture can be assembled differently depending on the task.</p><h3>Problem: the decoder sometimes needs information from another sequence</h3><p>For encoder-decoder Transformers, the decoder has to use the representation produced from the input sequence.</p><h4>How the encoder and decoder communicate</h4><p>Cross-attention is the mechanism that connects the decoder to the encoder’s output in an encoder-decoder Transformer. The decoder’s Query is derived from its own current state — the output of its masked self-attention layer. The Key and Value are derived from the encoder’s final output, the fully contextualized representation of the input sequence.</p><p>In effect, the decoder’s Query asks:</p><blockquote><strong>Given what I’ve generated so far, which parts of the input are most relevant to what comes next?</strong></blockquote><p>The resulting weighted combination of the encoder’s Values produces a context vector, which is passed into the decoder’s feed-forward layer and, from there, into the prediction of the next token. Self-attention allows a sequence to build context internally; cross-attention allows the decoder to use information from a separate input sequence. This handoff is what makes encoder-decoder tasks such as translation and summarization possible.</p><p>It’s also important to distinguish this architecture from modern decoder-only language models such as GPT-style models. The original Transformer used an encoder and a decoder, while decoder-only models use the decoder side without the encoder-decoder cross-attention described above.</p><h3>Closing thoughts</h3><p>The goal here wasn’t to produce a complete tutorial on Transformers. It was to close a specific gap between the terminology I used regularly and my actual understanding of the mechanism behind it.</p><p>What made the architecture click was not memorizing another diagram. It was asking a simpler question at every step:</p><blockquote><strong>What would fail if this component didn’t exist?</strong></blockquote><p>Scaled dot products, masking, positional encoding, multi-head attention, feed-forward networks — each becomes easier to understand once you connect it to the specific problem it was introduced to solve.</p><p>That may be the more useful lesson beyond Transformers. When faced with a complex system, don’t start by memorizing its components. Ask what constraint each component is responding to. The architecture then becomes easier to remember because you understand why it had to be there in the first place.</p><p><strong>Start with the problems. The architecture follows.</strong></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>References Vaswani, A., et al. (2017). <strong>Attention Is All You Need</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8ef66e02c06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>