<?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 Hidden Layer on Medium]]></title>
        <description><![CDATA[Stories by Hidden Layer on Medium]]></description>
        <link>https://medium.com/@hiddenlayerNx?source=rss-0cb3fd345501------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WkR5hPas6IqQWZjVil-xMA.jpeg</url>
            <title>Stories by Hidden Layer on Medium</title>
            <link>https://medium.com/@hiddenlayerNx?source=rss-0cb3fd345501------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:49:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hiddenlayerNx/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[The Room Where Every Word Hears Every Other: softmax(QKᵀ/√dₖ)V]]></title>
            <link>https://medium.com/@hiddenlayerNx/the-room-where-every-word-hears-every-other-softmax-qk%E1%B5%80-d%E2%82%96-v-671e6243206b?source=rss-0cb3fd345501------2</link>
            <guid isPermaLink="false">https://medium.com/p/671e6243206b</guid>
            <category><![CDATA[attention-is-all-you-need]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[self-attention]]></category>
            <dc:creator><![CDATA[Hidden Layer]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 10:35:48 GMT</pubDate>
            <atom:updated>2026-11-21T10:38:34.505Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Attention wasn’t the breakthrough. Parallelism was, and attention was the price of admission.</em></p><p><em>AI Journal Series #1 · Attention Is All You Need (Vaswani et al., 2017)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Uqo8_PvcZtBBI586kfaCw.png" /><figcaption>Transformer self-attention visualized through interconnected word tokens.</figcaption></figure><h3><strong>Reading one word at a time</strong></h3><p>You get one word. You squeeze everything you know into a fixed-size memory. Then you throw the word away and take the next one. By the time you reach “it” at the end of a long sentence, the noun it points back to is a faint smudge in a vector that has been overwritten forty times.</p><p>That isn’t how you actually read. Your eyes jump back. “It” looks straight at “the animal” without walking back through every word in between.</p><p>The paper this post is about asks: what if a model could do that too? What if every word could look at every other word directly, all at once, in a single step?</p><p>The answer is the Transformer. In my first post I wrote about <em>what</em> a language model computes, p(xₜ | x₍&lt;ₜ₎). This post is about the machine that computes it.</p><h3>The world before: a model that had to wait for itself</h3><p>In 2017 the best sequence models were RNNs (LSTMs, GRUs) in an encoder–decoder setup. The paper names the problem in the first sentence I highlighted: recurrent models produce hidden states hₜ, each a function of the previous state hₜ₋₁ and the current input:</p><pre>hₜ = f(hₜ₋₁, xₜ)</pre><p>That arrow from hₜ₋₁ to hₜ is the whole problem. You can’t compute h₅₀ until you have h₄₉. The paper says this “precludes parallelization within training examples.”</p><p>That’s easy to misread as “RNNs are slow.” The real issue is that a GPU is a machine for doing thousands of <em>independent</em> multiplications at once, and an RNN hands it a chain of <em>dependent</em> steps. The work isn’t too big; it’s too serial. And the paper adds that this gets worse with long sequences, “as memory constraints limit batching across examples.” So you lose parallelism inside a sentence <em>and</em> across sentences.</p><p>Convolutional models (ByteNet, ConvS2S) fixed the first problem, since they process all positions in parallel. But a convolution only sees a local window. The paper notes that the number of operations needed to relate two distant positions grows linearly with distance for ConvS2S and logarithmically for ByteNet. Distant words can talk to each other, but only through a chain of intermediaries.</p><p>Attention already existed, but “in all but a few cases” it was bolted onto an RNN. It was a helper; the recurrence still carried all the weight.</p><p>So the tension in 2017 was: <strong>recurrence gives you order but kills parallelism; convolution gives you parallelism but makes distance expensive.</strong></p><h3>The core idea</h3><p>Remove recurrence entirely. Build every layer from one operation: each position looks at every other position in the same sequence, decides how relevant each one is, and takes a weighted mix of what they contain.</p><p>That’s <strong>self-attention</strong>: “<em>an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence</em>.” The paper’s real claim is that the Transformer is the first transduction model relying <em>entirely</em> on it. Attention wasn’t new. Betting the whole architecture on it was.</p><p>The bet removes both walls at once. Position 50 doesn’t wait for position 49, so the whole layer becomes a few big matrix multiplications, which is exactly what GPUs want. And word 1 reaches word 50 in one step, not fifty.</p><p>There’s a price, though. Every token scoring every other token is an n × n grid per layer. Table 1 of the paper does the accounting: self-attention costs O(n²·d) per layer, against O(n·d²) for a recurrent layer, but it needs only O(1) sequential steps instead of O(n), and any two words are one step apart instead of n. For sentence-length inputs, where n is smaller than d = 512, that’s a bargain. For very long inputs it isn’t, and the authors say so.</p><p>The other cost: once recurrence is gone, the model has no idea what order the words came in. Keep that in mind; we’ll come back to it.</p><h3>How it works</h3><p>The Transformer model architecture: an encoder stack on the left and a decoder stack on the right, each repeated N times <em>Figure 1 from Vaswani et al. (2017), “The Transformer — model architecture.” Reproduced with attribution, per Google’s permission notice on the paper.</em></p><figure><img alt="The Transformer — model architecture." src="https://cdn-images-1.medium.com/max/367/1*D63Tupa8AyKdUxEm-_BZEg.png" /></figure><p><strong>Left tower: the encoder.</strong> N = 6 identical layers. Each layer has two sub-layers, multi-head self-attention and then a small feed-forward network, each wrapped as LayerNorm(x + Sublayer(x)). Every vector has the same width, d_model = 512, so the residual &quot;+&quot; works everywhere.</p><p><strong>Right tower: the decoder.</strong> Also N = 6 layers, with a third sub-layer in the middle that attends over the encoder’s output. That’s the bridge between the towers. The decoder’s own self-attention is <strong>masked</strong>, which I’ll explain below.</p><h3>Attention as a soft dictionary lookup</h3><p>The paper describes attention as “mapping a query and a set of key-value pairs to an output.” I picture it as a Python dict that has gone soft. A dict finds the <em>one</em> key that matches and returns its value. Attention compares your query against <em>every</em> key and returns a <em>blend</em> of all the values, weighted by how well each key matched.</p><p>Each token plays all three roles through three learned projections:</p><ul><li><strong>Query (Q):</strong> what am I looking for?</li><li><strong>Key (K):</strong> what do I advertise to others?</li><li><strong>Value (V):</strong> what do I hand over if you pick me?</li></ul><p>Now picture these as arrows in space. The dot product q · k is large when two arrows point the same way and near zero when they’re perpendicular. “How relevant is token j to token i?” becomes a question of geometry: <em>how aligned are their arrows?</em></p><p>Equation 1, the one I boxed:</p><pre>Attention(Q, K, V) = softmax( QKᵀ / √dₖ ) V</pre><p>Read it inside out. <strong>QKᵀ</strong> is every query dotted with every key: an n × n grid where row i is token i’s opinion of everyone else. <strong>÷ √dₖ</strong> is a scaling factor that looks cosmetic and isn’t (explained just below). <strong>softmax</strong> turns each row into weights that sum to 1. <strong>× V</strong> makes each token’s output a weighted average of everyone’s values.</p><p>It’s two matrix multiplications and a softmax, with no loop over positions anywhere.</p><h3>Why divide by √dₖ</h3><p>The paper gives the reason in footnote 4. Suppose the components of q and k are independent, with mean 0 and variance 1. Then q · k is a sum of dₖ such products, so its <strong>variance is dₖ</strong>.</p><p>With dₖ = 64, the raw scores spread out with a standard deviation of about 8. Two scores 8 apart give a softmax weight ratio of e⁸ ≈ 3,000 to 1, which is essentially one-hot. A softmax that saturated barely reacts when its inputs change, which in the paper’s words pushes it “into regions where it has extremely small gradients.” Learning stalls.</p><p>Dividing by √dₖ brings the variance back to 1, whatever the head size. It’s the same instinct as careful weight initialization: keep activations at unit scale so gradients can flow.</p><p>The paper compares this with <strong>additive attention</strong>, which scores each query–key pair with a tiny one-hidden-layer network. The two are similar in theoretical complexity, but dot-product attention is “much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.” That’s the first sign of the theme of the whole paper: the choice was made because it maps onto the hardware.</p><h3>Multi-head: several conversations at once</h3><p>One attention pattern per layer means each token gets <em>one</em> weighted average, and averages blur. If “it” needs to track both its noun and its verb, one softmax has to compromise.</p><p>The fix is to run h attentions in parallel, each in its own projected subspace:</p><pre>MultiHead(Q, K, V) = Concat(head₁, …, head_h) Wᴼ<br>where headᵢ = Attention(QWᵢQ, KWᵢK, VWᵢV)</pre><p>In the paper’s words, this lets the model “jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.”</p><p>The base model uses h = 8 heads of width dₖ = 512/8 = 64. Eight heads of width 64 add up to exactly 512, so you get eight viewpoints for about the price of one.</p><h3>Three kinds of attention, and the mask</h3><p>Encoder self-attention lets every source word look at every source word. Encoder–decoder attention takes queries from the decoder and keys and values from the encoder, so each output position can look at the whole source sentence. <strong>Masked decoder self-attention</strong> lets the decoder look only at what it has generated so far.</p><p>That mask matters a lot. During training the decoder sees the whole target sentence at once; that’s what makes training parallel. But position i must not peek at position i+1. So before the softmax, every “future” score is set to −∞. Since e^(−∞) = 0, the future gets exactly zero weight. Combined with shifting the outputs right by one, this “ensures that the predictions for position i can depend only on the known outputs at positions less than i.”</p><p>That’s p(xₜ | x₍&lt;ₜ₎) from my last post, implemented as a triangular matrix of −∞. A sequential <em>generation</em> process gets <em>trained</em> fully in parallel.</p><h3>Communicate, then compute</h3><p>After attention, each position passes through Equation 2, also boxed:</p><pre>FFN(x) = max(0, xW₁ + b₁)W₂ + b₂</pre><p>The key phrase is that it’s applied “to each position separately and identically,” with an inner width d_ff = 2048. My mental model of one layer: attention is where tokens <strong>talk to each other</strong>, and the FFN is where each token <strong>thinks privately</strong> about what it just heard. Stack six layers and you get six rounds of “communicate, then compute.”</p><h3>Order, injected by hand</h3><p>Self-attention is a weighted sum, and a sum doesn’t care about order: “dog bites man” and “man bites dog” look the same. The paper says it plainly: with no recurrence and no convolution, “we must inject some information about the relative or absolute position of the tokens.”</p><p>Their answer is to add sine and cosine waves to each embedding:</p><pre>PE(pos, 2i)   = sin( pos / 10000^(2i/d_model) )<br>PE(pos, 2i+1) = cos( pos / 10000^(2i/d_model) )</pre><p>Think of each pair of dimensions as a clock hand spinning at its own speed. A position is the reading of all the clocks at once, like a smooth binary counter.</p><p>Why waves and not just a learned table? The authors hypothesized it would let the model “easily learn to attend by relative positions,” because for any fixed offset k, the encoding of pos + k is a linear function of the encoding of pos. For each sin/cos pair, moving k steps ahead is the same rotation, by angle ωk, wherever you start. So “three words later” looks the same everywhere in the sentence.</p><p>They did try learned position embeddings, and the results were “nearly identical” (Table 3, row E). They kept the sinusoids because they “may allow the model to extrapolate” to sequences longer than any it saw in training.</p><h3>Training and decoding</h3><p><strong>Data.</strong> English→German used WMT 2014, about 4.5 million sentence pairs. Text is split with <strong>byte-pair encoding</strong>, which starts from characters and repeatedly merges the most frequently occurring pair of symbols into a new token. That gives a shared vocabulary of about 37,000 tokens. English→French used a much larger set of 36 million sentences.</p><p><strong>Regularization.</strong> Dropout (0.1 for the base model) is applied to every sub-layer’s output before the residual add. <strong>Label smoothing</strong> (ε_ls = 0.1) spreads a little probability across the vocabulary instead of training toward a one-hot target, so the model doesn’t become overconfident. The paper is honest about the trade-off: it “hurts perplexity… but improves accuracy and BLEU score.”</p><p><strong>Decoding.</strong> The model only gives next-token probabilities; a sentence has to be <em>searched</em> for. They use <strong>beam search</strong>, a heuristic search that keeps only the most promising partial translations at each step (beam size 4). A <strong>length penalty</strong> (α = 0.6) offsets the bias toward short outputs, since every extra token multiplies in another probability below 1. Beam size isn’t learned. It’s a hyperparameter that controls how much of the search space you explore.</p><p><strong>Hardware.</strong> One machine with 8 NVIDIA P100 GPUs. The base model trained for 100,000 steps in about 12 hours, and the big model for 300,000 steps in 3.5 days.</p><h3>What it achieved</h3><p>On English→German, the big Transformer scored <strong>28.4 BLEU</strong>, more than 2 BLEU above the previous best, ensembles included. On English→French it reached <strong>41.8 BLEU</strong> as a single model, at less than a quarter of the training cost of the previous state of the art. Even the base model beat every previously published model and ensemble on English→German. The training cost was about 3.3 × 10¹⁸ FLOPs, a fraction of what the competing models used.</p><p>It also generalized beyond translation. A 4-layer Transformer applied to English constituency parsing, with little task-specific tuning, beat nearly all previously reported models.</p><h3>Through my lens: the patterns this paper set in motion</h3><p>Reading my notes back with eight years of hindsight, what stands out isn’t one equation. It’s a handful of patterns that start in this paper and keep showing up in every paper after it.</p><h3>1. Build for the machine</h3><p>Almost every key choice here is a bet on hardware. Dot-product attention beat additive attention because it runs on fast matrix-multiplication code. Recurrence went because GPUs want independent work. Even the mask exists so that a step-by-step generation process can be <em>trained</em> all at once. The idea that won wasn’t the most expressive one; it was the one that fit the machine.</p><p>That pattern didn’t stop in 2017. FlashAttention, later in this series, makes attention faster without changing the math at all, just by changing how the computation moves through GPU memory.</p><h3>2. Scale up, and keep regularizing</h3><p>My Table 3 summary reads like a training recipe. More layers and wider layers help. Removing dropout hurts. Too few heads hurts, and so do too many. The big model wins on both counts: lowest perplexity, highest BLEU.</p><p>In 2017 that was a hyperparameter table. In hindsight, it’s the scaling story in miniature, the one GPT-2, GPT-3 and Chinchilla tell later in this series at sizes this paper never imagined.</p><h3>3. One block, many worlds</h3><p>The Transformer is one layer, stacked. Nothing in it is specific to translation, and the paper’s own conclusion says the authors planned to apply it to images, audio and video.</p><p>Then people started pulling it apart. <strong>BERT</strong> kept only the encoder and trained it to predict masked-out words using context from both sides. The <strong>GPT</strong> line kept only the masked decoder, the p(xₜ | x₍&lt;ₜ₎) machine from my last post, and just kept predicting the next word. The <strong>Vision Transformer</strong> cut images into patches and fed them to a standard Transformer as if they were words, with as few changes as possible. A block designed for German→English became the default building block for almost everything.</p><h3>4. The score is a system, not just a model</h3><p>Label smoothing made the model fit its training objective <em>worse</em> and translate <em>better</em>. Beam width and length penalty, knobs that don’t appear anywhere in Figure 1, moved the BLEU score. So did averaging the last checkpoints.</p><p>The lesson I took: what a model “can do” depends on how you train it and how you search its outputs, not only on its architecture. I suspect this comes back hard when the series reaches chain-of-thought and reasoning models.</p><h3>5. The hedges became the research agenda</h3><p>Every place the paper hedged turned into a field of its own. The sinusoids “may” extrapolate; later work tested that, found sinusoidal models extrapolate poorly beyond their training length, and replaced them with methods like ALiBi and RoPE. RoPE builds directly on the rotation idea above. The O(n²) cost the authors deferred to “future work” became the whole long-context problem. And their own hint that “a more sophisticated compatibility function than dot product may be beneficial” is a question I still don’t see settled.</p><h3>Back to the sentence</h3><p>Remember reading one word at a time, overwriting your memory forty times before you reached “it”?</p><p>The Transformer lets a model do what your eyes do: jump straight from “it” to “the animal.” But I don’t think the real story is “attention understands language.” Attention is the operation that lets every word look at every other word <em>using only matrix multiplies</em>. Once a model is made of matrix multiplies, it trains in 12 hours instead of weeks. And once it trains that fast, the obvious next move is to make it much bigger. Every pattern above follows from that.</p><p>The title says attention is all you need. After reading it closely, I’d put it this way: <strong>parallelism is what you needed, and attention is how you got it.</strong></p><p>Next in the series: GPT-2, which takes the right half of Figure 1, throws away the encoder, and asks what happens when you just keep predicting the next word.</p><h3>References</h3><ol><li>Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., &amp; Polosukhin, I. (2017). <em>Attention Is All You Need.</em> NeurIPS 2017. <a href="https://arxiv.org/abs/1706.03762">arXiv:1706.03762</a></li><li>Devlin, J., Chang, M.-W., Lee, K., &amp; Toutanova, K. (2018). <em>BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.</em> <a href="https://arxiv.org/abs/1810.04805">arXiv:1810.04805</a></li><li>Dosovitskiy, A., et al. (2021). <em>An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale.</em> ICLR 2021. <a href="https://arxiv.org/abs/2010.11929">arXiv:2010.11929</a></li><li>Press, O., Smith, N. A., &amp; Lewis, M. (2022). <em>Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation.</em> ICLR 2022. <a href="https://arxiv.org/abs/2108.12409">arXiv:2108.12409</a></li><li>Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., &amp; Liu, Y. (2021). <em>RoFormer: Enhanced Transformer with Rotary Position Embedding.</em> <a href="https://arxiv.org/abs/2104.09864">arXiv:2104.09864</a></li><li>Dao, T., Fu, D. Y., Ermon, S., Rudra, A., &amp; Ré, C. (2022). <em>FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness.</em> <a href="https://arxiv.org/abs/2205.14135">arXiv:2205.14135</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=671e6243206b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Machine That Finishes Your Thoughts: P(xₜ | x<ₜ)]]></title>
            <link>https://medium.com/@hiddenlayerNx/the-machine-that-finishes-your-thoughts-p-x%E2%82%9C-x-%E2%82%9C-c7b0a71bec7d?source=rss-0cb3fd345501------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7b0a71bec7d</guid>
            <category><![CDATA[cognitive-science]]></category>
            <category><![CDATA[ai-philosophy]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-research]]></category>
            <dc:creator><![CDATA[Hidden Layer]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 06:32:20 GMT</pubDate>
            <atom:updated>2026-04-28T06:48:43.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRUWTkFhmsF361xSZ57Owg.png" /></figure><p>People like to believe something magical happened with Large Language Models. As if intelligence quietly emerged somewhere between more GPUs and larger datasets. It didn’t. What actually happened is simpler — and harder to accept. We found a way to compress human language at scale, and when that compression is unpacked, it looks like reasoning.</p><p>If you’ve spent any time around these systems, you already know where the illusion begins. The Transformer architecture is doing one thing relentlessly well: modeling the probability of the next token.</p><blockquote><em>P(xₜ | x₍&lt;ₜ₎) — </em>next-token prediction.</blockquote><p>Not truth. Not understanding. Just continuation. The objective never changed — we just scaled it until outputs started feeling intentional.</p><p>I call it a copy cat. What’s being copied isn’t text — it’s structure. The model doesn’t memorize sentences; it internalizes distributions. It learns how arguments are shaped, how uncertainty is softened.</p><p>And if you’ve written enough code or papers, you start noticing something uncomfortable. Your own thinking behaves the same way. You reuse mental templates. You compress reasoning. You optimize for coherence long before you optimize for truth. The difference is not category — it is scale and speed.</p><blockquote>So what are LLMs, in practical terms?</blockquote><p>They are engines of plausible continuation over compressed human knowledge. They don’t know when they’re correct. They don’t know when they’re hallucinating. <em>They only know what fits.</em></p><p>Calling them “copycats” undersells them. Calling them “intelligent” oversells them.</p><p>They sit somewhere more precise —</p><blockquote>A system that has learned the shape of reasoning without ever participating in it.</blockquote><p>And if that feels close to how human thinking works under pressure… that’s not a coincidence.</p><blockquote>If a Human had a fraction of knowledge any LLM posses, he could have come up with million ideas. by <a href="https://medium.com/u/67f5049293c7">Naval Ravikant</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7b0a71bec7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>