<?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"><channel><title><![CDATA[Engineering Intelligence]]></title><description><![CDATA[Engineering Intelligence explores artificial intelligence and machine learning from first principles, bridging mathematical foundations, intuitive understanding]]></description><link>https://blog.vikassrinivasa.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 13 Nov 2026 06:11:19 GMT</lastBuildDate><atom:link href="https://blog.vikassrinivasa.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Transformer Decoders Explained: The Process of Backpropagation and Inference (Part 7)]]></title><description><![CDATA[Understanding Decoder Backpropagation and Inference Intuitively]]></description><link>https://blog.vikassrinivasa.dev/transformer-decoders-explained-the-process-of-backpropagation-and-inference-part-7</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/transformer-decoders-explained-the-process-of-backpropagation-and-inference-part-7</guid><category><![CDATA[transformers intuition]]></category><category><![CDATA[nlp transformers]]></category><category><![CDATA[nlp]]></category><category><![CDATA[transformers]]></category><category><![CDATA[Transformers in LLM]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Wed, 05 Mar 2025 13:57:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/265c06273063d7e0ed974916bf230b17.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In our previous blogs, we explored the <strong>decoder phase</strong> of the Transformer in detail, covering its architecture, attention mechanisms, and how it processes input sequences. If you haven’t read those yet, I highly recommend checking them out for a strong foundational understanding before diving into this one.</p>
<blockquote>
<p>Check out my blog on decoder phase of transformers here - <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-decoder-forward-pass-mechanism-and-key-insights-part-5">Transformer Decoder: Forward Pass Mechanism and Key Insights (part 5)</a>.</p>
</blockquote>
<p>Now, in this final installment of our series on Transformers, we go a step further—unveiling the <strong>mathematical underpinnings of backpropagation</strong> and <strong>how gradients guide learning</strong> in the training phase. We will also take a deep dive into <strong>the inference phase</strong>, where the Transformer <strong>generates text in an auto-regressive manner</strong>, one token at a time.</p>
<p>By the end of this blog, you will have a <strong>clear understanding</strong> of how Transformer decoders optimize learning and generate accurate sequences in real-world applications like machine translation, text generation, and beyond. Let’s get started! 🚀</p>
<h1 id="heading-decoder-backpropagation-in-the-training-phase">Decoder - BackPropagation In the Training Phase</h1>
<p>The weights and biases across all the various layers are learned during backpropagation. We will use Gradient descent algorithm for this. During the training phase the transformer’s output is a matrix of order \(M \times V_c\) where \(M\) is the number of tokens in the ground truth sequence and \(V_c\) the total number of unique tokens in the target vocabulary. This matrix essentially represents each token position in the ground truth as rows and each unique token in the vocabulary as a column. This means that the values in each row in this matrix denote the probability that the corresponding column token is the correct token for row position in the ground truth sequence.</p>
<p>We compute how far off the transformers predictions were from the ground truth using a loss function and we use gradient descent to compute how much each weight and bias contributes to this loss by finding the gradients of this loss with respect to each weight and bias. These gradients are then used to update the weights and biases. This is done until the loss is minimized to a desired value or for a set number of iterations called epochs.</p>
<h3 id="heading-loss-function-for-training-transformers-for-machine-translation">Loss Function for Training Transformers for Machine Translation</h3>
<p>The most commonly used <strong>loss function</strong> for training transformers on sequence-to-sequence tasks like machine translation is the <strong>Cross-Entropy Loss</strong>. This is a token-level loss that measures the difference between the predicted token probabilities and the ground truth tokens in the target sequence.</p>
<hr />
<h3 id="heading-1-cross-entropy-loss">1. <strong>Cross-Entropy Loss</strong></h3>
<p>The loss for a single target sequence is computed as:</p>
<p>$$\mathcal{L} = -\frac{1}{T} \sum_{t=1}^T \sum_{i=1}^{|V_c|} y_t^{\text{true}}[i] \log(y_t^{\text{pred}}[i])$$</p><p>Where:</p>
<ul>
<li><p>\(T\) : Length of the target sequence.</p>
</li>
<li><p>\(V_c\) : Size of the target vocabulary.</p>
</li>
<li><p>\(y_t^{\text{true}}\) : One-hot encoded true token at time step .</p>
</li>
<li><p>\(y_t^{\text{pred}}\) : Predicted probability distribution over the vocabulary for the t-th token (output of the softmax layer).</p>
</li>
</ul>
<p>The prediction probabilities \(y_t^{\text{pred}}\) come from the decoder output after applying the <strong>softmax</strong> function.</p>
<ul>
<li><p>For each time step \(t\), the loss ploenalizes the model for predicting probabilities far from the ground truth token's one-hot encoding</p>
</li>
<li><p>The average loss over all tokens in the sequence ensures equal contribution regardless of sequence length.</p>
</li>
</ul>
<hr />
<h3 id="heading-why-cross-entropy-for-machine-translation"><strong>Why Cross-Entropy for Machine Translation?</strong></h3>
<ul>
<li><p><strong>Multi-Class Output:</strong> At each time step, the decoder predicts the next token from a vocabulary of size \(|V_c|\), making it a multi-class classification problem.</p>
</li>
<li><p><strong>Alignment with Likelihood Maximization:</strong> Cross-entropy loss directly corresponds to minimizing the negative log-likelihood of the correct sequence.</p>
</li>
<li><p><strong>Efficient Backpropagation:</strong> Cross-entropy loss is differentiable, enabling gradient computation for weight updates during backpropagation.</p>
</li>
</ul>
<hr />
<h3 id="heading-how-it-works-for-each-position">How It Works for Each Position</h3>
<ol>
<li><p><strong>At timestep</strong> \(t\)<strong>:</strong></p>
<ul>
<li><p>The decoder generates \(y_t^{\text{pred}}\) , a probability distribution over the vocabulary using a softmax layer.</p>
</li>
<li><p>The ground truth token for \(t\) , \(y_t^{\text{true}}\) is a one-hot vector where the index corresponding to the correct token is 1, and the rest are 0.</p>
</li>
</ul>
</li>
<li><p>The <strong>Cross-Entropy Loss</strong> computes:</p>
<p> $$\mathcal{L}t = - \sum{i=1}^{|V_c|} y_t^{\text{true}}[i] \log(y_t^{\text{pred}}[i])$$</p>
<ul>
<li><p>Since \(y_t^{\text{true}}\) is one-hot encoded, this simplifies to:</p>
<p>  $$\mathcal{L}_t = - \log(y_t^{\text{pred}}[\text{correct_index}])$$</p>
</li>
<li><p>Only the probability assigned to the correct token contributes to the loss.</p>
</li>
</ul>
</li>
<li><p>The total loss over the sequence is the average of these token-level losses:</p>
<p> $$\mathcal{L} = -\frac{1}{T} \sum_{t=1}^T \log(y_t^{\text{pred}}[\text{correct_index}])$$</p>
</li>
</ol>
<hr />
<h1 id="heading-computing-gradients">Computing gradients</h1>
<p>In a simplified Transformer model where we have 1 encoder, 1 attention head, 1 feedforward layer, 1 decoder, 1 masked attention head, 1 encoder-decoder attention layer, 1 feedforward layer, and 1 final output layer, the gradients that need to be computed and the corresponding chain rule equations are listed below:</p>
<hr />
<h3 id="heading-gradients-to-compute-in-each-layer"><strong>Gradients to Compute in Each Layer</strong></h3>
<h3 id="heading-1-encoder">1. <strong>Encoder</strong></h3>
<ul>
<li><p><strong>Multi-Head Self-Attention Layer:</strong></p>
<ul>
<li><p>Gradients for Query, Key, and Value weights ( \(W_Q, W_K, W_V\) ):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_Q},\frac{\partial \mathcal{L}}{\partial W_K} , \frac{\partial \mathcal{L}}{\partial W_V}$$</p>
</li>
<li><p>Gradient for the attention projection weight ( \(W_O\) ):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_O}$$</p>
</li>
</ul>
</li>
<li><p><strong>Feedforward Layer:</strong></p>
<ul>
<li><p>Gradients for the two feedforward weights ( \(W_1, W_2\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_1}, \frac{\partial \mathcal{L}}{\partial W_2}$$</p>
</li>
<li><p>Gradients for biases ( \(b_1, b_2\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial b_1},\frac{\partial \mathcal{L}}{\partial b_2}$$</p>
</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-2-decoder">2. <strong>Decoder</strong></h3>
<ul>
<li><p><strong>Masked Multi-Head Attention Layer:</strong></p>
<ul>
<li><p>Gradients for Query, Key, and Value weights ( \(W_Q^{\text{masked}}, W_K^{\text{masked}}, W_V^{\text{masked}}\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_Q^{\text{masked}}},\frac{\partial \mathcal{L}}{\partial W_K^{\text{masked}}},\frac{\partial \mathcal{L}}{\partial W_V^{\text{masked}}}$$</p>
</li>
<li><p>Gradient for the attention projection weight ( \(W_O^{\text{masked}}\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_O^{\text{masked}}}$$</p>
</li>
</ul>
</li>
<li><p><strong>Encoder-Decoder Attention Layer:</strong></p>
<ul>
<li><p>Gradients for Query, Key, and Value weights ( \(W_Q^{\text{enc-dec}}, W_K^{\text{enc-dec}}, W_V^{\text{enc-dec}}\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_Q^{\text{enc-dec}}},\frac{\partial \mathcal{L}}{\partial W_K^{\text{enc-dec}}},\frac{\partial \mathcal{L}}{\partial W_V^{\text{enc-dec}}}$$</p>
</li>
<li><p>Gradient for the attention projection weight ( \(W_O^{\text{enc-dec}}\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_O^{\text{enc-dec}}}$$</p>
</li>
</ul>
</li>
<li><p><strong>Feedforward Layer:</strong></p>
<ul>
<li><p>Gradients for the two feedforward weights ( \(W_1^{\text{dec}}, W_2^{\text{dec}}\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_1^{\text{dec}}},\frac{\partial \mathcal{L}}{\partial W_2^{\text{dec}}}$$</p>
</li>
<li><p>Gradients for biases ( \(b_1^{\text{dec}}, b_2^{\text{dec}}\)):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial b_1^{\text{dec}}},\frac{\partial \mathcal{L}}{\partial b_2^{\text{dec}}}$$</p>
</li>
</ul>
</li>
<li><p><strong>Final Output Layer:</strong></p>
<ul>
<li><p>Gradient for the output projection weight ( \(W_{\text{out}}\) ):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_{\text{out}}}$$</p>
</li>
<li><p>Gradient for the output bias ( \(b_{\text{out}}\) ):</p>
<p>  $$\frac{\partial \mathcal{L}}{\partial b_{\text{out}}}$$</p>
</li>
</ul>
</li>
</ul>
<hr />
<h3 id="heading-chain-rule-equations-for-each-gradient"><strong>Chain Rule Equations for Each Gradient</strong></h3>
<ol>
<li><p><strong>Final Output Layer Gradients:</strong></p>
<ul>
<li><p><strong>Output weights (</strong> \(W_{\text{out}}\) <strong>):</strong></p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_{\text{out}}} = \frac{\partial \mathcal{L}}{\partial y_t^{\text{pred}}} \cdot \frac{\partial y_t^{\text{pred}}}{\partial z_t} \cdot \frac{\partial z<em>t}{\partial W</em>{\text{out}}}$$</p>
<p>  Where:</p>
<ul>
<li>\(z_t\) : Logits before the softmax.</li>
</ul>
</li>
<li><p><strong>Output bias (</strong> \(b_{\text{out}}\) <strong>):</strong></p>
<p>  $$\frac{\partial \mathcal{L}}{\partial b_{\text{out}}} = \frac{\partial \mathcal{L}}{\partial y_t^{\text{pred}}} \cdot \frac{\partial y_t^{\text{pred}}}{\partial z_t} \cdot \frac{\partial z<em>t}{\partial b</em>{\text{out}}}$$</p>
</li>
</ul>
</li>
<li><p><strong>Decoder Feedforward Gradients:</strong></p>
<ul>
<li><p><strong>First layer weights (</strong> \(W_1^{\text{dec}}\) <strong>):</strong></p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_1^{\text{dec}}} = \frac{\partial \mathcal{L}}{\partial h_2} \cdot \frac{\partial h_2}{\partial h_1} \cdot \frac{\partial h_1}{\partial W_1^{\text{dec}}}$$</p>
</li>
<li><p><strong>Second layer weights (</strong> \(W_2^{\text{dec}}\) <strong>):</strong></p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_2^{\text{dec}}} = \frac{\partial \mathcal{L}}{\partial h_2} \cdot \frac{\partial h_2}{\partial W_2^{\text{dec}}}$$</p>
</li>
</ul>
</li>
<li><p><strong>Encoder-Decoder Attention Gradients:</strong></p>
<ul>
<li><p><strong>Query weights (</strong> \(W_Q^{\text{enc-dec}}\) <strong>):</strong></p>
<p>  $$\frac{\partial \mathcal{L}}{\partial W_Q^{\text{enc-dec}}} = \frac{\partial \mathcal{L}}{\partial \alpha} \cdot \frac{\partial \alpha}{\partial Q} \cdot \frac{\partial Q}{\partial W_Q^{\text{enc-dec}}}$$</p>
</li>
<li><p>Similarly for \(W_K^{\text{enc-dec}}, W_V^{\text{enc-dec}},W_O^{\text{enc-dec}}\).</p>
</li>
</ul>
</li>
<li><p><strong>Masked Multi-Head Self-Attention Gradients:</strong></p>
<ul>
<li>Same formulas as for Encoder-Decoder Attention, but keys and values come from the decoder's \(T_{\text{input}}\).</li>
</ul>
</li>
<li><p><strong>Encoder Feedforward and Attention Gradients:</strong></p>
<ul>
<li>Identical to decoder feedforward and attention gradients, applied to the encoder's hidden states.</li>
</ul>
</li>
</ol>
<hr />
<h2 id="heading-weight-and-bias-updation-rule">Weight and Bias Updation Rule</h2>
<p>The weights and biases are updated using the formula</p>
<p>$$quantity=quantity- \alpha \times \frac{\partial \mathcal{L}}{\partial quantity}$$</p><h2 id="heading-minimizing-loss">Minimizing loss</h2>
<p>The Transformer computes the forward pass again with the updated weights and biases. The losses and gradients are recomputed and the weights are updated again. This process repeats until we minimize the loss to a desired value or for a fixed number of epochs.</p>
<hr />
<p>Now that we have understood the training phase, let’s now look at how the transformer works in the Inference Phase.</p>
<h1 id="heading-inference-phase">Inference Phase</h1>
<p>During inference, the <strong>encoder</strong> in the Transformer functions the same way as during training. It performs the following operations:</p>
<ul>
<li><p>Computes the <strong>attention outputs</strong>.</p>
</li>
<li><p>Passes them through a <strong>feedforward network (FFN)</strong>.</p>
</li>
<li><p>Adds <strong>residual connections</strong> and applies <strong>layer normalization</strong>.</p>
</li>
</ul>
<p>The key difference between training and inference lies in how the <strong>decoder</strong> operates. Unlike training, during inference, the decoder does not have access to the ground truth target sequence. Instead, it must <strong>generate the target sequence one token at a time cyclically</strong>. This mechanism is referred to as <strong>Auto Regressive Generation</strong>.</p>
<blockquote>
<p>Auto-regressive generation is a step-by-step process where a model generates output one token at a time. Each newly generated token is fed back into the model as input, along with previous tokens, until the entire sequence is produced.</p>
</blockquote>
<h3 id="heading-how-the-decoder-functions-during-inference">How the Decoder Functions During Inference:</h3>
<ol>
<li><p><strong>Initialization</strong>:</p>
<p> The decoder begins with only the <strong>start-of-sequence (SOS)</strong> token as input.</p>
</li>
<li><p><strong>Token Generation Cycle</strong>:</p>
<ul>
<li><p>At each timestep, the decoder generates one token, appends it to the current sequence, and uses the updated sequence as the input for the next timestep.</p>
</li>
<li><p>This process repeats until the <strong>end-of-sequence (EOS)</strong> token is generated or a predefined maximum sequence length is reached.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-step-by-step-breakdown-of-how-the-decoder-generates-text-in-inference"><strong>Step-by-Step Breakdown Of How the Decoder Generates Text in Inference</strong></h2>
<p>Let’s illustrate <strong>how a Transformer decoder works during inference</strong> with an example:<br /><strong>Task:</strong> Translate <strong>"Varun loves cricket and finance."</strong> into <strong>French</strong>.<br /><strong>Assumption:</strong> The encoder has already processed the sentence and produced <strong>contextual embeddings</strong>.</p>
<p>Now, let’s go through the <strong>inference process step by step</strong>.</p>
<ol>
<li><p><strong>Step 1 (Decoder Initialization)</strong>:</p>
<ul>
<li><p>The decoder receives the SOS token as input, represented as a matrix of size \(1 \times D\), where \(D\) is the embedding dimension.</p>
</li>
<li><p>The <strong>masked attention layer</strong> processes this input. Since only the SOS token is present, no masking is applied at this stage.</p>
</li>
<li><p>The <strong>alignment scores</strong> are computed, these scores are then normalized using the softmax function, and passed through the subsequent decoder layers just like in training phase.</p>
</li>
<li><p>The <strong>output layer</strong> projects the final representation over the vocabulary space to generate a \(1×V_c\) matrix, where \(V_c\) is the size of the vocabulary. This matrix contains the probabilities of all tokens in the vocabulary.</p>
</li>
<li><p>The token with the highest probability is selected as the first output token ( \(y_1\) ), which is then appended to the SOS token.</p>
</li>
<li><p>Example Output for Step 1:</p>
<ul>
<li><p>The decoder receives the input <code>[SOS]</code> , the decoder generates the first token (e.g., "Varun"), the decoder takes this token and appends it to the input sequence.</p>
</li>
<li><p>The updated sequence now becomes a matrix with:</p>
<ul>
<li><p><strong>First row:</strong> <code>[SOS]</code> token.</p>
</li>
<li><p><strong>Second row:</strong> The first generated token, e.g., "Varun".</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1741231081044/88c2a297-0812-431d-ad82-d73ca7e64936.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Step 2 (Next Cycle)</strong>:</p>
<ul>
<li><p><strong>Input</strong>: The decoder now receives the updated sequence \([SOS,y_1]\), represented as a matrix of size \(2×D\).</p>
</li>
<li><p>The decoder computes the <strong>query (Q)</strong>, <strong>key (K)</strong>, and <strong>value (V)</strong> matrices for this input and updates the <strong>mask matrix</strong> to enforce causal masking.</p>
</li>
<li><p>The updated mask matrix for two tokens looks like this:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1741231110672/27f81cf0-bc92-4471-9021-26264cd19384.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>The masked alignment scores are calculated, normalized, and passed through the remaining layers. The next token ( \(y_2\)) is predicted and appended to the sequence.</p>
</li>
<li><p>Example Output for Step 2:</p>
<ul>
<li><p>The Input to the decoder is now → <code>[SOS, "Varun"]</code>.</p>
</li>
<li><p>Masked attention processes both tokens and the Encoder-decoder attention attends to the encoder output. The decoder then predicts the second token, e.g., "aime."</p>
</li>
<li><p>The output at this step is now <code>[SOS, "Varun", "aime"]</code></p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Subsequent Steps</strong>:</p>
<ul>
<li><p>The process repeats, with the input sequence growing at each step ( \([SOS,y_1,y_2,…]\) ), and the <strong>mask matrix</strong> dynamically expands to ensure each token attends only to itself and previous tokens.</p>
</li>
<li><p>For example:</p>
<ul>
<li><p><strong>Cycle 3</strong>: The mask matrix for three tokens would be:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1741231136736/c1ea3ea5-b453-4084-82a7-82bf29960610.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
</li>
<li><p>The output for the example we considered given the input to the decoder is → <code>[SOS, "Varun", "aime"]</code> will be <code>[SOS, "Varun", "aime", "le"]</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Termination</strong>:</p>
<ul>
<li><p>The process continues until the decoder generates the EOS token or the maximum sequence length is reached.</p>
</li>
<li><p>The final output for the example we considered will be → "Varun aime le cricket et la finance." We obtain this output by a process called detokenization wherein the generated tokens are combined together and then returned as the output.</p>
</li>
</ul>
</li>
</ol>
<p><strong>Result</strong>: The decoder outputs the French translation: "Varun aime le cricket et la finance."</p>
<hr />
<h1 id="heading-key-difference-between-training-and-inference-phase-of-the-decoder">Key Difference Between Training and Inference Phase Of The Decoder</h1>
<p>During the <strong>inference phase</strong>, the key difference in the decoder lies in the absence of the <strong>ground truth target sequence</strong>. Instead, the decoder generates the target sequence <strong>token by token</strong>, using its own previously generated tokens as input at each decoding step.</p>
<p>Here’s how it differs from the training phase:</p>
<hr />
<h3 id="heading-1-input-to-the-decoder"><strong>1. Input to the Decoder</strong></h3>
<ul>
<li><p><strong>Training Phase:</strong></p>
<ul>
<li><p>The decoder receives the <strong>entire ground truth target sequence</strong> (e.g., in French: "Varun aime le cricket et la finance.") as input for the Masked Multi-Head Attention.</p>
</li>
<li><p>Masking ensures that the decoder can only attend to tokens up to the current timestep.</p>
</li>
</ul>
</li>
<li><p><strong>Inference Phase:</strong></p>
<ul>
<li><p>The decoder starts with only the <strong>start-of-sequence (SOS)</strong> token as input.</p>
</li>
<li><p>At each timestep, the decoder generates a token, appends it to the sequence, and feeds the updated sequence back as input.</p>
</li>
<li><p>This process repeats until the <strong>end-of-sequence (EOS)</strong> token is generated or a predefined maximum sequence length is reached.</p>
</li>
<li><p>For example:</p>
<ul>
<li><p>Step 1: <code>[SOS]</code></p>
</li>
<li><p>Step 2: <code>[SOS, "Varun"]</code></p>
</li>
<li><p>Step 3: <code>[SOS, "Varun", "aime"]</code>, and so on.</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="heading-2-sequence-generation"><strong>2. Sequence Generation</strong></h3>
<ul>
<li><p><strong>Training Phase:</strong></p>
<ul>
<li>The entire sequence is available at once, so the decoder can compute all tokens in parallel during a single forward pass.</li>
</ul>
</li>
<li><p><strong>Inference Phase:</strong></p>
<ul>
<li><p>Tokens are generated sequentially, one at a time, in an <strong>autoregressive</strong> manner.</p>
</li>
<li><p>At timestep \(t\), the decoder uses:</p>
<ul>
<li><p>The encoder output.</p>
</li>
<li><p>The previously generated sequence .</p>
<p>  \([SOS, y_1, y_2, \dots, y_{t-1}]\)</p>
</li>
<li><p>The attention mechanism to predict the next token \(y_t\).</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="heading-3-parallel-vs-sequential-processing"><strong>3. Parallel vs. Sequential Processing</strong></h3>
<ul>
<li><p><strong>Training Phase:</strong></p>
<ul>
<li>The decoder processes the target sequence in <strong>parallel</strong>, allowing for efficient computation.</li>
</ul>
</li>
<li><p><strong>Inference Phase:</strong></p>
<ul>
<li>The decoder operates <strong>sequentially</strong>, generating one token at a time. This is computationally slower compared to training.</li>
</ul>
</li>
</ul>
<h3 id="heading-4-predictions"><strong>4. Predictions</strong></h3>
<ul>
<li><p><strong>Training Phase:</strong></p>
<ul>
<li>The model predicts token probabilities for all positions simultaneously, compared against the ground truth using the Cross-Entropy Loss.</li>
</ul>
</li>
<li><p><strong>Inference Phase:</strong></p>
<ul>
<li><p>At each timestep, the decoder outputs a probability distribution over the vocabulary for the next token.</p>
</li>
<li><p>The token with the highest probability (or another strategy like beam search) is selected and added to the generated sequence.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-5-dynamic-masking">5. Dynamic Masking</h3>
<ul>
<li><p><strong>Training Phase:</strong></p>
<ul>
<li>The model uses a static mask to compute the masked attention scores.</li>
</ul>
</li>
<li><p><strong>Inference Phase:</strong></p>
<ul>
<li><p>The mask matrix dynamically adjusts to ensure that each token can only attend to itself and the tokens before it (causal masking).</p>
</li>
<li><p>For example:</p>
<ul>
<li><p>Cycle 1 (only SOS token):</p>
<p>  $$\text{Mask} = [0]$$</p>
</li>
<li><p>Cycle 2 (SOS + 1st generated token):</p>
<p>  $$\text{Mask} = \begin{bmatrix} 0 &amp; -\infty \ 0 &amp; 0 \end{bmatrix}$$</p>
</li>
<li><p>Cycle 3 (SOS + 1st + 2nd generated tokens):</p>
<p>  $$\text{Mask} = \begin{bmatrix} 0 &amp; -\infty &amp; -\infty \ 0 &amp; 0 &amp; -\infty \ 0 &amp; 0 &amp; 0 \end{bmatrix}$$</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>And with that, we conclude our deep dive into Transformer decoders! Throughout this series, we have uncovered the <strong>inner workings of the Transformer</strong>, from <strong>how it processes input sequences</strong> to <strong>how it learns through backpropagation</strong> and <strong>generates outputs during inference</strong>.</p>
<p>Key Takeaways:</p>
<ul>
<li><p>The <strong>training phase</strong> involves computing <strong>gradients</strong> and updating <strong>weights</strong> using <strong>backpropagation</strong> to minimize loss.</p>
</li>
<li><p>The <strong>inference phase</strong> follows an <strong>auto-regressive generation</strong> approach, where tokens are produced <strong>sequentially</strong> rather than in parallel.</p>
</li>
<li><p><strong>Masking techniques</strong> ensure that the model processes only relevant context at each step, preventing "cheating" by looking ahead.</p>
</li>
</ul>
<p>Transformers have revolutionized NLP, powering models like <strong>GPT, BERT, and T5</strong>. But as the field evolves, we’re seeing <strong>even more efficient architectures</strong> like <strong>Mixture of Experts (MoE) models, Retrieval-Augmented Transformers (RAG), and multimodal AI systems</strong> shaping the future.</p>
<p>I hope this series has provided you with a solid <strong>intuitive and mathematical understanding</strong> of how Transformers work. If you have any thoughts, questions, or ideas for future deep dives, feel free to share them!</p>
]]></content:encoded></item><item><title><![CDATA[Transformer Decoder: Forward Pass Mechanism and Key Insights (part 6)]]></title><description><![CDATA[Step-by-Step Guide to Decoder Forward Pass in Transformers]]></description><link>https://blog.vikassrinivasa.dev/transformer-decoder-forward-pass-mechanism-and-key-insights-part-6</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/transformer-decoder-forward-pass-mechanism-and-key-insights-part-6</guid><category><![CDATA[nlp transformers]]></category><category><![CDATA[nlp]]></category><category><![CDATA[encoder decoder]]></category><category><![CDATA[decoder]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Thu, 20 Feb 2025 03:28:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/265c06273063d7e0ed974916bf230b17.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we dive deep into the <strong>forward pass of the Transformer decoder</strong>, focusing on how it interacts with the encoder through cross-attention, refines token representations using feed-forward networks, and ultimately predicts the next token in the sequence. By breaking down each step—alignment scoring, softmax normalization, attention projection, and layer normalization—we build a clear understanding of how the decoder processes input information to generate accurate translations or text completions.</p>
<h2 id="heading-computing-the-encoder-decoder-cross-attention">Computing the Encoder-Decoder Cross Attention</h2>
<p>The next component of the Decoder is a Encoder-Decoder attention.</p>
<p>The encoder-decoder cross-attention mechanism connects the encoder’s contextualized representations of the input sequence with the decoder’s generation of the output sequence. It teaches the decoder to map the enriched encoder outputs to the ground truth passed to the decoder during teacher forcing.</p>
<p><strong>This layer is specially designed to determine how much attention each token in the ground truth sequence should pay to each token and dimension in the context-rich input sequence produced by the encoder</strong>.</p>
<p>There can be multiple layers of encoder-decoder attention for our example we are considering one.</p>
<h3 id="heading-1-purpose-of-the-encoder-decoder-attention-layer"><strong>1. Purpose of the Encoder-Decoder Attention Layer</strong></h3>
<h3 id="heading-11-bridge-between-encoder-and-decoder"><strong>1.1 Bridge Between Encoder and Decoder</strong></h3>
<ul>
<li><p>The <strong>encoder</strong> processes the input (e.g., English sentence) and generates <strong>context-rich embeddings</strong> for each token.</p>
</li>
<li><p>The <strong>decoder</strong> generates the output (e.g., French translation) using this contextual understanding.</p>
</li>
<li><p>The encoder-decoder attention layer allows the decoder to <strong>retrieve relevant information from the encoder</strong> at each decoding step.</p>
</li>
</ul>
<h3 id="heading-12-focus-on-relevant-parts-of-the-input"><strong>1.2 Focus on Relevant Parts of the Input</strong></h3>
<ul>
<li><p>Each <strong>target token</strong> should attend to <strong>the most relevant source tokens</strong>.</p>
</li>
<li><p>For example, while translating <strong>"cricket"</strong>, the decoder should focus on <strong>"criquet"</strong> in the source sequence.</p>
</li>
</ul>
<h3 id="heading-2-inputs-to-encoder-decoder-attention"><strong>2. Inputs to Encoder-Decoder Attention</strong></h3>
<p>Each Encoder-Decoder head takes 2 inputs:</p>
<ol>
<li><p><strong>The masked attention output</strong> \(Q_d\)</p>
<ul>
<li><p>Serves as the query vector representing the partially generated target sequence.</p>
</li>
<li><p>The Query vector is derived from the output of the masked self-attention layer in the decoder.</p>
</li>
<li><p>It represents the questions being asked by the current state of the ground truth sequence (or the partially generated target sequence) to map the context-rich input sequence from the encoder to the tokens in the target sequence.</p>
</li>
</ul>
</li>
<li><p><strong>The encoder output.</strong></p>
<ul>
<li><p>Serves as the key ( \(K_d\) ) and value ( \(V_d\) ) vectors, holding contextual embeddings of the source sequence.</p>
</li>
<li><p>The key matrix ( \(K_d\) ) represents the metadata about the encoder’s context-rich output.The value matrix ( \(V_d\) ) represents the actual content or information in the encoder’s context-rich output that is relevant for the task.</p>
</li>
<li><p>The Key and Value vectors are computed from the encoder’s output.</p>
</li>
<li><p>These are created by multiplying the encoder's output with learned weight matrices \(W_K\) and \(W_V\) respectively, which are of size \(D × (\frac{D}{h})\) where:</p>
<ul>
<li><p>\(D\) is the embedding dimension.</p>
</li>
<li><p>\(h\) is the number of attention heads.</p>
</li>
</ul>
</li>
<li><p>These inputs are used to derive the query, key and value vectors for the encoder-decoder attention layer denoted by \(Q_d\), \(K_d\) and \(V_d\) for each such layer.</p>
</li>
</ul>
</li>
</ol>
<p>where \(Q_d\), \(K_d\) and \(V_d\) are computed as</p>
<p>$$\begin{aligned} Q_d &amp;= \text{Masked Attention Output} \times W_{Qd} \\ K_d &amp;= \text{Encoder Output} \times W_{Kd} \\ V_d &amp;= \text{Encoder Output} \times W_{Vd} \end{aligned}$$</p><p>The <strong>Query</strong> (decoder’s contextualized understanding) interacts with the <strong>Keys</strong> (metadata from the encoder) to compute alignment scores that identify which parts of the input sequence are most relevant to the current decoding step. The <strong>Values</strong> (actual content from the encoder) provide the information needed for the decoder to generate the target token based on these alignment scores.</p>
<p>The Weight Matrix \(W_{Qd}\), \(W_{Kd}\) and \(W_{Vd}\) used in the example we considered are given below</p>
<p>$$\begin{array}{c c c} \textbf{Query Weight Matrix } (W_Q) &amp; \textbf{Key Weight Matrix } (W_K) &amp; \textbf{Value Weight Matrix } (W_V) \\ \begin{bmatrix} 0.3745 &amp; 0.9507 &amp; 0.7320 \\ 0.5987 &amp; 0.1560 &amp; 0.1560 \\ 0.0581 &amp; 0.8662 &amp; 0.6011 \end{bmatrix} &amp; \begin{bmatrix} 0.7081 &amp; 0.0206 &amp; 0.9699 \\ 0.8324 &amp; 0.2123 &amp; 0.1818 \\ 0.1834 &amp; 0.3042 &amp; 0.5248 \end{bmatrix} &amp; \begin{bmatrix} 0.4320 &amp; 0.2912 &amp; 0.6119 \\ 0.1395 &amp; 0.2921 &amp; 0.3664 \\ 0.4561 &amp; 0.7852 &amp; 0.1997 \end{bmatrix} \end{array}$$</p><p>The \(Q_d\), \(K_d\) and \(V_d\) vectors obtained are as follows :</p>
<p>$$\begin{array}{c c c} {Q_d} &amp; {K_d} &amp; {V_d} \\ \begin{bmatrix} 1.2040 &amp; 1.6229 &amp; 1.3741 \\ 1.1642 &amp; 1.5249 &amp; 1.3439 \\ 1.2093 &amp; 1.6202 &amp; 1.3871 \\ 1.1860 &amp; 1.5555 &amp; 1.3704 \\ 0.7762 &amp; 1.0511 &amp; 0.8792 \\ 0.7435 &amp; 0.9855 &amp; 0.8543 \\ 0.7554 &amp; 1.0133 &amp; 0.8733 \\ 0.7516 &amp; 0.9917 &amp; 0.8655 \\ -0.0720 &amp; -0.4547 &amp; 0.1067 \\ 0.6259 &amp; 1.0474 &amp; 0.6374 \\ 0.2013 &amp; 0.1109 &amp; 0.1203 \\ 0.3878 &amp; 0.7875 &amp; 0.3276 \end{bmatrix} &amp; \begin{bmatrix} 2.0255 &amp; 0.6438 &amp; 1.9469 \\ 1.9487 &amp; 0.5897 &amp; 1.9233 \\ 2.0405 &amp; 0.6402 &amp; 1.9653 \\ 1.9904 &amp; 0.6028 &amp; 1.9579 \\ 1.2949 &amp; 0.4174 &amp; 1.2496 \\ 1.2471 &amp; 0.3852 &amp; 1.2177 \\ 1.2920 &amp; 0.4027 &amp; 1.2280 \\ 1.2606 &amp; 0.3862 &amp; 1.2350 \\ -0.0428 &amp; -0.2864 &amp; 0.2265 \\ 1.0807 &amp; 0.4835 &amp; 0.8234 \\ -0.0858 &amp; -0.0521 &amp; 0.4378 \\ 0.6533 &amp; 0.3971 &amp; 0.3785 \end{bmatrix} &amp; \begin{bmatrix} 1.2040 &amp; 1.6229 &amp; 1.3741 \\ 1.1642 &amp; 1.5249 &amp; 1.3439 \\ 1.2093 &amp; 1.6202 &amp; 1.3871 \\ 1.1860 &amp; 1.5555 &amp; 1.3704 \\ 0.7762 &amp; 1.0511 &amp; 0.8792 \\ 0.7435 &amp; 0.9855 &amp; 0.8543 \\ 0.7554 &amp; 1.0133 &amp; 0.8733 \\ 0.7516 &amp; 0.9917 &amp; 0.8655 \\ -0.0720 &amp; -0.4547 &amp; 0.1067 \\ 0.6259 &amp; 1.0474 &amp; 0.6374 \\ 0.2013 &amp; 0.1109 &amp; 0.1203 \\ 0.3878 &amp; 0.7875 &amp; 0.3276 \end{bmatrix} \end{array}$$</p><hr />
<h3 id="heading-3-compute-the-alignment-score">3. Compute the Alignment Score</h3>
<p>The <strong>alignment score</strong> determines how much <strong>each target token attends to each source token</strong>.</p>
<p>The Alignment Score is computed as follows</p>
<p>$$Score(Q,K)=\frac{Q.K^{T}}{\sqrt{\frac{d}{\text{No. of Heads}}}}$$</p><p>The <strong>computed alignment scores</strong> are stored in a <strong>matrix</strong>:</p>
<p>$$\textbf{Alignment Scores} = \begin{bmatrix} 2.85 &amp; 2.75 &amp; 2.87 &amp; \dots &amp; 1.78 &amp; -0.12 &amp; 1.50 &amp; 0.18 &amp; 0.92 \\ 4.01 &amp; 3.86 &amp; 4.03 &amp; \dots &amp; 2.50 &amp; -0.16 &amp; 2.11 &amp; 0.25 &amp; 1.29 \\ 5.30 &amp; 5.11 &amp; 5.33 &amp; \dots &amp; 3.30 &amp; -0.22 &amp; 2.79 &amp; 0.34 &amp; 1.71 \\ \vdots &amp; \vdots &amp; \vdots &amp; \ddots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots \\ 4.37 &amp; 4.22 &amp; 4.40 &amp; \dots &amp; 2.73 &amp; -0.18 &amp; 2.30 &amp; 0.28 &amp; 1.41 \end{bmatrix}$$</p><hr />
<h3 id="heading-4-normalize-the-output-using-softmax">4. Normalize the output using Softmax</h3>
<p>We apply the <strong>softmax function</strong> to normalize alignment scores into <strong>probabilities</strong>.</p>
<p>$$α=Softmax(Score(Q, K))$$</p><p>The computed <strong>softmax weights</strong>:</p>
<p>$$\alpha = \begin{bmatrix} 0.17 &amp; 0.16 &amp; 0.18 &amp; 0.16 &amp; 0.06 &amp; 0.06 &amp; 0.06 &amp; 0.01 &amp; 0.04 &amp; 0.01 &amp; 0.03 \\ 0.20 &amp; 0.17 &amp; 0.21 &amp; 0.19 &amp; 0.05 &amp; 0.04 &amp; 0.05 &amp; 0.00 &amp; 0.03 &amp; 0.00 &amp; 0.01 \\ 0.22 &amp; 0.19 &amp; 0.23 &amp; 0.21 &amp; 0.03 &amp; 0.03 &amp; 0.03 &amp; 0.02 &amp; 0.00 &amp; 0.00 &amp; 0.01 \\ \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots &amp; \vdots \\ 0.21 &amp; 0.18 &amp; 0.22 &amp; 0.19 &amp; 0.04 &amp; 0.04 &amp; 0.04 &amp; 0.00 &amp; 0.02 &amp; 0.00 &amp; 0.01 \end{bmatrix}$$</p><hr />
<h3 id="heading-5-computing-the-attention-output">5. Computing the Attention Output</h3>
<p>The <strong>attention output</strong> is computed as:</p>
<p>$$\text{Attention Output}=α⋅V_d​$$</p><p>The <strong>computed attention output matrix</strong>:</p>
<p>$$\text{Attention Output} = \alpha \cdot V = \begin{bmatrix} 1.02 &amp; 1.37 &amp; 1.16 \\ 1.08 &amp; 1.44 &amp; 1.23 \\ 1.12 &amp; 1.49 &amp; 1.28 \\ 1.12 &amp; 1.50 &amp; 1.29 \\ 1.10 &amp; 1.46 &amp; 1.26 \\ 0.99 &amp; 1.33 &amp; 1.13 \\ 1.09 &amp; 1.45 &amp; 1.25 \\ 1.09 &amp; 1.46 &amp; 1.25 \\ 1.09 &amp; 1.45 &amp; 1.25 \\ 1.09 &amp; 1.46 &amp; 1.25 \end{bmatrix}$$</p><hr />
<h3 id="heading-6-projecting-the-attention-output">6. Projecting the Attention Output</h3>
<p>The <strong>attention output</strong> is projected back into the <strong>embedding space</strong> using a <strong>projection weight matrix(</strong>\(W_{edO}\)).</p>
<p>$$\text{Projected Output} = \text{Attention Output} \cdot W_{edO}$$</p><ul>
<li><p>Example <strong>Projection Matrix</strong> \(W_{edO}\) :</p>
<p>  $$W_{edO} = \begin{bmatrix} 0.3745 &amp; 0.9507 &amp; 0.7320 \ 0.5987 &amp; 0.1560 &amp; 0.1560 \ 0.0581 &amp; 0.8662 &amp; 0.6011 \end{bmatrix}$$</p>
</li>
<li><p>The projected output obtained by projecting back the attention output to the original embedding dimension D is as follows :</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740927353664/97476d71-7cee-44f7-984f-8f1cefb16857.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<hr />
<h3 id="heading-7-feed-forward-network-ffn">7. <strong>Feed Forward Network (FFN)</strong></h3>
<p>The projected output passes through an <strong>FFN</strong>:</p>
<p>$$FFN_{output} = (ReLU(\text{Final Attention Output}\times W_{d1}+b_{d1})\times W_{d2} +b_{d2})$$</p><p>where \(W_{d1}\) and \(W_{d2}\) are again weight matrices and \(b_{d1}\) and \(b_{d2}\) are the biases.</p>
<h3 id="heading-why-is-the-feed-forward-network-ffn-applied"><strong>Why is the Feed-Forward Network (FFN) Applied?</strong></h3>
<p>The <strong>Feed-Forward Network (FFN)</strong> acts as a <strong>final refinement layer</strong> that enhances the decoder’s representations before making predictions. It ensures that each token is <strong>processed individually</strong> while preserving the broader context learned from attention mechanisms.</p>
<h4 id="heading-1-fine-tuning-grammar-amp-meaning"><strong>1. Fine-Tuning Grammar &amp; Meaning</strong></h4>
<ul>
<li><p>The FFN helps polish sentence structure by refining <strong>syntax</strong> (word order) and <strong>semantics</strong> (meaning).</p>
</li>
<li><p>In <strong>machine translation</strong>, this ensures fluent and grammatically correct output.</p>
</li>
</ul>
<h4 id="heading-2-improving-token-specific-details"><strong>2. Improving Token-Specific Details</strong></h4>
<ul>
<li><p>Unlike attention, which focuses on <strong>relationships between tokens</strong>, the FFN processes each token <strong>independently</strong>.</p>
</li>
<li><p>This allows for <strong>word-level adjustments</strong>, making sure each token is represented accurately.</p>
</li>
</ul>
<h4 id="heading-3-capturing-complex-patterns"><strong>3. Capturing Complex Patterns</strong></h4>
<ul>
<li><p>The FFN introduces <strong>nonlinear transformations</strong>, enabling it to learn intricate relationships like:</p>
<ul>
<li><p><strong>Tense, gender, and plurality adjustments</strong> in translations.</p>
</li>
<li><p><strong>Handling idioms and nuanced expressions</strong> that require deep contextual understanding.</p>
</li>
</ul>
</li>
</ul>
<blockquote>
<p>📌 <strong>Think of the FFN as a final polish—refining each token’s representation to ensure clarity, coherence, and natural flow before making a prediction.</strong></p>
</blockquote>
<h3 id="heading-feedforward-network-output"><strong>FeedForward Network Output</strong></h3>
<p>The output of the FFN after both transformations is:</p>
<p>$$\text{FFN Output} = \begin{bmatrix} 9.4743 &amp; 8.7558 &amp; 5.8188 \\ 9.9507 &amp; 9.1566 &amp; 6.1009 \\ 10.3006 &amp; 9.4511 &amp; 6.3083 \\ 10.3164 &amp; 9.4643 &amp; 6.3176 \\ 10.1041 &amp; 9.2857 &amp; 6.1918 \\ 9.2654 &amp; 8.5799 &amp; 5.6952 \\ 10.0444 &amp; 9.2355 &amp; 6.1564 \\ 10.0896 &amp; 9.2735 &amp; 6.1832 \\ 10.0366 &amp; 9.2289 &amp; 6.1518 \\ 10.0658 &amp; 9.2535 &amp; 6.1691 \end{bmatrix}$$</p><hr />
<h3 id="heading-8residual-connection-output-preserving-and-enriching-context">8.<strong>Residual Connection Output: Preserving and Enriching Context</strong></h3>
<p>The <strong>residual connection</strong> enhances the decoder’s output by <strong>adding the projected encoder-decoder attention output back to the FFN output</strong>.</p>
<h3 id="heading-why-is-this-important"><strong>Why is this Important?</strong></h3>
<ol>
<li><p><strong>Preserving Context from Both Sequences</strong></p>
<ul>
<li><p>The decoder generates the output <strong>step by step</strong>, and it must retain:</p>
<ul>
<li><p><strong>Token-to-token relationships</strong> within the target sequence (from masked attention).</p>
</li>
<li><p><strong>Context alignment</strong> between the source and target sequences.</p>
</li>
</ul>
</li>
<li><p>The residual connection ensures that both <strong>local (target) and global (source) contexts</strong> are maintained.</p>
</li>
</ul>
</li>
<li><p><strong>Enriching Contextual Representations</strong></p>
<ul>
<li><p><strong>Encoder-decoder attention</strong> focuses on aligning <strong>source and target tokens</strong>.</p>
</li>
<li><p>The residual connection <strong>merges this alignment</strong> with the decoder’s evolving context, <strong>refining the representation for better coherence</strong>.</p>
</li>
</ul>
</li>
<li><p><strong>Preparing for Further Processing</strong></p>
<ul>
<li><p>The combined output is <strong>passed to the FFN</strong>, where:</p>
<ul>
<li><p>It undergoes <strong>grammatical and semantic refinement</strong>.</p>
</li>
<li><p>Each token’s representation is <strong>further enhanced for the next processing stage</strong>.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<blockquote>
<p>📌 <strong>In short, the residual connection prevents information loss, strengthens alignment, and ensures the decoder’s output remains rich in context and meaning.</strong></p>
</blockquote>
<h3 id="heading-how-is-the-residual-connection-computed">How is the residual connection computed ?</h3>
<p>The residual output obtained is as follows :</p>
<p>$$\text{Residual Output} = \text{Projected Encoder-Decoder Attention Output} + \text{FFN Output}$$</p><p>The residual output obtained is as follows :</p>
<p>$$\text{Residual Output} = \begin{bmatrix} 10.7412 &amp; 10.9458 &amp; 7.4774 \\ 11.2877 &amp; 11.4733 &amp; 7.8551 \\ 11.6887 &amp; 11.8611 &amp; 8.1329 \\ 11.7068 &amp; 11.8785 &amp; 8.1454 \\ 11.4635 &amp; 11.6433 &amp; 7.9769 \\ 10.5013 &amp; 10.7145 &amp; 7.3119 \\ 11.3951 &amp; 11.5772 &amp; 7.9295 \\ 11.4469 &amp; 11.6272 &amp; 7.9654 \\ 11.3861 &amp; 11.5685 &amp; 7.9233 \\ 11.4196 &amp; 11.6009 &amp; 7.9465 \end{bmatrix}$$</p><h3 id="heading-9-layer-normalized-output">9. Layer-Normalized Output</h3>
<p>The final step involves normalizing the residual output. <strong>Layer normalization ensures that the values in a layer's output have a consistent scale and distribution, which is critical for stable and efficient training in neural networks, including transformers.</strong></p>
<h3 id="heading-why-is-layer-normalization-important">Why Is Layer Normalization Important ?</h3>
<ol>
<li><p><strong>Consistent Scale:</strong></p>
<ul>
<li>By normalizing the outputs, layer normalization ensures that the scale of values remains consistent across tokens and dimensions, preventing instability caused by large or small activations.</li>
</ul>
</li>
<li><p><strong>Stable Training:</strong></p>
<ul>
<li>Normalized outputs reduce the likelihood of exploding or vanishing gradients during backpropagation, making training more stable.</li>
</ul>
</li>
<li><p><strong>Effective Gradient Flow:</strong></p>
<ul>
<li>Consistent scaling across layers ensures smoother and more predictable gradient updates, improving the model's ability to converge.</li>
</ul>
</li>
<li><p><strong>Token Independence:</strong></p>
<ul>
<li>In transformers, layer normalization is applied independently for each token. This allows the model to normalize the representation of each token without being affected by other tokens in the sequence.</li>
</ul>
</li>
</ol>
<p>The resulting matrix obtained, after applying layer normalization to the residual output is:</p>
<p>$$\text{Layer Normalized Output} = \begin{bmatrix} 0.6417 &amp; 0.7705 &amp; -1.4123 \\ 0.6506 &amp; 0.7622 &amp; -1.4127 \\ 0.6564 &amp; 0.7567 &amp; -1.4130 \\ 0.6566 &amp; 0.7564 &amp; -1.4130 \\ 0.6532 &amp; 0.7597 &amp; -1.4129 \\ 0.6375 &amp; 0.7745 &amp; -1.4120 \\ 0.6522 &amp; 0.7607 &amp; -1.4128 \\ 0.6529 &amp; 0.7599 &amp; -1.4129 \\ 0.6520 &amp; 0.7608 &amp; -1.4128 \\ 0.6525 &amp; 0.7603 &amp; -1.4128 \end{bmatrix}$$</p><p>Layer normalization marks the end of forward propagation in the decoder, leading to the final step—<strong>projecting the normalized output onto the target vocabulary space</strong> to predict the next token.</p>
<hr />
<h1 id="heading-final-projection-to-the-vocabulary-space">Final Projection to the Vocabulary Space</h1>
<p>The final step in the decoder is to project the <strong>layer-normalized output</strong> into the <strong>target vocabulary space</strong> to generate predictions for the next token.</p>
<h3 id="heading-how-does-this-projection-work"><strong>How Does This Projection Work?</strong></h3>
<ol>
<li><p><strong>Decoder Output Transformation</strong></p>
<ul>
<li><p>The decoder produces an output matrix of size \(M \times D\), where:</p>
<ul>
<li><p>\(M\) is the number of tokens in the generated sequence.</p>
</li>
<li><p>\(D\) is the embedding dimension.</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Mapping to Vocabulary Space</strong></p>
<ul>
<li><p>A learnable weight matrix \(W_{\text{vocab}} \) (of size \(D \times V_c\), where \(V_c\) is the vocabulary size) transforms the decoder's output into a probability distribution over all possible tokens.</p>
</li>
<li><p>Each token representation is projected from <strong>dimension</strong> \(D\) <strong>→ dimension</strong> \(V_c\), resulting in a matrix of size \(M \times V_c\).</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-purpose-of-the-projection"><strong>Purpose of the Projection</strong></h3>
<ul>
<li><p>Aligns the decoder’s contextualized output with the target vocabulary.</p>
</li>
<li><p>Produces a probability distribution over the vocabulary for each token in the sequence.</p>
</li>
<li><p>Ensures the model can <strong>sample or select the most likely next token</strong> during generation.</p>
</li>
</ul>
<h3 id="heading-computing-logits-amp-softmax"><strong>Computing Logits &amp; Softmax</strong></h3>
<p>The projected output, referred to as <strong>logits</strong>, is computed as:</p>
<p>$$\text{logits} = \text{Layer Normalized Output} \times W_{\text{vocab}} + b_{\text{vocab}}$$</p><p>These <strong>logits</strong> are then passed through a <strong>softmax function</strong> to obtain probabilities for each token is</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1740927432798/a5bad649-0c33-44ff-a57d-924a25a8f956.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Each row in the resulting matrix represents the <strong>probability distribution</strong> over the vocabulary for a given token position in the output sequence.</p>
</li>
<li><p>This is nothing but the probability of each token(column) in the target vocabulary being the correct token for that position in the target sequence.</p>
</li>
<li><p>The highest probability token is selected as the predicted output.</p>
</li>
</ul>
<h3 id="heading-why-softmax"><strong>Why Softmax?</strong></h3>
<ul>
<li><p>Converts raw logits into <strong>interpretable probability scores</strong>.</p>
</li>
<li><p>Ensures that the sum of probabilities across the vocabulary is <strong>1</strong> for each token position.</p>
</li>
<li><p>Helps in selecting the <strong>most likely</strong> next token during training and inference.</p>
</li>
</ul>
<hr />
<h2 id="heading-conclusion-amp-next-steps"><strong>Conclusion &amp; Next Steps</strong></h2>
<p>With the <strong>forward propagation in the Transformer decoder</strong> complete, we now have a detailed understanding of how the model processes information at each step. The decoder retrieves relevant context from the encoder, applies attention mechanisms, and refines token representations before making predictions.</p>
<p>However, the Transformer is only as good as its training process. To improve accuracy and minimize prediction errors, we must <strong>update the model’s parameters using backpropagation</strong>. In the next and final part of this series, we will <strong>delve into the backpropagation process and inference phase</strong>, exploring how gradients are computed, weights are adjusted, and how the model ultimately learns to generate high-quality outputs.</p>
<p>Stay tuned for the <strong>next blog</strong>, where we unravel the final part of the crucial training phase of Transformers! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Transformer Decoder: Forward Pass Mechanism and Key Insights (part 5)]]></title><description><![CDATA[Understanding the Transformer decoder's role in sequence input processing during the training phase, highlighting crucial features like self-attention.]]></description><link>https://blog.vikassrinivasa.dev/transformer-decoder-forward-pass-mechanism-and-key-insights-part-5</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/transformer-decoder-forward-pass-mechanism-and-key-insights-part-5</guid><category><![CDATA[decoder]]></category><category><![CDATA[nlp transformers]]></category><category><![CDATA[nlp]]></category><category><![CDATA[encoder decoder]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Thu, 20 Feb 2025 02:56:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/265c06273063d7e0ed974916bf230b17.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you’re following along in our <strong>Transformer series</strong>, this is the fifth installment, where we dive deep into the <strong>decoder phase</strong> during forward propagation in training. Before proceeding, we highly recommend checking out <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/how-transformers-work-tokenization-embeddings-and-positional-encoding-explained-part-1"><strong><em>Part 1</em></strong></a><strong>,</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-encoder-explained-a-deep-dive-into-attention-scores-part-2"><strong><em>Part 2</em></strong></a><strong>,</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-encoder-explained-multi-head-attention-part-3"><strong><em>Part 3</em></strong></a><strong>, and</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-encoder-explained-a-thorough-look-into-its-working-part-4"><strong><em>Part 4</em></strong></a> of this series to build a strong foundation on how <strong>encoders function within the Transformer architecture</strong>.</p>
<p>In a <strong>Transformer model</strong>, the <strong>decoder receives input</strong> from the previous decoder layer, refining and transforming it progressively through multiple layers. This process plays a crucial role in both the <strong>training phase and inference phase</strong>. While inference involves generating predictions step by step, training requires <strong>forward propagation</strong> to adjust model weights based on loss calculations.</p>
<p>In this blog, we will focus on the <strong>forward propagation mechanism</strong> during the <strong>training phase</strong> of the Transformer decoder. We will break down key operations, including <strong>self-attention, cross-attention, and feed-forward networks</strong>, to understand how data flows through the decoder during training.</p>
<p>Let’s get started!</p>
<hr />
<h2 id="heading-understanding-the-decoder-in-the-training-phase"><strong>Understanding the Decoder in the Training Phase</strong></h2>
<p>The <strong>Transformer decoder</strong> operates differently during the <strong>training phase</strong> compared to the <strong>inference phase</strong>. In training, it employs a strategy known as <strong>Teacher Forcing</strong>, which significantly influences how the model learns sequence relationships.</p>
<h3 id="heading-what-is-teacher-forcing"><strong>What is Teacher Forcing?</strong></h3>
<p><strong>Teacher forcing</strong> is a training technique commonly used in <strong>sequence-to-sequence (Seq2Seq) models</strong>. Instead of using the model’s own predictions as input for the next step, <strong>the actual ground truth sequence (target sequence) is provided</strong>.</p>
<h4 id="heading-why-is-teacher-forcing-used"><strong>Why Is Teacher Forcing Used?</strong></h4>
<ol>
<li><p><strong>Stabilizes Training</strong> – Early in training, the model’s predictions are often inaccurate. By using the correct target sequence as input, teacher forcing prevents <strong>error accumulation</strong> and allows the model to learn effectively.</p>
</li>
<li><p><strong>Faster Convergence</strong> – The model is guided by the correct sequence, helping it reach an <strong>optimal solution more quickly</strong>.</p>
</li>
<li><p><strong>Focus on Learning Relationships</strong> – By eliminating errors from previous predictions, the model <strong>learns the relationships between input and output sequences</strong> rather than struggling with its own mistakes.</p>
</li>
</ol>
<hr />
<h2 id="heading-decoder-operations-during-forward-propagation"><strong>Decoder Operations During Forward Propagation</strong></h2>
<p>During training, the decoder follows a specific sequence of operations at each step:</p>
<ol>
<li><p><strong>Masked Self-Attention</strong> – Ensures the model <strong>attends only to previous tokens</strong>, preventing information leakage from future tokens.</p>
</li>
<li><p><strong>Cross-Attention</strong> – Integrates the <strong>encoder’s output</strong> with the decoder’s partially generated sequence to align the input and output.</p>
</li>
<li><p><strong>Feed-Forward Layer</strong> – Applies <strong>non-linear transformations</strong> to extract meaningful features.</p>
</li>
<li><p><strong>Residual Connection</strong> – Aids in <strong>stable gradient flow</strong>, preventing vanishing gradients.</p>
</li>
<li><p><strong>Layer Normalization</strong> – Stabilizes training by maintaining <strong>consistent activation distributions</strong>.</p>
</li>
</ol>
<p>To fully grasp how the decoder processes input, let's first understand <strong>what inputs it receives and how they are prepared</strong>.</p>
<hr />
<h2 id="heading-preparing-the-target-sequence-for-the-decoder"><strong>Preparing the Target Sequence for the Decoder</strong></h2>
<p>The <strong>decoder receives two key inputs</strong>:</p>
<ol>
<li><p><strong>The encoder output</strong> – Encapsulates the <strong>contextualized representation</strong> of the input sequence.</p>
</li>
<li><p><strong>A partially generated ground truth sequence</strong> – A modified version of the target sequence that helps guide training.</p>
</li>
</ol>
<h3 id="heading-example-input-and-target-sequence"><strong>Example: Input and Target Sequence</strong></h3>
<h4 id="heading-english-input-source-sequence"><strong>English Input (Source Sequence)</strong></h4>
<p><em>"My name is Vikas. I love cricket, finance, and AI."</em></p>
<h4 id="heading-french-translation-target-sequence"><strong>French Translation (Target Sequence)</strong></h4>
<p><em>"Mon nom est Vikas. J'aime le cricket, la finance et l'IA."</em></p>
<p>However, the decoder does not directly use the <strong>target sequence</strong> as input. Instead, it <strong>shifts</strong> the target sequence to ensure an <strong>auto-regressive</strong> learning process.</p>
<hr />
<h2 id="heading-steps-to-create-the-shifted-target-sequence"><strong>Steps to Create the Shifted Target Sequence</strong></h2>
<p>To train the decoder properly, the target sequence is <strong>shifted to the right</strong>:</p>
<ul>
<li><p>A special <code>&lt;start&gt;</code> (start-of-sequence) token is <strong>added at the beginning</strong>.</p>
</li>
<li><p>The <strong>last token</strong> is removed to maintain the <strong>same sequence length</strong>.</p>
</li>
</ul>
<h3 id="heading-example-shifted-target-sequence"><strong>Example: Shifted Target Sequence</strong></h3>
<h4 id="heading-original-target-sequence-ground-truth"><strong>Original Target Sequence (Ground Truth)</strong></h4>
<p><code>["Mon", "nom", "est", "Vikas.", "J'aime", "le", "cricket,", "la", "finance", "et", "l'IA", "."]</code></p>
<h4 id="heading-shifted-target-sequence-decoder-input"><strong>Shifted Target Sequence (Decoder Input)</strong></h4>
<p><code>["&lt;start&gt;", "Mon", "nom", "est", "Vikas.", "J'aime", "le", "cricket,", "la", "finance", "et", "l'IA"]</code></p>
<h3 id="heading-why-shift-the-target-sequence"><strong>Why Shift the Target Sequence?</strong></h3>
<p>This <strong>shifted input</strong> ensures that, at each decoding step, the model <strong>generates the next token using only the previous tokens</strong>.</p>
<ul>
<li><p><strong>When generating "Mon"</strong>, the model sees only <strong>""</strong>.</p>
</li>
<li><p><strong>When generating "nom"</strong>, the model sees <strong>"" and "Mon"</strong>.</p>
</li>
<li><p><strong>When generating "est"</strong>, the model sees <strong>"", "Mon", and "nom"</strong>.</p>
</li>
</ul>
<p>This setup enforces an <strong>auto-regressive</strong> approach, mimicking how the decoder will function during inference while still leveraging <strong>teacher forcing</strong> for stable training.</p>
<hr />
<h2 id="heading-converting-to-vector-embeddings"><strong>Converting to Vector Embeddings</strong></h2>
<p>Before the decoder can process the target sequence, it must be converted into <strong>vector embeddings</strong> with the same dimensionality as the encoder output. This transformation ensures that each token is represented in a high-dimensional space, enabling the model to capture semantic relationships.</p>
<p>The vector embedding of the <strong>shifted target sequence</strong> results in a <strong>matrix of order</strong> \(M \times D\)[ Qd=Masked Attention Output×WQd Kd=Encoder Output×WKd Vd=Encoder Output×WVd ], where:</p>
<ul>
<li><p>\(M\) represents the number of tokens in the target sequence.</p>
</li>
<li><p>\(D\) is the embedding dimension.</p>
</li>
</ul>
<p>This embedded target sequence is denoted as \(T_{input}\).</p>
<p>$$T_{\text{input}} = \begin{bmatrix} 0.45 &amp; 0.67 &amp; -0.12 \\ 0.80 &amp; 0.05 &amp; -0.25 \\ 0.60 &amp; 0.90 &amp; 0.02 \\ 0.85 &amp; 0.10 &amp; 0.95 \\ 0.12 &amp; 0.22 &amp; 0.55 \\ -0.10 &amp; 0.03 &amp; -0.07 \\ 0.40 &amp; 0.75 &amp; -0.20 \\ 0.15 &amp; -0.01 &amp; 0.04 \\ -0.20 &amp; -0.10 &amp; 0.04 \\ 0.30 &amp; 0.40 &amp; 0.08 \end{bmatrix}$$</p><blockquote>
<p>📌 <strong>For a detailed explanation of how token embeddings are generated, refer to</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/how-transformers-work-tokenization-embeddings-and-positional-encoding-explained-part-1#heading-creating-embeddings-from-tokens">How Transformers Work: Tokenization Embeddings and Positional Encoding Explained (Part 1)</a></p>
</blockquote>
<hr />
<h2 id="heading-adding-positional-encodings"><strong>Adding Positional Encodings</strong></h2>
<p><a target="_blank" href="https://transformers-goto-guide.hashnode.dev/how-transformers-work-tokenization-embeddings-and-positional-encoding-explained-part-1">Since Transformers <strong>do not have a built-in notion of word</strong></a> <strong>order</strong>, we must add <strong>positional encodings</strong> to the embedded target sequence. These positional encodings inject sequential information into the embeddings, allowing the model to understand the relative position of words in a sentence.</p>
<p>The positional encodings are generated using the <strong>same sinusoidal function-based method</strong> discussed in the encoder. Adding these encodings results in the <strong>partially generated target sequence</strong>, which is then fed into the decoder.</p>
<p>Below is the matrix representing the <strong>positional encodings</strong> used in this example, along with the matrix obtained after adding them to the embeddings.</p>
<p>$$PE = \begin{bmatrix} 0.0000 &amp; 1.0000 &amp; 0.0000 \\ 0.8415 &amp; 0.9989 &amp; 0.0022 \\ 0.9093 &amp; 0.9957 &amp; 0.0043 \\ 0.1411 &amp; 0.9903 &amp; 0.0065 \\ -0.7568 &amp; 0.9828 &amp; 0.0086 \\ -0.9589 &amp; 0.9732 &amp; 0.0108 \\ -0.2794 &amp; 0.9615 &amp; 0.0129 \\ 0.6570 &amp; 0.9477 &amp; 0.0151 \\ 0.9894 &amp; 0.9318 &amp; 0.0172 \\ 0.4121 &amp; 0.9140 &amp; 0.0194 \end{bmatrix} \quad T_{\text{input}} + PE = \begin{bmatrix} 0.45 &amp; 1.67 &amp; -0.12 \\ 1.6415 &amp; 1.0489 &amp; -0.2478 \\ 1.5093 &amp; 1.8957 &amp; 0.0243 \\ 0.9911 &amp; 1.0903 &amp; 0.9565 \\ -0.6368 &amp; 1.2028 &amp; 0.5586 \\ -1.0589 &amp; 1.0032 &amp; -0.0592 \\ 0.1206 &amp; 1.7115 &amp; -0.1871 \\ 0.8070 &amp; 0.9377 &amp; 0.0551 \\ 0.7894 &amp; 0.8318 &amp; 0.0572 \\ 0.7121 &amp; 1.3140 &amp; 0.0994 \end{bmatrix}$$</p><blockquote>
<p>📌 <strong>To understand how positional encodings are computed and why they are necessary, refer to</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/how-transformers-work-tokenization-embeddings-and-positional-encoding-explained-part-1#heading-positional-encoding">How Transformers Work: Tokenization Embeddings and Positional Encoding Explained (Part 1)</a>.</p>
</blockquote>
<hr />
<h2 id="heading-masked-self-attention-in-the-decoder"><strong>Masked Self-Attention in the Decoder</strong></h2>
<p>Now that we have <strong>embedded the target sequence and added positional encodings</strong>, the next step is to understand how the <strong>decoder processes this sequence</strong> using <strong>Masked Self-Attention</strong>. This mechanism ensures the model predicts tokens <strong>one step at a time</strong> without seeing future words, which is crucial for <strong>language generation tasks like translation and text generation</strong>.</p>
<hr />
<h2 id="heading-what-is-masked-self-attention"><strong>What is Masked Self-Attention?</strong></h2>
<p>Masked self-attention is a specialized form of the <strong>attention mechanism</strong>, used exclusively in the <strong>decoder</strong> of a Transformer. It ensures that, when predicting a token, the model <strong>only attends to previous tokens</strong> and <strong>not future ones</strong>.</p>
<p>Without masking, the model could <strong>"cheat"</strong> during training by using future tokens, which wouldn't be available during inference. Masking ensures that the Transformer learns <strong>in an auto-regressive manner, just like during actual text generation</strong>.</p>
<blockquote>
<p><strong>🔍 Analogy:</strong> Think of reading a sentence one word at a time while covering the future words with your hand. This ensures that you rely only on the words you've already seen, rather than anticipating upcoming ones.</p>
</blockquote>
<hr />
<h2 id="heading-how-does-masked-self-attention-work"><strong>How Does Masked Self-Attention Work?</strong></h2>
<p>Masked attention works by using a <strong>masking matrix</strong> that prevents the decoder from looking at future tokens. This is done by setting certain positions in the <strong>attention score matrix</strong> to \(-\infty \) <strong>(or a very large negative number)</strong> before applying the <strong>softmax function</strong>.</p>
<ul>
<li><p>When softmax is applied, these masked positions get a probability of \(0\), effectively excluding them from contributing to the final output.</p>
</li>
<li><p>This ensures that at any given step, the model only considers <strong>previous tokens</strong> when making a prediction.</p>
</li>
</ul>
<hr />
<h2 id="heading-computing-masked-self-attention"><strong>Computing Masked Self-Attention</strong></h2>
<p>Just like in the <strong>encoder</strong>, masked attention follows a step-by-step computation process.</p>
<h3 id="heading-1-compute-query-key-and-value-matrices"><strong>1. Compute Query, Key, and Value Matrices</strong></h3>
<p>To compute <strong>masked attention</strong>, we first generate the <strong>Query (</strong> \(Q\) <strong>), Key (</strong> \(K\) <strong>), and Value (</strong> \(V\) <strong>) matrices</strong> from the input sequence.</p>
<p>The <strong>query weight matrix</strong> \(W_Q\)<strong>, key weight matrix</strong> \(W_K\)<strong>, and value weight matrix</strong> \(W_V\) are <strong>randomly initialized</strong> at the beginning of training. These matrices help the model determine <strong>which tokens should focus on others</strong> and how much importance to assign.</p>
<p>$$\begin{array}{ccc} \textbf{Query Weight Matrix } (W_Q) &amp; \textbf{Key Weight Matrix } (W_K) &amp; \textbf{Value Weight Matrix } (W_V) \\ \begin{bmatrix} 0.3745 &amp; 0.9507 &amp; 0.7320 \\ 0.5987 &amp; 0.1560 &amp; 0.1560 \\ 0.0581 &amp; 0.8662 &amp; 0.6011 \end{bmatrix} &amp; \begin{bmatrix} 0.7081 &amp; 0.0206 &amp; 0.9699 \\ 0.8324 &amp; 0.2123 &amp; 0.1818 \\ 0.1834 &amp; 0.3042 &amp; 0.5248 \end{bmatrix} &amp; \begin{bmatrix} 0.4320 &amp; 0.2912 &amp; 0.6119 \\ 0.1395 &amp; 0.2921 &amp; 0.3664 \\ 0.4561 &amp; 0.7852 &amp; 0.1997 \end{bmatrix} \end{array}$$</p><p>The Query ( \(Q\) ), Key ( \(K\) ), and Value ( \(V\) ) matrices are then obtained by multiplying the input sequence with these weight matrices.</p>
<p>$$\begin{array}{ccc} \textbf{Query Matrix } (Q) &amp; \textbf{Key Matrix } (K) &amp; \textbf{Value Matrix } (V) \\ \begin{bmatrix} 1.1613 &amp; 0.5844 &amp; 0.5178 \\ 1.2283 &amp; 1.5096 &amp; 1.2162 \\ 1.7016 &amp; 1.7517 &amp; 1.4151 \\ 1.0795 &amp; 1.9409 &amp; 1.4705 \\ 0.5140 &amp; 0.0661 &amp; 0.0573 \\ 0.2005 &amp; -0.9015 &amp; -0.6542 \\ 1.0589 &amp; 0.2196 &amp; 0.2428 \\ 0.8668 &amp; 0.9613 &amp; 0.7701 \\ 0.7969 &amp; 0.9298 &amp; 0.7420 \\ 1.0591 &amp; 0.9681 &amp; 0.7860 \end{bmatrix} &amp; \begin{bmatrix} 1.6868 &amp; 0.3274 &amp; 0.6771 \\ 1.9900 &amp; 0.1811 &amp; 1.6528 \\ 2.6512 &amp; 0.4410 &amp; 1.8213 \\ 1.7848 &amp; 0.5429 &amp; 1.6615 \\ 0.6528 &amp; 0.4122 &amp; -0.1058 \\ 0.0745 &amp; 0.1732 &amp; -0.8757 \\ 1.4758 &amp; 0.3090 &amp; 0.3300 \\ 1.3621 &amp; 0.2325 &amp; 0.9821 \\ 1.2619 &amp; 0.2103 &amp; 0.9469 \\ 1.6163 &amp; 0.3239 &amp; 0.9818 \end{bmatrix} &amp; \begin{bmatrix} 0.3726 &amp; 0.5247 &amp; 0.8632 \\ 0.7423 &amp; 0.5899 &amp; 1.3392 \\ 0.9275 &amp; 1.0125 &amp; 1.6228 \\ 1.0164 &amp; 1.3582 &amp; 1.1968 \\ 0.1475 &amp; 0.6045 &amp; 0.1626 \\ -0.3444 &amp; -0.0618 &amp; -0.2922 \\ 0.2055 &amp; 0.3882 &amp; 0.6635 \\ 0.5045 &amp; 0.5522 &amp; 0.8483 \\ 0.4831 &amp; 0.5178 &amp; 0.7992 \\ 0.5362 &amp; 0.6693 &amp; 0.9369 \end{bmatrix} \end{array}$$</p><blockquote>
<p>📌 <strong>For a detailed breakdown of how these matrices are computed, refer to</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/understanding-the-role-of-query-key-and-value-in-transformer-models?source=more_series_bottom_blogs">Understanding the Role of Query, Key, and Value Matrices in Transformer Models</a> .</p>
</blockquote>
<hr />
<h3 id="heading-2-compute-alignment-scores"><strong>2. Compute Alignment Scores</strong></h3>
<p>Once we have \(Q\)<strong>,</strong> \(K\) and \(V\) the next step is to compute the <strong>alignment scores</strong> using the scaled dot-product attention formula:</p>
<p>$$Score(Q, K) = \frac{Q \cdot K^T}{\sqrt{\frac{D}{\text{No. of Heads}}}}$$</p><p>Here:</p>
<ul>
<li><p>\(Q\): Query matrix</p>
</li>
<li><p>\(K\): Key matrix</p>
</li>
<li><p>\(D\): Dimensionality of the model</p>
</li>
<li><p>\(\text{No. of Heads}\) : Number of attention heads (in this example, we assume <strong>one head</strong>)</p>
</li>
</ul>
<p>Since we are using <strong>only one attention head</strong>, we compute <strong>a single alignment score matrix</strong>.</p>
<p>$$\textbf{Score(Q, K)} = \begin{bmatrix} 1.44 &amp; 1.88 &amp; 2.47 &amp; \dots &amp; 1.48 \\ 1.95 &amp; 2.72 &amp; 3.54 &amp; \dots &amp; 2.11 \\ 2.54 &amp; 3.48 &amp; 4.53 &amp; \dots &amp; 2.71 \\ \vdots &amp; \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\ 1.52 &amp; 2.06 &amp; 2.69 &amp; \dots &amp; 1.61 \end{bmatrix}$$</p><blockquote>
<p>📌 <strong>For a deeper understanding of scaled dot-product attention, check out</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-encoder-explained-a-deep-dive-into-attention-scores-part-2#heading-12-computing-the-alignment-scores"><strong>this blog where I explain how alignment scores are computed</strong></a><strong>.</strong></p>
</blockquote>
<hr />
<h2 id="heading-3-applying-the-mask"><strong>3. Applying the Mask</strong></h2>
<h3 id="heading-creating-the-mask-matrix"><strong>Creating the Mask Matrix</strong></h3>
<p>A <strong>static triangular mask matrix</strong> is used during training to ensure that a token <strong>only attends to past and current tokens</strong>, preventing information leakage from future tokens.</p>
<h4 id="heading-steps-to-construct-the-mask-matrix"><strong>Steps to Construct the Mask Matrix</strong></h4>
<ol>
<li><p><strong>Define Sequence Length (</strong> \(M\) <strong>)</strong></p>
<ul>
<li>Let \(M\) be the number of tokens in the target sequence.</li>
</ul>
</li>
<li><p><strong>Initialize a Full Matrix</strong></p>
<ul>
<li>Create an \(M\) matrix filled with <strong>zero values</strong>.</li>
</ul>
</li>
<li><p><strong>Apply Masking to Future Tokens</strong></p>
<ul>
<li><p>Use a <strong>triangular function</strong> to set all positions where \(j &gt; i\)(i.e., future tokens) to \(-\infty\).</p>
</li>
<li><p>The resulting <strong>mask matrix</strong> ensures that the model only considers <strong>current and past tokens</strong> for attention.</p>
</li>
</ul>
</li>
</ol>
<p>$$\textbf{Mask Matrix} = \begin{bmatrix} 0 &amp; -\infty &amp; -\infty &amp; \dots &amp; -\infty \\ 0 &amp; 0 &amp; -\infty &amp; \dots &amp; -\infty \\ 0 &amp; 0 &amp; 0 &amp; \dots &amp; -\infty \\ \vdots &amp; \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\ 0 &amp; 0 &amp; 0 &amp; \dots &amp; 0 \end{bmatrix}$$</p><p>This mask is then <strong>added</strong> to the <strong>alignment score matrix</strong>, ensuring that future tokens receive an attention weight of <strong>zero</strong> when softmax is applied.</p>
<h3 id="heading-computing-the-masked-alignment-scores"><strong>Computing the Masked Alignment Scores</strong></h3>
<p>Once the mask matrix is created, it is applied to the <strong>alignment score matrix</strong> as follows:</p>
<p>$$\text{Masked Score(Q, K)} = \text{Score(Q, K)} + \text{Mask Matrix}$$</p><p>This ensures that <strong>all future token positions</strong> contribute <strong>zero probability</strong> to the final attention output. The masked attention matrix in the decoder represents the relevance of each token in the target (ground truth) sequence with respect to every other token in the sequence, but only within the context of the tokens that are available for attention up to that point.</p>
<p>$$\textbf{Masked Score(Q, K)} = \begin{bmatrix} 1.44 &amp; -\infty &amp; -\infty &amp; \dots &amp; -\infty \\ 1.88 &amp; 2.72 &amp; -\infty &amp; \dots &amp; -\infty \\ 2.47 &amp; 3.54 &amp; 4.53 &amp; \dots &amp; -\infty \\ \vdots &amp; \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\ 1.48 &amp; 2.11 &amp; 2.71 &amp; \dots &amp; 1.61 \end{bmatrix}$$</p><hr />
<h2 id="heading-4-applying-softmax-to-obtain-attention-weights"><strong>4. Applying Softmax to Obtain Attention Weights</strong></h2>
<p>Now that we have the <strong>masked scores</strong>, the next step is to <strong>normalize them using the softmax function</strong>.</p>
<p>Softmax converts the masked alignment scores into a <strong>probability distribution</strong> that determines how much attention each token should receive. The formula used is:</p>
<p>$$\alpha = \text{Softmax}(\text{Masked Score}(Q, K))$$</p><p>Where:</p>
<ul>
<li><p>\(\alpha\) represents the <strong>attention weights</strong> after applying softmax.</p>
</li>
<li><p>Higher attention scores indicate <strong>stronger relevance</strong> between tokens.</p>
</li>
</ul>
<p>After this step, we obtain the <strong>attention weight matrix</strong>, which is used to compute the <strong>final masked attention output</strong>.</p>
<p>$$\textbf{Attention Weight Matrix} = \begin{bmatrix} 1.0000 &amp; 0.0000 &amp; 0.0000 &amp; 0.0000 &amp; \dots &amp; 0.0000 \\ 0.3015 &amp; 0.6985 &amp; 0.0000 &amp; 0.0000 &amp; \dots &amp; 0.0000 \\ 0.0845 &amp; 0.2471 &amp; 0.6684 &amp; 0.0000 &amp; \dots &amp; 0.0000 \\ \vdots &amp; \vdots &amp; \vdots &amp; \ddots &amp; \vdots &amp; \vdots \\ 0.0796 &amp; 0.1497 &amp; 0.2727 &amp; 0.1631 &amp; \dots &amp; 0.0905 \end{bmatrix}$$</p><hr />
<h2 id="heading-5-computing-the-masked-attention-output"><strong>5. Computing the Masked Attention Output</strong></h2>
<p>The <strong>final masked attention output</strong> is obtained by <strong>multiplying the attention weight matrix</strong> ( \(\alpha\) ) with the <strong>Value (</strong> \(V\) <strong>) matrix</strong>:</p>
<p>$$\text{Output} = \alpha \cdot V$$</p><p>This multiplication ensures that the attention mechanism <strong>weights the Value matrix</strong> according to the computed attention scores, resulting in a <strong>context-aware representation</strong> for each token.</p>
<p>$$\textbf{Output} = \begin{bmatrix} 0.3726 &amp; 0.5247 &amp; 0.8632 \\ 0.6308 &amp; 0.5702 &amp; 1.1957 \\ 0.8348 &amp; 0.8669 &amp; 1.4885 \\ 0.8701 &amp; 0.9780 &amp; 1.3929 \\ 0.7138 &amp; 0.8626 &amp; 1.1544 \\ 0.3403 &amp; 0.5605 &amp; 0.6270 \\ 0.6688 &amp; 0.8064 &amp; 1.1348 \\ 0.7030 &amp; 0.8258 &amp; 1.1677 \\ 0.6746 &amp; 0.7918 &amp; 1.1219 \\ 0.6909 &amp; 0.8052 &amp; 1.1497 \end{bmatrix}$$</p><h3 id="heading-final-output-projection"><strong>Final Output Projection</strong></h3>
<p>In case of <strong>multiple attention heads</strong>, the outputs from all heads would be <strong>concatenated</strong>. However, since our example uses <strong>only one attention head</strong>, the <strong>masked attention output matrix</strong> serves as our final result.</p>
<p>To prepare this output for the next layers, it is <strong>projected</strong> using a learnable weight matrix \(W_{dO}\):</p>
<p>$$\text{Final Output} = \text{Masked Attention Output} \cdot W_{dO}$$</p><p>This <strong>projection layer</strong> is used to <strong>blend the outputs from multiple heads</strong> (if present) into a <strong>single cohesive unit</strong>, just like in the encoder.</p>
<p>$$\begin{array}{c} \textbf{1. Projection Matrix } W_O \\ \text{The learned weight matrix used for the projection:} \\ W_O = \begin{bmatrix} 0.3745 &amp; 0.9507 &amp; 0.7320 \\ 0.5987 &amp; 0.1560 &amp; 0.1560 \\ 0.0581 &amp; 0.8662 &amp; 0.6011 \end{bmatrix} \\ \textbf{2. Final Projected Output} \\ \text{The attention output after applying the projection matrix:} \\ \text{Final Projected Output} = \begin{bmatrix} 0.5038 &amp; 1.1838 &amp; 0.8735 \\ 0.6471 &amp; 1.7244 &amp; 1.2695 \\ 0.9181 &amp; 2.2183 &amp; 1.6411 \\ 0.9922 &amp; 2.1863 &amp; 1.6267 \\ 0.8508 &amp; 1.8131 &amp; 1.3510 \\ 0.4994 &amp; 0.9540 &amp; 0.7134 \\ 0.7992 &amp; 1.7446 &amp; 1.2975 \\ 0.8255 &amp; 1.8087 &amp; 1.3454 \\ 0.7918 &amp; 1.7366 &amp; 1.2917 \\ 0.8076 &amp; 1.7783 &amp; 1.3224 \end{bmatrix} \end{array}$$</p><hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this blog, we explored how the Transformer decoder processes input during training, focusing on <strong>teacher forcing, masked self-attention, and target sequence preparation</strong>. We also broke down the step-by-step computation of <strong>masked attention</strong>, ensuring the model learns in an <strong>auto-regressive manner</strong> without peeking at future tokens.</p>
<p>In the next installment, we'll dive into <strong>encoder-decoder cross-attention, residual connections, and feed-forward networks</strong>—key components that refine the decoder's output. Stay tuned!</p>
]]></content:encoded></item><item><title><![CDATA[Transformer Encoder Explained : A Thorough Look into Its Working (Part 4)]]></title><description><![CDATA[Understanding Transformers: Easy Insights into Feed-Forward Networks, Residual Links, and Layer Normalization]]></description><link>https://blog.vikassrinivasa.dev/transformer-encoder-explained-a-thorough-look-into-its-working-part-4</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/transformer-encoder-explained-a-thorough-look-into-its-working-part-4</guid><category><![CDATA[nlp]]></category><category><![CDATA[nlp transformers]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Tue, 11 Feb 2025 13:56:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/327b7683e35b781b4f588a8275d8ff64.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Transformer encoder is a fundamental component of modern deep learning architectures, driving breakthroughs in natural language processing and sequence modeling. It processes input data through several key mechanisms:</p>
<ul>
<li><p><strong>Computing attention scores</strong> to determine token relationships.</p>
</li>
<li><p><strong>Passing data through a feed-forward network</strong> for deeper feature extraction.</p>
</li>
<li><p><strong>Adding residual connections</strong> to preserve information and improve gradient flow.</p>
</li>
<li><p><strong>Applying layer normalization</strong> for stable and efficient training.</p>
</li>
</ul>
<p><strong>If you haven’t already, check out</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-encoder-explained-a-deep-dive-into-attention-scores-part-2"><strong>Part 2</strong></a> <strong>of this series, where we break down how attention scores are computed—it’s essential for building a strong foundation!</strong></p>
<p>In this blog (Part 4 of our Transformer series), we’ll develop an intuitive understanding of <strong>feed-forward networks, residual connections, and layer normalization</strong>—key elements that refine and stabilize the Transformer’s learning process.</p>
<p>To make the most of this post, we highly recommend reading our previous blog on <strong>attention scores</strong>, as it sets the stage for the concepts we’ll explore here.</p>
<hr />
<h1 id="heading-feed-forward-network">Feed Forward Network</h1>
<p>The final attention output is further processed in a feed forward network where it undergoes two linear transformations with a non linear activation between them.</p>
<p><strong>A feedforward network (FFN) is a type of artificial neural network where information flows in one direction—from the input layer to the output layer—without looping back.</strong> <strong>It’s one of the simplest and most fundamental architectures in neural networks.</strong></p>
<p>Transformers are composed of linear layers (like attention) and matrix operations.Without non-linear transformations, the model would effectively collapse into a single linear transformation, no matter how many layers are stacked.<strong>The feedforward network introduces non-linear activation functions (like ReLU or GELU), which allow the model to learn complex, non-linear relationships in the data.</strong> <strong>Attention captures relationships between tokens, while the feedforward network adds grammatical and semantic refinement, ensuring each token’s representation aligns with the task and target language requirements.</strong></p>
<p>$$\text{FFN(X)}=\text{ReLU}(X \cdot W1+b1)\cdot W2+b2$$</p><p>Where,</p>
<ul>
<li><p>\(W_1 (D \times H)\) and \(W_2 (H \times D)\) are <strong>learned weight matrices</strong>.</p>
</li>
<li><p>\(b_1 (H)\) and \(b_2 (D)\) are <strong>learned bias vectors</strong>.</p>
</li>
<li><p>\(H\) (hidden neurons) is typically <strong>greater than</strong> \(D\).</p>
</li>
</ul>
<p>Here, \(D\) is the <strong>embedding dimension</strong> (features per token), and \(H\) is the <strong>number of hidden neurons</strong> in the feed-forward layer.</p>
<p>The <strong>output shape remains</strong> \(N \times D\), ensuring token representations retain their dimensions. This transformation <strong>enhances feature extraction</strong>, enriching contextual understanding before passing to the next layer.</p>
<p>The weight matrices (\(W_1\) and \(W_2\)) and biases ( \(b_1\) and \(b_2\) )used in our use case are given below.</p>
<p>$$\begin{aligned} \textbf{First Weight Matrix } (W_1) &amp;= \begin{bmatrix} 0.3745 &amp; 0.9507 &amp; 0.7320 &amp; 0.5987 \\ 0.1560 &amp; 0.1560 &amp; 0.0581 &amp; 0.8662 \\ 0.6011 &amp; 0.7081 &amp; 0.0206 &amp; 0.9699 \end{bmatrix} \\[8pt] \textbf{First Bias Vector } (b_1) &amp;= \begin{bmatrix} 0.8324, 0.2123, 0.1818, 0.1834 \end{bmatrix} \end{aligned}$$</p><p>$$\begin{aligned} \textbf{Second Weight Matrix } (W_2) &amp;= \begin{bmatrix} 0.3042 &amp; 0.5248 &amp; 0.4320 \\ 0.2912 &amp; 0.6119 &amp; 0.1395 \\ 0.2921 &amp; 0.3664 &amp; 0.4561 \\ 0.7852 &amp; 0.1997 &amp; 0.5142 \end{bmatrix} \\[8pt] \textbf{Second Bias Vector } (b_2) &amp;= \begin{bmatrix} 0.5924, 0.0465, 0.6075 \end{bmatrix} \end{aligned}$$</p><h3 id="heading-output-obtained-from-the-feed-forward-network-ffn">Output Obtained from the Feed-Forward Network (FFN)</h3>
<p>The Final FFN Output obtained is as follows</p>
<p>$$\text{FFN Output} = \begin{bmatrix} 2.4327 &amp; 1.7288 &amp; 2.1912 \\ 5.7504 &amp; 4.2261 &amp; 4.7223 \\ 6.6566 &amp; 4.9091 &amp; 5.4139 \\ 3.7186 &amp; 2.6970 &amp; 3.1723 \\ 1.5761 &amp; 1.0830 &amp; 1.5374 \\ 1.6820 &amp; 1.1630 &amp; 1.6183 \\ 3.0062 &amp; 2.1608 &amp; 2.6289 \\ 5.9794 &amp; 4.3994 &amp; 4.8973 \\ 3.7345 &amp; 2.7092 &amp; 3.1845 \\ 4.6607 &amp; 3.4069 &amp; 3.8912 \\ 2.1759 &amp; 1.5355 &amp; 1.9953 \\ 2.1123 &amp; 1.4874 &amp; 1.9467 \end{bmatrix}$$</p><h3 id="heading-how-does-the-feed-forward-network-ffn-work"><strong>How Does the Feed-Forward Network (FFN) Work?</strong></h3>
<p>In a transformer, the <strong>Feed-Forward Network (FFN)</strong> refines token representations after attention processing. It applies <strong>two linear transformations</strong> with a <strong>nonlinear activation</strong> in between, allowing the model to capture more complex relationships.</p>
<h4 id="heading-step-by-step-process"><strong>Step-by-Step Process:</strong></h4>
<p>For each token’s representation:</p>
<ol>
<li><p><strong>Input:</strong> The FFN receives the <strong>contextualized token vector</strong> from the attention mechanism.</p>
</li>
<li><p><strong>First Linear Transformation (Expansion):</strong> Expands the vector to a <strong>higher-dimensional space</strong> to capture richer feature interactions.</p>
<p> $$\text{Hidden} = \text{ReLU}(X W_1 + b_1)$$</p>
</li>
<li><p><strong>Nonlinear Activation:</strong> Uses <strong>ReLU</strong> (or another activation function) to introduce nonlinearity, enabling the model to learn complex patterns.</p>
</li>
<li><p><strong>Second Linear Transformation (Compression):</strong> Reduces the expanded representation <strong>back to its original dimension</strong> for consistency.</p>
<p> $$\text{Output} = \text{Hidden} W_2 + b_2$$</p>
</li>
</ol>
<h3 id="heading-why-is-the-feed-forward-network-necessary"><strong>Why Is the Feed-Forward Network Necessary?</strong></h3>
<p>While <strong>self-attention</strong> determines <strong>which tokens are important</strong>, it operates <strong>linearly</strong>—it captures relationships <strong>between</strong> tokens but not complex <strong>within-token</strong> feature interactions. The <strong>FFN addresses this limitation</strong> by:</p>
<ol>
<li><p><strong>Modeling Nonlinear Relationships:</strong> Introduces nonlinearity to enhance feature extraction.</p>
</li>
<li><p><strong>Dimensional Expansion &amp; Compression:</strong> Temporarily increases the feature space, allowing deeper transformations before returning to the original size.</p>
</li>
<li><p><strong>Feature Refinement:</strong> Emphasizes <strong>task-relevant</strong> features while suppressing noise.</p>
</li>
<li><p><strong>Task-Specific Representation:</strong> Fine-tunes token embeddings for downstream tasks like <strong>classification, translation, or question-answering</strong>.</p>
</li>
<li><p><strong>Combining Local &amp; Global Information:</strong> Processes each token <strong>independently</strong>, ensuring that <strong>global context from attention</strong> is applied effectively at the token level.</p>
</li>
</ol>
<p>By adding <strong>depth, expressiveness, and feature refinement</strong>, the FFN ensures that <strong>token representations are optimized</strong> for the model’s final output.</p>
<hr />
<h1 id="heading-adding-residual-connection">Adding Residual Connection</h1>
<p>Residual connections play a crucial role in transformers by preserving information, balancing contextual and refined features, and stabilizing training. They are added <strong>after the self-attention mechanism</strong> and <strong>after the feed-forward network (FFN).</strong></p>
<h3 id="heading-why-are-residual-connections-needed"><strong>Why Are Residual Connections Needed?</strong></h3>
<h4 id="heading-1-preserving-original-information"><strong>1. Preserving Original Information</strong></h4>
<p>Transformers apply <strong>complex transformations</strong> that can distort or lose critical input information. Residual connections help <strong>retain the original representation</strong> by adding the input back to the transformed output.</p>
<ul>
<li><p><strong>After Self-Attention:</strong></p>
<ul>
<li><p>The attention mechanism captures <strong>token-to-token relationships</strong> and dependencies (e.g., subject-verb-object structures).</p>
</li>
<li><p>Without residual connections, these relationships might be weakened as transformations continue.</p>
</li>
</ul>
</li>
<li><p><strong>After the Feed-Forward Network (FFN):</strong></p>
<ul>
<li><p>The FFN <strong>enhances grammatical, syntactic, and semantic properties</strong> at the <strong>token level</strong>.</p>
</li>
<li><p>However, it <strong>does not explicitly preserve</strong> the broader <strong>sequence-wide context</strong> captured by attention.</p>
</li>
<li><p>Residual connections ensure that both <strong>global dependencies (from attention)</strong> and <strong>local refinements (from FFN)</strong> are retained, leading to <strong>a well-balanced token representation.</strong></p>
</li>
</ul>
</li>
</ul>
<h4 id="heading-2-preventing-the-vanishing-gradient-problem"><strong>2. Preventing the Vanishing Gradient Problem</strong></h4>
<ul>
<li><p>In <strong>deep networks</strong>, gradients become <strong>smaller</strong> as they backpropagate, making it difficult to update earlier layers effectively.</p>
</li>
<li><p><strong>Residual connections provide a direct path for gradients</strong>, ensuring <strong>better weight updates</strong> and preventing <strong>training slowdowns</strong>.</p>
</li>
<li><p>This technique <strong>stabilizes deep architectures</strong>, enabling transformers to learn efficiently.</p>
</li>
</ul>
<h3 id="heading-how-the-residual-connection-works"><strong>How the Residual Connection Works</strong></h3>
<p>The residual connection simply <strong>adds the input vector (</strong> \(X\) <strong>) to the transformed output (</strong> \(F(X)\)<strong>)</strong>:</p>
<p>$$\text{Output}=X+F(X)$$</p><p>This <strong>element-wise addition</strong> allows the model to <strong>retain important input features while integrating new transformations</strong>, resulting in a more robust representation.</p>
<p>By combining <strong>local refinements (FFN) with global dependencies (attention)</strong> and <strong>ensuring stable gradient flow</strong>, residual connections significantly enhance the efficiency and effectiveness of transformer models.</p>
<p>For our use case, the residually connected output obtained is given below</p>
<p>$$\text{Residual Output} = \begin{bmatrix} 2.7440 &amp; 2.3293 &amp; 2.6400 \\ 6.7727 &amp; 6.3734 &amp; 6.3224 \\ 7.8748 &amp; 7.4775 &amp; 7.3278 \\ 4.3060 &amp; 3.8967 &amp; 4.0671 \\ 1.7016 &amp; 1.2856 &amp; 1.6900 \\ 1.8308 &amp; 1.4146 &amp; 1.8074 \\ 3.4410 &amp; 3.0284 &amp; 3.2764 \\ 7.0526 &amp; 6.6521 &amp; 6.5761 \\ 4.3258 &amp; 3.9159 &amp; 4.0846 \\ 5.4515 &amp; 5.0446 &amp; 5.1123 \\ 2.4321 &amp; 2.0163 &amp; 2.3550 \\ 2.3544 &amp; 1.9389 &amp; 2.2846 \end{bmatrix}$$</p><hr />
<p>The residual output obtained is then normalized using layer normalization, let’s understand how layer normalization works and how it is useful in transformers.</p>
<h1 id="heading-layer-normalization"><strong>Layer Normalization</strong></h1>
<p>Layer normalization standardizes the output of a layer by ensuring that the features in the token’s representation have a mean of 0 and a standard deviation of 1. It does this independently for each token, across all dimensions of its vector representation. For a token's vector representation $x = [x_1 , x_2 , … , x_D ]$ (of dimension $D$ ):</p>
<p>Layer normalization normalizes the values within a token (row-wise) to stabilize the learning process. The formula is:</p>
<p>$$\text{LayerNorm}(x) = \gamma \cdot \frac{x - \mu}{\sigma} + \beta$$</p><p>Where:</p>
<ul>
<li><p>\(x\): Input matrix (e.g., the residual output, shape $N \times D$).</p>
</li>
<li><p>\(mu\): Mean of each token's embedding (row mean):</p>
</li>
</ul>
<p>$$\mu = \frac{1}{D} \sum_{i=1}^{D} x_i$$</p><ul>
<li><p>\(\sigma\): Standard deviation of each token's embedding (row-wise standard deviation):</p>
<p>  $$\sigma = \sqrt{\frac{1}{D} \sum_{i=1}^{D} (x_i - \mu)^2 + \epsilon}$$</p>
<ul>
<li><p>\(\epsilon\): Small constant for numerical stability, e.g., \(10^{-6}\)).</p>
</li>
<li><p>\(\gamma\) : Learnable scaling parameter (shape \(D\)).</p>
</li>
<li><p>\(\beta\) : Learnable shifting parameter (shape \(D\)).</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-why-is-normalization-needed">Why is Normalization Needed?</h3>
<p>When training deep neural networks (like transformers), the intermediate values (like attention outputs or FFN outputs) can vary a lot between layers or during training. This variation causes two big problems:</p>
<ol>
<li><p><strong>Training Instability:</strong> If the values are too big (or too small), they can cause issues like exploding or vanishing gradients.This makes it hard for the network to learn effectively.</p>
</li>
<li><p><strong>Slower Learning:</strong> Networks need to adjust weights across layers to deal with the inconsistent scale of values. This slows down convergence (how fast the network learns). Layer normalization fixes these problems by normalizing the values to have a consistent scale for every token, regardless of the layer or input.</p>
</li>
</ol>
<h3 id="heading-how-is-layer-normalization-helpful">How is Layer Normalization Helpful?</h3>
<ol>
<li><p><strong>Stabilizes Training:</strong> It keeps the values in a predictable range, which means the model learns more smoothly and consistently.Gradients (the signals used to update weights) don’t explode or vanish, so learning stays on track.</p>
</li>
<li><p><strong>Token-Level Focus:</strong> In transformers, every token is processed independently.Layer normalization ensures that each token’s embedding is normalized independently, so it doesn’t depend on other tokens in the batch.</p>
</li>
<li><p><strong>Faster Convergence:</strong> By keeping values well-scaled, layer normalization allows the model to converge (learn) faster during training.</p>
</li>
<li><p><strong>Prepares for Next Layer:</strong> Layer normalization ensures the output is in a consistent scale, making it easier for the next layer to process it effectively.</p>
</li>
</ol>
<p>For our example , the output obtained on applying Layer Normalization is given below.</p>
<p>$$\text{LayerNorm Output} = \begin{bmatrix} 1.1330 &amp; 0.7191 &amp; 0.6758 \\ 1.2055 &amp; 0.7709 &amp; -0.4830 \\ 1.1982 &amp; 0.7851 &amp; -0.6501 \\ 1.1851 &amp; 0.7335 &amp; 0.1756 \\ 1.0913 &amp; 0.7164 &amp; 0.9469 \\ 1.0965 &amp; 0.7165 &amp; 0.9165 \\ 1.1591 &amp; 0.7239 &amp; 0.4599 \\ 1.2041 &amp; 0.7747 &amp; -0.5314 \\ 1.1856 &amp; 0.7338 &amp; 0.1684 \\ 1.2039 &amp; 0.7506 &amp; -0.1775 \\ 1.1208 &amp; 0.7178 &amp; 0.7628 \\ 1.1175 &amp; 0.7175 &amp; 0.7850 \end{bmatrix}$$</p><hr />
<h1 id="heading-conclusion-whats-next"><strong>Conclusion: What’s Next?</strong></h1>
<p>With <strong>Feed-Forward Networks, Residual Connections, and Layer Normalization</strong>, we have now completed the operations within <strong>one encoder layer</strong>. The next step depends on the model’s architecture:</p>
<ul>
<li><p>If this is the <strong>last encoder layer</strong>, the <strong>LayerNorm output</strong> is passed to the <strong>decoder</strong> for further processing.</p>
</li>
<li><p>Otherwise, it serves as input to the <strong>next encoder layer</strong>, where the process is repeated and token representations are refined even further.</p>
</li>
</ul>
<p>In this blog, we focused on understanding the <strong>encoder’s internal mechanisms</strong>. But what happens next? <strong>The decoder takes over!</strong></p>
<p>In the <strong>next part of this series</strong>, we’ll dive into the <strong>transformer decoder</strong>, breaking down its role <strong>intuitively</strong>—from handling encoder outputs to generating meaningful sequences.</p>
]]></content:encoded></item><item><title><![CDATA[Transformer Encoder Explained : Multi Head Attention (part 3)]]></title><description><![CDATA[Understanding the working of multi-head attention in depth]]></description><link>https://blog.vikassrinivasa.dev/transformer-encoder-explained-multi-head-attention-part-3</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/transformer-encoder-explained-multi-head-attention-part-3</guid><category><![CDATA[nlp transformers]]></category><category><![CDATA[nlp]]></category><category><![CDATA[multi head attention]]></category><category><![CDATA[attention-mechanism]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Sat, 08 Feb 2025 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/327b7683e35b781b4f588a8275d8ff64.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This blog is <strong>Part 3</strong> of our series on <strong>how transformers work</strong>. By the end of this post, you’ll have an <strong>intuitive understanding of Multi-Head Attention</strong>—a key mechanism that enhances the model’s ability to capture diverse relationships between tokens.</p>
<p>Self-attention has revolutionized deep learning models, enabling them to capture dependencies across an entire sequence, making them highly effective for NLP, computer vision, and other domains. However, a single self-attention mechanism might not be sufficient to capture multiple aspects of relationships within a sequence. This is where <strong>Multi-Head Attention (MHA)</strong> comes in.</p>
<p>Multi-Head Attention enhances the power of self-attention by allowing the model to attend to different parts of the input sequence <strong>simultaneously</strong>. This extension is a core component of the <strong>Transformer architecture</strong>, enabling models like <strong>BERT, GPT, and T5</strong> to process information more effectively.</p>
<p>In this article, we’ll explore <strong>how Multi-Head Attention extends Self-Attention</strong> and why it is crucial in modern deep learning models.</p>
<hr />
<h2 id="heading-self-attention-in-transformers"><strong>Self-Attention in Transformers</strong></h2>
<p>Before diving into Multi-Head Attention, let’s briefly revisit <strong>Self-Attention</strong>.</p>
<p>Self-attention enables a model to weigh different words in a sequence based on their relevance to each other. Given an input sequence, the model computes Query ( \(Q\) ), Key ( \(K\) ), and Value ( \(V \) ) matrices and derives attention scores using the <strong>Scaled Dot-Product Attention</strong> formula:</p>
<p>$$\text{Attention}(Q, K, V) = \text{softmax} \left( \frac{QK^T}{\sqrt{d_k}} \right) V$$</p><p>This mechanism allows each word to dynamically attend to other words in the sequence, capturing relationships effectively.</p>
<p>If you’d like a <strong>detailed explanation</strong> of how self-attention works, check out my blog post - <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-encoder-explained-a-deep-dive-into-attention-scores-part-2"><em>Transformer Encoder Explained : A Deep Dive into Attention Scores (Part 2)</em></a>.</p>
<p>Now, let’s see how Multi-Head Attention builds upon this concept.</p>
<hr />
<h1 id="heading-what-is-multi-head-attention"><strong>What is Multi-Head Attention?</strong></h1>
<p>While self-attention is powerful, it has a limitation: <strong>a single attention mechanism might not be enough to capture different aspects of word relationships</strong>. Consider a sentence like:</p>
<blockquote>
<p><em>"The bank approved the loan."</em></p>
</blockquote>
<ul>
<li><p>"Bank" could refer to a <strong>financial institution</strong> or a <strong>riverbank</strong> depending on context.</p>
</li>
<li><p>A single self-attention mechanism might focus on one aspect, missing the broader context.</p>
</li>
</ul>
<p>To address this, <strong>Multi-Head Attention (MHA)</strong> applies multiple <strong>self-attention mechanisms in parallel</strong>, allowing the model to <strong>attend to different information simultaneously</strong>.</p>
<hr />
<h2 id="heading-how-multi-head-attention-works"><strong>How Multi-Head Attention Works</strong></h2>
<p>Instead of computing attention using a single set of <strong>Q, K, V</strong>, Multi-Head Attention <strong>splits the input into multiple heads</strong> and applies self-attention independently. The results from all attention heads are then concatenated and projected into the final output.</p>
<p>The process involves the following steps:</p>
<ol>
<li><p><strong>Linear Projections</strong>: The input embeddings are transformed into multiple sets of <strong>Query (</strong> \(Q\) <strong>), Key (</strong> \(K\)<strong>), and Value (</strong> \(V\) <strong>)</strong> matrices using different learned weight matrices.</p>
<p> $$Q = X \cdot W_q \quad K = X \cdot W_k \quad V = X \cdot W_v$$</p>
<p> where:</p>
<ul>
<li><p>\(W_q, W_k, W_v\) are trainable weight matrices that create the respective projections.</p>
</li>
<li><p>These projections <strong>split the input into multiple attention heads</strong>, each having its own set of \(Q\), \(K\) and \(V\) matrices.</p>
</li>
</ul>
</li>
<li><p><strong>Independent Self-Attention</strong>: Each head applies self-attention separately on its respective \(Q\), \(K\) and \(V\).</p>
<p> $$\text{Attention}(Q, K, V) = \text{softmax} \left( \frac{QK^T}{\sqrt{d_k}} \right) V$$</p>
<p> where:</p>
<ul>
<li><p>\(QK^T\) computes similarity scores between tokens.</p>
</li>
<li><p>The <strong>softmax function</strong> normalizes these scores to determine attention weights.</p>
</li>
<li><p>The attention weights are used to scale the values \(V\), determining how much focus each token should receive.</p>
</li>
</ul>
</li>
</ol>
<p>    Since there are \(h\) <strong>attention heads</strong>, each computes attention separately on its own transformed \(Q, K, V\)matrices.</p>
<ol start="3">
<li><p><strong>Concatenation</strong>: The outputs of all heads are concatenated together by horizontally stacking them together into a single matrix.</p>
<p> $$\text{Concat(head_1​,head_2​,…,head_h​)}$$</p>
<ul>
<li><p>If there are \(h\) heads, then there are \(h\) matrices of shape \(N \times d_k\) that are stacked together into a single matrix.</p>
</li>
<li><p>Horizontally stacking the attention outputs from all heads produces a matrix of shape</p>
<p>  $$\text{Number of Tokens}×\text{Embedding Dimension}$$</p>
</li>
<li><h3 id="heading-why-concatenation-alone-isnt-enough"><strong>Why Concatenation Alone Isn't Enough</strong></h3>
<p>  At this stage, the stacked attention outputs from different heads are merely <strong>placed side by side</strong>, but they remain <strong>disjoint</strong>—each attention head has focused on different relationships independently, but there’s no mechanism yet to <strong>combine</strong> their insights into a unified representation.</p>
<ul>
<li><p>Without a <strong>learned transformation</strong>, the model has <strong>no way to determine</strong> how much weight to assign to the contributions of each head.</p>
</li>
<li><p>Each head might capture <strong>different semantic aspects</strong> (e.g., positional dependencies, syntax, or meaning), but simply concatenating them does not <strong>blend</strong> these insights into a meaningful form for the next layer.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>        To <strong>address this</strong>, we apply a final transformation using a trainable <strong>projection matrix</strong> \(W^O\)<strong>​</strong>.</p>
<ol start="4">
<li><p><strong>Final Linear Projection</strong>: To ensure consistency with the rest of the model, the concatenated vector is <strong>projected back to the original embedding dimension</strong> \(D\) using a weight matrix \(W^O\) of shape \(D \times D\):</p>
<p> $$\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \text{head}_2, \dots, \text{head}_h) W^O$$</p>
<ul>
<li><p>\(W^O\)​ <strong>learns how to blend</strong> the outputs from all heads to create a final <strong>context-aware representation</strong>.</p>
</li>
<li><p>This final transformation ensures that the output remains compatible with the input dimensions for further processing in the model.</p>
</li>
<li><p>The concatenated vector size ( \(h \times d_k\)) is reduced back to the original embedding dimension ( \(D\)) to ensure consistency with the rest of the model.</p>
</li>
</ul>
</li>
</ol>
<p>    By <strong>transforming</strong> the raw concatenated attention outputs, the model can <strong>assign appropriate importance</strong> to different attention heads, ensuring that the most relevant and meaningful information is propagated forward.</p>
<hr />
<h2 id="heading-why-is-this-important">Why Is This Important?</h2>
<ol>
<li><p><strong>Integration of Multiple Perspectives:</strong> Each attention head captures different aspects of the input sequence. The projection step ensures that these different perspectives are blended into a single, coherent representation.</p>
</li>
<li><p><strong>Consistency for Subsequent Layers:</strong> By projecting the concatenated output back to the embedding dimension, the transformer maintains dimensional consistency across layers, allowing seamless integration with feed-forward layers and residual connections.</p>
</li>
</ol>
<hr />
<h2 id="heading-intuitive-analogy">Intuitive Analogy:</h2>
<p>Imagine a team of specialists analyzing a document:</p>
<ul>
<li><p>Each specialist (attention head) focuses on a different aspect—grammar, semantics, tone, or structure.</p>
</li>
<li><p>They all produce individual reports (head outputs).</p>
</li>
<li><p>These reports are then merged and summarized into a single, cohesive document (the projection step) to ensure no insights are lost and the output is streamlined for further processing.</p>
</li>
</ul>
<hr />
<h3 id="heading-conclusion-the-power-of-multi-head-attention"><strong>Conclusion: The Power of Multi-Head Attention</strong></h3>
<p>Multi-Head Attention is a crucial enhancement of the self-attention mechanism, allowing transformers to <strong>capture multiple perspectives</strong> in parallel. By applying independent self-attention mechanisms, <strong>concatenating the outputs</strong>, and then <strong>projecting them back into the original embedding dimension</strong>, the model learns to extract richer contextual representations. This process ensures that transformers can <strong>effectively understand complex relationships between tokens</strong>, making them highly effective in NLP, computer vision, and beyond.</p>
<p>But Multi-Head Attention is just one piece of the puzzle. In the next part of this series, we’ll explore the <strong>Feed-Forward Network (FFN), Residual Connections, and Layer Normalization</strong>—key components that further refine the transformer’s ability to learn deep representations while stabilizing training.</p>
<p>Stay tuned for Part 4, where we’ll break down these mechanisms in detail! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the Role of Query, Key, and Value Matrices in Transformer Models]]></title><description><![CDATA[Explore the significance of Query, Key, and Value matrices in transformers, and understand their roles through intuitive explanations and analogies]]></description><link>https://blog.vikassrinivasa.dev/understanding-the-role-of-query-key-and-value-in-transformer-models</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/understanding-the-role-of-query-key-and-value-in-transformer-models</guid><category><![CDATA[nlp]]></category><category><![CDATA[nlp transformers]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Wed, 05 Feb 2025 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/XJXWbfSo2f0/upload/c479754d5895827ef2904e11f4693c7f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the world of transformers, the Query (Q), Key (K), and Value (V) matrices are the foundation of how attention mechanisms work. But what do these terms actually mean? Let’s break it down with an intuitive explanation and a practical analogy.</p>
<hr />
<h1 id="heading-what-do-query-q-key-k-and-valuev-matrices-denote">What do Query (Q), Key (K) and Value(V) matrices denote ?</h1>
<ol>
<li><p><strong>Query (Q):</strong> <strong><em>What are you looking for?</em></strong> The Query vector represents what a specific word (or token) is "looking for" in other words within the sequence.</p>
</li>
<li><p><strong>Key (K): <em>How do I identify information?</em></strong> The Key vector encodes information about a word in a way that makes it "searchable." Think of it as metadata for each token, indicating what kind of information this word provides.</p>
</li>
<li><p><strong>Value (V):</strong> <strong><em>What information do I provide?</em></strong> The Value vector represents the actual content or information that the word contributes to the overall representation.</p>
</li>
</ol>
<h3 id="heading-a-real-life-analogy-the-detective-team">A Real-Life Analogy: The Detective Team</h3>
<p>Imagine a team of detectives collaborating to solve a mystery. Here’s how Q, K, and V fit:</p>
<ul>
<li><p>Each detective has a specific question they want answered, like “Who was at the scene of the crime?”</p>
<p>  This is the <strong>Query</strong>—the focus of their search.</p>
</li>
<li><p>The evidence they have is labeled with tags like “time of arrival” or “fingerprints.” These labels make the evidence searchable.</p>
<p>  This is the <strong>Key</strong>—metadata describing what the evidence can tell us.</p>
</li>
<li><p>Each piece of evidence also contains the actual content: the fingerprint report, timestamps, or alibi details.</p>
<p>  This is the <strong>Value</strong>—the meaningful data itself.</p>
</li>
</ul>
<h1 id="heading-how-are-q-k-and-v-matrices-calculated">How Are Q, K, and V Matrices Calculated?</h1>
<p>The <strong>Query (</strong> \(Q\) <strong>)</strong>, <strong>Key (</strong> \(K\) <strong>)</strong>, and <strong>Value (</strong> \(V\) <strong>)</strong> matrices are computed by transforming the <strong>embedding vector (</strong> \(E\) <strong>)</strong> using learned weight matrices:</p>
<p>$$\text{Query(Q)}=E \times W_q \quad \text{Key(K)}=E \times W_k \quad \text{Value(V)}=E \times W_v$$</p><p>Where:</p>
<ul>
<li><p>\(E\) <strong>(Embedding Matrix,</strong> \( N \times D\) <strong>)</strong></p>
<ul>
<li><p>\(N\): Number of tokens in the input sequence.</p>
</li>
<li><p>\(D\): Feature dimensions describing each token (semantic meaning, syntactic role, and contextual nuance).</p>
</li>
</ul>
</li>
<li><p>\(W_q\), \(W_k\) and \(W_v\) are the learned weight matrices which are used to transform embeddings into <strong>queries, keys, and values</strong> for attention computation.</p>
</li>
</ul>
<h2 id="heading-why-multiply-weight-matrices-with-embeddings">Why Multiply Weight Matrices With Embeddings?</h2>
<p>When you multiply the embedding vector by the respective weight matrix (for Query, Key, or Value), the resulting matrix represents a transformation of the embedding. This transformation essentially <strong>adjusts the importance or emphasis assigned to each dimension</strong> of the token's representation for the specific role (Query, Key, or Value).</p>
<p>Let’s look at each of these matrices one by one now.</p>
<h2 id="heading-query-qweighted-questions">Query (Q):Weighted Questions</h2>
<p>The Query vector can indeed be thought of as a <strong>weighted representation of the questions that need to be asked about each token</strong>, specifically in terms of how relevant or important each dimension of the token's information is to the task at hand. The Query vector emphasizes certain dimensions of the token’s embedding, based on the context and the model's learned understanding of what is important for this token at this point in the sequence. These weights essentially tell the model, "<em>For this token, these specific aspects (dimensions) are most relevant when determining its relationship with other tokens</em>."</p>
<h3 id="heading-how-are-these-questions-formed">How are these questions formed ?</h3>
<ul>
<li><p>The "questions" encoded by the <strong>Query vector</strong> (via the weight matrix \(W_q\)) are <strong>not explicitly predetermined</strong>. Instead, they are <strong>learned</strong> during the model's training process.</p>
</li>
<li><p>The weight matrix \(W_q\) learns to transform the token embeddings into a space where they encode <em>"questions"</em> about the input.</p>
</li>
<li><p>These questions are context-sensitive, meaning the Query vector represents what this token is trying to "understand" based on its position and role in the sequence.</p>
</li>
</ul>
<p>So essentially the <strong>query matrix</strong> \(Q\) <strong>represents all the questions</strong> that are being asked about the input sequence. <strong>These questions aim to determine:</strong></p>
<ol>
<li><p><em>Which tokens are important for understanding the sequence.</em></p>
</li>
<li><p><em>Which properties (dimensions) of these tokens are relevant to answering the questions.</em></p>
</li>
</ol>
<p><strong>Think of it as</strong>: <em>"What do I need to focus on to understand this input?"</em></p>
<h2 id="heading-key-kmetadata-for-retrieval">Key (K):Metadata for Retrieval</h2>
<p>The weight matrix \(W_k\) adjusts the embedding to represent how the token provides information that others might find relevant. For instance, it might highlight dimensions like syntactic roles or semantic cues.</p>
<p><strong>The Key(K) matrix represents the metadata about each token</strong>, explaining:</p>
<ol>
<li><p><em>What kind of information each token provides.</em></p>
</li>
<li><p><em>How the dimensions of the token’s embedding describe this information.</em></p>
</li>
</ol>
<p><strong>Think of it as:</strong> <em>"Here’s my profile—this is what I can contribute and how to interpret me."</em></p>
<h2 id="heading-value-matrix-vthe-content">Value Matrix (V):The Content</h2>
<p><strong>Represents the actual content or information</strong> that each token contributes to the input sequence. This information is what the model ultimately uses after determining relevance via Query and Key interactions. <strong>Think of it as:</strong> <em>"Here’s the actual information I hold that can help you understand the sequence."</em></p>
<h3 id="heading-how-is-the-value-matrix-different-from-the-embedding-matrix">How is the value matrix different from the embedding matrix ?</h3>
<p>Both the value matrix and embedding matrix do indeed represent information about each token across dimensions, but they serve <strong>different purposes and are used differently</strong> in the transformer.</p>
<p>The <strong>embedding vector</strong> is like a general encyclopedia entry for a token—it’s rich and multi- purpose but not directly optimized for the specific task at hand. The <strong>Value vector</strong> on the other hand is like a custom summary of that entry, tuned to the specific needs of the attention mechanism in the current sequence. <strong>The value matrix is essentially an augmented and task-specific representation of the embedding vector, tailored to the input sequence and the task at hand.</strong></p>
<p>Here’s a travel guide analogy which will help you understand this better</p>
<p>Imagine a travel guidebook (the embedding vector):</p>
<ul>
<li><p>The guidebook contains all general information about a city (e.g., landmarks, history, transportation) - this is analogous to the embedding vector.</p>
</li>
<li><p>If you're planning a specific trip, you'll extract only the sections relevant to your trip goals (e.g.,places to visit, public transit details, etc.) and organize them for your itinerary - similar to the value vector.</p>
</li>
</ul>
<h3 id="heading-how-the-value-vector-augments-the-embedding-vector">How the Value Vector Augments the Embedding Vector:</h3>
<ol>
<li><p><strong>Embedding as a Base Representation:</strong> The embedding vector is a general-purpose encoding of a token, independent of the specific sequence or task. It contains semantic and syntactic information about the token in a learned vector space.</p>
</li>
<li><p><strong>Task-Specific Transformation:</strong> The Value vector is created by multiplying the embedding vector with a learned weight matrix ( \(W_v\) ). This transformation adjusts the embedding to emphasize dimensions that are relevant for the specific task or the context of the input sequence.</p>
</li>
<li><p><strong>Context-Aware Representation:</strong> The weight matrix ( \(W_v\) ) is learned during training and adapts the embedding to better reflect the token's role in the specific sequence. For example, in a translation task, certain dimensions might focus on semantic roles (e.g., subject-object relationships), while in a summarization task, different dimensions might emphasize sentence importance.</p>
</li>
<li><p><strong>Preserving the Core Information:</strong> The Value vector retains the core information from the embedding vector but filters and highlights the most task-relevant and context-relevant features.</p>
</li>
</ol>
<h2 id="heading-translating-to-transformers"><strong>Translating to Transformers :</strong></h2>
<p>In a transformer, every token in a sequence acts like a detective:</p>
<ol>
<li><p>Each token uses its <strong>Query</strong> to ask questions.</p>
</li>
<li><p>Every token presents its <strong>Key</strong> to show what kind of information it holds.</p>
</li>
<li><p>The token’s <strong>Value</strong> provides the actual content used after relevance is determined.</p>
</li>
</ol>
<p>The model calculates the relevance between Queries and Keys (called the alignment score) to determine how much attention each token should pay to others. This process enables dynamic, context-aware information sharing across the sequence.</p>
<h2 id="heading-why-q-k-and-v-are-powerful">Why Q, K, and V Are Powerful</h2>
<p>Using Query, Key, and Value matrices, transformers allow every token to interact dynamically with every other token in the sequence. This mechanism ensures that the model captures context effectively, making it one of the most powerful architectures for tasks like language translation, summarization, and more.</p>
<hr />
<p>Now that we’ve broken down the roles of <strong>Query (Q), Key (K), and Value (V)</strong> in a transformer, it’s clear how these components enable the model to dynamically determine relationships between tokens. Each token <strong>asks questions (Query), presents relevant details (Key), and provides useful content (Value)</strong>—forming the foundation of the attention mechanism that makes transformers so powerful.</p>
<p>But how does a transformer actually <strong>decide which tokens to focus on?</strong> This is where <strong>alignment scores</strong> come into play! 🚀</p>
<p>🔗 <strong>Read more about alignment scores and attention computation here:</strong> <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/transformer-encoder-explained-a-deep-dive-into-attention-scores-part-2"><em>Transformer Encoder Explained : A Deep Dive into Attention Scores (Part 2)</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Transformer Encoder Explained : A Deep Dive into Attention Scores (Part 2)]]></title><description><![CDATA[Explore the self-attention mechanism in transformer models, focusing on computing attention scores and understanding token relevance in sequences]]></description><link>https://blog.vikassrinivasa.dev/transformer-encoder-explained-a-deep-dive-into-attention-scores-part-2</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/transformer-encoder-explained-a-deep-dive-into-attention-scores-part-2</guid><category><![CDATA[nlp]]></category><category><![CDATA[nlp transformers]]></category><category><![CDATA[attention-mechanism]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Wed, 05 Feb 2025 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/afcd4c916bb16e838b02aac0d440d67c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In <strong>Part 1</strong> of this series, we explored how raw text is transformed into a numerical format through <strong>tokenization, embeddings, and positional encoding</strong>—laying the groundwork for understanding how transformers process data. If you haven't checked it out yet, you can read it here: <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/how-transformers-work-tokenization-embeddings-and-positional-encoding-explained-part-1"><em>How Transformers Work: Tokenization Embeddings and Positional Encoding Explained (Part 1)</em></a><em>.</em></p>
<p>Now, in <strong>Part 2</strong>, we dive into the <strong>self-attention mechanism</strong>, breaking down how transformers compute <strong>attention scores</strong> to determine which tokens in a sequence are most relevant to each other. Let’s get started! 🚀</p>
<hr />
<h1 id="heading-what-is-an-attention-score">What is an Attention Score?</h1>
<p>An <strong>attention score</strong> is a numerical value that determines how much importance one token in a sequence should assign to another. These scores are computed as part of the <strong>self-attention mechanism</strong> in a transformer, helping the model understand contextual relationships between tokens.</p>
<h3 id="heading-how-are-attention-scores-computed">How Are Attention Scores Computed?</h3>
<p>The process of computing attention scores involves several steps:</p>
<ol>
<li><p><strong>Generating Query (Q), Key (K), and Value (V) matrices</strong></p>
</li>
<li><p><strong>Computing alignment scores</strong> to measure relationships between tokens</p>
</li>
<li><p><strong>Applying the softmax function</strong> to normalize these scores into probabilities</p>
</li>
<li><p><strong>Applying a linear transformation</strong> to refine the attention output</p>
</li>
</ol>
<p>We’ll start by exploring how attention scores are calculated within a <strong>single attention head</strong> and then extend this understanding to <strong>multi-head attention</strong>, which enhances the model’s ability to capture diverse contextual relationships.</p>
<hr />
<h1 id="heading-11-computing-the-query-q-keyk-and-value-v-matrices">1.1 <strong>Computing The Query (Q) , Key(K) and Value (V) Matrices</strong></h1>
<p>The attention layer in the encoder has multiple attention heads and each head has three weight matrices \(W_q\),\(W_k\) and \(W_v\) each of order \(D \times (\frac{D}{\text{No. Of Heads}})\) ( \(D\) denotes dimension size). They are initialized randomly such that for each head the values of the weight matrices are unique i.e the values of the weight matrices of no two heads are the same. The weight matrices are used to compute three matrices namely query , key and value which are used to compute the attention scores.</p>
<ol>
<li><p><strong>Query (Q) :</strong></p>
<ol>
<li><p>A query is a vector that asks a question about the relationship between the current token and other tokens. For example, in a sentence, "The dog chased the cat," the query for "dog" might be asking, "Who or what is related to the dog?"</p>
</li>
<li><p>It is computed as follows :</p>
<p> $$Q= \text{Input Matrix} \times W_q$$</p>
</li>
<li><p>The "questions" encoded by the Query vector (via the weight matrix \(W_q\)) are not explicitly predetermined. Instead, they are learned during the model's training process.</p>
</li>
</ol>
</li>
<li><p><strong>Key (K):</strong></p>
<ol>
<li><p>Think of it as metadata for each token, indicating what kind of information this word provides. For example, in the sentence "The dog chased the cat," the key for "cat" might encode information like "animal" or "object being acted upon."</p>
</li>
<li><p>It is computed as :</p>
</li>
</ol>
</li>
</ol>
<p>$$K =\text{Input Matrix} \times W_k$$</p><ol>
<li><p><strong>Value (V):</strong></p>
<ol>
<li><p>What it represents:</p>
<p> A value is the vector containing the actual information or content of a token that will be passed to the next layer if that token is deemed important. In the example "The dog chased the cat," the value for "cat" might contain its embedding and context-specific information about "cat."</p>
</li>
<li><p>It is computed as :</p>
</li>
</ol>
</li>
</ol>
<p>    $$V= \text{Input Matrix}\times W_v$$</p>
<p>In our use case because our dimension size is small we can have only one attention head.</p>
<p>The weight matrices( \(W_q\), \(W_k\) and \(W_v\) will be initialized to random values initially , these randomly initialized weight matrices are given below:</p>
<p>$$\textbf{Weight Matrices:}$$</p><p>$$\begin{array}{c c c} {W_q} &amp; {W_k} &amp; {W_v} \\ \begin{bmatrix} 0.3745 &amp; 0.9507 &amp; 0.7320 \\ 0.5987 &amp; 0.1560 &amp; 0.1560 \\ 0.0581 &amp; 0.8662 &amp; 0.6011 \end{bmatrix} &amp; \begin{bmatrix} 0.7081 &amp; 0.0206 &amp; 0.9699 \\ 0.8324 &amp; 0.2123 &amp; 0.1818 \\ 0.1834 &amp; 0.3042 &amp; 0.5248 \end{bmatrix} &amp; \begin{bmatrix} 0.4320 &amp; 0.2912 &amp; 0.6119 \\ 0.1395 &amp; 0.2921 &amp; 0.3664 \\ 0.4561 &amp; 0.7852 &amp; 0.1997 \end{bmatrix} \\ \end{array}$$</p><p>The \(Q\), \(K\) and \(V\) matrices obtained on by multiplying the input matrix with their corresponding learned weight matrices ( \(W_q\), \(W_k\), and \(W_v\)) are given below :</p>
<p>$$\begin{array}{c c c} \textbf{Query Matrix } Q &amp; \textbf{Key Matrix } K &amp; \textbf{Value Matrix } V \\ \begin{bmatrix} 1.1904 &amp; 0.1467 &amp; 0.4669 \\ 2.0582 &amp; 0.2445 &amp; 1.6091 \\ 2.0105 &amp; 0.6131 &amp; 1.5091 \\ 1.4613 &amp; 0.2865 &amp; 1.2076 \\ 0.3440 &amp; 0.1828 &amp; -0.5350 \\ 0.4377 &amp; 0.4853 &amp; -0.5507 \\ 1.6470 &amp; 0.3173 &amp; 0.5242 \\ 2.0412 &amp; 0.2458 &amp; 1.6666 \\ 1.5460 &amp; 0.2431 &amp; 1.1800 \\ 1.6145 &amp; 0.2871 &amp; 1.5270 \\ 1.0075 &amp; 0.4310 &amp; 0.0520 \\ 0.9114 &amp; 0.2611 &amp; 0.1972 \end{bmatrix} &amp; \begin{bmatrix} 1.1904 &amp; 0.1467 &amp; 0.4669 \\ 2.0582 &amp; 0.2445 &amp; 1.6091 \\ 2.0105 &amp; 0.6131 &amp; 1.5091 \\ 1.4613 &amp; 0.2865 &amp; 1.2076 \\ 0.3440 &amp; 0.1828 &amp; -0.5350 \\ 0.4377 &amp; 0.4853 &amp; -0.5507 \\ 1.6470 &amp; 0.3173 &amp; 0.5242 \\ 2.0412 &amp; 0.2458 &amp; 1.6666 \\ 1.5460 &amp; 0.2431 &amp; 1.1800 \\ 1.6145 &amp; 0.2871 &amp; 1.5270 \\ 1.0075 &amp; 0.4310 &amp; 0.0520 \\ 0.9114 &amp; 0.2611 &amp; 0.1972 \end{bmatrix} &amp; \begin{bmatrix} 0.2001 &amp; 0.1991 &amp; 0.6198 \\ 0.7546 &amp; 0.6788 &amp; 1.3418 \\ 0.9585 &amp; 1.3736 &amp; 1.2265 \\ 0.6461 &amp; 0.7333 &amp; 0.9554 \\ -0.1936 &amp; 0.0401 &amp; -0.0691 \\ -0.0077 &amp; 0.6065 &amp; -0.0870 \\ 0.2914 &amp; 0.4476 &amp; 0.7973 \\ 0.7873 &amp; 0.7108 &amp; 1.3539 \\ 0.5923 &amp; 0.6145 &amp; 0.9882 \\ 0.7935 &amp; 0.8368 &amp; 1.1251 \\ 0.1999 &amp; 0.6229 &amp; 0.3577 \\ 0.1711 &amp; 0.3754 &amp; 0.3957 \end{bmatrix} \\ \end{array}$$</p><p><strong>NOTE :</strong></p>
<p>In actual practice however, the dimension size will be much larger like 512 , 768 and 1024. So , the resultant \(Q\), \(K\) and \(V\) matrices in those cases would be of the order \(N \times (\frac{D}{\text{No. Of Heads}})\).</p>
<p>Since, the example considered here has only one attention head, the \(Q\), \(K\) and \(V \) matrices are of the order \(N \times D\).</p>
<blockquote>
<p>📌 A deeper intuition behind the Query, Key, and Value vectors goes beyond the scope of this blog. However, you can explore it in detail in <a target="_blank" href="https://transformers-goto-guide.hashnode.dev/understanding-the-role-of-query-key-and-value-in-transformer-models">Understanding the Role of Query, Key, and Value Matrices in Transformer Models</a>.</p>
</blockquote>
<h1 id="heading-12-computing-the-alignment-scores"><strong>1.2 Computing The Alignment Scores</strong></h1>
<p>In transformer models, the alignment score matrix, denoted as \(Score(Q,K)\), plays a pivotal role in determining the relevance or importance of each token to every other token in a sequence.</p>
<h2 id="heading-what-is-the-alignment-score-matrix">What is the Alignment Score Matrix?</h2>
<p>The \(Score(Q, K)\) matrix represents <strong>how relevant or important each token is to every other token</strong> in the sequence. It determines the <strong>degree of alignment</strong> between the "questions" (Queries) being asked by a token and the "metadata" (Keys) provided by all other tokens. You can think of it as a <strong>"relevance map"</strong> that guides how much attention each token should pay to every other token.</p>
<p><strong>Formula for Alignment Score</strong></p>
<p>$$Score(Q, K)=\frac{Q \ldotp K^{T}}{\sqrt \frac{D}{\text{No. Of Heads}}}$$</p><p>Here:</p>
<ul>
<li><p>\(Q\): Query matrix</p>
</li>
<li><p>\(K\): Key matrix</p>
</li>
<li><p>\(D\): Dimensionality of the model</p>
</li>
<li><p>\(\text{No. of Heads}\) : Number of attention heads (in this case, only one)</p>
</li>
</ul>
<p>Since there is only one head in our example, we have only one score matrix.</p>
<h2 id="heading-how-it-works">How It Works ?</h2>
<p>A token's <strong>Query vector (</strong> \(Q\) <strong>)</strong> represents what it seeks to understand, while <strong>Key vectors (</strong>\(K\)<strong>)</strong> from other tokens describe the information they offer. The <strong>dot product of</strong> \(Q\) <strong>and</strong> \(K\) generates an <strong>alignment score</strong>, measuring how useful a token's information is to understand what the query vector seeks. This score helps determine how much attention each token should give to others.</p>
<h2 id="heading-how-to-interpret-the-scoreq-k-matrix">How to Interpret the Score(Q, K) Matrix ?</h2>
<p>The \(Score(Q, K)\)matrix provides a <strong>map of token-to-token importance</strong>. Each element reflects</p>
<ol>
<li><p><strong>Semantic Relationship</strong> : The dot product between \(Q\) and \(K\) captures the similarity between the query token and key tokens. A higher score indicates stronger semantic alignment.</p>
</li>
<li><p><strong>Relative Importance :</strong> The scores reflect the raw importance of each key token concerning the query token. These are used to compute attention weights.</p>
</li>
<li><p><strong>Contextual Focus :</strong> The alignment scores guide the query token in determining which tokens to "pay attention to" while constructing its representation.</p>
</li>
</ol>
<h3 id="heading-analogy-a-group-discussion"><strong>Analogy: A Group Discussion</strong></h3>
<p>Think of a conversation where:</p>
<ul>
<li><p>Each participant (token) <strong>asks questions</strong> ( \(Q\) ) to understand the context.</p>
</li>
<li><p>Every participant also <strong>shares their expertise</strong> ( \(K\) ) to provide useful information.</p>
</li>
<li><p>The \(\text{Score}(Q, K)\) <strong>matrix</strong> acts as a <strong>relevance chart</strong>, showing <strong>who best answers whose questions</strong>.</p>
</li>
</ul>
<p>For example, if someone asks about <strong>timelines</strong>, a participant specializing in <strong>timelines</strong> will have a <strong>high alignment score</strong>, influencing the discussion more.</p>
<h2 id="heading-example-alignment-score-matrix-in-practice">Example: Alignment Score Matrix in Practice</h2>
<p>The alignment score matrix for our use case is given below:</p>
<p>$$\text{Score}(Q, K) = \begin{bmatrix} 0.6727 &amp; 1.3030 &amp; \dots &amp; 0.5140 \\ 1.3371 &amp; 2.8624 &amp; \dots &amp; 1.0407 \\ 1.3881 &amp; 3.0150 &amp; \dots &amp; 1.0887 \\ \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\ 0.5179 &amp; 0.9806 &amp; \dots &amp; 0.3962 \end{bmatrix}$$</p><h3 id="heading-properties">Properties:</h3>
<ul>
<li><p>It is a square matrix of order \(N \times N\) where \(N\) is the number of tokens.</p>
</li>
<li><p>Each cell indicates the alignment score between a pair of tokens in the sequence.</p>
</li>
</ul>
<hr />
<h1 id="heading-13-normalizing-the-alignment-score-to-obtain-attention-weights"><strong>1.3. Normalizing the Alignment Score To Obtain Attention Weights</strong></h1>
<p><strong>The</strong> \(\text{Score}(Q, K)\)<strong>matrix is computed for all heads are then normalized using a softmax function to get attention weights denoted by</strong> \(\alpha\)<strong>.</strong> Applying softmax to the alignment scores serves to normalize them into a probability distribution, making the scores more interpretable and ensuring they can be treated as weights for aggregating the value vectors.</p>
<h2 id="heading-what-is-the-softmax-function">What is the Softmax Function?</h2>
<p>The softmax function <strong>converts raw scores into probabilities</strong>, <strong>normalizes values within [0,1]</strong>, and <strong>ensures they sum to 1</strong>.</p>
<p>The formula for the <strong>softmax activation function</strong> is:</p>
<p>$$\sigma(z_i) = \frac{e^{z_i}}{\sum_{j=1}^n e^{z_j}}$$</p><p>Where:</p>
<ul>
<li><p>\(z_i\) is the i-th input element to the softmax function.</p>
</li>
<li><p>\(e^{z_i}\) is the exponential function applied to \(z_i\).</p>
</li>
<li><p>\(n\) is the total number of input elements.</p>
</li>
<li><p>\(\sum_{j=1}^n e^{z_j}\) is the sum of the exponential of all input elements, which normalizes the output.</p>
</li>
</ul>
<h2 id="heading-how-softmax-enhances-alignment-scores"><strong>How Softmax Enhances Alignment Scores</strong></h2>
<h4 id="heading-before-normalization"><strong>Before Normalization:</strong></h4>
<p>The raw <strong>alignment scores</strong> \(\text{Score}(Q,K)\) represent similarity between Query and Key vectors but:</p>
<ul>
<li><p>Can have arbitrary values, including negatives or large magnitudes.</p>
</li>
<li><p>Lack a clear, interpretable scale for weighting Value vectors effectively.</p>
</li>
</ul>
<h4 id="heading-after-applying-softmax"><strong>After Applying Softmax:</strong></h4>
<p>Softmax transforms these raw scores into a <strong>probability distribution</strong>, making them more meaningful and useful for attention computation:</p>
<ol>
<li><p><strong>Ensuring Interpretability</strong></p>
<ul>
<li><p>Converts raw scores into probabilities that <strong>sum to 1</strong> for each Query.</p>
</li>
<li><p>Allows the model to understand <strong>relative importance</strong>, ensuring each token's influence is bounded and weighted appropriately.</p>
</li>
</ul>
</li>
<li><p><strong>Determining Relative Importance</strong></p>
<ul>
<li><p>The <strong>exponential function</strong> amplifies significant scores while <strong>suppressing smaller ones</strong>, sharpening attention towards <strong>highly relevant tokens</strong>.</p>
</li>
<li><p>The resulting attention scores help the model focus on <strong>the most important tokens</strong> in the sequence.</p>
</li>
<li><p>This essentially implies that softmax exaggerates score differences, ensuring attention is concentrated on the most relevant tokens.</p>
</li>
</ul>
</li>
<li><p><strong>Capturing Relevance</strong></p>
<ul>
<li><p>Normalization ensures that each Query token distributes attention effectively across Key tokens.</p>
</li>
<li><p>Higher scores indicate <strong>stronger relevance</strong>, guiding the model to pay more attention to critical tokens while minimizing distractions.</p>
</li>
<li><p>This essentially implies that softmax normalizes scores into a probability distribution, ensuring proper weighting of token relevance.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-example-attention-weights-in-practice">Example: Attention Weights in Practice</h2>
<p>For our use case, the attention weights ( \(\alpha\) ) are derived from the softmax-normalized alignment scores. The resulting weights are shown below:</p>
<p>$$\text{Attention Weights } (\alpha) = \begin{bmatrix} 0.0661 &amp; 0.1241 &amp; 0.1276 &amp; \dots &amp; 0.0999 &amp; 0.0593 &amp; 0.0564 \\ 0.0368 &amp; 0.1691 &amp; 0.1970 &amp; \dots &amp; 0.1197 &amp; 0.0278 &amp; 0.0258 \\ 0.0324 &amp; 0.1651 &amp; 0.2142 &amp; \dots &amp; 0.1275 &amp; 0.0234 &amp; 0.0219 \\ \vdots &amp; \vdots &amp; \vdots &amp; \ddots &amp; \vdots &amp; \vdots &amp; \vdots \\ 0.0661 &amp; 0.1196 &amp; 0.1271 &amp; \dots &amp; 0.1016 &amp; 0.0609 &amp; 0.0581 \\ 0.0685 &amp; 0.1159 &amp; 0.1217 &amp; \dots &amp; 0.0996 &amp; 0.0635 &amp; 0.0609 \end{bmatrix}$$</p><h2 id="heading-intuitive-analogy">Intuitive Analogy:</h2>
<p>Imagine you’re picking relevant answers in a quiz:</p>
<ul>
<li><p>The alignment scores are the raw relevance ratings (e.g., 7/10, 9/10, etc.) for each possible answer.</p>
</li>
<li><p>The softmax converts these ratings into percentages (e.g., 60%, 30%, 10%), showing how much weight you give to each answer when combining them to form your understanding.</p>
</li>
</ul>
<p>This analogy illustrates how the softmax function emphasizes the most relevant scores while normalizing the overall distribution.</p>
<hr />
<h1 id="heading-14-computing-the-final-attention-output-and-applying-linear-transformation">1.4. Computing the final Attention Output And Applying Linear Transformation</h1>
<p>Attention output for each head is computed as follows :</p>
<p>$$\text{Attention Output} = \alpha . V$$</p><p>Where:</p>
<ul>
<li><p>\(\alpha\) : Normalized attention scores (from \(\text{Softmax}(\text{Score}(Q,K))\)).</p>
</li>
<li><p>\(V\): Value matrix containing the information content for each token.</p>
</li>
</ul>
<h3 id="heading-breaking-down-the-computation"><strong>Breaking Down the Computation</strong></h3>
<ol>
<li><p><strong>Attention Weights (Softmax Scores)</strong> – Define how much focus a Query token assigns to each Key token, controlling how Value vectors influence its representation.</p>
</li>
<li><p><strong>Value Vectors (</strong> \(V\) <strong>)</strong> – Contain task-relevant semantic information from each token, essential for model understanding.</p>
</li>
<li><p><strong>Weighted Summation (</strong> \(\alpha \cdot V \) <strong>)</strong> – Aggregates Value vectors based on attention weights, ensuring relevant tokens contribute more while refining contextual representations.</p>
</li>
</ol>
<h3 id="heading-why-multiply-attention-weights-with-the-value-matrix"><strong>Why Multiply Attention Weights with the Value Matrix?</strong></h3>
<h4 id="heading-1-combining-relevant-information"><strong>1. Combining Relevant Information</strong></h4>
<ul>
<li><p>Attention weights ( \(\alpha\) ) indicate <strong>how much importance</strong> each token assigns to others.</p>
</li>
<li><p>The value matrix ( \(V\)) contains the actual <strong>content</strong> of each token.</p>
</li>
<li><p>Multiplying \(\alpha\) with \(V\) <strong>aggregates relevant information</strong>, weighted by importance.</p>
</li>
</ul>
<h4 id="heading-2-weighted-summation"><strong>2. Weighted Summation</strong></h4>
<ul>
<li><p>The final token representation is a <strong>weighted sum of value vectors</strong>.</p>
</li>
<li><p>This ensures the model <strong>focuses on the most relevant tokens</strong> while minimizing distractions.</p>
</li>
</ul>
<h4 id="heading-3-contextualization"><strong>3. Contextualization</strong></h4>
<ul>
<li><p><strong>Value vectors (</strong> \(V\) <strong>) provide content</strong>, while <strong>attention weights (</strong> \(\alpha\) <strong>) dictate importance</strong>.</p>
</li>
<li><p>This transformation <strong>enhances token embeddings</strong>, making them <strong>context-aware</strong> and capturing relationships in the sequence.</p>
</li>
</ul>
<h3 id="heading-analogy-writing-a-summary"><strong>Analogy: Writing a Summary</strong></h3>
<p>Imagine summarizing a paragraph:</p>
<ul>
<li><p><strong>Attention weights</strong> decide <strong>how much focus</strong> each sentence gets.</p>
</li>
<li><p><strong>Value vectors</strong> hold <strong>the actual information</strong> from the sentences.</p>
</li>
<li><p><strong>Weighted summation</strong> merges the most relevant details into a <strong>coherent summary</strong>.</p>
</li>
</ul>
<h3 id="heading-understanding-the-attention-output-matrix"><strong>Understanding the Attention Output Matrix</strong></h3>
<ul>
<li><p>Each <strong>row</strong> represents a token in the sequence.</p>
</li>
<li><p>The row’s values form a <strong>vector that encodes the token’s meaning</strong> after attending to other tokens.</p>
</li>
<li><p>This contextual representation allows the model to understand words <strong>in relation to the entire input sequence</strong>.</p>
</li>
</ul>
<h4 id="heading-matrix-dimensions"><strong>Matrix Dimensions</strong></h4>
<ul>
<li><p>The <strong>attention output matrix</strong> from each attention head has dimensions:</p>
</li>
<li><p>$$N \times \frac{D}{\text{No. of Heads}}$$</p></li>
<li><p>With \(H\) <strong>attention heads</strong>, we get \(H\) <strong>attention output matrices</strong> of the same size.</p>
</li>
<li><p>These matrices are <strong>horizontally stacked</strong> to form a <strong>single attention output matrix</strong> of size: \(N \times D\)</p>
</li>
</ul>
<p>$$\text{Attention Output} = \begin{bmatrix} 0.2131 &amp; 0.3482 &amp; 0.3967 \\ 0.8221 &amp; 1.0589 &amp; 1.3860 \\ 0.9912 &amp; 1.2546 &amp; 1.6513 \\ \vdots &amp; \vdots &amp; \vdots \\ 0.6240 &amp; 0.8280 &amp; 1.0567 \\ 0.1669 &amp; 0.2925 &amp; 0.3192 \\ 0.1561 &amp; 0.2777 &amp; 0.2999 \end{bmatrix}$$</p><hr />
<p>Now that we’ve explored how self-attention works within a <strong>single attention head</strong>, the next step is to understand how <strong>multi-head attention</strong> enhances this process—enabling the transformer to capture multiple aspects of meaning from different perspectives.</p>
<p>📌 <strong>Checkout Part 3 of the series</strong>, where we’ll dive deep into <strong>Multi-Head Attention</strong> and how it allows transformers to understand context even better! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[How Transformers Work: Tokenization Embeddings and Positional Encoding Explained (Part 1)]]></title><description><![CDATA[Learn How Transformers Operate Intuitively : The Basics of Tokenization, Embeddings and Positional Encoding]]></description><link>https://blog.vikassrinivasa.dev/how-transformers-work-tokenization-embeddings-and-positional-encoding-explained-part-1</link><guid isPermaLink="true">https://blog.vikassrinivasa.dev/how-transformers-work-tokenization-embeddings-and-positional-encoding-explained-part-1</guid><category><![CDATA[nlp transformers]]></category><category><![CDATA[nlp]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[AI]]></category><category><![CDATA[transformers]]></category><category><![CDATA[neural networks]]></category><dc:creator><![CDATA[Vikas Srinivasa]]></dc:creator><pubDate>Tue, 28 Jan 2025 14:08:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iar-afB0QQw/upload/afcd4c916bb16e838b02aac0d440d67c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In recent years, transformers have revolutionized the field of Natural Language Processing (NLP), enabling breakthroughs in machine translation, text generation, and conversational AI. But how do these powerful models actually work? In this series, we’ll break down the inner workings of transformers in an intuitive and structured manner. This first blog will focus on the foundational steps—tokenization and embeddings—crucial for transforming raw text into a format that transformers can understand. By the end of this post, you’ll have a clear grasp of how text is processed and represented numerically before feeding it into a transformer model.</p>
<h1 id="heading-what-is-a-transformer">What is a Transformer ?</h1>
<p>A <strong>Transformer</strong> is a deep learning model architecture designed to process and transform sequential data, such as text, into meaningful outputs. It is the foundation for many state-of-the-art natural language processing (NLP) models, such as GPT, BERT, and T5. Transformers are particularly effective because they rely on a mechanism called <strong>self-attention</strong>, which allows the model to weigh the importance of different words in a sequence when making predictions or translations.</p>
<p>To intuitively understand how a Transformer works, let's consider an example from a machine translation task, where we train a transformer to translate an English sentence into French. Below are the input and target sentences that will be used to train the transformer:</p>
<ol>
<li><p><strong>English Input (Source Sequence):</strong></p>
<p> <code>"My name is Vikas. I love cricket, finance and AI."</code></p>
</li>
<li><p><strong>French Translation (Target Sequence):</strong></p>
<p> <code>"Mon nom est Vikas. J'aime le cricket, la finance et l'IA."</code></p>
</li>
</ol>
<h1 id="heading-why-were-transformers-introduced">Why Were Transformers Introduced?</h1>
<p>Transformers were designed to address the following key limitations of RNNs and encoder-decoder models with attention:</p>
<ol>
<li><p><strong>Sequential Processing in RNNs:</strong></p>
<p> RNNs and encoder-decoder models with attention process inputs sequentially, which limits their ability to leverage parallelism during training. Transformers eliminate this constraint by processing entire sequences simultaneously using self-attention.</p>
</li>
<li><p><strong>Long-Term Dependencies:</strong></p>
<p> Even with attention mechanisms, RNNs can struggle with very long sequences due to their sequential nature and reliance on hidden states. Transformers use self-attention to directly compute dependencies between all tokens in a sequence, regardless of distance.</p>
</li>
<li><p><strong>Scalability:</strong></p>
<p> Training RNN-based models with attention can be computationally intensive for long sequences. Transformers scale more efficiently due to their ability to parallelize computations over the entire sequence.</p>
</li>
</ol>
<h1 id="heading-lets-start-with-the-first-step-tokenization">Let’s start with the first step , Tokenization</h1>
<p>Tokenization is a fundamental step in <strong>Natural Language Processing (NLP) pipelines</strong>, where a text corpus is broken into smaller units called <strong>tokens</strong>. These tokens can be <strong>words, subwords, or characters</strong>, making the text easier for models to process.</p>
<p>Transformers often use <strong>Byte Pair Encoding (BPE)</strong>, but for simplicity, we'll demonstrate <strong>word-based tokenization</strong> using the following corpus:</p>
<p><strong>Corpus:</strong><br /><em>"My name is Vikas. I love cricket, finance, and AI."</em></p>
<h3 id="heading-word-tokenization-process"><strong>Word Tokenization Process</strong></h3>
<ol>
<li><p><strong>Identifying Word Boundaries</strong> → Words are separated by <strong>spaces, punctuation, or delimiters</strong>.</p>
</li>
<li><p><strong>Handling Punctuation</strong> → Symbols like <strong>periods (.) and commas ( , )</strong> can be treated as <strong>separate tokens</strong> when needed for the task.</p>
</li>
</ol>
<h3 id="heading-tokenized-output"><strong>Tokenized Output</strong></h3>
<p>Applying <strong>word-based tokenization</strong> to the corpus results in:</p>
<p>$$\text{["My", "name", "is", "Vikas", ".", "I", "love", "cricket", ",", "finance", "and", "AI", "."]}$$</p><p>This simple yet effective tokenization method helps convert raw text into a structured format, making it easier for NLP models to analyze and process.</p>
<hr />
<h1 id="heading-creating-a-vocabulary">Creating a Vocabulary</h1>
<p>To prepare the text for input into a transformer model, we extract the unique tokens from the tokenized output. This step creates a vocabulary, which maps each token to a unique identifier (e.g., an integer). Here is the set of unique tokens from the corpus:</p>
<blockquote>
<p><em>["My", "name", "is", "Vikas", ".", "I", "love", "cricket", ",", "finance", "and", "AI"]</em></p>
</blockquote>
<hr />
<h1 id="heading-creating-embeddings-from-tokens">Creating Embeddings From Tokens</h1>
<p>The next step is to convert unique tokens into a format which machine learning models can understand.</p>
<p>Machine learning models operate on numerical data. The process of converting high-dimensional data such as text to a numerical format (called embeddings) that can be represented in a low dimensional space is called Vectorization.</p>
<h2 id="heading-what-is-an-embedding-vector">What is an Embedding Vector ?</h2>
<p><strong>Embedding Vectors are</strong> <strong>a High-Dimensional Representation of Tokens.</strong> Embedding vectors reside in a high-dimensional space where each token is represented by a vector. These vectors capture rich and meaningful information about each token. To achieve this, the information for each token is represented in terms of various features or properties:</p>
<p>Rows in the embedding matrix correspond to tokens. Columns in the embedding matrix correspond to latent features or properties.Values in the matrix indicate how much a particular token (row) relates to a specific property (column).</p>
<p>However, these columns (properties) are not explicitly named or predefined. Instead, they are learned during training.The initial values (scores) in the embedding matrix are random and adjusted as the model learns from the data.</p>
<h3 id="heading-what-is-embedding-dimension">What is Embedding Dimension ?</h3>
<p>The embedding dimension is the number of ways you can describe the meaning of a token. Each column (dimension) captures one aspect of the token’s semantics.</p>
<p><strong>Example Analogy:</strong> <strong>Describing a Person</strong></p>
<p>Imagine describing people in a table:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Person</td><td>Age</td><td>Height</td><td>Weight</td><td>Eye Color</td><td>Hair</td><td>Type</td><td>…</td></tr>
</thead>
<tbody>
<tr>
<td>Alice</td><td>25</td><td>5'7"</td><td>140</td><td>Brown</td><td>Curly</td><td></td><td>…</td></tr>
<tr>
<td>Bob</td><td>30</td><td>6’0”</td><td>180</td><td>Blue</td><td>Straight</td><td></td><td>…</td></tr>
</tbody>
</table>
</div><p>Each column represents a way to describe a person (age, height, etc.). The number of columns is the embedding dimension. More columns provide more descriptive power.</p>
<p>Similarly for tokens , each row in an embedding vector describes that token in as many ways as the number of columns.</p>
<p>Each column captures a distinct semantic property, such as:</p>
<ol>
<li><p>Does this word convey a sense of time?</p>
</li>
<li><p>Is this word formal or informal?</p>
</li>
<li><p>Does this word relate to food, emotions, or actions?</p>
</li>
</ol>
<p><strong>Deciding the Dimension Size</strong> The embedding dimension size determines how much information can be encoded for each token:</p>
<ol>
<li><p><strong>Complexity of Meaning:</strong></p>
<ol>
<li><p><strong>Small dimension (e.g., 50):</strong> Captures basic meanings. Useful for simple tasks like binary classification or topic detection.</p>
</li>
<li><p><strong>Large dimension (e.g., 512 or more):</strong> Captures rich, nuanced meanings. Necessary for complex tasks like machine translation, summarization, or question answering.</p>
</li>
</ol>
</li>
<li><p><strong>Analogous to Compression:</strong> Think of embedding as compressing the meaning of a token into a fixed-size vector:</p>
<ol>
<li><p><strong>Low-dimensional embeddings</strong>: Coarse representations that lose some details. Analogous to a black-and-white photo.</p>
</li>
<li><p><strong>High-dimensional embeddings</strong>: Detailed representations that preserve subtle nuances. Analogous to a high-resolution color photo.</p>
</li>
</ol>
</li>
</ol>
<p>There are many techniques used to create embeddings , for our use case let us consider Word2Vec. How Word2Vec works is beyond the scope of this blog.</p>
<p>For the sake of simplicity , let us assume a dimension size of 3. If we train Word2Vec on all the unique tokens in our corpus , our embedding matrix might end up looking like this.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Word</td><td>Vector (Dimension 3)</td></tr>
</thead>
<tbody>
<tr>
<td>My</td><td>[0.45, 0.12, -0.33]</td></tr>
<tr>
<td>name</td><td>[0.67, 0.22, -0.15]</td></tr>
<tr>
<td>is</td><td>[-0.12, 0.55, 0.88]</td></tr>
<tr>
<td>Vikas</td><td>[0.80, -0.10, 0.25]</td></tr>
<tr>
<td>.</td><td>[0.05, 0.03, -0.07]</td></tr>
<tr>
<td>I</td><td>[-0.25, 0.40, 0.70]</td></tr>
<tr>
<td>love</td><td>[0.60, 0.75, -0.20]</td></tr>
<tr>
<td>cricket</td><td>[0.90, 0.15, -0.10]</td></tr>
<tr>
<td>,</td><td>[0.02, -0.01, 0.04]</td></tr>
<tr>
<td>finance</td><td>[0.85, -0.20, 0.30]</td></tr>
<tr>
<td>and</td><td>[0.10, 0.50, 0.40]</td></tr>
<tr>
<td>AI</td><td>[0.95, 0.12, 0.08]</td></tr>
</tbody>
</table>
</div><p>The final embedding matrix for processing is as follows</p>
<p>$$\text{Embedding Matrix} = \begin{bmatrix} 0.45 &amp; 0.12 &amp; -0.33 \\ 0.67 &amp; 0.22 &amp; -0.15 \\ -0.12 &amp; 0.55 &amp; 0.88 \\ 0.80 &amp; -0.10 &amp; 0.25 \\ 0.05 &amp; 0.03 &amp; -0.07 \\ -0.25 &amp; 0.40 &amp; 0.70 \\ 0.60 &amp; 0.75 &amp; -0.20 \\ 0.90 &amp; 0.15 &amp; -0.10 \\ 0.02 &amp; -0.01 &amp; 0.04 \\ 0.85 &amp; -0.20 &amp; 0.30 \\ 0.10 &amp; 0.50 &amp; 0.40 \\ 0.95 &amp; 0.12 &amp; 0.08 \end{bmatrix}$$</p><p>So the embedding matrix is of the order \(N \times D\), where \(N\) is the number of unique tokens and \(D\) is the dimension size.</p>
<p><strong>Transformers solve the limitation of sequential processing and long term dependency,</strong> by processing tokens in parallel and using the self-attention mechanism.</p>
<p>This however comes with a limitation, that they do not have positional information about the input sequence. This means that positional encodings , have to be added to the embedding vector to give the transformer the positional context of the token.</p>
<hr />
<h1 id="heading-positional-encoding">Positional Encoding</h1>
<p>There are many types of positional encodings , but for this example let us consider the fixed sinusoidal positional encoding.</p>
<p>For a sequence position \(pos\) and dimension \(i\) in the embedding vector:</p>
<p>$$PE(pos,2i) = \sin\left(\frac{pos}{10,000^{\frac{2i}{d}}} \right)$$</p><p>$$PE(pos,2i+1) = \cos\left(\frac{pos}{10,000^{\frac{2i}{d}}} \right)$$</p><p>where,</p>
<ul>
<li><p>\(pos\): The position of the token in the sequence (e.g., 0, 1, 2, …).</p>
</li>
<li><p>\(i\): The dimension index of the embedding vector (e.g., 0, 1, 2, …).</p>
</li>
<li><p>\(d\): The total dimension size of the embeddings (e.g., 512). In our case, \(d=3\).</p>
</li>
</ul>
<p><strong>The positional encodings are added by the operation</strong></p>
<p>$$\text{Embedding Matrix} + \text{Positional Encodings Matrix}$$</p><p>Therefore , positional encodings matrix should also be of dimension \(N \times D\).</p>
<p>For our embedding matrix , the positional encodings is computed as</p>
<p>$$\text{Input Matrix} = \begin{bmatrix} 0.4500 &amp; 1.1200 &amp; -0.3300 \\ 1.5115 &amp; 1.2199 &amp; -0.1500 \\ 0.7893 &amp; 1.5499 &amp; 0.8800 \\ 0.9411 &amp; 0.8999 &amp; 0.2500 \\ -0.7068 &amp; 1.0299 &amp; -0.0700 \\ -1.2089 &amp; 1.3999 &amp; 0.7000 \\ 0.3206 &amp; 1.7499 &amp; -0.2000 \\ 1.5569 &amp; 1.1498 &amp; -0.1000 \\ 1.0094 &amp; 0.9898 &amp; 0.0400 \\ 1.2621 &amp; 0.7998 &amp; 0.3000 \\ -0.4440 &amp; 1.4998 &amp; 0.4000 \\ -0.0499 &amp; 1.1197 &amp; 0.0800 \end{bmatrix}$$</p><p>On adding the two together, we obtain the following input matrix.</p>
<p>$$\text{Positional Encoding Matrix} = \begin{bmatrix} 0.0000 &amp; 1.0000 &amp; 0.0000 \\ 0.8415 &amp; 0.9999 &amp; 0.0000 \\ 0.9093 &amp; 0.9999 &amp; 0.0000 \\ 0.1411 &amp; 0.9999 &amp; 0.0000 \\ -0.7568 &amp; 0.9999 &amp; 0.0000 \\ -0.9589 &amp; 0.9999 &amp; 0.0000 \\ -0.2794 &amp; 0.9999 &amp; 0.0000 \\ 0.6569 &amp; 0.9998 &amp; 0.0000 \\ 0.9894 &amp; 0.9998 &amp; 0.0000 \\ 0.4121 &amp; 0.9998 &amp; 0.0000 \\ -0.5440 &amp; 0.9998 &amp; 0.0000 \\ -0.9999 &amp; 0.9997 &amp; 0.0000 \end{bmatrix}$$</p><hr />
<h3 id="heading-conclusion-laying-the-foundation-for-transformers"><strong>Conclusion: Laying the Foundation for Transformers</strong></h3>
<p>In this blog, we explored the <strong>first crucial steps</strong> in understanding how transformers work—<strong>tokenization, embeddings, and positional encoding</strong>. These processes transform raw text into a numerical format that a transformer can interpret, setting the stage for the <strong>self-attention mechanism</strong> to process and learn relationships within sequences.</p>
<p>By using <strong>word embeddings</strong>, transformers can represent words in a meaningful, high-dimensional space, capturing <strong>semantic similarities and contextual relationships</strong>. However, since transformers process tokens <strong>in parallel</strong>, they lack an inherent sense of order—this is why <strong>positional encodings</strong> are crucial in providing <strong>context about token positions</strong> within a sequence.</p>
<p>But how do transformers actually process these embeddings to <strong>understand and generate language</strong>? The key lies in <strong>Self-Attention</strong>, the core innovation behind transformers, which enables them to dynamically focus on different words in a sequence.</p>
<p>👉 <strong>In the next part of this series, we’ll dive deep into Self-Attention—breaking down how transformers determine relationships between tokens, compute attention scores, and generate context-rich representations. Stay tuned! 🚀</strong></p>
]]></content:encoded></item></channel></rss>