<?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 Elsonccj on Medium]]></title>
        <description><![CDATA[Stories by Elsonccj on Medium]]></description>
        <link>https://medium.com/@elsonccj?source=rss-6b47723a0c29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3tl3lnLWuUXhk1Ne9s0XEA.jpeg</url>
            <title>Stories by Elsonccj on Medium</title>
            <link>https://medium.com/@elsonccj?source=rss-6b47723a0c29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:04:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elsonccj/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[Inside an LLM: What Actually Happens After You Send a Prompt?]]></title>
            <link>https://elsonccj.medium.com/inside-an-llm-what-actually-happens-after-you-send-a-prompt-1b56a4c6fc28?source=rss-6b47723a0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b56a4c6fc28</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Elsonccj]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 03:49:15 GMT</pubDate>
            <atom:updated>2026-08-23T12:38:52.361Z</atom:updated>
            <content:encoded><![CDATA[<p>Part II of my Transformer Series</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xzg_KaR2PHSNINk_9bFnxg.png" /></figure><h3><strong>1. Introduction</strong></h3><p>See the diagram above, a little scary isn’t it? I assure you that reading the entire article first will make the diagram less daunting. Let me walk you through it.</p><p>When we interact with an LLM, the experience feels almost trivial.</p><p>You type:</p><blockquote><em>“Explain how a car works.”</em></blockquote><p>You press Enter. A moment later, words begin appearing on the screen. But between those two events, an enormous amount of computation takes place.</p><h3><strong>2. What actually happens under the hood?</strong></h3><p>Your sentence is broken into tokens. Those tokens become numerical vectors. Every Transformer layer decides which previous tokens are relevant. Attention moves information between tokens. MLP (Multi-Layer Perceptron) blocks activate and transform learned features. Residual connections carry information through the network. This process repeats through dozens of layers.</p><p>Finally, the model produces a probability distribution over every token in its vocabulary and chooses what should come next. Then it repeats the entire process again and again.</p><p>In this article, we are going to follow that journey from beginning to end.</p><p>We will first look inside a typical decoder-style Transformer architecture used by most mainstream models today such as ChatGPT and Claude.</p><p>Once we understand that baseline, we will zoom out and look at the different ways modern models can be designed: encoder vs decoder, dense vs Mixture-of-Experts, autoregressive vs diffusion, and more.</p><p>Before we begin, refer to this amazing visual of the <a href="https://poloclub.github.io/transformer-explainer/"><strong><em>Transformer Explainer</em></strong></a> where you can interact and learn more about Transformers.</p><h3>3. Components of the Transformer</h3><h4>1. The Prompt</h4><p>Suppose we send the model a prompt:</p><blockquote><em>“The cat sat on the mat.”</em></blockquote><p>A Transformer does not actually understand letters or words directly.</p><p>The first step is therefore to convert the text into something that the neural network can process. In this case, embeddings.</p><p>This is the job of the <strong>Tokenizer</strong>. The tokenizer might break our sentence into tokens such as:</p><pre>&quot;The&quot;<br>&quot; cat&quot;<br>&quot; sat&quot;<br>&quot; on&quot;<br>&quot; the&quot;<br>&quot; mat&quot;<br>&quot;.&quot;</pre><p>Each token is then represented by an integer ID. Note that each token is not necessarily a complete word. For example, the word “Tokenizer” can be broken down into 3 tokens “Tok”, “eni” and “zer”, depending on the vocabulary of the model.</p><p>Conceptually:</p><pre>&quot;The&quot;  → 791<br>&quot;cat&quot;  → 8415<br>&quot;sat&quot;  → 7731</pre><p>These IDs are simply entries in the model’s vocabulary.</p><p>The neural network itself still cannot do much with the number 8415.</p><p>So the model performs another lookup.</p><h4>2. Token IDs Become Embeddings</h4><p>Every token ID corresponds to a learned vector called an <strong>embedding</strong>.</p><p>Suppose the model’s hidden size is 4096.</p><p>The token:</p><pre>&quot;cat&quot;</pre><p>might become a vector containing 4096 numbers:</p><pre>[0.17, -0.42, 0.81, 0.03, ...]</pre><p>We can represent this as:</p><pre>xₜ ∈ R⁴⁰⁹⁶ // Where x is vector of 4096 dimesions</pre><p>Those numbers do not correspond to simple human-readable meanings such as:</p><pre>dimension 1 = animal<br>dimension 2 = noun<br>dimension 3 = furry</pre><p>Instead, meaning is distributed across many dimensions.</p><p>This embedding becomes the model’s initial numerical representation of the token.</p><p>From here onward, we will often call the current representation of a token its <strong>hidden state</strong>.</p><h4>3. Hidden State</h4><p>A hidden state is simply:</p><blockquote><strong><em>The model’s current numerical representation of a token at a particular point in the neural network.</em></strong></blockquote><p>At the beginning, hidden state is represented as:</p><pre>h⁰</pre><p>This hidden state is mostly based on the token embedding and positional information.</p><p>After Transformer Layer 1:</p><pre>h¹</pre><p>contains additional contextual information.</p><p>After Layer 2:</p><pre>h²</pre><p>contains even more transformed information.</p><p>And so on:</p><pre>Embedding<br>   ↓<br>h⁰<br>   ↓<br>Layer 1<br>   ↓<br>h¹<br>   ↓<br>Layer 2<br>   ↓<br>h²<br>   ↓<br>Layer 3<br>   ↓<br>h³<br>   ↓<br>...</pre><p>This is important because the token &quot;bank&quot; does not maintain exactly the same representation throughout the model.</p><p>Consider:</p><blockquote><em>“I withdrew money from the bank.”</em></blockquote><p>and:</p><blockquote><em>“We sat beside the river bank.”</em></blockquote><p>The initial embedding for &quot;bank&quot; may be similar in both cases. But after several Transformer layers, the hidden states can become very different because attention incorporates the surrounding context. The hidden state is therefore constantly evolving.</p><h4>4. The Residual Stream: The Model’s Information Highway</h4><p>Before diving into attention, it helps to understand one structure that runs through almost the entire Transformer:</p><p>the <strong>residual stream</strong>.</p><p>I like to think of it as an information highway. The token’s hidden state travels down this highway. Attention reads from it and writes information back. The MLP reads from it and writes information back.</p><p>Then the updated representation travels into the next Transformer layer.</p><p>Conceptually:</p><pre>Residual Stream<br>      │<br>      ├──── Attention<br>      │        │<br>      │        ↓<br>      └────── + ─────→ Updated Stream<br>                         │<br>                         ├──── MLP<br>                         │      │<br>                         │      ↓<br>                         └───── + ─────→ Next Layer</pre><p>Notice something important.</p><p>Attention does not normally replace the original hidden state.</p><p>Instead:</p><pre>new_state = old_state + attention_update</pre><p>Then the MLP does the same:</p><pre>next_state = new_state + mlp_update</pre><p>That + is called a <strong>residual connection</strong>.</p><p>This allows information from earlier layers to continue flowing forward rather than being completely overwritten.</p><p>It also makes extremely deep neural networks much easier to train.</p><h4>5. The Attention Block</h4><p>Now suppose we are processing token 3:</p><blockquote><em>&quot;sat&quot;</em></blockquote><p>It enters a Transformer layer with a hidden state:</p><pre>h₃</pre><p>In architectures such as Llama and Qwen, the model typically normalizes this representation first using something such as <strong>RMSNorm</strong>.</p><p>Conceptually:</p><pre>h₃<br> ↓<br>RMSNorm<br> ↓<br>x₃</pre><p>The normalized representation is then sent into the attention mechanism.</p><p>This is where we encounter:</p><ul><li>Query</li><li>Key</li><li>Value</li></ul><h4>6. Q, K and V</h4><p>The layer contains learned weight matrices:</p><pre>WQ<br>WK<br>WV</pre><p>These were learned during model training or pretraining.</p><p>The token’s hidden state is multiplied by these matrices:</p><pre>Q = x × WQ<br>K = x × WK<br>V = x × WV</pre><p>For token 3:</p><pre>Q₃ = x₃ × WQ<br>K₃ = x₃ × WK<br>V₃ = x₃ × WV</pre><p>So the same hidden state is transformed into three different representations.</p><p>A useful mental model is:</p><h4>Query</h4><blockquote><em>“What information am I looking for?”</em></blockquote><h4>Key</h4><blockquote><em>“What kind of information do I contain that another token might look for?”</em></blockquote><h4>Value</h4><blockquote><em>“What information should I provide if another token attends to me?”</em></blockquote><p>The easiest phrase to remember is: <strong><em>Q asks. K matches. V provides.</em></strong></p><h4>How Does the Model Decide Which Tokens Matter?</h4><p>Suppose token 3 is currently being processed.</p><p>It has:</p><pre>Q₃</pre><p>Previous tokens have keys:</p><pre>K₁<br>K₂</pre><p>and token 3 also has:</p><pre>K₃</pre><p>The model compares the query of token 3 against every available key.</p><p>Conceptually:</p><pre>Q₃ · K₁<br>Q₃ · K₂<br>Q₃ · K₃</pre><p>This is a dot product.</p><p>In matrix notation:</p><pre>QKᵀ</pre><p>The result is a set of raw <strong>attention scores</strong>.</p><p>For example:</p><pre>Token 1 → 0.5<br>Token 2 → 2.7<br>Token 3 → 1.1</pre><p>At this point, token 2 appears to be the strongest match.</p><p>But these values are not yet normalized probabilities.</p><h4>Why Do We Divide by √dₖ?</h4><p>Scaled dot-product attention uses:</p><pre>QKᵀ / √dₖ</pre><p>where:</p><pre>dₖ</pre><p>is the dimensionality of the Query and Key vectors for that head.</p><p>Why?</p><p>As vector dimensionality increases, dot products can become very large. Very large attention scores can cause softmax to become extremely sharp:</p><pre>[0.00001, 0.99998, 0.00001]</pre><p>That can make training unstable.</p><p>Dividing by:</p><pre>√dₖ</pre><p>keeps the values within a more manageable numerical range.</p><p>This is why the mechanism is called: <strong><em>Scaled dot-product attention</em></strong></p><h4>7. The Causal Mask</h4><p>Decoder-style LLMs are designed to generate text from left to right. That means a token must not be allowed to look into the future. Suppose we have four tokens.</p><p>Without masking:</p><pre>Keys<br>          1  2  3  4</pre><pre>Query 1   ✓  ✓  ✓  ✓<br>Query 2   ✓  ✓  ✓  ✓<br>Query 3   ✓  ✓  ✓  ✓<br>Query 4   ✓  ✓  ✓  ✓</pre><p>Every token could see every other token.</p><p>For a decoder model, we instead want:</p><pre>             Keys<br>          1  2  3  4</pre><pre>Query 1   ✓  ✕  ✕  ✕<br>Query 2   ✓  ✓  ✕  ✕<br>Query 3   ✓  ✓  ✓  ✕<br>Query 4   ✓  ✓  ✓  ✓</pre><p>Token 3 may therefore attend to:</p><pre>1, 2, 3</pre><p>but not:</p><pre>4</pre><p>Future positions are masked by assigning them a value conceptually equivalent to:</p><pre>−∞</pre><p>before softmax.</p><p>Why −∞?</p><p>Because:</p><pre>e^(−∞) = 0</pre><p>Therefore the future token receives zero attention probability after softmax.</p><h4>8. Softmax</h4><p>Softmax turns Scores Into Attention Weights. Suppose the scaled attention scores for token 3 are:</p><pre>[0.1, 1.7, 1.2]</pre><p>The model applies <strong>softmax</strong>.</p><p>Softmax is:</p><pre>softmax(zᵢ) = e^(zᵢ) / Σ e^(zⱼ)</pre><p>Its job is to turn arbitrary scores into positive weights that sum to 1.</p><p>Our example might become:</p><pre>[0.11, 0.55, 0.34]</pre><p>which means:</p><pre>Token 1 → 11%<br>Token 2 → 55%<br>Token 3 → 34%</pre><p>So for this particular attention head, token 3 is paying the most attention to token 2.</p><p>This does not necessarily mean token 2 is “semantically similar.” Different heads can learn very different kinds of relationships. One may react strongly to grammatical structure. Another may identify long-distance dependencies. Another may respond to formatting. Another may track positional relationships.</p><h4>QK Tells Us Where to Look. V Tells Us What to Take.</h4><p>We now have attention weights:</p><pre>[0.11, 0.55, 0.34]</pre><p>The model applies those weights to the corresponding Value vectors:</p><pre>0.11 × V₁<br>+<br>0.55 × V₂<br>+<br>0.34 × V₃</pre><p>The result becomes the attention output for token 3.</p><p>This is the core Transformer attention equation:</p><pre>Attention(Q, K, V)<br>=<br>softmax(QKᵀ / √dₖ) × V</pre><p>If causal masking is needed:</p><pre>Attention(Q, K, V)<br>=<br>softmax((QKᵀ / √dₖ) + mask) × V</pre><h4>9. Attention Heads</h4><p>A Transformer generally does not calculate attention only once. It calculates several attention operations in parallel.</p><p>These are called <strong>attention heads</strong>.</p><p>Suppose a layer has 32 heads:</p><pre>                 Hidden State<br>                       │<br>       ┌───────────────┼───────────────┐<br>       │               │               │<br>       ↓               ↓               ↓<br>     Head 1          Head 2         ... Head 32<br>       │               │               │<br>       ↓               ↓               ↓<br>   Attention       Attention         Attention<br>       │               │               │<br>       ↓               ↓               ↓<br>    Output          Output           Output</pre><p>Each head operates in its own learned representation space.</p><p>That means the attention pattern in Head 1 could be:</p><pre>[0.1, 0.8, 0.1]</pre><p>while Head 2 could produce:</p><pre>[0.6, 0.1, 0.3]</pre><p>The model is effectively examining the same sequence from several different perspectives simultaneously.</p><h4>Concatenating the Attention Heads</h4><p>Each head produces its own vector. Suppose we have 32 heads and each head produces 128 dimensions.</p><p>Then:</p><pre>32 × 128 = 4096</pre><p>The model concatenates them:</p><pre>Head 1 | Head 2 | Head 3 | ... | Head 32</pre><p>giving one combined vector.</p><p>But at this point, the head outputs are effectively sitting side by side. The model therefore performs another learned transformation. This is the <strong>output projection</strong>.</p><h4>The Output Projection: Wₒ</h4><p>The attention layer contains another learned weight matrix:</p><pre>WO</pre><p>which the concatenated multi-head representation is multiplied by</p><p><strong>Conceptually</strong>:</p><pre>32 attention head outputs<br>          ↓<br>     concatenate<br>          ↓<br>         WO<br>          ↓<br>combined attention update</pre><p>If the hidden size is 4096, WO commonly maps:</p><pre>4096 → 4096</pre><p>Its job is not simply dimensionality reduction.</p><p>It learns how information produced by the different attention heads should be mixed back together.</p><p>So:</p><pre>Q, K and V</pre><p>determine the individual attention operations.</p><p>And:</p><pre>WO</pre><p>determines how their results are recombined.</p><h4>Attention Writes Back Into the Residual Stream</h4><p>The attention block has now produced an output:</p><pre>attention_update</pre><p>Instead of replacing the token’s original representation, the model adds it back:</p><pre>new_hidden_state<br>=<br>old_hidden_state<br>+<br>attention_update</pre><p>Conceptually:</p><pre>h ─────────────────────────┐<br>                           │<br>h → Attention → WO ─────── + → updated h</pre><p>This is our first major residual connection.</p><p>The attention block has effectively said:</p><blockquote><em>“Keep what you already knew, but add this contextual information I just gathered.”</em></blockquote><p>The updated representation now enters the next major component.</p><p>The <strong>MLP</strong>.</p><h4>10. The MLP</h4><p>Many simple Transformer explanations say:</p><blockquote><em>“After attention, the token passes through a feed-forward neural network (FFN).”</em></blockquote><p>That is technically correct, but it hides a lot of interesting machinery. The FFN is therefore also known as the MLP.</p><p>Modern LLMs such as Llama and Qwen commonly use a <strong>gated MLP</strong> containing three important projections:</p><pre>up_proj<br>gate_proj<br>down_proj</pre><p>The MLP does not directly communicate between different token positions. Attention does that. Instead, the MLP processes each token’s current representation independently.</p><p>A useful distinction is:</p><ul><li><strong><em>Attention moves information between tokens.</em></strong></li><li><strong><em>MLP transforms information inside each token representation.</em></strong></li></ul><h4>Why Does the MLP Expand the Hidden State?</h4><p>Suppose our residual stream has:</p><pre>4096 dimensions</pre><p>The MLP may temporarily expand this into something much larger:</p><pre>4096 → 11008</pre><p>Why?</p><p>One useful intuition is that this creates a much larger internal feature space.</p><p>The residual stream may contain 4096 dimensions, but the MLP temporarily opens a much larger workspace in which many different learned features can potentially activate.</p><p>This starts with the <strong>up projection</strong>.</p><h4>Up Projection</h4><p>The model calculates:</p><pre>u = x × Wup</pre><p>If:</p><pre>x = 4096 dimensions</pre><p>then:</p><pre>u = 11008 dimensions</pre><p>for example.</p><p>Conceptually:</p><pre>Residual representation<br>       4096<br>         ↓<br>      up_proj<br>         ↓<br>       11008</pre><p>You can think of up_proj as generating a large set of candidate features. Perhaps some are useful for syntax. Some for factual associations. Some for programming structures. Some for patterns we do not have simple human descriptions for.</p><p>The important point is that many potential features become available.</p><h4>Gate Projection</h4><p>At the same time, the model calculates another projection:</p><pre>g = x × Wgate</pre><p>This also expands into the intermediate dimension.</p><p>So the MLP now has two parallel branches:</p><pre>x<br>                 │<br>        ┌────────┴────────┐<br>        │                 │<br>        ↓                 ↓<br>     up_proj          gate_proj<br>        │                 │<br>        ↓                 ↓<br>        u                 g</pre><p>But the gate branch has a different job.</p><p>Instead of primarily representing candidate information, it helps determine:</p><blockquote><strong><em>Which features should be active for this particular token and context?</em></strong></blockquote><p>An activation function is applied to this gate. For many modern LLMs, that activation is <strong>SiLU</strong>.</p><h4>First, What is LU?</h4><p>LU stands for <strong><em>Linear Unit. </em></strong>GLU stands for<strong><em> Gated Linear Unit.</em></strong></p><p>The key idea is to create two representations. One carries information. The other controls a gate.</p><p>Conceptually:</p><pre>feature_branch × gate_branch</pre><p>A simplified GLU might look like:</p><pre>GLU(x)<br>=<br>(x × Wa)<br>×<br>sigmoid(x × Wb)</pre><p>The multiplication is element by element.</p><p>Suppose one candidate feature has value:</p><pre>5.0</pre><p>and the gate says:</p><pre>0.05</pre><p>Then:</p><pre>5.0 × 0.05 = 0.25</pre><p>That feature is strongly suppressed.</p><p>If another feature has:</p><pre>3.0</pre><p>and the gate gives:</p><pre>0.9</pre><p>then:</p><pre>3.0 × 0.9 = 2.7</pre><p>That feature passes through strongly.</p><p>This allows the network to dynamically control which features matter.</p><h4>What Is SiLU?</h4><p>SiLU stands for:</p><blockquote><strong><em>Sigmoid Linear Unit</em></strong></blockquote><p>It is defined as:</p><pre>SiLU(x) = x × sigmoid(x)</pre><p>where:</p><pre>sigmoid(x) = 1 / (1 + e^(−x))</pre><p>Why use an activation function at all?</p><p>Because if every neural-network operation were simply matrix multiplication, stacking many layers would still collapse into something equivalent to one large linear transformation.</p><p>Activation functions introduce <strong>non-linearity</strong>.</p><p>That is what allows neural networks to represent complex relationships.</p><h4>ReLU, GELU and SiLU</h4><p>Several activation functions have been popular in neural networks.</p><h4>ReLU</h4><p>ReLU is:</p><pre>ReLU(x) = max(0, x)</pre><p>If:</p><pre>x = −3</pre><p>then:</p><pre>ReLU(x) = 0</pre><p>If:</p><pre>x = 5</pre><p>then:</p><pre>ReLU(x) = 5</pre><p>It is extremely simple and historically very successful.</p><h4>GELU</h4><p>GELU stands for:</p><blockquote><strong><em>Gaussian Error Linear Unit</em></strong></blockquote><p>Unlike ReLU, which abruptly removes negative values, GELU suppresses them more smoothly.</p><p>GELU became particularly common in architectures such as BERT and earlier GPT-style Transformers.</p><h4>SiLU / Swish</h4><p>SiLU is smoother again:</p><pre>SiLU(x) = x × sigmoid(x)</pre><p>Large positive values mostly pass through.</p><p>Negative values can still contribute slightly instead of being instantly set to zero. Many modern LLM architectures use SiLU as part of a gated structure.</p><p>That leads us to: <strong>SwiGLU.</strong></p><h4>What Is SwiGLU?</h4><p>SwiGLU combines the gating idea with the SiLU/Swish activation.</p><p>A common form is:</p><pre>SwiGLU(x)<br>=<br>SiLU(x × Wgate)<br>×<br>(x × Wup)</pre><p>Then the full MLP becomes:</p><pre>MLP(x)<br>=<br>Wdown[<br>    SiLU(x × Wgate)<br>    ×<br>    (x × Wup)<br>]</pre><p>Conceptually:</p><pre>                    x<br>                    │<br>          ┌─────────┴─────────┐<br>          │                   │<br>          ↓                   ↓<br>       up_proj            gate_proj<br>          │                   │<br>          ↓                   ↓<br>          u                 SiLU(g)<br>          │                   │<br>          └──────── × ─────────┘<br>                    │<br>                    ↓<br>               gated features<br>                    │<br>                    ↓<br>                down_proj</pre><p>This gated structure is commonly used in modern decoder LLMs.</p><h4>What Is the Gate Really Doing?</h4><p>Suppose up_proj produces:</p><pre>Feature A = 4.5<br>Feature B = 2.1<br>Feature C = 7.3</pre><p>The gate might produce effective activation values such as:</p><pre>Feature A gate = 0.05<br>Feature B gate = 0.80<br>Feature C gate = 0.20</pre><p>After element-wise multiplication:</p><pre>Feature A = 4.5 × 0.05 = 0.225<br>Feature B = 2.1 × 0.80 = 1.68<br>Feature C = 7.3 × 0.20 = 1.46</pre><p>So even though Feature C originally had the largest value, Feature B becomes the strongest after gating.</p><p>A useful mental model is:</p><ul><li><strong><em>up_proj asks: Which features could be expressed?</em></strong></li><li><strong><em>gate_proj asks: Which of those features should matter right now?</em></strong></li></ul><h4>The Down Projection</h4><p>After gating, the model still has its large intermediate representation.</p><p>For example:</p><pre>11008 dimensions</pre><p>But the residual stream expects:</p><pre>4096 dimensions</pre><p>So the MLP applies:</p><pre>down_proj</pre><p>Conceptually:</p><pre>11008<br>   ↓<br>down_proj<br>   ↓<br>4096</pre><p>Mathematically:</p><pre>output = gated_features × Wdown</pre><p>The complete modern gated MLP therefore looks roughly like:</p><pre>x<br>│<br>├── up_proj ──────────────────┐<br>│                             │<br>└── gate_proj → SiLU ─────────×<br>                              │<br>                              ↓<br>                         down_proj<br>                              │<br>                              ↓<br>                         MLP output</pre><h4>The MLP Also Writes to the Residual Stream</h4><p>The MLP output is another update.</p><p>So:</p><pre>next_hidden_state<br>=<br>current_hidden_state<br>+<br>MLP_output</pre><p>That is essentially the core computational unit repeated throughout many modern Transformer LLMs.</p><h3>4. Why Repeat This Through So Many Layers?</h3><p>A model may contain:</p><pre>28 layers<br>32 layers<br>60 layers<br>80 layers<br>100+ layers</pre><p>Why repeat attention and MLP processing again and again?</p><p>Because every Transformer layer contains its <strong>own learned weights</strong>.</p><p>Layer 1 has:</p><pre>WQ¹<br>WK¹<br>WV¹<br>WO¹<br>Wup¹<br>Wgate¹<br>Wdown¹</pre><p>Layer 2 has:</p><pre>WQ²<br>WK²<br>WV²<br>WO²<br>Wup²<br>Wgate²<br>Wdown²</pre><p>These are not the same parameters. Furthermore, Layer 2 is not receiving the original token embedding. It receives the representation already modified by Layer 1.</p><p>So:</p><pre>Embedding<br>   ↓<br>Layer 1<br>   ↓<br>h¹<br>   ↓<br>Layer 2<br>   ↓<br>h²<br>   ↓<br>Layer 3<br>   ↓<br>h³<br>   ↓<br>...</pre><p>Every layer works with an increasingly transformed representation.</p><p>This allows the network to progressively build more complex features and relationships.</p><h4>QKV Is Recalculated at Every Layer</h4><p>This is an important point.</p><p>A token does not have one permanent Q, K and V.</p><p>At Layer 1:</p><pre>Q₃¹ = h₃⁰ × WQ¹<br>K₃¹ = h₃⁰ × WK¹<br>V₃¹ = h₃⁰ × WV¹</pre><p>After Layer 1, token 3 has a new hidden state:</p><pre>h₃¹</pre><p>Layer 2 then calculates:</p><pre>Q₃² = h₃¹ × WQ²<br>K₃² = h₃¹ × WK²<br>V₃² = h₃¹ × WV²</pre><p>Two things changed:</p><ol><li>The token’s hidden state changed.</li><li>The layer’s QKV weights changed.</li></ol><p>Therefore Layer 2 can produce completely different attention relationships from Layer 1. Each layer operates in its own learned representation space.</p><h4>Prefill: What Happens When Your Prompt First Enters?</h4><p>Suppose your complete prompt contains 1,000 tokens.</p><p>During the <strong>prefill phase</strong>, the model processes those prompt tokens through all Transformer layers. Importantly, modern GPUs can calculate many token positions in parallel.</p><p>At a particular layer, we can represent all hidden states as a matrix:</p><pre>H</pre><p>Then the model calculates:</p><pre>Q = H × WQ<br>K = H × WK<br>V = H × WV</pre><p>for all prompt positions.</p><p>The attention matrix becomes:</p><pre>QKᵀ</pre><p>The causal mask ensures that even though these calculations happen in parallel, token 100 cannot look at token 101.</p><p>So computationally the GPU can process many positions together.</p><p>Logically the model still respects:</p><pre>Token 1 sees: 1</pre><pre>Token 2 sees: 1, 2</pre><pre>Token 3 sees: 1, 2, 3</pre><pre>...</pre><pre>Token 1000 sees: 1 ... 1000</pre><h4>The KV Cache</h4><p>Remember the QKV we talked about earlier? While performing prefill, the model stores the Keys and Values produced by every prompt token at every Transformer layer.</p><p>This storage is called the:</p><blockquote><strong><em>KV cache</em></strong></blockquote><p>For example:</p><pre>Layer 1:<br>K₁ K₂ K₃ ... K₁₀₀₀<br>V₁ V₂ V₃ ... V₁₀₀₀</pre><pre>Layer 2:<br>K₁ K₂ K₃ ... K₁₀₀₀<br>V₁ V₂ V₃ ... V₁₀₀₀</pre><pre>...</pre><pre>Layer N:<br>K₁ K₂ K₃ ... K₁₀₀₀<br>V₁ V₂ V₃ ... V₁₀₀₀</pre><p>Remember:</p><p>Every layer has its <strong>own</strong> KV cache. Layer 10 does not reuse Layer 9’s Keys and Values. The KV cache can grow up to become quite significant.</p><h4>Why Cache K and V?</h4><p>Now suppose the model generates a new token:</p><pre>Token 1001</pre><p>It needs to know:</p><blockquote><em>Which previous tokens are useful to me?</em></blockquote><p>So it generates:</p><pre>Q₁₀₀₁</pre><p>and compares it with:</p><pre>K₁<br>K₂<br>K₃<br>...<br>K₁₀₀₀<br>K₁₀₀₁</pre><p>Once relevant tokens are identified, it retrieves information from:</p><pre>V₁<br>V₂<br>V₃<br>...<br>V₁₀₀₀<br>V₁₀₀₁</pre><p>Without a KV cache, the model would have to recompute the Keys and Values of the previous 1,000 tokens every time it generated another token.</p><p>That would be extremely wasteful.</p><p>Instead, it remembers them, so that it does not recompute them.</p><h4>Why Don’t We Cache Q?</h4><p>Because previous Queries are generally no longer required.</p><p>When token 500 was processed:</p><pre>Q₅₀₀</pre><p>was used to answer:</p><blockquote><em>“What should token 500 attend to?”</em></blockquote><p>Once that calculation is finished, future tokens do not care what token 500 was asking.</p><h4>Decode: Generating Tokens One at a Time</h4><p>After prefill is completed, the model enters the <strong>decode phase</strong>.</p><p>Suppose the prompt is:</p><blockquote><em>“The capital of France is”</em></blockquote><p>The KV cache already contains all prompt tokens.</p><p>The model predicts:</p><blockquote><em>Paris</em></blockquote><p>Now only that newly generated token needs to move through the Transformer.</p><p>At Layer 1 it calculates:</p><pre>QParis<br>KParis<br>VParis</pre><p>QParis attends against the existing cached Keys.</p><p>Then:</p><pre>KParis<br>VParis</pre><p>are appended to the Layer 1 cache. The token continues through Layer 2, Layer 3, and so on. After reaching the final layer, the model predicts another token.</p><p>Then another.</p><p>So inference looks like:</p><pre>Prompt<br>   ↓<br>Prefill<br>   ↓<br>Build KV cache<br>   ↓<br>Generate Token 1<br>   ↓<br>Append its KV<br>   ↓<br>Generate Token 2<br>   ↓<br>Append its KV<br>   ↓<br>Generate Token 3<br>   ↓<br>...</pre><p>This is why autoregressive generation is inherently sequential. The next generated token depends on what has already been generated.</p><h3>5. Finally: Turning the Hidden State Into the Next Token</h3><p>After the final Transformer layer, the newest token has a final hidden-state vector.</p><p>For example:</p><pre>4096 dimensions</pre><p>This is not yet a word.</p><p>The model first applies a final normalization.</p><p>Then it passes the hidden state into the <strong>language-model head</strong>, usually called the: <strong><em>LM head</em></strong></p><p>The LM head projects the hidden dimension into the model’s vocabulary size.</p><p>Suppose:</p><pre>Hidden size = 4096</pre><pre>Vocabulary size = 150,000</pre><p>The transformation is:</p><pre>4096<br>  ↓<br>LM Head<br>  ↓<br>150,000 logits</pre><p>There is now one number for every possible token in the vocabulary.</p><p>For example:</p><pre>&quot;Paris&quot;      14.2<br>&quot;London&quot;      8.1<br>&quot;France&quot;      6.4<br>&quot;Berlin&quot;      5.9<br>...</pre><p>These numbers are called <strong>logits</strong>.</p><p>They are not probabilities yet.</p><h4>From Logits to Probabilities</h4><p>Softmax can once again be used to convert logits into probabilities.</p><p>For example:</p><pre>Paris      → 0.91<br>London     → 0.03<br>France     → 0.02<br>Berlin     → 0.01<br>...</pre><p>The model or inference engine then chooses the next token according to its decoding strategy.</p><p>It might simply choose the highest-probability token.</p><p>Or it might use techniques such as:</p><ul><li>Temperature</li><li>Top-k sampling</li><li>Top-p sampling</li></ul><p>The selected token is appended to the sequence. Then the decode process repeats.</p><h3>6. What “Model Types” are there?</h3><p>Now that we understand the basic internal machinery of a Transformer LLM, we can look at the broader model landscape.</p><p>This is where terminology often becomes confusing.</p><p>You may hear statements such as:</p><ul><li><em>“Llama is decoder-only.”</em></li><li><em>“DeepSeek is an MoE.”</em></li><li><em>“This is a diffusion model.”</em></li></ul><p>At first, these can sound like competing categories.</p><p>BUT they are not.</p><p>They describe <strong>different dimensions of model design</strong>.</p><p>A single model could simultaneously be:</p><ul><li>Decoder-only</li><li>Transformer-based</li><li>Mixture-of-Experts</li><li>Autoregressive</li></ul><p>These properties answer different questions.</p><h4>Encoder, Decoder and Encoder–Decoder Models</h4><p>The original Transformer architecture had two major halves:</p><pre>Encoder → Decoder</pre><p>Modern models may use both or only one.</p><h4>1. Encoder-only</h4><p>An encoder is designed primarily to understand or represent an existing sequence.</p><p>Every token can generally attend to every other token.</p><p>Suppose the sentence is:</p><blockquote><em>“We sat beside the river bank.”</em></blockquote><p>When processing &quot;bank&quot;, an encoder can directly look at:</p><blockquote><em>&quot;river&quot;</em></blockquote><p>even though &quot;river&quot; appears later in the sequence.</p><p>This is called <strong>bidirectional attention</strong>.</p><p>Encoder models are useful for tasks such as:</p><ul><li>Text classification</li><li>Sentiment analysis</li><li>Embeddings</li><li>Semantic search</li><li>and more</li></ul><p>A classic example is BERT.</p><p>A useful mental model is:</p><blockquote><strong><em>Encoder = understand the input.</em></strong></blockquote><h4>2. Decoder-only</h4><p>A decoder-only model is designed around predicting what comes next.</p><p>Its fundamental objective is:</p><pre>P(next token | previous tokens)</pre><p>For example:</p><pre>&quot;The capital of France is&quot;<br>               ↓<br>             Paris</pre><p>Then:</p><pre>&quot;The capital of France is Paris&quot;<br>               ↓<br>             next token</pre><p>These models use causal attention because future output tokens do not yet exist. This is the architecture we have spent most of this article examining.</p><p>A useful mental model is:</p><blockquote><strong><em>Decoder = continue the sequence.</em></strong></blockquote><h4>3. Encoder–Decoder</h4><p>Encoder–decoder models contain both components.</p><p>The encoder processes the input. The decoder generates the output.</p><p>For example:</p><pre>English sentence<br>       ↓<br>    Encoder<br>       ↓<br>Encoded representation<br>       ↓<br>    Decoder<br>       ↓<br>Chinese sentence</pre><p>The decoder can use <strong>cross-attention</strong> to inspect encoder representations while generating.</p><p>In cross-attention:</p><pre>Q comes from the decoder.</pre><pre>K and V come from the encoder.</pre><p>This allows the decoder to ask:</p><blockquote><em>“Which part of the original input is relevant to what I am generating?”</em></blockquote><p>A useful mental model is:</p><blockquote><strong><em>Encoder–decoder = understand one sequence and generate another.</em></strong></blockquote><h4><strong>So why don’t we use the best of both worlds?</strong></h4><p>For general-purpose conversational LLMs, decoder-only architectures are usually sufficient because the model can already attend to the entire user prompt when generating its response. A separate bidirectional encoder may improve representations for some tasks, but the additional architecture and compute often don’t provide enough benefit to justify the trade-off at very large scale.</p><h4>4. Dense Models</h4><p>Now we move to a different design dimension.</p><p>A model can be:</p><pre>Dense</pre><p>or:</p><pre>Mixture-of-Experts</pre><p>In a dense model, every token generally passes through the same set of layer parameters.</p><p>For the MLP:</p><pre>Token<br>  ↓<br>up_proj<br>gate_proj<br>down_proj<br>  ↓<br>output</pre><p>Every token uses that same MLP.</p><p>If a dense model contains billions of parameters, a large portion of those relevant parameters is involved in processing every token.</p><p>Dense architectures are straightforward and predictable. But as models become larger, this becomes computationally expensive.</p><p>That motivated another approach.</p><h4>5. Mixture-of-Experts</h4><p>Mixture-of-Experts, or <strong>MoE</strong>, introduces multiple specialist MLPs called <strong>experts</strong>.</p><p>Instead of:</p><pre>Token<br>  ↓<br>One MLP</pre><p>we have:</p><pre>Expert 1<br>                 /<br>Token → Router → Expert 2<br>                 \<br>                  Expert 3<br>                  ...<br>                  Expert 64</pre><p>A small routing network looks at the token’s hidden state and chooses which experts should process it.</p><p>For example:</p><pre>Expert 7  → 0.65<br>Expert 23 → 0.35</pre><p>The resulting output might be conceptually:</p><pre>0.65 × Expert7(x)<br>+<br>0.35 × Expert23(x)</pre><p>Only a small subset of experts may activate for each token.</p><p>This means a model can have an enormous total number of parameters while using only a fraction of them during any one token computation.</p><p>That is the key idea behind MoE:</p><blockquote><strong><em>More total capacity without requiring every parameter to run for every token during inference.</em></strong></blockquote><h4>Where Does MoE Go Inside the Transformer?</h4><p>MoE does not necessarily replace attention.</p><p>A typical dense Transformer might look like:</p><pre>Attention<br>   ↓<br>Dense MLP</pre><p>An MoE Transformer may instead look like:</p><pre>Attention<br>   ↓<br>Router<br>   ↓<br>Selected Experts</pre><p>So the attention concepts we discussed earlier still exist:</p><pre>Q<br>K<br>V<br>Softmax<br>WO<br>Residual stream</pre><p>The difference is primarily in how the feed-forward computation is handled.</p><p>This is why saying:</p><blockquote><em>“Transformer or MoE?”</em></blockquote><p>is usually the wrong comparison. A model can be a<strong><em>Transformer that uses MoE.</em></strong></p><h4>Why Was MoE Created?</h4><p>Scaling neural networks usually improves their capabilities.</p><p>But increasing model size normally also increases computation. MoE offers a compromise. Imagine a dense 100-billion-parameter model. Processing every token might require using a substantial fraction of those parameters.</p><p>Now imagine an MoE model with several hundred billion total parameters, but only a subset is activated for each token.</p><p>You gain <strong><em>large parameter capacity </em></strong>without paying <strong><em>the full computation cost of every parameter for every token.</em></strong></p><p>Of course, MoE introduces its own challenges:</p><ul><li>Routing complexity</li><li>Expert load balancing</li><li>Distributed communication</li><li>Training stability</li><li>Memory requirements etc</li></ul><p>It is not free efficiency.</p><p>But it is one of the major techniques used to scale model capacity.</p><h4>6. Diffusion Models</h4><p>Diffusion describes a fundamentally different way of generating output.</p><p>The most famous examples come from image generation.</p><p>Instead of:</p><pre>pixel 1<br>then pixel 2<br>then pixel 3</pre><p>a diffusion model starts with something resembling random noise.</p><p>Then it repeatedly refines that noise:</p><pre>Random Noise<br>     ↓<br>Less Noise<br>     ↓<br>Rough Structure<br>     ↓<br>More Detail<br>     ↓<br>Final Image</pre><p>The model learns how to reverse a noise-corruption process. This has been extraordinarily effective for image generation.</p><p>Researchers have also explored diffusion-style generation for text.</p><p>Instead of generating:</p><pre>The<br>↓<br>The cat<br>↓<br>The cat sat<br>↓<br>The cat sat down</pre><p>a diffusion-style language model could conceptually begin with:</p><pre>[MASK] [MASK] [MASK] [MASK]</pre><p>Then:</p><pre>The [MASK] sat [MASK]</pre><p>Then:</p><pre>The cat sat [MASK]</pre><p>Then:</p><pre>The cat sat down</pre><p>The important conceptual difference is that the model may refine multiple positions rather than being forced to commit strictly from left to right.</p><p>So:</p><blockquote><strong><em>Autoregressive generation progressively extends a sequence.</em></strong></blockquote><p>while:</p><blockquote><strong><em>Diffusion progressively refines a representation.</em></strong></blockquote><h3>7. A Better Way to Think About Modern Model Architectures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4-tGREOOHYQ4IaIepzowQ.png" /></figure><p>Instead of asking:</p><blockquote><em>“What type of model is this?”</em></blockquote><p>ask several questions.</p><h4>How is the Transformer organized?</h4><p>Possible answers:</p><pre>Encoder-only<br>Decoder-only<br>Encoder–decoder</pre><h4>How are parameters activated?</h4><p>Possible answers:</p><pre>Dense<br>Mixture-of-Experts</pre><h4>How is output generated?</h4><p>Possible answers:</p><pre>Autoregressive<br>Diffusion</pre><h4>How is sequence information processed?</h4><p>Possible answers include:</p><pre>Transformer attention<br>State-space mechanisms<br>Hybrid architectures</pre><p>These dimensions can be mixed and matched. That gives us a much more accurate mental model of today’s AI landscape.</p><h3>8. One Sentence to Remember</h3><p>If everything in this article feels like too much information, remember this:</p><blockquote><strong><em>Attention decides where to get information from, the MLP decides how to transform the information, and the residual stream carries the accumulated result through the model.</em></strong></blockquote><h3>9. Final Thoughts</h3><p>An LLM can look almost magical from the outside.</p><p>You type a question. It writes an answer.</p><p>But underneath the interface, the process is much more mechanical.</p><p>The extraordinary behaviour emerges from <strong>how many learned parameters participate in these operations, how many layers repeat them, and how those parameters were learned from enormous amounts of training data.</strong></p><p>And that brings us naturally to another question:</p><blockquote><em>Where did all those weights or learned matrices -</em><em>WQ, </em><em>WK, </em><em>WV, </em><em>WO, </em><em>up_proj, </em><em>gate_proj, </em><em>down_proj, embeddings and everything else actually come from?</em></blockquote><p>Refer to the previous part of this series: <strong>How an LLM is pretrained.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b56a4c6fc28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git: A comprehensive guide to mastering version control (with cheatsheet)]]></title>
            <link>https://elsonccj.medium.com/git-a-comprehensive-guide-to-mastering-version-control-with-cheatsheet-b71597f5a4ac?source=rss-6b47723a0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71597f5a4ac</guid>
            <dc:creator><![CDATA[Elsonccj]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 07:35:02 GMT</pubDate>
            <atom:updated>2026-08-23T12:43:00.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Sivv6bUD_xO6C03yTvWoA.png" /><figcaption>Git Illustration generated by ChatGPT</figcaption></figure><p>You spend hours working on something important. It finally worked. You made lots of final touch up to make it look impressive.</p><p>All of a sudden your application broke down and you don’t know where it first failed.</p><p>Imagine if you had a <strong>timeline of your work</strong>, where you could jump back to any moment when things still worked.</p><p><strong>That’s Git.</strong> It’s a time machine for your code. Every time you “save” in Git, it takes a snapshot. You can go back to any snapshot, share your snapshots with friends, and even work on different versions of the picture at the same time.</p><h3><strong>1. `git init` — “Let’s Start Saving”</strong></h3><p>You just bought a brand-new notebook. Before you can track any of your drawings, you need to <strong>label the notebook</strong> and set it up. git init is you writing your name on the cover and putting the dividers in.</p><p><strong>What it does<br></strong>git init creates a hidden .git folder in your project directory. This folder is Git&#39;s brain - it stores all your snapshots, your history, and your configuration. Without it, Git has no idea your project even exists.</p><pre># Navigate to your project folder first cd my-awesome-project <br># Initialize Git<br>git init<br><br># Add your local to track where you are pushing to git<br>git remote add origin &lt;url to your Github repository&gt;</pre><p>You’ll see: Initialized empty Git repository in /my-awesome-project/.git/</p><p>Git created its “notebook” in your project. Nothing is saved yet — you’ve just set up the infrastructure. Your project is now <strong>Git-aware</strong>.</p><blockquote><em>💡 </em><strong><em>Pro tip:</em></strong><em> You only ever run </em><em>git init once per project. If you&#39;re cloning someone else&#39;s project, Git already initialises the repo for you - no need to run this.</em></blockquote><h3><strong>2. `git add` — “Put It in the Envelope”</strong></h3><p>Think of Git like mailing a package. You have stuff scattered around your room (your changed files). Before you can mail anything, you need to <strong>pick up the items and put them in an envelope</strong>. git add is you picking things up and putting them in the envelope - but you haven&#39;t sealed or sent it yet.</p><p>This “envelope” is called the <strong>staging area</strong>.</p><p><strong>What it does<br></strong>git add moves your changes from your working directory into the staging area, ready to be committed (saved as a snapshot).</p><pre># Add a specific file<br>git add index.html<br><br># Add multiple specific files<br>git add index.html styles.css<br><br># Add everything in the current directory<br>git add .<br><br># Add all files with a specific extension<br>git add *.js</pre><p><strong>Why does the staging area exist?<br></strong>Great question. Let’s say you made 10 changes but only 3 of them are related. You can git add just those 3 and commit them as one clean, logical snapshot - leaving the other 7 for a separate commit later. This keeps your history readable and meaningful.</p><pre># See what&#39;s staged vs unstaged<br>git status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*VgpmnpC7W3BEAG7Q-hTf_w.png" /><figcaption>git status output example</figcaption></figure><p>Green = staged (in the envelope). Red = changed but not staged (on the floor).</p><h3><strong>3. `git commit` — “Seal the Envelope and Stamp It”</strong></h3><p>You’ve put your items in the envelope. Now you <strong>seal it, write the date, and write a description on the outside</strong> so Future You knows what’s inside without opening it. That sealed envelope is a commit.</p><p><strong>What it does<br></strong>git commit takes everything in your staging area and permanently saves it as a snapshot in your project history. Each commit gets a unique ID (a hash like a3f9c2b) and your message.</p><pre># Commit with a message <br>git commit -m &quot;Add navigation bar to homepage&quot; <br><br># Add and commit in one step (only for tracked files) <br>git commit -am <br><br># Open your editor to write a longer message <br>git commit</pre><p><strong>Writing Good Commit Messages<br></strong>This is where most beginners go wrong. Bad commit messages are like sealing an envelope and writing “stuff” on the outside. Useless.</p><p><strong>Bad:</strong></p><pre>fixed it <br>wip <br>made changes<br>refactoring</pre><p><strong>Good:</strong></p><pre>Fix null pointer exception in user login flow<br>Add dark mode toggle to settings page<br>Refactor API response handler to use async/await</pre><p>A good commit message completes the sentence: <em>“optimised using async…”</em></p><blockquote><em>💡 </em><strong><em>Pro tip:</em></strong><em> Small, frequent commits are better than large, rare ones. Think of it like hitting Ctrl+S often while writing an essay.</em></blockquote><h3><strong>4. `git push` and `git pull` — “Send the Package / Receive New Packages”</strong></h3><p>So far, everything has been in your room (your local machine). But your team is across the world. You need a <strong>shared post office</strong> — that’s GitHub, GitLab, or Bitbucket (the “remote”).</p><ul><li>git push = <strong>You send your sealed envelopes to the post office</strong> so others can see them.</li><li>git pull = <strong>You collect new packages from the post office</strong> that your teammates sent.</li></ul><p><strong>git push</strong></p><pre># Push your current branch to the remote<br>git push origin main <br><br># Push and set the upstream (first time pushing a new branch)<br>git push -u origin feature/login-page <br><br># Force push (dangerous - only use when you know what you&#39;re doing)<br>git push --force</pre><p>When you run git push origin main:</p><ul><li>origin = the name of your remote (the post office&#39;s address)</li><li>main = the branch you&#39;re pushing</li></ul><p><strong>git pull</strong></p><pre># Pull latest changes from remote<br>git pull origin main<br><br># Pull with rebase instead of merge (cleaner history — more on this later)<br>git pull --rebase origin main</pre><p>git pull is actually two commands in disguise: git fetch (download the updates) followed by git merge (apply them to your local code).</p><p>A typical workflow looks like this:</p><pre>git pull origin main         # Get latest from the team<br># ... do your work ...<br>git add .<br>git commit -m &quot;Add feature X&quot;<br>git push origin main         # Share your work with the team</pre><blockquote><em>⚠️ </em><strong><em>Common mistake:</em></strong><em> Forgetting to </em><em>git pull before pushing. If your teammate pushed while you were working, Git will reject your push. Always pull first.</em></blockquote><h3><strong>5. Branching Strategy — “Working in Parallel Universes”</strong></h3><p>Imagine your codebase is a Minecraft world. The main branch is the &quot;official&quot; server that everyone plays on. Now, you want to test a new dangerous mode - you wouldn&#39;t install it directly on the official server! You shall <strong>spin up a private copy of the world</strong>, test the mode there, and only merge it into the official server if it works.</p><p>Branches are those private copies.</p><pre># Create a new branch<br>git branch feature/new_branch_name <br><br># Create AND switch to it in one command<br>git checkout -b feature/new_branch_name <br><br># Modern way (Git 2.23+)<br>git switch -c feature/new_branch_name</pre><p><strong>Local vs Remote Branches<br></strong>This confuses a lot of people.</p><ul><li><strong>Local branch</strong> = exists only on your machine</li><li><strong>Remote branch</strong> = exists on the remote (GitHub/GitLab)</li></ul><p>When you create a branch locally and push it:</p><pre># Create branch locally<br>git switch -c feature/your_branch<br><br># Work and commit...<br>git add .<br>git commit -m &quot;Add dark mode toggle&quot;<br><br># Push to remote for the first time<br>git push -u origin feature/your_branch</pre><p>The -u flag links your local branch to the remote one. After that, git push and git pull without arguments will just work.</p><p><strong>Branching Strategies in the Real World:</strong></p><p><strong>GitHub Flow (simple):</strong></p><ul><li>main = always deployable</li><li>Create a branch for any feature/fix</li><li>Open a Pull Request when done</li><li>Merge into main</li></ul><p><strong>GitFlow (complex):</strong></p><ul><li>main = production releases</li><li>develop = integration branch</li><li>feature/* = new features</li><li>hotfix/* = emergency fixes</li><li>release/* = release preparation</li></ul><p>For most projects, GitHub Flow is enough.</p><p><strong>Switching Between Branches</strong></p><pre># See all branches<br>git branch -a        # local + remote<br>git branch           # local only<br><br># Switch to an existing branch<br>git switch main   <br># or<br>git checkout main   <br><br># Delete a branch (local)<br>git branch -d feature/dark-mode<br><br># Delete a remote branch<br>git push origin --delete feature/dark-mode</pre><h3><strong>6. `git merge` vs `git rebase` — “Two Ways to Combine Work”</strong></h3><p>This is where things get interesting. Both commands combine work from different branches, but they do it differently — and the choice matters for how clean your history looks.</p><p>You and your friend are both writing chapters of a book.</p><ul><li><strong>Merge:</strong> You both finish, then sit down together and <strong>staple your chapters at the end of the book</strong>. There’s a visible record that two people worked separately and then joined up.</li><li><strong>Rebase:</strong> You take your chapters and <strong>rewrite them as if you wrote them after your friend</strong>, so the book reads as one continuous story with no visible “join point”.</li></ul><p><strong>‘git merge’</strong></p><pre># Switch to the branch you want to merge INTO<br>git switch main<br><br># Merge your feature branch in<br>git merge feature/your_branch</pre><p>This creates a <strong>merge commit</strong> — a new commit that has two parents (the tip of main and the tip of your feature branch).</p><pre>      A---B---C feature/dark-mode <br>     /         \<br>D---E---F---G---H main (after merge)</pre><p><strong>Pros:</strong> Preserves the full context of what happened and when. Non-destructive.</p><p><strong>Cons:</strong> History can look cluttered with lots of merge commits.</p><p><strong>`git rebase`</strong></p><pre># Switch to your feature branch<br>git switch feature/your_branch<br><br># Rebase onto main<br>git rebase main</pre><p>This <strong>replays your commits on top of</strong> main, as if you had branched off the latest version.</p><pre>Before:                      After rebase: <br>     A---B                               A&#39;--B&#39; feature/dark-mode <br>    /                                   /<br>D---E---F                      D---E---F  main</pre><p>Note the &#39; - your commits get <strong>rewritten with new hashes</strong>. They have the same changes but are now on a new base.</p><p><strong>Pros:</strong> Linear, clean history. Easier to read with git log.</p><p><strong>Cons:</strong> Rewrites history. <strong>Never rebase a branch that others are working on</strong> — it will cause chaos.</p><p><strong>Interactive Rebase (Bonus)</strong></p><p>One of Git’s most powerful features:</p><pre># Rewrite the last 3 commits<br>git rebase -i HEAD~3</pre><p>This opens an editor where you can:</p><ul><li>pick - keep the commit as-is</li><li>squash - combine with the previous commit</li><li>reword - change the commit message</li><li>drop - delete the commit entirely</li></ul><blockquote><em>⚠️ After rebasing, you have rewritten history, your remote branch will not know about the rewritten history, hence to push now, you have to do a ‘git push --force’.</em></blockquote><p>This is how you turn messy WIP commits into clean, professional history before merging. For a more indepth dive into rebasing, learn more <a href="https://medium.com/@shekharsomani98/git-rebase-the-complete-guide-to-maintaining-clean-linear-history-28b88b3ef0d6">here</a>.</p><h3><strong>`git cherry-pick` — “I Just Want That One Thing”</strong></h3><p>Imagine your friend has a bag of mixed sweets. You don’t want the whole bag — you just want <strong>that one specific lollipop</strong>. git cherry-pick lets you reach into another branch and grab just one specific commit.</p><pre># First, find the commit hash you want<br>git log feature/payments --oneline<br># a3f9c2b Fix tax calculation rounding error<br># 7d2e1ab Add Stripe integration<br># ...<br><br># Cherry-pick just that one fix into your current branch<br>git cherry-pick a3f9c2b</pre><p>Git applies that commit’s changes to your current branch as a <strong>new commit</strong>.</p><p><strong>Common Use Cases</strong></p><ol><li><strong>Hotfix propagation:</strong> You fixed a critical bug in main. You need that fix in your older v1.2 release branch too.</li></ol><pre>git switch release/v1.2<br>git cherry-pick &lt;commit-hash-of-bugfix&gt;</pre><p><strong>2. Salvaging work from an abandoned branch:Cherry-pick a range:</strong></p><pre># Your colleague&#39;s branch won&#39;t be merged, but it had one useful function<br>git cherry-pick &lt;their-commit-hash&gt;</pre><p>3. <strong>Cherry-pick a range:</strong></p><pre># Pick commits from abc123 up to def456 (exclusive of abc123)<br>git cherry-pick abc123..def456</pre><blockquote><em>⚠️ Cherry-pick creates a new commit with a new hash — it’s a copy, not a move. The original commit still exists on its branch.</em></blockquote><h3><strong>8. Advanced Git — Comparing Branches and More</strong></h3><p><strong>Comparing Two Branches</strong></p><pre># See commits in feature-branch that aren&#39;t in main<br>git log main..feature/dark-mode <br><br># See the actual diff between two branches<br>git diff main..feature/dark-mode<br><br># See which files differ<br>git diff main..feature/dark-mode --name-only <br><br># See commits in either branch but not both (symmetric difference)<br>git log main...feature/dark-mode</pre><p><strong>`git log` — Reading History Like a Pro</strong></p><pre># Clean one-liner view<br>git log --oneline<br><br># Visual graph of branches<br>git log --oneline --graph --all<br><br># Filter by author<br>git log --author=&quot;Elson&quot;<br><br># Filter by date<br>git log --after=&quot;2024-01-01&quot; --before=&quot;2024-06-01&quot;<br><br># Search commit messages<br>git log --grep=&quot;authentication&quot;<br><br># See what changed in each commit<br>git log -p<br><br># Last 5 commits<br>git log -5</pre><p><strong>`git stash` — “Hold That Thought”</strong></p><p>You’re in the middle of work but need to switch branches urgently. You can’t commit half-done work. Enter git stash.</p><pre># Save your current work temporarily<br>git stash<br><br># See what&#39;s stashed<br>git stash list<br><br># Bring your work back<br>git stash pop<br><br># Apply without removing from stash<br>git stash apply<br><br># Stash with a name<br>git stash push -m &quot;half-done dark mode&quot;</pre><p>Think of it as putting your work in a drawer while you deal with something else, then taking it back out.</p><p><strong>`git blame` — “Who Wrote This?!”</strong></p><pre># See who last changed each line of a file<br>git blame src/app.js<br><br># Blame with line range<br>git blame -L 20,35 src/app.js</pre><p>Every line shows the commit hash, author, date, and the line content. Useful for tracking down when a bug was introduced — and by whom. 👀</p><p><strong>`git bisect` — Binary Search for Bugs</strong></p><p>You know it worked 50 commits ago, and it’s broken now. git bisect binary-searches through commits to find exactly which one introduced the bug.</p><pre>git bisect start<br>git bisect bad                # Current commit is broken<br>git bisect good v1.0          # This tag was working<br><br># Git checks out the midpoint commit<br># Test your code, then tell Git:<br>git bisect good   # or<br>git bisect bad<br><br># Repeat until Git finds the culprit<br># When done:<br>git bisect reset</pre><h3><strong>9. Returning to a Previous Commit — “The Time Machine”</strong></h3><p>This is one of the most important — and most feared — things in Git. There are several ways to “go back”, and choosing the right one matters.</p><p><strong>Option 1: `git checkout &lt;hash&gt;` — Just Looking Around</strong></p><pre>git checkout a3f9c2b</pre><p>This puts you in a <strong>“detached HEAD” state</strong> — you’re looking at the old snapshot like a museum exhibit. Nothing is changed permanently. Great for investigating old code.</p><p>To go back to your branch:</p><pre>git switch main</pre><p><strong>Option 2: `git revert` — Undo Safely (Recommended)</strong></p><pre># Undo a specific commit by creating a new &quot;reverse&quot; commit<br>git revert a3f9c2b</pre><p>This is the <strong>safe, collaborative way</strong> to undo. It creates a new commit that reverses the changes. Your history stays intact — it just adds an “undo” entry. Use this on shared branches.</p><pre>...---A---B---C---D (revert of B)</pre><p><strong>Option 3: `git reset` — Rewriting History</strong></p><p>This is the power tool. Use carefully.</p><pre># Move HEAD back 1 commit, keep changes staged<br>git reset --soft HEAD~1<br><br># Move HEAD back 1 commit, keep changes unstaged<br>git reset --mixed HEAD~1   # (default)<br><br># Move HEAD back 1 commit, DISCARD all changes<br>git reset --hard HEAD~1    # ⚠️ Irreversible!</pre><blockquote><em>⚠️ </em><strong><em>Never </em></strong><strong><em>git reset --hard on commits that have been pushed to a shared branch.</em></strong><em> It rewrites history and will break your teammates&#39; repos.</em></blockquote><p><strong>For simplicity:</strong></p><p><strong>--soft</strong> — moves the commit pointer back, but keeps your changes staged. It&#39;s like the commit never happened but your work is still queued up ready to recommit.</p><p><strong>--mixed</strong> (the default) — moves the pointer back and unstages your changes, but keeps the files intact. You have to git add again before recommitting.</p><p><strong>--hard</strong> — moves the pointer back and wipes everything. Your working files are overwritten to match the old commit. There&#39;s no undo for this one.</p><p><strong>Option 4: Restore a Single File to a Past Version</strong></p><pre># Restore a specific file to how it was in commit abc123<br>git checkout abc123 -- src/components/Button.js<br><br># Or using the modern syntax<br>git restore --source=abc123 src/components/Button.js</pre><h3><strong>10. Unstaging Files — “Take It Out of the Envelope”</strong></h3><p>You ran git add . and immediately regret it. Maybe you accidentally staged a .env file with secrets, or a node_modules folder. Don&#39;t panic.</p><p><strong>Unstage a File (Keep Your Changes)</strong></p><pre># Modern way (Git 2.23+)<br>git restore --staged index.html<br><br># Old way<br>git reset HEAD index.html</pre><p>Your changes are still there in the file — they’re just no longer queued up for the next commit.</p><p><strong>Unstage Everything</strong></p><pre>git restore --staged .</pre><p><strong>Discard Changes in a File Entirely</strong></p><p>This is more drastic — it throws away your uncommitted changes:</p><pre># Discard changes in working directory (⚠️ unrecoverable)<br>git restore index.html<br><br># Old way<br>git checkout -- index.html</pre><h3><strong>Quick Reference Cheatsheet</strong></h3><pre># Setup<br>git init                          # Start a new repo<br>git clone &lt;url&gt;                   # Copy a remote repo<br><br># Referencing remote<br>git remote add origin &lt;url&gt;<br><br># Everyday<br>git status                        # See what&#39;s going on<br>git add .                         # Stage everything<br>git commit -m &quot;message&quot;           # Commit with message<br>git push origin main              # Push to remote<br>git pull origin main              # Pull from remote<br><br># Branching<br>git switch -c feature/name        # Create + switch to branch<br>git switch main                   # Go back to main<br>git merge feature/name            # Merge branch into current<br>git branch -d feature/name        # Delete local branch<br><br># Rebase<br>git rebase main                   # Rebase current branch onto main<br>git rebase -i HEAD~3              # Interactive rebase (last 3 commits)<br><br># History<br>git log --oneline --graph --all   # Visual history<br>git diff main..feature/name       # Diff between branches<br>git blame file.js                 # Who changed each line<br><br># Undo<br>git restore --staged file.js      # Unstage a file<br>git restore file.js               # Discard working changes<br>git revert &lt;hash&gt;                 # Undo a commit safely<br>git reset --soft HEAD~1           # Undo last commit, keep changes<br><br># Utilities<br>git stash                         # Save uncommitted work temporarily<br>git stash pop                     # Restore stashed work<br>git cherry-pick &lt;hash&gt;            # Grab one commit from another branch<br>```</pre><h3>Closing Thoughts</h3><p>One final key point that many misunderstood about Git is that it does not “save a copy” of the entire repository every time you commit and push. Git only tracks the differences between them and <strong>ONLY</strong> these differences are tracked and saved.</p><p>Git is one of those tools that feels overwhelming at first but becomes second nature with practice. The key insight is this: <strong>Git is not about commands, it’s about snapshots and history.</strong></p><p>Once you stop thinking of Git as a save system and start thinking of it as a <em>time machine and collaboration tool</em>, everything clicks. You stop being afraid of git reset or git rebase because you understand what&#39;s actually happening under the hood.</p><p>Start simple: init, add, commit, push, pull. Branch early. Commit often. Write meaningful messages. The rest will follow.</p><p>Happy coding. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71597f5a4ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning about Poetry (not the Literature kind)]]></title>
            <link>https://elsonccj.medium.com/learning-about-poetry-not-the-literature-kind-dd2078b52810?source=rss-6b47723a0c29------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd2078b52810</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[poetry]]></category>
            <dc:creator><![CDATA[Elsonccj]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 07:40:46 GMT</pubDate>
            <atom:updated>2026-03-18T12:36:54.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NflKjsIQc5gCdK-ZOBGUJw.png" /></figure><p>I started learning Python a few years ago. As I delved into the world of Python, managing dependencies have become an inevitable task. Traditional tools like pip and virtualenv were handy but often cumbersome, lacking a seamless integration for project dependency management and packaging. That’s when I discovered <strong>Poetry</strong>. This article consolidates my learnings and experiences using Poetry in my recent project, Yahoo Search Engine. Check it out <a href="https://github.com/Vivolance/yahoo_search_engine">here</a>!</p><h3><strong>What is Poetry?</strong></h3><p>Here is an analogy: Think of poetry as a big box of toys, and you want to share them with your friends. But you do not want them to go through the hassle of putting the pieces of toys together themselves to start playing. Instead, you want to give them a ready-to-play box where everything they need is already inside and ready. Poetry is like the ready-to-play box that any of your friends could just open and play!</p><p>For the seasoned, Poetry is a dependency management and packaging tool for Python that is designed to handle the complexities of dependency resolution and to simplify the process of creating, managing and publishing Python projects. This allows other users of your script to install required dependencies on their environment directly using Poetry without needing to go through the hassle to manually installing each dependency.</p><h3>Advantages of Poetry</h3><ol><li><strong>Dependency Resolution</strong>: Poetry uses a robust dependency resolver to ensure all dependencies are compatible, automatically resolving and installing them.</li><li><strong>Ease of Use</strong>: Its intuitive syntax and commands make creating new projects, adding dependencies, and publishing packages straightforward.</li><li><strong>Reproducibility</strong>: By generating a poetry.lock file, Poetry locks the exact versions of all dependencies, ensuring the environment can be recreated accurately.</li><li><strong>Environment Management</strong>: Poetry creates and manages virtual environments automatically, ensuring project isolation and avoiding conflicts.</li><li><strong>Compatibility</strong>: Everything is handled within a single configuration file, pyproject.toml. The pyproject.toml file standardises the project configuration, making it compatible with other tools adhering to PEP</li></ol><h3>Disadvantages of Poetry</h3><ol><li><strong>Learning Curve</strong>: Transitioning from traditional tools like pip and virtualenv to Poetry can require some initial learning.</li><li><strong>Performance</strong>: Dependency resolution in Poetry can be slower compared to pip, especially for projects with many dependencies. This is because not all libraries on PyPI have properly declared their metadata and, as such, they are not available via the PyPI JSON API. Poetry has no choice but to download the packages and inspect them to get the necessary information. this process is taxing both in bandwidth and time.</li></ol><h3>How to use Poetry?</h3><p>It is simple really! I have consolidated the steps required to established and maintain your Poetry file below. Give it a try!</p><p><strong>Step 1: Starting Poetry</strong></p><pre>Poetry init</pre><p>Remember the toy box we mentioned? By running poetry init, we create a default pyproject.toml file. This is the main file where you will define all your required dependencies inside this file. Here is an example below of my project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5uVXSj1DdyCoCt9k19yyg.png" /><figcaption>Figure 1 — pyproject.toml file for YahooSearchEngine</figcaption></figure><p>Notice there are different sections to categorize each dependency according to what their usages are. To understand how to define the various versions of your dependency required, and the tips and tricks on how to interchange between versions to suit your project, check out the full Poetry Documentation <a href="https://python-poetry.org/docs/managing-dependencies/">here</a>.</p><p><strong>Step 2: Adding dependencies<br></strong>We can add dependencies by doing:</p><pre>Poetry add alembic</pre><p><strong>Step 3: Installing your dependencies</strong><br>After adding all the required dependencies, this step allows Poetry to read all defined dependencies and version in your pyproject.toml file and installs it, creating a poetry.lock file.</p><pre>poetry install --no-root</pre><p><strong>Step 4: Maintaining Dependencies</strong><br>To upgrade or downgrade (in some cases) your dependencies or make changes to the versions directly in the pyproject.toml, we can create a new lock file with:</p><pre>poetry lock --no-update</pre><p>This allows a new lock file to be created with ONLY your updates. Note that the ‘--no-update’ ensures that we do not update other dependencies accidentally that we did not change in our pyproject.toml file. As a maintainer of your repository, it is your responsibility to upgrade versions of your dependencies from time to time to ensure the compatibility of your scripts!</p><p>And you are done!</p><h3>Final Words</h3><p>Embracing Poetry has been a game-changer, and I highly recommend it to anyone looking to enhance their Python development experience. The seamlessness in handling dependencies, ease of packaging and unified approach to project management have significantly streamlined my workflow. Share your thoughts with me!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd2078b52810" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>