<?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:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[Dimensionality Reduction: LLM's from scratch series]]></title><description><![CDATA[A multipart series that rebuilds Large Language Models from first principles — starting with the mathematical foundations (derivatives, gradients, backpropagation, optimization), then moving through the core building blocks (embeddings, attention, transformers, training objectives), and finally into practical LLM engineering (tokenization, scaling, evaluation, inference, tooling, and production concerns). The goal is to make every concept intuitive and rigorous, connecting the theory to how modern LLM systems actually work.]]></description><link>https://www.dimensionalityreduction.com/s/llms-from-scratch-series</link><image><url>https://substackcdn.com/image/fetch/$s_!hB8u!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F245f5146-493e-4ef9-bcfb-83cdb3311ca0_1024x1024.png</url><title>Dimensionality Reduction: LLM&apos;s from scratch series</title><link>https://www.dimensionalityreduction.com/s/llms-from-scratch-series</link></image><generator>Substack</generator><lastBuildDate>Sat, 20 Jun 2026 13:43:04 GMT</lastBuildDate><atom:link href="https://www.dimensionalityreduction.com/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Nuno Fonseca]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[dimensionalityreduction@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[dimensionalityreduction@substack.com]]></itunes:email><itunes:name><![CDATA[Nuno Fonseca]]></itunes:name></itunes:owner><itunes:author><![CDATA[Nuno Fonseca]]></itunes:author><googleplay:owner><![CDATA[dimensionalityreduction@substack.com]]></googleplay:owner><googleplay:email><![CDATA[dimensionalityreduction@substack.com]]></googleplay:email><googleplay:author><![CDATA[Nuno Fonseca]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[Large Language Models from scratch - Part 2]]></title><description><![CDATA[The Transformer, or how a single architecture changed everything.]]></description><link>https://www.dimensionalityreduction.com/p/large-language-models-from-scratch-dfe</link><guid isPermaLink="false">https://www.dimensionalityreduction.com/p/large-language-models-from-scratch-dfe</guid><dc:creator><![CDATA[Nuno Fonseca]]></dc:creator><pubDate>Mon, 08 Jun 2026 00:22:07 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!hKOB!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!hKOB!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!hKOB!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 424w, https://substackcdn.com/image/fetch/$s_!hKOB!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 848w, https://substackcdn.com/image/fetch/$s_!hKOB!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 1272w, https://substackcdn.com/image/fetch/$s_!hKOB!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!hKOB!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png" width="1456" height="971" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:971,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2308123,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!hKOB!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 424w, https://substackcdn.com/image/fetch/$s_!hKOB!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 848w, https://substackcdn.com/image/fetch/$s_!hKOB!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 1272w, https://substackcdn.com/image/fetch/$s_!hKOB!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47a08aa6-8e6e-4d41-9ad0-38862d7b26df_1536x1024.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In Part 1 we built a neural network from the ground up. We saw how neurons perform linear calculations, how activation functions introduce non-linearity, how the forward pass produces a prediction, and how backpropagation and gradient descent iteratively adjust every weight in the network to minimize the loss. We trained a small network to predict whether a student would pass or fail an exam based on study hours and class attendance. The math was simple. The principles were clear.</p><p>Now it&#8217;s time to go deeper. Much deeper.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.dimensionalityreduction.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Dimensionality Reduction! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p>What we built in Part 1 has a name. A network where every neuron in one layer is connected to every neuron in the next layer, where information flows strictly in one direction from input to output, with no loops and no memory &#8212; that&#8217;s called a <strong>Multi-Layer Perceptron</strong>, or <strong>MLP</strong>. The name traces back to Frank Rosenblatt&#8217;s <strong>Perceptron</strong> from 1958, which was a single artificial neuron that could learn to classify inputs into two categories. A single perceptron is just one neuron: it takes inputs, multiplies them by weights, adds a bias, applies an activation function, and produces an output. Stack multiple perceptrons in layers &#8212; an input layer, one or more hidden layers, an output layer &#8212; connect every neuron to every neuron in the adjacent layer, and you get a <em>multi-layer</em> perceptron. You&#8217;ll also encounter the terms &#8220;fully connected&#8221; or &#8220;dense&#8221; network, which mean the same thing.</p><p>MLPs are remarkably powerful in a theoretical sense. There&#8217;s a result called the <strong>Universal Approximation Theorem</strong> that says an MLP with a single hidden layer containing enough neurons can approximate <em>any</em> continuous function to arbitrary precision. In principle, given enough neurons and enough data, an MLP can learn anything.</p><p>But in practice, MLPs have a fundamental structural limitation: they take a <strong>fixed-size input</strong> and produce a <strong>fixed-size output</strong>, and they have absolutely no concept of <strong>order</strong>. When our student-exam network received (study_hours, attendance) as input, it didn&#8217;t matter which feature was &#8220;first&#8221; or &#8220;second&#8221; &#8212; those are just positions in a vector. There&#8217;s no temporal relationship, no sequence, no notion of &#8220;this came before that.&#8221;</p><p>This might seem like a minor issue, but it&#8217;s actually a devastating one when it comes to language. Consider two sentences:</p><p><em>&#8220;The dog bit the man&#8221;</em> and <em>&#8220;The man bit the dog&#8221;</em></p><p>Same words. Completely different meanings. The meaning lives in the <strong>order</strong>. An MLP that receives these words as a bag of features &#8212; ignoring position &#8212; would see them as identical. And even if we encoded position somehow, we&#8217;d face another problem: sentences have variable length. &#8220;Hi&#8221; is one token. &#8220;The quick brown fox jumps over the lazy dog&#8221; is nine. An MLP requires a fixed input dimension set at design time. Language simply doesn&#8217;t work that way.</p><p>This is the crack that opens the door to everything that follows.</p><h2>I. The Road to the Transformer</h2><p>The history of neural networks applied to language is essentially the history of trying to solve the sequence problem: how do you build a network that can process inputs of variable length, where the order of elements matters, and where elements far apart in the sequence can influence each other&#8217;s meaning?</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!bSec!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!bSec!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 424w, https://substackcdn.com/image/fetch/$s_!bSec!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 848w, https://substackcdn.com/image/fetch/$s_!bSec!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 1272w, https://substackcdn.com/image/fetch/$s_!bSec!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!bSec!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png" width="1280" height="200" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/ee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:200,&quot;width&quot;:1280,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:32394,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!bSec!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 424w, https://substackcdn.com/image/fetch/$s_!bSec!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 848w, https://substackcdn.com/image/fetch/$s_!bSec!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 1272w, https://substackcdn.com/image/fetch/$s_!bSec!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fee861eaf-7ae3-4d74-8456-48f093ac73cb_1280x200.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><h3>Recurrent Neural Networks (RNNs)</h3><p>The first serious attempt was the <strong>Recurrent Neural Network</strong>. The idea, dating back to the 1980s, was elegant: give the network a form of memory. Instead of processing the entire input at once, an RNN processes it <strong>one element at a time</strong>, maintaining a <strong>hidden state</strong> that acts as a rolling summary of everything it has seen so far.</p><p>At each time step *t*, the RNN takes two inputs: the current element xtx_t xt&#8203; (say, a word) and the previous hidden state ht&#8722;1h_{t-1} ht&#8722;1&#8203; (the memory of everything before). It combines them to produce a new hidden state:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{h}_t = \\alpha\\!\\left(W_h \\mathbf{h}_{t-1} + W_x \\mathbf{x}_t + b\\right)&quot;,&quot;id&quot;:&quot;OTSPOMYDZL&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where Wh&#8203; and Wx&#8203; are weight matrices and &#945; is an activation function (typically tanh). The hidden state <strong>h</strong>t&#8203; is then both the output for this step and the memory carried forward to the next step.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!IT6h!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!IT6h!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 424w, https://substackcdn.com/image/fetch/$s_!IT6h!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 848w, https://substackcdn.com/image/fetch/$s_!IT6h!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 1272w, https://substackcdn.com/image/fetch/$s_!IT6h!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!IT6h!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png" width="900" height="340" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:340,&quot;width&quot;:900,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:25011,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!IT6h!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 424w, https://substackcdn.com/image/fetch/$s_!IT6h!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 848w, https://substackcdn.com/image/fetch/$s_!IT6h!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 1272w, https://substackcdn.com/image/fetch/$s_!IT6h!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F330f3b23-1113-4f6b-a191-3d736a0f82d6_900x340.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>This is clever. The network can handle sequences of any length because it processes them step by step. Word order is preserved because the hidden state accumulates information in the order it arrives. And in theory, information from the very first word can influence the processing of the very last word, because it&#8217;s encoded (however faintly) in the hidden state that gets passed forward at every step.</p><p>In practice, though, there&#8217;s a fatal problem: the <strong>vanishing gradient</strong>.</p><p>Remember how backpropagation works. We compute the loss at the output, then trace the chain of derivatives backward through the network to figure out how each weight contributed to the error. In an RNN, the chain goes backward through *time* &#8212; from the last word, through the second-to-last, through the one before that, all the way back to the first word. At each time step, the gradient gets multiplied by the weight matrix Wh&#8203;. Here&#8217;s the problem: when you repeatedly multiply by the same matrix, the result tends to either shrink toward zero or explode toward infinity &#8212; depending on whether the matrix, loosely speaking, &#8220;contracts&#8221; or &#8220;expands&#8221; the vectors it&#8217;s applied to. (There&#8217;s a precise way to characterize this using a concept called *eigenvalues*, which we&#8217;ll explore properly later when we discuss residual connections.) In most practical cases, Wh&#8203; is slightly contractive, so the gradient shrinks exponentially with each step. By the time it reaches words 20, 50, or 100 steps back, the gradient is effectively zero. The network can&#8217;t learn long-range dependencies because the error signal vanishes before it reaches the weights that need updating.</p><p>There&#8217;s also the opposite problem: if the eigenvalues are greater than 1, the gradients <strong>explode</strong>, growing exponentially and causing numerical instability. Gradient clipping can mitigate this, but the fundamental issue remains: vanilla RNNs struggle with sequences longer than about 10-20 elements.</p><h3>LSTMs and GRUs</h3><p>In 1997, Sepp Hochreiter and J&#252;rgen Schmidhuber proposed the <strong>Long Short-Term Memory</strong> (LSTM) network, specifically designed to address the vanishing gradient problem. The key innovation was the introduction of <strong>gating mechanisms</strong> &#8212; learned switches that control what information to keep, what to forget, and what to output.</p><p>An LSTM cell maintains two kinds of state: a <strong>hidden state</strong> hth_t ht&#8203; (like a regular RNN) and a <strong>cell state</strong> CtC_t Ct&#8203;, which acts as a long-term memory highway. The cell state runs through time with minimal interference &#8212; information can flow along it unchanged unless a gate explicitly decides to modify it. This is the crucial insight: by providing a path where gradients can flow without being multiplied by weight matrices at every step, LSTMs allow error signals to propagate much further back in time.</p><p>The three gates are:</p><ul><li><p><strong>Forget gate</strong>: decides what information from the previous cell state to discard</p></li><li><p><strong>Input gate</strong>: decides what new information to write into the cell state</p></li><li><p><strong>Output gate</strong>: decides what part of the cell state to expose as the hidden state</p></li></ul><p>The <strong>GRU</strong> (Gated Recurrent Unit), proposed in 2014 by Kyunghyun Cho, simplified the LSTM by combining the forget and input gates into a single &#8220;update gate&#8221; and merging the cell state and hidden state. It often performs comparably to LSTMs with fewer parameters.</p><p>Both LSTMs and GRUs dramatically improved the ability to model longer sequences, and they dominated NLP for years. But they still share a fundamental limitation inherited from the RNN paradigm: they process sequences <strong>one step at a time</strong>. Each hidden state depends on the previous one, creating a strict sequential dependency. This means:</p><ol><li><p><strong>No parallelism during training</strong>: you must compute h1h_1 h1&#8203; before h2h_2 h2&#8203;, h2h_2 h2&#8203; before h3h_3 h3&#8203;, and so on. On modern GPUs, which are massively parallel processors, this sequential bottleneck is extremely expensive.</p></li><li><p><strong>The bottleneck problem persists</strong>: even with gates, there&#8217;s a practical limit to how much information can be compressed into a fixed-size hidden state vector. For very long sequences, early information still degrades.</p></li></ol><h3>Seq2Seq and the Encoder-Decoder Paradigm</h3><p>A major milestone came with the <strong>sequence-to-sequence</strong> (Seq2Seq) model, popularized around 2014 for machine translation. The idea was to chain two RNNs (typically LSTMs) together:</p><ul><li><p>An <strong>encoder</strong> RNN reads the entire input sequence (say, a French sentence) one token at a time and compresses it into a single hidden state vector &#8212; the &#8220;context vector.&#8221;</p></li><li><p>A <strong>decoder</strong> RNN takes that context vector and generates the output sequence (the English translation) one token at a time.</p></li></ul><p>This was a breakthrough for translation and other sequence-to-sequence tasks, but it had a glaring weakness: the entire meaning of the input sequence, no matter how long, had to be squeezed into a single fixed-size vector. That context vector was a bottleneck. For short sentences it worked reasonably well. For longer sentences, critical information inevitably got lost.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!nCXR!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!nCXR!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 424w, https://substackcdn.com/image/fetch/$s_!nCXR!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 848w, https://substackcdn.com/image/fetch/$s_!nCXR!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 1272w, https://substackcdn.com/image/fetch/$s_!nCXR!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!nCXR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png" width="900" height="280" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:280,&quot;width&quot;:900,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:20627,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!nCXR!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 424w, https://substackcdn.com/image/fetch/$s_!nCXR!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 848w, https://substackcdn.com/image/fetch/$s_!nCXR!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 1272w, https://substackcdn.com/image/fetch/$s_!nCXR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3a89c6bf-c5aa-4e60-928e-0948d1abec96_900x280.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3>The Birth of Attention (Bahdanau, 2014)</h3><p>Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio proposed a solution in their landmark 2014 paper: instead of forcing the decoder to rely on a single compressed context vector, <strong>let the decoder look back at all the encoder&#8217;s hidden states and decide which ones are most relevant at each decoding step</strong>.</p><p>This is the <strong>attention mechanism</strong> in its original form. At each step of decoding, the model computes a set of &#8220;attention weights&#8221; &#8212; one for each position in the input sequence &#8212; that say &#8220;how much should I focus on this part of the input right now?&#8221; These weights are used to create a weighted combination of all encoder hidden states, producing a custom context vector for each decoding step.</p><p>The intuition is natural. When a human translator is generating the English word &#8220;cat,&#8221; they focus on the French word &#8220;chat,&#8221; not on the article &#8220;le&#8221; or the period at the end of the sentence. The model learns to do the same thing: focus on what&#8217;s relevant, ignore what&#8217;s not, and the notion of &#8220;relevant&#8221; changes with each output token.</p><p>Bahdanau attention transformed the field. Translation quality improved significantly, especially for long sentences. But perhaps more importantly, it introduced an idea that would prove far more powerful than anyone initially realized: <strong>the notion that a network can learn to dynamically route information based on content, rather than relying on fixed connectivity patterns</strong>.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!2T6L!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!2T6L!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 424w, https://substackcdn.com/image/fetch/$s_!2T6L!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 848w, https://substackcdn.com/image/fetch/$s_!2T6L!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 1272w, https://substackcdn.com/image/fetch/$s_!2T6L!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!2T6L!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png" width="900" height="340" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/e4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:340,&quot;width&quot;:900,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:50588,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!2T6L!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 424w, https://substackcdn.com/image/fetch/$s_!2T6L!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 848w, https://substackcdn.com/image/fetch/$s_!2T6L!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 1272w, https://substackcdn.com/image/fetch/$s_!2T6L!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4975799-2b4d-4e2b-abdf-7a2993cddd26_900x340.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3>&#8220;Attention Is All You Need&#8221; (Vaswani et 2017)</h3><p>By 2017, a group of researchers at Google &#8212; Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan Gomez, &#321;ukasz Kaiser, and Illia Polosukhin &#8212; asked a radical question: if the attention mechanism is doing the heavy lifting, why keep the recurrent structure at all?</p><p>Their paper, &#8220;Attention Is All You Need,&#8221; proposed the <strong>Transformer</strong>: an architecture that dispenses entirely with recurrence and convolutions, relying solely on attention mechanisms and feedforward networks. The results were striking &#8212; not only did the Transformer match or exceed the performance of the best RNN-based models, it was dramatically faster to train because it could process all positions in a sequence <strong>in parallel</strong>.</p><p>This wasn&#8217;t just an incremental improvement. It was a paradigm shift. Within a few years, virtually every state-of-the-art language model would be based on the Transformer architecture. BERT, GPT, T5, LLaMA, Claude &#8212; all Transformers. The architecture proved so versatile that it spread beyond language into vision (ViT), protein structure prediction (AlphaFold 2), music generation, robotics, and more.</p><p>Let&#8217;s now understand it completely.</p><h2>II. Embeddings</h2><p>Before we can walk through the Transformer, we need to understand one of the most important concepts in all of deep learning: <strong>embeddings</strong>. We touched on the idea that neural networks work with numbers, not words. But the question of <em>how</em> words become numbers, and what those numbers <em>mean</em>, is deeper and more beautiful than it first appears.</p><h3>The Problem: Words Are Discrete</h3><p>A neural network performs multiplications and additions. It works with continuous numbers &#8212; floating point values that can be added, multiplied, and differentiated. But language is <strong>discrete</strong>. The word &#8220;cat&#8221; isn&#8217;t a number. It&#8217;s a symbol from a finite vocabulary. You can&#8217;t meaningfully multiply &#8220;cat&#8221; by 0.7 or compute the gradient of &#8220;cat&#8221; with respect to anything.</p><p>The most naive approach to converting words into numbers is <strong>one-hot encoding</strong>. If your vocabulary has 50,000 words, you represent each word as a vector of length 50,000 where exactly one position is 1 and all others are 0. The word &#8220;cat&#8221; might be:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;[0, 0, 0, \\ldots, 1, \\ldots, 0, 0, 0]&quot;,&quot;id&quot;:&quot;FLCAHLIMFB&quot;}" data-component-name="LatexBlockToDOM"></div><p>with the 1 at position 3,742 (wherever &#8220;cat&#8221; falls in the vocabulary).</p><p>This technically works, but it has serious problems:</p><ol><li><p><strong>Dimensionality</strong>: each vector has 50,000 dimensions. For a vocabulary of 100,000 tokens, each word is a 100,000-dimensional vector. This is wasteful and computationally expensive.</p></li><li><p><strong>Sparsity</strong>: each vector is 99.998% zeros. Almost all the information is &#8220;this is not the word.&#8221;</p></li><li><p><strong>No notion of similarity</strong>: in one-hot space, &#8220;cat&#8221; is exactly as far from &#8220;kitten&#8221; as it is from &#8220;democracy&#8221; or &#8220;earthquake.&#8221; Every word is equidistant from every other word. The representation captures no semantic relationships whatsoever.</p></li></ol><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!yL3I!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!yL3I!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 424w, https://substackcdn.com/image/fetch/$s_!yL3I!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 848w, https://substackcdn.com/image/fetch/$s_!yL3I!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 1272w, https://substackcdn.com/image/fetch/$s_!yL3I!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!yL3I!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png" width="860" height="300" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/e70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:300,&quot;width&quot;:860,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:59528,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!yL3I!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 424w, https://substackcdn.com/image/fetch/$s_!yL3I!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 848w, https://substackcdn.com/image/fetch/$s_!yL3I!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 1272w, https://substackcdn.com/image/fetch/$s_!yL3I!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe70afc6e-6a35-45ff-bdd4-1bfe373c8a5c_860x300.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>We need something better: a way to represent words as dense, low-dimensional vectors where <strong>similar words are near each other</strong> and <strong>dissimilar words are far apart</strong>.</p><h3>The Embedding Matrix</h3><p>The solution is an <strong>embedding matrix</strong>, and it&#8217;s much simpler than it sounds. It&#8217;s a matrix&#8203; with shape <strong>(vocabulary_size &#215; d_model)</strong>, where d_model is the dimensionality of the embedding space (a hyperparameter we choose &#8212; common values are 768, 1024, 4096, or higher).</p><p>Each row of this matrix corresponds to one token in the vocabulary. Row 0 is the vector for token 0, row 3,742 is the vector for &#8220;cat,&#8221; and so on. To &#8220;embed&#8221; a word, you simply look up its row. That&#8217;s it. The embedding operation is a table lookup:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!S0Sm!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!S0Sm!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 424w, https://substackcdn.com/image/fetch/$s_!S0Sm!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 848w, https://substackcdn.com/image/fetch/$s_!S0Sm!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 1272w, https://substackcdn.com/image/fetch/$s_!S0Sm!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!S0Sm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png" width="820" height="380" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f9b69a31-8286-477c-a084-2c93c0c44829_820x380.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:380,&quot;width&quot;:820,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:56929,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!S0Sm!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 424w, https://substackcdn.com/image/fetch/$s_!S0Sm!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 848w, https://substackcdn.com/image/fetch/$s_!S0Sm!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 1272w, https://substackcdn.com/image/fetch/$s_!S0Sm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9b69a31-8286-477c-a084-2c93c0c44829_820x380.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{e}_i = W_E[i]&quot;,&quot;id&quot;:&quot;LLPQMRVAOK&quot;}" data-component-name="LatexBlockToDOM"></div><p>Go to row ii i, pull out the vector. No computation &#8212; just a memory access, like reading <code>array[3]</code>.</p><p>You might wonder: how does a discrete index lookup &#8212; something that feels more like a database query than a mathematical operation &#8212; fit into a framework built entirely on differentiable matrix operations? Gradients need smooth, continuous functions, not integer indexing. The answer is that you *could* express the same lookup as a matrix multiplication using a one-hot vector. If x is a one-hot vector (all zeros except a 1 at position i, then:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_E^T \\mathbf{x} = W_E[i]&quot;,&quot;id&quot;:&quot;HTPFHEUBJR&quot;}" data-component-name="LatexBlockToDOM"></div><p>The matrix multiplication with a one-hot vector simply selects row i. But nobody actually constructs the one-hot vector or performs this multiplication &#8212; it would be exactly the wasteful, sparse, high-dimensional operation we just argued against. The one-hot formulation exists purely to prove that the lookup is mathematically equivalent to a differentiable operation, which means gradients can flow through it during backpropagation. In practice, the embedding is implemented as a direct index: give me row ii i of the matrix. PyTorch&#8217;s <code>nn.Embedding</code> does exactly this.</p><p>So &#8220;cat&#8221; goes from a sparse 50,000-dimensional vector to a dense vector of, say, 768 dimensions. Something like:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{e}_{\\text{cat}} = [0.23, -0.87, 0.41, 0.05, \\ldots, -0.33, 0.71]&quot;,&quot;id&quot;:&quot;SLQBTWYCIG&quot;}" data-component-name="LatexBlockToDOM"></div><p>These 768 numbers <em>are</em> the model&#8217;s understanding of the word &#8220;cat.&#8221; But here&#8217;s the crucial question: where do these numbers come from?</p><h3>Where Does the Embedding Matrix Live in the Model?</h3><p>Before answering that, let&#8217;s place this matrix in the overall architecture. In a decoder-only LLM, the embedding matrix&#8203; sits right at the <strong>input</strong> of the network &#8212; the first learned component a token encounters after tokenization. The input pipeline is:</p><ol><li><p>Raw text &#8594; tokenizer &#8594; sequence of integer token IDs</p></li><li><p>Each token ID indexes into the embedding matrix to retrieve its embedding vector</p></li><li><p>Positional information is added (sinusoidal encoding, or RoPE applied inside attention)</p></li><li><p>The resulting vectors enter the first Transformer block</p></li></ol><p>That&#8217;s the input side. But there&#8217;s a symmetric situation at the output. After all N Transformer blocks, the final vector at each position passes through an <strong>output projection matrix</strong> <em>Whead&#8203;</em> (also called the &#8220;unembedding&#8221; or &#8220;LM head&#8221;) that maps from <strong>dmodel</strong>&#8203; back to vocabulary space, producing one raw score per token in the vocabulary. These raw scores are called <strong>logits</strong> &#8212; a term borrowed from statistics that simply means "unnormalized scores before they're converted to probabilities." A logit can be any real number: positive, negative, or zero. By itself, a logit of 2.7 doesn't mean much &#8212; it only becomes meaningful once we compare it against all the other logits. That comparison happens via the <strong>softmax</strong> function, which converts the full vector of logits into a probability distribution (all values between 0 and 1, summing to 1). The token with the highest logit gets the highest probability.</p><p>Here&#8217;s the interesting part: in many modern LLMs, the output projection <em>Whead</em>&#8203; is the <strong>same matrix</strong> as the input embedding matrix&#8203; &#8212; specifically, its transpose. This technique is called <strong>weight tying</strong> (or &#8220;tied embeddings&#8221;). When weight tying is used, the embedding matrix effectively lives at <strong>both ends</strong> of the network: it turns token IDs into vectors at the input, and it measures how closely the network&#8217;s final output vector matches each token&#8217;s embedding at the output. The same geometric structure serves both translation directions.</p><p>The intuition for why this works geometrically: if the embedding of &#8220;cat&#8221; points in a certain direction in dmodel&#8203;-dimensional space, then a final hidden vector that also points in that direction should have a high score for the token &#8220;cat.&#8221; That&#8217;s exactly what the transposed embedding matrix computes &#8212; the dot product between the output vector and each token&#8217;s embedding. So tying the matrices creates a consistent round-trip: the same geometry that converts tokens to vectors at the input is the geometry used to pick which token a vector is closest to at the output.</p><p>Weight tying is a design choice. It&#8217;s used in GPT-2 and many smaller models because it roughly halves the parameters of the embedding/output layer &#8212; which for large vocabularies can save hundreds of millions of parameters. Some larger models keep the matrices separate to give the output head more flexibility. Either way, the embedding matrix itself is a significant chunk of an LLM&#8217;s parameters: for a vocabulary of 128,000 tokens and dmodel&#8203;=4096, the embedding matrix alone contains over 524 million parameters.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!WJna!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!WJna!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 424w, https://substackcdn.com/image/fetch/$s_!WJna!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 848w, https://substackcdn.com/image/fetch/$s_!WJna!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 1272w, https://substackcdn.com/image/fetch/$s_!WJna!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!WJna!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png" width="600" height="520" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/dd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:520,&quot;width&quot;:600,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:55116,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!WJna!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 424w, https://substackcdn.com/image/fetch/$s_!WJna!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 848w, https://substackcdn.com/image/fetch/$s_!WJna!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 1272w, https://substackcdn.com/image/fetch/$s_!WJna!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd95121e-b3ba-4aa1-a49c-d98df41b71c4_600x520.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>With the architectural placement clear, let&#8217;s return to the question of how these numbers come about.</p><h3>How Embeddings Are Learned</h3><p>The embedding matrix&#8203; is initialized with <strong>random values</strong>. At the very beginning of training, the vector for &#8220;cat&#8221; is random noise &#8212; it encodes no meaning whatsoever. It&#8217;s no closer to &#8220;kitten&#8221; than to &#8220;democracy.&#8221;</p><p>But the embedding matrix is a <strong>parameter of the network</strong>, just like every weight matrix we saw in Part 1. It participates in the forward pass: the token&#8217;s embedding vector flows through the network, contributes to a prediction, and the prediction is compared against reality via the loss function. Then backpropagation computes the gradient of the loss with respect to every parameter &#8212; including the entries of the embedding matrix&#8203;.</p><p>Let&#8217;s trace this concretely. Suppose the model is processing the sentence &#8220;The cat sat on the ___&#8221; and needs to predict the next word. It embeds each token, processes them through the network, and produces a probability distribution over the vocabulary. Let&#8217;s say it predicts &#8220;moon&#8221; with 30% probability and &#8220;mat&#8221; with 2% probability. But the true next word is &#8220;mat.&#8221;</p><p>The cross-entropy loss is high: the model was confident in the wrong answer. Backpropagation now computes</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{e}_{\\text{cat}}}&quot;,&quot;id&quot;:&quot;WIVYOWPXMR&quot;}" data-component-name="LatexBlockToDOM"></div><p>&#8212; how should the embedding vector for &#8220;cat&#8221; change to make this prediction less wrong? And :</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{e}_{\\text{sat}}}&quot;,&quot;id&quot;:&quot;UAVBCCOGIW&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>&#8212; and so on for every token in the input. Gradient descent then nudges each embedding vector in the direction that reduces the loss.</p><p>Over billions of such updates across billions of sentences:</p><ul><li><p>&#8220;cat&#8221; and &#8220;kitten&#8221; keep appearing in similar contexts (&#8221;The ___ purred,&#8221; &#8220;She petted the ___,&#8221; &#8220;The ___ chased the mouse&#8221;). Each time, the gradients push their embedding vectors in similar directions. Gradually, they drift closer together in the embedding space.</p></li><li><p>&#8220;cat&#8221; and &#8220;earthquake&#8221; almost never appear in similar contexts. Their gradients push them in unrelated directions. They drift apart, or simply never converge.</p></li><li><p>Subtler relationships emerge too. &#8220;king&#8221; and &#8220;queen&#8221; appear in similar contexts, but with systematic differences that correlate with gender. &#8220;walked&#8221; and &#8220;walking&#8221; appear in similar contexts but with differences that correlate with tense. The embedding space develops <strong>directions</strong> that correspond to these semantic properties.</p></li></ul><p>This is worth pausing on. <strong>Nobody told the model that &#8220;king&#8221; and &#8220;queen&#8221; are related.</strong> Nobody defined &#8220;gender&#8221; as a concept. Nobody hand-crafted a taxonomy of semantic relationships. The only signal was the loss &#8212; billions of instances of &#8220;you predicted the wrong next word, here&#8217;s how wrong you were.&#8221; And from that signal alone, through the mechanics of gradient descent, the embedding matrix organized itself into a space where meaning has geometric structure.</p><h3>The Geometry of Meaning</h3><p>What does this geometric structure look like? Each embedding vector is a point in a high-dimensional space (768 dimensions, 4096 dimensions, or more). We can&#8217;t visualize these spaces directly, but we can reason about them using the tools of linear algebra.</p><p><strong>Distance and similarity</strong>: two words with similar meanings have embedding vectors that are close together. &#8220;Similarity&#8221; is typically measured by <strong>cosine similarity</strong> &#8212; the cosine of the angle between two vectors:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{cosine\\_similarity}(a,b)=\\frac{a\\cdot b}{\\lVert a\\rVert \\,\\lVert b\\rVert}&quot;,&quot;id&quot;:&quot;XSMRREALAH&quot;}" data-component-name="LatexBlockToDOM"></div><p>A value of 1 means the vectors point in exactly the same direction (maximally similar). A value of 0 means they&#8217;re orthogonal (unrelated). A value of -1 means they point in opposite directions.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!MjYW!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!MjYW!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 424w, https://substackcdn.com/image/fetch/$s_!MjYW!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 848w, https://substackcdn.com/image/fetch/$s_!MjYW!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 1272w, https://substackcdn.com/image/fetch/$s_!MjYW!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!MjYW!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png" width="750" height="500" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/cc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:500,&quot;width&quot;:750,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:61649,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!MjYW!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 424w, https://substackcdn.com/image/fetch/$s_!MjYW!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 848w, https://substackcdn.com/image/fetch/$s_!MjYW!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 1272w, https://substackcdn.com/image/fetch/$s_!MjYW!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcc85b854-42ad-4db6-91aa-968ee537c04d_750x500.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><p><strong>Linear substructures</strong>: the most famous finding from word embedding research (originally from Word2Vec, but it applies to all learned embeddings) is that semantic relationships correspond to <strong>directions</strong> in the embedding space. The classic example:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{e}_{\\text{king}} - \\mathbf{e}_{\\text{man}} + \\mathbf{e}_{\\text{woman}} \\approx \\mathbf{e}_{\\text{queen}}&quot;,&quot;id&quot;:&quot;HDRHVSLSRK&quot;}" data-component-name="LatexBlockToDOM"></div><p>What this says is that there&#8217;s a direction in the embedding space that corresponds to the concept &#8220;male &#8594; female.&#8221; If you start at &#8220;king&#8221; and move in that direction, you arrive near &#8220;queen.&#8221; If you start at &#8220;uncle&#8221; and move in the same direction, you arrive near &#8220;aunt.&#8221; This direction wasn&#8217;t programmed &#8212; it <strong>emerged</strong> from the loss landscape because the systematic substitution patterns in language (contexts where &#8220;king&#8221; appears are similar to contexts where &#8220;queen&#8221; appears, modulo gender-correlated words) created gradient pressure that organized the space this way.</p><p>Similar directions encode other relationships: verb tense (&#8221;walking&#8221; &#8722; &#8220;walked&#8221; &#8776; &#8220;swimming&#8221; &#8722; &#8220;swam&#8221;), country-capital relations (&#8221;France&#8221; &#8722; &#8220;Paris&#8221; &#8776; &#8220;Japan&#8221; &#8722; &#8220;Tokyo&#8221;), and many more. These directions can&#8217;t easily be named or isolated in a single dimension. They&#8217;re <strong>distributed across many dimensions simultaneously</strong> &#8212; a concept might be partly encoded in dimension 47, partly in dimension 203, partly in dimension 651, combined in a way that only makes sense as a direction in the full high-dimensional space.</p><h3>The Pressure of Many Directions</h3><p>There&#8217;s a powerful image that makes the richness of embeddings click, and it&#8217;s worth spelling out explicitly because it justifies why embedding vectors carry so much concentrated meaning.</p><p>During training, each token in the vocabulary appears in countless different contexts. Consider the word &#8220;bank&#8221;:</p><ul><li><p><em>&#8220;river bank&#8221;</em> &#8212; gradients push its embedding toward concepts of geography, water, land, physical edges</p></li><li><p><em>&#8220;bank account&#8221;</em> &#8212; gradients push toward finance, money, institutions, transactions</p></li><li><p><em>&#8220;blood bank&#8221;</em> &#8212; gradients push toward medical, storage, biological concepts</p></li><li><p><em>&#8220;bank of clouds&#8221;</em> &#8212; gradients push toward meteorology, collections, spatial aggregation</p></li><li><p><em>&#8220;bank the plane&#8221;</em> &#8212; gradients push toward motion, aviation, tilting</p></li><li><p><em>&#8220;bank shot&#8221;</em> &#8212; gradients push toward sports, angles, reflection</p></li><li><p>And hundreds or thousands of others</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!t9GX!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!t9GX!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 424w, https://substackcdn.com/image/fetch/$s_!t9GX!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 848w, https://substackcdn.com/image/fetch/$s_!t9GX!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 1272w, https://substackcdn.com/image/fetch/$s_!t9GX!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!t9GX!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png" width="650" height="500" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:500,&quot;width&quot;:650,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:58808,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!t9GX!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 424w, https://substackcdn.com/image/fetch/$s_!t9GX!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 848w, https://substackcdn.com/image/fetch/$s_!t9GX!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 1272w, https://substackcdn.com/image/fetch/$s_!t9GX!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd23f5c42-c970-4f24-81c5-443747a8fa0b_650x500.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Every time &#8220;bank&#8221; appears in training, backpropagation computes how *this specific vector* &#8212; the single row in the embedding matrix&#8203; indexed by the &#8220;bank&#8221; token &#8212; should change to reduce the prediction error for that context. And critically: **all these gradients flow back to the same vector**. The embedding for &#8220;bank&#8221; is updated by the finance contexts and the geography contexts and the aviation contexts and the sports contexts, all shaping the same 4096 numbers.</p><p>The vector cannot move in all these directions simultaneously at full strength. It has to find a single location in the high-dimensional space that, averaged over all the contexts in which this token appears, best serves the prediction task. This is an optimization problem with many competing objectives collapsed into one signal, and the solution the network converges on is a kind of <strong>balance</strong> &#8212; a vector that encodes a bit of every use of the word, weighted by frequency and by how much each context matters for prediction accuracy.</p><p>This is precisely where high dimensionality earns its keep. In a low-dimensional space &#8212; say 10 or 20 dimensions &#8212; these competing directional pressures would <strong>destructively interfere</strong>. Moving closer to &#8220;finance&#8221; would necessarily mean moving farther from &#8220;geography,&#8221; because there simply wouldn&#8217;t be enough independent directions to accommodate both. The vector would end up in some bland compromise that poorly serves any individual context.</p><p>In 4096 dimensions, there&#8217;s enough geometric room that &#8220;the finance direction&#8221; and &#8220;the geography direction&#8221; and &#8220;the aviation direction&#8221; can be <strong>nearly orthogonal to each other</strong>. The vector for &#8220;bank&#8221; can encode a substantial component along all of them simultaneously, because they point in different directions and don&#8217;t cancel out. The same vector can be near the finance cluster <em>and</em> near the geography cluster <em>and</em> near the aviation cluster &#8212; these are different directions in the space, and there&#8217;s room for all of them to coexist.</p><p>This is the concentrated richness of embeddings. Each vector is a dense multi-register pointer: it simultaneously encodes the word&#8217;s semantic neighbors along many different axes, because training pressure came from many different types of contexts. The embedding vector isn&#8217;t the word&#8217;s meaning in any single sense &#8212; it&#8217;s a <strong>compressed superposition</strong> of all the ways the word gets used, layered along nearly-orthogonal directions in a high-dimensional space. This is what the &#8220;richness&#8221; of a good embedding means: it carries many partial meanings at once, encoded along independent enough directions that downstream layers can pull out whichever one is relevant.</p><p>This framing also explains something that would otherwise be puzzling: <strong>why the Transformer&#8217;s contextual processing works</strong>. The raw embedding vector is an ambiguous superposition of all the word&#8217;s senses. But the Transformer&#8217;s attention layers can selectively read from specific directions. When processing &#8220;I deposited money at the bank,&#8221; the surrounding tokens (<em>money</em>, <em>deposited</em>) create an attention pattern that pulls the finance direction out of the bank vector and suppresses the geography direction. When processing &#8220;We sat on the bank of the river,&#8221; attention does the reverse. The embedding matrix stores all of it; the later layers disambiguate based on context.</p><p>By the time a vector has passed through 20, 40, or 80 Transformer blocks, it no longer represents &#8220;bank in general&#8221; &#8212; it represents &#8220;bank in this specific sentence, given the surrounding evidence.&#8221; The raw embedding was the full superposition; the network progressively collapses it toward the relevant sense. Hold this image &#8212; it explains why embeddings need to be rich, why dimensionality has to be high, and why the Transformer layers after the embedding layer are doing genuinely useful work rather than just copying information around.</p><h3>Why So Many Dimensions?</h3><p>Why 768 or 4096 dimensions? Why not 50 or 10?</p><p>Each dimension is a <strong>latent feature</strong> that the network discovered during training. You can&#8217;t point at dimension 347 and say &#8220;that&#8217;s the formality dimension.&#8221; The features are distributed, entangled, and not human-interpretable in isolation. But collectively, they need enough &#8220;room&#8221; to encode all the distinctions the model needs to make.</p><p>Think of it this way: the vocabulary might have 50,000 tokens. Each of those tokens has relationships with thousands of other tokens along dozens of semantic axes (topic, sentiment, formality, grammatical role, concreteness, temporal reference, and countless others). Compressing all of that into, say, 50 dimensions would force the model to reuse dimensions in conflicting ways &#8212; &#8220;dimension 12 encodes both formality and verb tense&#8221; &#8212; creating destructive interference. More dimensions give the model more room to represent distinct concepts along orthogonal directions without interference.</p><p>In practice, there&#8217;s a tradeoff: more dimensions mean more parameters, more computation, and more data needed to learn meaningful structure. The choice of embedding dimension is a design decision that balances model capacity against computational cost.</p><h3>Embeddings Are Not Static</h3><p>One crucial point: in modern Transformers, the embedding matrix produces the <em>initial</em> representation of each token, but that representation is then transformed by every subsequent layer of the network. After passing through 32 or 96 layers of attention and feedforward processing, the vector at position 5 is no longer just the embedding of the word that was originally at position 5. It has been enriched with contextual information from every other position in the sequence. The same word &#8220;bank&#8221; will have very different representations after processing in &#8220;river bank&#8221; versus &#8220;bank account.&#8221;</p><p>This is sometimes called <strong>contextual embeddings</strong> &#8212; the initial embedding captures the meaning of a word in isolation, but the Transformer layers progressively build a representation that captures the meaning of the word <em>in this specific context</em>. This is one of the reasons Transformer-based models dramatically outperform older approaches like Word2Vec, where each word had a single fixed embedding regardless of context.</p><h3>Why Is This Matrix Called &#8220;Embeddings&#8221;?</h3><p>Here&#8217;s a question worth pausing on, because it gets at something fundamental about how we think about these models &#8212; and it&#8217;s the same question that probably lurks in the back of your mind right now.</p><p>Think back to Part 1. Our student-exam MLP had several weight matrices &#8212; the weights connecting input to hidden layer, hidden layer to output. All of those matrices were learned through the same process: forward pass, compute loss, backpropagate, gradient descent. Mathematically, they all had identical status &#8212; just tensors of numbers being nudged by the chain rule.</p><p>The Transformer, as we&#8217;re about to see in the next section, contains many more learned matrices &#8212; it has weight matrices inside its attention mechanism, weight matrices inside the feedforward network (which is literally the same kind of MLP from Part 1), plus normalization parameters. All of them start random. All of them are shaped by the same loss. Yet we single out the embedding matrix and say its rows &#8220;mean&#8221; something. We say the vector for &#8220;cat&#8221; represents the meaning of &#8220;cat.&#8221; But we wouldn&#8217;t say the same thing about a row of one of the hidden-layer weight matrices from Part 1&#8217;s MLP. Why not?</p><p>And &#8212; to pose the sharpest version of the question &#8212; if we invented some extra matrix <em>Winvented</em>&#8203; and inserted it somewhere in the architecture, it too would get learned weights, shaped by the loss. Would its rows &#8220;mean&#8221; something? What makes the embedding matrix semantically special compared to every other learned matrix?</p><p>This is a sharp question, and the answer illuminates something important. The status of a matrix as &#8220;semantic&#8221; &#8212; as carrying interpretable per-token meaning &#8212; doesn&#8217;t come from the math of how it&#8217;s updated. Every matrix is updated the same way. It comes from <strong>where the matrix sits in the architecture</strong>, and specifically <strong>what it is connected to</strong>.</p><p>The embedding matrix has one property that nothing else in the network has: <strong>it is indexed by discrete token identity</strong>. Row 3,742 of the embedding matrix is retrieved if and only if the token &#8220;cat&#8221; appears at an input position. Across the entire training corpus &#8212; across billions of training examples &#8212; every single gradient that flows back to row 3,742 originates from a context where &#8220;cat&#8221; specifically was being processed. That row accumulates, through sheer consistent association, everything the network ever had to know about &#8220;cat&#8221; in order to predict well.</p><p>No other matrix in the network has this property. Consider the weight matrices from Part 1&#8217;s student-exam MLP. The weights connecting the input layer to hidden neuron h1 were used for <em>every</em> student that passed through the network &#8212; they weren&#8217;t specific to any particular student. They encoded a <strong>transformation</strong> (how to combine study hours and attendance into a useful hidden feature), not a <strong>concept</strong> tied to a specific input. The same principle applies to every other weight matrix in a Transformer: they&#8217;re applied uniformly to whatever input flows through them, regardless of which token happens to sit there. They encode transformations &#8212; how to reshape an arbitrary input &#8212; not concepts tied to specific vocabulary items. They operate on already-processed representations, never having a clean one-to-one correspondence with discrete symbols.</p><p>The embedding matrix is the unique place in the network where a token&#8217;s identity is preserved as a retrievable address. It&#8217;s the only matrix where &#8220;row &#8594; specific token&#8221; is a stable mapping throughout training. And because of that, it&#8217;s the only place where <strong>per-token meaning</strong> can accumulate into a persistent vector.</p><p>Now, what about the thought experiment &#8212; what if we inserted an extra matrix <em>Winvented</em>&#8203; between the embedding lookup and the first layer of the network? Would it learn meaningful representations?</p><p>It would learn something &#8212; every matrix does &#8212; but it wouldn&#8217;t be &#8220;embeddings&#8221; in the semantic sense. Here&#8217;s why: it would be applied uniformly to every input that flows through the network. It wouldn&#8217;t have per-token rows; it would be a single transformation. And mathematically, something even more telling happens: since the composition of two linear operations is itself a linear operation, such a matrix could be <strong>absorbed directly into the embedding matrix&#8203; </strong><em><strong>We</strong></em>. The &#8220;real&#8221; embedding matrix would still be the composite <em>Winvented&#8203;&#8901;We</em>, because that&#8217;s what determines the final per-token vector that enters the first layer. The inserted matrix wouldn&#8217;t represent anything new; it would just redistribute the learned mapping across two matrices instead of one. In a sense, it would disappear into the embedding.</p><p>To get a second &#8220;embedding-like&#8221; matrix with its own distinct meaning, you&#8217;d need a second place in the architecture where <strong>discrete identity is preserved</strong> &#8212; a second kind of symbol that gets looked up by a distinct integer index. This is exactly what some architectures do: BERT has separate <strong>token embeddings</strong>, <strong>position embeddings</strong>, and <strong>segment embeddings</strong>, each indexed by a different discrete identity (token ID, absolute position, segment ID). Each of these is a legitimate &#8220;embedding&#8221; in the semantic sense &#8212; the rows of each matrix accumulate meaning for their respective kind of identity. They&#8217;re all embeddings, and they&#8217;re the only matrices in the network that qualify.</p><p>So what makes a matrix an embedding isn&#8217;t the fact that it&#8217;s learned &#8212; every matrix is learned. It&#8217;s the <strong>architectural privilege of being directly indexed by discrete identity</strong>. That&#8217;s the sole bridge between symbolic inputs and continuous computation, and the rows at that bridge are where symbolic meaning is anchored in the vector space. Every other matrix operates on what has already crossed the bridge.</p><p>This framing will become increasingly useful as we enter the next section and meet the Transformer&#8217;s many internal weight matrices. The Transformer contains dozens of learned matrices with names like K, Q, V&#8203; &#8212; we&#8217;ll define each one carefully when we get there. But here&#8217;s the punchline you can take with you: they are <strong>all</strong> weight matrices in exactly the same sense as the weights in Part 1&#8217;s student-exam MLP. They start random. They&#8217;re updated by backpropagation. The loss is their only teacher. None of them are &#8220;embeddings&#8221; &#8212; they don&#8217;t have the architectural privilege of being indexed by discrete identity. What makes the Transformer powerful isn&#8217;t that it introduces some new type of parameter with new mathematical properties; it&#8217;s that it arranges ordinary weight matrices into a structure where useful computations are reachable via gradient descent.</p><p>Put another way: if you&#8217;re ever inclined to feel that embeddings are a fundamentally different kind of object from &#8220;just weights,&#8221; resist that intuition. They <em>are</em> just weights. What&#8217;s different is their position in the graph. And once you internalize that, the whole Transformer becomes conceptually simpler: it&#8217;s one big grid of learnable parameters, with a few of them (the embeddings) given the architectural privilege of being directly addressed by discrete tokens, and all the rest shaped by the loss into whatever useful transformations the architecture makes reachable.</p><h2>III. The Transformer Architecture</h2><p>We&#8217;re now ready to dissect the Transformer itself. We&#8217;ll go through every component of the architecture described in &#8220;Attention Is All You Need,&#8221; understanding not just <em>what</em> each piece does but <em>why</em> it&#8217;s there.</p><h3>Tokenization</h3><p>Before anything enters the model, raw text must be converted into a sequence of integers. This process is called <strong>tokenization</strong>, and the choices made here have surprisingly deep consequences.</p><p>The simplest approach would be to treat each word as a token. But this creates problems: the vocabulary would need to contain every word the model might ever encounter, including rare words, technical terms, names, and words from hundreds of languages. A word-level vocabulary would either be enormous (millions of entries) or would constantly encounter words it doesn&#8217;t recognize.</p><p>The opposite extreme &#8212; treating each character as a token &#8212; gives a tiny vocabulary (a few hundred entries) and never encounters unknown inputs, but sequences become very long and the model has to learn to assemble meaning from individual characters, which is inefficient.</p><p>Modern LLMs use a middle ground: <strong>subword tokenization</strong>. The two most common algorithms are <strong>Byte-Pair Encoding (BPE)</strong> and <strong>SentencePiece</strong>. The basic idea is:</p><ol><li><p>Start with individual characters (or bytes) as the initial vocabulary.</p></li><li><p>Count which pairs of adjacent tokens appear most frequently in the training data.</p></li><li><p>Merge the most frequent pair into a single new token.</p></li><li><p>Repeat until the vocabulary reaches a target size (typically 32,000 to 128,000 tokens).</p></li></ol><p>The result is a vocabulary where common words like &#8220;the&#8221; or &#8220;and&#8221; are single tokens, while rarer words are split into meaningful subunits. &#8220;Unhappiness&#8221; might tokenize as [&#8221;un&#8221;, &#8220;happiness&#8221;], and a very rare word like &#8220;defenestration&#8221; might become [&#8221;de&#8221;, &#8220;fen&#8221;, &#8220;est&#8221;, &#8220;ration&#8221;]. This gives the best of both worlds: a manageable vocabulary size, no unknown-word problem, and subword units that often correspond to meaningful morphological pieces.</p><h3>Token Embeddings + Positional Information</h3><p>Once text is tokenized into a sequence of integer IDs each token ID is used to look up its embedding vector from the embedding matrix&#8203;, as we described in the previous section. This gives us a sequence of vectors:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;[\\mathbf{e}_1, \\mathbf{e}_2, \\ldots, \\mathbf{e}_n]&quot;,&quot;id&quot;:&quot;RHINQUJVTG&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each ei&#8203; has dimension dmodel&#8203; (e.g., 4096).</p><p>But there&#8217;s a problem. The Transformer processes all positions <strong>in parallel</strong>, not sequentially like an RNN. This is a major advantage for speed, but it means the model has no inherent notion of word order. Without additional information, the Transformer would see &#8220;the cat sat on the mat&#8221; and &#8220;mat the on sat cat the&#8221; as identical &#8212; just a set of token embeddings with no positional structure.</p><p>We need to inject positional information somehow. The original &#8220;Attention Is All You Need&#8221; paper used <strong>sinusoidal positional encodings</strong>: fixed mathematical functions (sines and cosines of different frequencies) that generate a unique vector for each position, which is then added to the token embedding:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{x}_i = \\mathbf{e}_i + \\mathbf{p}_i&quot;,&quot;id&quot;:&quot;OYZYMNHVAO&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where <strong>p</strong>i&#8203; is the positional encoding for position<strong> i</strong>. The sinusoidal encoding was defined as:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{PE}(\\mathrm{pos}, 2k) = \\sin\\!\\left(\\frac{\\mathrm{pos}}{10000^{2k/d_{\\mathrm{model}}}}\\right)&quot;,&quot;id&quot;:&quot;THHOBGSJOR&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{PE}(\\mathrm{pos}, 2k+1) = \\cos\\!\\left(\\frac{\\mathrm{pos}}{10000^{2k/d_{\\mathrm{model}}}}\\right)&quot;,&quot;id&quot;:&quot;JPEOPTJIQJ&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Each dimension of the positional encoding uses a sinusoid with a different frequency. This has elegant properties: positions far apart have very different encodings, and the model can potentially learn to attend to relative positions because the difference between any two sinusoidal encodings depends only on their distance, not their absolute positions.</p><p>However, most modern LLMs have moved to a more sophisticated approach called <strong>Rotary Position Embeddings (RoPE)</strong>, introduced by Jianlin Su et al. in 2021. RoPE is worth understanding because it&#8217;s used in LLaMA, Mistral, and most current open-source LLMs.</p><h4>RoPE: Rotary Position Embeddings</h4><p>The core idea behind RoPE is beautifully geometric: instead of <em>adding</em> a positional vector to the embedding, RoPE <em>rotates</em> the embedding vector by an angle proportional to its position.</p><p>To understand why rotation works, we need to think about what attention actually computes (we&#8217;ll see this fully in the next section, but the key point is relevant now). Attention computes the dot product between a query vector q at one position and a key vector k at another position. We want this dot product to depend on the <em>relative</em> distance between the two positions, not on their absolute positions.</p><p>RoPE achieves this by operating on pairs of dimensions. For a vector in d-dimensional space, RoPE groups the dimensions into d/2 pairs and applies a 2D rotation to each pair, where the rotation angle depends on the position:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\begin{bmatrix}\nx'_{2k} \\\\\nx'_{2k+1}\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n\\cos(m\\theta_k) &amp; -\\sin(m\\theta_k) \\\\\n\\sin(m\\theta_k) &amp; \\cos(m\\theta_k)\n\\end{bmatrix}\n\\begin{bmatrix}\nx_{2k} \\\\\nx_{2k+1}\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;YQOSUVWXEX&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where m is the position index and &#952;_k = 10000^-2k/d sets a different rotation speed for each pair of dimensions.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!M4y0!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!M4y0!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 424w, https://substackcdn.com/image/fetch/$s_!M4y0!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 848w, https://substackcdn.com/image/fetch/$s_!M4y0!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 1272w, https://substackcdn.com/image/fetch/$s_!M4y0!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!M4y0!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png" width="750" height="350" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:350,&quot;width&quot;:750,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:36107,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!M4y0!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 424w, https://substackcdn.com/image/fetch/$s_!M4y0!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 848w, https://substackcdn.com/image/fetch/$s_!M4y0!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 1272w, https://substackcdn.com/image/fetch/$s_!M4y0!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1d6c5042-ec9b-4cd1-816f-a99ca9d21363_750x350.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Why does this encode relative position? Because of a fundamental property of rotations: when you compute the dot product of two rotated vectors, the result depends only on the <em>difference</em> between their rotation angles, not on the angles themselves. If position m rotates by angle m&#952; and position n rotates by angle n&#952;, their dot product depends on (m-n)&#952; &#8212; the relative distance. This is exactly the property we want: the model&#8217;s ability to determine how far apart two tokens are doesn&#8217;t depend on where they sit in absolute terms, only on their relative distance from each other.</p><p>This has practical benefits too: since there&#8217;s no hard-coded maximum position, RoPE allows models to generalize (to some extent) to sequence lengths longer than those seen during training.</p><h3>Self-Attention: The Core Mechanism</h3><p>We&#8217;ve now embedded our tokens and encoded their positions. The sequence of vectors [x_1, x_2, ..., x_n] is ready to enter the Transformer&#8217;s core: the <strong>self-attention mechanism</strong>.</p><p>The fundamental question that attention answers is: <strong>for each token in the sequence, which other tokens should it pay attention to, and how much?</strong></p><p>Consider the sentence: &#8220;The animal didn&#8217;t cross the street because <strong>it</strong> was too tired.&#8221; What does &#8220;it&#8221; refer to? To the animal, not the street. A human understands this instantly because of contextual reasoning. The attention mechanism gives the model the same ability: when processing the token &#8220;it,&#8221; the model can learn to attend strongly to &#8220;animal&#8221; and weakly to &#8220;street,&#8221; effectively resolving the reference.</p><h4>Queries, Keys, and Values</h4><p>The attention mechanism operates through three sets of vectors called <strong>queries</strong>, <strong>keys</strong>, and <strong>values</strong>. The metaphor is a soft dictionary lookup:</p><ul><li><p>The <strong>query</strong> is what a token is &#8220;looking for&#8221; &#8212; what kind of information does it need?</p></li><li><p>The <strong>key</strong> is what a token &#8220;advertises&#8221; &#8212; what kind of information does it contain?</p></li><li><p>The <strong>value</strong> is what a token &#8220;gives&#8221; &#8212; the actual content it contributes when attended to.</p></li></ul><p>For each input vector x_i, the model computes three vectors by multiplying with three separate learned weight matrices:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{q}_i = W_Q \\mathbf{x}_i \\quad\n\\mathbf{k}_i = W_K \\mathbf{x}_i \\quad\n\\mathbf{v}_i = W_V \\mathbf{x}_i&quot;,&quot;id&quot;:&quot;QSCTFBEQAU&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where W_Q, W_K, and W_V are matrices of shape (d_model &#215; d_k) for queries and keys, and (d_model &#215; d_v) for values. These matrices are <strong>learned parameters</strong> &#8212; they start random and are shaped by gradient descent, just like the embedding matrix, just like every weight in the network. The loss is the only signal, and from it the model discovers what kinds of queries to form, what keys to advertise, and what values to pass along.</p><h4>Why Not Just Use the Raw Vectors Directly?</h4><p>This deserves a careful answer, because there&#8217;s an obvious simpler alternative: just compute dot products between the raw input vectors x_i and x_j to measure similarity, then use those as attention weights to mix the raw vectors. No W_Q, no W_K, no W_V &#8212; just raw similarity between embeddings. Why introduce three extra learned matrices?</p><p>The answer has several layers.</p><p><strong>First: what a token needs to look for is not the same as what it contains.</strong> Consider the word &#8220;it&#8221; in &#8220;The animal didn&#8217;t cross the street because it was too tired.&#8221; The embedding vector for &#8220;it&#8221; encodes what &#8220;it&#8221; <em>is</em> &#8212; a pronoun, third person, singular. But what &#8220;it&#8221; <em>needs</em> &#8212; the information it must retrieve to be useful &#8212; is entirely different: it needs to find its antecedent, &#8220;animal.&#8221; The query for &#8220;it&#8221; should be something like &#8220;I&#8217;m looking for a noun that could be my referent,&#8221; while the key for &#8220;animal&#8221; should be something like &#8220;I&#8217;m a noun that could be someone&#8217;s referent.&#8221; These are fundamentally different roles, and a single raw vector can&#8217;t play both roles simultaneously. W_Q transforms the raw vector into a &#8220;what am I looking for?&#8221; representation, while W_K transforms the same raw vector into a &#8220;what do I advertise?&#8221; representation. These two projections allow the same token to ask one kind of question and answer a different kind.</p><p><strong>Second: what you retrieve should be different from what you match on.</strong> Even once the attention pattern is decided &#8212; &#8220;position 6 should attend strongly to position 1&#8221; &#8212; the information that flows from position 1 to position 6 shouldn&#8217;t just be position 1&#8217;s raw embedding or its key. The key&#8217;s job was to <em>get selected</em>; the value&#8217;s job is to <em>contribute useful content</em> once selected. For example, the key for &#8220;animal&#8221; might encode &#8220;I am a concrete noun, animate, singular&#8221; (the properties that make it match the query from &#8220;it&#8221;), but the value for &#8220;animal&#8221; might encode the specific semantic content that &#8220;it&#8221; needs for downstream processing &#8212; information about what kind of entity it is, its role in the sentence, etc. W_V creates this separate &#8220;payload&#8221; that gets transmitted once a match is made.</p><p><strong>Third: without projections, attention would be symmetric and context-blind.</strong> The dot product of raw vectors x_i &#183; x_j is symmetric &#8212; it equals x_j &#183; x_i. This means token A would attend to token B exactly as much as B attends to A. But in language, relationships are rarely symmetric: &#8220;it&#8221; should attend strongly to &#8220;animal,&#8221; but &#8220;animal&#8221; shouldn&#8217;t particularly need to attend to &#8220;it&#8221; at all. The separate W_Q and W_K matrices break this symmetry: q_i &#183; k_j &#8800; q_j &#183; k_i in general, because different matrices are applied on each side.</p><p><strong>Fourth: projections give the model learnable control over what matters.</strong> Raw embedding similarity is fixed by the embedding matrix. But attention needs to change its behavior at every layer. In block 3, attention might need to group tokens by syntactic role. In block 15, it might need to group them by semantic topic. In block 30, it might need to match questions with their answers. Each block has its own W_Q, W_K, W_V matrices, so each block can define &#8220;similarity&#8221; differently. The raw embeddings are the same everywhere; the projections give each layer its own notion of relevance.</p><p>In summary: W_Q, W_K, and W_V decouple three fundamentally different roles &#8212; asking, advertising, and contributing &#8212; that a single vector cannot serve simultaneously. Without them, attention would be a rigid, symmetric similarity measure over fixed representations. With them, attention becomes a flexible, asymmetric, learnable routing mechanism that can implement different information-flow patterns at every layer of the network.</p><p>Let&#8217;s walk through a concrete example with small dimensions to build intuition. Suppose we have a 3-token sequence and d_k = d_v = 4 (real models use 64 or 128, but the mechanics are identical).</p><p>After the linear projections, we have:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!sKM-!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!sKM-!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 424w, https://substackcdn.com/image/fetch/$s_!sKM-!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 848w, https://substackcdn.com/image/fetch/$s_!sKM-!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 1272w, https://substackcdn.com/image/fetch/$s_!sKM-!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!sKM-!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png" width="1382" height="356" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:356,&quot;width&quot;:1382,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:56447,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!sKM-!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 424w, https://substackcdn.com/image/fetch/$s_!sKM-!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 848w, https://substackcdn.com/image/fetch/$s_!sKM-!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 1272w, https://substackcdn.com/image/fetch/$s_!sKM-!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F72d3493f-5d9f-4f94-bacf-ba83bd6ccc0f_1382x356.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h4>Scaled Dot-Product Attention</h4><p>Now comes the core computation. For each pair of positions (i, j), we compute how much position i should attend to position j by taking the <strong>dot product</strong> of the query at position i with the key at position j:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{score}(i,j) = \\mathbf{q}_i \\cdot \\mathbf{k}_j&quot;,&quot;id&quot;:&quot;BEQJEJESCZ&quot;}" data-component-name="LatexBlockToDOM"></div><p>The dot product measures how aligned two vectors are &#8212; if the query and key point in similar directions, the score is high, meaning &#8220;this token has relevant information for what I&#8217;m looking for.&#8221; If they&#8217;re orthogonal, the score is zero, meaning &#8220;not relevant.&#8221;</p><p>For our 3-token example, we compute all pairwise dot products to form the <strong>attention score matrix</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;S = QK^T =\n\\begin{bmatrix}\n\\mathbf{q}_1 \\cdot \\mathbf{k}_1 &amp; \\mathbf{q}_1 \\cdot \\mathbf{k}_2 &amp; \\mathbf{q}_1 \\cdot \\mathbf{k}_3 \\\\\n\\mathbf{q}_2 \\cdot \\mathbf{k}_1 &amp; \\mathbf{q}_2 \\cdot \\mathbf{k}_2 &amp; \\mathbf{q}_2 \\cdot \\mathbf{k}_3 \\\\\n\\mathbf{q}_3 \\cdot \\mathbf{k}_1 &amp; \\mathbf{q}_3 \\cdot \\mathbf{k}_2 &amp; \\mathbf{q}_3 \\cdot \\mathbf{k}_3\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;XFCHOAAMTK&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each row tells us: for this token&#8217;s query, how relevant is every other token&#8217;s key?</p><p>But before we turn these scores into weights, we <strong>scale</strong> them by dividing by &#8730;{d_k}:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;S_{\\text{scaled}} = \\frac{QK^T}{\\sqrt{d_k}}&quot;,&quot;id&quot;:&quot;VORXDLNUVW&quot;}" data-component-name="LatexBlockToDOM"></div><p>Why? It&#8217;s about controlling variance. When d_k is large (say 64 or 128), the dot product of two random vectors tends to have a large magnitude &#8212; specifically, its variance grows proportionally to d_k. Large input values to the softmax function push it into regions where the gradient is extremely small (softmax saturates &#8212; one value dominates and all others are near zero). This makes learning difficult. Dividing by &#8730;{d_k} normalizes the variance back to 1, keeping the softmax in a well-behaved regime where gradients can flow.</p><p>Now we apply <strong>softmax</strong> to each row of the scaled score matrix:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;A = \\mathrm{softmax}\\!\\left(\\frac{QK^T}{\\sqrt{d_k}}\\right)&quot;,&quot;id&quot;:&quot;UNOFQLVLGU&quot;}" data-component-name="LatexBlockToDOM"></div><p>Softmax converts each row of raw scores into a probability distribution &#8212; the values are all positive and sum to 1. Each row A[i, :] now contains the <strong>attention weights</strong> for position i: how much attention does position i pay to every other position?</p><p>Finally, we compute the output by using these attention weights to take a <strong>weighted sum of the value vectors</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{output}_i = \\sum_j A[i,j] \\cdot \\mathbf{v}_j&quot;,&quot;id&quot;:&quot;FLEFLZZSTP&quot;}" data-component-name="LatexBlockToDOM"></div><p>In matrix form:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{Attention}(Q,K,V) = \\mathrm{softmax}\\!\\left(\\frac{QK^T}{\\sqrt{d_k}}\\right) V&quot;,&quot;id&quot;:&quot;VQEHUHGJUY&quot;}" data-component-name="LatexBlockToDOM"></div><p>The output for each position is a blend of all value vectors, weighted by how relevant each position&#8217;s key was to this position&#8217;s query. If position i attends strongly to position j (high A[i,j]), then position j&#8217;s <strong>value</strong> vector contributes heavily to position i&#8217;s output. If the attention weight is near zero, that position&#8217;s value barely contributes.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!zwch!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!zwch!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 424w, https://substackcdn.com/image/fetch/$s_!zwch!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 848w, https://substackcdn.com/image/fetch/$s_!zwch!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 1272w, https://substackcdn.com/image/fetch/$s_!zwch!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!zwch!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png" width="800" height="420" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:420,&quot;width&quot;:800,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:32961,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!zwch!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 424w, https://substackcdn.com/image/fetch/$s_!zwch!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 848w, https://substackcdn.com/image/fetch/$s_!zwch!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 1272w, https://substackcdn.com/image/fetch/$s_!zwch!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F466e1968-c6b1-41d2-9fcd-34a900670908_800x420.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><p>This is the complete attention mechanism. And notice something crucial: <strong>every component</strong> &#8212; W_Q, W_K, W_V &#8212; is a learned weight matrix. The model discovers, through gradient descent against the loss, what queries to ask, what keys to advertise, and what values to pass. Nobody programs the model to resolve coreferences or track syntactic dependencies. The loss function says &#8220;you predicted the wrong next word,&#8221; and backprop shapes these matrices until the attention patterns that emerge are the ones that best reduce prediction error.</p><h4>Causal (Masked) Attention</h4><p>In the original Transformer (designed for translation), the encoder uses <strong>bidirectional</strong> attention &#8212; each token can attend to every other token in the sequence, including tokens that come after it. This makes sense for understanding input: to comprehend the meaning of a word, you need the full context.</p><p>But for <strong>generation</strong> &#8212; predicting the next token &#8212; you cannot look at future tokens. When the model is trying to predict what comes after &#8220;The cat sat on the,&#8221; it can&#8217;t peek at the answer. This would be cheating during training, and during inference the future tokens simply don&#8217;t exist yet.</p><p>The solution is a <strong>causal mask</strong> (also called a &#8220;look-ahead mask&#8221;): a lower-triangular matrix of ones and zeros (or equivalently, negative infinities and zeros) that is added to the attention scores before softmax:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{Mask} =\n\\begin{bmatrix}\n0 &amp; -\\infty &amp; -\\infty \\\\\n0 &amp; 0 &amp; -\\infty \\\\\n0 &amp; 0 &amp; 0\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;NYZNTUCGKR&quot;}" data-component-name="LatexBlockToDOM"></div><p>Adding -&#8734; to a score before softmax effectively sets that attention weight to zero &#8212; position i is prevented from attending to any position j &gt; i. Token 1 can only see itself. Token 2 can see tokens 1 and 2. Token 3 can see tokens 1, 2, and 3. And so on.</p><p>This is why decoder-based models (GPT-style) are called <strong>autoregressive</strong>: they generate text one token at a time, each token conditioned only on the tokens that came before it.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!bl-I!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!bl-I!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 424w, https://substackcdn.com/image/fetch/$s_!bl-I!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 848w, https://substackcdn.com/image/fetch/$s_!bl-I!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 1272w, https://substackcdn.com/image/fetch/$s_!bl-I!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!bl-I!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png" width="500" height="480" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:480,&quot;width&quot;:500,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:53585,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!bl-I!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 424w, https://substackcdn.com/image/fetch/$s_!bl-I!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 848w, https://substackcdn.com/image/fetch/$s_!bl-I!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 1272w, https://substackcdn.com/image/fetch/$s_!bl-I!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F731cf134-7cfd-4d63-ac88-6f6312f86824_500x480.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h4>Multi-Head Attention</h4><p>A single attention operation computes one set of attention weights for each position. But a token might need to attend to different parts of the sequence for different reasons. &#8220;it&#8221; in our earlier example needs to attend to &#8220;animal&#8221; for coreference resolution, but it might also need to attend to &#8220;tired&#8221; to understand the predicate, and to &#8220;didn&#8217;t&#8221; to understand negation.</p><p><strong>Multi-head attention</strong> addresses this by running multiple attention operations in parallel, each with its own learned W_Q, W_K, W_V matrices:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{head}_h = \\mathrm{Attention}(X W_Q^{(h)}, X W_K^{(h)}, X W_V^{(h)})&quot;,&quot;id&quot;:&quot;MMGTPGASWS&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each head has a reduced dimensionality: if d_model = 768 and we have h = 12 heads, each head operates in d_k = d_v = 768/12 = 64 dimensions. This is the crucial design choice. Each head doesn&#8217;t see the full 768-dimensional representation &#8212; it&#8217;s forced to work with only 64 dimensions. Head 1 operates in one 64-dimensional subspace, head 2 in a different 64-dimensional subspace, and so on.</p><p>This dimensional constraint is what <strong>forces</strong> the heads to develop different perspectives. If every head operated on the full 768 dimensions, they&#8217;d all be looking at the same information and solving the same optimization problem &#8212; different random initialization might give early diversity, but gradient descent would tend to push them toward similar solutions over training. By restricting each head to a small subspace, the architecture guarantees that each head must learn to form useful attention patterns from a <em>different slice</em> of the representation. Head 1 can only see features that live in its 64 dimensions. Head 2 can only see features in its own, different 64 dimensions. The diversity is structurally enforced, not hoped for.</p><p>There&#8217;s also a computational benefit: the total cost of H heads at d_k dimensions each equals the cost of a single head at the full d_model dimensions. You get multiple perspectives for the same price as one.</p><h4>Why Not Just One Big Head?</h4><p>It&#8217;s worth pausing on the tempting alternative: instead of H small heads, why not use a single head at the full d_model width and skip the splitting (and W_O) entirely? The first thing to notice is that this <strong>wouldn&#8217;t save anything</strong>. A single full-width head needs three d_model &#215; d_model matrices &#8212; that&#8217;s 3 &#215; d_model^2 parameters. Multi-head uses the <em>same</em> 3 &#215; d_model^2 for all its Q/K/V projections combined, because stacking H matrices of width d_k = d_model/H side by side reconstructs a d_model &#215; d_model matrix. Multi-head then adds W_O on top, so it&#8217;s actually <em>slightly more</em> expensive, not cheaper. Saving parameters was never the motivation &#8212; the total query/key/value capacity is identical either way.</p><p>The real reason is what a single head can and cannot do. No matter how wide you make it, one head produces exactly <strong>one</strong> set of attention weights per position &#8212; one softmax distribution over the sequence. And softmax is competitive: it sums to 1, so attending strongly to one token necessarily suppresses the others. But &#8220;it&#8221; in our example needs to look at &#8220;animal&#8221; (its referent) <em>and</em> &#8220;tired&#8221; (the predicate) <em>and</em> &#8220;didn&#8217;t&#8221; (negation) at the same time. A single distribution can&#8217;t point firmly in several directions at once &#8212; it&#8217;s forced into a blurry compromise. Widening the head gives it richer query and key <em>vectors</em>, but it still collapses them into a single softmax: same bottleneck, just higher-dimensional inputs. What you actually need is several independent attention patterns, and that is precisely what H heads provide &#8212; H separate softmaxes that don&#8217;t compete, later fused by W_O.</p><p>Seen this way, the dimensional slicing isn&#8217;t the goal; it&#8217;s the mechanism that lets you afford many attention patterns on a fixed budget. You have d_model &#8220;query dimensions&#8221; to spend, and H simply decides how many independent patterns you carve them into. The authors didn&#8217;t just guess at this &#8212; the original paper ran the ablation, reporting that a single head was about 0.9 BLEU worse than the multi-head configuration at the same total dimensionality, while using too many heads (each too thin to form discriminating dot products) also hurt quality. The H = 8, d_k = 64 region was the sweet spot: enough parallel patterns, each still wide enough to be sharp.</p><p>After all heads compute their outputs, the results are <strong>concatenated</strong> and passed through a final linear projection:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{MultiHead}(X) = \\mathrm{Concat}(\\mathrm{head}_1, \\ldots, \\mathrm{head}_h) \\, W_O&quot;,&quot;id&quot;:&quot;UXYSIMZVKY&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where W_O is yet another learned weight matrix of shape (d_model &#215; d_model) that blends the outputs of all heads back into the full d_model-dimensional space.</p><h4>A Note on Implementation</h4><p>Conceptually, each head has its own separate small W_Q, W_K, W_V matrices &#8212; and that&#8217;s the clearest way to think about it. But in actual PyTorch implementations, you&#8217;ll see something different: one large W_Q matrix of shape (d_model, d_model) that processes the input in a single matrix multiplication, and then the result is <em>reshaped</em> into H separate chunks of d_k dimensions. This produces identical numbers to the &#8220;separate small matrices&#8221; approach &#8212; stacking H matrices of shape (d_model, d_k) side by side gives one matrix of shape (d_model, d_model), and multiplying then slicing is the same as slicing then multiplying. The single large multiplication is just much faster on a GPU, which is optimized for big, regular operations. The &#8220;reshape&#8221; itself is free &#8212; no data is copied or moved, the GPU just reinterprets the same memory as having a different shape.</p><h4>Why Do We Need W_O After Concatenation?</h4><p>At this point you might ask: isn&#8217;t the concatenated vector already the right shape? If each head outputs a vector of dimension d_v = d_model/H, and we concatenate H of them, we get a vector of dimension d_model. That&#8217;s the same dimension the rest of the network expects. Why not just use the concatenated vector directly and skip the extra matrix?</p><p>The concatenated vector has a structural problem: it&#8217;s <strong>compartmentalized</strong>. Dimensions 0 through d_v - 1 came entirely from head 1. Dimensions d_v through 2d_v - 1 came entirely from head 2. And so on. There&#8217;s no mixing between heads. Whatever head 1 computed sits in its own section, whatever head 2 computed sits in its section, and the two sections never interact.</p><p>But the downstream layers &#8212; the residual connection, the FFN, the next block&#8217;s attention &#8212; expect a single unified representation at each position, not a partitioned one. The next block&#8217;s W_Q matrix, for instance, will multiply the entire d_model-dimensional vector to produce a new query. If that query needs to combine information from something head 1 discovered (say, syntactic structure) with something head 2 discovered (say, semantic similarity), it would need to reach into both compartments of the concatenated vector simultaneously. Without W_O, the only way to mix these compartments is to leave it to the next layer&#8217;s matrices, which means the network has to &#8220;waste&#8221; some of its capacity in those matrices just to undo the compartmentalization from the previous layer.</p><p>W_O solves this by performing a <strong>cross-head mixing</strong> immediately after concatenation. It&#8217;s a full (d_model &#215; d_model) matrix, so every dimension of its output can be a weighted combination of every dimension of its input &#8212; mixing head 1&#8217;s contributions with head 2&#8217;s, head 3&#8217;s, and so on. This lets the network produce a coherent, unified representation that combines the best insights from all heads, rather than passing along a segmented structure and hoping downstream layers sort it out.</p><p>Think of it this way: the multiple heads are like a panel of experts who each analyzed the sequence from their own perspective. Concatenation puts their reports side by side on a desk. W_O is the decision-maker who reads all the reports and writes a single, integrated summary. That summary is what the rest of the network acts on.</p><p>W_O is also a learned parameter &#8212; shaped by the loss just like everything else &#8212; so the network discovers the best way to fuse head outputs for the prediction task. In practice, trained W_O matrices often show interesting structure: some output dimensions draw heavily from one specific head, others blend several heads, reflecting the fact that different aspects of the final representation benefit from different combinations of the heads&#8217; outputs.</p><p>Different heads learn to specialize in different things. Research on trained Transformers has found heads that track syntactic dependencies (subject-verb agreement), heads that handle coreference (pronoun resolution), heads that focus on nearby tokens (local context), and heads that attend to distant tokens (long-range dependencies). This specialization isn&#8217;t programmed &#8212; it emerges from the loss function, because having diverse attention patterns leads to better predictions.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!15R1!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!15R1!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 424w, https://substackcdn.com/image/fetch/$s_!15R1!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 848w, https://substackcdn.com/image/fetch/$s_!15R1!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 1272w, https://substackcdn.com/image/fetch/$s_!15R1!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!15R1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png" width="800" height="460" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:460,&quot;width&quot;:800,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:65164,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!15R1!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 424w, https://substackcdn.com/image/fetch/$s_!15R1!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 848w, https://substackcdn.com/image/fetch/$s_!15R1!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 1272w, https://substackcdn.com/image/fetch/$s_!15R1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc606cac2-57b2-4a17-a4bd-a0f55fca3d90_800x460.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><h3>The Feedforward Network (FFN)</h3><p>After the multi-head attention layer, each position&#8217;s vector passes through a <strong>position-wise feedforward network</strong>. And here&#8217;s where we come full circle to Part 1, because this feedforward network is nothing more and nothing less than an <strong>MLP</strong> &#8212; the exact same kind of network we built from scratch.</p><p>Remember our student-exam network? It had an input layer (2 neurons: study hours, attendance), a hidden layer (3 neurons), and an output layer (1 neuron). Each layer was fully connected to the next. That was an MLP. The FFN inside each Transformer block is the same thing, just with different dimensions:</p><ul><li><p><strong>Input layer</strong>: the d_model-dimensional vector at a single position (e.g., 4096 dimensions)</p></li><li><p><strong>Hidden layer</strong>: d_ff neurons (e.g., 16384 = 4 &#215; 4096)</p></li><li><p><strong>Output layer</strong>: back to d_model dimensions (4096)</p></li></ul><p>That&#8217;s it. The entire example from Part 1 &#8212; the student pass/fail predictor with its weights, biases, linear combinations, activation functions, and backpropagation &#8212; is just a small component inside a single Transformer block. Every Transformer block contains one of these MLPs. A 32-block Transformer contains 32 separate MLPs (each with its own weights).</p><p>Let&#8217;s be explicit about the connection. In Part 1, a single neuron computed:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;z = \\sum_{i=1}^{n} w_i x_i + b \\quad\ny = \\alpha(z)&quot;,&quot;id&quot;:&quot;BIJZRKXHWG&quot;}" data-component-name="LatexBlockToDOM"></div><p>The FFN's first layer does the exact same thing, just for all neurons at once using matrix notation:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{h} = W_1 \\mathbf{x} + b_1&quot;,&quot;id&quot;:&quot;FNMUGHZJYI&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each row of W&#8321; is the weight vector for one neuron in the hidden layer. The matrix multiplication computes all the linear combinations simultaneously. Then the activation function is applied element-wise:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{h}_{\\text{act}} = \\mathrm{activation}(\\mathbf{h})&quot;,&quot;id&quot;:&quot;FOHCMIXJSW&quot;}" data-component-name="LatexBlockToDOM"></div><p>And the second layer contracts back:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{FFN}(x) = W_2 \\cdot \\mathbf{h}_{\\text{act}} + b_2&quot;,&quot;id&quot;:&quot;XLUAIUOYIK&quot;}" data-component-name="LatexBlockToDOM"></div><p>Written in one line:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{FFN}(x) = W_2 \\cdot \\mathrm{activation}(W_1 \\mathbf{x} + b_1) + b_2&quot;,&quot;id&quot;:&quot;QEBDRMEJWY&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where W&#8321; has shape (d_model &#215; d_ff) and W&#8322; has shape (d_ff &#215; d_model). Typically d_ff = 4 &#215; d_model, so the FFN expands the representation to a wider space, applies the non-linearity, and then projects it back down.</p><h4>Why is it necessary to &#8220;Expand and Contract&#8221; ?</h4><p>The term &#8220;expand and contract&#8221; describes what happens dimensionally, but let&#8217;s trace what this means for the information flowing through.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!5Rjm!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!5Rjm!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 424w, https://substackcdn.com/image/fetch/$s_!5Rjm!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 848w, https://substackcdn.com/image/fetch/$s_!5Rjm!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 1272w, https://substackcdn.com/image/fetch/$s_!5Rjm!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!5Rjm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png" width="700" height="420" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/b67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:420,&quot;width&quot;:700,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:76840,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!5Rjm!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 424w, https://substackcdn.com/image/fetch/$s_!5Rjm!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 848w, https://substackcdn.com/image/fetch/$s_!5Rjm!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 1272w, https://substackcdn.com/image/fetch/$s_!5Rjm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb67d89b7-c7ff-467f-ae35-3bba942d554f_700x420.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>When a 4096-dimensional vector enters W&#8321; and becomes a 16384-dimensional vector, the representation has been projected into a <strong>much wider space</strong>. Each of these 16384 dimensions is a learned feature detector &#8212; a specific linear combination of the input&#8217;s 4096 dimensions, followed by a nonlinear activation. Some of these feature detectors might activate (produce a non-zero value) for inputs related to animals, others for inputs related to past tense, others for inputs that look like the start of a list. The wider space gives the network 16384 &#8220;slots&#8221; to check for different patterns.</p><p>The activation function then decides which of these feature detectors &#8220;fire.&#8221; With ReLU, any dimension that computed a negative value gets zeroed out. Only the relevant features survive. This is <strong>sparse activation</strong> &#8212; in practice, at any given position, most of the 16384 neurons are inactive (zero). The activation function selects which features are relevant for this particular input.</p><p>Then W&#8322; takes the surviving (non-zero) activations and projects them back to 4096 dimensions. Each column of W&#8322; is the &#8220;contribution&#8221; that one hidden neuron makes to the output. The second matrix effectively says: &#8220;given that these particular features activated, here&#8217;s how to update the representation.&#8221; It combines the active features&#8217; contributions into a coherent d_model-dimensional update.</p><p>The expand-then-contract pattern is like this: the first matrix asks 16384 yes/no questions about the input (expansion), the activation function selects the relevant answers (gating), and the second matrix synthesizes the relevant answers back into a compact representation (contraction).</p><h4>Activation Function: GELU vs ReLU</h4><p><strong>GELU</strong> (Gaussian Error Linear Unit) has largely replaced ReLU in modern Transformers. Where ReLU hard-clips negative values to zero, GELU applies a smooth, probabilistic gating:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{GELU}(x) = x \\cdot \\Phi(x)&quot;,&quot;id&quot;:&quot;YPVZLKXCQA&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Where phi(x) is the cumulative distribution function of the standard normal distribution. Intuitively, GELU multiplies each value by the probability that a standard Gaussian random variable is less than that value. Small negative values are smoothly dampened rather than harshly zeroed, which empirically leads to better training dynamics.</p><h4>Why Is the FFN Needed At All?</h4><p>Attention handles the <em>mixing of information across positions</em> &#8212; it lets each token gather relevant information from other tokens. But it doesn&#8217;t do much <em>processing</em> of that gathered information. The attention output at each position is a weighted average of value vectors, which is still a linear combination. Non-linear processing &#8212; the ability to compute complex functions of the gathered information &#8212; requires the FFN.</p><p>Think of it this way: attention is the &#8220;communication&#8221; step (tokens exchange information), and the FFN is the &#8220;thinking&#8221; step (each token independently processes what it received). Without the FFN, the Transformer would just be stacking linear operations on top of linear operations (since the attention mechanism is fundamentally a weighted average, which is linear in the values). The FFN&#8217;s activation function is what introduces genuine non-linearity, giving each block the computational power to learn complex transformations.</p><h4>The FFN as a Key-Value Memory</h4><p>Recent research has suggested an elegant interpretation: the FFN layers act as <strong>key-value memories</strong>. The first matrix W&#8321; maps the input to a set of &#8220;keys&#8221; in the wider space, the activation function selects which keys are active, and the second matrix W&#8322; retrieves the associated &#8220;values.&#8221; In this view, each neuron in the wider layer stores a piece of knowledge, and the input determines which pieces of knowledge are retrieved. This is why scaling up the FFN (making d_ff larger) tends to increase the amount of factual knowledge a model can store.</p><h4>The FFN Is Applied Per-Position &#8212; Independently</h4><p>One detail worth emphasizing: the FFN is applied <strong>independently to each position in the sequence</strong>, using the <strong>same weights</strong> for every position. Position 0&#8217;s vector goes through W&#8321; and W&#8322;. Position 1&#8217;s vector goes through the same W&#8321; and W&#8322;. Position 2 the same. They share weights but don&#8217;t interact &#8212; there&#8217;s no information flow between positions inside the FFN. All cross-position communication happens in the attention layer. The FFN is purely a per-position transformation.</p><p>This is different from the student-exam MLP in Part 1, where the entire input was fed in at once. Here, the FFN processes one position&#8217;s vector at a time (though in practice, for efficiency, all positions are batched through the same matrix multiplication simultaneously &#8212; the math is the same either way).</p><h4>SwiGLU: The Modern FFN Variant</h4><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!idBR!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!idBR!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 424w, https://substackcdn.com/image/fetch/$s_!idBR!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 848w, https://substackcdn.com/image/fetch/$s_!idBR!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 1272w, https://substackcdn.com/image/fetch/$s_!idBR!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!idBR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png" width="760" height="500" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:500,&quot;width&quot;:760,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:55812,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!idBR!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 424w, https://substackcdn.com/image/fetch/$s_!idBR!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 848w, https://substackcdn.com/image/fetch/$s_!idBR!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 1272w, https://substackcdn.com/image/fetch/$s_!idBR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F26983c87-67eb-4a3d-ad0e-8b1eb4edbc68_760x500.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>The FFN we described above &#8212; two matrices with an activation in between &#8212; is what the original Transformer paper used. But most modern LLMs, including LLaMA, Mistral, and their derivatives, use a modified version called <strong>SwiGLU</strong> (Swish-Gated Linear Unit), introduced by Noam Shazeer in 2020. Understanding this variant matters not just for comprehension but for practical work: if you ever fine-tune an LLM with techniques like LoRA, you&#8217;ll encounter the names of these matrices directly.</p><p>The standard FFN has two weight matrices:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{FFN}(x) = W_2 \\cdot \\mathrm{ReLU}(W_1 \\cdot \\mathbf{x} + b_1) + b_2&quot;,&quot;id&quot;:&quot;YAIMPDEWZQ&quot;}" data-component-name="LatexBlockToDOM"></div><p>W&#8321; expands from d_model to d_ff, ReLU activates, W&#8322; contracts back. Two matrices, one activation.</p><p>SwiGLU replaces this with <strong>three</strong> weight matrices and a gating mechanism:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{FFN}_{\\mathrm{SwiGLU}}(x) = W_{\\mathrm{down}} \\cdot \\left(\\mathrm{SiLU}(W_{\\mathrm{gate}} \\cdot \\mathbf{x}) \\odot (W_{\\mathrm{up}} \\cdot \\mathbf{x})\\right)&quot;,&quot;id&quot;:&quot;KAXRVEXCCO&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where &#8857; denotes element-wise multiplication &#8212; multiplying two vectors entry by entry. The three matrices have specific roles:</p><p><strong>W_gate</strong> (the &#8220;gate projection&#8221;): projects from d_model to d_ff, then passes the result through <strong>SiLU</strong> (Sigmoid Linear Unit, also called &#8220;Swish&#8221;), a smooth activation function. SiLU is defined as SiLU(x) = x &#183; sigmoid(x), which is similar to GELU but simpler to compute. The output of this path is a vector of gating values &#8212; numbers that determine how &#8220;open&#8221; each dimension is. Values near zero mean &#8220;block this dimension,&#8221; values near one mean &#8220;let it through.&#8221;</p><p><strong>W_up</strong> (the &#8220;up projection&#8221;): also projects from d_model to d_ff, in parallel with the gate path. This produces the actual content &#8212; the information that might pass through. No activation function is applied here. This is the raw signal.</p><p><strong>W_down</strong> (the &#8220;down projection&#8221;): projects from d_ff back to d_model. This is the contraction step, playing the same role as W&#8322; in the standard FFN.</p><p>The key difference from the standard FFN: instead of one matrix producing values that ReLU then hard-clips, <strong>two matrices collaborate</strong>. The gate path decides <em>which dimensions to open</em> (via SiLU), the up path provides <em>what content to let through</em>, and the element-wise multiplication combines them &#8212; only information that the gate &#8220;approves&#8221; survives. Then the down projection compresses the result back to d_model dimensions.</p><p>This is the same gating idea that made LSTMs effective &#8212; learned gates that control information flow &#8212; now applied inside the FFN. It gives the network finer-grained control over what information passes through, compared to ReLU&#8217;s blunt &#8220;positive values live, negative values die&#8221; approach. Empirically, SwiGLU produces better results than standard ReLU or GELU FFNs at the same parameter count.</p><p>There&#8217;s a practical consequence worth noting. The standard FFN has two weight matrices (W&#8321; and W&#8322;), while SwiGLU has three (gate, up, down). To keep the total parameter count comparable, SwiGLU models typically use a smaller d_ff. For example, where a standard FFN might use d_ff = 4 &#215; d_model, a SwiGLU FFN might use d_ff = 8/3 &#215; d_model (roughly 2.67&#215;). With three matrices at the smaller width, the total parameter count ends up similar to two matrices at the larger width.</p><p><strong>Why this matters for fine-tuning</strong>: when you fine-tune a model using LoRA (Low-Rank Adaptation) or similar techniques, you select which weight matrices to apply adapters to. A typical LoRA configuration targets some or all of these matrices:</p><ul><li><p>q_proj, k_proj, v_proj, o_proj &#8212; the four attention matrices (W_Q, W_K, W_V, W_O from the attention section)</p></li><li><p>gate_proj, up_proj, down_proj &#8212; the three SwiGLU FFN matrices</p></li></ul><p>Now you know exactly what each of those names refers to. The attention projections are the Q/K/V matrices and the output projection we described in the attention section. The gate/up/down projections are the three FFN matrices we just described. Every learnable matrix in a modern Transformer block is covered by these seven names (plus the LayerNorm parameters, which are usually not targeted by LoRA because they&#8217;re small).</p><h4>Mixture of Experts: Scaling the FFN Without Scaling Compute</h4><p>Everything we&#8217;ve described so far is a <strong>dense</strong> Transformer &#8212; every parameter participates in every forward pass, for every token. But there&#8217;s an increasingly popular architectural variant that modifies the FFN specifically, leaving everything else untouched: <strong>Mixture of Experts (MoE)</strong>.</p><p>The idea flows naturally from two observations we&#8217;ve already made. First, the FFN acts as a key-value memory &#8212; each neuron in the hidden layer stores a piece of knowledge, and the activation function selects which neurons fire. Second, only a fraction of neurons activate for any given input (the rest are zeroed by ReLU). So most of the FFN&#8217;s capacity is &#8220;dark&#8221; at any given moment. What if we leaned into that sparsity more aggressively?</p><p>A MoE layer replaces the single FFN with <strong>multiple independent FFNs</strong> &#8212; typically 8, 16, or even 64 &#8212; called <strong>experts</strong>. Each expert is a complete FFN: its own W_1^(e), activation, W_2^(e), biases. Structurally identical to the FFN we described, just replicated several times with independent weights.</p><p>On top of the experts sits a small learned <strong>router network</strong> (also called a gating network) &#8212; typically a single linear layer followed by softmax &#8212; that takes each token&#8217;s vector as input and produces a probability distribution over the experts:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;g=softmax(Wrouter&#8203;&#8901;x)&quot;,&quot;id&quot;:&quot;YDLFCJLVRP&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where W_router has shape (d_model &#215; n_experts) and g is a vector of n_experts probabilities saying &#8220;how relevant is each expert for this token?&#8221;</p><p>The key design choice is <strong>top-k routing</strong>: instead of running all experts, the router selects only the top k (typically k = 2) experts with the highest gating scores. Only those k experts run their forward pass for this token. The outputs of the selected experts are then combined as a weighted sum, using the gating scores as weights:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{MoE}(x) = \\sum_{i \\in \\mathrm{top}\\text{-}k} g_i \\cdot \\mathrm{FFN}_i(x)&quot;,&quot;id&quot;:&quot;EXCWFTMEBJ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Everything else in the Transformer block stays exactly the same. The block becomes:</p><p>LayerNorm &#8594; Multi-Head Attention &#8594; Residual &#8594; LayerNorm &#8594; <strong>Router &#8594; top-k FFNs</strong> &#8594; Residual</p><p>Attention is unchanged. Residuals are unchanged. Normalization is unchanged. Only the FFN slot is swapped out.</p><p><strong>Why does this matter?</strong> It decouples the model&#8217;s <strong>total knowledge capacity</strong> from its <strong>per-token compute cost</strong>. Consider Mixtral 8x7B, a well-known MoE model. It has 8 experts, each roughly the size of a 7B-parameter model&#8217;s FFN. The total parameter count is about 47 billion. But with top-2 routing, only 2 of the 8 experts run for any given token, so the active parameter count per token is about 13 billion. The model has the knowledge capacity of a ~47B dense model but the inference cost of a ~13B dense model. It gets the quality benefits of scale without the full computational price.</p><p>This connects directly to the &#8220;FFN as key-value memory&#8221; interpretation. A single FFN has a fixed number of memory slots (neurons in the hidden layer). If you want the model to know more facts, you need more slots, which means a bigger d_ff, which means more compute per token. MoE breaks this tradeoff: 8 experts means 8&#215; the memory slots, but since only 2 run per token, the compute only doubles rather than octupling. Different experts can specialize in different domains of knowledge &#8212; one might activate for medical text, another for code, another for legal language &#8212; and the router learns which bank of knowledge is relevant for each token. The router itself is learned through the same loss and gradient descent process as everything else: it starts random, and the loss signal shapes it to route tokens to whichever experts reduce prediction error.</p><p>There are engineering subtleties we won&#8217;t dive deep into &#8212; load balancing (ensuring all experts get used, not just a few favorites), auxiliary losses (penalties that encourage balanced routing), and the communication overhead in distributed training (different experts may live on different GPUs). But architecturally, MoE is a clean substitution at the FFN level. If you understand the dense FFN, you understand MoE &#8212; it&#8217;s the same computation, replicated and gated.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!QE8R!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!QE8R!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 424w, https://substackcdn.com/image/fetch/$s_!QE8R!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 848w, https://substackcdn.com/image/fetch/$s_!QE8R!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 1272w, https://substackcdn.com/image/fetch/$s_!QE8R!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!QE8R!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png" width="750" height="420" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:420,&quot;width&quot;:750,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:51030,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!QE8R!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 424w, https://substackcdn.com/image/fetch/$s_!QE8R!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 848w, https://substackcdn.com/image/fetch/$s_!QE8R!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 1272w, https://substackcdn.com/image/fetch/$s_!QE8R!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3679f3d3-d9a5-4dfd-984b-bd0d6ad7d33d_750x420.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><h3>Layer Normalization and Residual Connections</h3><p>Two more components are essential for making deep Transformers trainable:</p><p><strong>Residual connections</strong> (also called skip connections) add the input of a sub-layer directly to its output:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;x&#8242;=SubLayer(x)+x&quot;,&quot;id&quot;:&quot;FSHKRZDAYU&quot;}" data-component-name="LatexBlockToDOM"></div><p>This looks like an innocuous formula &#8212; just adding two vectors. But it&#8217;s arguably the single most important structural innovation that makes deep Transformers trainable. Without residual connections, a 32-block Transformer would be practically impossible to train. With them, networks of 80 or even 128 blocks train reliably. Let&#8217;s understand why.</p><h4>The Problem Without Residual Connections</h4><p>Imagine a deep network without residual connections. Each block applies a transformation f to its input:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;x_1 = f_1(x_0) \\quad x_2 = f_2(x_1) \\quad x_3 = f_3(x_2) \\quad \\cdots \\quad x_N = f_N(x_{N-1})&quot;,&quot;id&quot;:&quot;SYUHPSMDRI&quot;}" data-component-name="LatexBlockToDOM"></div><p>The output is the result of composing all these functions: f_N applied to f_{N-1} applied to ... applied to f_1 applied to x_0 &#8212; a long chain. During backpropagation, the chain rule tells us the gradient of the loss with respect to an early layer's parameters involves the <strong>product of all intermediate derivatives</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial x_0}\n=\n\\frac{\\partial \\mathcal{L}}{\\partial x_N}\n\\cdot\n\\frac{\\partial f_N}{\\partial x_{N-1}}\n\\cdot\n\\frac{\\partial f_{N-1}}{\\partial x_{N-2}}\n\\cdots\n\\frac{\\partial f_2}{\\partial x_1}\n\\cdot\n\\frac{\\partial f_1}{\\partial x_0}&quot;,&quot;id&quot;:&quot;BBZLBQVSUD&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each of those derivative terms is a <strong>Jacobian matrix</strong>. In Part 1, our network had scalar values flowing between neurons, so each derivative was just a single number. But in a Transformer, what flows between layers are vectors (4096-dimensional, say), and the derivative of a vector-valued function with respect to a vector input is a matrix, not a scalar. The Jacobian is simply that matrix: each entry tells us how much one particular output dimension changes when we nudge one particular input dimension. It&#8217;s the multi-dimensional generalization of the single-number derivative from Part 1.</p><p>In Part 1, we saw the chain rule multiplied through each layer&#8217;s derivatives &#8212; each was a scalar, and we multiplied scalars together. Here, the chain rule multiplies Jacobian matrices together. And just as a product of many small scalars (each less than 1) shrinks toward zero, a product of many matrices can shrink too &#8212; but the notion of &#8220;small&#8221; for a matrix is captured by its <strong>eigenvalues</strong>.</p><p>An eigenvalue is, informally, a number that tells you how much a matrix stretches or shrinks along a particular direction &#8212; but the eigenvalue itself is just a scalar, not a direction. The direction comes from its paired <strong>eigenvector</strong>. They always come together: every square matrix has a set of special vectors (called eigenvectors) along which the matrix acts like simple scalar multiplication instead of the usual rotation-and-scaling. The defining equation is Av = &#955; v: the matrix A applied to eigenvector v gives back the same vector v scaled by &#955;. The eigenvector v says <em>which direction</em> is special; the eigenvalue &#955; says <em>what happens along that direction</em>. If &#955; = 0.9, any component of a vector that lies along eigenvector v gets shrunk by 10% each time the matrix is applied. If &#955; = 1.1, that component grows by 10%. If &#955; = 1, it&#8217;s preserved exactly.</p><p>With that context: if these Jacobians typically have eigenvalues less than 1 (which is common &#8212; most learned transformations are slightly contractive), then multiplying 32 or 80 of them together gives a product that approaches zero exponentially fast:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;0.932&#8776;0.0350.980&#8776;0.0002&quot;,&quot;id&quot;:&quot;HSGVJMUQVB&quot;}" data-component-name="LatexBlockToDOM"></div><p>The gradient that reaches the first block is essentially zero. The early layers receive no meaningful error signal, so they can&#8217;t learn. This is the vanishing gradient problem &#8212; the same phenomenon that plagued RNNs, now showing up in the depth dimension instead of the time dimension.</p><h4>What Residual Connections Change</h4><p>With a residual connection, each block computes:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;xi+1&#8203;=fi&#8203;(xi&#8203;)+xi&#8203;&quot;,&quot;id&quot;:&quot;YFZLEEXOJB&quot;}" data-component-name="LatexBlockToDOM"></div><p>This tiny change &#8212; adding the input back to the output &#8212; transforms the gradient picture entirely. Let's see why. Taking the derivative with respect to x_i:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial x_i}{\\partial x_{i+1}} = \\frac{\\partial x_i}{\\partial f_i} + I&quot;,&quot;id&quot;:&quot;TQCSOZMQPN&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where I is the <strong>identity matrix</strong> &#8212; a square matrix with 1s on the diagonal and 0s everywhere else, which acts like the number 1 for matrices: multiplying any vector by I returns the same vector unchanged. This is the crucial difference. Without the residual, the derivative was just the Jacobian of the sub-layer &#8212; a matrix that might have small eigenvalues. With the residual, we <strong>add the identity matrix</strong>, which has eigenvalues of exactly 1 (every direction is an eigenvector, and none of them get stretched or shrunk).</p><p>Now when we chain these derivatives across many blocks:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial x_0}{\\partial x_N} = \\prod_{i=0}^{N-1} \\left( \\frac{\\partial x_i}{\\partial f_i} + I \\right)&quot;,&quot;id&quot;:&quot;AGKDNQOPOI&quot;}" data-component-name="LatexBlockToDOM"></div><p>When you expand this product, you get many terms, but one term is always I &#183; I &#183; I &#8230; = I. That&#8217;s the term where we picked I from every factor. No matter what the individual Jacobian terms look like &#8212; even if they&#8217;re tiny, even if they&#8217;re noisy &#8212; there&#8217;s always a path where the gradient flows directly from the loss to the earliest layer with a multiplier of 1. No shrinkage. No vanishing.</p><p>This is the <strong>gradient highway</strong>. The residual connections create a direct path from the output all the way back to the input, and the gradient can travel this path without being multiplied by any learned weight matrix. The individual blocks&#8217; Jacobian contributions add information on top of this highway, but they can never block it.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!P0qn!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!P0qn!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 424w, https://substackcdn.com/image/fetch/$s_!P0qn!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 848w, https://substackcdn.com/image/fetch/$s_!P0qn!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 1272w, https://substackcdn.com/image/fetch/$s_!P0qn!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!P0qn!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png" width="580" height="380" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/af774a64-9419-4909-8437-9293a07f5c76_580x380.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:380,&quot;width&quot;:580,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:37604,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!P0qn!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 424w, https://substackcdn.com/image/fetch/$s_!P0qn!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 848w, https://substackcdn.com/image/fetch/$s_!P0qn!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 1272w, https://substackcdn.com/image/fetch/$s_!P0qn!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Faf774a64-9419-4909-8437-9293a07f5c76_580x380.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h4>A Concrete Analogy</h4><p>Think of a company with 30 management layers between the CEO and the front-line workers. Without residual connections, information from the front line has to pass through every layer of management to reach the CEO. At each level, managers summarize, filter, and inevitably distort the message. By the time it reaches the top, the original information is barely recognizable. And when the CEO sends feedback down, the same 30-layer game of telephone distorts it beyond usefulness.</p><p>Residual connections are like giving every employee a direct email line to every other employee. The management layers still exist &#8212; they still do their processing, their summarizing, their value-added transformations. But the raw information also flows directly through, bypassing the chain entirely. A manager&#8217;s job is no longer to replace the information with a fully processed version; it&#8217;s to <strong>add their insights on top of the original</strong>. The original always survives.</p><h4>&#8220;Learning the Residual&#8221;</h4><p>There&#8217;s also a conceptual benefit beyond gradient flow. Without residual connections, each block must learn the complete transformation from input to desired output. With residual connections, each block only has to learn the <strong>difference</strong> between what the input already is and what it should be after this block&#8217;s processing:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;f_i(x) = x_{i+1} - x_i&quot;,&quot;id&quot;:&quot;CGQPRUBXVU&quot;}" data-component-name="LatexBlockToDOM"></div><p>This &#8220;difference&#8221; is typically a small, targeted modification &#8212; a subtle contextual update from attention, a small knowledge retrieval from the FFN. Learning a small modification to an already-good representation is much easier than learning the entire representation from scratch at every layer.</p><p>This also explains an empirical observation: in trained Transformers, the outputs of each block&#8217;s attention and FFN sub-layers tend to have <strong>much smaller magnitude</strong> than the residual stream they&#8217;re added to. The sub-layers make small, surgical updates. The residual stream carries the bulk of the information.</p><h4>Residual Connections in a Transformer Block</h4><p>In a pre-norm Transformer block, residual connections appear <strong>twice</strong> &#8212; once around the attention sub-layer and once around the FFN:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X' = X + \\mathrm{MultiHeadAttention}(\\mathrm{LayerNorm}(X))&quot;,&quot;id&quot;:&quot;UKRGYGUTBQ&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X'' = X' + \\mathrm{FFN}(\\mathrm{LayerNorm}(X'))&quot;,&quot;id&quot;:&quot;KBQMENZHVU&quot;}" data-component-name="LatexBlockToDOM"></div><p>In the first line, X (the block&#8217;s input) is added directly to the attention output. The attention mechanism gets to make its contribution, but it can never erase what was already in X &#8212; it can only add to it.</p><p>In the second line, X&#8217; (the post-attention representation) is added directly to the FFN output. Same principle: the FFN adds its processing, but the post-attention information always survives.</p><p>This means the <strong>residual stream</strong> &#8212; the main flow of information through the network &#8212; is never overwritten, only enriched. Each block deposits its contribution into the stream, like tributaries feeding into a river. The river (the residual stream) accumulates information from every block it has passed through.</p><h4>Residual Connections in the Backward Pass</h4><p>We already saw this in the worked example, but let&#8217;s make it explicit. At the end of block 2, we had:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X^{(2)} = X_{\\text{mid}}^{(2)} + \\mathrm{ffn\\_out}^{(2)}&quot;,&quot;id&quot;:&quot;ABGKMCNPJF&quot;}" data-component-name="LatexBlockToDOM"></div><p>When we computed the backward pass, the gradient on this sum <strong>split into both paths</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial X_{\\text{mid}}^{(2)}} {+}{=} \\frac{\\partial \\mathcal{L}}{\\partial X^{(2)}}, \\quad\n\\frac{\\partial \\mathcal{L}}{\\partial \\mathrm{ffn\\_out}^{(2)}} = \\frac{\\partial \\mathcal{L}}{\\partial X^{(2)}}&quot;,&quot;id&quot;:&quot;JECOUBSYTM&quot;}" data-component-name="LatexBlockToDOM"></div><p>The same gradient goes to both the skip path and the FFN path. The skip path gives X^(2)_mid its gradient immediately &#8212; no matrix multiplication, no activation function derivative, no potential for shrinkage. The FFN path also contributes a gradient, but it passes through W&#8322;, ReLU, W&#8321;, and LayerNorm, so it&#8217;s modified (and potentially shrunk). The total gradient on X^(2)_mid is the <strong>sum</strong> of both paths &#8212; the clean skip gradient plus the FFN-processed gradient.</p><p>This splitting happens at every residual connection. In a 2-block model like our example, the gradient from the loss reaches the embeddings via 2^4 = 16 different paths (two residual splits per block, two blocks, and we count each combination). In a 32-block model, there are 2^64 paths. The gradient doesn&#8217;t need all of them &#8212; it only needs the direct highway (picking the skip at every split) to ensure the signal reaches the earliest layers. All the other paths add information about how the intermediate transformations should change, but even if they all vanished, the highway alone would keep the network trainable.</p><p><strong>Layer normalization</strong> stabilizes the values flowing through the network by normalizing them to have zero mean and unit variance:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{LayerNorm}(x) = \\gamma \\cdot \\frac{x - \\mu}{\\sigma + \\epsilon} + \\beta&quot;,&quot;id&quot;:&quot;NIRXLITGUB&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where &#956; and &#963; are the mean and standard deviation computed across the dimensions of x (not across the batch), and &#947; and &#946; are learned scale and shift parameters. The small &#949; prevents division by zero.</p><h4>What Do &#947; and &#946; Do, and What Is &#8220;Identity Initialization&#8221;?</h4><p>The normalization step &#8212; subtracting the mean and dividing by the standard deviation &#8212; forces every vector to have zero mean and unit variance. But this might be <strong>too aggressive</strong>. Maybe the network actually needs some dimensions to have larger magnitudes than others, or maybe a slightly non-zero mean is useful for a particular layer&#8217;s computations. If we locked the output to exactly zero mean and unit variance, we&#8217;d be constraining the network&#8217;s expressiveness.</p><p>&#947; (gain) and &#946; (shift) are learnable per-dimension parameters that give the network the freedom to <strong>undo the normalization</strong> if that turns out to be beneficial. After normalizing to zero mean and unit variance, the network can learn to scale each dimension by &#947;_i and shift it by &#946;_i:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;y_i = \\gamma_i \\cdot \\hat{x}_i + \\beta_i&quot;,&quot;id&quot;:&quot;HBZKBRZSWF&quot;}" data-component-name="LatexBlockToDOM"></div><p>If the network learns &#947; = [1, 1, 1, 1] and &#946; = [0, 0, 0, 0], the output is exactly the normalized values &#8212; the normalization is fully applied. If it learns &#947;_i and &#946;_i that exactly reverse the normalization, the output equals the original input &#8212; as if LayerNorm weren&#8217;t there. In between, the network can learn any combination of &#8220;how much to normalize&#8221; per dimension.</p><p><strong>Identity initialization</strong> simply means starting &#947; = [1, 1, ..., 1] and &#946; = [0, 0, ..., 0], which makes the initial behavior &#8220;apply normalization fully.&#8221; This is a sensible starting point: normalize everything at the start, and let the network learn to relax this during training if it finds that helpful. It&#8217;s called &#8220;identity&#8221; because with these values, the &#947; &#183; x&#770; + &#946; step is the identity function on the already-normalized values &#8212; it passes them through unchanged.</p><p>In our worked example, we use &#947; = [1,1,1,1] and &#946; = [0,0,0,0] throughout, so the scale-and-shift step has no effect, and the LayerNorm output is just the normalized values. But in a real trained model, &#947; and &#946; would have drifted from their initial values to whatever the loss found useful.</p><h4>Why Is LayerNorm Needed?</h4><p>Without normalization, the values in the network can drift to very large or very small magnitudes as they pass through many layers, making optimization unstable. But &#8220;making optimization unstable&#8221; is vague &#8212; let&#8217;s be specific about what goes wrong.</p><p>In a deep network, each layer&#8217;s output is the input to the next layer. If a layer happens to produce values that are much larger than expected &#8212; say, vectors with magnitudes of 50 instead of 1 &#8212; the next layer&#8217;s matrix multiplications will produce even larger values. These large values then enter softmax (in attention) or activation functions, pushing them into regions where gradients are either vanishingly small (saturated softmax, where one position gets 99.99% of the attention) or numerically unstable (exploding values that overflow floating-point precision). Training becomes erratic: some gradient updates are near-zero, others are huge, and the optimizer struggles to make consistent progress.</p><p>LayerNorm prevents this by forcing every vector to have a controlled scale before it enters the next computation. It&#8217;s like recalibrating a measuring instrument after each measurement &#8212; no matter what the previous step produced, the next step always receives inputs in a well-behaved numerical range.</p><h4>Why Is LayerNorm Applied Multiple Times Per Block?</h4><p>In a pre-norm Transformer, LayerNorm appears <strong>twice per block</strong>: once before attention, and once before the FFN. This means a 32-block Transformer has 64 LayerNorms (plus one final LN before the output head &#8212; 65 total).</p><p>This isn&#8217;t redundant. Each sub-layer (attention and FFN) can produce outputs with very different scales. The attention output is a weighted average of value vectors (which can have unpredictable magnitude), and the FFN output passes through a nonlinear activation that can produce extreme values for some inputs. After each of these operations and its residual addition, the vector&#8217;s statistics have shifted &#8212; its mean and variance may have drifted from the well-behaved range. So we normalize again before the next computation.</p><p>Think of it this way: every time the representation passes through a learned transformation (attention or FFN), its numerical properties can drift. Every LayerNorm is a &#8220;checkpoint&#8221; that resets the scale to something manageable before the next transformation. Without these periodic resets, the drift would compound across blocks. By block 30 or 80, the values could be in a completely uncontrolled range, making training impossible.</p><p>There&#8217;s also a subtlety about where the LN sits. The residual connection adds the sub-layer&#8217;s output to the original input: x&#8217; = x + SubLayer(LN(x)). Because the residual path carries the un-normalized x directly, and each block adds a new contribution to it, the residual stream can grow in magnitude over many blocks. The LayerNorm before each sub-layer ensures that what the sub-layer <em>sees</em> as input is always well-scaled, even if the residual stream itself has drifted. This is one of the key reasons <strong>pre-norm</strong> (normalize before the sub-layer) works better than <strong>post-norm</strong> (normalize after the residual add): in pre-norm, the sub-layer always gets a clean, normalized input, and the residual stream remains free to accumulate information without being forced through normalization.</p><p>The original Transformer paper applied normalization after each sub-layer (<strong>post-norm</strong>):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;x&#8242;=LayerNorm(SubLayer(x)+x)&quot;,&quot;id&quot;:&quot;NIFDGOIVQB&quot;}" data-component-name="LatexBlockToDOM"></div><p>Most modern LLMs use <strong>pre-norm</strong> instead, applying normalization before each sub-layer:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;x&#8242;=SubLayer(LayerNorm(x))+x&quot;,&quot;id&quot;:&quot;GOHYBHXWHK&quot;}" data-component-name="LatexBlockToDOM"></div><p>Pre-norm tends to make training more stable, especially for very deep models, because the residual path remains &#8220;clean&#8221; &#8212; the unnormalized x flows directly through the skip connection without being modified by normalization.</p><h4>RMSNorm: A Modern Simplification</h4><p>While LayerNorm is what the original Transformer paper used, most modern LLMs &#8212; including LLaMA, Mistral, and their derivatives &#8212; have switched to a simplified variant called <strong>RMSNorm</strong> (Root Mean Square Layer Normalization), introduced by Zhang and Sennrich in 2019.</p><p>LayerNorm does two things: it subtracts the mean (centering the values around zero) and divides by the standard deviation (scaling them to unit variance). RMSNorm drops the mean-centering entirely and only rescales by the <strong>root mean square</strong> of the values:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{RMSNorm}(x) = \\gamma \\cdot \\frac{x}{\\mathrm{RMS}(x)}, \\quad \\text{where} \\quad\n\\mathrm{RMS}(x) = \\sqrt{\\frac{1}{d} \\sum_{i=1}^{d} x_i^2}&quot;,&quot;id&quot;:&quot;YENAAYIADG&quot;}" data-component-name="LatexBlockToDOM"></div><p>Notice what&#8217;s missing compared to LayerNorm: there&#8217;s no mean subtraction, and there&#8217;s no &#946; shift parameter. Just a division by RMS and a learnable scale &#947;.</p><p>The key insight from the RMSNorm paper was that most of LayerNorm&#8217;s benefit comes from the <strong>rescaling</strong> (controlling magnitude), not from the <strong>recentering</strong> (shifting the mean to zero). Removing the mean computation saves about 10-15% of the normalization cost per layer. That might sound modest, but in a 80-block model with two normalizations per block plus one at the output &#8212; 161 normalizations per forward pass &#8212; the savings compound. And since normalization is applied at every step, to every position, on every training example, even a small per-operation saving translates to real efficiency at scale.</p><p>Functionally, RMSNorm and LayerNorm behave very similarly: both keep values in a well-behaved numerical range, both prevent drift across deep layers, and both are applied in the same positions (pre-attention and pre-FFN in pre-norm architectures). The difference is purely in which statistics are computed. For the conceptual understanding we&#8217;re building, everything we said about why normalization is needed, why it appears multiple times per block, and why pre-norm beats post-norm applies equally to RMSNorm. It&#8217;s a drop-in replacement that trades a tiny amount of theoretical flexibility for a meaningful efficiency gain.</p><h3>A Complete Transformer Block</h3><p>Let&#8217;s now assemble these components into a single <strong>Transformer block</strong>. In a decoder-only model (GPT-style), one block looks like this:</p><ol><li><p><strong>Layer Norm</strong> on the input</p></li><li><p><strong>Masked Multi-Head Self-Attention</strong> (causal, so no peeking at future tokens)</p></li><li><p><strong>Add</strong> the residual (input + attention output)</p></li><li><p><strong>Layer Norm</strong> on the result</p></li><li><p><strong>Feedforward Network</strong> (expand, GELU, contract)</p></li><li><p><strong>Add</strong> the residual (step 3 output + FFN output)</p></li></ol><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!FcIt!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!FcIt!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 424w, https://substackcdn.com/image/fetch/$s_!FcIt!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 848w, https://substackcdn.com/image/fetch/$s_!FcIt!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 1272w, https://substackcdn.com/image/fetch/$s_!FcIt!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!FcIt!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png" width="500" height="560" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d868adb5-41d9-4420-886c-cfb851307104_500x560.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:560,&quot;width&quot;:500,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:38977,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!FcIt!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 424w, https://substackcdn.com/image/fetch/$s_!FcIt!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 848w, https://substackcdn.com/image/fetch/$s_!FcIt!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 1272w, https://substackcdn.com/image/fetch/$s_!FcIt!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd868adb5-41d9-4420-886c-cfb851307104_500x560.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Formally, for a block with input X:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X' = X + \\mathrm{MultiHeadAttention}(\\mathrm{LayerNorm}(X))&quot;,&quot;id&quot;:&quot;BITDIYQORG&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X'' = X' + \\mathrm{FFN}(\\mathrm{LayerNorm}(X'))&quot;,&quot;id&quot;:&quot;UYWSRFIICO&quot;}" data-component-name="LatexBlockToDOM"></div><p>That&#8217;s it. That&#8217;s the entire block. And a full Transformer is just this block <strong>repeated N times</strong>, one after another, with each block having its own independent set of learned weights (W_Q, W_K, W_V, W_O for attention; W&#8321;, W&#8322; for the FFN; &#947;, &#946; for each LayerNorm).</p><p>GPT-2 Small uses 12 blocks (larger GPT-2 variants go up to 48). GPT-3 uses 96. LLaMA 7B uses 32. LLaMA 70B uses 80. Each block refines the representation, building increasingly abstract and contextual understanding. The first few layers tend to handle syntax and local patterns. The middle layers capture semantic relationships and factual knowledge. The final layers prepare the representation for the specific prediction the model needs to make.</p><h3>Stacking N Blocks: Depth of Processing</h3><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!I7QF!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!I7QF!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 424w, https://substackcdn.com/image/fetch/$s_!I7QF!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 848w, https://substackcdn.com/image/fetch/$s_!I7QF!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 1272w, https://substackcdn.com/image/fetch/$s_!I7QF!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!I7QF!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png" width="450" height="650" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:650,&quot;width&quot;:450,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:51003,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!I7QF!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 424w, https://substackcdn.com/image/fetch/$s_!I7QF!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 848w, https://substackcdn.com/image/fetch/$s_!I7QF!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 1272w, https://substackcdn.com/image/fetch/$s_!I7QF!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F83b07d30-6dc6-425f-a238-7ef96c963186_450x650.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>When we say a Transformer has &#8220;N layers&#8221; or &#8220;N blocks&#8221; &#8212; GPT-2 has 12, GPT-3 has 96, LLaMA 7B has 32 &#8212; we mean that the attention-plus-FFN pattern is repeated N times <strong>sequentially in depth</strong>. The output of block 1 becomes the input of block 2. The output of block 2 becomes the input of block 3. And so on, up to block N. It&#8217;s exactly like the forward pass through hidden layers in Part 1&#8217;s MLP: data flows through one transformation after another, in order.</p><p>Crucially, each block has <strong>its own independent set of weights</strong>. Block 1 has its own W_Q^(1), W_K^(1), W_V^(1), W_O^(1), W_1^(1), W_2^(1), and LayerNorm parameters. Block 2 has a completely separate set &#8212; W_Q^(2), W_K^(2), W_V^(2), and so on. No weights are shared across blocks. Each block is a fresh set of learnable parameters. When we say a 7-billion-parameter model, most of those billions are simply the sum of the weights of every block stacked in the model, plus the embeddings.</p><p>Information flows through this stack in a single forward pass, always in the same direction: embeddings (plus positional info) &#8594; block 1 &#8594; block 2 &#8594; ... &#8594; block N &#8594; output head &#8594; softmax. Within each block, all positions of the sequence are processed <strong>in parallel</strong> &#8212; this is where the Transformer&#8217;s famous parallelism lives. The attention operation looks at every position simultaneously. But across blocks, there is strict sequential dependency: block 3 can&#8217;t start until block 2 has finished producing its output.</p><p>A useful mental model: each block is one round of &#8220;reading and thinking&#8221; about the sequence.</p><ul><li><p>Block 1 sees the raw embeddings (the superposition of all senses we discussed earlier) and produces an initial round of contextualization &#8212; mostly local syntax, morphological patterns, surface-level relationships.</p></li><li><p>Block 2 operates on block 1&#8217;s output. Its inputs are no longer raw embeddings but already-contextualized vectors. So block 2 can build on that first round, picking up slightly more abstract patterns &#8212; short-range dependencies, simple phrase structure.</p></li><li><p>By block 20 or 50 or 80, the vectors at each position have been enriched many times over. Each round of attention has pulled in additional information from across the sequence. Each FFN has added more processing per position. The representations have become deeply contextualized and highly abstract.</p></li></ul><p>Empirical studies of trained Transformers &#8212; via probing experiments, attention visualization, and mechanistic interpretability research &#8212; broadly support this picture: early blocks handle surface features and local patterns, middle blocks capture semantic composition and factual associations, and later blocks refine the representation for the specific output task. In an LLM, the final block&#8217;s output at the final position is what passes through the output head to generate the next token.</p><p>Depth matters because each block can only do a limited amount of work. A single block can mix information across positions once through attention, and apply one FFN transformation per position. To build up deep reasoning &#8212; tracking long chains of dependencies, performing implicit multi-step inference, integrating many pieces of evidence &#8212; you need many rounds of this. Depth gives the model the computational budget for genuinely complex thinking. This is why the most capable LLMs tend to be very deep (80 or more blocks) as well as wide (large d_model).</p><h3>Sensible Values: Real-World Configurations</h3><p>To anchor all this with concrete numbers, here are the configurations of some well-known models:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!moSK!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!moSK!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 424w, https://substackcdn.com/image/fetch/$s_!moSK!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 848w, https://substackcdn.com/image/fetch/$s_!moSK!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 1272w, https://substackcdn.com/image/fetch/$s_!moSK!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!moSK!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png" width="1394" height="838" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:838,&quot;width&quot;:1394,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:138605,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!moSK!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 424w, https://substackcdn.com/image/fetch/$s_!moSK!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 848w, https://substackcdn.com/image/fetch/$s_!moSK!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 1272w, https://substackcdn.com/image/fetch/$s_!moSK!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6387d98f-f6ae-4c87-90d4-29483e593a1f_1394x838.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>A few patterns worth noticing:</p><ol><li><p><strong>d_k per head stays fairly constant</strong> across model sizes &#8212; almost always 64 or 128. What changes as models grow is how many heads fit into d_model. This is a deliberate design choice: each head needs enough dimensions to form meaningful Q/K dot products, and below about 64 dimensions the attention signal gets noisy.</p></li><li><p><strong>FFN inner dimension is about 4&#215; d_model</strong>. This ratio has stayed remarkably consistent across almost all Transformer models. The FFN expands the representation to a 4&#215;-wider space for non-linear processing, then contracts back.</p></li><li><p><strong>Depth and width scale together as models grow</strong>, but not at the same rate. Going from GPT-2 Small (117M) to GPT-3 (175B) &#8212; a 1500&#215; increase in parameters &#8212; d_model grows 16&#215; while the number of blocks grows 8&#215;. The parameter count is dominated by the N &#215; d_model^2 product, which grows about 2000&#215;.</p></li><li><p><strong>Total parameters are dominated by the block weights</strong>. Each block contributes roughly 12 &#215; d_model^2 parameters (4&#215; from the Q/K/V/O attention matrices, and 8&#215; from the two FFN matrices, since one is d_model &#215; 4d_model and the other is 4d_model &#215; d_model). Multiply by N blocks and you have the bulk of the model&#8217;s parameters.</p></li></ol><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!RLbY!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!RLbY!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 424w, https://substackcdn.com/image/fetch/$s_!RLbY!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 848w, https://substackcdn.com/image/fetch/$s_!RLbY!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 1272w, https://substackcdn.com/image/fetch/$s_!RLbY!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!RLbY!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png" width="900" height="450" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:450,&quot;width&quot;:900,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:58853,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!RLbY!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 424w, https://substackcdn.com/image/fetch/$s_!RLbY!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 848w, https://substackcdn.com/image/fetch/$s_!RLbY!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 1272w, https://substackcdn.com/image/fetch/$s_!RLbY!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F307d058f-dc47-4c2d-a532-33dc7523612c_900x450.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>There's no universal law dictating these exact ratios &#8212; they emerged from years of empirical experimentation. The Kaplan et al. (2020) and Hoffmann et al. (2022, <strong>the "Chinchilla" paper</strong>) scaling laws explored how these hyperparameters should scale together for optimal performance at a given compute budget, and modern models are configured following those findings. But fundamentally, every extra block adds another round of attention and FFN processing, every extra head adds another way to attend in parallel within a block, and the choice of how to allocate compute between depth and width is a design tradeoff.</p><h3>Grouped Query Attention (GQA)</h3><p>In the multi-head attention we described, every head has its own W_Q, W_K, and W_V. If a model has 64 heads, that means 64 independent query matrices, 64 independent key matrices, and 64 independent value matrices. This is the standard setup &#8212; called <strong>Multi-Head Attention (MHA)</strong>.</p><p>But there&#8217;s a practical problem that shows up during inference (text generation). When the model generates text token by token, it needs to keep the key and value vectors from all previous tokens in memory &#8212; this is the <strong>KV-cache</strong> (which we&#8217;ll cover properly in Part 3). With 64 heads, each storing key and value vectors for every position in the sequence, across every block in the model, the KV-cache grows enormous. For a 70-billion parameter model generating a long document, the KV-cache alone can consume tens of gigabytes of GPU memory.</p><p><strong>Grouped Query Attention (GQA)</strong>, introduced by Ainslie et al. in 2023, addresses this by observing something surprising: the model doesn&#8217;t actually need 64 independent sets of keys and values. It still benefits from 64 independent sets of <em>queries</em> (each query head learns a different &#8220;question to ask&#8221;), but the keys and values can be shared across groups of query heads without significantly hurting quality.</p><p>Here&#8217;s how it works mechanically. Instead of 64 query heads and 64 KV heads, GQA might use 64 query heads but only 8 KV heads. The 64 query heads are divided into 8 groups of 8. All 8 query heads in a group share the same key and value projections:</p><ul><li><p>Group 1: query heads 1&#8211;8 all use W_K^1 and W_V^1</p></li><li><p>Group 2: query heads 9&#8211;16 all use W_K^2 and W_V^2</p></li><li><p>...</p></li><li><p>Group 8: query heads 57&#8211;64 all use W_K^8 and W_V^8</p></li></ul><p>Each query head still has its own W_Q &#8212; so each head still asks its own question. But when computing K and V, eight different query heads look at the same keys and values. The attention scores and outputs are still computed per query head (since Q differs), so each head can still produce a different attention pattern. They just do it from a shared set of keys and values.</p><p>This sits on a spectrum between two extremes:</p><ul><li><p><strong>Multi-Head Attention (MHA)</strong>: every head has its own Q, K, V. Maximum expressiveness, maximum KV-cache size. This is what the original Transformer paper proposed.</p></li><li><p><strong>Multi-Query Attention (MQA)</strong>: every head has its own Q, but all heads share a single K and single V. Minimum KV-cache size, but some quality degradation. This was proposed by Shazeer in 2019.</p></li><li><p><strong>Grouped Query Attention (GQA)</strong>: a middle ground. Heads are grouped, and each group shares K/V. You choose how many KV heads to use &#8212; anywhere between 1 (MQA) and H (MHA).</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!3RBI!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!3RBI!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 424w, https://substackcdn.com/image/fetch/$s_!3RBI!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 848w, https://substackcdn.com/image/fetch/$s_!3RBI!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 1272w, https://substackcdn.com/image/fetch/$s_!3RBI!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!3RBI!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png" width="880" height="450" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:450,&quot;width&quot;:880,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:91753,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!3RBI!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 424w, https://substackcdn.com/image/fetch/$s_!3RBI!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 848w, https://substackcdn.com/image/fetch/$s_!3RBI!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 1272w, https://substackcdn.com/image/fetch/$s_!3RBI!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F56ac7dca-bfc0-438a-ab0b-d00761b251e8_880x450.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Why does sharing keys and values work? The intuition is that the &#8220;what do I contain?&#8221; (key) and &#8220;what do I give?&#8221; (value) roles are less diverse across heads than the &#8220;what am I looking for?&#8221; (query) role. Many heads ask different questions about the same input, but the input <em>is</em> the same &#8212; the key and value representations don&#8217;t need as much per-head specialization. Different query heads can extract different information from the same key-value pairs simply by asking different questions.</p><p>The practical impact is significant. LLaMA 2 70B uses 64 query heads but only 8 KV heads (8 groups of 8). This reduces the KV-cache memory by 8&#215; compared to standard MHA &#8212; from &#8220;barely fits on a high-end GPU&#8221; to &#8220;comfortably fits.&#8221; The quality loss is negligible in practice, and in some benchmarks GQA models actually perform slightly better than MHA models, likely because the shared keys and values act as a mild form of regularization.</p><p>GQA has become the standard for large models. LLaMA 2 (70B), LLaMA 3, Mistral, and most recent open-source architectures use it. For smaller models where the KV-cache isn&#8217;t a bottleneck, standard MHA is still common. The choice depends on the inference constraints you&#8217;re designing for.</p><h3>The Output Head</h3><p>After passing through all N Transformer blocks, the model has a sequence of vectors &#8212; one per input token &#8212; each of dimension d_model. For next-token prediction, we only care about the <strong>last position</strong> (or, during training, every position, since we predict the next token at every position simultaneously).</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!oMMo!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!oMMo!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 424w, https://substackcdn.com/image/fetch/$s_!oMMo!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 848w, https://substackcdn.com/image/fetch/$s_!oMMo!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 1272w, https://substackcdn.com/image/fetch/$s_!oMMo!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!oMMo!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png" width="760" height="490" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:490,&quot;width&quot;:760,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:63131,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!oMMo!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 424w, https://substackcdn.com/image/fetch/$s_!oMMo!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 848w, https://substackcdn.com/image/fetch/$s_!oMMo!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 1272w, https://substackcdn.com/image/fetch/$s_!oMMo!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4e96d936-9923-43ca-9aa6-d75b403e91df_760x490.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>This gives us <strong>five training signals from one forward pass</strong>. The five per-position cross-entropy losses are averaged into a <strong>single scalar</strong>, and then a <strong>single backward pass</strong> propagates all five error signals at once. This works because the gradient of an average of losses is just the average of the individual gradients: where the five error signals reach a shared weight (and nearly every weight is shared across positions), their contributions simply add up. So one traversal of the network accumulates all five corrections &#8212; you do <em>not</em> run backpropagation five separate times. Without this trick, training would be 5&#215; slower: you'd need a separate forward and backward pass for each prefix length.</p><p>The output vector passes through a final <strong>linear layer</strong> that projects from d_model to the full vocabulary size:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{logits} = \\mathbf{x}_{\\text{final}} \\cdot W_{\\text{head}} + b&quot;,&quot;id&quot;:&quot;UUFWTMDFDQ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where W_head has shape (d_model &#215; V), with V being the vocabulary size. The result is a vector of V <strong>logits</strong> &#8212; the raw, unnormalized scores we introduced earlier &#8212; one per token in the vocabulary.</p><p>Many models use <strong>weight tying</strong>: the output projection matrix W_head is set to be the transpose of the embedding matrix W_E. This makes intuitive sense &#8212; the embedding matrix maps from vocabulary space to model space, and the output projection maps from model space back to vocabulary space. They&#8217;re doing inverse operations, so sharing the weights (a) reduces the total parameter count and (b) creates a geometric consistency where producing a token is literally &#8220;finding the token whose embedding is most similar to the output vector.&#8221;</p><p>The logits are then passed through a <strong>softmax</strong> function to produce a probability distribution:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;P(t_i \\mid t_1, \\ldots, t_n) = \\frac{e^{z_i}}{\\sum_{j=1}^{V} e^{z_j}}&quot;,&quot;id&quot;:&quot;AUQPCDUFWA&quot;}" data-component-name="LatexBlockToDOM"></div><p>This gives the model's predicted probability for every token in the vocabulary being the next token. During training, this distribution is compared against the actual next token using <strong>cross-entropy loss</strong> (generalizing the binary cross-entropy we saw in Part 1 to a multi-class setting):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L} = - \\sum_{c=1}^{V} y_c \\log(\\hat{p}_c)&quot;,&quot;id&quot;:&quot;CZCODXMAOB&quot;}" data-component-name="LatexBlockToDOM"></div><p>Since the true next token is a one-hot vector (all zeros except for the correct token), this simplifies to:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L} = -\\log(\\hat{p}_{\\text{correct}})&quot;,&quot;id&quot;:&quot;IHYXSYGWAI&quot;}" data-component-name="LatexBlockToDOM"></div><p>Which is just the negative log probability the model assigned to the correct next token. If the model was confident and correct (high hat{p}_correct), the loss is small. If the model was confident and wrong, the loss is enormous. Same principle as the binary case in Part 1, extended to 50,000+ classes.</p><h4>Generating Text: Sampling Strategies</h4><p>During inference (text generation), the model produces a probability distribution over the vocabulary and must select a single token. The simplest approach is <strong>greedy decoding</strong>: always pick the token with the highest probability. But this often produces repetitive, generic text.</p><p>More sophisticated strategies include:</p><p><strong>Temperature</strong>: before softmax, divide the logits by a temperature parameter T:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;P(t_i) = \\frac{e^{z_i / T}}{\\sum_j e^{z_j / T}}&quot;,&quot;id&quot;:&quot;JVAMEAMOEP&quot;}" data-component-name="LatexBlockToDOM"></div><ul><li><p>T = 1: standard probabilities</p></li><li><p>T &lt; 1: distribution becomes sharper (more confident, more deterministic)</p></li><li><p>T &gt; 1: distribution becomes flatter (more random, more creative)</p></li></ul><p><strong>Top-k sampling</strong>: sort tokens by probability, keep only the top k tokens, redistribute their probabilities, and sample from this truncated distribution.</p><p><strong>Top-p (nucleus) sampling</strong>: instead of a fixed k, keep the smallest set of tokens whose cumulative probability exceeds p (e.g., 0.9). This adapts to the model&#8217;s confidence &#8212; sometimes only 5 tokens might cover 90% of the probability mass, other times it might be 500.</p><p>In practice, most systems combine temperature with top-p sampling for a good balance of coherence and variety.</p><h3>The Complete Picture: From Text In to Prediction Out</h3><p>We&#8217;ve now covered every component of the Transformer individually. Before we move to the worked example, let&#8217;s step back and see the full architecture as a single, coherent pipeline. This is the view you should hold in your head &#8212; the complete journey that a piece of text takes from raw characters to a probability distribution over the next token.</p><p><strong>Step 1: Tokenization.</strong> Raw text enters the system as a string of characters. The tokenizer (BPE, SentencePiece, or similar) breaks it into a sequence of integer token IDs. &#8220;The cat sat on the&#8221; might become [1, 4523, 8891, 312, 1]. This step is purely mechanical &#8212; no neural network is involved. The tokenizer is a fixed algorithm, trained once on a large text corpus, then frozen. Its job is to convert the infinite variety of text into a finite vocabulary of integer IDs that the model can work with.</p><p><strong>Step 2: Embedding lookup.</strong> Each token ID is used to index into the embedding matrix W_E, pulling out a dense vector of d_model dimensions. Token ID 4523 retrieves row 4523 of W_E. The sequence of integers becomes a sequence of vectors &#8212; a matrix of shape (sequence_length, d_model). This is where discrete symbols cross the bridge into continuous space.</p><p><strong>Step 3: Positional encoding.</strong> Position information is injected, either by adding sinusoidal vectors, adding learned positional embeddings, or (in models using RoPE) by rotating the vectors inside the attention computation. After this step, two instances of the same token at different positions have different vector representations, so the model can distinguish word order.</p><p><strong>Step 4: The Transformer blocks.</strong> This is the core of the model, where all the &#8220;thinking&#8221; happens. The sequence of vectors passes through N blocks stacked in series &#8212; block 1&#8217;s output feeds into block 2, block 2&#8217;s output feeds into block 3, and so on up to block N. Each block performs the same two-step pattern:</p><ul><li><p><strong>Attention sub-layer</strong>: every position looks at every previous position (via causal masking), computes relevance scores through the Q/K/V mechanism across multiple heads, gathers information from relevant positions, and combines it through the output projection W_O. This is the &#8220;communication&#8221; step &#8212; positions exchange information.</p></li><li><p><strong>FFN sub-layer</strong>: each position independently passes through a small MLP (the gate/up/down projections in modern models, or the simpler W&#8321;/W&#8322; in the original). This is the &#8220;thinking&#8221; step &#8212; each position processes the information it gathered.</p></li></ul><p>Both sub-layers are wrapped in LayerNorm (or RMSNorm) and residual connections, ensuring stable training and clean gradient flow. Each block has its own independent weights &#8212; no sharing between blocks.</p><p>After N blocks, the representation at each position has been enriched by N rounds of attention and N rounds of per-position processing. Early blocks tend to capture surface-level patterns (syntax, local context), middle blocks capture semantic relationships and factual knowledge, and later blocks refine the representation toward the specific prediction the model needs to make.</p><p><strong>Step 5: Final normalization.</strong> One last LayerNorm (or RMSNorm) is applied to the output of the final block, ensuring the values are in a well-behaved numerical range before the output computation.</p><p><strong>Step 6: Output head.</strong> The vector at the last position &#8212; the position that&#8217;s predicting what comes next &#8212; is projected from d_model dimensions to vocabulary-size dimensions through the output head matrix. With weight tying, this is just the transpose of the embedding matrix: the dot product of the final vector with each token&#8217;s embedding row produces one logit per token. Tokens whose embeddings are most aligned with the final hidden vector get the highest logits.</p><p><strong>Step 7: Softmax.</strong> The logits are converted to a probability distribution via softmax. Every token in the vocabulary now has a probability between 0 and 1, and all probabilities sum to 1. The model has answered the question: &#8220;Given everything I&#8217;ve seen so far, how likely is each possible next token?&#8221;</p><p><strong>Step 8: Sampling or loss.</strong> During inference (text generation), a token is sampled from this distribution using temperature, top-k, or top-p strategies, and the process repeats from step 1 with the new token appended. During training, the probability assigned to the <em>actual</em> next token is compared against 1.0 via cross-entropy loss, producing the scalar error signal that drives backpropagation through every parameter in the pipeline.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!GCXU!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!GCXU!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 424w, https://substackcdn.com/image/fetch/$s_!GCXU!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 848w, https://substackcdn.com/image/fetch/$s_!GCXU!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 1272w, https://substackcdn.com/image/fetch/$s_!GCXU!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!GCXU!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png" width="950" height="280" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:280,&quot;width&quot;:950,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:65708,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!GCXU!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 424w, https://substackcdn.com/image/fetch/$s_!GCXU!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 848w, https://substackcdn.com/image/fetch/$s_!GCXU!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 1272w, https://substackcdn.com/image/fetch/$s_!GCXU!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2faf439e-5278-496b-a810-4ae0e8e02200_950x280.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>That&#8217;s the entire architecture. Eight steps, in order, every time. The model sees text, converts it to vectors, processes those vectors through many rounds of attention and feedforward computation, and produces a probability distribution over what comes next. Everything we covered in the preceding sections &#8212; embeddings, positional encoding, Q/K/V projections, multi-head attention, causal masking, the FFN and its variants, residual connections, LayerNorm &#8212; slots into this pipeline at a specific, well-defined point. There are no hidden steps, no additional mechanisms we haven&#8217;t discussed.</p><p>Now let&#8217;s see it in action with real numbers.</p><h2>IV. An End-to-End Worked Example</h2><p>Now let&#8217;s see the whole thing in action &#8212; one complete forward pass through all eight steps, then one complete backward pass, with every number computed explicitly. Just like Part 1, we&#8217;ll follow every calculation so that nothing is left as a black box.</p><p>To make this tractable by hand, we&#8217;ll use a deliberately tiny model. Real LLMs have billions of parameters and thousands of dimensions; ours will have dozens of parameters and single-digit dimensions. But the mechanics are identical &#8212; what changes with scale is the size of the matrices, not the operations themselves.</p><h3>Setup</h3><p>Our tiny Transformer will have:</p><ul><li><p><strong>Vocabulary size</strong> V = 8</p></li><li><p><strong>Model dimension</strong> d_model = 4</p></li><li><p><strong>Number of heads per block</strong> H = 2, so d_k = d_v = d_model/H = 2</p></li><li><p><strong>Number of blocks</strong> N = 2</p></li><li><p><strong>FFN inner dimension</strong> d_ff = 8 (2&#215; d_model; real models use 4&#215;, but we&#8217;ll keep it small)</p></li><li><p><strong>Activation</strong> in the FFN: ReLU (matching Part 1 for continuity)</p></li><li><p><strong>Weight tying</strong>: the output projection W_head equals W_E^T (so the embedding matrix is used at both input and output)</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!SCbd!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!SCbd!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 424w, https://substackcdn.com/image/fetch/$s_!SCbd!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 848w, https://substackcdn.com/image/fetch/$s_!SCbd!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 1272w, https://substackcdn.com/image/fetch/$s_!SCbd!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!SCbd!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png" width="600" height="700" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/dc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:700,&quot;width&quot;:600,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:72266,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!SCbd!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 424w, https://substackcdn.com/image/fetch/$s_!SCbd!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 848w, https://substackcdn.com/image/fetch/$s_!SCbd!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 1272w, https://substackcdn.com/image/fetch/$s_!SCbd!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdc702ed6-71c6-4163-a1d1-2b95dd792f18_600x700.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Our vocabulary:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!WXnr!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!WXnr!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 424w, https://substackcdn.com/image/fetch/$s_!WXnr!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 848w, https://substackcdn.com/image/fetch/$s_!WXnr!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 1272w, https://substackcdn.com/image/fetch/$s_!WXnr!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!WXnr!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png" width="1372" height="746" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/bd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:746,&quot;width&quot;:1372,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:43821,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!WXnr!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 424w, https://substackcdn.com/image/fetch/$s_!WXnr!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 848w, https://substackcdn.com/image/fetch/$s_!WXnr!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 1272w, https://substackcdn.com/image/fetch/$s_!WXnr!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd2da4f7-5556-4221-88a9-7f06cb823dbe_1372x746.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>Input sentence:</strong> &#8220;the cat sat on the&#8221; &#8594; token IDs [0, 1, 2, 3, 0] <strong>Target next token:</strong> &#8220;mat&#8221; &#8594; token ID 5</p><p>We want the model to learn that after &#8220;the cat sat on the,&#8221; the likely next word is &#8220;mat.&#8221; Of course, with random weights it won&#8217;t predict this well at first. What we&#8217;ll see is exactly one forward pass (to make a prediction and compute loss), then one backward pass (to compute gradients), then one weight update.</p><h3>Step 1: From Tokens to Vectors</h3><p>The first step is to convert each token ID into a vector via the embedding matrix W_E (shape V &#215; d_model = 8 &#215; 4). Its initial values (chosen deliberately simple for this example):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_E =\n\\begin{bmatrix}\n0.1 &amp; 0.2 &amp; 0.0 &amp; 0.1 \\\\\n0.3 &amp; 0.1 &amp; 0.2 &amp; 0.0 \\\\\n0.0 &amp; 0.3 &amp; 0.1 &amp; 0.2 \\\\\n0.2 &amp; 0.0 &amp; 0.3 &amp; 0.1 \\\\\n0.4 &amp; 0.2 &amp; 0.1 &amp; 0.1 \\\\\n0.1 &amp; 0.4 &amp; 0.2 &amp; 0.3 \\\\\n0.0 &amp; 0.1 &amp; 0.4 &amp; 0.2 \\\\\n0.2 &amp; 0.2 &amp; 0.2 &amp; 0.2\n\\end{bmatrix}\n\\quad\n\\begin{array}{l}\n\\text{the} \\\\\n\\text{cat} \\\\\n\\text{sat} \\\\\n\\text{on} \\\\\n\\text{dog} \\\\\n\\text{mat} \\\\\n\\text{ran} \\\\\n\\text{and}\n\\end{array}&quot;,&quot;id&quot;:&quot;JDGJCTUUYC&quot;}" data-component-name="LatexBlockToDOM"></div><p>Row 0 is the vector for &#8220;the,&#8221; row 5 is the vector for &#8220;mat,&#8221; and so on.</p><p>For our input sequence [0, 1, 2, 3, 0], we look up rows 0, 1, 2, 3, and 0 again:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;E =\n\\begin{bmatrix}\n0.1 &amp; 0.2 &amp; 0.0 &amp; 0.1 \\\\\n0.3 &amp; 0.1 &amp; 0.2 &amp; 0.0 \\\\\n0.0 &amp; 0.3 &amp; 0.1 &amp; 0.2 \\\\\n0.2 &amp; 0.0 &amp; 0.3 &amp; 0.1 \\\\\n0.1 &amp; 0.2 &amp; 0.0 &amp; 0.1\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;BFJCNQVWDT&quot;}" data-component-name="LatexBlockToDOM"></div><p>Five rows for five positions. Notice that positions 0 and 4 are identical &#8212; both are the vector for &#8220;the.&#8221; Without positional information, the model would see these two positions as indistinguishable, and the whole sequence would be order-invariant.</p><p>To fix this, we add a positional encoding W_P (chosen simply, purely for this example):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_P =\n\\begin{bmatrix}\n0.00 &amp; 0.00 &amp; 0.00 &amp; 0.00 \\\\\n0.10 &amp; 0.05 &amp; 0.00 &amp; 0.00 \\\\\n0.15 &amp; 0.10 &amp; 0.00 &amp; 0.00 \\\\\n0.20 &amp; 0.15 &amp; 0.00 &amp; 0.00 \\\\\n0.25 &amp; 0.20 &amp; 0.00 &amp; 0.00\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;AKTQETHXWW&quot;}" data-component-name="LatexBlockToDOM"></div><p>Adding E + W_P gives us X^(0), the input to the first Transformer block:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X^{(0)} =\n\\begin{bmatrix}\n0.10 &amp; 0.20 &amp; 0.00 &amp; 0.10 \\\\\n0.40 &amp; 0.15 &amp; 0.20 &amp; 0.00 \\\\\n0.15 &amp; 0.40 &amp; 0.10 &amp; 0.20 \\\\\n0.40 &amp; 0.15 &amp; 0.30 &amp; 0.10 \\\\\n0.35 &amp; 0.40 &amp; 0.00 &amp; 0.10\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;JXRPQNLPIO&quot;}" data-component-name="LatexBlockToDOM"></div><h3>Step 2: Layer Normalization (Pre-Attention)</h3><p>Inside block 1, the first operation is a LayerNorm applied to X^(0). LayerNorm normalizes each row independently, computing the mean and standard deviation <strong>across the 4 dimensions of that row</strong>, then rescaling.</p><p>For row 0 of X^(0) (the vector [0.10, 0.20, 0.00, 0.10]):</p><p>Mean: &#956; = (0.10 + 0.20 + 0.00 + 0.10)/4 = 0.10</p><p>Variance: &#963;^2 = [(0)^2 + (0.10)^2 + (-0.10)^2 + (0)^2]/4 = 0.005</p><p>Standard deviation: &#963; = &#8730;{0.005 + &#949;} &#8776; 0.0708 (using &#949; = 10^-5)</p><p>Normalized: (x - &#956;)/&#963; = [0, 0.10, -0.10, 0]/0.0708 = [0, 1.413, -1.413, 0]</p><p>Then scaled and shifted: &#947; &#8857; x&#770; + &#946;. With &#947; = [1,1,1,1] and &#946; = [0,0,0,0] (the identity initialization we&#8217;re using throughout), the output is just [0, 1.413, -1.413, 0].</p><p>You might wonder what this scale-and-shift step is doing, given that with these values it has no visible effect. We covered &#947; and &#946; in detail in the architecture section, but it&#8217;s worth reinforcing here in the context of actual numbers.</p><p>The normalization step forcefully rescaled this vector to have zero mean and unit variance. But maybe the attention mechanism that comes next would work better if certain dimensions had slightly different magnitudes &#8212; perhaps dimension 2 should be amplified, or the whole vector needs a small positive shift. &#947; and &#946; are learnable parameters (just like weights and biases) that let the network undo, modify, or preserve the normalization as it sees fit. With &#947; = [1,1,1,1] and &#946; = [0,0,0,0], we&#8217;re at the <strong>identity initialization</strong>: the network starts by fully applying the normalization, and during training, &#947; and &#946; will drift to whatever values the loss function finds useful. In a trained model these values are typically close to but not exactly at their initial values &#8212; the network has learned a slight per-dimension rescaling that helps downstream computations.</p><p>In our worked example, since we&#8217;re showing one forward and backward pass before any training has happened, &#947; and &#946; are still at their initial values and the scale-and-shift is a no-op. But they&#8217;re there, they&#8217;re learnable, and they receive gradients just like every other parameter in the network.</p><p>Applying the same to all five rows:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X^{(0)}_{\\mathrm{LN}} =\n\\begin{bmatrix}\n0.000 &amp; 1.413 &amp; -1.413 &amp; 0.000 \\\\\n1.485 &amp; -0.262 &amp; 0.087 &amp; -1.310 \\\\\n-0.549 &amp; 1.646 &amp; -0.988 &amp; -0.110 \\\\\n1.362 &amp; -0.734 &amp; 0.524 &amp; -1.153 \\\\\n0.822 &amp; 1.121 &amp; -1.270 &amp; -0.673\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;VMESMQXVCB&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is what feeds into the multi-head attention.</p><h3>Step 3: Multi-Head Self-Attention &#8212; First Head</h3><p>Before we proceed with calculations, let&#8217;s settle a question that&#8217;s been hanging in the air: <strong>is a single head the same as &#8220;self-attention&#8221;?</strong></p><p>Yes. Self-attention is defined by <strong>where the queries, keys, and values come from</strong>: in self-attention, all three are computed from the same sequence. (In <em>cross-attention</em>, used in the original Transformer&#8217;s decoder, queries come from the decoder and keys/values come from the encoder &#8212; the decoder attends to the encoder&#8217;s output.) Self-attention is the mechanism we&#8217;ve been describing all along, and it doesn&#8217;t say anything about how many heads are involved. A single-head self-attention is already self-attention &#8212; it&#8217;s just self-attention with H = 1 parallel computation. The Q/K/V mechanism with one head IS self-attention.</p><p><strong>Multi-head self-attention</strong> means running several self-attention computations in parallel &#8212; each with its own W_Q, W_K, W_V matrices &#8212; and combining their outputs. Each individual head is a full self-attention operation in its own right, just working in a lower-dimensional subspace. Let&#8217;s see this concretely by computing head 1 in detail first, then head 2, then seeing how they combine.</p><h4>Head 1: Computing Q, K, V</h4><p>Head 1 has its own three weight matrices (shape d_model &#215; d_k = 4 &#215; 2). Initial values:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_Q^{(1,1)} =\n\\begin{bmatrix}\n0.5 &amp; 0.1 \\\\\n0.1 &amp; 0.4 \\\\\n0.2 &amp; 0.3 \\\\\n0.0 &amp; 0.2\n\\end{bmatrix}\n,\\quad\nW_K^{(1,1)} =\n\\begin{bmatrix}\n0.4 &amp; 0.0 \\\\\n0.2 &amp; 0.5 \\\\\n0.1 &amp; 0.3 \\\\\n0.3 &amp; 0.1\n\\end{bmatrix}\n,\\quad\nW_V^{(1,1)} =\n\\begin{bmatrix}\n0.3 &amp; 0.2 \\\\\n0.0 &amp; 0.4 \\\\\n0.5 &amp; 0.1 \\\\\n0.2 &amp; 0.3\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;GQJUIUYPPI&quot;}" data-component-name="LatexBlockToDOM"></div><p>(Superscript (1,1) means &#8220;block 1, head 1.&#8221;)</p><p>We multiply the normalized input X^(0)_LN by each of these to get Q, K, V for head 1:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;Q^{(1,1)} = X^{(0)}_{\\mathrm{LN}} W_Q^{(1,1)} =\n\\begin{bmatrix}\n-0.141 &amp; 0.141 \\\\\n0.734 &amp; -0.192 \\\\\n-0.307 &amp; 0.285 \\\\\n0.713 &amp; -0.230 \\\\\n0.269 &amp; 0.015\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;MJKIPKCYBD&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each row is the query vector for one position &#8212; a 2-dimensional vector (because d_k = 2). Position 0&#8217;s query is [-0.141, 0.141], position 1&#8217;s is [0.734, -0.192], and so on.</p><p>Let me show the first-row computation explicitly so the matrix multiplication is fully transparent. For position 0: query = [0.000, 1.413, -1.413, 0.000] &#183; W_Q^(1,1) gives two numbers:</p><ul><li><p>First component: 0.000 &#183; 0.5 + 1.413 &#183; 0.1 + (-1.413) &#183; 0.2 + 0.000 &#183; 0.0 = 0.141 - 0.283 = -0.141 &#10003;</p></li><li><p>Second component: 0.000 &#183; 0.1 + 1.413 &#183; 0.4 + (-1.413) &#183; 0.3 + 0.000 &#183; 0.2 = 0.565 - 0.424 = 0.141 &#10003;</p></li></ul><p>Similarly:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;K^{(1,1)} =\n\\begin{bmatrix}\n0.141 &amp; 0.283 \\\\\n0.157 &amp; -0.236 \\\\\n-0.022 &amp; 0.516 \\\\\n0.105 &amp; -0.325 \\\\\n0.224 &amp; 0.112\n\\end{bmatrix}\n,\\quad\nV^{(1,1)} =\n\\begin{bmatrix}\n-0.706 &amp; 0.424 \\\\\n0.227 &amp; -0.192 \\\\\n-0.680 &amp; 0.417 \\\\\n0.440 &amp; -0.314 \\\\\n-0.523 &amp; 0.284\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;OJWFMEABIK&quot;}" data-component-name="LatexBlockToDOM"></div><p>So every position now has its own query vector, its own key vector, and its own value vector &#8212; all in a 2-dimensional subspace specific to head 1.</p><h4>Head 1: Attention Scores</h4><p>Attention scores come from Q K^T / &#8730;{d_k}. With d_k = 2, we divide by &#8730;{2} &#8776; 1.414.</p><p>The dot product between position 4&#8217;s query and position 0&#8217;s key:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{q}_4 \\cdot \\mathbf{k}_0 = 0.269 \\cdot 0.141 + 0.015 \\cdot 0.283 = 0.038 + 0.004 = 0.042&quot;,&quot;id&quot;:&quot;YLMPDBHXXQ&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;score(4,0)=0.042/1.414=0.030&quot;,&quot;id&quot;:&quot;YHIIZNTQFO&quot;}" data-component-name="LatexBlockToDOM"></div><p>Doing this for every pair (i, j) gives the full score matrix:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{scores}^{(1,1)} =\n\\begin{bmatrix}\n0.014 &amp; -0.039 &amp; 0.054 &amp; -0.043 &amp; -0.011 \\\\\n0.035 &amp; 0.114 &amp; -0.082 &amp; 0.099 &amp; 0.101 \\\\\n0.026 &amp; -0.082 &amp; 0.109 &amp; -0.088 &amp; -0.026 \\\\\n0.025 &amp; 0.118 &amp; -0.095 &amp; 0.106 &amp; 0.095 \\\\\n0.030 &amp; 0.027 &amp; 0.001 &amp; 0.017 &amp; 0.044\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;RYQBCFALXQ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each row is how much a query at that position &#8220;liked&#8221; each key. Row 4, for example, shows how the query for the last &#8220;the&#8221; scored against every key from position 0 to 4. All numbers are small, reflecting the fact that this model has random weights &#8212; there are no strong preferences yet.</p><h4>Head 1: Causal Mask and Softmax</h4><p>Because we&#8217;re building a decoder-only (autoregressive) model, each position must only attend to previous positions (and itself). We apply a causal mask &#8212; adding -&#8734; to all upper-triangular entries:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{scores}^{(1,1)}_{\\mathrm{masked}} =\n\\begin{bmatrix}\n0.014 &amp; -\\infty &amp; -\\infty &amp; -\\infty &amp; -\\infty \\\\\n0.035 &amp; 0.114 &amp; -\\infty &amp; -\\infty &amp; -\\infty \\\\\n0.026 &amp; -0.082 &amp; 0.109 &amp; -\\infty &amp; -\\infty \\\\\n0.025 &amp; 0.118 &amp; -0.095 &amp; 0.106 &amp; -\\infty \\\\\n0.030 &amp; 0.027 &amp; 0.001 &amp; 0.017 &amp; 0.044\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;KVLHRTNPHO&quot;}" data-component-name="LatexBlockToDOM"></div><p>Now we apply softmax row by row. For row 1, [0.035, 0.114, -&#8734;, -&#8734;, -&#8734;]:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{softmax}(0.035, 0.114) =\n\\left[\n\\frac{e^{0.035}}{e^{0.035} + e^{0.114}},\n\\frac{e^{0.114}}{e^{0.035} + e^{0.114}}\n\\right]\n\\\\\n=\n\\left[\n\\frac{1.036}{2.157},\n\\frac{1.121}{2.157}\n\\right]\n=\n[0.480, 0.520]&quot;,&quot;id&quot;:&quot;SDQCBSAROA&quot;}" data-component-name="LatexBlockToDOM"></div><p>(The -&#8734; entries softmax to 0.) So position 1&#8217;s query attends 48% to position 0 and 52% to position 1 (itself).</p><p>Doing this for all rows:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;A^{(1,1)} =\n\\begin{bmatrix}\n1.000 &amp; 0 &amp; 0 &amp; 0 &amp; 0 \\\\\n0.480 &amp; 0.520 &amp; 0 &amp; 0 &amp; 0 \\\\\n0.335 &amp; 0.301 &amp; 0.364 &amp; 0 &amp; 0 \\\\\n0.246 &amp; 0.270 &amp; 0.218 &amp; 0.266 &amp; 0 \\\\\n0.201 &amp; 0.201 &amp; 0.196 &amp; 0.199 &amp; 0.204\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;XLNMKKADMS&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the attention matrix for head 1. Row 4 tells us that the last "the" is attending roughly uniformly to all five positions (about 20% each). That's expected &#8212; with random weights, nothing has been learned to make the model prefer any particular past position. After training, we'd see much spikier distributions.</p><h4>Head 1: Output</h4><p>The output of head 1 is A^(1,1) V^(1,1). For the last row (position 4):</p><p>out4(1,1)&#8203;= 0.201&#8901;[&#8722;0.706,0.424]+0.201&#8901;[0.227,&#8722;0.192]+0.196&#8901;[&#8722;0.680,0.417]+0.199&#8901;[0.440,&#8722;0.314]+0.204&#8901;[&#8722;0.523,0.284]</p><p>Computing each term and summing:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{out}_4^{(1,1)} = [-0.249, 0.124]&quot;,&quot;id&quot;:&quot;TOAVZXMYRG&quot;}" data-component-name="LatexBlockToDOM"></div><p>For all positions:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{out}^{(1,1)} =\n\\begin{bmatrix}\n-0.706 &amp; 0.424 \\\\\n-0.221 &amp; 0.104 \\\\\n-0.416 &amp; 0.236 \\\\\n-0.143 &amp; 0.060 \\\\\n-0.249 &amp; 0.124\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;NGSRYLNSVN&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is a (5, 2) matrix: five positions, each now represented in head 1&#8217;s 2-dimensional output space. That&#8217;s all head 1 does. It&#8217;s a complete self-attention computation in a 2-dimensional subspace.</p><h3>Step 4: Multi-Head Self-Attention &#8212; Second Head (in Parallel)</h3><p>Here&#8217;s where the &#8220;multi-head&#8221; part matters. Head 2 does <strong>exactly the same kind of computation</strong> as head 1, but with its own independent weight matrices:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_Q^{(1,2)} =\n\\begin{bmatrix}\n0.2 &amp; 0.3 \\\\\n0.4 &amp; 0.1 \\\\\n0.0 &amp; 0.5 \\\\\n0.3 &amp; 0.0\n\\end{bmatrix}\n,\\quad\nW_K^{(1,2)} =\n\\begin{bmatrix}\n0.1 &amp; 0.4 \\\\\n0.3 &amp; 0.0 \\\\\n0.2 &amp; 0.2 \\\\\n0.5 &amp; 0.1\n\\end{bmatrix}\n,\\quad\nW_V^{(1,2)} =\n\\begin{bmatrix}\n0.0 &amp; 0.5 \\\\\n0.3 &amp; 0.2 \\\\\n0.4 &amp; 0.0 \\\\\n0.1 &amp; 0.3\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;ZFYDUCZBKS&quot;}" data-component-name="LatexBlockToDOM"></div><p>Note: these are <strong>different matrices</strong> from head 1&#8217;s. That&#8217;s the whole point. Both heads see the same input X^(0)_LN, but they project it into different subspaces. Because the projections are different, the queries, keys, and values are different, and therefore the resulting attention patterns and outputs are different. This gives the model two independent &#8220;perspectives&#8221; on the same sequence at the same depth.</p><p>Running the same calculation pipeline &#8212; Q^(1,2) = X^(0)_LN W_Q^(1,2), and so on &#8212; head 2 produces its own attention weights and output:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;A^{(1,2)} =\n\\begin{bmatrix}\n1.000 &amp; 0 &amp; 0 &amp; 0 &amp; 0 \\\\\n0.413 &amp; 0.587 &amp; 0 &amp; 0 &amp; 0 \\\\\n0.376 &amp; 0.222 &amp; 0.402 &amp; 0 &amp; 0 \\\\\n0.189 &amp; 0.314 &amp; 0.176 &amp; 0.320 &amp; 0 \\\\\n0.232 &amp; 0.163 &amp; 0.242 &amp; 0.162 &amp; 0.201\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;EYOOGZUJMB&quot;}" data-component-name="LatexBlockToDOM"></div><p>Compare this to head 1&#8217;s attention matrix. Row 1 here is [0.413, 0.587]; in head 1 it was [0.480, 0.520]. Different weights, different patterns. With only random initialization the differences are modest, but after training, different heads typically learn to focus on very different things &#8212; one head might track syntactic agreement, another might resolve coreferences, another might focus on nearby tokens, and so on. The capacity for diversity comes from having separate W_Q, W_K, W_V per head.</p><p>Head 2&#8217;s output:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{out}^{(1,2)} =\n\\begin{bmatrix}\n-0.141 &amp; 0.283 \\\\\n-0.161 &amp; 0.291 \\\\\n-0.057 &amp; 0.181 \\\\\n-0.107 &amp; 0.211 \\\\\n-0.108 &amp; 0.237\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;YKMJQPHPES&quot;}" data-component-name="LatexBlockToDOM"></div><h4>About &#8220;Running in Parallel&#8221;</h4><p>Note the word <strong>parallel</strong>. Both heads operate on the same input X^(0)_LN. Neither depends on the other&#8217;s output. On a GPU, you&#8217;d compute head 1 and head 2 simultaneously on different cores. They&#8217;re independent computations that share the same input &#8212; that&#8217;s all &#8220;parallel&#8221; means here.</p><p>And critically: <strong>they are not averaged</strong>. This is a common misconception. Many people assume multi-head attention combines the heads by averaging their outputs. It doesn&#8217;t. The heads are <strong>concatenated</strong>.</p><h3>Step 5: Concatenation and Output Projection</h3><p>Head 1 output is shape (5, 2). Head 2 output is shape (5, 2). To combine them, we concatenate along the last dimension, giving a matrix of shape (5, 4):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{concat}^{(1)} =\n\\begin{bmatrix}\n-0.706 &amp; 0.424 &amp; -0.141 &amp; 0.283 \\\\\n-0.221 &amp; 0.104 &amp; -0.161 &amp; 0.291 \\\\\n-0.416 &amp; 0.236 &amp; -0.057 &amp; 0.181 \\\\\n-0.143 &amp; 0.060 &amp; -0.107 &amp; 0.211 \\\\\n-0.249 &amp; 0.124 &amp; -0.108 &amp; 0.237\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;DUIMUCBUAF&quot;}" data-component-name="LatexBlockToDOM"></div><p>Look at the structure: the first 2 columns are head 1&#8217;s output, the last 2 columns are head 2&#8217;s output. They sit side by side. Each row now has 4 numbers &#8212; the first 2 from head 1, the second 2 from head 2.</p><p>Why concatenate instead of averaging? Because the heads operate in different subspaces. Averaging would force their outputs to live in the same 2D space, which would defeat the purpose of having multiple heads. Concatenation keeps each head&#8217;s contribution distinct.</p><p>Now comes the key combining step: a learned output projection W_O^(1) of shape (d_model, d_model) = (4, 4):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_O^{(1)} =\n\\begin{bmatrix}\n0.4 &amp; 0.1 &amp; 0.2 &amp; 0.0 \\\\\n0.0 &amp; 0.3 &amp; 0.1 &amp; 0.4 \\\\\n0.2 &amp; 0.2 &amp; 0.3 &amp; 0.1 \\\\\n0.1 &amp; 0.0 &amp; 0.2 &amp; 0.3\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;DUCXOZHGNO&quot;}" data-component-name="LatexBlockToDOM"></div><p>The matrix multiplication concat^(1) &#183; W_O^(1) mixes all 4 concatenated values of each row (2 from each head) into a new 4-dimensional representation:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{attn\\_out}^{(1)} =\n\\begin{bmatrix}\n-0.283 &amp; 0.028 &amp; -0.085 &amp; 0.240 \\\\\n-0.092 &amp; -0.023 &amp; -0.024 &amp; 0.113 \\\\\n-0.160 &amp; 0.018 &amp; -0.040 &amp; 0.143 \\\\\n-0.058 &amp; -0.018 &amp; -0.013 &amp; 0.077 \\\\\n-0.098 &amp; -0.009 &amp; -0.023 &amp; 0.110\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;VPHWIEMLHX&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the final output of the multi-head attention sub-layer. W_O^(1) is also a learnable parameter &#8212; it learns how to best combine the heads. In a sense, W_O learns which aspects of which heads to emphasize when producing the final output. The heads produce diverse views; W_O chooses how to fuse them.</p><h3>Step 6: Residual Connection and FFN</h3><p>The residual connection adds the attention output back to the original input (the pre-LN input, X^(0), not the post-LN input):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X_{\\text{mid}}^{(1)} = X^{(0)} + \\mathrm{attn\\_out}^{(1)} =\n\\begin{bmatrix}\n-0.183 &amp; 0.228 &amp; -0.085 &amp; 0.340 \\\\\n0.308 &amp; 0.127 &amp; 0.176 &amp; 0.113 \\\\\n-0.010 &amp; 0.418 &amp; 0.060 &amp; 0.343 \\\\\n0.342 &amp; 0.132 &amp; 0.288 &amp; 0.177 \\\\\n0.252 &amp; 0.391 &amp; -0.023 &amp; 0.210\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;CWXPOVAQXJ&quot;}" data-component-name="LatexBlockToDOM"></div><p>This residual is essential &#8212; it means gradients during the backward pass have a direct path from X^(1)_mid back to X^(0), bypassing the attention mechanism entirely. Without this, deep Transformers would be very difficult to train.</p><p>Next, another LayerNorm (normalizing X^(1)_mid to zero mean and unit variance at each position), then the feedforward network. This is where the MLP from Part 1 shows up inside the Transformer.</p><p>The FFN has two weight matrices and two bias vectors:</p><ul><li><p>W_1^(1) of shape (4, 8): takes the 4-dimensional vector at each position and expands it to 8 dimensions</p></li><li><p>b_1^(1): bias of length 8</p></li><li><p>W_2^(1) of shape (8, 4): contracts the 8-dimensional representation back to 4 dimensions</p></li><li><p>b_2^(1): bias of length 4</p></li></ul><p>This is exactly the structure of Part 1&#8217;s MLP: input layer (4 neurons) &#8594; hidden layer (8 neurons) &#8594; output layer (4 neurons). The hidden layer has twice as many neurons as the input, which is the &#8220;expand&#8221; step. The output layer contracts back to the original size.</p><p>Let's trace position 4 (the last "the") through the FFN step by step.</p><p>After LayerNorm 1b, position 4's vector is:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{x}_4^{(\\mathrm{LN})} = [0.299, 1.231, -1.547, 0.017]&quot;,&quot;id&quot;:&quot;NLNPYGNFWN&quot;}" data-component-name="LatexBlockToDOM"></div><p><strong>First layer (expand)</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{h}_4 = \\mathbf{x}_4^{(\\mathrm{LN})} \\cdot W_1^{(1)} + b_1^{(1)}&quot;,&quot;id&quot;:&quot;BMZGNRMOQE&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the same computation we did for every hidden neuron in Part 1: for each of the 8 neurons in the hidden layer, compute the weighted sum of all 4 inputs plus the bias. The result is an 8-dimensional vector:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{h}_4 = [0.004, 0.525, -0.302, 0.220, 0.467, -0.435, 0.193, -0.060]&quot;,&quot;id&quot;:&quot;GQNZVREONQ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each number is one neuron&#8217;s pre-activation value. Neuron 1 computed 0.525 (a moderately positive response to this input), neuron 2 computed -0.302 (a negative response), neuron 4 computed 0.467, and so on.</p><p><strong>Activation (ReLU)</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{h}_4^{(\\mathrm{act})} = \\mathrm{ReLU}(\\mathbf{h}_4) = [0.004, 0.525, 0, 0.220, 0.467, 0, 0.193, 0]&quot;,&quot;id&quot;:&quot;LAXPSGLTUU&quot;}" data-component-name="LatexBlockToDOM"></div><p>ReLU zeroes out the negative values. Neurons 2, 5, and 7 (which had values -0.302, -0.435, -0.060) are now dead &#8212; they contribute nothing to the output. Only neurons 0, 1, 3, 4, and 6 are &#8220;active.&#8221; This is the sparse activation pattern: 5 out of 8 neurons fire for this particular input. A different input would activate a different subset.</p><p>This is identical to what happened in Part 1 when hidden neuron h3 had a pre-activation of -0.057 and ReLU set it to 0. Same mechanism, just with more neurons.</p><p><strong>Second layer (contract)</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{ffn\\_out}_4 = \\mathbf{h}_4^{(\\mathrm{act})} \\cdot W_2^{(1)} + b_2^{(1)} = [0.205, 0.349, 0.183, 0.311]&quot;,&quot;id&quot;:&quot;UTRXZJROSP&quot;}" data-component-name="LatexBlockToDOM"></div><p>Only the 5 active neurons contribute to this sum. Each active neuron&#8217;s contribution is determined by its activation value multiplied by its column in W&#8322;. The dead neurons multiply by zero and contribute nothing. The result is a 4-dimensional vector &#8212; back to d_model &#8212; representing the FFN&#8217;s processed output for this position.</p><p>The full FFN output for all five positions:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{ffn\\_out}^{(1)} =\n\\begin{bmatrix}\n0.128 &amp; 0.349 &amp; 0.092 &amp; 0.429 \\\\\n0.329 &amp; 0.323 &amp; 0.444 &amp; 0.220 \\\\\n0.152 &amp; 0.371 &amp; 0.092 &amp; 0.446 \\\\\n0.338 &amp; 0.380 &amp; 0.403 &amp; 0.250 \\\\\n0.205 &amp; 0.349 &amp; 0.183 &amp; 0.311\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;XIMGSDRHPG&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each row was processed independently through the same W_1^(1), ReLU, W_2^(1) &#8212; each with different activations, different sets of neurons firing, but the same weights. This is one complete MLP pass, applied identically to each of the five positions.</p><p>After the FFN, another residual add:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X^{(1)} = X_{\\text{mid}}^{(1)} + \\mathrm{ffn\\_out}^{(1)} =\n\\begin{bmatrix}\n-0.054 &amp; 0.577 &amp; 0.007 &amp; 0.770 \\\\\n0.637 &amp; 0.450 &amp; 0.620 &amp; 0.333 \\\\\n0.142 &amp; 0.789 &amp; 0.152 &amp; 0.789 \\\\\n0.681 &amp; 0.512 &amp; 0.691 &amp; 0.426 \\\\\n0.457 &amp; 0.739 &amp; 0.161 &amp; 0.520\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;SFIWWCWWLX&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the final output of block 1 &#8212; five positions, each enriched with contextual information from attention and further processed by the FFN. X^(1) is what enters block 2.</p><h3>Step 7: Block 2</h3><p>Block 2 has the <strong>same structure</strong> as block 1 &#8212; LayerNorm, multi-head attention (same 2 heads), residual, LayerNorm, FFN, residual &#8212; but with its <strong>own independent set of weights</strong>. Everything we did in steps 2 through 6 repeats, but with different numbers.</p><p>I won&#8217;t walk through all the block 2 calculations step by step (they&#8217;re mechanically identical to block 1), but the final output is:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X^{(2)} =\n\\begin{bmatrix}\n0.151 &amp; 1.016 &amp; 0.189 &amp; 1.117 \\\\\n1.075 &amp; 0.529 &amp; 1.187 &amp; 0.487 \\\\\n0.385 &amp; 1.270 &amp; 0.342 &amp; 1.172 \\\\\n1.138 &amp; 0.588 &amp; 1.268 &amp; 0.582 \\\\\n0.649 &amp; 1.161 &amp; 0.351 &amp; 0.888\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;ZXGOVESMJX&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each row is the representation at that position, now having passed through <strong>two complete rounds</strong> of attention and FFN processing. Compared to the embeddings we started with, these vectors have been enriched by information from all previous positions (via attention) and further processed by nonlinear transformations (via the FFNs).</p><h3>Step 8: Final LayerNorm, Output Head, Softmax</h3><p>After all blocks, a final LayerNorm is applied:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;X_{\\text{final}}^{(2)} =\n\\begin{bmatrix}\n-1.039 &amp; 0.884 &amp; -0.954 &amp; 1.109 \\\\\n0.812 &amp; -0.924 &amp; 1.169 &amp; -1.058 \\\\\n-0.947 &amp; 1.110 &amp; -1.045 &amp; 0.882 \\\\\n0.781 &amp; -0.979 &amp; 1.197 &amp; -0.999 \\\\\n-0.378 &amp; 1.335 &amp; -1.377 &amp; 0.420\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;UYXZCYAOVH&quot;}" data-component-name="LatexBlockToDOM"></div><p>For next-token prediction, we only care about the <strong>last position</strong> &#8212; position 4, whose vector is h = [-0.378, 1.335, -1.377, 0.420]. This is what the model has built up through the entire network as its final understanding of &#8220;what should come next after &#8216;the cat sat on the&#8217;&#8221;.</p><p>Now we convert this 4-dimensional vector into logits over the vocabulary using the output head. With weight tying, W_head = W_E^T, so the logit for each token t is simply h &#183; W_E[t] &#8212; the dot product between the final hidden vector and that token&#8217;s embedding row.</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{logits} = \\mathbf{h} \\cdot W_E^T&quot;,&quot;id&quot;:&quot;MSLQLYXZSY&quot;}" data-component-name="LatexBlockToDOM"></div><p>Computing each:</p><ul><li><p>logit(the) = (-0.378)(0.1) + (1.335)(0.2) + (-1.377)(0.0) + (0.420)(0.1) = -0.038 + 0.267 + 0 + 0.042 = 0.271</p></li><li><p>logit(cat) = (-0.378)(0.3) + (1.335)(0.1) + (-1.377)(0.2) + (0.420)(0.0) = -0.113 + 0.134 - 0.275 = -0.255</p></li><li><p>logit(mat) = (-0.378)(0.1) + (1.335)(0.4) + (-1.377)(0.2) + (0.420)(0.3) = -0.038 + 0.534 - 0.275 + 0.126 = 0.347</p></li></ul><p>Full logits:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!t05K!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!t05K!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 424w, https://substackcdn.com/image/fetch/$s_!t05K!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 848w, https://substackcdn.com/image/fetch/$s_!t05K!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 1272w, https://substackcdn.com/image/fetch/$s_!t05K!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!t05K!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png" width="1376" height="750" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/e2f93116-e594-4463-9d66-617680ba92c1_1376x750.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:750,&quot;width&quot;:1376,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:58854,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!t05K!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 424w, https://substackcdn.com/image/fetch/$s_!t05K!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 848w, https://substackcdn.com/image/fetch/$s_!t05K!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 1272w, https://substackcdn.com/image/fetch/$s_!t05K!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f93116-e594-4463-9d66-617680ba92c1_1376x750.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Softmax converts these to probabilities. Let me show the first few calculations:</p><p>e^0.271 &#8776; 1.311 </p><p>e^-0.255 &#8776; 0.775 </p><p>e^0.347 &#8776; 1.415 </p><p>e^-0.447 &#8776; 0.639 </p><p>e^0.020 &#8776; 1.020 </p><p>e^0.347 &#8776; 1.415 </p><p>e^-0.333 &#8776; 0.717 </p><p>e^0.000 = 1.000</p><p>Sum = 8.292. </p><p>Dividing each:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!kXeo!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!kXeo!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 424w, https://substackcdn.com/image/fetch/$s_!kXeo!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 848w, https://substackcdn.com/image/fetch/$s_!kXeo!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 1272w, https://substackcdn.com/image/fetch/$s_!kXeo!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!kXeo!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png" width="1374" height="746" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:746,&quot;width&quot;:1374,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:59272,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!kXeo!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 424w, https://substackcdn.com/image/fetch/$s_!kXeo!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 848w, https://substackcdn.com/image/fetch/$s_!kXeo!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 1272w, https://substackcdn.com/image/fetch/$s_!kXeo!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff9d2a922-ada3-45ac-877c-163ea9e9029f_1374x746.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>The model assigns probability <strong>0.171</strong> to the correct answer &#8220;mat.&#8221; That&#8217;s barely above uniform (1/8 = 0.125). With random weights, this is about what we&#8217;d expect &#8212; the model has no reason to prefer &#8220;mat&#8221; over &#8220;sat&#8221; (note they&#8217;re tied at 0.171), and it gives reasonable probability to everything. Tokens like &#8220;on&#8221; and &#8220;ran&#8221; get pushed slightly down.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!m1KN!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!m1KN!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 424w, https://substackcdn.com/image/fetch/$s_!m1KN!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 848w, https://substackcdn.com/image/fetch/$s_!m1KN!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 1272w, https://substackcdn.com/image/fetch/$s_!m1KN!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!m1KN!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png" width="920" height="400" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:400,&quot;width&quot;:920,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:57766,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!m1KN!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 424w, https://substackcdn.com/image/fetch/$s_!m1KN!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 848w, https://substackcdn.com/image/fetch/$s_!m1KN!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 1272w, https://substackcdn.com/image/fetch/$s_!m1KN!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8a90eb76-c9df-4126-a4e6-593e893696a8_920x400.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3>Step 9: The Loss</h3><p>Cross-entropy loss against the target (token 5, &#8220;mat&#8221;):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L} = -\\log(p_{\\text{mat}}) = -\\log(0.171) = 1.768&quot;,&quot;id&quot;:&quot;VZNOMLOAVB&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is our scalar loss value. A loss of 1.768 means the model is &#8220;surprised&#8221; by the correct answer &#8212; specifically, it assigned only 17.1% probability, which is mediocre. Ideally the model would assign near 100% probability to &#8220;mat,&#8221; giving a loss near 0. For comparison, a uniform model would give -log(1/8) = log(8) &#8776; 2.08, so we&#8217;re doing slightly better than random &#8212; but not much.</p><p>One simplification to flag: as we saw in <em>The Output Head</em>, a real training step computes a prediction at <strong>every</strong> position and averages all of those cross-entropy losses into one scalar. Here we're tracing only the <strong>last</strong> position's prediction ("the cat sat on the" &#8594; "mat") so the arithmetic stays tractable by hand. The mechanics are identical &#8212; the only difference is whether the single scalar at the top of the backward pass is one position's loss or the mean of all of them. Everything that follows works the same way regardless.</p><h3>Step 10: The Backward Pass &#8212; Gradient at the Output</h3><p>Now we trace the chain rule backward through the entire network. The first gradient is the derivative of the loss with respect to the logits. For softmax followed by cross-entropy, there&#8217;s a beautifully clean formula:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathrm{logit}_i} = p_i - y_i&quot;,&quot;id&quot;:&quot;HNKUYMJWZL&quot;}" data-component-name="LatexBlockToDOM"></div><p>where p_i is the predicted probability and y_i is 1 if i is the target, else 0. For our prediction:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ZlVO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ZlVO!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 424w, https://substackcdn.com/image/fetch/$s_!ZlVO!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 848w, https://substackcdn.com/image/fetch/$s_!ZlVO!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 1272w, https://substackcdn.com/image/fetch/$s_!ZlVO!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!ZlVO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png" width="1380" height="744" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/a00fac15-4883-4752-a058-da68337ad1f4_1380x744.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:744,&quot;width&quot;:1380,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:77114,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ZlVO!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 424w, https://substackcdn.com/image/fetch/$s_!ZlVO!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 848w, https://substackcdn.com/image/fetch/$s_!ZlVO!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 1272w, https://substackcdn.com/image/fetch/$s_!ZlVO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa00fac15-4883-4752-a058-da68337ad1f4_1380x744.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Pause to notice what this says. The gradient is <strong>negative for the target</strong> (&#8221;mat&#8221; gets -0.829) and <strong>positive for all the other tokens</strong>. In gradient descent, we move in the negative gradient direction, so:</p><ul><li><p>The logit for &#8220;mat&#8221; will go <strong>up</strong> (we subtract a negative &#8594; add)</p></li><li><p>The logits for all other tokens will go <strong>down</strong></p></li></ul><p>Which is exactly what we want: make the correct answer more probable, make the incorrect answers less probable. That single -0.829 on &#8220;mat&#8221; is the error signal that&#8217;s about to ripple backward through every matrix in the network.</p><h3>Step 11: From Logits Back to the Final Hidden State</h3><p>The logits were computed as logits = h &#183; W_E^T. Using the matrix calculus rule for this kind of product:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}} = \\frac{\\partial \\mathcal{L}}{\\partial \\mathrm{logits}} \\cdot W_E&quot;,&quot;id&quot;:&quot;VIHXGYTOMN&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is a vector-matrix product: an 8-dimensional gradient dotted into the 8&#215;4 matrix W_E, giving a 4-dimensional result. Working through:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}} = [0.050, -0.182, -0.036, -0.138]&quot;,&quot;id&quot;:&quot;HBXZLDIBER&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the gradient telling us how the final hidden vector should change to reduce the loss. It says: decrease component 1 (the second dimension, which had a large positive value of 1.335 in h), increase nothing significantly, decrease component 3. In other words, the network&#8217;s final hidden representation needs to move a bit away from where it currently sits.</p><p><strong>But also &#8212; and this is important &#8212; we get a gradient on W_E itself directly from this step</strong>, through the weight tying. Since &#8220;mat&#8221; is the target, its embedding row receives a large gradient pushing it toward h:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial W_E[\\text{mat}]} =\n\\frac{\\partial \\mathcal{L}}{\\partial \\mathrm{logit}_{\\text{mat}}} \\cdot \\mathbf{h}\n= -0.829 \\cdot [-0.378, 1.335, -1.377, 0.420]&quot;,&quot;id&quot;:&quot;ZWZRJHYHEZ&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;= [0.313, -1.107, 1.142, -0.349]&quot;,&quot;id&quot;:&quot;ICHUPUHMFW&quot;}" data-component-name="LatexBlockToDOM"></div><p>Every other row of W_E also receives a small gradient (their logits had positive gradients, so their rows get pushed in the opposite direction from h). We&#8217;ll come back to these when we combine the gradients on W_E from both ends of the network.</p><h3>Step 12: Backward Through the Final LayerNorm</h3><p>Next, the gradient flows back through the final LayerNorm. LayerNorm&#8217;s backward pass is a bit involved (it couples all dimensions of a row through the mean and variance calculations), but the key point is: we can compute the gradient on X^(2) from the gradient on X^(2)_final. Since only the last position contributes to our loss (the loss is computed only from position 4&#8217;s prediction), gradients at positions 0&#8211;3 are zero, and the gradient at position 4 flows through:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial X_{\\text{pos }4}^{(2)}} = [0.337, -0.052, -0.176, -0.109]&quot;,&quot;id&quot;:&quot;EQBPIUDXFW&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the gradient entering the top of block 2.</p><h3>Step 13: Backward Through Block 2</h3><p>At the end of block 2, we had X^(2) = X^(2)_mid + ffn_out^(2) (the residual). Because this was a sum, tthe gradient flows to both paths unchanged &#8212; each path receives the full upstream gradient:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial X_{\\text{mid}}^{(2)}} {+}{=} \\frac{\\partial \\mathcal{L}}{\\partial X^{(2)}}, \\quad\n\\frac{\\partial \\mathcal{L}}{\\partial \\mathrm{ffn\\_out}^{(2)}} = \\frac{\\partial \\mathcal{L}}{\\partial X^{(2)}}&quot;,&quot;id&quot;:&quot;WNVIVJWBYK&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the &#8220;residual highway&#8221; at work: X^(2)_mid gets the gradient directly (through the skip connection) AND through the FFN path once we propagate through the FFN.</p><p><strong>Through the FFN.</strong> The FFN&#8217;s forward pass was ffn_out = ReLU(X^(2)_mid,LN W_1^(2) + b_1^(2)) &#183; W_2^(2) + b_2^(2). Now we trace the chain rule backward through each step &#8212; exactly as we did for the student-exam MLP in Part 1, because that&#8217;s what this is: backpropagation through an MLP.</p><p><strong>Step A: Gradient on W_2^(2) and b_2^(2).</strong> The last operation was ffn_out = h_act &#183; W_2 + b_2. This is a linear layer, and the gradient on its weight matrix is the same formula we used in Part 1 &#8212; the product of the upstream gradient and the layer&#8217;s input:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial W_2^{(2)}} = \\mathbf{h}_{\\text{act}}^{\\top} \\cdot \\frac{\\partial \\mathcal{L}}{\\partial \\mathrm{ffn\\_out}}&quot;,&quot;id&quot;:&quot;ZFTMSTLTRS&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the transpose of the post-ReLU activations (shape 8 &#215; 5) multiplied by the incoming gradient (shape 5 &#215; 4), giving an 8 &#215; 4 gradient matrix. Every entry tells us: &#8220;how much should this particular weight in W&#8322; change to reduce the loss?&#8221;</p><p>For the bias: the gradient is simply the sum of the incoming gradients across all positions &#8212; exactly as in Part 1 where the bias gradient equaled the delta.</p><p><strong>Step B: Propagate through W_2^(2).</strong> To continue the chain backward, we need the gradient on the post-ReLU hidden activations:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}_{\\text{act}}} = \\frac{\\partial \\mathcal{L}}{\\partial \\mathrm{ffn\\_out}} \\cdot \\left(W_2^{(2)}\\right)^{\\top}&quot;,&quot;id&quot;:&quot;LMTYNDYBVJ&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the incoming gradient (shape 5 &#215; 4) multiplied by W_2^T (shape 4 &#215; 8), giving a 5 &#215; 8 result &#8212; one 8-dimensional gradient vector per position. This is the chain rule at work: to find how the hidden layer&#8217;s activations affected the loss, we multiply by the weights that connected them to the output.</p><p>For position 4, this gives:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}_{\\text{act},4}} = [0.003, -0.003, 0.060, -0.060, 0.011, -0.008, 0.058, -0.071]&quot;,&quot;id&quot;:&quot;REDPRWKGFJ&quot;}" data-component-name="LatexBlockToDOM"></div><p>All 8 neurons receive a gradient &#8212; the loss is telling each one how it should have been different.</p><p><strong>Step C: Backward through ReLU.</strong> This is where dead neurons become visible. ReLU&#8217;s derivative is trivially simple:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{ReLU}'(z) =\n\\begin{cases}\n1 &amp; \\text{if } z > 0 \\\\\n0 &amp; \\text{if } z \\le 0\n\\end{cases}&quot;,&quot;id&quot;:&quot;RPJBUTCTKL&quot;}" data-component-name="LatexBlockToDOM"></div><p>For position 4, the pre-activation values were:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathbf{h}_4 = [0.004, 0.525, -0.302, 0.220, 0.467, -0.435, 0.193, -0.060]&quot;,&quot;id&quot;:&quot;PRZTVTXGEQ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Neurons 2, 5, and 7 had negative pre-activations (bolded). ReLU set them to zero in the forward pass, and now ReLU's derivative sets their gradients to zero in the backward pass:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}_4} = [0.003, -0.003, 0, -0.060, 0.011, 0, 0.058, 0]&quot;,&quot;id&quot;:&quot;BHHIYTPGIY&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is exactly what happened in Part 1 when hidden neuron h2 had a pre-activation of -0.061, ReLU killed it, and all its gradients became zero. Same mechanism: <strong>dead neurons don&#8217;t learn</strong>. They contributed nothing to the output, so they receive no error signal. The gradient passes through only the 5 neurons that were &#8220;alive&#8221; (had positive pre-activations).</p><p><strong>Step D: Gradient on W_1^(2) and b_1^(2).</strong> The first FFN layer was h = X_LN &#183; W_1 + b_1. Same formula again:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial W_1^{(2)}} = X_{\\mathrm{LN}}^{\\top} \\cdot \\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}}&quot;,&quot;id&quot;:&quot;PZQRQLZEUT&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial b_1^{(2)}} = \\sum_{\\text{positions}} \\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}}&quot;,&quot;id&quot;:&quot;IZMTGFXHRO&quot;}" data-component-name="LatexBlockToDOM"></div><p>And to continue backward to the LayerNorm input:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial X_{\\mathrm{LN}}} = \\frac{\\partial \\mathcal{L}}{\\partial \\mathbf{h}} \\cdot \\left(W_1^{(2)}\\right)^{\\top}&quot;,&quot;id&quot;:&quot;NFIVVXEIKE&quot;}" data-component-name="LatexBlockToDOM"></div><p>The LayerNorm backward then transforms this into the gradient on X^(2)_mid from the FFN path.</p><p>We add this to the gradient from the skip connection to get the full gradient on X^(2)_mid.</p><p>The entire backward pass through the FFN is step-for-step identical to the backpropagation we computed in Part 1: gradient on the output weight matrix, propagate through the output weights, apply the activation function&#8217;s derivative (zeroing dead neurons), gradient on the input weight matrix, propagate through the input weights. The Transformer&#8217;s FFN backward pass IS the MLP backward pass from Part 1. Every block has one of these, and every block&#8217;s FFN gets its own set of weight gradients &#8212; one for each of W&#8321;, W&#8322;, b&#8321;, b&#8322; &#8212; computed by the same chain rule we&#8217;ve been using all along.</p><p><strong>Through the attention.</strong> Now X^(2)_mid = X^(1) + attn_out^(2). Again the residual splits. Propagating through attention:</p><ul><li><p>From the attention output equation (attn_out = concat &#183; W_O), we get the gradient on W_O and on the concatenated head outputs.</p></li><li><p>The concatenation splits back: the first d_k columns of the gradient go to head 1, the last d_k columns to head 2.</p></li><li><p>For each head, we then backprop through out^(h) = A^(h) V^(h), the softmax, the scaled dot product, and finally the Q/K/V projections.</p></li></ul><p>The gradients on block 2&#8217;s head 1 Q/K/V matrices:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial W_Q^{(2,1)}} =\n\\begin{bmatrix}\n0.0001 &amp; -0.0002 \\\\\n-0.0014 &amp; 0.0043 \\\\\n0.0016 &amp; -0.005 \\\\\n-0.0003 &amp; 0.0008\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;VOOKABISYE&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial W_K^{(2,1)}} =\n\\begin{bmatrix}\n-0.0031 &amp; 0.002 \\\\\n0.0034 &amp; -0.0021 \\\\\n-0.0045 &amp; 0.0029 \\\\\n0.0042 &amp; -0.0027\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;ANCOBGWGSW&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial W_V^{(2,1)}} =\n\\begin{bmatrix}\n0.0026 &amp; 0.0051 \\\\\n0.0100 &amp; 0.0198 \\\\\n-0.0049 &amp; -0.0096 \\\\\n-0.0077 &amp; -0.0152\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;ZOPWZFMKJI&quot;}" data-component-name="LatexBlockToDOM"></div><p>These are small values &#8212; which makes sense. Block 2 is near the output, so gradients haven&#8217;t had many layers to grow; also, this is one training example, so no single gradient should be huge. The model will get nudged slightly toward making h point more strongly toward &#8220;mat&#8221;&#8217;s embedding, and every Q/K/V matrix contributes a small share of that adjustment. Head 2&#8217;s matrices get their own (different) gradients through the same mechanism.</p><p>Once we&#8217;ve gone through both heads, we sum their contributions to the gradient on X^(1) (the normalized input to block 2&#8217;s attention), propagate back through LN 2a, and combine with the attention residual skip to get the gradient on X^(1) (the block 1 output):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial X^{(1)}} =\n\\begin{bmatrix}\n-0.013 &amp; 0.021 &amp; 0.008 &amp; -0.016 \\\\\n-0.048 &amp; 0.065 &amp; 0.024 &amp; -0.041 \\\\\n-0.010 &amp; 0.020 &amp; 0.011 &amp; -0.020 \\\\\n-0.053 &amp; 0.073 &amp; 0.027 &amp; -0.047 \\\\\n0.326 &amp; -0.043 &amp; -0.168 &amp; -0.115\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;SRWKOGLYNP&quot;}" data-component-name="LatexBlockToDOM"></div><p>Notice something important: <strong>all five positions now have non-zero gradients</strong>, even though only position 4 produced the loss. This happened inside the attention of block 2 &#8212; when computing attention weights for position 4&#8217;s query, the keys and values from all previous positions were involved, so gradients flowed back to all of them. The gradient magnitudes at positions 0&#8211;3 are much smaller than at position 4 (which is where the prediction actually happened), but they&#8217;re non-zero, and they&#8217;ll continue propagating backward through block 1 to the embeddings.</p><h3>Step 14: Backward Through Block 1</h3><p>The pattern repeats exactly for block 1. Walk through the residual at the end of block 1 (splits), through the FFN (give gradients to W&#8321;, W&#8322;, b&#8321;, b&#8322; of block 1), through the residual at the attention end, through W_O, through both heads&#8217; Q/K/V projections, through the LayerNorm 1a, and combine with the skip to get the gradient on X^(0):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial X^{(0)}} =\n\\begin{bmatrix}\n-0.085 &amp; 0.081 &amp; 0.068 &amp; -0.065 \\\\\n-0.075 &amp; 0.005 &amp; 0.110 &amp; -0.039 \\\\\n-0.064 &amp; 0.040 &amp; 0.076 &amp; -0.051 \\\\\n-0.096 &amp; 0.018 &amp; 0.096 &amp; -0.019 \\\\\n0.437 &amp; -0.067 &amp; -0.128 &amp; -0.243\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;JCVTQWLRNI&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the gradient on the embedding+positional sum at each position. Positions 0&#8211;3 have small gradients (they only received error signal through the attention flow-back); position 4 has the largest gradient (it&#8217;s the position that actually produced the loss).</p><h3>Step 15: Gradient on the Embedding Matrix</h3><p>Now we map these position-wise gradients back to the embedding matrix W_E. Each position used a specific row of W_E (looked up by token ID), so the gradient flows back to that row.</p><p><strong>Key insight</strong>: positions 0 and 4 are both &#8220;the&#8221; (token 0). Their gradients <strong>sum</strong> into row 0 of W_E, because a row that&#8217;s been used multiple times accumulates gradient from every use.</p><p>From the input side:</p><ul><li><p>Position 0 (&#8221;the&#8221;) contributes: [-0.085, 0.081, 0.068, -0.065]</p></li><li><p>Position 1 (&#8221;cat&#8221;) contributes: [-0.075, 0.005, 0.110, -0.039]</p></li><li><p>Position 2 (&#8221;sat&#8221;) contributes: [-0.064, 0.040, 0.076, -0.051]</p></li><li><p>Position 3 (&#8221;on&#8221;) contributes: [-0.096, 0.018, 0.096, -0.019]</p></li><li><p>Position 4 (&#8221;the&#8221;, again) contributes: [0.437, -0.067, -0.128, -0.243]</p></li></ul><p>Summing for &#8220;the&#8221; (positions 0 and 4):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\left.\\frac{\\partial \\mathcal{L}}{\\partial W_E[\\text{the}]}\\right|_{\\text{input-side}} = [0.352, 0.014, -0.060, -0.307]&quot;,&quot;id&quot;:&quot;RTWCGGMJIA&quot;}" data-component-name="LatexBlockToDOM"></div><p><strong>But remember</strong>: because we&#8217;re using weight tying, W_E also appears at the output. The gradient from the output side is what we computed back in step 11 &#8212; every token&#8217;s embedding gets a contribution based on how that token appeared in the softmax.</p><p>Combining both sides, the final gradient on W_E:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!GiUv!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!GiUv!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 424w, https://substackcdn.com/image/fetch/$s_!GiUv!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 848w, https://substackcdn.com/image/fetch/$s_!GiUv!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 1272w, https://substackcdn.com/image/fetch/$s_!GiUv!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!GiUv!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png" width="1374" height="740" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:740,&quot;width&quot;:1374,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:99944,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!GiUv!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 424w, https://substackcdn.com/image/fetch/$s_!GiUv!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 848w, https://substackcdn.com/image/fetch/$s_!GiUv!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 1272w, https://substackcdn.com/image/fetch/$s_!GiUv!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F47759b4e-dc06-4c10-97d3-8fce8a56590d_1374x740.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>The row for <strong>&#8220;mat&#8221; has by far the largest gradient</strong> &#8212; because &#8220;mat&#8221; is the target, and weight tying gave it a massive gradient directly from the output layer. Rows for tokens that didn&#8217;t appear in the input (dog, ran, and) only have output-side gradients, from having been considered and partially predicted by the softmax. Rows for tokens that did appear (the, cat, sat, on) have both input-side and output-side contributions.</p><h3>Step 16: The Weight Update</h3><p>Applying gradient descent with learning rate &#951; = 0.5 (just like Part 1):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_E^{\\text{new}}[i] = W_E^{\\text{old}}[i] - \\eta \\cdot \\frac{\\partial \\mathcal{L}}{\\partial W_E[i]}&quot;,&quot;id&quot;:&quot;MUZUEVAJNA&quot;}" data-component-name="LatexBlockToDOM"></div><p>For "mat":</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_E[\\text{mat}]^{\\text{new}} = [0.1, 0.4, 0.2, 0.3] - 0.5 \\cdot [0.314, -1.107, 1.142, -0.349]&quot;,&quot;id&quot;:&quot;PNFSZDWKTA&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;= [-0.057, 0.954, -0.371, 0.474]&quot;,&quot;id&quot;:&quot;DFXAXMYKGX&quot;}" data-component-name="LatexBlockToDOM"></div><p>The embedding for &#8220;mat&#8221; moved <strong>substantially</strong>. Its second component jumped from 0.4 to 0.954, its third went from 0.2 to -0.371. The direction of the update is aligned with -gradient, which for the output-side contribution is aligned with +h (the final hidden vector from this example). In other words, <strong>&#8220;mat&#8221;&#8217;s embedding was pushed toward the current hidden state&#8217;s direction</strong>. Next time the network sees this context, the dot product between h and &#8220;mat&#8221;&#8217;s embedding will be larger &#8594; higher logit &#8594; higher probability. The network has learned (a tiny bit) from this example.</p><p>For a Q/K/V matrix that got a smaller gradient, the update is tinier. For example, W_V^(2,1):</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;W_V^{(2,1)\\,\\text{new}} =\n\\begin{bmatrix}\n0.4 &amp; 0.0 \\\\\n0.1 &amp; 0.3 \\\\\n0.2 &amp; 0.4 \\\\\n0.3 &amp; 0.1\n\\end{bmatrix}\n- 0.5 \\cdot\n\\begin{bmatrix}\n0.0026 &amp; 0.0051 \\\\\n0.0100 &amp; 0.0198 \\\\\n-0.0049 &amp; -0.0096 \\\\\n-0.0077 &amp; -0.0152\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0.3987 &amp; -0.0025 \\\\\n0.0950 &amp; 0.2901 \\\\\n0.2024 &amp; 0.4048 \\\\\n0.3039 &amp; 0.1076\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;TYSBJJVSPC&quot;}" data-component-name="LatexBlockToDOM"></div><p>A microscopic nudge. But applied over billions of training examples, across billions of parameters, these microscopic nudges are exactly what shape a random Transformer into a coherent language model.</p><h3>The Big Picture</h3><p>Let&#8217;s step back and appreciate what just happened.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!T9bm!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!T9bm!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 424w, https://substackcdn.com/image/fetch/$s_!T9bm!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 848w, https://substackcdn.com/image/fetch/$s_!T9bm!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 1272w, https://substackcdn.com/image/fetch/$s_!T9bm!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!T9bm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png" width="880" height="500" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:500,&quot;width&quot;:880,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:117357,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/194854579?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!T9bm!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 424w, https://substackcdn.com/image/fetch/$s_!T9bm!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 848w, https://substackcdn.com/image/fetch/$s_!T9bm!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 1272w, https://substackcdn.com/image/fetch/$s_!T9bm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F409a67d1-25f8-4a91-b9af-defb5de9ac4b_880x500.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><p>We started with one input sequence, one target token, and a network full of essentially random weights. The model made a weak prediction (17.1% probability on the correct answer). The cross-entropy loss was 1.768. A single scalar &#8212; one number.</p><p>Backpropagation took that one number and traced it backward through <strong>every single parameter</strong> in the network:</p><ul><li><p>Every entry of the output head W_E^T (via weight tying, every embedding row)</p></li><li><p>Every LayerNorm gain and bias (two LNs per block &#215; two blocks + one final = 5 LNs)</p></li><li><p>Every attention weight matrix: W_Q, W_K, W_V for each of two heads, plus W_O (shared across heads, one per block) &#8212; (3 &#215; 2 heads + 1) &#215; 2 blocks = 14 attention matrices</p></li><li><p>Every FFN weight matrix and bias: W&#8321;, W&#8322;, b_1, b_2 &#8212; 4 sets &#215; 2 blocks = 8 FFN parameters</p></li><li><p>Every entry of the embedding matrix W_E (already counted via weight tying)</p></li><li><p>Positional encodings (if they were learnable; in our example they were fixed)</p></li></ul><p>Every single one of these parameters got a tiny push, proportional to how much it contributed to the final loss. The push always points in the direction that would, if repeated, reduce the loss &#8212; that&#8217;s what gradient descent guarantees.</p><p>Some observations that should feel powerful by now:</p><ol><li><p><strong>The only signal was -log(0.171) = 1.768</strong>. One scalar. Everything else &#8212; all 1000+ individual parameter updates &#8212; was derived by mechanical application of the chain rule.</p></li><li><p><strong>&#8220;mat&#8221;&#8217;s embedding got the biggest update</strong>. Because of weight tying, the output layer directly pulled &#8220;mat&#8221;&#8217;s row toward the current hidden state vector. Next time this sequence is seen, &#8220;mat&#8221; will be scored higher at the output.</p></li><li><p><strong>Every Q/K/V matrix in every head in every block got updated</strong>. Not because anyone programmed them to do specific things, but because the chain rule traced the loss back through each of them. If head 7 of block 12 happened to route slightly more attention to the wrong position, its W_Q and W_K will shift slightly to route less that way next time. No one told it which attention pattern is right &#8212; the loss implicitly informed it.</p></li><li><p><strong>The same token at different positions had its gradients accumulated</strong>. &#8220;The&#8221; appeared at positions 0 and 4; both gradient contributions summed into the same row of W_E. This is how the network learns that &#8220;the&#8221; has some consistent representation across positions &#8212; because all its uses push the same row of the embedding matrix.</p></li><li><p><strong>Weight tying means dual updates for the same matrix</strong>. W_E received gradients from both the input side (through the whole network) and the output side (directly from the logit computation). These added together.</p></li><li><p><strong>Positions 0&#8211;3 got non-zero gradients</strong>, even though only position 4 produced the loss. This happened via attention: the query at position 4 attended to keys and values at all previous positions, so when the loss propagated back through attention, it flowed to those positions too. This is how &#8220;context&#8221; tokens get their embeddings shaped &#8212; they matter for what came after, so they get a share of the error signal.</p></li></ol><p>Now imagine this entire process, but with:</p><ul><li><p>A vocabulary of 128,000 tokens instead of 8</p></li><li><p>d_model of 4,096 instead of 4</p></li><li><p>32 heads per block instead of 2</p></li><li><p>32 blocks instead of 2</p></li><li><p>Sequences of thousands of tokens instead of five</p></li><li><p>Trillions of training examples, processed in batches of thousands at a time</p></li><li><p>An optimizer like AdamW that tracks running averages of gradients rather than using them directly</p></li><li><p>A learning rate schedule, gradient clipping, mixed-precision training</p></li></ul><p>The forward and backward passes look the same. The matrices are much bigger. The number of parameter updates per step is in the hundreds of billions. The effect per example is much smaller. But the principle &#8212; loss &#8594; gradient &#8594; update, applied mechanically via the chain rule to every single parameter &#8212; is exactly what we just walked through.</p><p>That&#8217;s how an LLM learns. There&#8217;s no secret step. It&#8217;s just this, repeated an enormous number of times.</p><div><hr></div><p>Well and this is it for Part 2. We went from the simple MLP of Part 1 through the entire Transformer architecture &#8212; embeddings, attention, feedforward networks, residual connections, normalization &#8212; and we traced a complete forward and backward pass through a working (if tiny) model, watching every weight get updated by the chain rule. Next time we will see how a Transformer goes from random weights to a working assistant: pretraining on trillions of tokens, supervised fine-tuning, alignment via RLHF and DPO, and the engineering of inference and serving.</p><p>Until next time!</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.dimensionalityreduction.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Dimensionality Reduction! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Large Language Models from scratch - Part 1]]></title><description><![CDATA[Or how to deconstruct the discovery of the century in (mostly) understandable parts.]]></description><link>https://www.dimensionalityreduction.com/p/large-language-models-from-scratch</link><guid isPermaLink="false">https://www.dimensionalityreduction.com/p/large-language-models-from-scratch</guid><dc:creator><![CDATA[Nuno Fonseca]]></dc:creator><pubDate>Fri, 23 Jan 2026 01:39:00 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!791n!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!791n!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!791n!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 424w, https://substackcdn.com/image/fetch/$s_!791n!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 848w, https://substackcdn.com/image/fetch/$s_!791n!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 1272w, https://substackcdn.com/image/fetch/$s_!791n!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!791n!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png" width="1456" height="971" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:971,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1887794,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!791n!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 424w, https://substackcdn.com/image/fetch/$s_!791n!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 848w, https://substackcdn.com/image/fetch/$s_!791n!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 1272w, https://substackcdn.com/image/fetch/$s_!791n!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F94afd57e-9b5b-4c3c-aa83-507c46ce4caf_1536x1024.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><p>Large Language Models are everywhere now. OpenAI&#8217;s ChatGPT took the world by storm in late 2022 and since then the number of LLM&#8217;s exploded, whether they be proprietary, open-weights or open-source. At the time of this writing, more than <strong>2.3M models</strong> are registered in Hugging Face, <strong>317k</strong> alone in the category of &#8216;<a href="https://huggingface.co/models?pipeline_tag=text-generation&amp;sort=trending">Text Generation</a>&#8217;. OpenAI reportedly has <a href="https://techcrunch.com/2025/10/06/sam-altman-says-chatgpt-has-hit-800m-weekly-active-users/#:~:text=Sam%20Altman%20says%20ChatGPT%20has%20hit%20800M%20weekly%20active%20users%20%7C%20TechCrunch">800M active weekly users</a>, Anthropic reached <a href="https://www.anthropic.com/news/anthropic-raises-series-f-at-usd183b-post-money-valuation">300,000 business customers</a> and approximately 30 million monthly active users for its Claude AI assistant as of Q2 2025. Google&#8217;s Gemini App <a href="https://blog.google/products/gemini/gemini-3/#note-from-ceo">surpassed 650 million users per month</a>, and AI Overviews - the intelligent summary that appears at the top when you do a Google search - now have <a href="https://blog.google/products/gemini/gemini-3/#note-from-ceo">2 billion users every month</a>. We&#8217;re definitely witnessing a disruptive technology that shows no signs of decelerating.</p><p>But what exactly are Large Language Models? How do they work, what are their mathematical foundations, how do they differ from each other, but most importantly: what are the steps to build one from scratch? That's the goal for these series of posts that will be as comprehensible as possible. There are a lot of not so trivial concepts that one needs to be comfortable with in order to grasp the core ideas behind LLM&#8217;s, and what better way to understand the process than actually developing one from scratch? The idea is to simplify as much as possible the theory, reducing it to its first principles, but at the same time deliver an organic whole that encompasses state-of-the-art techniques not too far away from production grade LLM&#8217;s. Of course, training a production grade model requires substantial investment, so we will adapt for it to be manageable in consumer-grade hardware.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.dimensionalityreduction.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Dimensionality Reduction! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p>What&#8217;s on the menu on this part?</p><ol><li><p>Machine Learning Models</p></li><li><p>Neural Networks</p><ol><li><p>Neural Network Inference</p></li><li><p>Neural Network Training</p><p></p></li></ol></li></ol><p>Let&#8217;s begin.</p><p>What you see today when you interact with ChatGPT is a rather simple system: there&#8217;s a chat input where you write what you want the model to answer to, hit enter, and then you wait for the model response. Depending on the model you can also upload documents, images, sound as a context to the chat prompt; you can also select whether you want the model to &#8220;think&#8221; harder, do a &#8220;deep research&#8221;, search the web, etc. But in the end of the day you have a system that receives an input, and a black box that ruminates on that input and outputs an answer.</p><p>But, what&#8217;s in that box?</p><p>For the purpose of our reflexion we will consider that behind such a system is only one model. As you will see, a production-grade such system may rely on several models, not just one and not all from the same type, but we will focus our analysis specifically on one type of model: a Large Language Model.</p><h3><strong>Machine Learning Models</strong></h3><p>An LLM, as the name implies, is first and foremost a <strong>Language Model</strong> that is Large. When we say Language Model we mean a Machine Learning Language Model. A Machine Learning model is what you end up with when training an algorithm on data, typically lots of it, being essentially a complex function that learns patterns in the training data to then make predictions or decisions on new, unseen data without explicit programming for every scenario. In this regard we can say that a machine automatically learns and generalizes it&#8217;s understanding of the training dataset it was fed with in the first place and is able to answer, most of the time correctly, on data that it has never seen.</p><p>Machine learning algorithms are typically divided in 3 types:</p><ul><li><p><strong>Supervised Learning</strong>: Learns from labeled data (input-output pairs) to predict outcomes. It&#8217;s normally used in two types of problems that mostly differ on whether the results are discrete or continuous: <strong>classification problems</strong> - where the response belongs to a set of classes (e.g., spam detection) - and <strong>regression problems</strong> - where the response is continuous (e.g., house price prediction).</p><p></p></li><li><p><strong>Unsupervised Learning</strong>: Finds patterns in unlabeled data, often grouping similar items (clustering).</p><p></p></li><li><p><strong>Reinforcement Learning</strong>: Learns through trial-and-error, receiving rewards or penalties (e.g., autonomous driving).</p></li></ul><p>Each type has its own set of machine learning algorithms: for classification problems the most popular ones are typically: Support Vector Machines (SVM),  Decision Trees, Ensemble Trees, Naive Bayes, <em>k</em>-Nearest Neighbors (KNN), and&#8230;Neural Networks. </p><p>For regression problems the most popular ones start with Linear Regression, Polynomial Regression, Decision Tree Regression, Random Forest Regression, Support Vector Regression, and&#8230; Neural Networks.</p><p>As you can see there are lots of machine learning algorithms. I should make an honorary mention of <strong>XGBoost</strong>, that is normally considered the swiss army knife of the ML algorithms, with an excellent track record for both classification and regression problems. It&#8217;s an Ensemble Trees method that normally combines several decision trees - also called weak learners - and then aggregates the result using a <strong>boosting technique</strong>: trees are built sequentially, with each new tree focusing on correcting the errors of the previous ones. There are at least two more techniques regarding the Ensemble Trees method: <strong>bagging</strong>, trains multiple trees independently on different random subsets (with replacement) of the training data (<strong>Random Forest</strong> is a good example of this), and <strong>stack/voting</strong>, that trains different types of models (or same type with different parameters) and uses a meta-model or voting to combine their final predictions.</p><p>Deep diving on each and every one of these algorithms is outside of the scope of our analysis, but we will go in much deeper in just one of them because it&#8217;s at the root of LLMs: Neural Networks.</p><h3><strong>Neural Networks</strong></h3><p>Artificial Neural Networks (ANN) are fascinating. They&#8217;re directly inspired by the biological brain, composed by a network of neurons that communicate via electrochemical signals. Artificial neurons, or nodes, receive input signals, process them, and pass them to other nodes. Biological neurons pass information, or &#8220;fire&#8221;, when the input signal exceeds a certain threshold, and that&#8217;s exactly what happens with artificial neurons: they use activation functions that decide whether they should &#8220;fire&#8221;. The concept of artificial neurons goes way back to the 40&#8217;s with Warren McCulloch and Walter Pitts creating the first mathematical model of an artificial neuron. The field has been advancing since then with the development of the Perceptron, the introduction of the backpropagation algorithm, and a whole series of different and evermore sophisticated ANN architectures.</p><p>Let&#8217;s start with a simple example. Consider the following ANN:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Qj1W!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Qj1W!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 424w, https://substackcdn.com/image/fetch/$s_!Qj1W!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 848w, https://substackcdn.com/image/fetch/$s_!Qj1W!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 1272w, https://substackcdn.com/image/fetch/$s_!Qj1W!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Qj1W!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png" width="1456" height="1229" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1229,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:148523,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Qj1W!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 424w, https://substackcdn.com/image/fetch/$s_!Qj1W!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 848w, https://substackcdn.com/image/fetch/$s_!Qj1W!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 1272w, https://substackcdn.com/image/fetch/$s_!Qj1W!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f30889a-0e2e-4a12-950e-a76feb1eec51_1614x1362.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>This network has an <strong>Input</strong> Layer, one <strong>Hidden</strong> Layer, and an <strong>Output</strong> Layer. Typically all neural networks have one Input and one Output layers, and one or more Hidden layers. As the name implies, the input layer holds as many neurons as needed for the input data of the problem at hand. Similarly, the output layer will hold as many neurons as needed for holding a prediction result. The hidden layers represent the network&#8217;s core <em>feature extraction</em> (more on this in a bit) capability, essentially being where all the computation work is done. The number of nodes on each hidden layer, and the number of hidden layers, is perfectly arbitrary. It really depends on the problem we want to solve, but generally the more hidden layers there are, the deeper the network is (hence the notion of deep learning, applied to deep neural networks), and the more each hidden layer learns increasingly abstract representations of the data that flows from one hidden layer to the next.</p><p>The way information flows from the input to the output layer - also called a <strong>forward pass</strong> - and from one node to another node is by performing <strong>linear calculations</strong> and a <strong>function activation</strong>:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!iSut!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!iSut!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 424w, https://substackcdn.com/image/fetch/$s_!iSut!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 848w, https://substackcdn.com/image/fetch/$s_!iSut!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 1272w, https://substackcdn.com/image/fetch/$s_!iSut!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!iSut!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png" width="1456" height="818" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:818,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:222248,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!iSut!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 424w, https://substackcdn.com/image/fetch/$s_!iSut!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 848w, https://substackcdn.com/image/fetch/$s_!iSut!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 1272w, https://substackcdn.com/image/fetch/$s_!iSut!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6cdea9fc-3e19-4c47-9bc9-50d0b1e88a0f_1498x842.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Each neuron performs a linear calculation based on all its input connections and a function activation on the result of the linear calculation.</p><p>First it sums up all the information coming in the neuron:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;z = \\sum_{i=1}^{n} w_i x_i + b&quot;,&quot;id&quot;:&quot;KGGVQWDADQ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;x_i&quot;,&quot;id&quot;:&quot;JZEJTXMNUV&quot;}" data-component-name="LatexBlockToDOM"></div><p><strong>Input / Feature</strong>: The data being fed into the neuron. We will get back to this <em>feature</em> notion a bit later.</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_i&quot;,&quot;id&quot;:&quot;ZBYQEXXCZZ&quot;}" data-component-name="LatexBlockToDOM"></div><p><strong>Weight</strong>: Determines the importance of each input feature. It acts as a slope, controlling how strongly the input influences the output.</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;b&quot;,&quot;id&quot;:&quot;TTDZNFHAXD&quot;}" data-component-name="LatexBlockToDOM"></div><p><strong>Bias</strong>: A trainable parameter that shifts the activation function left or right, allowing the model to fit data that does not pass through the origin. It mostly adds flexibility in what would otherwise be just a sequence of multiplications.</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;z&quot;,&quot;id&quot;:&quot;CECLKZEPMZ&quot;}" data-component-name="LatexBlockToDOM"></div><p><strong>Pre-activation / Linear Combination</strong>: The result of the linear transformation before applying the activation function.</p><p></p><p>Lastly we apply the <strong>activation function</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;y = \\alpha(z)&quot;,&quot;id&quot;:&quot;HGYQMNUNEL&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\alpha&quot;,&quot;id&quot;:&quot;WYHALWKGEF&quot;}" data-component-name="LatexBlockToDOM"></div><p><strong>Activation function</strong>: sigmoid, ReLU, tanh, softmax, etc. These non-linear functions  introduce non-linearity in what would be just a sum of linear equations, collapsing all hidden layers and severely impacting the network&#8217;s ability to learn complex patterns in data.</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;y&quot;,&quot;id&quot;:&quot;GXSWWMKOFR&quot;}" data-component-name="LatexBlockToDOM"></div><p>The final result that is <strong>passed to the next node</strong>.</p><h3><strong>Neural Network Inference</strong></h3><p>Let&#8217;s apply a simple problem to the example we gave earlier that hopefully will put these simple calculations into some context. Consider the scenario of a student that needs to pass a final exam, having attended its respective classes and having studied for some hours per day. We consider <strong>x1 is the number of hours a student studies per day</strong>, <strong>x2 is the percentage of class attendance</strong>, and we want to predict <strong>if the student will pass or fail the exam</strong>. There are several ways to model even this simple problem, we could try to infer the actual continuous score of the exam from 0-100%. Or to infer the discrete grade - from A to F - or just infer that he will pass or fail the exam, as a binary classification. These three different outcomes imply three different output layers, activation functions and, as we will see, loss functions. But we will stick to the simplest example and predict simply whether the student will pass or fail the exam.</p><p>Let&#8217;s consider, as an input example:</p><ul><li><p>x1: 5 hours</p></li><li><p>x2: 60%</p></li></ul><p>So the student studied <strong>5 hours a day</strong> and attended <strong>60% of classes</strong>. Let&#8217;s find out if, according to the network, he will pass or fail the exam.</p><p>An <strong>already</strong> <strong>trained network</strong> behaves like this:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Kns8!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Kns8!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 424w, https://substackcdn.com/image/fetch/$s_!Kns8!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 848w, https://substackcdn.com/image/fetch/$s_!Kns8!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 1272w, https://substackcdn.com/image/fetch/$s_!Kns8!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Kns8!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png" width="1456" height="1279" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/da310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1279,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:259445,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Kns8!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 424w, https://substackcdn.com/image/fetch/$s_!Kns8!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 848w, https://substackcdn.com/image/fetch/$s_!Kns8!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 1272w, https://substackcdn.com/image/fetch/$s_!Kns8!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda310ffe-eae3-437a-b975-9e7c8d03f52b_1628x1430.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>We input both variables in the Input layer. Notice that both x1 and x2 are normalized values between [0, 1]. To normalize the x1 value we consider 10h as a maximum value, so 5h is 50%, or 0.5. Regarding attendance, 60% is already in the [0,1] interval. It&#8217;s important that all the values be normalized so both inputs contribute proportionally and no feature dominates the others.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!lZPK!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!lZPK!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 424w, https://substackcdn.com/image/fetch/$s_!lZPK!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 848w, https://substackcdn.com/image/fetch/$s_!lZPK!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 1272w, https://substackcdn.com/image/fetch/$s_!lZPK!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!lZPK!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png" width="1456" height="1280" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1280,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:305859,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!lZPK!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 424w, https://substackcdn.com/image/fetch/$s_!lZPK!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 848w, https://substackcdn.com/image/fetch/$s_!lZPK!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 1272w, https://substackcdn.com/image/fetch/$s_!lZPK!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d964eca-51cb-4c47-bbaa-96f80dc5c6cd_1626x1430.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Then for each connection between every input node and a hidden layer&#8217;s node there&#8217;s a <strong>weight</strong> value attributed to that connection. In the picture above you can see, for instance, between <strong>x1</strong> and <strong>h1</strong> the value of <strong>+0.82</strong>. And between <strong>x1</strong> and <strong>h3</strong> the value of <strong>-0.45</strong>. Each connection then has a <strong>learned weight</strong>:</p><pre><code>From Study Hours (x&#8321;):
  &#8594; h&#8321;: w = 0.82
  &#8594; h&#8322;: w = 0.71
  &#8594; h&#8323;: w = -0.45</code></pre><pre><code>From Attendance (x&#8322;):
  &#8594; h&#8321;: w = 0.65
  &#8594; h&#8322;: w = 0.89
  &#8594; h&#8323;: w = 0.78</code></pre><p>These values were obtained during training and are static once the network is trained. Whatever the inputs, these values are always the same. Bias values are also learned and static, we show them next.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!HYNf!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!HYNf!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 424w, https://substackcdn.com/image/fetch/$s_!HYNf!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 848w, https://substackcdn.com/image/fetch/$s_!HYNf!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 1272w, https://substackcdn.com/image/fetch/$s_!HYNf!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!HYNf!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png" width="1456" height="1284" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1284,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:421680,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!HYNf!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 424w, https://substackcdn.com/image/fetch/$s_!HYNf!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 848w, https://substackcdn.com/image/fetch/$s_!HYNf!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 1272w, https://substackcdn.com/image/fetch/$s_!HYNf!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd213d48d-84fd-4ce5-b336-76cbbe9f66cd_1626x1434.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><pre><code>Biases: [-0.50, -0.60, -0.30]</code></pre><p>You can see biases on the top right corner of each hidden layer&#8217;s node.</p><p>Next we perform linear calculations referenced earlier, so for each hidden layer&#8217;s node we compute the following for every incoming connection:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;z = \\sum_{i=1}^{n} w_i x_i + b&quot;,&quot;id&quot;:&quot;WMFDNCCODI&quot;}" data-component-name="LatexBlockToDOM"></div><p>And we obtain the following values, that you can see in the picture on each h1, h2 and h3 nodes:</p><pre><code>h&#8321;: z = (0.82 * 0.500) + (0.65 * 0.600) - 0.50 = 0.3000
h&#8322;: z = (0.71 * 0.500) + (0.89 * 0.600) - 0.60 = 0.2890
h&#8323;: z = (-0.45 * 0.500) + (0.78 * 0.600) - 0.30 = -0.057</code></pre><p>So now, after linear calculations you can see each result on each hidden layer&#8217;s node. Now we perform the <strong>ReLU</strong> function activation over each hidden layer node result as we stated earlier:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;y = \\alpha(z)&quot;,&quot;id&quot;:&quot;VBYKGUFWAO&quot;}" data-component-name="LatexBlockToDOM"></div><p>Which in ReLU&#8217;s case:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;f(z) = max(0, z)&quot;,&quot;id&quot;:&quot;IDIZYGOUDF&quot;}" data-component-name="LatexBlockToDOM"></div><p>ReLU is an acronym for <strong>Rectified Linear Unit</strong>. Basically resets negative values to zero and lets through positive values. We could&#8217;ve chosen other functions, there are various alternatives, we will go deeper on this later.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!arb5!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!arb5!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 424w, https://substackcdn.com/image/fetch/$s_!arb5!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 848w, https://substackcdn.com/image/fetch/$s_!arb5!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 1272w, https://substackcdn.com/image/fetch/$s_!arb5!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!arb5!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png" width="1456" height="1281" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/cd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1281,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:417114,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!arb5!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 424w, https://substackcdn.com/image/fetch/$s_!arb5!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 848w, https://substackcdn.com/image/fetch/$s_!arb5!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 1272w, https://substackcdn.com/image/fetch/$s_!arb5!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcd0c5f16-4980-42a4-b41e-415bf8b6c39f_1618x1424.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>As you can see, looking to h1, h2 and h3 nodes, only node <strong>h3</strong> changed value from a negative value <strong>-0.057</strong> to <strong>0</strong>. This is because, as we said earlier, ReLU resets negative values to zero and lets through positive values. That was what happened to <strong>h1</strong> and <strong>h2</strong> nodes, whose value stayed the same. So at this point on each h1, h2 and h3 we have final linear calculations plus ReLU activation function results.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!XdaC!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!XdaC!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 424w, https://substackcdn.com/image/fetch/$s_!XdaC!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 848w, https://substackcdn.com/image/fetch/$s_!XdaC!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 1272w, https://substackcdn.com/image/fetch/$s_!XdaC!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!XdaC!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png" width="1456" height="1282" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1282,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:437449,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!XdaC!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 424w, https://substackcdn.com/image/fetch/$s_!XdaC!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 848w, https://substackcdn.com/image/fetch/$s_!XdaC!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 1272w, https://substackcdn.com/image/fetch/$s_!XdaC!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9274843e-daac-4c19-add8-7102368a7fe3_1620x1426.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Next we continue, doing the same calculations per connection. The next connection&#8217;s weights obtained in training:</p><pre><code>h&#8321; &#8594; output: w = 0.85
h&#8322; &#8594; output: w = 0.72
h&#8323; &#8594; output: w = -0.55</code></pre><p>Bias we reveal next.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ZmRX!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ZmRX!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 424w, https://substackcdn.com/image/fetch/$s_!ZmRX!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 848w, https://substackcdn.com/image/fetch/$s_!ZmRX!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 1272w, https://substackcdn.com/image/fetch/$s_!ZmRX!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!ZmRX!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png" width="1456" height="1285" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/fef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1285,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:473577,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ZmRX!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 424w, https://substackcdn.com/image/fetch/$s_!ZmRX!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 848w, https://substackcdn.com/image/fetch/$s_!ZmRX!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 1272w, https://substackcdn.com/image/fetch/$s_!ZmRX!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffef958f3-34b1-45df-8832-4bf0d874f479_1616x1426.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><pre><code>Output bias: b = -0.20</code></pre><p>Now we perform the same computation again, this time from h1, h2 and h3 values computed earlier as our <strong>Input / Feature</strong> values:</p><pre><code>z = (0.85 * 0.300) + (0.72 * 0.289) + (-0.55 * 0) - 0.20 = 0.2631</code></pre><p>Now we apply another activation function, this time we choose to apply the <strong>sigmoid function</strong>, that squashes values to probabilities between [0,1]:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\n&#963;(z) = \\frac{1}{1 + e^{-z}}\n\n&quot;,&quot;id&quot;:&quot;NHOWCXNOXV&quot;}" data-component-name="LatexBlockToDOM"></div><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!nksZ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!nksZ!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 424w, https://substackcdn.com/image/fetch/$s_!nksZ!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 848w, https://substackcdn.com/image/fetch/$s_!nksZ!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 1272w, https://substackcdn.com/image/fetch/$s_!nksZ!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!nksZ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png" width="1456" height="1277" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/b6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1277,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:484498,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!nksZ!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 424w, https://substackcdn.com/image/fetch/$s_!nksZ!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 848w, https://substackcdn.com/image/fetch/$s_!nksZ!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 1272w, https://substackcdn.com/image/fetch/$s_!nksZ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb6fdc513-de1e-43c3-85d2-4ab45216573c_1626x1426.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Applying the sigmoid function to the obtained value <strong>0.263</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\sigma(0.263) = \\frac{1}{1 + e^{-0.263}}\n\n= \\frac{1}{1 + 0.7688}\n              = \\frac{1}{1.7688}\n              \\approx 0.5655\n&quot;,&quot;id&quot;:&quot;EDUXUOVMKE&quot;}" data-component-name="LatexBlockToDOM"></div><p>We end up with the full prediction of the network for the first question, that was to know if the student passed or not given that the student studied 5 hours per day and attended 60% of classes: <strong>56.5%</strong>. So yes, the student would pass (barely).</p><p>You can see that choosing sigmoid as activating function in the output layer was not innocent. Even though the prediction only required some way of performing binary classification - pass / fail - the network&#8217;s output values are <strong>always continous</strong> - we will see why in a bit - and therefore we settle anything equal or above 0.5 as passing the exam, anything lower than that, means the student fails the exam.</p><p>As you can see, aside from some probably unfamiliar functions, the core network&#8217;s calculations are really simple to follow along. But what you are seeing is just an already trained network doing inference. But how was the network&#8217;s trained ?</p><h3><strong>Neural Network Training</strong></h3><p>This will be a bit trickier, but we will go through step by step as we did in inference. It&#8217;s very, very important that we nail these building blocks with very basic networks because from here things will get a lot more complex so we need to be very clear on the fundamentals.</p><p>Let&#8217;s dive in.</p><p>For training a neural network, or any other kind of model, we generally need <strong>three datasets</strong>: <strong>training</strong>, <strong>validation</strong> and <strong>test</strong> datasets. Usually they&#8217;re segmented over the total collection of observations of the reality we want to model, for instance: <strong>80% </strong>training, <strong>10%</strong> validation, <strong>10%</strong> test. For big data <strong>90%</strong> training, <strong>5% </strong>validation, <strong>5%</strong> test is also common. For all datasets we must sample from the same distribution:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;Ptrain&#8203;(x,y)&#8776;Pval&#8203;(x,y)&#8776;Ptest&#8203;(x,y)&#8776;Preal&#8203;(x,y)&quot;,&quot;id&quot;:&quot;VVVQNEJPRA&quot;}" data-component-name="LatexBlockToDOM"></div><p>To put it in another way: <strong>validation </strong>and<strong> test </strong>are<strong> &#8220;small versions of reality&#8221;.</strong><br><strong>training</strong> is <strong>&#8220;what the model studies&#8221;</strong>. So one must strive to keep the same diversity found globally in the studied reality on each and every one of the datasets, otherwise we&#8217;re modeling different &#8220;realities&#8221; making the process unfruitful. This process is also called <em>stratified sampling</em>, A <strong>stratified sample</strong> is a way of splitting data so that <strong>each subset keeps the same structure as the full dataset</strong>. Instead of sampling randomly, we <strong>preserve the proportions of important groups</strong> (called <em>strata</em>).</p><p>The validation process is stateless, during validation the model is freezed and <strong>there are no weight updates</strong>, only in the training process weights get updated. In this regard, and generally speaking, the validation dataset is normally used to tune the training algorithm&#8217;s hyperparameters/early stopping - because you train the model over the training dataset with a specific hyperparameter config and then you validate this model/configuration agaisnt the validation dataset. It&#8217;s from this match that is calculated the<strong> validation loss</strong>, i.e., the average error the model makes on the <strong>validation dataset</strong> and is used to estimate how well the model generalizes, because this dataset was not seen in training data. The <strong>training loss</strong> is the same error, but is calculated over the <strong>training dataset</strong> and it is the quantity that is <strong>minimized during learning</strong>.</p><p>The training loss:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L}_{train}(\\theta)\n= \\frac{1}{N_{train}} \\sum_{i=1}^{N_{train}} \n\\ell\\!\\left(y_i, f_\\theta(x_i)\\right)&quot;,&quot;id&quot;:&quot;NWTKRUVMPC&quot;}" data-component-name="LatexBlockToDOM"></div><p>The validation loss:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L}_{val}(\\theta)\n= \\frac{1}{N_{val}} \\sum_{i=1}^{N_{val}} \n\\ell\\!\\left(y_i, f_\\theta(x_i)\\right)\n&quot;,&quot;id&quot;:&quot;BVEODVRIZJ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where:</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ykFj!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ykFj!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 424w, https://substackcdn.com/image/fetch/$s_!ykFj!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 848w, https://substackcdn.com/image/fetch/$s_!ykFj!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 1272w, https://substackcdn.com/image/fetch/$s_!ykFj!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!ykFj!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png" width="404" height="167.40331491712706" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:false,&quot;imageSize&quot;:&quot;normal&quot;,&quot;height&quot;:300,&quot;width&quot;:724,&quot;resizeWidth&quot;:404,&quot;bytes&quot;:37712,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:&quot;center&quot;,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ykFj!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 424w, https://substackcdn.com/image/fetch/$s_!ykFj!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 848w, https://substackcdn.com/image/fetch/$s_!ykFj!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 1272w, https://substackcdn.com/image/fetch/$s_!ykFj!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9d97d2da-dd0c-47d8-9661-fe80418e87e1_724x300.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>These are rather simple equations: we just apply the loss function <strong>to the real observed value</strong> - the training target - <strong>and the prediction of the network</strong> - that is, the complex function that receives an input <strong>x</strong> and gives an output <strong>f(x) </strong>by performing the linear calculations you saw earlier in the inference example<strong> </strong>- (we will see some loss functions in detail, particularly <strong>cross-entropy </strong>and <strong>mean squared error</strong> (MSE)). We sum all those loss values and divide by the number of elements in the dataset to get the average value.</p><p>We will keep training, trying to reduce both the training and the validation losses, that is, trying to minimize the errors the model obtains while trying to model the reality we&#8217;re interested in. Training loss normally goes down as the training progresses, but validation loss can down or go up. If that happens, it&#8217;s a clear signal of <strong>overfitting</strong>, that is, the model keeps reducing the loss over the training set, but is no longer generalizing well to unseen data. It&#8217;s being overfitted to the training set, modeling noise instead of signal. When this happens, the training process may stop early.</p><p>Once the model is trained and validated, it can finally be evaluated on the <strong>test</strong> dataset, a subset the model has never seen during the entire process, and conventional metrics are calculated: accuracy, precision, recall, F1-score, etc. The model training process ends here.</p><p>All of these concepts could also be applied to other machine learning algorithms, they&#8217;re not exclusive of neural networks, but are necessary to have a full picture of the scope of work. Let&#8217;s now see effectively how a neural network is actually trained. We will just focus on the core training mechanics, essentially seeing how weights get updated when processing a training dataset.</p><p>To go back to the same student problem we tackled before, consider this training dataset:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!j3ji!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!j3ji!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 424w, https://substackcdn.com/image/fetch/$s_!j3ji!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 848w, https://substackcdn.com/image/fetch/$s_!j3ji!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 1272w, https://substackcdn.com/image/fetch/$s_!j3ji!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!j3ji!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png" width="1456" height="505" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:505,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:95329,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!j3ji!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 424w, https://substackcdn.com/image/fetch/$s_!j3ji!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 848w, https://substackcdn.com/image/fetch/$s_!j3ji!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 1272w, https://substackcdn.com/image/fetch/$s_!j3ji!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F03eeb439-0f57-4f40-a866-5e7dfd744321_1464x508.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Here we see quite a few observations of the reality we are trying to model. We see a student that doesn&#8217;t study very much nor attends class (and inevitably fails the exam). We see an average student, an excellent student, and examples of both extremities: a student that studies but skips class, and vice-versa, one that attends but barely studies. If you notice, all of the cases have targeted observations: all have pass/fail outcomes. It&#8217;s as if this is an historical record of student behaviours and their respective exam outcomes. This is our observable reality, it&#8217;s by mining this list and showing to a network a comprehensive set of examples that try to describe in it&#8217;s more complete form the observable reality we want to model, that we effectively teach the network to discern the relation between hours of study, class attendance, and final exam outcome. And the network, with enough examples and training, will learn it automatically.</p><p>As we said earlier, for effectively training a model we also need a validation and test datasets, but for now we will only concentrate in the core training algorithm and on how the training process uses the training dataset.</p><p>So the training process will iterate on every example of the training dataset multiple times. We say that when a model has trained over the entire dataset - that is, that saw all the examples contained in the dataset once- that it completed <strong>1 epoch</strong>. Training often involves <strong>multiple epochs</strong> because error minimization and weight updating is an iterative process. It&#8217;s as if the network was studying a book and it read the whole book several times, not just one. More epochs means more learning, until it starts memorizing, which is not good, because the network stops learning the underlying patterns and starts learning data itself which leads to overfitting and thus poor generalization.</p><p>Let&#8217;s start by picking the first example of the dataset, the poor student, that studied 2 hours/day and only attended 30% of classes, having failed the exam. Normalized values are, respectively, x1 = 0.2 and x2 = 0.3 :</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!2-4-!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!2-4-!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 424w, https://substackcdn.com/image/fetch/$s_!2-4-!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 848w, https://substackcdn.com/image/fetch/$s_!2-4-!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 1272w, https://substackcdn.com/image/fetch/$s_!2-4-!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!2-4-!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png" width="1456" height="1279" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1279,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:262788,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!2-4-!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 424w, https://substackcdn.com/image/fetch/$s_!2-4-!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 848w, https://substackcdn.com/image/fetch/$s_!2-4-!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 1272w, https://substackcdn.com/image/fetch/$s_!2-4-!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7086a7ff-13a3-4e02-ba62-4db170cac8fa_1628x1430.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Now we do a <strong>forward pass</strong>, that is, we perform all the previous calculations we saw earlier as if we were inferencing, this time with <strong>random weights</strong>.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ViYM!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ViYM!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 424w, https://substackcdn.com/image/fetch/$s_!ViYM!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 848w, https://substackcdn.com/image/fetch/$s_!ViYM!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 1272w, https://substackcdn.com/image/fetch/$s_!ViYM!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!ViYM!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png" width="1456" height="1282" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/e1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1282,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:488496,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ViYM!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 424w, https://substackcdn.com/image/fetch/$s_!ViYM!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 848w, https://substackcdn.com/image/fetch/$s_!ViYM!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 1272w, https://substackcdn.com/image/fetch/$s_!ViYM!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe1968fc7-0e65-44f7-a21f-cd5e02269627_1626x1432.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Here the model predicted that a poor student would <strong>pass the final exam</strong>, because the network&#8217;s output was 0.533, that is &gt;= 0.5. But remember that the target score was 0, not 0.533, so the student, as observed, failed the final exam:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!FNOJ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!FNOJ!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 424w, https://substackcdn.com/image/fetch/$s_!FNOJ!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 848w, https://substackcdn.com/image/fetch/$s_!FNOJ!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 1272w, https://substackcdn.com/image/fetch/$s_!FNOJ!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!FNOJ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png" width="1456" height="1289" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1289,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:495525,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!FNOJ!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 424w, https://substackcdn.com/image/fetch/$s_!FNOJ!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 848w, https://substackcdn.com/image/fetch/$s_!FNOJ!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 1272w, https://substackcdn.com/image/fetch/$s_!FNOJ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7dff06ca-9c52-4a96-baa2-4015cf3f6a14_1620x1434.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><p>So we have an error of -53.3%, the difference between the predicted value: 53.3%, and the target value the network should&#8217;ve predicted: 0 (fail). Now the idea is to <strong>update all the weights of the network in such a way that we minimize this error</strong>. In order to do that we will compute the training loss as we saw earlier and use a cross-entropy function, in this case, <strong>binary cross-entropy</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L}\n= -\\left[\ny \\log(\\hat{p}) + (1 - y)\\log(1 - \\hat{p})\n\\right]\n&quot;,&quot;id&quot;:&quot;ZKGPAACOAJ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Binary cross-entropy loss is tipically used in binary classification problems, but why use this function and not something else, and what is this thing really? Let&#8217;s take a look.</p><p>When we train a neural network for a <strong>binary classification problem</strong>, we are trying to answer a question that sounds extremely simple: <em>yes or no</em>. Did the student pass the exam or not? Is this email spam or not? Is this transaction fraudulent or legitimate?</p><p>Even though the final answer is binary, a neural network never works with hard &#8220;yes&#8221; or &#8220;no&#8221; decisions internally. Instead, it always produces <strong>continuous values</strong> (more on this in a bit). In the case of binary classification, the network usually outputs a number between 0 and 1. This number is best understood as a <strong>degree of belief</strong>. When the model outputs 0.9, it is saying &#8220;I believe there is a 90% chance this is a yes.&#8221; When it outputs 0.1, it is saying &#8220;I believe there is a 10% chance this is a yes.&#8221;</p><p>This is why the sigmoid function is so commonly used at the output layer: it guarantees that the network&#8217;s output stays between 0 and 1, which makes it naturally interpretable as a probability. However, there is an important distinction here. While the <strong>model outputs probabilities</strong>, the <strong>training data does not</strong>. The real world does not give us probabilities; it gives us <strong>outcomes</strong>. A student either passed or failed. An email is either spam or it isn&#8217;t. So the training labels are always discrete values: 0 or 1.</p><p>This type of situation is perfectly described by something called a <strong>Bernoulli experiment</strong>. A Bernoulli experiment is the simplest kind of random experiment imaginable. It has only two possible outcomes: success or failure, yes or no, 1 or 0. A Bernoulli distribution simply says that there is some probability <em>p</em> that the outcome is 1, and a probability <em>1 - p</em> that the outcome is 0. That&#8217;s all it is. In binary classification, the world generates Bernoulli outcomes, and the neural network&#8217;s job is to estimate the probability <em>p</em>.</p><p>At this point, we need a way to measure how good the model&#8217;s predictions are. This is where the concept of <strong>likelihood</strong> comes in. Likelihood answers a very intuitive question: <em>given what the model predicted, how plausible was what actually happened?</em> If a model predicts a 95% chance of passing and the student passes, that outcome feels very reasonable. If the model predicts a 2% chance of passing and the student passes, that outcome feels surprising. Likelihood is simply a way of quantifying that feeling of surprise.</p><p>During training, we want the model to make the observed outcomes as plausible as possible. In other words, we want to <strong>maximize the likelihood</strong> of the data under the model&#8217;s predictions. However, there is a practical issue: probabilities multiply when we look at many data points, and multiplying many small numbers quickly becomes numerically unstable. To solve this, we take the <strong>logarithm</strong> of the likelihood. <strong>Logarithms turn multiplications into additions</strong>, making the math more stable and easier to optimize. There is another benefit: probabilities close to zero turn into very large negative numbers when we take the log, which means confident mistakes are heavily penalized.</p><p>Because most optimization algorithms are designed to <em>minimize</em> a quantity rather than maximize it, we simply negate the log-likelihood. This gives us what is called the <strong>negative log-likelihood</strong>. In plain language, negative log-likelihood measures how surprised the model is by reality. The more surprised it is, the larger the loss.</p><p>Now comes the key connection. When the outcomes follow a Bernoulli distribution &#8212; meaning the labels are 0 or 1 &#8212; the negative log-likelihood simplifies into a very specific mathematical expression. That expression is what we call <strong>binary cross-entropy</strong>. For a single data point, it looks like what we already showed :</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L}\n= -\\left[\ny \\log(\\hat{p}) + (1 - y)\\log(1 - \\hat{p})\n\\right]\n&quot;,&quot;id&quot;:&quot;GUETKBRPXV&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>This formula has a very intuitive interpretation. Let&#8217;s dissect it a bit where each symbol means:</p><ul><li><p><em>y</em> is the <strong>true label</strong> (either 0 or 1)</p><ul><li><p><em>y=1</em> means &#8220;YES / positive class&#8221;</p></li><li><p><em>y=0 </em>means &#8220;NO / negative class&#8221;</p></li></ul></li><li><p><em>p(hat)</em> is the model&#8217;s predicted <strong>probability that the label is 1</strong></p><ul><li><p>e.g. <em>p(hat)</em>&#8203;=0.90 means &#8220;90% chance it&#8217;s class 1&#8221;</p></li></ul></li></ul><p>Now let&#8217;s see how this formula behaves in the two possible cases.</p><p>If the true label is 1, that is, <em>y = 1,</em> the loss depends only on:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;-\\log(\\hat{p}) \n&quot;,&quot;id&quot;:&quot;ZYPFRKJYWP&quot;}" data-component-name="LatexBlockToDOM"></div><p>A high value of <em>p(hat)</em> means the log is close to 0, so -<em>log</em> is tiny which is good. But if <em>p(hat) </em>is low, the log is actually a very large negative number so -log is huge. <strong>You are punished if the model assigned a low probability to something that actually happened.</strong> </p><p>If the true label is 0, that is,<em> y = 0</em>, the loss depends on:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;-\\log(1 - \\hat{p})\n&quot;,&quot;id&quot;:&quot;BKQHTRVKGU&quot;}" data-component-name="LatexBlockToDOM"></div><p>Here the reverse thing happens. If <em>p(hat)</em> is low, the result will be tiny. If it&#8217;s high, the result will be huge because log will approach zero. You are punished if the model was confident in the wrong direction. <strong>Confident and correct predictions lead to very small losses, while confident and wrong predictions lead to very large losses</strong>. This is exactly the behavior we want when training a classifier.</p><p>A word about the word <strong>entropy</strong> in &#8220;cross-entropy&#8221;. It comes from information theory, where entropy measures uncertainty or unpredictability. Low entropy means outcomes are easy to predict; high entropy means they are unpredictable. The word <strong>cross</strong> is there because we are comparing two different probability distributions: the true distribution that generated the data, and the distribution predicted by the model. Cross-entropy measures how inefficient it is to describe reality using the model&#8217;s probabilities instead of the true ones. Training a model by minimizing cross-entropy is equivalent to making the model&#8217;s predicted distribution match reality as closely as possible.</p><p>This is why binary cross-entropy is the standard loss function for binary classification. It matches the nature of the data, it trains the model to produce meaningful probabilities, it strongly penalizes confident mistakes, and it works perfectly with sigmoid outputs. In simple terms, binary cross-entropy teaches a model to be <strong>honest about uncertainty</strong> when the world only gives yes-or-no answers.</p><p>Now, remember when we said the output of the network are always continuous ? Well there&#8217;s another particularity that loss functions must follow: they must all be <strong>differentiable</strong>. But why?</p><p>Let&#8217;s first see what &#8220;differentiable&#8221; means: a function is differentiable if you can compute its derivative (slope) everywhere. Formally, this needs to exist:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{d}{dx} f(x)&quot;,&quot;id&quot;:&quot;MEQWGWTLCN&quot;}" data-component-name="LatexBlockToDOM"></div><p>That means:</p><ul><li><p>The function is <strong>smooth</strong></p></li><li><p>No sharp corners</p></li><li><p>No jumps</p></li><li><p>No flat pieces with no slope</p></li></ul><p>A brief note on derivative. A <strong>derivative</strong> measures how fast a function changes at a particular point. Intuitively, it tells us how sensitive the output of a function is to small changes in its input. Geometrically, the derivative at a point corresponds to the <strong>slope of the tangent line</strong> to the curve at that point. The tangent line is the straight line that just touches the curve at a single point and best approximates the function near that point. While the curve may bend and change direction, the tangent line captures its instantaneous direction and steepness exactly at that location.</p><p>In the context of neural networks, the loss function depends on many parameters, and derivatives tell us how sensitive the loss is to each weight or bias. By computing these derivatives, we understand how small adjustments to parameters affect the model&#8217;s error, which is precisely the information needed to guide learning. In this sense, derivatives provide the local compass that allows optimization algorithms to navigate the complex landscape of neural network training.</p><p>Back to &#8220;differentiable&#8221; concept.</p><p>The loss function needs to be differentiable because training employs the most common learning algorithm: <strong>gradient descent</strong>. It works by computing the derivative of the loss with respect to (<strong>wrt</strong>) each model parameter (or model weight, it&#8217;s the same) and then nudging those parameters in the direction that reduces the loss. If the loss function were not differentiable, there would be no reliable way to know whether a small change to a weight improves or worsens the model. Learning would simply not be possible.</p><p>Formally, gradient descent is defined as follows:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\theta \\leftarrow \\theta - \\eta \\nabla_\\theta \\mathcal{L}&quot;,&quot;id&quot;:&quot;WTERLCTPXL&quot;}" data-component-name="LatexBlockToDOM"></div><p>Where:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!DsiM!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!DsiM!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 424w, https://substackcdn.com/image/fetch/$s_!DsiM!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 848w, https://substackcdn.com/image/fetch/$s_!DsiM!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 1272w, https://substackcdn.com/image/fetch/$s_!DsiM!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!DsiM!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png" width="1434" height="448" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:448,&quot;width&quot;:1434,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:63332,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!DsiM!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 424w, https://substackcdn.com/image/fetch/$s_!DsiM!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 848w, https://substackcdn.com/image/fetch/$s_!DsiM!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 1272w, https://substackcdn.com/image/fetch/$s_!DsiM!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F84f5ea3e-3954-4aaf-b5f3-290ae04bad54_1434x448.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Great. But what is the &#8220;gradient&#8221; ? The gradient is a vector of partial derivatives that tells you how much the loss changes when each weight changes. Formally:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\nabla_\\theta \\mathcal{L}\n=\n\\begin{bmatrix}\n\\frac{\\partial \\mathcal{L}}{\\partial w_1} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_2} \\\\\n\\vdots \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial b}\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;QTSCQEWRKQ&quot;}" data-component-name="LatexBlockToDOM"></div><p>Each partial derivative tells you: &#8220;If I move a tiny bit in this coordinate direction, does the function go up or down?&#8221;</p><p>When you combine them into a vector, you get the <strong>direction that increases the function the fastest</strong>.</p><p>But in the gradient descent equation notice the minus sign. The gradient points uphill, that is, the direction of the steepest increase:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\nabla_\\theta \\mathcal{L}&quot;,&quot;id&quot;:&quot;WUFFANRIPX&quot;}" data-component-name="LatexBlockToDOM"></div><p>But we want to <strong>go downhill</strong> (reduce the loss).</p><p>So we move <strong>in the opposite direction</strong>:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;- \\eta \\nabla_\\theta \\mathcal{L}&quot;,&quot;id&quot;:&quot;LHOGHWDOOD&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>To give you a clearer mental image, imagine you&#8217;re on a foggy mountain and want to reach the valley.</p><ul><li><p>You can&#8217;t see the whole landscape</p></li><li><p>You only feel the slope under your feet</p></li></ul><p>So you:</p><ol><li><p>Feel which way goes downhill (<strong>gradient</strong>)</p></li><li><p>Take a small step that way (<strong>learning rate</strong>, <em><strong>n</strong></em>)</p></li><li><p>Repeat</p></li></ol><p>Eventually you reach the bottom. And this works because the loss function is:</p><ul><li><p>Smooth</p></li><li><p>Differentiable</p></li><li><p>Shaped like a bowl</p></li></ul><p>We call the process of calculating the gradient <strong>backpropagation</strong>, and we call <strong>gradient descent</strong> the rule by which we actually update the weights using the gradient vector.</p><p>A neural network is a function with thousands or millions of parameters. The loss is therefore a function of many variables. Training the network means computing how sensitive the loss is to each parameter, that is, finding out the partial derivatives of the loss function with respect to each weight,  and form the gradient vector, which tells us how to move in parameter space to reduce the loss.</p><p>The way backpropagation helps achieve this is by applying a rule called the <strong>chain rule</strong>, that intuitively works like this: if something depends on something else, which depends on something else, then the rate of change is the product of all intermediate changes. Or in other words, the chain rule says that when a quantity depends on another through a sequence of transformations, <strong>its derivative is the product of the derivatives of each transformation</strong>. Neural networks are nothing more than long chains of functions, so backpropagation is simply the chain rule applied repeatedly.</p><p>But how do you effectively calculate the gradient vector ? Let&#8217;s continue.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!509F!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!509F!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 424w, https://substackcdn.com/image/fetch/$s_!509F!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 848w, https://substackcdn.com/image/fetch/$s_!509F!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 1272w, https://substackcdn.com/image/fetch/$s_!509F!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!509F!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png" width="1456" height="1280" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1280,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:577169,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!509F!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 424w, https://substackcdn.com/image/fetch/$s_!509F!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 848w, https://substackcdn.com/image/fetch/$s_!509F!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 1272w, https://substackcdn.com/image/fetch/$s_!509F!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9f4cd645-7f07-4b84-b320-618ba325e6bc_1668x1466.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>As we were saying, the target is <strong>0</strong> and the predicted value is 0.533. So we substitute those two numbers, <strong>y </strong>and <strong>p(hat) </strong>in the binary cross-entropy equation when the true label is 0 :</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathcal{L}\n= -\\log(1 - \\hat{p})\n= -\\log(1 - 0.533)\n\\approx -\\log(0.467)\n\\approx 0.761\n&quot;,&quot;id&quot;:&quot;UCVZWFZONK&quot;}" data-component-name="LatexBlockToDOM"></div><p>This is the loss value. For sigmoid output with BCE, the derivative wrt the <strong>logit</strong> (that is, the raw score before sigmoid activation) is:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\delta_y \\equiv \\frac{\\partial \\mathcal{L}}{\\partial z_y}\n= \\hat{p} - y\n&quot;,&quot;id&quot;:&quot;VNRQFSAEVW&quot;}" data-component-name="LatexBlockToDOM"></div><p>So:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\delta_y = 0.533 - 0 = 0.533&quot;,&quot;id&quot;:&quot;RJGERBEEIJ&quot;}" data-component-name="LatexBlockToDOM"></div><p>This number is the &#8220;error signal&#8221; at the output.</p><p>So what we will do now is to calculate, according to the chain rule, the derivatives of all the forward dependency chain, starting on the weights connecting the hidden nodes, the hidden nodes and their activations, the output weights, the prediction, and effectively the loss function:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w \\;\\rightarrow\\; z_h \\;\\rightarrow\\; h \\;\\rightarrow\\; z_y \\;\\rightarrow\\; \\hat{p} \\;\\rightarrow\\; \\mathcal{L}\n&quot;,&quot;id&quot;:&quot;BSJFSLPRJY&quot;}" data-component-name="LatexBlockToDOM"></div><p>Formally:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w}\n=\n\\frac{\\partial \\mathcal{L}}{\\partial \\hat{p}}\n\\cdot\n\\frac{\\partial \\hat{p}}{\\partial z_y}\n\\cdot\n\\frac{\\partial z_y}{\\partial h}\n\\cdot\n\\frac{\\partial h}{\\partial z_h}\n\\cdot\n\\frac{\\partial z_h}{\\partial w}&quot;,&quot;id&quot;:&quot;NNIOFWCAXM&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>So let&#8217;s begin by calculating the gradients for the weights that connect the hidden layer&#8217;s nodes <em>h1</em>, <em>h2</em> and <em>h3,</em> and the output.</p><p>For each output weight the derivative is like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{h_j \\to y}}\n= \\delta_y \\cdot h_j&quot;,&quot;id&quot;:&quot;OGGWDJNBRH&quot;}" data-component-name="LatexBlockToDOM"></div><p>And for the output <em>bias</em>, the derivative is:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial b_y}\n= \\delta_y\n&quot;,&quot;id&quot;:&quot;HNDFTFVGCO&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>So the calculated gradients for all the hidden &#8594; output nodes:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{h_1 \\to y}}\n= 0.533 \\cdot 0.064\n= 0.034112\n&quot;,&quot;id&quot;:&quot;MJGOOKYMMX&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{h_2 \\to y}}\n= 0.533 \\cdot 0.000\n= 0\n&quot;,&quot;id&quot;:&quot;UUQDYTIJLB&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{h_3 \\to y}}\n= 0.533 \\cdot 0.074\n= 0.039442\n&quot;,&quot;id&quot;:&quot;PLLTMKETLH&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>We now calculate the gradients for hidden nodes. Don&#8217;t forget that hidden nodes have a ReLU activation function. First derivative also includes it, and is like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\delta_{h_j}\n\\equiv\n\\frac{\\partial \\mathcal{L}}{\\partial z_{h_j}}\n=\n\\delta_y \\cdot w_{h_j \\to y} \\cdot \\mathrm{ReLU}'(z_{h_j})\n&quot;,&quot;id&quot;:&quot;XJMVELNVSG&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>The ReLU derivative being:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\mathrm{ReLU}'(z) =\n\\begin{cases}\n1, &amp; z > 0 \\\\\n0, &amp; z \\le 0\n\\end{cases}\n&quot;,&quot;id&quot;:&quot;PMKCMBSODR&quot;}" data-component-name="LatexBlockToDOM"></div><p><br>The ReLU derivative for each hidden layer neuron is like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;z_{h_1} = 0.064 > 0\n\\;\\Rightarrow\\;\n\\mathrm{ReLU}'(z_{h_1}) = 1\n&quot;,&quot;id&quot;:&quot;IOJDQOGRIQ&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;z_{h_2} = -0.061 \\le 0\n\\;\\Rightarrow\\;\n\\mathrm{ReLU}'(z_{h_2}) = 0\n&quot;,&quot;id&quot;:&quot;KRYYNQUOZJ&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;z_{h_3} = 0.074 > 0\n\\;\\Rightarrow\\;\n\\mathrm{ReLU}'(z_{h_3}) = 1\n&quot;,&quot;id&quot;:&quot;WSFHUOHKFU&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Gradient values for hidden nodes:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\delta_{h_1}\n= 0.533 \\cdot 0.20 \\cdot 1\n= 0.1066\n&quot;,&quot;id&quot;:&quot;IRTYJTQAWU&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\delta_{h_2}\n= 0.533 \\cdot (-0.15) \\cdot 0\n= 0&quot;,&quot;id&quot;:&quot;ICCFSBYHCW&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\delta_{h_3}\n= 0.533 \\cdot 0.25 \\cdot 1\n= 0.13325\n&quot;,&quot;id&quot;:&quot;UMAVUBKEAX&quot;}" data-component-name="LatexBlockToDOM"></div><p>We now finally calculate the gradients for all the weights that connect the input nodes and the hidden layer&#8217;s nodes.</p><p>The first derivative is for the input weights is like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{x_i \\to h_j}}\n=\n\\delta_{h_j} \\cdot x_i\n&quot;,&quot;id&quot;:&quot;QLLWAVASHH&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>And for the hidden nodes bias:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial b_{h_j}}\n=\n\\delta_{h_j}&quot;,&quot;id&quot;:&quot;NTNEPNQMKS&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>So the gradients for the weights connecting to the hidden neuron <em>h1</em> are calculated like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{x_1 \\to h_1}}\n= 0.1066 \\cdot 0.2\n= 0.02132&quot;,&quot;id&quot;:&quot;CIMMUUKWLZ&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{x_2 \\to h_1}}\n= 0.1066 \\cdot 0.3\n= 0.03198\n&quot;,&quot;id&quot;:&quot;DKBZGSIKWF&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial b_{h_1}}\n= 0.1066\n&quot;,&quot;id&quot;:&quot;CQJRAZCZBS&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>And the gradients for the weights connecting to the hidden neuron <em>h2</em> are calculated like this: </p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\delta_{h_2} = 0\n\\quad\\Rightarrow\\quad\n\\text{all gradients for } h_2 \\text{ are zero}\n&quot;,&quot;id&quot;:&quot;RHIMCGPHOO&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Finally,  the gradients for the weights connecting to the hidden neuron <em>h3</em> are calculated like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{x_1 \\to h_3}}\n= 0.13325 \\cdot 0.2\n= 0.02665\n&quot;,&quot;id&quot;:&quot;HUDZASOGJX&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial w_{x_2 \\to h_3}}\n= 0.13325 \\cdot 0.3\n= 0.039975\n&quot;,&quot;id&quot;:&quot;GSRHLKLCAI&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\frac{\\partial \\mathcal{L}}{\\partial b_{h_3}}\n= 0.13325&quot;,&quot;id&quot;:&quot;LFLHBYZQVG&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Having calculated all the gradients, we now perform the gradient descent update on all weights.</p><p>Recalling the formula, the gradient descent update rule is:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\theta \\leftarrow \\theta - \\eta \\nabla_\\theta \\mathcal{L}&quot;,&quot;id&quot;:&quot;PGAEQQLUDU&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>So each weight updates like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w \\leftarrow w - \\eta \\frac{\\partial \\mathcal{L}}{\\partial w}\n&quot;,&quot;id&quot;:&quot;WMNFJUXZJS&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Considering <strong>the learning rate as 0.5</strong>, here are the hidden nodes &#8594; output weight updates:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{h_1 \\to y}\n= 0.20 - 0.5 \\cdot 0.034112\n= 0.20 - 0.017056\n= 0.182944\n&quot;,&quot;id&quot;:&quot;UIRWWVUHOG&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{h_2 \\to y} = -0.15\n&quot;,&quot;id&quot;:&quot;NZZJWCCOAZ&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{h_3 \\to y}\n= 0.25 - 0.5 \\cdot 0.039442\n= 0.25 - 0.019721\n= 0.230279\n&quot;,&quot;id&quot;:&quot;GJLSCUGFNW&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;b_y = 0.10 - 0.5 \\cdot 0.533\n= 0.10 - 0.2665\n= -0.1665&quot;,&quot;id&quot;:&quot;XTSWTVPQZL&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Now, for the hidden node <em>h1</em> updates:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{x_1 \\to h_1}\n= 0.15 - 0.5 \\cdot 0.02132\n= 0.15 - 0.01066\n= 0.13934\n&quot;,&quot;id&quot;:&quot;NXVRGQHJWK&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{x_2 \\to h_1}\n= -0.22 - 0.5 \\cdot 0.03198\n= -0.22 - 0.01599\n= -0.23599\n&quot;,&quot;id&quot;:&quot;YDPIIZPKRO&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;b_{h_1}\n= 0.10 - 0.5 \\cdot 0.1066\n= 0.10 - 0.0533\n= 0.0467\n\n&quot;,&quot;id&quot;:&quot;LZUJCXBVCD&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>The hidden <em>h2</em> suffers no updates:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{x_1 \\to h_2} = -0.18&quot;,&quot;id&quot;:&quot;EZIAZKMVRC&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{x_2 \\to h_2} = 0.25\n&quot;,&quot;id&quot;:&quot;GENMMMIEGU&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;b_{h_2} = -0.10\n&quot;,&quot;id&quot;:&quot;HXZXWYGVYX&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>And finally the hidden <em>h3</em> node updates:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{x_1 \\to h_3}\n= 0.30 - 0.5 \\cdot 0.02665\n= 0.30 - 0.013325\n= 0.286675\n\n&quot;,&quot;id&quot;:&quot;TZWONIAMAI&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;w_{x_2 \\to h_3}\n= -0.12 - 0.5 \\cdot 0.039975\n= -0.12 - 0.0199875\n= -0.1399875\n\n&quot;,&quot;id&quot;:&quot;OJBRVCPCUG&quot;}" data-component-name="LatexBlockToDOM"></div><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;b_{h_3}\n= 0.05 - 0.5 \\cdot 0.13325\n= 0.05 - 0.066625\n= -0.016625\n\n&quot;,&quot;id&quot;:&quot;NEDXAWAHLK&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>All of these calculations are in fact what the gradient vector is all about: all the individual gradients stacked together. Formally:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\nabla_{\\theta}\\mathcal{L}\n=\n\\begin{bmatrix}\n\\frac{\\partial \\mathcal{L}}{\\partial w_{h_1 \\to y}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{h_2 \\to y}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{h_3 \\to y}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial b_y} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{x_1 \\to h_1}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{x_2 \\to h_1}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial b_{h_1}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{x_1 \\to h_2}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{x_2 \\to h_2}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial b_{h_2}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{x_1 \\to h_3}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial w_{x_2 \\to h_3}} \\\\\n\\frac{\\partial \\mathcal{L}}{\\partial b_{h_3}}\n\\end{bmatrix}\n&quot;,&quot;id&quot;:&quot;LJVHKPLEIY&quot;}" data-component-name="LatexBlockToDOM"></div><p>And with filled in values:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\nabla_{\\theta}\\mathcal{L}\n=\n\\begin{bmatrix}\n0.034112 \\\\\n0 \\\\\n0.039442 \\\\\n0.533 \\\\\n0.02132 \\\\\n0.03198 \\\\\n0.1066 \\\\\n0 \\\\\n0 \\\\\n0 \\\\\n0.02665 \\\\\n0.039975 \\\\\n0.13325\n\\end{bmatrix}&quot;,&quot;id&quot;:&quot;EFRKCAWZYG&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>So the gradient descent in vector form is like this:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\theta_{\\text{new}}\n=\n\\theta_{\\text{old}}\n-\n\\eta\n\\begin{bmatrix}\n0.034112 \\\\\n0 \\\\\n0.039442 \\\\\n0.533 \\\\\n0.02132 \\\\\n0.03198 \\\\\n0.1066 \\\\\n0 \\\\\n0 \\\\\n0 \\\\\n0.02665 \\\\\n0.039975 \\\\\n0.13325\n\\end{bmatrix}\n&quot;,&quot;id&quot;:&quot;GEXKLOSVSV&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>Whew, and finally after all these calculations, the weights are updated with all these calculated values respectively. Now when the training process picks up a second sample - like the one below, an &#8220;average student&#8221;, where <strong>x1 = 0.5</strong> and <strong>x2 = 0.6</strong> -  the forward pass of this second sample already shows weights updated by the previous training process.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Fi4n!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Fi4n!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 424w, https://substackcdn.com/image/fetch/$s_!Fi4n!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 848w, https://substackcdn.com/image/fetch/$s_!Fi4n!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 1272w, https://substackcdn.com/image/fetch/$s_!Fi4n!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Fi4n!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png" width="1456" height="1285" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1285,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:515233,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.dimensionalityreduction.com/i/182271606?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Fi4n!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 424w, https://substackcdn.com/image/fetch/$s_!Fi4n!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 848w, https://substackcdn.com/image/fetch/$s_!Fi4n!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 1272w, https://substackcdn.com/image/fetch/$s_!Fi4n!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4994e148-912e-4383-a5eb-e6e6e10a4d96_1656x1462.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>If you watch closely and compare with the weights in the beginning, they&#8217;ve changed! Each weight was updated in proportion to how much it contributed to the error. Active neurons update their weights, inactive neurons remain unchanged, and the model moves step by step toward lower loss.</p><p>And from here on the network would continue training and would iterate on all the available samples, sometimes more than once, that is, more than <strong>1 epoch</strong>.</p><p>In theory, gradient descent computes the gradient using the entire training dataset. In practice, this is computationally expensive. <strong>Stochastic Gradient Descent</strong> (SGD) approximates the true gradient by computing it on a small random subset of the data. If you have a million points as training dataset, you would pick a batch size, let&#8217;s say 128. Then it would pick 128 samples randomly from the entire dataset (that&#8217;s why it&#8217;s called stochastic) and average them. Only then it would update the weights. This introduces noise into the optimization process, but dramatically speeds up training and often improves generalization. Most modern neural networks are trained using mini-batch SGD or adaptive variants such as Adam.</p><p></p><p></p><p>Well and this is it for Part 1. This post about LLM&#8217;s from scratch doesn&#8217;t have a lot of LLM specifics really, but these basic ANN building blocks are crucial for understanding what lies ahead. Next time we will do a deep dive on what kind of ANN&#8217;s LLM&#8217;s are built on and how are they effectively trained.</p><p>Until next time!</p><p></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://www.dimensionalityreduction.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Dimensionality Reduction! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item></channel></rss>