惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Full Disclosure
V
Vulnerabilities – Threatpost
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
SecWiki News
SecWiki News
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
B
Blog
TaoSecurity Blog
TaoSecurity Blog
The Last Watchdog
The Last Watchdog
H
Hacker News: Front Page
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园_首页
D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Y
Y Combinator Blog
W
WeLiveSecurity
N
News and Events Feed by Topic
F
Fortinet All Blogs
PCI Perspectives
PCI Perspectives
WordPress大学
WordPress大学
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
Forbes - Security
Forbes - Security
T
Tailwind CSS Blog
Hacker News: Ask HN
Hacker News: Ask HN
爱范儿
爱范儿
腾讯CDC
Last Week in AI
Last Week in AI
月光博客
月光博客
C
Cybersecurity and Infrastructure Security Agency CISA
P
Proofpoint News Feed
Help Net Security
Help Net Security
V
V2EX
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
H
Heimdal Security Blog
L
LINUX DO - 最新话题
GbyAI
GbyAI
The Hacker News
The Hacker News
罗磊的独立博客
S
SegmentFault 最新的问题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 【当耐特】
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V2EX - 技术
V2EX - 技术
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
O
OpenAI News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Chapter 10: Multi-Head Attention and the MLP Block
Gary Jackson · 2026-04-30 · via DEV Community

What You'll Build

Multi-head attention (running several attention computations in parallel, each on its own slice of the per-token embedding vector) and the MLP block (a two-layer feed-forward network for per-position "thinking"). Both concepts are introduced here and implemented in Model.cs in Chapter 11.

Depends On

Chapters 5, 8, 9 (Helpers, RmsNorm, residual connections, single-head attention).

Why Multiple Heads?

A single attention head can only learn one kind of "what am I looking for?" pattern. With multiple heads, the model can look for different kinds of relationships at the same time. In larger models with bigger embedding dimensions, individual heads often specialise in distinct patterns (one might track syntax, another semantics). At our small scale (headDimension = 4), the specialisation is fuzzier, but the mechanism is the same.

The trick: instead of running 4 full-size attention computations, we split the embedding dimension into 4 slices. If embeddingSize = 16 and headCount = 4, each head operates on 4 dimensions (headDimension = 4). This doesn't lose information because the projections (queryWeights, keyWeights, valueWeights) can learn to put related information into the same slice. The heads compute independently and their outputs are concatenated (not averaged or summed) back to the full embedding size. Concatenation keeps all the per-head information in distinct dimensions, so nothing is lost before the next step.

Multi-Head Attention

// Shape reference - integrated into GptModel.Forward in Chapter 11.
// The for loop is sequential, but conceptually each head is independent.
// In production, all heads are computed in a single matrix multiply on a GPU.

var concatenatedHeads = new List<Value>();

for (int h = 0; h < headCount; h++)
{
    int headStart = h * headDimension;
    List<Value> queryForHead = q.GetRange(headStart, headDimension);

    var attentionLogits = new List<Value>();
    for (int t = 0; t < cachedKeys.Count; t++)
    {
        List<Value> keyForHead = cachedKeys[t].GetRange(headStart, headDimension);
        var dot = new Value(0);
        for (int j = 0; j < headDimension; j++)
        {
            dot += queryForHead[j] * keyForHead[j];
        }

        attentionLogits.Add(dot / Math.Sqrt(headDimension));
    }

    List<Value> attentionWeights = Helpers.Softmax(attentionLogits);

    var headOutput = new List<Value>();
    for (int j = 0; j < headDimension; j++)
    {
        headOutput.Add(new Value(0));
    }

    for (int t = 0; t < cachedValues.Count; t++)
    {
        List<Value> valueForHead = cachedValues[t].GetRange(headStart, headDimension);
        Value w = attentionWeights[t];
        for (int j = 0; j < headDimension; j++)
        {
            headOutput[j] += w * valueForHead[j];
        }
    }

    concatenatedHeads.AddRange(headOutput); // concatenate this head's output
}

// After concatenation, project through outputWeights to mix information across heads
x = Helpers.Linear(concatenatedHeads, outputWeights);

Enter fullscreen mode Exit fullscreen mode

The final Linear(concatenatedHeads, outputWeights) is important. After concatenation, each dimension still belongs to a single head. The outputWeights projection mixes information across heads, letting the model combine what different heads found.

The MLP Block

MLP stands for Multi-Layer Perceptron, a generic term for a stack of linear layers with nonlinearities between them. In transformers it's specifically a two-layer feed-forward network.

Attention is the communication mechanism (tokens talk to each other). The MLP is the computation mechanism (each position "thinks" independently). Concretely, it projects up to 4x the embedding dimension, applies ReLU, then projects back down.

// Shape reference - integrated into GptModel.Forward in Chapter 11.

x = Helpers.Linear(x, mlpUpWeights); // project up: embeddingSize -> 4*embeddingSize
x = [.. x.Select(xi => xi.Relu())]; // nonlinearity
x = Helpers.Linear(x, mlpDownWeights); // project down: 4*embeddingSize -> embeddingSize

Enter fullscreen mode Exit fullscreen mode

Why project up and then back down? The wider intermediate layer gives the model more "room to think" (more dimensions to combine features in) before compressing back to the residual stream size.

We use ReLU here for simplicity. Production transformers typically use smoother variants like GeLU or SwiGLU, but the role is the same: introduce a nonlinearity between the two linear projections.

The Transformer Block

A single transformer layer combines attention and MLP, each wrapped with RMSNorm and a residual connection:

// Shape reference - integrated into GptModel.Forward in Chapter 11.

// Attention with residual
var xResidual = new List<Value>(x);
x = Helpers.RmsNorm(x);
x = /* multi-head attention + outputWeights projection */;
for (int i = 0; i < embeddingSize; i++)
{
    x[i] += xResidual[i];
}

// MLP with residual
xResidual = new List<Value>(x);
x = Helpers.RmsNorm(x);
x = /* MLP block */;
for (int i = 0; i < embeddingSize; i++)
{
    x[i] += xResidual[i];
}

Enter fullscreen mode Exit fullscreen mode

Stacking Blocks

Our model uses layerCount = 1 (a single block), but the architecture supports stacking multiple blocks in sequence. Each block reads from and writes to the same residual stream:

Embeddings
    ↓
┌─ Block 1 ─┐
│ Attention  │
│ MLP        │
└────────────┘
    ↓
┌─ Block 2 ─┐
│ Attention  │
│ MLP        │
└────────────┘
    ↓
   ...
    ↓
┌─ Block N ─┐
│ Attention  │
│ MLP        │
└────────────┘
    ↓
Output projection (lmHead)

Enter fullscreen mode Exit fullscreen mode

Deeper models (more blocks) can learn more complex patterns because each block refines the representation further. GPT-2's largest variant used 48 blocks.

Exercise: Multi-Head Attention + MLP

Like Chapter 9, this exercise uses hand-crafted Q/K/V so you can see the behaviour rather than waiting for training to discover it. The setup: embeddingSize = 8, headCount = 2, headDimension = 4, three cached positions. Head 0's Q slice is aligned with K[1], and head 1's Q slice is aligned with K[2], so the two heads should attend to different positions. After the demo, a second pass runs an MLP block on a fixed input to show the up-project → ReLU → down-project shape change.

Create Chapter10Exercise.cs:

// --- Chapter10Exercise.cs ---

using static MicroGPT.Helpers;

namespace MicroGPT;

public static class Chapter10Exercise
{
    public static void Run()
    {
        MultiHeadAttentionDemo();
        Console.WriteLine();
        MlpBlockDemo();
    }

    // Hand-crafted multi-head attention on a 3-position sequence.
    // embeddingSize = 8, headCount = 2, headDimension = 4. Head 0 and Head 1 are set up to
    // attend to *different* positions so we can see the independence.
    private static void MultiHeadAttentionDemo()
    {
        const int EmbeddingSize = 8;
        const int HeadCount = 2;
        const int HeadDimension = EmbeddingSize / HeadCount;

        // Each cached key has two halves: the first 4 dims serve head 0,
        // the last 4 dims serve head 1. Both halves happen to match here,
        // but they could be completely different - each head only reads its slice.
        var cachedKeys = new List<List<Value>>
        {
            new() { new(1), new(0), new(0), new(0), new(1), new(0), new(0), new(0) }, // K[0]
            new() { new(0), new(1), new(0), new(0), new(0), new(1), new(0), new(0) }, // K[1]
            new() { new(0), new(0), new(1), new(0), new(0), new(0), new(1), new(0) }, // K[2]
        };

        var cachedValues = new List<List<Value>>
        {
            new() { new(10), new(0), new(0), new(0), new(100), new(0), new(0), new(0) }, // V[0]
            new() { new(0), new(20), new(0), new(0), new(0), new(200), new(0), new(0) }, // V[1]
            new() { new(0), new(0), new(30), new(0), new(0), new(0), new(300), new(0) }, // V[2]
        };

        // Q is designed so head 0 matches K[1] and head 1 matches K[2].
        //    head 0 slice                head 1 slice
        var query = new List<Value>
        {
            new(0),
            new(5),
            new(0),
            new(0),
            new(0),
            new(0),
            new(5),
            new(0),
        };

        var concatenatedHeads = new List<Value>();

        for (int h = 0; h < HeadCount; h++)
        {
            int headStart = h * HeadDimension;
            List<Value> queryForHead = query.GetRange(headStart, HeadDimension);

            var attentionLogits = new List<Value>();
            for (int t = 0; t < cachedKeys.Count; t++)
            {
                List<Value> keyForHead = cachedKeys[t].GetRange(headStart, HeadDimension);
                var dot = new Value(0);
                for (int j = 0; j < HeadDimension; j++)
                {
                    dot += queryForHead[j] * keyForHead[j];
                }

                attentionLogits.Add(dot / Math.Sqrt(HeadDimension));
            }

            List<Value> attentionWeights = Softmax(attentionLogits);

            var headOutput = new List<Value>();
            for (int j = 0; j < HeadDimension; j++)
            {
                headOutput.Add(new Value(0));
            }

            for (int t = 0; t < cachedValues.Count; t++)
            {
                List<Value> valueForHead = cachedValues[t].GetRange(headStart, HeadDimension);
                Value w = attentionWeights[t];
                for (int j = 0; j < HeadDimension; j++)
                {
                    headOutput[j] += w * valueForHead[j];
                }
            }

            concatenatedHeads.AddRange(headOutput); // concatenate this head's output

            Console.WriteLine(
                $"--- Head {h} (dims {headStart}..{headStart + HeadDimension - 1}) ---"
            );
            Console.WriteLine(
                $"  Q slice = [{string.Join(", ", queryForHead.Select(v => v.Data))}]"
            );
            for (int t = 0; t < attentionWeights.Count; t++)
            {
                Console.WriteLine($"  attn weight[{t}] = {attentionWeights[t].Data:F4}");
            }

            Console.WriteLine(
                $"  head output = [{string.Join(", ", headOutput.Select(v => v.Data.ToString("F2")))}]"
            );
        }

        Console.WriteLine();
        Console.WriteLine("Concatenated multi-head output (length embeddingSize = 8):");
        Console.WriteLine(
            $"  [{string.Join(", ", concatenatedHeads.Select(v => v.Data.ToString("F2")))}]"
        );
        Console.WriteLine(
            "Note how the first 4 dims are dominated by V[1] and the last 4 by V[2] -"
        );
        Console.WriteLine(
            "the two heads attended to different positions and both contributions survived."
        );
    }

    // Shows the MLP block: up-project -> ReLU -> down-project.
    // We don't train anything here; we just run a fixed input through random weights
    // to show that the shape goes embeddingSize -> 4*embeddingSize -> embeddingSize.
    private static void MlpBlockDemo()
    {
        const int EmbeddingSize = 4;
        var random = new Random(42);

        List<List<Value>> mlpUpWeights = CreateMatrix(random, 4 * EmbeddingSize, EmbeddingSize);
        List<List<Value>> mlpDownWeights = CreateMatrix(random, EmbeddingSize, 4 * EmbeddingSize);

        var x = new List<Value> { new(0.5), new(-0.3), new(1.0), new(-0.8) };
        Console.WriteLine($"--- MLP Block (embeddingSize = {EmbeddingSize}) ---");
        Console.WriteLine($"  input           ({x.Count, 2} dims): [{Format(x)}]");

        List<Value> hidden = Linear(x, mlpUpWeights);
        Console.WriteLine($"  after up-proj   ({hidden.Count, 2} dims): [{Format(hidden)}]");

        var activated = hidden.Select(v => v.Relu()).ToList();
        int negBefore = hidden.Count(v => v.Data < 0);
        Console.WriteLine(
            $"  after ReLU      ({activated.Count, 2} dims): [{Format(activated)}]  (zeroed {negBefore} negatives)"
        );

        List<Value> output = Linear(activated, mlpDownWeights);
        Console.WriteLine($"  after down-proj ({output.Count, 2} dims): [{Format(output)}]");

        static string Format(IEnumerable<Value> vs) =>
            string.Join(", ", vs.Select(v => v.Data.ToString("F3")));
    }
}

Enter fullscreen mode Exit fullscreen mode

Uncomment the Chapter 10 case in the dispatcher in Program.cs:

case "ch10":
    Chapter10Exercise.Run();
    break;

Enter fullscreen mode Exit fullscreen mode

Then run it:

dotnet run -- ch10

Enter fullscreen mode Exit fullscreen mode

You should see head 0's attention peak at position 1, head 1's peak at position 2, and the concatenated output with distinct contributions in each half. The MLP demo shows the dimensionality change: 4 → 16 → 4, with ReLU zeroing out 6 of the 16 intermediate entries (the exact count is deterministic with Random(42)).

This exercise lives in Chapter10Exercise.cs so you can come back to it any time.

Key Distinction: Communication vs. Computation

The transformer alternates between two fundamentally different operations:

  • Attention is communication across time. The token at position t looks at tokens 0..t-1.
  • MLP is computation at a single position. No cross-position information flow.

That's the design pattern of the entire transformer: communicate, compute, communicate, compute, on a residual stream that carries information forward.