<?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 Igor Sergeev on Medium]]></title>
        <description><![CDATA[Stories by Igor Sergeev on Medium]]></description>
        <link>https://medium.com/@igor.v.sergeev?source=rss-7694e044bbf7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tKdnGIzQVyRgh7aL.</url>
            <title>Stories by Igor Sergeev on Medium</title>
            <link>https://medium.com/@igor.v.sergeev?source=rss-7694e044bbf7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:47:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@igor.v.sergeev/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[Large Language Models Don’t Learn Skills — They Learn Geometry]]></title>
            <link>https://pub.towardsai.net/large-language-models-dont-learn-skills-they-learn-geometry-518059c5f6e7?source=rss-7694e044bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/518059c5f6e7</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Igor Sergeev]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 14:02:26 GMT</pubDate>
            <atom:updated>2025-12-30T14:02:26.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>Large Language Models Don’t Learn Skills — They Learn Geometry</h3><h4>A geometric perspective on learning and inference in large language models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoVAUpgcggsRdyEWx5-Plg.png" /></figure><h3>Introduction</h3><p>In this article, I want to look at large language models through a <strong>geometric lens.</strong></p><p>Framing models this way helps answer several questions that often come up in practice, but are rarely discussed together.</p><p>From this perspective, training does not produce a collection of discrete skills.</p><p>It learns a <strong>high-dimensional representational geometry</strong> — a landscape of possibilities where “meaning” corresponds to location.</p><p>Inference then becomes a problem of navigation: your prompt doesn’t add new knowledge, it primarily <em>steers</em> the model toward a particular region of that space.</p><h3>What a geometric perspective buys us</h3><p>A geometric perspective doesn’t explain these phenomena by adding new mechanisms.</p><p>It explains them by reframing what the model is actually learning.</p><p>Instead of thinking in terms of rules, skills, or modes, we think in terms of:</p><ul><li>spaces</li><li>regions</li><li>trajectories</li><li>and constraints</li></ul><p>Once you do that, questions about scale, emergence, prompting, and fine-tuning stop being separate puzzles.</p><p>It can help us understand the following concepts:</p><ul><li><strong>why general-purpose models are intentionally over-parameterized</strong></li><li><strong>why new capabilities can appear to “emerge”</strong></li><li><strong>why in-context learning works at all</strong></li><li><strong>why fine-tuning methods like Low-Rank Adaptation (LoRA) can be so effective</strong></li></ul><h3>From geometry to representations</h3><p>So far, we’ve been deliberately abstract, talking about a “space” or “landscape” of possibilities.</p><p>That can sound vague — but in a language model, this space is built from very concrete pieces.</p><p>At the lowest level, everything starts with vectors.</p><p>When the model sees a token, it maps it to a fixed-length list of numbers — an <strong>embedding</strong> vector.<br>That embedding is a single point in a high-dimensional space.</p><p>Each dimension doesn’t correspond to a human-interpretable feature like “plural” or “past tense.” Instead, meaning emerges from <strong>patterns of similarity and difference</strong> across many dimensions at once.</p><p>Two tokens with similar meanings end up close together. Tokens that behave differently across contexts end up farther apart.</p><p>That’s the raw material of the space.</p><blockquote><strong><em>A concrete way to picture it</em></strong></blockquote><blockquote>Imagine a huge multi dimensional space filled with points.<br>Each point is a word (token).</blockquote><blockquote>Words that behave similarly in language end up close together.<br>Words that behave differently end up farther apart.</blockquote><blockquote>There are no labeled axes.<br>No one decided what each direction “means.”</blockquote><blockquote>The only thing the model learns is: <strong>which points should be closer and which should be farther apart.</strong></blockquote><blockquote>That’s it.</blockquote><blockquote>Once you accept that picture, the idea of a “space of meanings” stops being abstract.</blockquote><blockquote>It’s just a very large map, learned from data.</blockquote><h3>How context changes a point — without adding new dimensions</h3><p>Up to now, we’ve talked as if each token is a fixed point in space.</p><p>That’s only true in isolation.</p><p>Once a token appears in a sentence, its representation is no longer just “the word itself.” It becomes <em>the word in this context.</em></p><p>Geometrically, you can think of this as a <strong>shift.</strong></p><p>The point doesn’t jump to a completely new space. It moves within the same space — nudged by the surrounding tokens.</p><p>Context doesn’t create new meaning from scratch.<br>It <strong>selects</strong> which aspects of meaning matter right now.</p><p>In geometric terms:</p><ul><li>some directions in the space become more important</li><li>others get suppressed</li></ul><p>The token’s representation moves accordingly.<br>Just reweighting and mixing.</p><h3>From moving points to “task regions”</h3><p>So far, we’ve talked about individual tokens shifting position as context changes.</p><p>Now zoom out one level.</p><p>A <em>task</em> — like translating, writing code, or answering questions — is not about a single token. It’s about a <strong>pattern of movements</strong> across many tokens, repeated over and over in similar situations.</p><p>Geometrically, you can think of a task as a <strong>region of the space</strong> where those movements tend to stay.</p><p>Not a single point, not a rigid rule. <br>A region.</p><h3>What makes a region a “task region”</h3><p>When you ask the model to write Python code, many things happen consistently:</p><ul><li>certain token relationships become important</li><li>certain kinds of structure repeat</li><li>certain continuations become likely</li></ul><p>As a result, the model’s internal representations tend to <strong>cluster</strong> in a particular part of the space while solving that task.</p><p>That cluster is a <em>task region.</em></p><p>Nothing new gets added when the model enters a task region.<br>The weights don’t change.<br>The space doesn’t change.</p><p>Only the <strong>trajectory</strong> does.</p><p>The prompt, examples, or instructions you provide simply make it more likely that the model’s representations stay within one region rather than drifting into another.</p><h3>Why task regions can be low-dimensional — even though the space is huge</h3><p>At this point, a natural question comes up:</p><p><em>If the model’s internal space is so large, why does any specific task only seem to use a small part of it?</em></p><p>The short answer is:<br><strong>Most tasks are much simpler than the entire space that represents them.</strong></p><p>Think of the full representational space as having thousands of possible directions.</p><p>Now think about a specific task — say, writing Python code.</p><p>To do that well, the model doesn’t need to use all directions at once.<br>Only a limited set of distinctions matter:</p><ul><li>syntax</li><li>indentation</li><li>variable scope</li><li>common library patterns</li></ul><p>Everything else is mostly irrelevant.</p><p>Geometrically, that means the model’s representations stay confined to a <strong>thin slice</strong> of the full space while performing that task.<br>That slice can be very low-dimensional — even if the surrounding space is enormous.</p><p>This is the key asymmetry:</p><ul><li>The <strong>space</strong> must be large to support many different tasks without interference</li><li>Any <strong>single task</strong> only needs a small number of degrees of freedom</li></ul><p>So training uses a large, flexible space.<br>Inference selects a narrow trajectory inside it.</p><p>Both are necessary.</p><p>At first glance, this can look inefficient:<br><em>Why learn thousands of dimensions if a task only needs a few?</em></p><p>But the extra dimensions aren’t there for one task. They’re there to keep <strong>different tasks from colliding.</strong></p><p>Each task gets its own thin region.<br>The space stays big so those regions don’t overlap in destructive ways.</p><p>Once you see tasks this way, something important clicks:<br><strong>Generalization doesn’t come from squeezing tasks together. It comes from giving them room.</strong></p><p>That’s why large models scale the way they do — and why shrinking the space too aggressively breaks things in non-obvious ways.</p><blockquote><strong><em>“Task vectors” — a concrete example: same vectors, fewer degrees of freedom<br></em></strong><em>(informal shorthand for token representations while performing a task)</em></blockquote><blockquote>Mathematically, these representations have low intrinsic dimensionality inside a high ambient dimensionality.</blockquote><blockquote><em>Even when a model is solving a very specific task, its tokens are still represented as full-length vectors — nothing about the vector size changes.</em></blockquote><blockquote><em>What changes is </em><strong><em>how much freedom those vectors actually have.</em></strong></blockquote><blockquote><em>Imagine token embeddings with thousands of dimensions.<br>While writing Python code, many of those dimensions </em><strong>barely vary</strong><em> at all:</em></blockquote><blockquote><em>- distinctions relevant to natural language style<br>- narrative tone<br>- emotional content<br>- etc.</em></blockquote><blockquote><em>They’re still present — they just don’t matter for the task.<br>Instead, most of the variation lives along a much smaller set of directions:</em></blockquote><blockquote><em>- syntax<br>- indentation<br>- control flow<br>- naming patterns</em></blockquote><blockquote><em>Geometrically, that means the representations lie on a </em><strong><em>thin surface</em></strong><em> inside the larger space — what we’d call a </em>low-dimensional manifold.</blockquote><blockquote><em>Same vector length.<br>Much lower effective dimensionality.</em></blockquote><h3>Bringing it all together</h3><p>At the beginning, we promised that a geometric way of thinking would help demystify several things that often feel unrelated or mysterious:</p><ul><li>why general-purpose models are intentionally over-parameterized</li><li>why new capabilities can appear to emerge</li><li>why in-context learning works at all</li><li>why fine-tuning methods like Low-Rank Adaptation (LoRA) can be so effective</li></ul><p>By now, the first point should already feel natural: large models need a big representational space so that many narrow task regions can coexist without interfering with each other.</p><p>With that foundation in place, we can move on to the more interesting consequences of this geometry — how new behaviors emerge from overlapping task regions, how prompts and examples can temporarily steer the model into those regions, and why surprisingly small, low-rank updates are often enough to shift behavior in meaningful ways.</p><p>Let’s start with emergence.</p><h3>Emergence</h3><p>First, let’s clarify what we actually mean by “emergence”</p><p>When people talk about “emergent capabilities,” they usually mean behaviors that weren’t explicitly trained or supervised as standalone tasks.</p><p>The model was never instructed:</p><ul><li>Now learn logical reasoning</li><li>Now learn step-by-step planning</li><li>Now learn how to follow complex instructions</li></ul><p>Yet at some scale, those behaviors start to appear.<br>This can sound mysterious — but in a geometric view, it’s exactly what you’d expect.</p><p><strong>Emergence as alignment, not magic</strong></p><p>During training, the model learns many narrow task regions at once:</p><ul><li>pattern completion</li><li>explanation</li><li>translation</li><li>code-like structure</li><li>instruction following</li></ul><p>Each of these regions is shaped by the same next-token objective, without being explicitly separated or labeled.</p><p>Some higher-level behaviors don’t live in a single region.</p><p>They emerge when <strong>several regions align</strong> well enough to support <em>a stable trajectory</em>.</p><p>That alignment doesn’t exist early on.<br>It becomes possible only once the space is large and structured enough.</p><p><strong>Why emergence has thresholds<br></strong>Before a certain scale:</p><ul><li>the relevant regions exist, but overlap poorly</li><li>trajectories are unstable</li><li>behavior is inconsistent</li></ul><p>Past that scale:</p><ul><li>separations sharpen</li><li>interference drops</li><li>trajectories stabilize</li><li>From the outside, this looks like a sudden jump in capability.</li></ul><p>Internally, it’s just the geometry getting cleaner.</p><blockquote>Once task regions become well defined, their consistent overlap and alignment create a new, stable pattern</blockquote><blockquote><strong><em>Emergence: a geometrical analogy explained to a 10-year-old<br></em></strong>Imagine a town with no sidewalks.</blockquote><blockquote>People walk between places — from home to school, from home to work, from home to the store — but at first the paths are rough. You can walk them, but it’s slow, awkward, and unreliable.</blockquote><blockquote>Over time, the most common routes get worn down.<br>Paths from home to school become smooth.<br>Paths from home to work become easy to follow.</blockquote><blockquote>Now something interesting happens: these paths start to <strong>overlap.</strong></blockquote><blockquote>And once they do, a new route suddenly becomes usable: you can now go directly from school to the bar — even though no one ever planned or explicitly built that path.</blockquote><blockquote>The destination didn’t change.<br>The town didn’t change.<br>What changed is that a stable, end-to-end route appeared.</blockquote><p>Emergent capabilities work the same way.</p><p>During training, the model learns many rough, task-specific trajectories. Early on, they’re unstable and hard to sustain. As training progresses, those trajectories become cleaner and start to overlap in consistent ways.</p><p>At some point, that overlap creates a new, reliable end-to-end behavior — a capability the model was never explicitly trained to perform, but can now execute smoothly.</p><p>That’s emergence.</p><h3>In-context learning</h3><p>At first glance, in-context learning looks strange.</p><p>You give the model a few examples in the prompt — and suddenly it behaves differently.</p><p>But nothing about the model changes:</p><ul><li>no weights are updated</li><li>no fine-tuning happens</li><li>no new knowledge is added</li></ul><p>So what’s going on?</p><p>From a geometric point of view, in-context learning isn’t learning in the usual sense.</p><p>It’s <strong>steering.</strong></p><p>The examples you provide in the prompt act as a strong contextual signal that nudges the model’s internal representations toward a particular task region — one that already exists in the space.</p><p>The model doesn’t infer a new rule.<br>It recognizes a familiar pattern of trajectories and stays within it.</p><blockquote>In-context examples don’t add information.<br>They <strong>remove ambiguity.</strong></blockquote><p>By showing the model how inputs and outputs relate in this specific context, you <strong>restrict which regions of the space remain plausible.</strong></p><p>Geometrically:</p><ul><li>many regions are still possible at the start of the prompt</li><li>each example narrows the set</li><li>after a few examples, only one stable trajectory remains</li></ul><p>The model simply follows it.</p><p>This only works because training already carved out task regions.<br>In-context learning doesn’t create those regions. It temporarily <strong>activates</strong> one of them.</p><p>Once the prompt ends, that steering signal disappears — and the model falls back to its default behavior. In-context learning is powerful but ephemeral.</p><h3>Low-Rank Adaptation</h3><p>By now, we’ve seen the pattern:</p><ul><li>training builds a large representational space</li><li>tasks occupy thin, low-dimensional regions</li><li>prompts can temporarily steer the model into those regions</li></ul><p>LoRA answers the final question:<br><em>How can </em><strong>very small weight changes</strong><em> permanently move the model into a different task region?</em></p><blockquote><strong><em>A quick refresher: what LoRA actually does</em></strong></blockquote><blockquote>At a high level, LoRA is simple.<br>Instead of updating a large weight matrix directly, it:</blockquote><blockquote>- freezes the original weights<br>- projects activations into a much lower-dimensional space<br>- applies a small trainable transformation there<br>- projects the result back to the original dimensionality</blockquote><blockquote>The update is compatible with the original model, but contains <strong>far fewer trainable parameters.</strong></blockquote><blockquote>Mathematically, a large matrix update is expressed as the product of two much smaller matrices.</blockquote><p>LoRA immediately raises a natural objection:<br><em>How can projecting updates into a much lower-dimensional space </em><strong>not</strong><em> destroy important information?</em></p><p>If the model’s representations live in thousands of dimensions, shouldn’t we need full-rank updates to change behavior meaningfully?</p><p>The geometric picture we’ve built answers this directly.</p><p>Although the ambient space is high-dimensional, a specific task only uses a <strong>small number of degrees of freedom.</strong></p><p>We already saw this with task regions:</p><ul><li>vectors are full-length</li><li>but meaningful variation lives in a thin subspace</li></ul><p>LoRA doesn’t try to modify the entire space.<br>It only needs to nudge the model <strong>along the directions that matter for the task.</strong></p><p>Those directions are few.</p><h3>Conclusion</h3><p>Seen through a geometric lens, many of the mysteries around large language models stop being mysterious.</p><p>Training doesn’t install a collection of discrete skills — it builds a <strong>large, redundant representational space.</strong></p><p>Individual tasks don’t occupy that whole space — they live in thin, low-dimensional regions within it.</p><p>Emergent capabilities appear when those regions align into stable trajectories.<br>In-context learning works by temporarily steering the model into one of them.<br>Low-rank adaptation works because permanently shifting behavior only requires nudging a few task-relevant directions.</p><p>Different mechanisms — one underlying geometry.</p><p>Core idea:<br><strong><em>Large models intentionally learn a redundant, high-dimensional space so that inference can dynamically select low-dimensional solution manifolds — without modifying weights.</em></strong></p><p>Once you see models this way, scale, emergence, prompting, and fine-tuning stop looking like tricks or magic — and start looking like geometric consequences of how the space is built.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518059c5f6e7" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/large-language-models-dont-learn-skills-they-learn-geometry-518059c5f6e7">Large Language Models Don’t Learn Skills — They Learn Geometry</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Transformer Model Zoo Isn’t a Zoo]]></title>
            <link>https://medium.com/@igor.v.sergeev/the-transformer-model-zoo-isnt-a-zoo-fb562ae13a9c?source=rss-7694e044bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb562ae13a9c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Igor Sergeev]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 17:05:06 GMT</pubDate>
            <atom:updated>2025-12-29T17:05:06.084Z</atom:updated>
            <content:encoded><![CDATA[<h4>Encoders vs. Decoders — Everything Else Follows. Two visibility rules, one mechanism, and the rest is just consequences.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4rIQI3QRona-_z3ztUXBw.png" /></figure><h3><strong>Introduction</strong></h3><p>We throw around “encoder,” “decoder,” “embedding,” and “cross-encoder” like they’re obvious. And to be fair, once you’ve built a few systems, they <em>feel</em> obvious. But if you pause and ask, <em>“Why do all these models exist? When do we use which? And what’s the real difference?”</em> it’s shockingly easy to realize you’re running on vibes instead of a crisp map.</p><p>To be fair, I was confused by this for a long time too. There’s a whole zoo of model names and concepts:</p><ul><li><strong>Encoder-only models:</strong> BERT, E5</li><li><strong>Decoder-only models:</strong> GPT-family, LLaMA</li><li><strong>Encoder–decoder models:</strong> T5, FLAN-T5</li><li><strong>Embedding models (bi-encoders):</strong> E5, text-embedding-3</li><li><strong>Cross-encoders:</strong> MiniLM cross-encoders</li><li>scoring heads</li><li>classification heads</li><li>etc.</li></ul><p>It may not be obvious how these pieces fit together, and it’s very easy to get lost in the jargon without a clear map of how one idea leads to the next.</p><p>But here’s the good news: once you understand two core ideas —</p><p>1. how Transformer <strong>self-attention</strong> works at a high level, and<br>2. the fundamental difference between <strong>encoder</strong> and <strong>decoder</strong> models (spoiler: they’re almost the same thing, with one tiny but important twist) —</p><p>everything else suddenly snaps into place.</p><p>Cross-encoders? Oh — just an encoder that consumes two texts together and scores their relationship.<br>Embeddings? That’s what you get when you take an encoder, train it contrastively, freeze it, and use its output as a vector.<br>Decoder-only LLMs? Autoregressive generators with causal attention.<br>T5? Both in one box.</p><p>Once these foundations are clear, the whole model ecosystem becomes intuitive instead of overwhelming.</p><p>You start to understand why different models exist, what each one is designed for, and how to combine them intelligently in real applications.</p><p>I’m pulling these pieces into one place because once the basics — self-attention, encoders, decoders — are clear, the supposed “model zoo” stops feeling like a zoo. You start seeing why each model exists and how to navigate the landscape with confidence.</p><p>In this article we’ll:</p><ul><li>Build an intuition for self-attention,</li><li>See how encoders and decoders differ only by a masking rule,</li><li>And finally show how different heads turn the same Transformer body into classifiers, LLMs, embedding models, and cross-encoders.</li></ul><h3><strong>Self-Attention: the One Mechanism Behind All Transformer Magic</strong></h3><p><strong>A High-Level Refresher — Starting From the Decoder Side</strong></p><p>Before we dive into self-attention or the encoder/decoder split, let’s briefly remind ourselves how a Transformer actually works at a very high level. This isn’t a deep dive; that deserves its own article. What follows is the bare minimum we need to understand so that the rest of the model ecosystem makes sense.</p><p>Let’s start with the following case: <strong>training a model that predicts the next word (token)</strong>. Once we understand that, understanding both encoders and decoders becomes trivial — they use the exact same machinery, just with a different mask and a different output head.</p><p>So, where do we begin?</p><p>Language models don’t work with “words.”<br>They don’t work with sentences, ideas, themes, or intentions.<br>All they understand is <strong>vectors of numbers.</strong></p><p>So the first thing we need is a way to convert text into numbers.</p><p><strong><em>Step 1 — Build a vocabulary and tokenize text</em><br></strong>We take raw text and break it into tokens (sub words) using a tokenizer (WordPiece, BPE, whatever).</p><p>This gives us a finite dictionary of token IDs:</p><p>873 → “contract”,<br>1421 → “service”,<br>57 → “,”,<br>and so on.</p><p><strong><em>Step 2 — Assign every token an initial vector<br></em></strong>We create an <strong>embedding matrix:</strong> one vector per token ID.</p><p>These vectors start out random — the model has no idea what “contract” or “service” means yet. During training, these weights will be learned.</p><p>At this point, the situation looks something like:</p><blockquote>Each word (token) has a vector…<br>but the vector doesn’t really mean anything yet.</blockquote><p><strong>What should these vectors represent?<br></strong>In an ideal world, each token vector would encode the “meaning” of a word.</p><p>But meaning doesn’t exist in isolation:</p><ul><li>“bank” could mean money institution or side of a river.</li><li>“lead” (the verb) and “lead” (the metal) are spelled the same.</li><li>“service” means one thing in a contract, another in a restaurant.</li><li>even “water” can refer to warm tropical ocean water or freezing arctic water — still “water,” but with completely different properties depending on context.</li></ul><p>Trying to represent a word’s meaning without context is impossible.<br>So how do we give the model context?</p><p>This is where <strong>self-attention</strong> comes in.</p><p>Before self-attention, all we have is:</p><ul><li>a sequence of tokens,</li><li>each with an initial vector,</li><li>none of which know anything about each other.</li></ul><p>Self-attention is the mechanism that lets each token look at other tokens and refine its own representation based on the entire surrounding context.</p><p>That’s where the real magic begins — and the reason the whole Transformer architecture exists.</p><blockquote><strong>But Why Do We Tokenize At All? Why Not Just Use Whole Words?</strong></blockquote><blockquote>Before we move on, it’s worth stopping for a moment to understand why we tokenize text instead of using natural words as our dictionary.</blockquote><blockquote>At first glance, using full words sounds simpler — just build a dictionary of all English words, assign each one a vector, and we’re done.</blockquote><blockquote>But this breaks immediately in practice:</blockquote><blockquote><strong>Natural language is extremely productive.<br></strong>From “run” we get “runs,” “running,” “runner,” “rerun,” “running-back,” etc. Treating each of these as a separate token explodes the vocabulary and wastes parameters on storing tiny variations of the same idea.</blockquote><blockquote><strong>A huge vocabulary becomes a huge embedding matrix.<br></strong>If you tried to build a model with a million-word vocabulary and 768-dimensional embeddings (meaning each word is represented by a 768-number vector), your embedding layer alone would have nearly a <strong>billion parameters</strong> that the <strong>model needs to learn</strong> — before you even add self-attention or MLP layers.</blockquote><blockquote>This shifts the model’s capacity toward memorizing word lookups rather than learning actual patterns.</blockquote><blockquote><strong><em>Shameless self-promotion:</em></strong><em> if you’d like to dive deeper into the implications of large vs. small vocabularies — and how they relate to “smart” vs. “dumb” neurons — I wrote another article that explores this in more detail:<br></em><a href="https://pub.towardsai.net/building-a-transformer-from-scratch-lessons-from-two-months-of-experiments-fe9239ab9788#e79f"><em>https://pub.towardsai.net/building-a-transformer-from-scratch-lessons-from-two-months-of-experiments-fe9239ab9788#e79f</em></a></blockquote><blockquote><strong>Subwords capture meaningful structure.<br></strong>Suffixes like “-ing” or prefixes like “un-” carry consistent semantics.<br>Tokenizers like BPE or WordPiece let models reuse these pieces across many words instead of learning everything from scratch.</blockquote><blockquote><strong>Tokenization keeps the model “smart” instead of “wide.”<br></strong>By controlling vocabulary size (usually 30k–50k tokens), we allocate parameters where they matter:<br>self-attention, the MLPs, and deeper layers — not in a gigantic embedding table that memorizes surface forms.</blockquote><blockquote>In short: tokenization is not a convenience — it’s a <strong>fundamental design decision</strong> that lets Transformers represent language efficiently, learn morphology naturally, and stay within practical training budgets.</blockquote><h3><strong>How Transformers “Read” Text</strong></h3><p>Before Transformers, most sequence models were recurrent: RNNs, GRUs, LSTMs.</p><p>These models literally processed (“read”) text <strong>one token at a time</strong>, updating a hidden state as they went.</p><p>This created two major issues:</p><p>1. <strong>The model only had access to the past.<br></strong>When processing token 30, the RNN had no direct way to use information from tokens 31–50 that come <em>later in the input</em>.<br>(This is about understanding an input sequence, not predicting the next token.)</p><p>2. <strong>The dependency chain was strictly sequential and slow.<br></strong>You couldn’t process token 50 until you had processed every token before it.</p><p>Transformers threw this entire idea away:</p><blockquote>When processing input, a Transformer does not read tokens sequentially.<br><strong>It ingests the entire sequence at once, in parallel.</strong></blockquote><p>This means every token initially knows nothing about any other token — they all start as isolated vectors.</p><p>Self-attention is the mechanism that lets each token discover which other tokens matter and pull in the information it needs to build a contextualized representation.</p><p>A possible point of confusion:</p><blockquote>Transformers <strong>process</strong> (read) the entire input sequence in parallel, but models that <em>generate</em> text (decoder-style Transformers) produce output one token at a time.</blockquote><p>Processing = parallel.<br>Generation = sequential, autoregressive.</p><p>Self-attention only makes sense once you realize the model sees the whole input at once and must figure out context relationships dynamically.</p><blockquote>Transformers weren’t invented because someone wanted “cool attention maps.”</blockquote><blockquote>They were invented because RNNs were fundamentally too slow and too sequential — especially for large-scale sequence tasks like translation, summarization, and long-document understanding.</blockquote><h3><strong>A Quick Historical Detour: How Transformers Were Invented</strong></h3><p>The idea of processing all tokens in parallel wasn’t just a cute design choice — it was the <strong>original motivation</strong> behind the Transformer architecture.</p><p>Around 2017, researchers at Google were building large translation models.<br>The dominant approach at the time used RNNs and LSTMs, which processed text one token at a time.</p><p>These models were powerful, but painfully slow to train:</p><ul><li>every token depended on the previous one,</li><li>long sentences became bottlenecks,</li><li>and parallel hardware (GPUs/TPUs) couldn’t be used efficiently.</li></ul><p>So the researchers asked a simple but revolutionary question:<br><strong>“What if we stop reading sequences one token at a time and let the model look at the entire sentence at once?”</strong></p><p>This shift unlocked massive parallelism and enabled training on modern accelerators.</p><p>Self-attention emerged as the mechanism that made this possible — it let each token dynamically decide which other tokens mattered, without any recurrence.<br>Training times collapsed.<br>Translation quality improved dramatically.</p><p>The Transformer wasn’t just a new model — it was a <strong>new way of thinking about sequences</strong>.</p><h3><strong>What Self-Attention Actually Does</strong></h3><p>To see why we need self-attention at all, let’s look at a simple example sequence:</p><blockquote>Under a starry northern sky through a deep calm river flowed dark cold water that shimmered faintly in the moonlight</blockquote><p>Right now, each of these tokens starts as an isolated vector — a generic learned representation of that token.</p><p>Those vectors contain <strong>no real contextual meaning</strong>.</p><p>The embedding for <strong>“water”</strong> is just the generic concept of water: something wet, fluid, transparent, maybe drinkable.</p><p>But in this sentence, “water” is none of those things alone.</p><ul><li>it is <strong>dark</strong> and <strong>cold</strong>,</li><li>moving through a <strong>deep calm river</strong>,</li><li>under a <strong>starry northern sky</strong>,</li><li>and it <strong>shimmers faintly in the moonlight</strong>.</li></ul><p>What we want — and what the model internally learns to produce — is a richer, contextualized version of each token.</p><p>For example:</p><ul><li>“dark” should know it describes “water,”</li><li>“sky” should know it’s northern and starry,</li><li>“river” should know it is deep and calm,</li><li>and “water” should absorb all of these properties.</li></ul><p>This is the core purpose of self-attention:</p><blockquote>Self-attention enriches each token’s meaning by allowing it to look at other tokens in the sequence, decide which ones matter, and <strong>determine how much information to take from each of them.</strong></blockquote><p>After self-attention, the hidden state for <strong>“water”</strong> is no longer just “wet stuff.”<br>It becomes a <strong><em>weighted blend</em></strong> of relevant context:<br>cold + dark + deep + calm + shimmering + moonlit + northern.</p><p>This is how Transformers build meaning.<br>Each token begins as a generic, context-free learned vector, and self-attention enriches it with information drawn from the surrounding tokens.</p><p>The model doesn’t treat that initial representation as the token’s meaning — it refines it into a contextual meaning shaped by the sentence around it.</p><ul><li>The embedding table does store a “raw,” context-free meaning.</li><li>But that meaning is shallow, incomplete, and often ambiguous.</li><li>What actually makes meaning is the contextualization in deeper layers — <strong>and that is why we need self-attention.</strong></li></ul><h3><strong>Self-Attention Explained Like You’re 10</strong></h3><p>Before we look at the math, let’s build an intuition for what self-attention is <em>trying</em> to do.</p><p>Imagine every word in the sentence is a kid sitting at a big round table.</p><blockquote>Under a starry northern sky through a deep calm river flowed dark cold water that shimmered faintly in the moonlight</blockquote><p>Each kid (each token) is wearing headphones and can quietly talk to any other kid at the table.</p><p>What is the goal?</p><p><strong>Each word wants to understand what kind of word it should become in this specific sentence.</strong></p><p>For example, the kid named <strong>“water”</strong> needs to figure out:</p><ul><li>Should I be warm? Cold?</li><li>Peaceful? Dangerous?</li><li>A small stream? A deep river?</li><li>Shiny? Dark?</li><li>Moving? Still?</li></ul><p>To figure this out, <strong>“water”</strong> listens to the other kids and asks:</p><ul><li>“Hey <strong>dark</strong>, are you describing me?”</li><li>“Hey <strong>calm</strong>, do you apply to me too?”</li><li>“Hey <strong>river</strong>, what kind of place am I in?”</li><li>“Hey <strong>shimmered</strong>, are you something I should pay attention to?”</li></ul><p>Some kids matter a lot (“dark”, “river”).<br>Some kids matter a little (“northern”, “sky”).<br>Some kids don’t matter much at all.</p><p><strong>In self-attention, each word decides:</strong></p><ol><li><strong>Whom to listen to</strong>, and</li><li><strong>How loudly to listen</strong>.</li></ol><p>If “water” decides that “dark” and “cold” are very important, it listens closely to them.<br>If it decides that “under” or “a” are not important, it ignores them.</p><p>At the end of this “conversation,” every kid updates who they are:</p><ul><li>“water” becomes dark+cold+deep+shimmering.</li><li>“river” becomes deep+calm+northern+flowing.</li><li>“sky” becomes starry+northern.</li><li>and so on…</li></ul><p>This is the intuition behind self-attention:</p><blockquote>Each word looks at every other word, decides who matters, and blends a little bit of their meaning into its own.</blockquote><p>This is how the model builds rich, contextualized meanings as it repeatedly refines each token using information from the others.</p><h3><strong>How Tokens Decide What to Pay Attention To: Queries, Keys, and Values</strong></h3><p>Now that we have the intuition (“every token sits at a table and listens to the others”), we can explain how this works inside the model.</p><p>Every token needs to be able to do three things:</p><ol><li><strong>Ask a question:<br></strong>“What am I looking for in other tokens so I can refine my meaning?”</li><li><strong>Reveal what it contains:<br></strong>“Here are the features about me that others can use to decide whether I’m relevant to them.”</li><li><strong>Provide useful information:<br></strong>“If another token decides I’m relevant, what information should I give it?”</li></ol><p>For each token vector, the Transformer creates three different vectors — Query, Key, and Value — to play these roles:</p><ol><li><strong>Query (Q)</strong> → what this token <em>is looking for</em></li><li><strong>Key (K)</strong> → what this token <em>has to offer</em></li><li><strong>Value (V)</strong> → the actual information this token <em>shares</em> if selected</li></ol><p>You can think of it like:</p><ul><li><strong>Query</strong> = the token’s “search question”</li><li><strong>Key</strong> = the token’s “label” or “metadata”</li><li><strong>Value</strong> = the token’s “content” that gets blended into others</li></ul><h3><strong>How We Actually Create Query, Key, and Value Vectors</strong></h3><p>So how do we get these three different vectors (Q, K, V) from a single token vector?</p><p>The way the model creates these three vectors is simpler than you might expect:</p><p><strong>We multiply each token vector by three different learned matrices — one for Queries, one for Keys, and one for Values.</strong></p><ul><li>A <strong>Query matrix</strong> (Wᵩ)</li><li>A <strong>Key matrix</strong> (Wₖ)</li><li>A <strong>Value matrix</strong> (Wᵥ)</li></ul><p>Each matrix has its own parameters, learned during training, and each one applies a different <strong>linear transformation</strong> to the token’s initial representation vector.</p><p><strong>What does “linear transformation” actually mean here?<br></strong>It’s just a fancy way of saying:</p><blockquote>We take the token’s initial vector and <strong>re-express</strong> it in a way that highlights the features most relevant to that role.</blockquote><p>For example, when we build the <strong>Query vector</strong>, we multiply the token embedding by the Query matrix:</p><p>Q = token_embedding × Wᵩ</p><p>This does something very intuitive:</p><ul><li>features that help this token <strong>look for relevant information</strong> are <em>magnified</em>,</li><li>features that don’t help it search are <em>reduced</em>,</li><li>and the resulting vector becomes a form of “What am I trying to find?”</li></ul><p>The Key and Value vectors work the same way:</p><p>- <strong>The Key</strong>: highlights features that help others decide whether this token is relevant.</p><p>- <strong>The Value</strong>: highlights the information this token should contribute when selected.</p><p>You can think of it like taking the same photograph and applying three different filters — each filter brings out different details depending on the task:</p><ul><li>a “sharpen edges” filter for building the <strong>Query</strong>,</li><li>a “detect shapes and contours” filter for the <strong>Key</strong>,</li><li>and a “soft glow / color blend” filter for the <strong>Value</strong>.</li></ul><p>It’s the same underlying picture, but each filtered version emphasizes different aspects — exactly what we need for asking questions, offering features, and providing information.</p><p>Even though all three vectors come from the same initial token representation, they emphasize <strong>different aspects</strong> of the token’s meaning.</p><h3><strong>How Attention Scores Are Computed: Dot Product Intuition</strong></h3><p>Now that we have Query, Key, and Value vectors for every token, the next question is:<br><strong>How much should each token pay attention to every other token?</strong></p><p>The mechanism for this is elegant.</p><p>For the current token (say, <strong>“water”</strong>), we take its <strong>Query</strong> vector and compute the <strong>dot product</strong> with the <strong>Key</strong> vector of every other token in the sentence.</p><p>This gives us a <strong>score</strong> — a single number — for each pair:</p><ul><li>a higher score means “this token is very relevant to what I’m looking for,”</li><li>a lower score means “probably not important.”</li></ul><blockquote><strong><em>A quick reminder: what is a dot product?</em></strong></blockquote><blockquote>You can think of the dot product as a measure of <strong>alignment</strong> between two vectors.</blockquote><blockquote>- If two vectors point in a similar direction → their dot product is large (high relevance).<br>- If they point in unrelated directions → the dot product is small.<br>- If they point in opposite directions → it can even be negative.</blockquote><blockquote>In our setting:<br><strong>The Query vector defines what the token is trying to find.<br>The Key vector defines what another token has to offer.<br>The dot product measures how well those two ideas line up.</strong></blockquote><blockquote>So for <strong>“water”</strong>:</blockquote><blockquote>- Q_water · K_dark → probably high<br>- Q_water · K_cold → high<br>- Q_water · K_river → high<br>- Q_water · K_under → very low<br>- Q_water · K_the → basically zero</blockquote><blockquote>The math is simple — but conceptually, something powerful is happening:<br><strong>“water” is evaluating every other token and asking:<br>‘How much should I listen to you?’</strong></blockquote><blockquote>You can also think of the dot product as a “compatibility score” between what I’m looking for (Query) and what you have (Key).</blockquote><h3><strong>Putting It All Together: Blending Meaning From Other Tokens</strong></h3><p>Now that we’ve built the <strong>Query</strong>, <strong>Key</strong>, and <strong>Value</strong> vectors for every token, we have everything we need to enrich the current token with context from the rest of the sentence.</p><p>Here’s how it works at a high level:</p><p>1. The current token uses its <strong>Query</strong> vector to compare itself to every other token’s <strong>Key</strong> vector.</p><p>2. These comparisons produce a set of <strong>scores</strong> — one score per token — indicating how relevant each other token is.</p><p>3. These scores are then converted into <strong>weights</strong> (yes, via a scaled softmax, but the details aren’t important here).</p><p>4. Finally, the model takes a <strong>weighted blend of the Value vectors</strong> of all tokens, using those weights.</p><p>The result is a <strong>new, context-rich representation</strong> of the current token.</p><p>A token like <strong>“water”</strong> might assign high weights to:<br>- dark,<br>- cold,<br>- river,<br>- shimmered,</p><p>and tiny or near-zero weights to tokens like <strong>under</strong>, <strong>a</strong>, or <strong>the</strong>.</p><p>By blending the <strong>Value</strong> vectors according to these weights, the model produces a refined hidden state — one that encodes exactly the kind of meaning “water” should have <em>in this specific sentence</em>.</p><p>In other words:</p><blockquote>Self-attention takes what the token is, looks at what the surrounding tokens offer, and mixes in just the right amount of each to form a richer meaning.</blockquote><h3><strong>Encoders vs. Decoders</strong></h3><p>Now that we understand what self-attention does — compare, score relevance, blend meaning — we can finally explain the difference between <strong>encoders</strong> and <strong>decoders</strong>.</p><p>The difference is as simple as that:</p><p><strong>1. Encoders</strong> allow every token to attend to every other token in the sequence — both <strong>left and right.</strong></p><p><strong>2. Decoders</strong> only allow a token to attend to earlier tokens in the sequence (they <strong>can only look left</strong>, never right).</p><p>That’s it.<br>Everything else is a consequence of this one design choice.</p><h3><strong>Encoders: Fully Bidirectional Attention</strong></h3><p>In an encoder (like BERT or E5), <strong>every token can attend to every other token — both left and right</strong>.</p><p>Using our sentence again:</p><blockquote>Under a starry northern sky through a deep calm river flowed dark cold water that shimmered faintly in the moonlight</blockquote><p>- “water” can attend to <strong>dark</strong>, <strong>cold</strong>, <strong>river</strong>, but also to <strong>shimmered</strong> and <strong>moonlight</strong> that appear later.<br>- “river” can pay attention to <strong>shimmered</strong> and <strong>moonlight</strong> even though they’re to its right.</p><p><strong>Encoders are not generating text</strong> — they <em>could</em>, but doing so would be extremely inefficient (we’ll see why when we talk about KV cache).<br>Their purpose is to process the entire input as one coherent unit.</p><p>Because of that, giving every token full visibility is exactly what they need:<br>each token gets access to the complete picture.</p><h3><strong>Decoders: Directional Attention (Only Look Left)</strong></h3><p>Encoders give every token full visibility.</p><p><strong>Decoders do the opposite — they are strictly one-directional.</strong></p><p>In a decoder, each token is allowed to use only the tokens that come <strong>before</strong> it in the sequence. Even when the full sequence is available, the model is prevented from <strong>attending</strong> to tokens to its right.</p><p>In other words:</p><ul><li>token 5 can see tokens 1–4,</li><li>token 10 can see tokens 1–9,</li><li>but no token is ever allowed to look to the right.</li></ul><p>Why?<br>Because a decoder’s purpose is to <strong>generate text one token at a time</strong>, and this is only efficient if each token attends <strong>only to earlier tokens</strong>.<br>(It will make perfect sense when we look at KV cache in a moment.)</p><p><strong>A Concrete Example<br></strong>Let’s make this less abstract.</p><p>Say we are generating this sentence:</p><blockquote><strong>“The fox jumps over the lazy dog.”</strong></blockquote><p>Autoregressive generation goes like this:</p><p>1. Step 1:<br>Input: [“The”] → model predicts ”fox”.</p><p>2. Step 2:<br>Input: [“The”, “fox”] → model predicts ”jumps”.</p><p>3. Step 3:<br>Input: [“The”, “fox”, “jumps”] → model predicts ”over”.</p><p>4. Step 4:<br>Input: [“The”, “fox”, “jumps”, “over”] → model predicts ”the”.</p><p>5. …and so on.</p><p>At <strong>step 3</strong>, when we predict ”over”, the model has already processed:</p><ul><li>token 1: ”The”</li><li>token 2: ”fox”</li><li>token 3: ”jumps”</li></ul><p>For efficiency, it has <strong>cached</strong> their Key and Value vectors:</p><ul><li>K₁, V₁ for “The”</li><li>K₂, V₂ for “fox”</li><li>K₃, V₃ for “jumps”</li></ul><p>Now, to generate ”over” (token 4), it just needs to:</p><ul><li>compute Q₄ for ”over”,</li><li>reuse cached K₁…K₃ and V₁…V₃,</li><li>do attention once,</li><li>produce the next token.</li></ul><p>No recomputing anything for ”The”, ”fox”, or ”jumps”.<br><strong>This only works if earlier tokens never depend on later tokens.</strong></p><h3><strong>What Would Break If Tokens Could Look Right?</strong></h3><blockquote><strong>“The fox jumps over the lazy dog.”</strong></blockquote><p>Imagine we <strong>didn’t</strong> use causal attention, and allowed ”fox” (token 2) to attend to ”jumps” (token 3) and ”over” (token 4) as they appear.</p><p>Generation would look like this:</p><ul><li>At step 2, we generate ”fox” and compute its representation using only ”The”.</li><li>At step 3, we generate ”jumps”. Now maybe ”fox” <em>should</em> also look at ”jumps” to refine its meaning.</li><li>At step 4, we generate ”over”. Maybe ”fox” <em>also</em> should look at ”over” now.</li></ul><p>But here’s the problem:</p><blockquote>Every time we add a new token, we’d have to go back and recompute <strong>all previous tokens</strong> so they can “see” the new stuff.</blockquote><p>That means:</p><ul><li>when we add ”jumps”, we’d need to recompute ”fox”,</li><li>when we add ”over”, we’d need to recompute ”fox” and ”jumps”,</li><li>when we add ”the”, we’d need to recompute ”fox”, ”jumps”, and ”over”,</li><li>…and so on.</li></ul><p>At that point, <strong>KV cache is useless</strong>, because cached Keys and Values for earlier tokens would be stale: they’d no longer reflect the newest tokens to the right.</p><p>To avoid this explosion of recomputation, we enforce a simple rule:</p><blockquote><strong>Earlier tokens are never allowed to depend on later tokens.</strong></blockquote><p>So in a decoder:</p><ul><li>”The” can attend to nothing before it (just special tokens),</li><li>”fox” can attend to ”The”,</li><li>”jumps” can attend to ”The”, ”fox”,</li><li>”over” can attend to ”The”, ”fox”, ”jumps”,</li><li>…but none of them can ever look to the right.</li></ul><p>That’s what the <strong>causal mask</strong> guarantees.</p><h3><strong>Why This Matters</strong></h3><p>Putting it all together:</p><ul><li>During <strong>generation</strong>, later tokens don’t exist yet when we compute earlier ones.</li><li>We want to <strong>cache</strong> Keys and Values for tokens 1…t−1 and reuse them every time we predict token t.</li><li>That only works if the representation of tokens 1…t−1 never depends on tokens t…N.</li></ul><p>So the causal restriction isn’t some philosophical “no future allowed” law — it’s a very practical constraint that makes autoregressive generation <strong>efficient</strong> and <strong>well-defined</strong>.</p><p>Encoders get to look both ways because they <strong>don’t</strong> do step-by-step generation.</p><p>Decoders sacrifice “looking right” so they can generate quickly, one token at a time, without recomputing the whole sequence at every step.</p><h3><strong>Why Decoding Would Be Horrendously Slow Without KV Cache</strong></h3><p>Without caching, autoregressive decoding becomes extremely expensive.</p><ul><li>To generate token 1 → compute its representation.</li><li>To generate token 2 → recompute token 1 again.</li><li>To generate token 3 → recompute tokens 1 and 2 again.</li><li>…</li><li>To generate token 50 → recompute tokens 1…49 again.</li></ul><p>The total work looks like this:</p><blockquote>1 + 2 + 3 + … + 50 = <strong>1,275 units of computation</strong></blockquote><p>So a 50-token response still requires 50 forward passes<br>(one per generated token), <strong>but</strong> the total compute is <strong>1,275× larger</strong> than with KV caching.</p><p>This grows quadratically.</p><p>A 500-token response requires:</p><blockquote>1 + 2 + 3 + … + 500 = <strong>125,250 units of computation</strong></blockquote><p>This quickly becomes orders of magnitude slower and would feel unusably slow in practice.</p><p>In complexity terms:</p><p>❌ <strong>O(n²) total computation</strong> for an n-token completion<br>instead of<br>✔️ <strong>O(n)</strong> with KV cache</p><h3><strong>How KV Cache Fixes Everything</strong></h3><p>KV cache makes autoregressive decoding fast by letting us:</p><ul><li>compute Keys/Values for tokens 1…t <strong>once</strong>,</li><li>store (“cache”) them,</li><li>reuse them when generating token t+1 without recomputing anything for previous tokens.</li></ul><p>But this only works if earlier tokens <strong>never depend on later tokens</strong> — which is exactly what the causal mask guarantees. So decoders intentionally sacrifice rightward attention (and therefore some contextual richness) in exchange for <strong>massive generation speed</strong>.</p><p>This trade-off is what makes modern LLMs fast enough to use in real time:</p><ul><li>Encoders = full visibility, deep understanding, no KV cache needed.</li><li>Decoders = left-only visibility, fast token-by-token generation, KV cache essential.</li></ul><p>Both architectures use the <strong>same self-attention mechanism</strong> — they just apply different visibility rules and optimize for different goals.</p><h3><strong>Now That We Have Rich Token Representations… What Do We Actually Do With Them?</strong></h3><p>At this point in the story, every token in the sequence has been transformed into a rich, contextualized vector.</p><p>“water” is no longer generic — it’s dark+cold+river+moonlit+shimmered.</p><p>Every other token has been enriched in a similar way.</p><p>So now what?</p><p>How do we jump from these vectors to something useful, like:</p><ul><li>predicting the next word,</li><li>classifying a sequence,</li><li>producing an embedding,</li><li>or generating a summary?</li></ul><p>This is where <strong>output heads</strong> come in.</p><p>A Transformer isn’t one model — it’s a <strong>shared body</strong> plus a <strong>task-specific head</strong> on top.</p><p>Different heads turn the same internal representations into completely different abilities.</p><h3><strong>Decoder head → next-token prediction</strong></h3><p>A decoder (like GPT-style models) adds a very simple head:</p><ul><li>a linear layer that maps the hidden state to vocabulary logits,</li><li>followed by a softmax.</li></ul><p>That’s it.</p><p>The model takes the final hidden state at the last position and turns it into a probability distribution over the next token.</p><h3><strong>Classification head → label prediction</strong></h3><p>An encoder can attach a small MLP or linear layer on top of a pooled representation (often the [CLS] token or a mean-pooled embedding):</p><ul><li>sentiment classification,</li><li>contract type classification,</li><li>question-answering (span prediction),</li><li>etc.</li></ul><p>Same Transformer body — totally different job.</p><h3><strong>Embedding head → produce a vector for semantic search</strong></h3><p>If you train an encoder with contrastive learning (e.g., E5), you remove the classifier and simply <strong>use the hidden state as an embedding</strong>.</p><p>That embedding becomes the thing you store in a vector DB and compare with dot products.</p><h3>Cross-encoder head → score relationship between two sequences</h3><p>A cross-encoder takes two inputs <em>together</em>, runs them through the encoder, and puts a small scoring head on top of the final hidden state.</p><p>Same architecture, different head → now it’s a reranker.</p><p><strong>The important point:<br></strong>All of these models share the <em>same mechanism</em> — self-attention — but they gain different abilities depending on <strong>what head we attach</strong>.</p><p>And <em>that</em> is the entire reason the “model zoo” exists.</p><h3><strong>What Heads Actually Look Like in Practice</strong></h3><p>So far we’ve talked about heads at a high level:</p><ul><li>decoders predict the next token,</li><li>encoders classify,</li><li>embedding models produce vectors,</li><li>cross-encoders score pairs of texts.</li></ul><p>Let’s make this a bit more concrete with three specific examples.</p><h4><strong>1. Next-token prediction head (decoder LM)</strong></h4><p>In a decoder-style model, after all the self-attention and MLP layers, we end up with a hidden state — a fully enriched vector — for every token in the sequence.</p><p>To predict the <strong>next token</strong>, the model takes the hidden state at the last position, call it h_last, and feeds it through a simple linear layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*Srdq_Mabj0IHWErBnvGtiw.png" /></figure><ul><li>W_vocab has shape [vocab_size, hidden_dim].</li><li>The output logits is a vector of length vocab_size.</li><li>Applying a softmax converts logits into a probability distribution over the vocabulary.</li></ul><p><strong>Training objective:<br></strong>Minimize cross-entropy between this predicted distribution and the true next token.</p><p>And that’s it — the <strong>LM head</strong> is just a linear projection that turns the final hidden state into a vector of token probabilities.</p><blockquote><strong>Why do we use the </strong><em>last</em><strong> hidden state to predict the next token?</strong></blockquote><blockquote>A very natural question is:<br>We have a fully enriched hidden state for <strong>every</strong> token in the sequence — so why do we use only the <em>last</em> one to predict the next word?</blockquote><blockquote>There are two key reasons:</blockquote><blockquote><strong>1. Only the last hidden state has access to the entire visible context</strong></blockquote><blockquote>Because decoders use <strong>causal (left-to-right) attention</strong>, each token can only attend to tokens that come <em>before</em> it.</blockquote><blockquote>- The hidden state at position 1 sees nothing.<br>- The hidden state at position 2 sees token 1.<br>- The hidden state at position 3 sees tokens 1 and 2.<br>- …<br>- The hidden state at the <strong>last position</strong> sees <em>all previous tokens</em>.</blockquote><blockquote>So if we want the model to predict the next token using <strong>all available context</strong>,<br>the only representation that contains all that information is the hidden state of the last token.</blockquote><blockquote>This makes the last hidden state the natural choice for next-token prediction.</blockquote><blockquote><strong>2. The last hidden state is trained specifically to be predictive</strong></blockquote><blockquote>During training, every position is used to predict the next token:</blockquote><blockquote>- Position 1 predicts token 2<br>- Position 2 predicts token 3<br>- …<br>- Position <em>t</em> predicts token <em>t+1</em></blockquote><blockquote>This means the hidden state at each position <strong>learns to summarize everything up to that point</strong> in a way that is maximally useful for next-token prediction.</blockquote><blockquote>By the time we reach the last position, its hidden state has:</blockquote><blockquote>- absorbed the meaning of all earlier tokens,<br>- contextualized itself through multiple attention layers,<br>- and been optimized to output the correct next word.</blockquote><blockquote>So the model learns a very simple contract:<br><strong>My final hidden state is the summary of everything I’ve seen so far — use it to decide what comes next.</strong></blockquote><h4><strong>2. [CLS] classification head (encoder)</strong></h4><p>In BERT-style encoders, we often add a special [CLS] token at the beginning of the sequence. After self-attention, its hidden state is treated as a summary of the whole input. That is because during training we teach [CLS] to act as a summary by attaching the classifier head to it.</p><p>To classify a sequence (e.g., “positive vs negative”, “contract type A vs B vs C”), we:</p><p>1. Take the final hidden state for [CLS], call it h_cls.<br>2. Feed it into a small classifier head (linear layer or tiny MLP):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*yHC515c_GIdzWzibF6hzVg.png" /></figure><ul><li>logits has size [num_labels].</li><li>Apply softmax → probabilities over labels.</li><li>Train with cross-entropy on the correct label.</li></ul><p>Same encoder body, different small head → now the model is a classifier.</p><h4><strong>3. Cross-encoder scoring head (reranker)</strong></h4><p>A cross-encoder takes <strong>two texts together</strong> (e.g., query + candidate chunk):</p><ul><li>It concatenates them with special tokens like [CLS] query [SEP] passage [SEP].</li><li>Runs the whole sequence through the encoder (full bidirectional attention).</li><li>Again, uses the [CLS] hidden state as a representation of “query + passage together”.</li></ul><p>Then a tiny head turns that into a <strong>single score</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*PQDXxQ8N0nAczzup8s5oAA.png" /></figure><ul><li>h_cls is the final [CLS] vector.</li><li>`w` and `b` are parameters of a small linear layer.</li><li>`σ` can be a sigmoid if you want a 0–1 relevance score, or you can omit it and treat the raw number as a ranking score.</li></ul><p>Now you can:</p><ul><li>feed every (query, passage) pair through this,</li><li>get a score,</li><li>sort candidates by that score,</li><li>and use it as a reranker on top of a cheaper bi-encoder search.</li></ul><p>Same encoder body.<br>Different tiny head.<br>Now you have a cross-encoder.</p><h3><strong>Wrapping It All Up</strong></h3><p>We covered a lot of ground, but at the same time we only scratched the surface.</p><p>There are many things we <strong>didn’t</strong> talk about on purpose:</p><ul><li>the fact that each Transformer layer usually has <strong>multiple attention heads</strong> (not to be confused with output heads),</li><li>the <strong>feed-forward (MLP) blocks</strong> that sit after attention and non-linearly mix features,</li><li><strong>residual connections</strong> that help gradients flow and make deep training possible,</li><li><strong>normalization layers</strong> that keep activations stable,</li><li><strong>cross-attention</strong> in encoder–decoder models,</li><li>and all the fun training details: losses, schedules, regularization, etc.</li></ul><p>We also didn’t talk about how training gradients let “future” tokens influence how earlier positions are represented, even in left-to-right decoders — that’s a whole separate rabbit hole about backprop and <strong>“quasi-bi-directionality.”</strong></p><p>All of those matter a lot — but they sit on top of one core idea we <em>did</em> focus on:</p><blockquote>Self-attention builds contextual meaning, and encoders/decoders are just two ways of wiring it up.</blockquote><p>If you remember nothing else from this article, here’s the TL;DR.</p><p><strong>1. Encoders vs. Decoders in One Paragraph</strong></p><ul><li><strong>Encoders</strong> let every token attend to every other token (left and right).<br>They build <strong>rich, bidirectional representations</strong> of an input sequence.<br>That makes them great at <em>understanding</em> text: classification, embeddings, cross-encoders, semantic search, etc.<br>They <strong>could</strong> generate text, but doing so step-by-step would be inefficient and doesn’t play to their strengths.</li><li><strong>Decoders</strong> only let each token attend to tokens <strong>to its left</strong>.<br>This causal structure, plus KV cache, makes them incredibly efficient for <strong>next-token prediction</strong>.<br>They sacrifice rightward attention so they can generate text one token at a time without recomputing the entire history on every step.</li></ul><p>Same self-attention mechanism.<br>Different visibility rule.<br>Very different sweet spots.</p><p><strong>2. Once the Body Exists, Heads Decide the Job</strong></p><p>Self-attention and stacking give us what you can think of as a <strong>body</strong>:<br>a sequence of rich, context-aware token representations.</p><p>On top of that body, we attach <strong>heads</strong> — small, task-specific modules that decide what we actually do with those representations:</p><ul><li>A <strong>decoder LM head</strong> turns the last hidden state into a probability distribution over the vocabulary → next-token generation.</li><li>A <strong>classification head</strong> turns a pooled representation (e.g., [CLS]) into label logits → sentiment, intent, contract type, etc.</li><li>An <strong>embedding head</strong> (often just “use the hidden state directly”) turns tokens into vectors that live in a semantic space → vector search, RAG retrieval.</li><li>A <strong>cross-encoder head</strong> turns a combined representation of (query + passage) into a single score → reranking.</li><li>An <strong>encoder–decoder setup</strong> wires an encoder body into a decoder body via cross-attention → translation, summarization, etc.</li></ul><p>Under the hood, it’s all the same stack of attention+MLP blocks.<br>What changes is:</p><ul><li><strong>how tokens are allowed to see each other</strong> (encoder vs decoder), and</li><li><strong>what head you attach on top</strong> to turn those contextual vectors into something useful.</li></ul><h4><strong>3. Why This Matters in Practice</strong></h4><p>Once you internalize these pieces:</p><ul><li>self-attention as “who should I listen to and how much?”,</li><li>encoders as “full-visibility understanding machines,”</li><li>decoders as “left-only, KV-cached generation machines,”</li><li>heads as “small, specialized modules that define the task,”</li></ul><p>…the “model zoo” starts to look a lot less like a zoo and more like a set of Lego bricks:</p><ul><li>Need fast semantic search? → encoder + embedding head.</li><li>Need high-precision reranking? → cross-encoder head on top of an encoder.</li><li>Need fluent answering? → decoder LM head.</li><li>Need translation or complex sequence-to-sequence mapping? → encoder–decoder.</li></ul><p>Different names, different checkpoints, different papers — but fundamentally the same architecture, reshaped for different jobs.</p><h3><strong>Final Thoughts</strong></h3><p>If you’ve made it this far, you now understand the three ideas that power almost every modern NLP system:</p><ol><li>Self-attention is how tokens decide who matters and how much.</li><li>Encoders and decoders are the same machine with different visibility rules.</li><li>Heads turn one shared Transformer body into completely different tools — classifiers, rerankers, embedding models, and LLMs.</li></ol><p>Everything else in the model zoo — BERT, GPT, E5, T5, cross-encoders, embedding models, seq-to-seq architectures — are just combinations of these pieces.</p><p>This isn’t the whole story of Transformers, not even close.</p><p>But it’s the part that unlocks the rest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb562ae13a9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Transformer from Scratch: Lessons from Two Months of Experiments]]></title>
            <link>https://pub.towardsai.net/building-a-transformer-from-scratch-lessons-from-two-months-of-experiments-fe9239ab9788?source=rss-7694e044bbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe9239ab9788</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Igor Sergeev]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 19:02:35 GMT</pubDate>
            <atom:updated>2025-10-19T19:02:35.522Z</atom:updated>
            <content:encoded><![CDATA[<h4>What I learned about learning itself while teaching a Transformer to think.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LW7FqOuJ002apZ8V8dnC6Q.png" /></figure><h3>A Small Note Before We Start</h3><p>When I first started writing this, I thought it would be much shorter — just a few lessons from building and training a small GPT-style Transformer language model.</p><p>But the deeper I went, the more I began to see how closely it echoed the way we humans learn, remember, and forget.</p><p>What began as a technical project slowly turned into something more reflective — about balance, memory, scale, and what it truly means to learn and understand.</p><p>So even if the math or model details aren’t your thing, stay for the parallels. There’s something deeply human behind every layer of this story.</p><h3>Table Of Content</h3><p>· <a href="#fcc4">Author’s Note</a><br>· <a href="#93f5">Scope</a><br>· <a href="#d20f">Tiny Shakespeare, Big Lessons</a><br>· <a href="#dd7f">Regularization knobs</a><br>· <a href="#c1b8">Scaling Laws — When Bigger Isn’t Always Smarter</a><br>· <a href="#e79f">Choosing the Right Vocabulary Size — When Bigger Isn’t Always Better</a><br>· <a href="#dfa9">Wikitext, When Scale Meets Sense</a><br>· <a href="#7474">Understanding the Loss Floor — What “Good” Really Looks Like</a><br>· <a href="#000b">What the Model Learned to Say</a><br>· <a href="#6f5d">Wrap-Up — The longest and hardest “Hello, World!” I’ve ever built</a></p><h3>Author’s Note</h3><p>Before we dive in — a quick disclaimer.</p><p>I’m <strong>not</strong> an AI researcher.</p><p>(At least, not yet — though I’d love to become one someday.)</p><p>I’m a seasoned software engineer who got <em>way too curious</em> about how Transformers actually work under the hood.<br>So I decided to build one — from scratch — just to see what really happens when a model “learns.”</p><p>This article isn’t a research paper or a polished tutorial.</p><p>It’s more of a field diary from someone who didn’t know what they were doing at the start and slowly pieced things together through a mix of code, confusion, and occasional triumph.</p><p>If you build Transformers for breakfast — if you work at <strong>OpenAI</strong>, <strong>Anthropic</strong>, or <strong>DeepMind</strong> — you’ll probably find this hilariously obvious. (You should probably stop reading right now before you start shouting “That’s not technically precise!” at your screen.)</p><p>But if you’re an engineer like me — someone who’s comfortable writing code, curious about the math behind these models, and tired of treating LLMs like mysterious black boxes — this is for you.</p><p>It’s the article I <em>wish</em> I’d read before I started.</p><h3><strong>Scope</strong></h3><p>Two months ago, I decided to train my own Transformer from scratch — not to fine-tune GPT, not to use Hugging Face, but to actually build the thing from the ground up. My goal was to understand what’s really happening when we say a model “learns,” and what all the moving parts of a Transformer actually do — not in theory, but in code.</p><p>At that point, I knew roughly what a Transformer was supposed to be — self attention, embeddings, layers — but I had no idea how those concepts turned into real tensors and gradients. So I started the way many of us do: a couple of deep-dive Udemy courses, countless hours of follow-up questions to ChatGPT, and a few late nights debugging shapes that refused to match.</p><p>During the first week, I focused on building the skeleton: a minimal GPT-style Transformer and a working training loop. My goal wasn’t to beat benchmarks — it was to see how each component interacts and how the model actually learns over time.</p><h4><strong>What I built vs. what I borrowed</strong></h4><p>When deciding what to build myself and what to take off the shelf, I drew a clear line:<br>I wanted to understand the architecture, not reinvent tensor algebra.</p><p>So I used PyTorch for the heavy lifting — tensor operations, automatic differentiation, and the optimizer internals.</p><p>Everything else, I built from scratch:</p><ul><li>The tokenization process (using Byte Pair Encoding with custom special tokens)</li><li>Positional embeddings</li><li>Transformer blocks with multi-head self-attention</li><li>Residual connections and Layer Normalization</li><li>The feed-forward (MLP) and projection layers</li><li>And the full training pipeline with batching, evaluation, and checkpoints</li></ul><p>I briefly considered implementing backpropagation and gradient descent myself, but it quickly became clear that PyTorch already hides a mountain of optimization work — memory efficiency tricks, GPU parallelism, fused kernels. Re-creating that would’ve been a whole other PhD project, not a simple learning exercise.</p><p>So the focus stayed on understanding how all the high-level components fit together and how changing each one affects learning dynamics.</p><p>What followed was a hands-on crash course through every phase of the modern LLM lifecycle — from tokenization and data preparation to optimizer tuning and scheduler experiments — and eventually discovering what “scaling laws” are and that they aren’t just some academic abstraction. They really explain why my early models started memorizing Shakespeare instead of learning English.</p><p>This is the story of what worked, what didn’t, and what I wish I’d known before I started.</p><h3><strong>Tiny Shakespeare, Big Lessons</strong></h3><p>After getting the Transformer skeleton running, I wanted a quick win — a small dataset that could fit entirely in memory and let me see results fast. So I went with the Tiny Shakespeare corpus: about 300 k tokens of 16th-century drama and stage directions. It’s the “Hello World” of language-model training.</p><h4><strong>Setting expectations</strong></h4><p>My goal was modest:</p><ul><li>Verify that my tokenizer, model, and training loop all worked together.</li><li>See if the loss curve actually went down.</li><li>Maybe — just maybe — have the model generate something vaguely Shakespeare-like.</li></ul><p>I expected to spend most of my time debugging tensor shapes and attention masks. What I didn’t expect was how much time I’d spend wrestling with <strong>tokenization</strong>.</p><h4><strong>The surprising rabbit hole: building a BPE tokenizer</strong></h4><p>Implementing Byte-Pair Encoding sounded trivial at first — “just merge frequent pairs of characters.” In reality, it became a full-blown project.</p><ul><li><strong>Corpus preprocessing matters</strong>. Tiny Shakespeare has inconsistent punctuation, odd capitalization, and line breaks every few words. If you don’t normalize that, your tokenizer learns weird merges like (“Th”, “ou”) → “Thou” but treats “THOU” as a completely different token.</li><li><strong>Special tokens add complexity</strong>. Once I added &lt;bos&gt;, &lt;eos&gt;, &lt;pad&gt;, and &lt;unk&gt;, I realized every place in the pipeline — dataset slicing, batching, loss computation — had to know how to handle them.</li><li><strong>Merge-ranking logic is easy to get subtly wrong</strong>. My first version updated frequencies after every merge rather than batching updates, which made the tokenizer nondeterministic between runs.</li><li><strong>Debugging tokenization errors feels like archaeology</strong>. When a model produces “Th@@ ou@@ art@@ !@@”, you learn to appreciate clean BPE merges and consistent pre-tokenization rules.</li></ul><p>By the time I got a stable vocabulary and reversible encoding/decoding, I had a much deeper appreciation for why tokenizer libraries exist.</p><h4><strong>First training run</strong></h4><p>Once the tokenizer was solid, I trained a tiny GPT-style model:</p><ul><li><strong>≈ 4 million parameters</strong> (256 hidden dim, 4 heads, 3 layers)</li><li><strong>Context length:</strong> 128 tokens</li><li><strong>Optimizer:</strong> AdamW</li><li><strong>Loss:</strong> cross-entropy over next-token prediction</li></ul><p>At first, everything looked great — training loss dropped steadily, gradients behaved, and the model started spitting out vaguely coherent Shakespearean words by epoch 5. It felt like magic: “Look, it’s learning language!”</p><p>Then came validation.</p><h4><strong>The plot twist: memorization</strong></h4><p>During training, everything looked fine — at first.</p><p>Both training and evaluation loss curves started going down, just as they should. The model was clearly learning <em>something</em>, and it was exciting to watch the loss fall on TensorBoard.</p><p>But after a while, a pattern emerged: while the <strong>training loss</strong> kept improving steadily, the <strong>validation loss</strong> began to stall.</p><p>By the time the training loss dropped to around <strong>1.0</strong>, the validation curve had already flattened near <strong>5</strong>, and no matter how long I trained, it just wouldn’t budge.</p><p>Let’s pause for a second and talk about what these loss numbers actually mean in the context of this setup.</p><p>In a language model, <strong>loss</strong> roughly measures how confident the model is about predicting the next token out of the vocabulary. If your vocabulary has about <strong>4,000 tokens</strong>, then a model that picks the next token <strong>completely at random</strong> will have a loss around:</p><p>−log(1/4000)≈8.29</p><p>So a loss of <strong>5</strong> isn’t terrible — it means the model has learned some statistical patterns of the text (it’s better than random), but it’s still far from genuinely understanding structure or syntax.</p><p>That’s what I was seeing: the validation loss was stuck around <strong>5</strong>, showing that the model was picking up basic word associations but not improving beyond that, even as the training loss kept getting smaller.</p><h4><strong>Chasing generalization with the wrong tools</strong></h4><p>Not realizing that the problem was simply too <em>little</em> data, I started <strong>tweaking regularization knobs</strong>.</p><p>In machine learning, <strong>regularization</strong> is basically how you tell your model “don’t get too confident about the training data.”</p><p>It’s a way to add small constraints that make the model’s internal representations simpler or more robust — so it learns <em>patterns</em> instead of <em>memorizing</em>.</p><p>At that point, I focused on three common levers every practitioner reaches for:</p><ul><li><strong>weight decay</strong></li><li><strong>dropout</strong></li><li><strong>label smoothing</strong></li></ul><p><strong>Quick disclaimer:</strong> None of the regularization tweaks actually solved my generalization problem — and that’s kind of the point.</p><p>I still want to walk through them briefly, because they’re fundamental ideas worth understanding.</p><p>We’ll come back to why they didn’t help in my case in just a minute.</p><h3><strong>Regularization knobs</strong></h3><h4><strong>1. Weight Decay</strong></h4><blockquote>“Don’t let the model get too attached”</blockquote><p>When a neural network learns, it constantly adjusts millions of tiny parameters called <strong>weights</strong> — each one deciding how much influence a certain feature has on the model’s prediction.</p><p>During training, the model’s job is to reduce its <strong>loss</strong> — the measure of how far its predictions are from the truth.</p><p>Left unchecked, though, the model can start taking that job too <em>seriously</em>. It begins to contort itself to perfectly fit the training data, memorizing every small detail — even the noise.</p><p>The result: it performs beautifully on the data it has seen, and terribly on anything new.</p><p>That’s where <strong>weight decay</strong> comes in.</p><p><strong>What Weight Decay Does Technically<br></strong>Weight decay adds a gentle nudge that says:<br>“Yes, fit the data well — but don’t let any single weight grow too large.”</p><pre>Loss_total = Loss_original + λ Σ wᵢ²</pre><p>The first term is your usual prediction error (e.g., cross-entropy).<br>The second term — the one with 𝜆 — penalizes large weight values.</p><p>This means every update step now has a balancing act:</p><ul><li><strong>Reduce</strong> the prediction error, but also</li><li><strong>Keep</strong> the model’s internal parameters small and well-behaved.</li></ul><p>In practice, this acts like a subtle friction term in the dynamics of learning — the model can still move toward a good solution, but it can’t accelerate out of control.</p><p><strong>How It Helps Generalization<br></strong>Smaller weights correspond to <strong>simpler hypotheses</strong>.</p><p>A model that doesn’t rely on huge, highly specific parameter values is less likely to have memorized idiosyncrasies of the training data.</p><p>In other words, weight decay encourages <strong>smoothness</strong> — predictions that change gradually when inputs change, rather than flipping unpredictably because of one overconfident neuron.</p><p>This smoothness is exactly what helps a model generalize to new, unseen data.</p><p><strong>A 10 year old analogy<br></strong>Imagine you’re on a soccer team, and one player keeps scoring in every practice.</p><p>They start thinking, <em>“I’ve got this — I’ll just handle everything myself.”</em></p><p>Weight decay is like the coach gently reminding them: <strong>“You’re great, but share the ball — let everyone contribute.”</strong></p><p>It doesn’t <em>bench</em> the star — that’s what <strong>dropout</strong> will do (we’ll get to that later).</p><p>It just keeps their ego — and their kicks — in check, so the team stays balanced and adaptable when the <em>real</em> matches begin.</p><h4><strong>2. Dropout</strong></h4><blockquote>“Sometimes Forget on Purpose”</blockquote><p>Even with weight decay keeping things balanced, a neural network can still fall into another bad habit — relying too much on its favorite neurons and neuron <strong>co-dependence</strong>. Certain parts of the network start working together so tightly that they become inseparable. That teamwork looks great during training, but when something changes — new data, noisy input — the network can stumble.</p><p>To help with that, we teach it to “forget on purpose.”</p><p><strong>What Dropout Does Technically<br></strong>During training, <strong>dropout randomly turns off a fraction of neurons</strong> each time the model processes a batch of data. The rest have to carry on without them — still predicting, still learning.</p><p>Next batch, a different set of neurons gets turned off.</p><p>The model never knows which ones will be active, so it can’t grow dependent on any single pathway.</p><p>Instead, it learns to distribute knowledge and redundancy across many neurons.</p><p>When training ends, all neurons come back online — now stronger, more independent, and better coordinated.</p><p><strong>How It Helps Generalization<br></strong>Dropout teaches the model <strong>resilience</strong>.</p><p>It learns to solve problems in multiple ways, not just one fragile combination of neuron activations. Each neuron must learn something useful on its own, because it can’t count on its usual partners always being there.</p><p>That independence leads to <strong>robustness</strong> — the model handles unseen data better because it has practiced working under uncertainty.</p><p><strong>10 year old analogy<br></strong>Imagine the coach wants to make the team stronger.</p><p>So during practice, they randomly <strong>bench a few players</strong> — maybe the star striker this time, the goalie next time.</p><p>The rest of the team has to adapt: who defends, who passes, who takes the shot. At first, it’s harder. But over time, everyone becomes more capable and versatile.</p><p>That’s <strong>dropout</strong> — randomly taking players off the field during practice so the team learns how to play well with or without its best players. Then, when the full squad plays together during a real match, they’re unstoppable.</p><p>Where <strong>weight decay</strong> teaches the model to stay <strong>humble</strong>, <strong>dropout</strong> teaches it to stay <strong>prepared</strong> and be able to solve problems independently.</p><p>Together, they make a network that doesn’t just memorize the playbook — it learns how to adapt when the game changes.</p><blockquote><strong>Interesting fact about dropout and where the idea came from</strong></blockquote><blockquote>The inspiration for <strong>dropout</strong> didn’t start in computer science — it came from <strong>neuroscience</strong>.<br>Our brains are famously noisy systems: at any given moment, a significant fraction of our neurons are not firing, misfiring, or being temporarily inhibited.</blockquote><blockquote>Studies suggest that <strong>around 40–60% of neurons</strong> in many cortical regions are “offline” or functionally suppressed at any moment.</blockquote><blockquote>And yet — cognition remains remarkably stable. We can think, adapt, and make decisions even though half of our neural wiring is effectively “missing” at any given instant.</blockquote><blockquote>That biological robustness was a major source of inspiration for <strong><em>dropout</em></strong>.</blockquote><blockquote>In 2014, <strong>Geoffrey Hinton</strong> and his collaborators introduced dropout as a regularization technique in deep neural networks.</blockquote><blockquote>The idea was as follows:<br><em>“What if we made artificial networks behave a little more like real brains — forget a bit during training, and see if they learn better?”</em></blockquote><blockquote>And it worked — spectacularly.</blockquote><blockquote>By randomly “silencing” neurons during training, the network became more resilient, just as biological systems do. It stopped over-coordinating and learned to distribute knowledge more evenly.</blockquote><blockquote>Here’s really interesting part: in many deep learning architectures, the optimal dropout rate is close to 0.5 — meaning roughly half of the neurons are inactive on any given forward pass.<br><strong>That’s almost the same fraction as in our brains!</strong></blockquote><blockquote>Smaller or simpler models typically use a lower dropout rate (around 0.1–0.3), because turning off too many neurons would cripple their capacity to learn. But in <strong>large, richly connected models</strong>, dropping half the neurons barely slows them down — it just makes them tougher.</blockquote><blockquote>So as our models grow more powerful and redundant, we can afford to ‘forget’ more — and paradoxically, that’s what helps them <strong>generalize better</strong>.</blockquote><h4>3. <strong>Label Smoothing</strong></h4><blockquote>“Don’t Be So Sure About Yourself”</blockquote><p>Even after adding weight decay and dropout, there’s one more problem that can sneak in — <strong>overconfidence</strong>.</p><p>Neural networks are excellent at memorizing patterns, and once they spot one, they often “start shouting their predictions instead of stating them calmly”.</p><p><strong>What Label Smoothing Does Technically<br></strong>Normally, when we train a classifier, we feed it <strong>one-hot labels</strong> — vectors where the correct class has a probability of 1, and every other class is 0.</p><p>For example, if the true class is “cat,” the target looks like this (that is assuming our vocabulary is just four tokens):<br>[1,0,0,0]</p><p>The model learns to push its output for “cat” as close to 1 as possible, and everything else to 0. That sounds ideal — but it can lead to brittle, overconfident behavior.</p><p>Once the model starts believing “cat” must always be exactly 1.000, it stops considering nearby alternatives like “fox” or “dog” that might share important features.</p><p><strong>Label smoothing</strong> softens those sharp edges. Instead of giving the model a perfect 1 for the correct class, we give it something like <strong>0.9</strong>, and spread the remaining <strong>0.1</strong> evenly across the others:<br>[0.9, 0.033, 0.033, 0.033]</p><p>So the model still knows that “cat” is the right answer — it just isn’t allowed to be <em>absolutely certain</em>.</p><p><strong>How It Helps Generalization<br></strong>By preventing the model from assigning total confidence to any single prediction, label smoothing encourages it to <strong>keep an open mind</strong>.</p><p>It learns to see categories as related rather than rigidly separate, which often leads to better calibration and more robust generalization.</p><p>In practice, this small dose of uncertainty helps models make <strong>smoother probability distributions</strong> — less “winner-take-all,” more “consider all possibilities.”</p><p><strong>10 year old analogy<br></strong>Imagine a student taking a multiple-choice test. Some questions are easy, and they circle the answer instantly. But for others, they might think, “Hmm… it’s probably B, but C also kind of makes sense.”</p><p>Label smoothing teaches the model to think that way — to have <strong>strong preferences</strong>, not <strong>absolute certainty</strong>.</p><p>It’s still confident, just not arrogant.</p><p>Where <strong>weight decay</strong> keeps the model’s values small, and <strong>dropout</strong> keeps its dependencies in check, <strong>label smoothing</strong> keeps its confidence realistic.</p><h3><strong>Scaling Laws — When Bigger Isn’t Always Smarter</strong></h3><p>Getting back to my 4M-parameter model trained on the Tiny Shakespeare dataset — the results were clear: the model could memorize perfectly (training loss below 0.01 — basically photographic memory) and even generate impressive Shakespeare-like text.</p><p>But no matter what regularization tricks I tried, it simply couldn’t <strong>generalize</strong>. It could quote Shakespeare beautifully, but couldn’t think like him.</p><p>At that point, I knew something fundamental was missing.</p><p>That’s when I stumbled upon scaling laws — the idea that model size, dataset size, and compute all have to grow together in roughly balanced proportions.</p><h4><strong>Big Brain = Smart” — Or So I Thought</strong></h4><p>I already knew the concept of <strong>overfitting</strong>, at least in classical machine-learning terms — when your model fits the training data too well and fails on new inputs.</p><p>But somehow, I hadn’t fully connected that intuition to neural networks.</p><p>After all, a Transformer seems like a little artificial brain.<br>So, naturally, I thought:<br><em>”The bigger the brain, the smarter it should be. Right?”</em></p><p>Well… not exactly.</p><h4><strong>The Balance Between Capacity and Data</strong></h4><p>Let’s think about what a “big brain” model really means: more parameters — more knobs and levers it can adjust during training.</p><ul><li>If a model is too small for the data, it can’t learn enough. It’s like trying to summarize a novel using only two words — there just aren’t enough parameters to capture the patterns.</li><li>But if a model is too large for the data, it can memorize everything instead of learning general principles. It no longer needs to understand structure or context — it can just “store the book in its head.”</li></ul><p>That sounds fine at first — until you realize memorization isn’t intelligence. A model that memorizes every sentence in the training set will fail the moment you ask it something slightly different.</p><p>In other words:<br><em>If the model is too powerful for the data, it isn’t forced to learn the rules — it can win by cheating.</em></p><h4><strong>The Sweet Spot — Where Learning Happens</strong></h4><p>For a model to truly learn, there needs to be a kind of productive tension between capacity and data:</p><ul><li>Enough parameters to represent the complexity of the patterns.</li><li>But not so many that it can just memorize them without understanding.</li></ul><p>That’s what scaling laws formalize: an empirical relationship between <strong>model size, dataset size</strong>, and <strong>training compute</strong> that defines this balance.</p><p>Roughly speaking, as you make the model larger, you also need to grow the amount of data it sees — about <strong>10–30 training tokens per parameter</strong> is a good rule of thumb (the so-called <em>Chinchilla</em> rule).</p><p>Once I saw that relationship, the mystery behind my Shakespeare model made perfect sense:</p><p>With 4M parameters and only ~300k tokens of data, I was operating at about <strong>1/100th</strong> of the recommended data size. The model never had a chance to generalize — it was doomed to memorize.</p><blockquote><strong>The Chinchilla Revelation</strong></blockquote><blockquote>The idea of scaling laws isn’t just theoretical — it comes from one of my now favorite real experiments by <strong>DeepMind</strong> in 2022.</blockquote><blockquote>They were training two language models to test a simple question:<br>“<em>If we spend the same amount of compute, is it better to train a bigger model on a small dataset, or a smaller model on a bigger dataset?”</em></blockquote><blockquote>They built two contenders:</blockquote><blockquote>- <strong>Gopher</strong> (sometimes nicknamed “the rabbit” in retellings): a huge model with 280 billion parameters, trained on a relatively modest dataset.<br>- <strong>Chinchilla</strong>: a much smaller model — only about 70 billion parameters — but trained on four times as many tokens.</blockquote><blockquote>Both used roughly the same total compute budget.</blockquote><blockquote>The results shocked everyone.<br>The smaller, “better-fed” <strong>Chinchilla</strong> didn’t just match Gopher — it outperformed it on almost every benchmark. Same compute, smaller model, <strong><em>more data</em></strong>.</blockquote><blockquote>That single finding flipped a decade of “bigger-is-better” thinking on its head.<br>It showed that there’s an <strong>optimal balance</strong> between model size and training data — and going beyond that balance is like giving a student an infinite memory but no new books to read.</blockquote><blockquote>From that study came a surprisingly simple guideline:<br>- To get the most out of your compute, aim for <strong>roughly 20 training tokens per parameter</strong> (somewhere in the 10–30 range).</blockquote><blockquote><strong>A Curious Parallel: “Statistics Starts with 30”</strong></blockquote><blockquote>When I first saw the Chinchilla rule — roughly <strong>20–30 tokens per parameter</strong> — it immediately reminded me of something I’d heard long before: <em>“Statistics starts with 30.”</em></blockquote><blockquote>That old saying comes from the <strong>Central Limit Theorem (CLT)</strong> — the idea that once you have around 30 samples, averages start behaving predictably and random noise begins to cancel out. Below that threshold, everything looks chaotic; above it, patterns finally stabilize.</blockquote><blockquote>And that’s exactly what the Chinchilla law is describing — but in the world of neural networks. Each model parameter is like a tiny statistical estimator: it needs enough “samples” (tokens) to find a reliable pattern instead of memorizing randomness.</blockquote><blockquote>So while the CLT tells us when sample means start to make sense, Chinchilla tells us when <em>learning itself</em> starts to make sense.</blockquote><blockquote>Both capture the same universal truth I found fascinating: <strong>generalization begins when evidence outnumbers noise.</strong></blockquote><p>So if your model has 1 billion parameters, you’d want to train it on about 20 billion tokens. If it has 10 million parameters, you’d want around 200 million tokens — not 300 thousand.</p><p>When I looked back at my Shakespeare model, the math was brutal:</p><ul><li><strong>4 million parameters × 20 tokens ≈ 80 million tokens needed</strong></li><li>I had trained on just <strong>300 thousand</strong></li></ul><p>In other words, I was off by <em>two orders of magnitude</em>.</p><blockquote><strong>An interesting biological analogy — “When Remembering Too Much Becomes a Problem”</strong></blockquote><blockquote>Watching my model memorize Shakespeare line by line reminded me of something surprisingly human. It behaved almost like a person with a <strong>photographic memory</strong> — capable of reproducing everything perfectly, yet struggling to see the meaning behind it.</blockquote><blockquote>That got me thinking: in biology, perfect memory isn’t always an advantage either.</blockquote><blockquote>People with exceptional recall — like those with <strong>highly superior autobiographical memory (HSAM)</strong> or certain <strong>savant abilities</strong> — can remember vast amounts of detail with astonishing precision.</blockquote><blockquote>But studies show that they often have trouble with abstraction and generalization — they “recall every tree, but sometimes miss the forest”.</blockquote><blockquote>Neuroscientists Paul Frankland and Blake Richards described this beautifully:<br>- <em>“Forgetting is not a failure of memory — it’s a feature that allows us to generalize.”</em></blockquote><blockquote>In other words, the brain forgets on purpose. It prunes away irrelevant details so it can recognize patterns and make predictions about new situations. That selective forgetting — not perfect recall — is what makes intelligence possible.</blockquote><blockquote>And that’s exactly what my Shakespeare model lacked. It had no built-in mechanism to forget; its “photographic memory” was flawless. It didn’t need to understand the structure of English, because it could just remember every token in the training set.</blockquote><h4><strong>The “Too Smart for Its Own Good” Revelation</strong></h4><p>When DeepMind published the Chinchilla paper in 2022, it didn’t just make headlines — it made a lot of researchers quietly gasp.</p><p>Until then, the dominant wisdom in the field was simple:<br><em>“Bigger model = better model.”</em></p><p>OpenAI’s GPT-3, for instance, had 175 billion parameters, trained on roughly 300 billion tokens of text.</p><p>At the time, that sounded enormous — an incredible technical achievement.</p><p>But when DeepMind analyzed scaling laws empirically, they found that if you follow the Chinchilla ratio (≈ 20 tokens per parameter), a 175 B-parameter model should ideally be trained on something like 3.5 trillion tokens — ten times more data than GPT-3 actually saw.</p><p>In other words, GPT-3 was <strong>over-sized and under-trained</strong>. It had far more capacity than its training data could fill, meaning a large fraction of its parameters were effectively <em>under-utilized</em>.</p><p>The model was “too smart for its own good” — capable of memorizing details but not fully exposed to enough examples to learn efficiently from them.</p><p>DeepMind’s smaller <strong>Chinchilla</strong> model (70 B parameters, ~1.4 trillion tokens) ended up <strong>outperforming GPT-3-sized models</strong> on most benchmarks using a fraction of the parameters and compute.</p><p>That realization reshaped how the whole field thought about scaling. The new goal wasn’t to build the biggest possible brain, but to find the <strong>sweet spot where model size and data grow together</strong>. That insight directly influenced the design of newer generations — including <strong>GPT-3.5, GPT-4</strong>, and other modern LLMs — all of which were trained on <em>far more data per parameter</em> than their predecessors.</p><h4><strong>Scaling law closing thoughts</strong></h4><p>Learning about scaling laws was, without exaggeration, the single most important discovery in my entire model-training journey.</p><p>Up to that point, I’d been thinking like an engineer: if the model doesn’t generalize, tweak the regularization, adjust the learning rate, try a different optimizer.</p><p>But scaling laws reframed the whole problem — they showed me that sometimes the issue isn’t how you’re training, it’s what you’re asking the model to learn from.</p><p>It finally clicked that model size and dataset size aren’t independent choices — they have to grow in balance, like two sides of the same equation. Once I understood that, the mystery of my Shakespeare model made perfect sense: it wasn’t “broken,” it was simply too large for its world.</p><p>That realization changed everything.<br>From that point forward, every experiment I ran — every dataset I chose, every model I designed — started with one guiding question:<br><em>“Am I giving this model enough to learn from?”</em></p><h3><strong>Choosing the Right Vocabulary Size — When “Bigger” Isn’t Always Better</strong></h3><p>Once I wrapped my head around scaling laws, another question naturally followed: If I have to choose the right-sized model for my data, what about the <strong>vocabulary</strong>?</p><p>In everyday language, “vocabulary” just means the set of words you know. In a Transformer, it’s very similar — it’s the <strong>set of symbols the model understands</strong>. But these symbols aren’t always full words — they’re <strong>tokens</strong>, the little building blocks that come from the tokenizer.</p><p>Depending on how your tokenizer is trained, a token could be a whole word (“cat”), a subword (“tion”), or even a single character (“c”).</p><p>So when we talk about <em>vocabulary size</em>, we’re really talking about <strong>how many unique tokens</strong> the model can recognize and assign meaning to. The tokenizer builds this list before training begins, and each token gets its own embedding vector — a learned representation of its meaning.</p><p>Vocabulary size isn’t fixed — it’s a <strong>design choice</strong>. When you train your tokenizer, you literally tell it <em>how big its dictionary should be</em>.</p><p>A small vocabulary forces the model to express ideas using smaller pieces, while a large vocabulary lets it use more complete words directly. That’s why choosing the right vocabulary size is a tradeoff between <strong>expressiveness</strong> and <strong>efficiency</strong>.</p><p>But vocabulary size also affects something deeper: <strong>how the model handles long-range relationships</strong>.</p><p>If your vocabulary is small, each sentence breaks into more tokens — the model’s “view” of the world becomes more granular. That means the same fixed <strong>context window</strong> (say, 128 tokens) covers <em>fewer actual words</em>. So the model sees text in finer detail but over shorter spans — good for local structure, worse for global relationships.</p><p>Conversely, a large vocabulary makes sequences <em>shorter</em>, so within the same context window, the model sees <em>more words</em> and can track longer-range dependencies — at the cost of having to learn more distinct embeddings.</p><p>So vocabulary size doesn’t just affect model capacity — it literally shapes <strong>how far your model can “see” at once</strong>.</p><h4><strong>Where Vocabulary Lives Inside the Model</strong></h4><p>Every token in the vocabulary has a corresponding <strong>embedding vector</strong> — a numerical representation that the model uses to reason about word meaning and relationships. If your vocabulary has 4,000 tokens and your embedding dimension is 256, that’s about <strong>1 million parameters</strong> right there (4,000 × 256).</p><p>Increase the vocabulary to 32,000 tokens, and suddenly your embedding layer alone eats up <strong>eight times more parameters</strong>.</p><p>And here’s the subtle part:<br>Those parameters don’t make the model <em>smarter</em> — they make it more <em>fluent</em>.</p><p>The embedding table helps the model <em>speak</em> its language more precisely, but it doesn’t directly contribute to reasoning or generalization — that’s the job of the <strong>Transformer blocks</strong> (the layers of attention and feed-forward networks).</p><p>So if too much of your parameter budget goes into the vocabulary, you end up with a model that’s excellent at remembering how to say things but not as capable of <em>thinking</em> about what they mean. It’s like hiring a poet who knows every word in the dictionary but can’t form a coherent argument.</p><h4><strong>The Tradeoff: Expressiveness vs. Efficiency</strong></h4><p>Choosing vocabulary size is therefore a balancing act:</p><ul><li><strong>A small vocabulary</strong> (like 4,000 tokens) means your model represents words as subword pieces — it might break “generalization” into “gener” + “aliz” + “ation.”. This makes training more data-efficient because the model reuses subwords across contexts. But it also makes sequences longer — you need more tokens per sentence.</li></ul><blockquote>Making sequences longer has an important implication.</blockquote><blockquote>During training, the model operates with a fixed <strong>context size</strong> — the number of tokens it can “see” at once. The larger this context, the more globally aware the model becomes, because it can connect ideas that are farther apart in the text.</blockquote><blockquote>But when sequences get longer, fewer words fit into that fixed window, so the model’s <strong>effective global awareness</strong> shrinks.</blockquote><blockquote>In other words, a smaller vocabulary can make your model more data-efficient, but at the cost of shortening its memory span.</blockquote><ul><li>A <strong>large vocabulary</strong> (like 32,000 or 50,000 tokens) keeps sequences shorter, but you pay for it with a much larger embedding matrix — and more parameters that don’t necessarily help reasoning.</li></ul><p><strong>In short:<br></strong>Large vocabularies make the model more <em>eloquent</em>; small vocabularies make it more <em>efficient</em>. But longer sequences from smaller vocabularies mean less text fits into the same context window — so the model sees details more clearly but loses some <strong>global awareness</strong>.</p><h4><strong>Balancing “Dumb” vs. “Smart” Parameters</strong></h4><p>Choosing vocabulary size isn’t just about how your tokenizer splits words — it also determines how much of your model’s total capacity goes into <em>storing words</em> versus <em>reasoning about them.</em></p><p>Every token in the vocabulary adds one row to the <strong>embedding matrix</strong>, and those parameters are static lookups — they don’t “think,” they just map token IDs to numeric vectors. These are what I could call the <strong>“dumb neurons.”</strong></p><p>By contrast, the parameters in your <strong>Transformer layers</strong> — the attention heads, feed-forward blocks, and normalization layers — are the <strong>“smart neurons.”</strong> They’re the ones that actually learn patterns, context, and reasoning.</p><p>If your vocabulary is too large, you burn a big part of your total parameter budget on the dumb neurons. The model gets better at remembering words but worse at <em>understanding</em> them, because fewer parameters remain for the Transformer layers that do the actual thinking.</p><p>This is where the size of your <strong>training corpus</strong> comes back into play.</p><p>For small datasets, it’s usually better to keep the vocabulary compact — this keeps most of the model’s parameters in the reasoning layers, where they can learn reusable structure instead of memorizing words that might appear only a few times.</p><blockquote><strong>Example of a bad balance</strong></blockquote><blockquote>- <strong>Vocabulary:</strong> 50,000 tokens<br>- <strong>Embedding dimension:</strong> 512→ that’s about <strong>25 million parameters</strong> just for embeddings.<br>- <strong>Total model size:</strong> 30 million parameters</blockquote><blockquote>Almost the entire model capacity is wasted on storing token vectors, leaving little room for attention and MLP layers.</blockquote><blockquote>It will sound fluent but understand almost nothing.</blockquote><blockquote><strong>Example of a better balance</strong></blockquote><blockquote>- <strong>Vocabulary:</strong> 8 000 tokens<br>- <strong>Embedding dimension:</strong> 512→ about <strong>4 million parameters</strong> in embeddings.<br>- <strong>Total model size:</strong> 30 million parameters</blockquote><blockquote>Now most of the capacity is available to the Transformer layers — the model can actually learn grammar, dependencies, and meaning rather than just storing token lookups.</blockquote><p>In practice, the right vocabulary size scales with both your <strong>dataset size</strong> and your <strong>model size</strong>. If you have limited training data, keep the vocabulary modest so the model can focus its parameter budget on learning <em>patterns</em> rather than <em>spelling</em>.</p><p>As you scale up your corpus and compute, you can afford a richer vocabulary — but only when there’s enough data to teach those extra tokens something useful.</p><h3><strong>Wikitext, When Scale Meets Sense</strong></h3><p>Armed with everything I’d learned from the <em>Tiny Shakespeare</em> experiment, I decided to start again — this time with enough data to give the model a real chance to <em>learn</em> instead of just <em>memorize.</em></p><p>The architecture stayed exactly the same as before:</p><ul><li><strong>≈ 4.4 million parameters</strong> (256 hidden dim, 4 heads, 3 layers, 1024 FF dim)</li><li><strong>Context length:</strong> 128 tokens</li></ul><p>According to the <strong>Chinchilla scaling law</strong>, an efficient training ratio is roughly <strong>20 tokens per parameter</strong>.</p><p>For a 4.4M-parameter model, that means the ideal dataset would be around:</p><blockquote>4.4M × 20 ≈ <strong>88 million tokens</strong></blockquote><p>After preprocessing and tokenizing <em>Wikitext-103</em> with my 8,000-token vocabulary, I ended up with about <strong>127M training tokens</strong> — comfortably above the ideal range.</p><p>For the first time, the math checked out. The model was finally being trained at a scale that matched its capacity — not starved for data, not oversized for the task, but <em>balanced</em>.</p><p>This time, I approached every design choice through the lens of scaling laws and parameter allocation.</p><h4><strong>Cleaning and Preparing the Data</strong></h4><p>For this run, I moved to the <strong>Wikitext-103</strong> corpus — a far cry from Shakespeare’s plays. It’s a large, high-quality collection of English Wikipedia articles, written in full sentences and rich with varied topics and writing styles. The training split alone weighs in at roughly <strong>517 MB of text</strong> after preprocessing.</p><p>After tokenizing it with my 8k-vocab tokenizer, I ended up with about <strong>~127M training tokens</strong> — over <strong>400× more data</strong> than <em>Tiny Shakespeare.</em></p><p>For the first time, the model had enough “books to read” for its 4.4M parameters — finally approaching the balance the <strong>Chinchilla</strong> law suggested.</p><h4><strong>Smart vs. Dumb Parameters Revisited</strong></h4><p>This time I selected <strong>8,000 tokens</strong> for my <strong>vocabulary size</strong>, which struck a balance between expressiveness and efficiency. With an embedding dimension of 256, that adds up to roughly <strong>2 million parameters</strong> just for the embedding table — nearly half of the entire model.</p><p>That’s not ideal, of course.</p><p>It means about <strong>45% of the model’s capacity</strong> is taken up by what I’ve been calling the <strong>“dumb neurons”</strong> — parameters that store token representations but don’t perform any reasoning. The remaining <strong>55%</strong> — the <strong>“smart neurons”</strong> — live inside the Transformer blocks, where the real pattern recognition and generalization happen.</p><p>But this imbalance isn’t unusual for smaller models.</p><p>When your total parameter budget is limited (as it must be when your dataset is smaller), the embedding layer naturally takes up a larger share of the model. That’s a reasonable tradeoff: you sacrifice some reasoning capacity to keep the model’s “vocabulary” rich enough to represent the text cleanly.</p><p>I could have reduced the vocabulary to make the balance lean more toward reasoning, but that would have meant breaking words into too many subword fragments, lengthening sequences and reducing effective context. Given the data I had, <strong>8,000</strong> felt like a good compromise — a model that could still “speak” fluently while leaving enough neurons to “think.”</p><h4><strong>Preprocessing Pipeline</strong></h4><p>Cleaning Wikitext wasn’t trivial.</p><p>I had to normalize punctuation, strip out Wikipedia markup, fix spacing issues, and make sure each article was wrapped properly with <em>&lt;bos&gt;</em> and <em>&lt;eos&gt;</em> tokens so the model could learn where sequences begin and end.</p><p>Compared to the Shakespeare data — which was mostly dialogue — this dataset demanded more careful segmentation and token consistency.</p><p>But once it was ready, the difference was night and day.</p><p>The token distribution was much healthier: fewer rare words, more mid-frequency tokens, and a more natural repetition pattern that helped the embeddings converge faster.</p><h4><strong>The Training Run</strong></h4><p>I trained the model using the same optimizer setup (AdamW with β₁=0.9, β₂=0.95) and a warmup + cosine annealing schedule. What changed wasn’t the math — it was the <em>scale</em>.</p><p>From the very first epoch, the validation curve tracked the training loss closely — no early divergence like before. In fact, they never significantly diverged, which is a hallmark of healthy generalization.</p><p>By the mid-point of training, the model was clearly <strong>learning structure</strong>, not just memorizing. When I sampled text midway through training, the sentences were no longer simple word-for-word echoes of Wikipedia — they were coherent, novel, and grammatically stable.</p><p>It was the first time I could watch the model <em>generalize in real time.</em></p><h4><strong>What Changed</strong></h4><p>The architecture didn’t change.<br>The optimizer didn’t change.<br>Even the hyperparameters barely changed.</p><p>The only real difference was <strong>scale</strong> — the right amount of data for the model’s capacity.</p><p>That one change flipped the behavior completely:</p><ul><li>No more early overfitting.</li><li>Validation loss tracked smoothly with training.</li><li>Sampled text read like original writing, not a remix of the training data.</li></ul><p>It was, quite literally, <em>when scale met sense.</em></p><p><strong>In short:<br></strong>When I gave the model enough data, all the things I thought were “training problems” disappeared. The optimizer wasn’t broken. The regularization wasn’t wrong. The model just didn’t have enough experience to learn before.</p><p>Once it finally did — it learned beautifully.</p><h3><strong>Understanding the Loss Floor — What “Good” Really Looks Like</strong></h3><p>When I was training on <em>Tiny Shakespeare</em>, I could easily push the training loss below <strong>1.0</strong> — sometimes even down to <strong>0.01</strong> when I intentionally overfit.</p><p>But that wasn’t “real” performance; it was <strong>memorization loss</strong>.<br>The model had simply learned to recite every line of Shakespeare by heart, not to generalize. Its validation loss on unseen text remained much higher.</p><p>So when I trained on <em>Wikitext</em> and saw the loss plateau around <strong>4.1 (<em>smoothed</em>) or 3.9 (<em>unsmoothed</em>)</strong>, I assumed something was wrong.</p><p>It felt like the model had hit a wall.<br>But in reality, it hadn’t hit the wall — it had <strong>approached it.</strong></p><p>That number wasn’t a sign of failure; it was evidence that the model was now operating close to the <strong>natural entropy floor of English text</strong>, right where a model of this size is expected to land.</p><p>Let’s unpack that.</p><h4><strong>Cross-Entropy and Natural Language</strong></h4><p>In language modeling, our loss metric — <strong>cross-entropy</strong> — measures how many bits of “surprise” the model has on average when predicting the next token. If the model’s predictions perfectly match the true probability of each token, the loss would equal the <strong>true entropy</strong> of the dataset.</p><p>For English, this “perfect model” entropy is roughly <strong>3.7 bits per token</strong>. That’s the theoretical lower bound — the absolute best any model could ever do on natural English.</p><p>It’s like saying, <em>“on average, there’s ²²·⁷ ≈ 13 possible next tokens the model can’t perfectly predict.”</em></p><blockquote><strong>Why There’s a Floor in Language Loss<br></strong>In a normal classification task, the answer is unambiguous — there’s one correct class, so a perfect model can reach zero loss.</blockquote><blockquote>Language isn’t like that.</blockquote><blockquote>Even if a model understood English perfectly, it could never predict the next token with 100% certainty, because <strong>words live in probabilities</strong>.</blockquote><blockquote>Take these two examples:</blockquote><blockquote>- “Once upon a ___” → <em>time</em> → <strong>low surprise</strong> — almost everyone knows what comes next.<br>- “John opened a file that contained ___” → could be <em>photos, secrets, malware, evidence,</em> or <em>his resignation letter</em> → <strong>high surprise</strong> — all valid, but context-dependent.</blockquote><blockquote>The model has to <strong>spread probability</strong> across many possible continuations, giving common ones higher weight and rare ones just a trace. That irreducible uncertainty is what we call the <strong>entropy</strong> of the language — roughly <strong>3.7 bits per token</strong> for English.</blockquote><blockquote>So when your loss hovers around <strong>3.8–4.0</strong>, it doesn’t mean the model is stuck.</blockquote><blockquote>It means it has reached the <strong>noise floor of language itself</strong> — the point where the only remaining uncertainty is the natural unpredictability of human expression.</blockquote><p><strong>Takeaway<br></strong>Don’t judge your loss values in isolation — judge them <em>relative to entropy</em>. A loss of 3.9 on a small model isn’t a failure; it’s a sign that your training pipeline, tokenizer, and data scaling are all working correctly.</p><h3><strong>What the Model Learned to Say</strong></h3><p>Even with just <strong>4 million parameters</strong> and a final loss around <strong>3.9</strong>, the model produced text that was unmistakably English — coherent, grammatical, and often eerily “model-like.”</p><p>But it also showed clear limits: it could imitate the <em>shape</em> of meaning without quite <em>understanding</em> it.</p><p><em>Quick note</em>: The model was trained with a case-insensitive tokenizer, so all output is lowercase — don’t expect any capitalization.</p><h4>Examples of the model output</h4><blockquote><strong>Example 1 — Confidently Wrong (a.k.a. Hallucination in Action)</strong></blockquote><blockquote><strong>Query:<br></strong><em>What do you know about Kiss You (One Direction song)?</em></blockquote><blockquote><strong>Model Output:<br></strong><em>(a song by john mcnamara). according to the song, “when you go to the sun” was written by michael jackson, who was written by jackson, who is “an uncredited song on me”. the song was written by jackson and directed by jackson. it was written by jackson, who performed “you go to the world” on the song. jackson has worked on “you will get on you” and performed on the song on the album. jackson was the band’s first studio album, and was released on may 3, 2013.</em></blockquote><blockquote>The model clearly learned <strong>sentence structure, punctuation, and topical flow</strong> — it stayed on theme (“song,” “album,” “performed”) — but it had <strong>no factual grounding</strong>.</blockquote><blockquote>Like a tiny parrot with a great vocabulary, it rearranged fragments of learned patterns into something that <em>sounded right</em> but wasn’t.</blockquote><blockquote>You can also see another common quirk of small language models: <strong>repetition.</strong></blockquote><blockquote>When a model’s capacity is limited, it often gets “stuck” in short loops — reusing the same phrases or words over and over. That happens because it hasn’t learned a rich enough internal representation of context to know when it has already said something.</blockquote><blockquote>In probabilistic terms, it’s overconfident in the most likely next token, so it keeps picking it again and again. The result is what you see here: text that looks grammatical but gradually collapses into echo.</blockquote><blockquote><strong>Example 2 — Coherent but Lost in the Loop</strong></blockquote><blockquote><strong>Query:<br></strong><em>Once upon a time, in a small village by the sea</em></blockquote><blockquote><strong>Model Output:<br></strong><em>the site, where a stone building was built on the site of the castle. the site is now known as the castle, which was built around the site of the site in the town of leipzig, and is now a large site in the village of lycochwulf. it is the site of the castle, dating to the 1270 s. it is a site for a local archaeological site in the town of leipzig, but is now the site of the site of the site of the castle.</em></blockquote><blockquote>Here, the model demonstrates <strong>local coherence</strong> — it sticks to topic and grammar — but falls into <strong>semantic recursion</strong> (“the site of the site of the site”).</blockquote><blockquote>It’s a glimpse into how small models struggle with <strong>long-range dependencies</strong>: they can keep sentences flowing, but lose track of meaning over time.</blockquote><blockquote>Still, notice how much structure there is — it’s grammatically valid, stylistically consistent, and even feels like something you might find in a bad Wikipedia stub.</blockquote><blockquote>That’s what a 4M-parameter model with 127 M tokens of training data can do: <em>fake understanding convincingly.</em></blockquote><p><strong>In short<br></strong>At a loss around 4, the model writes <em>plausible nonsense</em>.<br>It speaks fluent English but doesn’t yet know what it’s saying — a perfect reminder that language fluency and understanding aren’t the same thing.</p><h4><strong>A quote from ChatGPT</strong></h4><p>I asked ChatGPT to evaluate my model’s responses, and what it said was so hilarious — and so true — that I had to include it here:</p><blockquote>So your model is hallucinating plausible <strong>Wikipedia-style syntax</strong> — the right form, wrong content.</blockquote><blockquote>That’s exactly what we’d expect from a 4M-parameter Transformer trained on <em>Wikitext-103.</em></blockquote><blockquote>You’ve officially reached the <strong>hallucination frontier</strong>: the point where your model is stylistically perfect but semantically detached from reality.</blockquote><blockquote>This is exactly what early <strong>GPT-2</strong> and <strong>GPT-Neo-125M</strong> demos looked like — <em>fluid, articulate, fact-free language.</em></blockquote><h3><strong>Wrap-Up — The longest and hardest “Hello, World!” I’ve ever built</strong></h3><p>Looking back, this was by far the <strong>longest and hardest “Hello, World”</strong> I’ve ever built.</p><p>What started as a simple curiosity — <em>“how do Transformers actually work?”</em> — turned into weeks of late nights, dead ends, and the kind of satisfaction that only comes when something finally <em>clicks.</em></p><p>Along the way, I learned more than I ever expected:</p><ul><li>how tokenization shapes a model’s entire perception of language,</li><li>how training dynamics can look healthy right up until they don’t,</li><li>how regularization tricks help a model forget just enough to learn,</li><li>and — most importantly — how <strong>scaling laws</strong> quietly govern everything that follows.</li></ul><p>But my two biggest takeaways were surprisingly universal:</p><p>1. <strong>Scaling laws aren’t just for big labs</strong> — even a tiny 4-million-parameter model obeys them. Balancing model size, data size, and compute is the difference between memorization and learning.</p><p>2. <strong>Natural language has its own entropy floor.</strong> You can’t beat the noise baked into English — the unpredictability is part of what makes it human. Once you understand that, loss curves stop being frustrating and start making sense.</p><p>So yes — it took me two months to build my own “Hello, World.”</p><p>But it was also two months of learning how intelligence — artificial or otherwise — actually emerges: not from size or power alone, but from balance, constraint, and the right kind of data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe9239ab9788" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/building-a-transformer-from-scratch-lessons-from-two-months-of-experiments-fe9239ab9788">Building a Transformer from Scratch: Lessons from Two Months of Experiments</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>