<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by hackice20 on Medium]]></title>
        <description><![CDATA[Stories by hackice20 on Medium]]></description>
        <link>https://medium.com/@yashkam431?source=rss-f284f529e9b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jQo_9YOoFfbGvNAY</url>
            <title>Stories by hackice20 on Medium</title>
            <link>https://medium.com/@yashkam431?source=rss-f284f529e9b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:53:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashkam431/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Journey of a Sentence Through a Transformer]]></title>
            <link>https://medium.com/@yashkam431/the-journey-of-a-sentence-through-a-transformer-434902aafb03?source=rss-f284f529e9b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/434902aafb03</guid>
            <category><![CDATA[transformer-architecture]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[transformer-model]]></category>
            <dc:creator><![CDATA[hackice20]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 15:14:29 GMT</pubDate>
            <atom:updated>2025-07-10T03:53:09.353Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine we’re going to follow a sentence on its incredible journey through the Transformer architecture. Our traveling companion will be the sentence:</p><blockquote><em>“The cat chases the mouse”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*73fZPV9wTsE6rtREVvU0Kg.png" /><figcaption>Transformer</figcaption></figure><h3>Part 1: Getting Ready for the Journey</h3><h3>Input Embedding : Giving Words Their Identity Cards</h3><p>Think of this first step like giving each word a special identity card. But instead of a photo and name, each word gets a long list of numbers (a vector of size 512 in the original paper). These numbers capture the essence of what the word means.</p><pre>&quot;cat&quot; → [0.2, -0.5, 0.8, ..., 0.3] (512 numbers)</pre><p>But wait! We need to make sure each word remembers its place in line. That’s where positional encoding comes in.</p><h3>Detailed Calculations</h3><h3>Input Embedding Calculation Example</h3><p>For our sentence “The cat chases the mouse”, let’s see a simplified embedding (using smaller vectors for clarity):</p><pre>Word embeddings (d_model = 8 instead of 512 for illustration):<br>&quot;The&quot;    → [ 0.2,  0.1, -0.3,  0.4,  0.2,  0.1, -0.1,  0.3]<br>&quot;cat&quot;    → [ 0.5, -0.2,  0.4, -0.1,  0.3,  0.2,  0.1, -0.2]<br>&quot;chases&quot; → [-0.3,  0.4,  0.2,  0.3, -0.2,  0.5,  0.2,  0.1]</pre><h3>Positional Encoding :Adding Timestamp Stamps</h3><p>Every word gets a special “timestamp” added to its identity card. The clever part? These timestamps are created using sine and cosine waves:</p><pre>PE(pos, 2i) = sin(pos / 10000^(2i/d_model))<br>PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))</pre><p>In plain English:</p><ul><li>pos: Which position is the word in? (0 for “The”, 1 for “cat”, etc.)</li><li>i: Which number in our 512-number list are we looking at?</li><li>The result: A unique pattern of numbers that tells us exactly where each word sits</li></ul><p>So now each word has:</p><ul><li>Its meaning numbers (embeddings)</li><li>Its position numbers (positional encoding) Added together like mixing two colors of paint!</li></ul><h3>Positional Encoding Calculation</h3><p>For position pos=1 (“cat”) and d_model=8:</p><pre>For even dimensions (i=0,2,...):<br>PE(1,0) = sin(1/10000^(0/8)) = sin(0.0001) = 0.0001<br>PE(1,2) = sin(1/10000^(2/8)) = sin(0.0016) = 0.0016</pre><pre>For odd dimensions (i=1,3,...):<br>PE(1,1) = cos(1/10000^(1/8)) = cos(0.0003) = 0.9999<br>PE(1,3) = cos(1/10000^(3/8)) = cos(0.0047) = 0.9999</pre><pre>Positional encoding for &quot;cat&quot; (pos=1):<br>[ 0.0001, 0.9999, 0.0016, 0.9999, 0.0251, 0.9997, 0.3962, 0.9182]</pre><pre>Final embedding = Word embedding + Positional encoding:<br>[ 0.5001, 0.7999, 0.4016, 0.8999, 0.3251, 1.1997, 0.4962, 0.7182]</pre><h3>Part 2: The Heart of the Journey :Self-Attention</h3><h3>The Cocktail Party Analogy with Math</h3><p>Imagine each word at a cocktail party. Each word needs to figure out who it should pay attention to. Here’s how it works:</p><p>Each word creates three versions of itself (through matrix multiplication):</p><ul><li>Query (Q): “What am I looking for?”</li><li>Key (K): “What can I offer?”</li><li>Value (V): “What information do I have?”</li></ul><p>Let’s see how “chases” decides who to pay attention to:</p><pre>Attention Score = (Q × K^T) / √d_k</pre><p>In party terms:</p><ul><li>“chases” (with its Query) looks around the room</li><li>Compares its Query with everyone’s Keys</li><li>Divides by √d_k (like turning down the music so people don’t shout)</li><li>Uses softmax (like ensuring you split 100% of your attention among people)</li><li>Finally multiplies by Values (collecting information from everyone, weighted by how much attention you paid them)</li></ul><h3>Self-Attention Calculations</h3><p>Let’s calculate attention for “chases” with actual numbers:</p><p>Creating Q, K, V matrices</p><pre>Original vector for &quot;chases&quot; (simplified to 4 dimensions):<br>x = [-0.3, 0.4, 0.2, 0.3]</pre><pre>Weight matrices (learned during training):<br>W_Q = [[ 0.1,  0.2],<br>       [-0.1,  0.1],<br>       [ 0.3,  0.2],<br>       [ 0.1, -0.1]]</pre><pre>W_K and W_V similar but with different values</pre><pre>Q = x × W_Q = [-0.3(0.1) + 0.4(-0.1) + 0.2(0.3) + 0.3(0.1),<br>                -0.3(0.2) + 0.4(0.1) + 0.2(0.2) + 0.3(-0.1)]<br>  = [0.02, 0.01]</pre><p>Calculating Attention Scores</p><pre>Q × K^T calculation for &quot;chases&quot; attending to &quot;cat&quot;:<br>Q = [0.02, 0.01]<br>K_cat = [0.03, 0.02]</pre><pre>Score = Q × K^T / √d_k<br>      = (0.02 × 0.03 + 0.01 × 0.02) / √2<br>      = 0.0008 / 1.4142<br>      = 0.00057</pre><pre>Do this for all words, then apply softmax:</pre><pre>Raw scores:<br>&quot;The&quot;:    0.00042<br>&quot;cat&quot;:    0.00057<br>&quot;chases&quot;: 0.00039<br>&quot;the&quot;:    0.00041<br>&quot;mouse&quot;:  0.00054</pre><pre>Softmax results:<br>&quot;The&quot;:    0.1<br>&quot;cat&quot;:    0.4<br>&quot;chases&quot;: 0.1<br>&quot;the&quot;:    0.1<br>&quot;mouse&quot;:  0.3</pre><p>Computing Final Values</p><pre>Weighted sum calculation:<br>Final = Σ(attention_weight × value)</pre><pre>For &quot;chases&quot;:<br>= 0.1 × V_the + 0.4 × V_cat + 0.1 × V_chases + 0.1 × V_the + 0.3 × V_mouse<br>= 0.1[-0.1, 0.2] + 0.4[0.3, 0.1] + 0.1[0.2, 0.3] + 0.1[-0.1, 0.2] + 0.3[0.2, 0.1]<br>= [-0.01, 0.02] + [0.12, 0.04] + [0.02, 0.03] + [-0.01, 0.02] + [0.06, 0.03]<br>= [0.18, 0.14]</pre><p>Real numbers might look like:</p><pre>&quot;chases&quot; paying attention:<br>&quot;The&quot;   → 10% attention<br>&quot;cat&quot;   → 40% attention (important! This is the subject)<br>&quot;chases&quot;→ 10% attention<br>&quot;the&quot;   → 10% attention<br>&quot;mouse&quot; → 30% attention (important! This is the object)</pre><h3>Multi-Head Attention :Multiple Conversation Topics</h3><p>But wait, there’s more! The Transformer doesn’t just have one conversation. It has 8 different conversations happening simultaneously (8 heads). Why?</p><p>Imagine each head is focusing on different aspects:</p><ul><li>Head 1 might focus on who’s doing the action</li><li>Head 2 might focus on what’s being done to whom</li><li>Head 3 might focus on grammar</li><li>And so on…</li></ul><p>The math stays the same, but it happens 8 times in parallel:</p><pre>MultiHead(Q, K, V) = Concat(head_1, ..., head_8)W^O</pre><h3>Part 3: Processing the Information</h3><h3>Feed-Forward Neural Network :Personal Reflection Time</h3><p>After all this socializing, each word goes to a quiet room to process what it learned. This is our feed-forward neural network:</p><pre>FFN(x) = max(0, xW_1 + b_1)W_2 + b_2</pre><p>In human terms:</p><ol><li>Take all the information gathered (x)</li><li>Transform it into a bigger space (× W_1 + b_1)</li><li>Keep only the positive stuff (max(0, …))</li><li>Transform it back to our normal size (× W_2 + b_2)</li></ol><h3>Layer Normalization &amp; Residual Connections :Staying Grounded</h3><p>To make sure our words don’t get too carried away:</p><ul><li>Layer normalization: Like making sure everyone’s speaking at the same volume</li><li>Residual connections: Like keeping your original thoughts while adding new ones</li></ul><h3>Feed-Forward Network Calculations</h3><p>Let’s calculate the feed-forward network output for our attention result:</p><pre>Input x = [0.18, 0.14]</pre><pre>First transformation (d_model → d_ff):<br>W_1 = [[ 0.1,  0.2,  0.3],<br>       [-0.1,  0.2,  0.1]]<br>b_1 = [0.1, 0.1, 0.1]</pre><pre>xW_1 + b_1 = [0.18(0.1) + 0.14(-0.1), <br>              0.18(0.2) + 0.14(0.2),<br>              0.18(0.3) + 0.14(0.1)] + [0.1, 0.1, 0.1]<br>           = [0.004, 0.064, 0.068] + [0.1, 0.1, 0.1]<br>           = [0.104, 0.164, 0.168]</pre><pre>After ReLU (max(0,x)):<br>[0.104, 0.164, 0.168]</pre><pre>Second transformation (d_ff → d_model):<br>W_2 = [[ 0.2,  0.1],<br>       [ 0.1,  0.3],<br>       [-0.1,  0.2]]<br>b_2 = [0.1, 0.1]</pre><pre>Final = ReLU(xW_1 + b_1)W_2 + b_2<br>      = [0.104(0.2) + 0.164(0.1) + 0.168(-0.1),<br>         0.104(0.1) + 0.164(0.3) + 0.168(0.2)] + [0.1, 0.1]<br>      = [0.0208 + 0.0164 - 0.0168,<br>         0.0104 + 0.0492 + 0.0336] + [0.1, 0.1]<br>      = [0.1204, 0.1932]</pre><h3>Layer Normalization Calculation</h3><pre><em>For output vector y = [0.1204, 0.1932]:</em><br>1. Calculate mean:<br>μ = (0.1204 + 0.1932)/2 = 0.1568</pre><pre>2. Calculate variance:<br>σ² = ((0.1204 - 0.1568)² + (0.1932 - 0.1568)²)/2<br>   = ((-0.0364)² + (0.0364)²)/2<br>   = 0.00132</pre><pre>3. Normalize:<br>ŷ = (y - μ)/√(σ² + ε)<br>  = [0.1204 - 0.1568, 0.1932 - 0.1568]/√(0.00132 + 1e-5)<br>  = [-0.0364, 0.0364]/0.0364<br>  = [-1, 1]</pre><pre>4. Scale and shift (learned parameters γ, β):<br>If γ = [1.2, 1.2] and β = [0.1, 0.1]:<br>output = γ * ŷ + β<br>       = [1.2 * -1 + 0.1, 1.2 * 1 + 0.1]<br>       = [-1.1, 1.3]</pre><h3>Part 4: The Full Journey</h3><p>This whole process happens 6 times! Each time through:</p><ol><li>Words attend to each other (Multi-Head Attention)</li><li>Process the information (Feed-Forward)</li><li>Normalize and add residual connections</li></ol><p>After all this, our sentence “The cat chases the mouse” has been deeply analyzed:</p><ul><li>“chases” knows its subject is “cat”</li><li>“mouse” knows it’s being chased</li><li>Each word understands its role in the whole sentence</li></ul><h3>The Mathematics Behind It All</h3><p>Even though we’ve explained this in a friendly way, the math is still doing heavy lifting:</p><p><strong>Attention Calculation</strong>:</p><pre>Attention(Q,K,V) = softmax(QK^T/√d_k)V</pre><ul><li>Q, K, V are matrices</li><li>√d_k keeps numbers from getting too big</li><li>softmax turns everything into percentages</li></ul><p><strong>Computational Complexity</strong>:</p><ul><li>O(n²·d) means: if your sentence doubles in length, the computation takes 4 times longer</li><li>But it’s all happening in parallel, unlike older models!</li></ul><h3>Training Details Learning Through Experience</h3><p>Let’s see exactly how the Transformer learns, using real numbers and calculations.</p><h3>The Loss Function Measuring Mistakes</h3><p>Imagine we’re training on a translation task:</p><ul><li>Input: “The cat chases the mouse”</li><li>Expected Output: “Le chat chasse la souris”</li></ul><p>The model makes predictions for each word, outputting probability distributions. Let’s look at a single word prediction:</p><pre>For translating &quot;cat&quot;, the model outputs probabilities:<br>chat: 0.7<br>chien: 0.2<br>cheval: 0.05<br>autres: 0.05<br><br>Correct answer: &quot;chat&quot;</pre><p>The cross-entropy loss is calculated as:</p><pre>Loss = -Σ(y_true * log(y_pred))<br><br>Where:<br>y_true = [1, 0, 0, 0] (one-hot encoding for &quot;chat&quot;)<br>y_pred = [0.7, 0.2, 0.05, 0.05] (model&#39;s predictions)<br><br>Loss = -(1 * log(0.7) + 0 * log(0.2) + 0 * log(0.05) + 0 * log(0.05))<br>     = -log(0.7)<br>     = 0.357</pre><h3>Label Smoothing Don&#39;t Be Too Confident</h3><p>The paper uses label smoothing with ε = 0.1. Instead of pure 1s and 0s, we use:</p><pre>y_true_smoothed = (1 - ε) * y_true + ε/K<br><br>Where:<br>K = number of classes<br>ε = 0.1<br><br>For our example:<br>y_true_smoothed = [0.925, 0.025, 0.025, 0.025]<br><br>New Loss = -(0.925 * log(0.7) + 0.025 * log(0.2) + 0.025 * log(0.05) + 0.025 * log(0.05))<br>        = 0.401</pre><h3>Optimization The Learning Process</h3><p>The Adam optimizer adjusts the model’s parameters using:</p><ul><li>β₁ = 0.9 (momentum)</li><li>β₂ = 0.98 (RMSprop factor)</li><li>ε = 10⁻⁹ (numerical stability)</li></ul><p>The learning rate follows a special schedule:</p><pre>lrate = d_model^(-0.5) * min(step_num^(-0.5), step_num * warmup_steps^(-1.5))<br><br>Example calculation for d_model = 512, warmup_steps = 4000:<br>At step 1000:<br>lrate = 512^(-0.5) * min(1000^(-0.5), 1000 * 4000^(-1.5))<br>     = 0.044 * min(0.0316, 0.0395)<br>     = 0.044 * 0.0316<br>     = 0.00139</pre><p>Let&#39;s see a complete parameter update for one weight w:</p><pre>Current weight w = 0.5<br>Gradient g = 0.1<br>Step t = 1000<br><br>1. Update biased moments:<br>m_t = β₁ * m_{t-1} + (1 - β₁) * g<br>    = 0.9 * 0.05 + 0.1 * 0.1<br>    = 0.055<br><br>v_t = β₂ * v_{t-1} + (1 - β₂) * g²<br>    = 0.98 * 0.03 + 0.02 * 0.01<br>    = 0.0294<br><br>2. Bias correction:<br>m̂_t = m_t / (1 - β₁^t)<br>    = 0.055 / (1 - 0.9^1000)<br>    ≈ 0.055<br><br>v̂_t = v_t / (1 - β₂^t)<br>    = 0.0294 / (1 - 0.98^1000)<br>    ≈ 0.0294<br><br>3. Parameter update:<br>w_new = w - lrate * m̂_t / (√v̂_t + ε)<br>      = 0.5 - 0.00139 * 0.055 / (√0.0294 + 10⁻⁹)<br>      = 0.5 - 0.00139 * 0.055 / 0.171<br>      = 0.5 - 0.00045<br>      = 0.49955</pre><h3>Putting It All Together One Training Step</h3><p>For our sentence &quot;The cat chases the mouse&quot;, one complete training step involves:</p><p>Forward pass through the model:</p><ul><li>Input embeddings + positional encodings</li><li>6 encoder layers with attention and feed-forward</li><li>Output probabilities for each target word</li></ul><p>Calculate loss using cross-entropy with label smoothing</p><ul><li>Sum losses for all words in the sequence</li><li>Apply label smoothing as shown above</li></ul><p>Backpropagate gradients:</p><ul><li>Compute gradients for all parameters</li><li>Scale gradients based on attention dimension (1/√d_k)</li></ul><p>Update parameters using Adam:</p><ul><li>Apply learning rate schedule</li><li>Update moments and parameters as shown above</li></ul><p>Track metrics:</p><ul><li>Training loss</li><li>Validation loss</li><li>BLEU score (for translation tasks)</li><li>Perplexity</li></ul><h3>Conclusion</h3><p>The beauty of the Transformer is how it combines intuitive ideas (paying attention to relevant words) with powerful mathematics. Each word:</p><ol><li>Gets its identity (embedding)</li><li>Remembers its position (positional encoding)</li><li>Has multiple conversations (multi-head attention)</li><li>Processes what it learned (feed-forward)</li><li>Stays grounded (normalization and residuals)</li></ol><p>And it does all this while maintaining mathematical rigor and computational efficiency!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=434902aafb03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>