<?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[Backpropolis]]></title><description><![CDATA[Building language models from scratch: neural networks, tokenizers, attention, and transformer architecture, implemented step by step in PyTorch.]]></description><link>https://backpropolis.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6a8529e312a05b966906826e/7a614d81-637a-4771-86e8-faf6f62e5bab.jpg</url><title>Backpropolis</title><link>https://backpropolis.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:41:47 GMT</lastBuildDate><atom:link href="https://backpropolis.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Self-Attention and Multi-Head Attention]]></title><description><![CDATA[Build Self-Attention, Multi-Head, Causal, and Cross-Attention from scratch in PyTorch: the four building blocks behind every transformer.]]></description><link>https://backpropolis.hashnode.dev/self-attention-and-multi-head-attention</link><guid isPermaLink="true">https://backpropolis.hashnode.dev/self-attention-and-multi-head-attention</guid><category><![CDATA[transformers]]></category><category><![CDATA[attention]]></category><category><![CDATA[pytorch]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[David Hoang]]></dc:creator><pubDate>Tue, 01 Dec 2026 14:03:51 GMT</pubDate><content:encoded><![CDATA[<p><em>Building Self-Attention, Multi-Head Attention, Causal Attention, and Cross-Attention from scratch in PyTorch</em></p>
<h1>Introduction</h1>
<p>The single equation that changed NLP shipped in 2017 inside <em>Attention Is All You Need</em> (Vaswani et al.). Scaled dot-product self-attention replaced recurrence, convolution, and alignment models with one operation. Every LLM since, from GPT to DeepSeek, runs on variants of it.</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image.png" alt="“Attention is All You Need” paper (https://arxiv.org/abs/1706.03762)" style="display:block;margin:0 auto" />

<p>“Attention is All You Need” paper (<a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a>)</p>
<p>By the end of this post you will have built, from scratch in PyTorch, working implementations of Self-Attention, Multi-Head Attention, Causal Self-Attention, and Cross-Attention, the four building blocks that power every transformer.</p>
<p>No history lesson. No survey of 200 papers. Just the mechanics, the shapes, and the code. If you know what a tensor is and can read a <code>nn.Module</code>, you're ready.</p>
<p>All code in this post is available as runnable Jupyter notebooks at <a href="https://github.com/backpropolis/nlp_from_scratch/tree/main/attention">github.com/backpropolis/nlp_from_scratch</a>.</p>
<p>Note: We'll thread a single running example through the entire post: the sentence <em>"The CEO announced record earnings on Friday"</em>, embedded into <code>d_model = 64</code>. Watch how each mechanism transforms these vectors step by step.</p>
<hr />
<h1>Self-Attention</h1>
<p>Right now, each of our 7 tokens ["The", "CEO", "announced", … "Friday"] is an isolated 64-dimensional vector. "announced" has no idea that "CEO" is its subject or that "Friday" is when it happened. How does a model let every token decide which other tokens matter, without any hardwired positional rules?</p>
<p>Self-attention computes a weighted sum of all other tokens' representations, with weights determined by learned relevance, not fixed position. This is the atomic operation inside every transformer layer: BERT's encoder, ViT's patch interactions, the encoder side of T5. All bidirectional self-attention. Decoder-only models (GPT, LLaMA) use the causal variant we'll cover later.</p>
<h2>Query, Key, and Value</h2>
<p>Each token's embedding is a single vector, but it needs to play three roles at once. "announced" needs to <em>search</em> for its subject, while "CEO" needs to <em>advertise</em> that it is one, and both need to <em>transmit</em> their content when matched. A single vector can't encode "what am I looking for" and "what do I offer" simultaneously, so we project the input into three separate spaces:</p>
<pre><code class="language-plaintext">Q = X @ W_Q    K = X @ W_K    V = X @ W_V
</code></pre>
<ul>
<li><strong>X</strong> <code>[batch, seq_len, d_model]</code>: Input embeddings</li>
<li><strong>W_Q, W_K</strong> <code>[d_model, d_k]</code>: Project each token into query and key spaces</li>
<li><strong>W_V</strong> <code>[d_model, d_v]</code>: Project each token into value space</li>
<li><strong>Q</strong> <code>[batch, seq_len, d_k]</code>: What this token is <strong>looking for</strong></li>
<li><strong>K</strong> <code>[batch, seq_len, d_k]</code>: What this token <strong>advertises</strong></li>
<li><strong>V</strong> <code>[batch, seq_len, d_v]</code>: The <strong>content</strong> transmitted when attention is paid</li>
</ul>
<p>Two tokens interact strongly when their query-key dot product is high. "announced" is looking for a subject, and "CEO" advertises exactly that. The diagram below shows this three-way split from a single input embedding:</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%201.png" alt="image.png" style="display:block;margin:0 auto" />

<p>*In practice (and in all implementations below), we set <code>d_v = d_k</code>. The math generalizes to <code>d_v ≠ d_k</code>, but most architectures use equal dimensions for simplicity.</p>
<h2>Scaled Dot-Product Attention</h2>
<p>Those Q, K, V matrices are ready. "announced" now has a query vector, and "CEO" has a key vector. Their dot product measures how relevant they are to each other. But raw dot products between 64-dimensional vectors produce scores in the hundreds, pushing softmax into near-one-hot regions where gradients vanish. How do you turn them into stable, interpretable weights?</p>
<pre><code class="language-plaintext">Attention(Q, K, V) = softmax(Q @ K.T / sqrt(d_k)) @ V
</code></pre>
<ul>
<li><strong>Q @ K.T</strong> → <code>[batch, seq_len, seq_len]</code> — Raw relevance scores between all token pairs</li>
<li><strong>sqrt(d_k)</strong> (scalar) — Scaling factor. Dot product variance grows with <code>d_k</code>, saturating softmax</li>
<li><strong>attn_weights</strong> → <code>[batch, seq_len, seq_len]</code> — Row-wise probability distribution</li>
<li><strong>Output</strong> → <code>[batch, seq_len, d_v]</code> — Weighted average of all value vectors</li>
</ul>
<p>Without scaling, each element in <code>Q @ K.T</code> is a sum of <code>d_k</code> products; variance grows linearly with <code>d_k</code>, pushing softmax into near-one-hot regions where gradients vanish. Divide by <code>sqrt(d_k)</code> to keep the distribution smooth. Multiply by V to produce the final output: each token's new representation is a weighted mix of all values.</p>
<p>In our 7-token example, the attention matrix is <code>[1, 7, 7]</code>. The row for "announced" peaks on "CEO" (subject) and "earnings" (object).</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%202.png" alt="image.png" style="display:block;margin:0 auto" />

<p>That's the full mechanism. Translating it into code is straightforward.</p>
<h2>Implementation from Scratch</h2>
<pre><code class="language-python">class SelfAttention(nn.Module):
    def __init__(self, d_model: int, d_k: int | None = None):
        super().__init__()
        self.d_k = d_k if d_k is not None else d_model
        self.W_q = nn.Linear(d_model, self.d_k, bias=False)
        self.W_k = nn.Linear(d_model, self.d_k, bias=False)
        self.W_v = nn.Linear(d_model, self.d_k, bias=False)

    def forward(self, x: torch.Tensor) -&gt; tuple[torch.Tensor, torch.Tensor]:
        Q = self.W_q(x)  # (batch, seq_len, d_k)
        K = self.W_k(x)  # (batch, seq_len, d_k)
        V = self.W_v(x)  # (batch, seq_len, d_k)
        scores = torch.bmm(Q, K.transpose(1, 2)) / math.sqrt(self.d_k)
        weights = F.softmax(scores, dim=-1)  # (batch, seq_len, seq_len)
        out = torch.bmm(weights, V)          # (batch, seq_len, d_k)
        return out, weights
</code></pre>
<p>Simple, but expensive. Every token attends to every other token.</p>
<p>📓 <a href="https://github.com/backpropolis/nlp_from_scratch/blob/main/attention/1.%20self_attention.ipynb">Run the full self-attention notebook</a> — includes bidirectional and causal modes with shape checks and attention heatmaps.</p>
<h2>Computational Cost</h2>
<p>Complexity: <code>O(n² * d)</code> time and memory. A 4,096-token sequence → ~16.8M entries per head per layer. At 128k tokens → ~16.4B. This quadratic scaling motivates every efficiency variant (such as sparse attention, Flash Attention, etc). The chart below shows how the attention matrix grows with sequence length:</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%203.png" alt="image.png" style="display:block;margin:0 auto" />

<h2>Key Takeaways</h2>
<p>Self-attention projects each token into Q, K, V spaces, computes scaled dot-product scores, and outputs a weighted combination of all value vectors, making every token's new representation a function of the entire sequence. It's the atomic unit of transformer attention, used in every encoder (BERT, ViT, T5 encoder) and as the core of every decoder. Powerful all-to-all connectivity at <code>O(n²)</code> time and memory cost.</p>
<p>A single head can only capture one type of token relationship: "announced" attends to both "CEO" and "Friday" through the same weights. What if different positions need different relationship types?</p>
<hr />
<h1>Multi-Head Attention (MHA)</h1>
<p>One head captures one relationship type. What if "announced" needs to attend to "CEO" for subject-verb agreement <em>and</em> to "Friday" for temporal grounding, simultaneously?</p>
<p>MHA solves this by running <strong>h</strong> independent heads in parallel, each with its own Q/K/V projections learning different relationship types, then combining their outputs through a learned projection <strong>W_O</strong>.</p>
<h2>The Three-Stage Pipeline</h2>
<pre><code class="language-plaintext">head_i = Attention(X @ W_i_Q,  X @ W_i_K,  X @ W_i_V)
Output = Concat(head_1, ..., head_h) @ W_O
</code></pre>
<ul>
<li><strong>Stage 1 — Parallel projections:</strong> Each head i projects into <code>d_k = d_model / h</code>. With <code>d_model = 64</code> and <code>h = 4</code>, each head works in 16 dimensions → <code>head_i</code>: <code>[batch, seq_len, d_k]</code></li>
<li><strong>Stage 2 — Concatenation:</strong> Stack all head outputs along the feature dim → <code>[batch, seq_len, h * d_k]</code> = <code>[batch, seq_len, d_model]</code></li>
<li><strong>Stage 3 — Output projection:</strong> <code>W_O</code> <code>[d_model, d_model]</code> mixes heads → <code>[batch, seq_len, d_model]</code></li>
</ul>
<p>Each head computes scaled dot-product attention in its own <code>d_k</code>-dimensional subspace. One learns subject-verb links ("announced" → "CEO"), another temporal relations ("announced" → "Friday"). <code>W_O</code> mixes these patterns into a unified representation. The diagram below traces data through all three stages:</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%204.png" alt="image.png" style="display:block;margin:0 auto" />

<h2>The Dimension Split</h2>
<p>A natural question: doesn't running <em>h</em> heads cost h times more? No. Each head works in <code>d_k = d_model / h</code>, not full <code>d_model</code>. With <code>d_model = 64</code> and <code>h = 4</code>: each head is 16-dimensional. Total parameters across all heads ≈ one full-dimensional head. MHA is a better allocation of the same compute budget, not a more expensive one.</p>
<p>The implementation reuses the <code>SelfAttention</code> class from earlier, one instance per head.</p>
<h2>Implementation from Scratch</h2>
<pre><code class="language-python">class MultiHeadAttention(nn.Module):
    def __init__(self, d_model: int, n_heads: int):
        super().__init__()
        self.d_k = d_model // n_heads
        self.heads = nn.ModuleList([SelfAttention(d_model, self.d_k) for _ in range(n_heads)])
        self.W_o = nn.Linear(d_model, d_model, bias=False)

    def forward(self, x: torch.Tensor):
        outs, weights = [], []
        for head in self.heads:
            h_out, h_w = head(x)
            outs.append(h_out)
            weights.append(h_w)
        out = self.W_o(torch.cat(outs, dim=-1))   # (batch, seq_len, d_model)
        return out, torch.stack(weights, dim=1)    # weights: (batch, n_heads, seq_len, seq_len)
</code></pre>
<p>📓 <a href="https://github.com/backpropolis/nlp_from_scratch/blob/main/attention/2.%20mutihead_attention.ipynb">Run the multi-head attention notebook</a> — includes per-head visualizations and a detailed single-head vs. multi-head comparison table.</p>
<h2>Key Takeaways</h2>
<p><strong>h</strong> parallel heads in <code>d_model / h</code> subspaces, combined via learned <code>W_O</code>, with the same total compute as single-head. MHA is the original design (GPT-2, OLMo); newer models use GQA (Llama 3) or MLA (DeepSeek V3) to reduce KV cache cost.</p>
<p>MHA gives every head full access to all positions, but for autoregressive generation, "Friday" shouldn't peek at tokens that come after it. One additive mask solves this.</p>
<hr />
<h1>Causal Self-Attention</h1>
<p>Standard attention lets every token see every other token, including the future. When the model is trying to predict what comes after "The CEO announced", position 2 ("announced") can look ahead and see "record" sitting at position 3. It just copies instead of learning to predict. That's where causal masks come in.</p>
<pre><code class="language-plaintext">CausalAttention(Q, K, V) = softmax(Q @ K.T / sqrt(d_k) + M) @ V
</code></pre>
<p>Add one hard constraint to standard attention: each token sees only itself and earlier positions. This is the attention mechanism inside every decoder-only LLM — GPT, Claude, LLaMA, Mistral — where the model generates one token at a time, left to right. Without this mask, the model copies instead of predicts.</p>
<h2>The Mask Mechanism</h2>
<p>We need position 2 ("announced") to attend only to positions 0–2, while position 6 ("Friday") can see everything. Add −∞ to the banned positions before softmax. They get exactly zero weight:</p>
<pre><code class="language-plaintext">M[i][j] = 0       if j &lt;= i
M[i][j] = -inf    if j &gt; i
</code></pre>
<ul>
<li><strong>Mask added</strong> before softmax, to scaled scores</li>
<li><strong>Effect of e^(-inf):</strong> exactly zero attention weight</li>
<li><strong>Result:</strong> lower-triangular attention matrix</li>
<li><strong>Reuse:</strong> computed once, shared across all heads and layers</li>
<li><strong>Training:</strong> all T positions computed in one forward pass. Position t sees tokens 0…t simultaneously, no T separate passes needed</li>
</ul>
<p>Add M to <code>Q @ K.T / sqrt(d_k)</code> before softmax. Future positions get <code>-inf</code>, softmax maps them to exactly zero. The mask is built with <code>torch.triu(..., diagonal=1)</code> which produces the upper-triangular boolean, and <code>masked_fill</code> sets those positions to <code>-inf</code>.</p>
<p>In our 7-token example, "CEO" (position 1, 0-indexed) sees only ["The", "CEO"]. "Friday" (position 6) sees the full sequence. The attention matrix is lower-triangular: 28 active entries out of 49.</p>
<p>Concretely: when generating "The CEO announced ___", position 2 attends only to ["The", "CEO", "announced"]. It cannot see "record" at position 3 or "Friday" at position 6. If position 2 could peek at position 3, it would just copy "record" instead of learning to predict it.</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%205.png" alt="image.png" style="display:block;margin:0 auto" />

<p>The mask handles training and shapes. But at inference time, the causal constraint unlocks a major optimization.</p>
<h2>KV Cache and Inference Cost</h2>
<p>The causal mask means token t never attends beyond t, so keys and values for positions <code>1...t-1</code> are fixed once computed. Caching them is safe. Bidirectional attention would invalidate the cache with every new token.</p>
<p>During autoregressive generation, each new token attends to all previous tokens. The KV cache stores past key/value tensors to avoid recomputation:</p>
<pre><code class="language-plaintext">KV cache memory (bytes) = 2 * n_layers * n_heads * T * d_k * bytes_per_element
</code></pre>
<ul>
<li><strong>2</strong> = one tensor for K, one tensor for V</li>
<li><strong>LLaMA 3 8B</strong> (32 layers, 32 heads, d_k = 128, T = 8,192) → ~4 GB (float16)</li>
<li><strong>Same config, T = 128k</strong> → ~69 GB (float16)</li>
</ul>
<p>This linear-in-T memory scaling is the dominant inference bottleneck. It's why long conversations slow down and why providers charge per-token. It drives GQA (share K/V across head groups) and MLA (compress K/V into a low-rank latent). The chart below shows KV cache memory scaling with sequence length:</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%206.png" alt="image.png" style="display:block;margin:0 auto" />

<p><em>Gotcha: many heads assign disproportionate weight to the first token. Under the causal mask, it's the only position visible to all others, acting as a default "sink" for leftover attention mass (see StreamingLLM).</em></p>
<p>The implementation adds just two lines to <code>SelfAttention</code>: build the mask, apply it before softmax.</p>
<h2>Implementation from Scratch</h2>
<pre><code class="language-python">class CausalSelfAttention(nn.Module):
    def __init__(self, d_model: int, d_k: int):
        super().__init__()
        self.d_k = d_k
        self.W_q = nn.Linear(d_model, d_k, bias=False)
        self.W_k = nn.Linear(d_model, d_k, bias=False)
        self.W_v = nn.Linear(d_model, d_k, bias=False)

    def forward(self, x: torch.Tensor) -&gt; torch.Tensor:
        Q, K, V  = self.W_q(x), self.W_k(x), self.W_v(x)
        seq_len  = x.size(1)
        scores   = torch.bmm(Q, K.transpose(1, 2)) / math.sqrt(self.d_k)
        mask     = torch.triu(torch.ones(seq_len, seq_len, dtype=torch.bool), diagonal=1)
        weights  = F.softmax(scores.masked_fill(mask, float("-inf")), dim=-1)
        return torch.bmm(weights, V)
</code></pre>
<p>📓 Causal attention is covered in the <a href="https://github.com/backpropolis/nlp_from_scratch/blob/main/attention/1.%20self_attention.ipynb">self-attention notebook</a> — the unified <code>SelfAttention</code> class handles both bidirectional and causal modes via an optional mask parameter.</p>
<h2>Key Takeaways</h2>
<p>Lower-triangular mask enables autoregressive generation, KV caching, and single-pass training, the foundation of every decoder-only model (GPT, LLaMA, Mistral). Bidirectional models (BERT) see everything but can't generate; encoder-decoder models (T5) combine both via cross-attention.</p>
<p>Causal attention lets a sequence attend to itself with temporal constraints. But what about attending to a completely different sequence?</p>
<hr />
<h1>Cross-Attention</h1>
<p>Causal self-attention connects tokens within one sequence. But what if the decoder needs to ask: "which of the encoder's tokens matter for what I'm generating right now?"</p>
<pre><code class="language-plaintext">CrossAttention(Q, K, V) = softmax(Q @ K.T / sqrt(d_k)) @ V
</code></pre>
<p>Cross-attention connects two separate sequences: queries from one, keys/values from the other. Same formula as self-attention, but Q and K/V come from different sources.</p>
<h2>The Mechanism</h2>
<p>Consider translating "The CEO announced record earnings on Friday" (7 tokens) into Vietnamese: "Tổng giám đốc đã công bố thu nhập kỷ lục vào thứ Sáu" (13 tokens). The decoder generates the Vietnamese output token by token, and at each step it needs to look back at the English source to decide what to translate next. The two sequences have different lengths: 13 Vietnamese tokens querying 7 English tokens.</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%2010.png" alt="image.png" style="display:block;margin:0 auto" />

<p>Each line connects a decoder token (bottom) to an encoder token (top), with thickness proportional to attention weight. Notice the rectangular structure: every decoder token can attend to all encoder tokens — no causal mask needed since the encoder output is already complete.</p>
<p>The wiring: Q from one sequence, K/V from the other:</p>
<pre><code class="language-plaintext">Q = X_Q  @ W_Q       # from decoder: [batch, seq_len_q, d_model] -&gt; [batch, seq_len_q, d_k]
K = X_KV @ W_K       # from encoder: [batch, seq_len_kv, d_model] -&gt; [batch, seq_len_kv, d_k]
V = X_KV @ W_V       # from encoder: [batch, seq_len_kv, d_model] -&gt; [batch, seq_len_kv, d_k]
</code></pre>
<ul>
<li><strong>X_Q</strong> <code>[batch, seq_len_q, d_model]</code> — Querying sequence (decoder)</li>
<li><strong>X_KV</strong> <code>[batch, seq_len_kv, d_model]</code> — Context sequence (encoder)</li>
<li><strong>Attention matrix</strong> <code>[batch, seq_len_q, seq_len_kv]</code> — <strong>Rectangular</strong>, not square</li>
</ul>
<p>In our example, the attention matrix is <code>13 x 7</code>: each of the 13 decoder rows specifies how one Vietnamese token distributes attention across all 7 English tokens.</p>
<p>That covers the mechanism. But cross-attention doesn't exist in isolation; it's one of three sub-layers inside each decoder block.</p>
<h2>Role in the Original Transformer</h2>
<p>Each decoder block in the original Transformer stacks three sub-layers in sequence:</p>
<ul>
<li><strong>1. Causal self-attention</strong> — Q from decoder, K/V from decoder</li>
<li><strong>2. Cross-attention</strong> — Q from decoder, K/V from encoder</li>
<li><strong>3. Feed-forward network</strong> — position-wise, no attention</li>
</ul>
<p>The encoder output is computed once and reused by every decoder layer at every generation step. The diagram below shows the full decoder block with all three sub-layers, residual connections, and the encoder output feeding K/V into the cross-attention layer:</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%208.png" alt="image.png" style="display:block;margin:0 auto" />

<p>This encoder-decoder design powered the original Transformer. But most modern text-only LLMs have moved away from it entirely.</p>
<h2>Cross-Attention vs. Concatenation</h2>
<p>Modern text-only LLMs (GPT, LLaMA) are decoder-only — no encoder, no cross-attention. They concatenate the two sequences and let causal self-attention handle the rest. The tradeoff:</p>
<ul>
<li><strong>Concatenation</strong> — Simpler, no extra architecture. But cost is <code>O((seq_q + seq_kv)²)</code>, the combined length quadratic.</li>
<li><strong>Cross-attention</strong> — Cost is <code>O(seq_q × seq_kv)</code>, keeping the two sequences separate. But requires dedicated Q/K/V projections wired across encoder and decoder.</li>
</ul>
<p>For text-only LLMs, concatenation wins. Cross-attention remains dominant in multimodal architectures where the two modalities have very different representations: Flamingo (language → image features), Stable Diffusion (U-Net ← CLIP text), Whisper (decoder ← audio encoder).</p>
<h2>Implementation from Scratch</h2>
<p>The data flow diagram below maps directly to the code: X_Q feeds W_Q on the decoder side, X_KV feeds W_K and W_V on the encoder side, and both streams merge at the attention computation. Notice that <code>seq_len_q</code> and <code>seq_len_kv</code> are independent — 13 and 7 in our translation example — producing the rectangular matrix from earlier.</p>
<img src="https://backpropolis.github.io/posts/2026-03-30-self-attn/asset/image%207.png" alt="image.png" style="display:block;margin:0 auto" />

<pre><code class="language-python">class CrossAttention(nn.Module):
    def __init__(self, d_model: int, d_k: int | None = None):
        super().__init__()
        self.d_k = d_k if d_k is not None else d_model
        self.W_q = nn.Linear(d_model, self.d_k, bias=False)
        self.W_k = nn.Linear(d_model, self.d_k, bias=False)
        self.W_v = nn.Linear(d_model, self.d_k, bias=False)

    def forward(self, x_q: torch.Tensor, x_kv: torch.Tensor) -&gt; tuple[torch.Tensor, torch.Tensor]:
        Q = self.W_q(x_q)    # (batch, seq_len_q,  d_k)
        K = self.W_k(x_kv)   # (batch, seq_len_kv, d_k)
        V = self.W_v(x_kv)   # (batch, seq_len_kv, d_k)
        scores = torch.bmm(Q, K.transpose(1, 2)) / math.sqrt(self.d_k)  # (batch, seq_len_q, seq_len_kv)
        weights = F.softmax(scores, dim=-1)  # (batch, seq_len_q, seq_len_kv)
        out = torch.bmm(weights, V)          # (batch, seq_len_q, d_k)
        return out, weights
</code></pre>
<p>📓 <a href="https://github.com/backpropolis/nlp_from_scratch/blob/main/attention/3.%20cross_attention.ipynb">Run the cross-attention notebook</a> — includes padding mask handling and a translation alignment visualization.</p>
<h2>Key Takeaways</h2>
<p>Same formula as self-attention, but Q from one sequence and K/V from another → rectangular <code>seq_len_q x seq_len_kv</code> matrix. Bridges encoder-decoder in the original Transformer. Standard for multimodal; replaced by concatenation in text-only LLMs.</p>
<hr />
<h1>Conclusion</h1>
<p>Four mechanisms, one core operation. <strong>Self-attention</strong> gives every token all-to-all connectivity through Q, K, V projections and scaled dot-product scoring. <strong>Multi-head attention</strong> runs h independent heads in parallel subspaces, then recombines via W_O, with the same compute budget but richer representations. <strong>Causal self-attention</strong> adds a lower-triangular mask that blocks future positions, enabling autoregressive generation and KV caching. <strong>Cross-attention</strong> splits Q and K/V across two sequences, producing a rectangular attention matrix that bridges encoder and decoder.</p>
<p>Every transformer since 2017 (GPT, BERT, LLaMA, Whisper, Stable Diffusion) is built from combinations of these four building blocks.</p>
<p>The shapes, the scaling, and the masks are the same; only the wiring changes.</p>
]]></content:encoded></item><item><title><![CDATA[Neural Network From Scratch: From One Neuron to a Tiny MLP in NumPy]]></title><description><![CDATA[Build a tiny MLP in pure NumPy: Dense layers, ReLU, softmax cross-entropy, backpropagation, SGD, and regularization, trained on a spiral dataset.]]></description><link>https://backpropolis.hashnode.dev/neural-network-from-scratch-from-one-neuron-to-a-tiny-mlp-in-numpy</link><guid isPermaLink="true">https://backpropolis.hashnode.dev/neural-network-from-scratch-from-one-neuron-to-a-tiny-mlp-in-numpy</guid><category><![CDATA[neural networks]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[backpropagation]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[numpy]]></category><dc:creator><![CDATA[David Hoang]]></dc:creator><pubDate>Tue, 24 Nov 2026 14:40:20 GMT</pubDate><content:encoded><![CDATA[<p><em>Start with one neuron, expand it into Dense layers, then train a small network on a curved spiral dataset</em></p>
<h2>Brief Intro</h2>
<p>A neural network is a model that learns from examples. Instead of writing every rule by hand, we give it data, compare its prediction with the correct answer, and let it adjust its internal numbers until the predictions improve.</p>
<p>The idea is loosely inspired by biological neurons: many small units receive signals, combine them, and pass a result forward. In machine learning, those signals are numbers, and the things being adjusted are weights and biases.</p>
<p>This post builds that idea from the smallest useful piece: one neuron. Once that one piece is clear, every later section only answers one question: how do we make the same idea handle more inputs, more samples, harder shapes, and actual learning?</p>
<p>Companion notebook: <a href="https://github.com/backpropolis/nlp_from_scratch/blob/main/src/0.neural_net/0.%20neural_network_from_scratch.ipynb"><code>src/0.neural_net/0. neural_network_from_scratch.ipynb</code></a>. The notebook uses pure NumPy, no PyTorch, no autograd.</p>
<hr />
<h2>One Neuron</h2>
<p>The smallest neural network unit receives inputs, multiplies them by weights, adds a bias, and produces one output. This is the smallest place where the main ingredients appear: input, weight, bias, prediction, and loss.</p>
<p>With one input, the neuron is just a line:</p>
<pre><code class="language-text">output = weight * input + bias
</code></pre>
<pre><code class="language-python">x = 3
w = 0.8
b = 2

output = w * x + b
print(output)  # 4.4
</code></pre>
<ul>
<li><strong>Input</strong>: the value the model receives.</li>
<li><strong>Weight</strong>: controls how strongly the input affects the output.</li>
<li><strong>Bias</strong>: shifts the output up or down.</li>
<li><strong>Output</strong>: the prediction from this tiny model.</li>
</ul>
<p>The weight changes the slope of the line. A larger positive weight makes the output climb faster as the input grows. A negative weight flips the slope downward. The bias shifts the whole line up or down without changing the slope.</p>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/weight_bias_line.png" alt="Weight and bias line examples" />
A weight changes the slope of the line; a bias shifts the line without changing its slope.</p>
<p>With more than one input feature, one neuron still produces one output. In vector form, the neuron takes a dot product between the input vector and the weight vector, then adds one bias:</p>
<pre><code class="language-text">output = dot(inputs, weights) + bias
</code></pre>
<p>Expanded, that same dot product is just a weighted sum:</p>
<pre><code class="language-text">output = sum(inputs * weights) + bias
</code></pre>
<pre><code class="language-python">inputs = [1, 2, 3]
weights = [0.2, 0.8, -0.5]
bias = 2

output = (
    inputs[0] * weights[0]
    + inputs[1] * weights[1]
    + inputs[2] * weights[2]
    + bias
)

print(output)  # 2.3
</code></pre>
<p>Shape view for this one-neuron case:</p>
<pre><code class="language-text">inputs   [D]
weights  [D]
output   scalar
</code></pre>
<p>Drawn as a small computation graph:
<img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/1neuron.png" alt="alt text" />
Each input is first scaled by its own weight. The neuron then adds those scaled values plus one bias to produce one output.</p>
<p>The model is useful only if we can say how wrong it was. For a simple regression target, squared error is enough:</p>
<pre><code class="language-python">target = 3.0
loss = (output - target) ** 2

print(loss)  # 0.49
</code></pre>
<h3><em>Bonus: Why squared error?</em></h3>
<p>The raw error can be positive or negative:</p>
<pre><code class="language-text">error = output - target
</code></pre>
<p>If <code>output = 2.3</code> and <code>target = 3.0</code>, the error is <code>-0.7</code>. If <code>output = 3.7</code>, the error is <code>0.7</code>. Both predictions are equally wrong, but the signs are different. Squaring removes the sign:</p>
<pre><code class="language-text">(-0.7) ** 2 = 0.49
( 0.7) ** 2 = 0.49
</code></pre>
<p>Why not use absolute error?</p>
<pre><code class="language-text">loss = abs(output - target)
</code></pre>
<p>Absolute error also removes the sign, but it has a sharp corner at <code>0</code>, so the derivative is not defined exactly at the target. Away from <code>0</code>, its gradient is always either <code>-1</code> or <code>1</code>.</p>
<p>That means the gradient push has the same strength whether the model is very far from the target or already very close. Squared error changes that:</p>
<pre><code class="language-text">loss = error ** 2
dLoss/dError = 2 * error
</code></pre>
<p>When the error is large, the gradient is large. When the error gets small, the gradient also gets small. This gives training a natural braking effect near the target.</p>
<p>Why not use a fourth power?</p>
<pre><code class="language-text">loss = error ** 4
dLoss/dError = 4 * error ** 3
</code></pre>
<p>Now the loss becomes too sensitive. A small error like <code>0.5</code> gives a tiny gradient, while a large error like <code>10</code> gives a gradient of <code>4000</code>. Squared error is a useful middle ground for this first regression example: it removes the sign, gives smooth gradients, and makes larger mistakes matter more without being as extreme as higher powers.</p>
<p>For classification, we will switch to cross-entropy later. Squared error is only here because it is the simplest loss for understanding one numeric prediction.</p>
<p>The output is the prediction. The loss is the penalty. Training is the process of changing the weights and bias so the loss gets smaller.</p>
<p>The important distinction is that inputs come from data, while weights and biases belong to the model. During training, the input values stay fixed for a given sample; the model changes its weights and biases to make better outputs.</p>
<p>This hand-written neuron is useful because every number is visible. It is also obviously not how we want to write a real model, so the next step is to replace the repeated arithmetic with array operations.</p>
<hr />
<h2>Arrays, Matrices, and Tensors</h2>
<p>The previous neuron had three inputs and three weights. A real model may have millions, so the first upgrade is not conceptual; it is notation. The same weighted sum can be written as a dot product between an input vector and a weight vector.</p>
<pre><code class="language-python">inputs = np.array([1, 2, 3])
weights = np.array([0.2, 0.8, -0.5])
bias = 2

output = inputs @ weights + bias
</code></pre>
<p>Shape view:</p>
<pre><code class="language-text">inputs   [D]
weights  [D]
output   scalar
</code></pre>
<p>The dot product does exactly what the hand-written neuron did:</p>
<pre><code class="language-text">inputs @ weights
= inputs[0] * weights[0]
  + inputs[1] * weights[1]
  + inputs[2] * weights[2]
</code></pre>
<p>To produce multiple outputs, put many weight vectors side by side in a matrix:</p>
<pre><code class="language-text">x    [D]
W    [D, H]
b    [H]
out  [H] = x @ W + b
</code></pre>
<p>To process many samples at once, stack the samples into a batch:</p>
<pre><code class="language-text">X    [B, D]    # B samples, D features per sample
W    [D, H]    # D input features, H output features
b    [1, H]    # broadcast across the batch
out  [B, H] = X @ W + b
</code></pre>
<p>This is the shape convention used through the rest of the post:</p>
<pre><code class="language-text">Rows are samples.
Columns are features.
</code></pre>
<p>Matrix multiplication has one rule that matters here: the inner dimensions must match.</p>
<pre><code class="language-text">X @ W
[B, D] @ [D, H] -&gt; [B, H]
</code></pre>
<p>The <code>D</code> dimensions disappear into dot products. The remaining dimensions become the output shape: one row per sample, one column per output feature.</p>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/matrix_multiplication.png" alt="Matrix multiplication shape diagram" /></p>
<p>In deep learning code, "tensor" usually means a multidimensional array. A vector is a 1D tensor, a matrix is a 2D tensor, and a batch of images might be a 4D tensor like <code>[B, H, W, C]</code>. Arrays also need to be rectangular along each dimension: every row in a matrix must have the same number of columns, otherwise it is just a ragged Python list and not a useful numeric array.</p>
<p>Once the shapes are written this way, the next abstraction is almost forced: package <code>X @ W + b</code> into a reusable layer.</p>
<hr />
<h2>Dense Layer</h2>
<p>A Dense layer is the array version of many neurons sitting side by side. Every neuron receives the same input vector, but each neuron owns a different weight column and a different bias. The layer wraps <code>X @ W + b</code>, takes a batch of vectors, and projects each vector into a new feature space.</p>
<p>For the first pass, ignore gradients and look only at the forward computation.</p>
<pre><code class="language-python">class Dense:
    def __init__(self, n_in, n_out, rng, init="xavier"):
        if init == "he":
            scale = np.sqrt(2.0 / n_in)
        elif init == "xavier":
            scale = np.sqrt(1.0 / n_in)
        else:
            raise ValueError(f"unknown init: {init}")

        self.W = rng.normal(0.0, scale, size=(n_in, n_out))
        self.b = np.zeros((1, n_out))

    def forward(self, x, training=True):
        return x @ self.W + self.b
</code></pre>
<p>For <code>B = 32</code>, <code>D = 2</code>, <code>H = 64</code>:</p>
<pre><code class="language-text">x      [32, 2]
W      [2, 64]
b      [1, 64]
out    [32, 64]
</code></pre>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/dense.png" alt="alt text" />
Caption: a Dense layer is just matrix multiplication plus a bias broadcast across the batch.</p>
<ul>
<li><strong><code>n_in</code></strong> is the number of input features.</li>
<li><strong><code>n_out</code></strong> is the number of output features.</li>
<li><strong><code>W</code></strong> stores one column per output feature.</li>
<li><strong><code>b</code></strong> is broadcast across all rows in the batch.</li>
</ul>
<p>The weight matrix shape is chosen so the forward pass does not need a transpose:</p>
<pre><code class="language-text">X [B, D] @ W [D, H] -&gt; out [B, H]
</code></pre>
<p>Some tutorials store weights as <code>[H, D]</code> and call <code>X @ W.T</code>. Both layouts represent the same math. This post stores weights as <code>[D, H]</code> because the forward pass reads directly as <code>X @ W + b</code>.</p>
<p>Weights start as small random numbers so neurons do not all behave identically. Biases usually start at zero because the weights already break symmetry; the bias can learn its offset later.</p>
<p>One Dense layer is already enough to build a linear classifier. Using the <code>Sequential</code> wrapper we define later, a <code>[B, 2]</code> input can map to 3 class scores:</p>
<pre><code class="language-python">linear_model = Sequential([
    Dense(2, 3, np.random.default_rng(100), init="xavier"),
])
</code></pre>
<pre><code class="language-text">X       [B, 2]
W       [2, 3]
b       [1, 3]
logits  [B, 3] = X @ W + b
</code></pre>
<p>The three output numbers are called <strong>logits</strong>. They are raw class scores, not probabilities. The predicted class is the index of the largest logit:</p>
<pre><code class="language-python">preds = logits.argmax(axis=1)
</code></pre>
<p>That gives us the simplest classifier worth testing. Before adding hidden layers, we should see exactly where this linear model breaks.</p>
<hr />
<h2>The First Target: Spiral Data</h2>
<p>The Dense layer can produce class scores, but a toy classifier is only interesting if the data exposes its limits. Linear data can be fit by a straight line or a few straight decision regions. Spiral data is still easy to draw, but not easy for straight lines. Each sample is a 2D point, and the label is one of three spiral arms.</p>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/spiral_dataset.png" alt="Three-class spiral dataset" /></p>
<pre><code class="language-python">def make_spiral(samples_per_class=120, n_classes=3, noise=0.20, seed=42):
    rng = np.random.default_rng(seed)
    X = np.zeros((samples_per_class * n_classes, 2), dtype=np.float64)
    y = np.zeros(samples_per_class * n_classes, dtype=np.int64)

    for class_id in range(n_classes):
        ix = slice(class_id * samples_per_class, (class_id + 1) * samples_per_class)
        r = np.linspace(0.0, 1.0, samples_per_class)
        t = np.linspace(class_id * 4.0, (class_id + 1) * 4.0, samples_per_class)
        t = t + rng.normal(0.0, noise, samples_per_class)
        X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]
        y[ix] = class_id

    return X, y
</code></pre>
<p>The shapes are small:</p>
<pre><code class="language-text">X       [360, 2]    # 360 points, each point has x1 and x2
y       [360]       # integer labels: 0, 1, 2
logits  [360, 3]    # one score per class
</code></pre>
<p>Read the plot literally: each dot is one training example, and the color is the label. The word "spiral" only describes the shape of the toy dataset. We use it because a straight line cannot separate the classes, but the data is still small enough to debug.</p>
<p>Each sample has two features:</p>
<pre><code class="language-text">sample = [x1, x2]
target = class_id
</code></pre>
<p>The colors in the plot are only for us. The model does not see red, green, or blue. It only sees two coordinates and a target label like <code>0</code>, <code>1</code>, or <code>2</code>.</p>
<p>The one-layer linear model exposes the first failure mode:</p>
<pre><code class="language-text">Linear model:
X [B, 2] -&gt; Dense(2, 3) -&gt; logits [B, 3]
</code></pre>
<p>With the notebook seed, the linear baseline reaches <code>48.6%</code> validation accuracy (<code>54.5%</code> train accuracy). It learns three broad regions split by straight lines, but the spiral needs a boundary that bends.</p>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/linear_vs_mlp_boundary.png" alt="Linear model versus MLP on the spiral dataset" /></p>
<p>The important point: the linear baseline does not fail because the optimizer is bad. It fails because one Dense layer can only draw linear boundaries. A hidden layer gives the model more room, but only if we add something that prevents stacked Dense layers from collapsing back into one linear map.</p>
<hr />
<h2>ReLU: Why Dense Layers Need an Activation</h2>
<p>The spiral failure suggests adding a hidden layer. But adding another Dense layer by itself does not solve the problem, because two linear transformations in a row still collapse into one linear transformation.</p>
<pre><code class="language-text">y = (X @ W1 + b1) @ W2 + b2
  = X @ (W1 @ W2) + (b1 @ W2 + b2)
  = X @ W' + b'
</code></pre>
<p>Without a nonlinearity, stacking Dense layers only creates a bigger linear model. ReLU breaks that collapse with one small function:</p>
<pre><code class="language-python">class ReLU:
    def forward(self, x, training=True):
        self.mask = x &gt; 0
        return np.maximum(0.0, x)

    def backward(self, dout):
        return dout * self.mask

    def parameters(self):
        return []
</code></pre>
<pre><code class="language-text">ReLU(x) = max(0, x)
</code></pre>
<ul>
<li><strong>Forward</strong>: positive values pass through, negative values become <code>0</code>.</li>
<li><strong>Backward</strong>: gradients pass only through positions that were positive during the forward pass.</li>
<li><strong>Effect</strong>: many ReLU units split the input space into small linear regions that can bend around the spiral.</li>
</ul>
<p>The step function is the simplest "fire or do not fire" activation, but it throws away too much information: every positive input becomes the same <code>1</code>, and every negative input becomes the same <code>0</code>. ReLU keeps the useful part of that idea without collapsing all positive values together.</p>
<pre><code class="language-text">step(-0.1) = 0      step(100.0) = 1
ReLU(-0.1) = 0      ReLU(100.0) = 100.0
</code></pre>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/relu_vs_step.png" alt="Step function versus ReLU" />
Step only says active or inactive. ReLU keeps the positive magnitude, which gives later layers more useful signal.</p>
<p>That difference matters for learning. A ReLU neuron has an activation region: inputs on one side of its threshold are silent, and inputs on the other side pass through with their size preserved. Many such regions can approximate a curved boundary with piecewise-linear segments.</p>
<p>Our main MLP only adds one hidden Dense layer and one ReLU:</p>
<pre><code class="language-python">model = Sequential([
    Dense(2, 64, np.random.default_rng(101), init="he"),
    ReLU(),
    Dense(64, 3, np.random.default_rng(102), init="xavier"),
])
</code></pre>
<pre><code class="language-text">X          [B, 2]
Dense1     [B, 64]
ReLU       [B, 64]
Dense2     [B, 3]
logits     [B, 3]
</code></pre>
<p>The first Dense layer creates 64 hidden features. ReLU gates those features. The second Dense layer mixes the gated features into 3 class scores.</p>
<p>ReLU gives the model the shape it was missing. The next problem is different: the model now returns three raw scores per point, so we need a clean way to read those scores as class predictions and training loss.</p>
<hr />
<h2>Softmax: From Logits to Class Probabilities</h2>
<p>The ReLU MLP ends with logits: raw class scores. For prediction, we only need the largest logit:</p>
<pre><code class="language-python">def accuracy(model, X, y):
    logits = model.forward(X, training=False)
    preds = logits.argmax(axis=1)
    return (preds == y).mean()
</code></pre>
<p>Softmax is useful when we want class probabilities and a classification loss. It does two things:</p>
<ol>
<li>Exponentiate logits so every value becomes positive.</li>
<li>Normalize each row so the values sum to 1.</li>
</ol>
<pre><code class="language-python">shifted = logits - logits.max(axis=1, keepdims=True)
exp_scores = np.exp(shifted)
probs = exp_scores / exp_scores.sum(axis=1, keepdims=True)
</code></pre>
<pre><code class="language-text">logits  [B, C]
probs   [B, C]
y       [B]
</code></pre>
<p>Each row of <code>probs</code> sums to <code>1</code>. The largest probability points to the predicted class, but the probabilities also tell us how confident the model was.</p>
<pre><code class="language-text">logits row:  [4.8, 1.2, 2.4]
softmax row: [0.90, 0.02, 0.08]
prediction:  class 0
</code></pre>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/softmax_logits_probs.png" alt="Logits and softmax probabilities" />
Softmax keeps the winning class the same, but converts raw scores into probabilities.</p>
<p>The exponential is monotonic: a larger logit still becomes a larger exponentiated value. That means softmax does not change which class wins; it changes raw scores into comparable confidence values.</p>
<p>Cross-entropy penalizes the model when the correct class gets low probability:</p>
<pre><code class="language-python">correct_probs = probs[np.arange(len(y)), y]
loss = -np.log(correct_probs + 1e-12).mean()
</code></pre>
<p>For sparse labels, <code>y</code> contains class indices:</p>
<pre><code class="language-text">probs:
  sample 0 -&gt; [0.70, 0.10, 0.20]
  sample 1 -&gt; [0.10, 0.50, 0.40]
  sample 2 -&gt; [0.02, 0.90, 0.08]

y = [0, 1, 1]

correct_probs = [0.70, 0.50, 0.90]
losses = -log(correct_probs)
</code></pre>
<p>Cross-entropy only needs the probability assigned to the correct class. If the correct class gets probability near <code>1</code>, the loss is near <code>0</code>. If it gets probability near <code>0</code>, the loss becomes very large.</p>
<p>The subtraction in stable softmax is a numerical trick:</p>
<pre><code class="language-text">softmax([1000, 1001, 1002])
== softmax([-2, -1, 0])
</code></pre>
<p>Softmax contains <code>exp</code>, so large logits can overflow. Subtracting the per-sample max keeps the numbers safe without changing the probabilities.</p>
<p>In the loss, we also clip or add a tiny epsilon around probabilities before <code>log</code>. The reason is practical: <code>-log(0)</code> is infinite, and one infinite value can ruin the whole training step.</p>
<p>Now we have a scalar loss. The loss tells us how wrong the model is; backpropagation tells us how each weight should move to reduce it.</p>
<hr />
<h2>Backpropagation</h2>
<p>The forward pass produced logits, and cross-entropy turned those logits into one loss number. Training needs the reverse path: how did each parameter affect that loss? A gradient is that sensitivity: if this weight moves a little, how does the loss move?</p>
<p>Start with a one-variable function:</p>
<pre><code class="language-text">y = f(x)
</code></pre>
<p>The derivative tells us the slope at a point. For a line, the slope is constant. For a curve, the slope depends on where we measure it. In training, the "curve" is the loss as a function of every weight and bias in the model.</p>
<p>Neural networks have many parameters, so we need <strong>partial derivatives</strong>:</p>
<pre><code class="language-text">dLoss/dW1    how much W1 affected the loss
dLoss/db1    how much b1 affected the loss
dLoss/dX     how much the layer input affected the loss
</code></pre>
<p>Backpropagation is chain rule bookkeeping. The model is a chain of functions:</p>
<pre><code class="language-text">X -&gt; Dense1 -&gt; ReLU -&gt; Dense2 -&gt; SoftmaxCrossEntropy -&gt; loss
</code></pre>
<pre><code class="language-mermaid">graph LR
    X["X&lt;br/&gt;[B, 2]"] --&gt; D1["Dense1&lt;br/&gt;[B, 64]"]
    D1 --&gt; R["ReLU&lt;br/&gt;[B, 64]"]
    R --&gt; D2["Dense2&lt;br/&gt;logits [B, 3]"]
    D2 --&gt; L["SoftmaxCrossEntropy&lt;br/&gt;loss scalar"]
    L -. "dlogits [B, 3]" .-&gt; D2B["Dense2.backward"]
    D2B -. "dhidden [B, 64]" .-&gt; RB["ReLU.backward"]
    RB -. "dhidden [B, 64]" .-&gt; D1B["Dense1.backward"]

    style X fill:#DBEAFE,stroke:#3B82F6,color:#111827
    style D1 fill:#DCFCE7,stroke:#10B981,color:#111827
    style R fill:#DCFCE7,stroke:#10B981,color:#111827
    style D2 fill:#DCFCE7,stroke:#10B981,color:#111827
    style L fill:#FEE2E2,stroke:#EF4444,color:#111827
    style D2B fill:#FEF3C7,stroke:#F59E0B,color:#111827
    style RB fill:#FEF3C7,stroke:#F59E0B,color:#111827
    style D1B fill:#FEF3C7,stroke:#F59E0B,color:#111827
</code></pre>
<p>Caption: forward values move left to right. Gradients start at the loss and move backward through the same layers in reverse order.</p>
<p>The gradient starts at the loss and moves backward through that chain. Each layer receives an incoming gradient, multiplies it by its local derivative, stores gradients for its own parameters, then returns the gradient for the previous layer.</p>
<p>That gives each layer two concrete jobs:</p>
<pre><code class="language-text">1. Compute gradients for its own parameters.
2. Return the gradient for the layer before it.
</code></pre>
<p>In code, trainable arrays are easier to manage if each one stores both its value and gradient:</p>
<pre><code class="language-python">class Parameter:
    """Trainable array plus its gradient."""

    def __init__(self, value):
        self.value = np.asarray(value, dtype=np.float64)
        self.grad = np.zeros_like(self.value)

    def zero_grad(self):
        self.grad.fill(0.0)
</code></pre>
<p>Now the Dense layer can cache its input during the forward pass and reuse it during the backward pass:</p>
<pre><code class="language-python">class Dense:
    def __init__(self, n_in, n_out, rng, init="he"):
        if init == "he":
            scale = np.sqrt(2.0 / n_in)
        elif init == "xavier":
            scale = np.sqrt(1.0 / n_in)
        else:
            raise ValueError(f"unknown init: {init}")

        self.W = Parameter(rng.normal(0.0, scale, size=(n_in, n_out)))
        self.b = Parameter(np.zeros((1, n_out)))

    def forward(self, x, training=True):
        self.x = x
        return x @ self.W.value + self.b.value

    def backward(self, dout):
        self.W.grad[...] = self.x.T @ dout
        self.b.grad[...] = dout.sum(axis=0, keepdims=True)
        return dout @ self.W.value.T

    def parameters(self):
        return [self.W, self.b]
</code></pre>
<p>Shape view:</p>
<pre><code class="language-text">Forward:
  x      [B, D]
  W      [D, H]
  b      [1, H]
  out    [B, H]

Backward:
  dout   [B, H]
  dW     [D, H] = x.T @ dout
  db     [1, H] = sum(dout over batch)
  dx     [B, D] = dout @ W.T
</code></pre>
<ul>
<li><strong><code>dout</code></strong> is the gradient arriving from the next layer.</li>
<li><strong><code>W.grad</code></strong> has the same shape as <code>W.value</code>, because the optimizer updates every weight.</li>
<li><strong><code>b.grad</code></strong> sums over the batch because the same bias is broadcast to every sample.</li>
<li><strong><code>dx</code></strong> is not a parameter update. It is the gradient passed to the previous layer.</li>
</ul>
<p>Why is <code>dW = x.T @ dout</code>? Each weight connects one input feature to one output neuron. For a batch, the gradient for that weight accumulates the product of:</p>
<pre><code class="language-text">input feature value * incoming gradient for that neuron
</code></pre>
<p>Writing all those products at once gives:</p>
<pre><code class="language-text">x.T    [D, B]
dout   [B, H]
dW     [D, H]
</code></pre>
<p>Why is <code>db = sum(dout)</code>? The same bias is added to every sample in the batch, so its total effect is the sum of all incoming gradients for that output neuron.</p>
<p>Why is <code>dx = dout @ W.T</code>? The previous layer needs to know how the current layer's output depends on its input. The weights tell us how strongly each input feature contributed to each output feature, so the gradient flows back through <code>W.T</code>.</p>
<p>For softmax plus cross-entropy, the gradient has a compact form:</p>
<pre><code class="language-python">class SoftmaxCrossEntropy:
    def forward(self, logits, y):
        shifted = logits - logits.max(axis=1, keepdims=True)
        exp_scores = np.exp(shifted)
        self.probs = exp_scores / exp_scores.sum(axis=1, keepdims=True)
        self.y = y

        correct_probs = self.probs[np.arange(len(y)), y]
        return -np.log(correct_probs + 1e-12).mean()

    def backward(self):
        grad = self.probs.copy()
        grad[np.arange(len(self.y)), self.y] -= 1.0
        grad /= len(self.y)
        return grad
</code></pre>
<p>For one sample whose correct class is <code>2</code>:</p>
<pre><code class="language-text">probs before: [0.70, 0.20, 0.10]
one_hot(y):   [0.00, 0.00, 1.00]
gradient:     [0.70, 0.20, -0.90]
</code></pre>
<p>Positive gradients on the wrong classes push those logits down. The negative gradient on the correct class pushes that logit up.</p>
<p>That compact gradient is the reason many implementations combine Softmax and Cross-Entropy into one class for backward. Calculating the Softmax Jacobian separately is possible, but the combined derivative simplifies to:</p>
<pre><code class="language-text">dlogits = (probs - one_hot(y)) / batch_size
</code></pre>
<p>At this point each layer knows how to run forward and backward. The next piece is only plumbing: connect the layers so the whole model behaves like one object.</p>
<hr />
<h2>Sequential: A Tiny Framework</h2>
<p>The Dense and ReLU layers now share the same pattern: run forward, keep the state needed for backward, then send gradients back. The loss function will stay outside the model, and <code>Sequential</code> will connect the model layers into one object.</p>
<pre><code class="language-python">class Sequential:
    def __init__(self, layers):
        self.layers = layers

    def forward(self, x, training=True):
        for layer in self.layers:
            x = layer.forward(x, training=training)
        return x

    def backward(self, grad):
        for layer in reversed(self.layers):
            grad = layer.backward(grad)
        return grad

    def parameters(self):
        params = []
        for layer in self.layers:
            params.extend(layer.parameters())
        return params

    def zero_grad(self):
        for param in self.parameters():
            param.zero_grad()
</code></pre>
<p>Forward goes left to right:</p>
<pre><code class="language-text">X -&gt; Dense1 -&gt; ReLU -&gt; Dense2 -&gt; logits -&gt; loss
</code></pre>
<p>Backward goes right to left:</p>
<pre><code class="language-text">dlogits -&gt; Dense2.backward -&gt; ReLU.backward -&gt; Dense1.backward
</code></pre>
<p>Layers with parameters expose <code>Parameter</code> objects to the optimizer. Layers without parameters, like ReLU, only pass gradients along.</p>
<p>After <code>backward</code>, every trainable parameter has a gradient. Those gradients still do nothing until an optimizer uses them to change the parameter values.</p>
<hr />
<h2>Optimizer: SGD</h2>
<p>Backpropagation computes gradients; SGD uses them. It does not need to know which layer a parameter came from. It only sees each <code>Parameter</code> and moves its <code>value</code> in the opposite direction of <code>grad</code>.</p>
<pre><code class="language-python">class SGD:
    def __init__(self, lr=0.75):
        self.lr = lr

    def step(self, params):
        for param in params:
            param.value -= self.lr * param.grad
</code></pre>
<p>The word "descent" means we move downhill on the loss curve. If the gradient points in the direction where loss increases fastest, <code>-gradient</code> points toward lower loss.</p>
<p>Before gradients, one naive idea is random search: try random weights, keep them if loss improves, and repeat. That can work on tiny examples, but it scales terribly because a real network has thousands or millions of parameters. Gradients give direction instead of blind guessing.</p>
<p>The learning rate controls how large each update step is:</p>
<table>
<thead>
<tr>
<th align="right"><code>lr</code></th>
<th>Typical behavior</th>
</tr>
</thead>
<tbody><tr>
<td align="right">Too small</td>
<td>Loss decreases very slowly</td>
</tr>
<tr>
<td align="right">About right</td>
<td>Loss decreases smoothly, accuracy rises</td>
</tr>
<tr>
<td align="right">Too large</td>
<td>Loss jumps around or becomes <code>nan</code></td>
</tr>
</tbody></table>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/sgd_learning_rate.png" alt="Learning rate step sizes on a loss curve" />
The gradient gives the downhill direction. The learning rate decides how far to step in that direction.</p>
<p>SGD optimizes loss, not accuracy directly. Accuracy can sometimes stay flat while loss improves because the model is becoming more confident on already-correct samples, or less wrong on hard samples, before enough predictions flip to change accuracy.</p>
<p>In the notebook, <code>lr = 0.75</code> works well for the small MLP on the spiral dataset with He initialization. If you change hidden size, noise, normalization, or batch size, the best learning rate can change too.</p>
<p>We now have every moving part: model, loss, gradients, and optimizer. The full training loop is just those parts in the right order.</p>
<hr />
<h2>Training the MLP</h2>
<p>All previous sections were pieces of this loop. Now they run together: forward pass, loss, backward pass, parameter update, then repeat.</p>
<pre><code class="language-mermaid">graph TD
    DATA["X_train, y_train&lt;br/&gt;batch data"] --&gt; FWD["model.forward&lt;br/&gt;logits"]
    FWD --&gt; LOSS["loss_fn.forward&lt;br/&gt;scalar loss"]
    LOSS --&gt; ZERO["model.zero_grad&lt;br/&gt;clear old grads"]
    ZERO --&gt; BWD["loss_fn.backward + model.backward&lt;br/&gt;write gradients"]
    BWD --&gt; STEP["optimizer.step&lt;br/&gt;update parameters"]
    STEP --&gt; NEXT["next epoch"]
    NEXT --&gt; DATA
    FWD --&gt; EVAL["accuracy on train/val&lt;br/&gt;training=False"]

    style DATA fill:#DBEAFE,stroke:#3B82F6,color:#111827
    style FWD fill:#DCFCE7,stroke:#10B981,color:#111827
    style LOSS fill:#FEE2E2,stroke:#EF4444,color:#111827
    style ZERO fill:#FEF3C7,stroke:#F59E0B,color:#111827
    style BWD fill:#FEF3C7,stroke:#F59E0B,color:#111827
    style STEP fill:#DCFCE7,stroke:#10B981,color:#111827
    style NEXT fill:#E0E7FF,stroke:#6366F1,color:#111827
    style EVAL fill:#F3E8FF,stroke:#8B5CF6,color:#111827
</code></pre>
<p>Caption: the training loop repeats the same sequence: predict, measure loss, clear gradients, backpropagate, update parameters, and evaluate without training-only behavior.</p>
<pre><code class="language-python">loss_fn = SoftmaxCrossEntropy()
optimizer = SGD(lr=0.75)

for epoch in range(2001):
    logits = model.forward(X_train, training=True)
    loss = loss_fn.forward(logits, y_train)

    model.zero_grad()
    model.backward(loss_fn.backward())
    optimizer.step(model.parameters())

    if epoch % 100 == 0:
        train_acc = accuracy(model, X_train, y_train)
        val_acc = accuracy(model, X_val, y_val)
        print(epoch, loss, train_acc, val_acc)
</code></pre>
<p>One concrete pass:</p>
<pre><code class="language-text">1. model.forward
   X_train [288, 2] -&gt; logits [288, 3]

2. loss_fn.forward
   logits [288, 3] + y_train [288] -&gt; scalar loss

3. loss_fn.backward
   scalar loss -&gt; dlogits [288, 3]

4. model.zero_grad
   clear old gradients before writing new ones

5. model.backward
   dlogits -&gt; dW2, db2, dW1, db1

6. optimizer.step
   W1, b1, W2, b2 move a little bit
</code></pre>
<p>One full pass over the training data is called an epoch. This notebook uses the whole training set in each update, which keeps the code simple. In larger training runs, the same logic usually runs on mini-batches:</p>
<pre><code class="language-text">full-batch:  one update uses all training samples
mini-batch:  one update uses a smaller slice, like 32 or 128 samples
</code></pre>
<p>Mini-batches are faster on hardware and usually produce updates that generalize better than fitting one sample at a time.</p>
<p>After a few hundred epochs, loss drops clearly. With the notebook seed, the final MLP reaches <code>98.6%</code> validation accuracy and <code>99.7%</code> train accuracy. The number is not the main lesson; the decision boundary is.</p>
<p>The linear model creates hard straight boundaries. The MLP creates a piecewise-linear boundary with enough small pieces to wrap around the spiral. The network does not hard-code a curved formula; it learns to stitch many local linear maps together.</p>
<p>That result is good, but it is still only meaningful if the model works beyond the exact points it trained on.</p>
<hr />
<h2>Validation Data and Test Data</h2>
<p>The training loop can make training loss go down even when the model is memorizing. Low training loss does not guarantee the model learned the real pattern. That is why we split the data.</p>
<pre><code class="language-mermaid">graph LR
    DATASET["full dataset&lt;br/&gt;X, y"] --&gt; SHUFFLE["shuffle indices"]
    SHUFFLE --&gt; TRAIN["training split&lt;br/&gt;updates weights"]
    SHUFFLE --&gt; VAL["validation split&lt;br/&gt;chooses settings"]
    SHUFFLE --&gt; TEST["test split&lt;br/&gt;final check only"]

    style DATASET fill:#DBEAFE,stroke:#3B82F6,color:#111827
    style SHUFFLE fill:#DCFCE7,stroke:#10B981,color:#111827
    style TRAIN fill:#FEF3C7,stroke:#F59E0B,color:#111827
    style VAL fill:#E0E7FF,stroke:#6366F1,color:#111827
    style TEST fill:#FEE2E2,stroke:#EF4444,color:#111827
</code></pre>
<p>Caption: training data changes the parameters, validation data guides development choices, and test data should stay untouched until the end.</p>
<pre><code class="language-python">def train_val_split(X, y, val_ratio=0.20, seed=7):
    rng = np.random.default_rng(seed)
    idx = rng.permutation(len(X))
    split = int((1.0 - val_ratio) * len(X))
    train_idx, val_idx = idx[:split], idx[split:]
    return X[train_idx], y[train_idx], X[val_idx], y[val_idx]
</code></pre>
<pre><code class="language-text">Training data    used to update weights
Validation data  used to check choices during development
Test data        used once at the end
</code></pre>
<p>For this small post, the notebook uses a train/validation split. In a larger project, keep a separate test set untouched until the final evaluation.</p>
<p>The reason for the split is not ceremony. A large enough network can memorize the exact training points. On the training scatter plot, that can look impressive. On new points from the same distribution, the decision boundary may fail because it learned the accidents of the training sample rather than the rule behind the data.</p>
<p>Overfitting looks like this:</p>
<pre><code class="language-text">train loss keeps going down
train accuracy keeps going up
validation accuracy stops improving or drops
</code></pre>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/overfitting.png" alt="Overfitting loss curve and wiggly decision boundary" />
Overfitting often looks good on training data while validation performance stops improving.</p>
<p>When splitting data, avoid leakage. For ordinary shuffled tabular data, random splitting may be fine. For time-series data, random splitting can be misleading because neighboring timestamps can be almost identical. In that case, hold out whole time blocks so validation really means "future or unseen conditions."</p>
<p>The model is not done when it fits the training data. It is done when it also works on data it did not train on.</p>
<p>When validation performance starts to lag behind training performance, the next question is how to reduce memorization without removing the model's ability to learn.</p>
<hr />
<h2>Generalization: L1, L2, and Dropout</h2>
<p>Validation data tells us when the model is overfitting. Regularization is one way to respond: it adds pressure against memorization while keeping the same forward/backward/optimizer structure.</p>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/regularization_weights.png" alt="Regularization effect on weight values" />
Regularization changes the pressure on weights, not the basic training loop.</p>
<p>L2 regularization penalizes large weights. It adds a second term to the loss:</p>
<pre><code class="language-python">data_loss = loss_fn.forward(logits, y_train)
l2_loss = lambda_l2 * np.sum(W * W)
loss = data_loss + l2_loss
</code></pre>
<p>The square matters. A weight of <code>10</code> gets penalized much more than a weight of <code>1</code>, so L2 discourages the model from leaning too hard on a few large parameters.</p>
<p>The backward contribution is simple:</p>
<pre><code class="language-text">dW += 2 * lambda_l2 * W
</code></pre>
<p>L1 regularization penalizes absolute weight size:</p>
<pre><code class="language-python">data_loss = loss_fn.forward(logits, y_train)
l1_loss = lambda_l1 * np.sum(np.abs(W))
loss = data_loss + l1_loss
</code></pre>
<p>L1 pushes small weights toward exactly zero more aggressively than L2. That can make the model sparse, but it is less common to use L1 alone for basic neural networks.</p>
<p>The backward contribution is based on the sign of the weight:</p>
<pre><code class="language-text">dW += lambda_l1 * sign(W)
</code></pre>
<p>Dropout attacks memorization differently. It randomly zeroes part of an activation during training so the model cannot depend too heavily on a few hidden units:</p>
<pre><code class="language-python">class Dropout:
    def __init__(self, p=0.1, rng=None):
        if not 0.0 &lt;= p &lt; 1.0:
            raise ValueError("p must be in [0, 1).")
        self.p = p
        self.rng = rng or np.random.default_rng()

    def forward(self, x, training=True):
        if not training or self.p == 0:
            self.mask = np.ones_like(x)
            return x

        keep_prob = 1.0 - self.p
        self.mask = (self.rng.random(x.shape) &lt; keep_prob) / keep_prob
        return x * self.mask

    def backward(self, dout):
        return dout * self.mask

    def parameters(self):
        return []
</code></pre>
<p>The division by <code>keep_prob</code> is inverted dropout. If we keep only <code>90%</code> of activations, the kept activations are scaled up by <code>1 / 0.9</code> so the expected activation size stays roughly the same. That lets evaluation skip dropout entirely.</p>
<p><img src="https://backpropolis.github.io/posts/2026-03-23-neural-net/asset/dropout_mask.png" alt="Dropout mask applied to hidden activations" />
Dropout randomly hides some hidden activations during training, so the model cannot rely on the same units every time.</p>
<p>The important gotcha: dropout is on during training and off during evaluation. If you forget <code>training=False</code> during evaluation, accuracy becomes noisy because every evaluation uses a different mask.</p>
<p>By now the model has enough moving parts that most bugs are no longer syntax bugs. They are shape, order, or training-mode bugs.</p>
<hr />
<h2>Common Bugs</h2>
<ul>
<li>Forgetting to divide the gradient by batch size in <code>SoftmaxCrossEntropy.backward</code>.</li>
<li>Writing <code>dW = dout @ x.T</code> instead of <code>dW = x.T @ dout</code>.</li>
<li>Summing softmax over the wrong axis. For class probabilities, each sample row should sum to <code>1</code>.</li>
<li>Broadcasting bias correctly in forward but forgetting <code>keepdims=True</code> for <code>db</code>.</li>
<li>Returning <code>dout @ W</code> instead of <code>dout @ W.T</code> from <code>Dense.backward</code>.</li>
<li>Calling <code>optimizer.step()</code> before the full backward pass.</li>
<li>Using dropout during evaluation because <code>training=False</code> was missing.</li>
<li>Computing softmax before argmax for accuracy. It is not wrong, but it is unnecessary.</li>
</ul>
<p>Most of these mistakes come from losing track of the same three things: shapes, gradient flow, and whether the model is training or evaluating.</p>
<hr />
<h2>Key Takeaway</h2>
<p>The full model looks larger than the first neuron, but it is built from the same idea repeated carefully. At the basic level, a neural network is not a black box. In this post, the whole model is a few NumPy matrices, a ReLU mask, a stable softmax, and an SGD loop.</p>
<pre><code class="language-text">Neural network =
  linear projections
  + nonlinear activations
  + a loss function
  + backpropagation
  + an optimizer
</code></pre>
<p>Frameworks like PyTorch automate backward passes and parameter management, but the learning logic is still this loop: predict, measure the error, send the error backward, and update the parameters.</p>
<h2>References</h2>
<ul>
<li>CS231n, <a href="https://cs231n.github.io/neural-networks-case-study/">Neural Network Case Study</a> - spiral dataset and a 2-layer neural network, excellent for a first lesson.</li>
<li>Harrison Kinsley and Daniel Kukiela, <em>Neural Networks from Scratch in Python</em> - the local PDF used for the neuron, Dense layer, activation, loss, optimizer, backpropagation, and regularization explanations.</li>
<li>NumPy Tutorials, <a href="https://numpy.org/numpy-tutorials/tutorial-deep-learning-on-mnist/">Deep learning on MNIST</a> - an MLP-from-scratch example on MNIST.</li>
<li>Karpathy, <a href="https://github.com/karpathy/micrograd">micrograd</a> - a tiny scalar autograd engine, good for a longer session on computational graphs.</li>
</ul>
]]></content:encoded></item></channel></rss>