Wednesday, August 19, 2026

Multi-Head Multi-Layer Self-Attention: How LLMs Understand Context

 

Multi-Head Multi-Layer Self-Attention: How LLMs Understand Context

If you are learning how Large Language Models (LLMs) such as GPT work, you will quickly encounter terms like self-attention, multi-head attention, Transformer layers, and multi-layer attention.

At first, these concepts can feel intimidating.

But the underlying idea is surprisingly simple:

An LLM repeatedly looks at the relationships between tokens, from multiple perspectives, and builds a progressively richer understanding of the input.

This article breaks down what multi-head multi-layer self-attention means and how it fits into the architecture of modern LLMs.


The One-Sentence Definition

Multi-head multi-layer self-attention is the repeated use of multiple parallel attention mechanisms across stacked Transformer layers, allowing an LLM to progressively build richer representations of relationships and context between tokens.

And the hierarchy is:

Self-Attention
      ↓
Multi-Head Self-Attention
      ↓
Transformer Block
      ↓
Multiple Transformer Blocks
      ↓
Transformer Architecture
      ↓
Large Language Model

Once this hierarchy becomes clear, the architecture of GPT becomes much easier to understand.



1. Start with Self-Attention

Let's start with a simple sentence:

"The engineer fixed the server because it was down."

When the model processes the word "it", it needs to understand what "it" refers to.

Is it:

  • the engineer?

  • the server?

  • something else?

Self-attention allows the model to examine the other tokens in the sentence and determine which ones are relevant.

Conceptually:

The engineer fixed the server because it was down.
                    ↑                  ↑
                    │                  │
                 context           important

The model assigns different attention weights to different tokens.

The important idea is:

Self-attention allows every token to consider other tokens in the sequence when building its representation.

This is one of the fundamental ideas behind the Transformer architecture.


2. Why Do We Need Multiple Attention Heads?

A sentence can contain many different types of relationships.

Consider:

"The customer contacted the bank because she needed a loan."

There are several relationships here.

The model needs to understand:

  • Who contacted whom?

  • Who does "she" refer to?

  • What is the relationship between "needed" and "loan"?

  • Why did the customer contact the bank?

One attention mechanism may not be sufficient to capture all these relationships.

This is where multi-head attention comes in.

Instead of having one attention mechanism, the Transformer uses multiple attention heads.

Conceptually:

                    Sentence
                       │
       ┌───────────────┼───────────────┐
       ↓               ↓               ↓
     Head 1          Head 2          Head 3
       │               │               │
   Relationship      Grammar        Semantic
    patterns         patterns        patterns
       │               │               │
       └───────────────┼───────────────┘
                       ↓
                Combined result

Each head performs its own attention calculation.

The outputs of the heads are then combined.


3. Think of Attention Heads as Different Perspectives

A useful analogy is to imagine that you give the same document to several experts.

One expert focuses on:

Grammar

Which words are connected grammatically?

Another focuses on:

Relationships

Which entity is related to which?

Another focuses on:

Meaning

What concepts are connected?

Another might focus on:

Context

What information elsewhere in the sentence changes the meaning of this word?

The experts aren't explicitly programmed to perform these roles. The model learns useful attention patterns during training.

That's an important distinction.

We shouldn't assume:

"Head 1 is always the grammar head."

Instead:

Different heads can learn different useful patterns and relationships.


4. Every Attention Head Has Query, Key and Value

Remember the basic self-attention mechanism?

It uses three components:

  • Query (Q) — What information am I looking for?

  • Key (K) — What information do I contain?

  • Value (V) — What information should I provide?

For a single attention mechanism, we can think of it as:

Query
   │
   ↓
Compare with Keys
   │
   ↓
Calculate attention scores
   │
   ↓
Retrieve weighted Values
   │
   ↓
Attention output

With multiple heads, we have multiple sets of learned transformations:

Head 1 → Q₁, K₁, V₁
Head 2 → Q₂, K₂, V₂
Head 3 → Q₃, K₃, V₃
...
Head N → Qₙ, Kₙ, Vₙ

Each head can therefore learn a different representation of relationships between tokens.


5. What Happens After the Heads Finish?

The outputs of the individual attention heads are combined.

Conceptually:

Head 1 ──┐
Head 2 ──┤
Head 3 ──┤
Head 4 ──┤
Head 5 ──┤
          ↓
      Concatenate
          ↓
   Linear projection
          ↓
     Final output

This gives the Transformer a combined representation containing information from all the attention heads.

So the basic process is:

Split → Attend independently → Combine


6. Now Add Multiple Layers

We have now understood multi-head attention.

But modern LLMs don't perform this operation only once.

They stack many Transformer layers.

For example:

Input
  ↓
Transformer Layer 1
  ↓
Transformer Layer 2
  ↓
Transformer Layer 3
  ↓
...
  ↓
Transformer Layer N
  ↓
Output

Each layer receives the representation produced by the previous layer.

This is where the term multi-layer comes from.


7. Why Do We Need Multiple Layers?

Because language understanding is hierarchical and complex.

Consider:

"The bank approved the loan because the customer's credit history was excellent."

A simplified intuition might be:

Earlier layers

The model begins learning relatively local relationships:

bank → approved
customer → credit
credit → history

Middle layers

It can build more complex relationships:

customer
    ↓
credit history
    ↓
excellent
    ↓
loan approval

Deeper layers

The representation can capture the broader relationship:

The customer's strong credit history contributed to the bank approving the loan.

Again, this is a conceptual illustration rather than a strict rule that every early layer performs grammar and every later layer performs semantics.

The important idea is:

Each layer transforms the representation and passes a richer representation to the next layer.


8. Putting Multi-Head and Multi-Layer Together

Now we can combine the two ideas.

Imagine a Transformer with four layers and four attention heads per layer:

                         INPUT
                           │
                           ↓
              ┌───────────────────────┐
              │       LAYER 1         │
              │                       │
              │ Head 1 ──┐            │
              │ Head 2 ──┤            │
              │ Head 3 ──┤ Attention   │
              │ Head 4 ──┘            │
              └───────────┬───────────┘
                          ↓
              ┌───────────────────────┐
              │       LAYER 2         │
              │                       │
              │ Head 1 ──┐            │
              │ Head 2 ──┤            │
              │ Head 3 ──┤ Attention   │
              │ Head 4 ──┘            │
              └───────────┬───────────┘
                          ↓
              ┌───────────────────────┐
              │       LAYER 3         │
              │                       │
              │ Head 1 ──┐            │
              │ Head 2 ──┤            │
              │ Head 3 ──┤ Attention   │
              │ Head 4 ──┘            │
              └───────────┬───────────┘
                          ↓
              ┌───────────────────────┐
              │       LAYER 4         │
              │                       │
              │ Head 1 ──┐            │
              │ Head 2 ──┤            │
              │ Head 3 ──┤ Attention   │
              │ Head 4 ──┘            │
              └───────────┬───────────┘
                          ↓
                        OUTPUT

This is the basic intuition behind multi-head, multi-layer attention in a Transformer.


9. But a Transformer Layer Is More Than Attention

There is an important technical detail.

A Transformer layer is not simply:

Multi-head attention → next layer

A typical Transformer block also contains a feed-forward network and normalization/residual connections.

Conceptually:

                 Input
                   │
                   ↓
          Multi-Head Attention
                   │
                   ↓
          Residual + Normalization
                   │
                   ↓
         Feed-Forward Network
                   │
                   ↓
          Residual + Normalization
                   │
                   ↓
                Output

This entire block is then repeated many times.

Therefore, when people casually say:

"This LLM has many layers of attention"

they usually mean that the model contains many Transformer blocks, each containing an attention mechanism.


10. The Complete Picture

We can now connect everything together:

Text
  ↓
Tokens
  ↓
Token Embeddings
  ↓
Positional Information
  ↓
┌───────────────────────────────────┐
│        Transformer Layer 1        │
│                                   │
│  Multi-Head Self-Attention        │
│              ↓                    │
│     Feed-Forward Network          │
└─────────────────┬─────────────────┘
                  ↓
┌───────────────────────────────────┐
│        Transformer Layer 2        │
│                                   │
│  Multi-Head Self-Attention        │
│              ↓                    │
│     Feed-Forward Network          │
└─────────────────┬─────────────────┘
                  ↓
                 ...
                  ↓
┌───────────────────────────────────┐
│        Transformer Layer N        │
│                                   │
│  Multi-Head Self-Attention        │
│              ↓                    │
│     Feed-Forward Network          │
└─────────────────┬─────────────────┘
                  ↓
          Final Representation
                  ↓
        Next-Token Prediction

This repeated transformation is what allows the model to build increasingly sophisticated representations of the input.


11. Where Does GPT Fit In?

GPT-style models use causal self-attention.

That means the model is not allowed to look at future tokens when predicting the next token.

Suppose the model has:

"The cat sat on the"

The model needs to predict what comes next.

It can use:

The
 ↓
cat
 ↓
sat
 ↓
on
 ↓
the
 ↓
?

But it cannot peek at the answer.

The attention mechanism is therefore masked so that each position can only attend to the appropriate previous context.

The model might produce something conceptually like:

mat       42%
floor     18%
chair      9%
bed        6%
...

It then selects or samples a token and continues generating.


12. One More Important Distinction

It is useful to keep these terms separate:

Self-Attention

Tokens attend to other tokens in the same sequence.

Multi-Head Self-Attention

Multiple attention mechanisms examine those relationships in parallel.

Multi-Layer Transformer

Multiple Transformer blocks are stacked so that representations are repeatedly transformed.

Causal Self-Attention

Attention is restricted so that a token cannot use future tokens when generating text.

LLM

A large neural network built using many such Transformer components and trained to model language.


13. A Simple Mental Model

If you remember only one analogy, remember this:

Imagine a large team of analysts working in multiple rounds.

Round 1

Several analysts examine the raw information from different perspectives.

             Input
               ↓
       ┌───────┼───────┐
       ↓       ↓       ↓
   Analyst   Analyst  Analyst
       └───────┼───────┘
               ↓
        Combined view

Round 2

Another group receives that combined view and analyzes it again.

       Combined view
              ↓
      Multiple analysts
              ↓
       Better representation

Round 3

The process continues.

     Better representation
              ↓
      Multiple analysts
              ↓
      Even richer representation

That is a useful mental model for multi-head multi-layer self-attention.



Monday, August 17, 2026

Understanding Self-Attention and Multi-Head Attention in Large Language Models

 

Understanding Self-Attention and Multi-Head Attention in Large Language Models

Large Language Models (LLMs) such as GPT, Claude, and Gemini can generate remarkably coherent text, answer questions, summarize documents, and even write code. But underneath all of this is a deceptively simple idea:

An LLM predicts what token should come next.

To understand how LLMs make those predictions so effectively, we need to understand one of the most important ideas behind modern language models: attention.

This article takes you from the basics of LLMs to Self-Attention and finally to Multi-Head Attention.


1. First: What Does an LLM Actually Do?

At its core, an LLM predicts the next token based on the tokens that came before it.

A token can be:

  • A complete word

  • A part of a word

  • A single character

  • Sometimes punctuation or another small piece of text

For example, the sentence:

"The engineer fixed the server."

might be broken into several tokens rather than exactly one token per word.

When generating text, the model might predict:

The → engineer → fixed → the → server → ...

The model doesn't necessarily generate only one word at a time in the way humans think about words. It predicts tokens, and those predictions can continue for hundreds or even thousands of tokens, producing entire paragraphs or documents.

Why are LLMs so much better than older language models?

Modern LLMs have two major advantages:

1. Far more parameters

Parameters are the learned values inside the neural network. Modern LLMs contain vastly more parameters than traditional recurrent models.

2. Far more context

LLMs can consider relationships between many tokens in their context rather than treating language as a short sequence of immediately preceding words.

And this second capability is where Transformers and attention become extremely important.


2. The Transformer: The Architecture Behind Modern LLMs

The Transformer is the architecture that made today's generation of LLMs possible.

A traditional Transformer consists of two major components:

Input Text
    │
    ▼
┌─────────────┐
│   Encoder   │
└─────────────┘
    │
    ▼
Intermediate Representation
    │
    ▼
┌─────────────┐
│   Decoder   │
└─────────────┘
    │
    ▼
Output Text

Encoder

The encoder takes the input text and converts it into an internal representation that captures information about the text.

Decoder

The decoder uses that representation to generate useful output text.

A classic example is machine translation.

Suppose we want to translate:

"The engineer fixed the server."

from English into French.

The encoder processes the English sentence and creates an internal representation.

The decoder then uses that representation to generate the French translation.


3. But How Does the Transformer Understand Context?

This is where the key concept appears:

Self-Attention

Self-attention allows the model to examine the tokens in a sequence and determine which tokens are important to each other when understanding a particular token.

Consider this sentence:

"The animal didn't cross the road because it was tired."

What does "it" refer to?

Most humans immediately understand that "it" probably refers to the animal, not the road.

But the model has to learn this relationship mathematically.

Self-attention gives it a mechanism for doing exactly that.

Instead of treating every token independently, the model asks:

"For this token, which other tokens should I pay attention to?"


4. How Does Self-Attention Work?

For every token, the Transformer creates three representations:

Query (Q)

"What information am I looking for?"

Key (K)

"What information do I contain?"

Value (V)

"What information should I provide if I'm relevant?"

You can think of this like searching a database.

The Query is your search request.

The Key describes what each item contains.

The Value is the actual information you retrieve.

The model compares a token's Query with the Keys of other tokens to determine how relevant those tokens are.

Conceptually:

Query
  │
  ├── compare with Key 1 → relevance
  ├── compare with Key 2 → relevance
  ├── compare with Key 3 → relevance
  └── compare with Key 4 → relevance

These relevance scores become attention weights.

The model then uses those weights to determine how much information to take from each Value.


5. A Simple Example

Consider:

"The engineer fixed the server because it was crashing."

When the model processes the token "it", it needs to understand what "it" refers to.

Self-attention might produce something conceptually like:

                 "it"
                  │
       ┌──────────┼──────────┐
       ↓          ↓          ↓
   engineer     server    crashing
     0.15        0.55        0.20

These numbers are only illustrative, but they show the basic idea.

The model gives greater attention to "server" than to "engineer" when interpreting "it".

The important point is:

Self-attention does not mean looking at everything equally.

Instead, the model calculates different attention weights for different tokens.

Some tokens are highly relevant.

Others are less relevant.


6. Why Is This So Powerful?

Consider how humans understand a sentence.

When we read:

"The engineer fixed the server because it was crashing."

we don't interpret every word in isolation.

We connect:

  • engineer → who performed the action

  • fixed → what action happened

  • server → what was fixed

  • crashing → why the action was necessary

  • it → what the pronoun refers to

The meaning of one word can depend heavily on other words.

Self-attention allows the model to build representations where the meaning of a token is influenced by its surrounding context.

This is one of the major reasons Transformers are so effective at understanding language.


7. But One Attention Mechanism Isn't Enough

Now consider a more complicated sentence:

"The engineer gave the manager the report because he had requested it."

There are several relationships that the model needs to understand.

For example:

engineer ↔ gave
manager  ↔ requested
report   ↔ it
engineer ↔ he

These relationships are not all the same.

Some involve:

  • Grammar

  • Pronoun resolution

  • Meaning

  • Actions

  • Objects

  • Relationships between entities

A single attention mechanism might struggle to capture all of these different relationships effectively.

So the Transformer uses a more powerful idea:

Multi-Head Attention


8. What Is Multi-Head Attention?

The simplest way to understand Multi-Head Attention is to imagine multiple specialists reading the same sentence simultaneously.

Instead of having one attention mechanism, the Transformer has multiple attention heads.

Conceptually:

                    Sentence
                       │
          ┌────────────┼────────────┐
          ↓            ↓            ↓
       Head 1        Head 2       Head 3
          │            │            │
       Grammar       Meaning      Context
       relations     relations    relations
          │            │            │
          └────────────┼────────────┘
                       ↓
                 Combine Results
                       │
                       ↓
               Final Representation

Each head can learn to focus on different types of relationships.


9. Why Do We Need Multiple Heads?

Imagine you're reading a paragraph.

At the same time, your brain might pay attention to several different things.

Person

Who is performing the action?

Object

What is the action being performed on?

Grammar

What does this pronoun refer to?

Time

When did something happen?

Meaning

What does the sentence actually mean?

Relationships

How are the different concepts connected?

A single perspective isn't necessarily enough to capture all of these relationships.

Multi-head attention allows the neural network to learn different patterns in parallel.

One attention head might become useful for grammatical relationships.

Another might focus on relationships between entities.

Another might capture positional or contextual relationships.

The important point is that the model learns what each head should specialize in during training. We shouldn't assume that every individual head literally corresponds to a human-defined category such as "grammar" or "meaning."


10. Self-Attention vs. Multi-Head Attention

This distinction is worth remembering.

Self-Attention asks:

"Which other tokens should I pay attention to?"

It calculates relationships between tokens within the sequence.

Multi-Head Attention asks:

"Can we examine those relationships from multiple learned perspectives at the same time?"

Multiple attention heads perform attention operations in parallel, allowing the model to capture different patterns in the same input.


11. Putting It All Together

Let's return to our example:

"The engineer gave the manager the report because he had requested it."

A Transformer doesn't simply read this sentence as a list of independent words.

Instead, attention mechanisms allow it to build contextual representations.

Conceptually:

                 Sentence
                    │
                    ▼
              Tokenization
                    │
                    ▼
             Token Representations
                    │
                    ▼
          ┌─────────────────────┐
          │ Multi-Head Attention│
          └─────────────────────┘
                    │
          ┌─────────┼─────────┐
          ↓         ↓         ↓
       Head 1    Head 2    Head 3 ...
          │         │         │
          └─────────┼─────────┘
                    ↓
          Contextual Representation
                    │
                    ▼
            Further Transformer
                Processing
                    │
                    ▼
             Next-token prediction

The model repeatedly performs these kinds of transformations as information moves through the Transformer.

Eventually, the resulting representation is used to predict what token should come next.

And that simple prediction process, repeated over and over, is what allows an LLM to generate remarkably sophisticated text.


12. The Big Picture

If you're learning LLMs, it's useful to keep the hierarchy in your head:

LLM
 │
 └── Transformer
       │
       ├── Attention
       │     │
       │     └── Self-Attention
       │             │
       │             ├── Query
       │             ├── Key
       │             └── Value
       │
       └── Multi-Head Attention
             │
             ├── Head 1
             ├── Head 2
             ├── Head 3
             └── ...

The exact architecture of modern LLMs can be more nuanced than this simplified picture. For example, many popular generative LLMs are decoder-only Transformers rather than the original encoder-decoder Transformer architecture.

But the core intuition remains extremely useful:

Tokens provide the pieces.

Self-attention determines which pieces are relevant to one another.

Multi-head attention examines those relationships from multiple learned perspectives.

The Transformer processes this contextual information.

The LLM uses the resulting representation to predict the next token.

And by repeating that process at enormous scale, an LLM can transform a simple sequence of token predictions into something that looks remarkably like understanding.


The One-Minute Takeaway

If you remember only four things, remember these:

1. LLMs predict tokens.
They generate text by repeatedly predicting what token should come next.

2. Transformers provide the architecture.
They allow models to process relationships between tokens efficiently.

3. Self-attention provides context.
It answers: "Which other tokens are important when understanding this token?"

4. Multi-head attention provides multiple perspectives.
It allows the model to learn different relationships between tokens simultaneously.

Self-Attention: "Who should I pay attention to?"

Multi-Head Attention: "Let's ask that question from multiple learned perspectives."

That is one of the fundamental ideas behind modern Large Language Models.

Monday, June 22, 2026

Claude Everyday - Compaction

Compaction — and why you shouldn't fully trust it


A short explainer on how Claude Code keeps long conversations alive, what it costs you, and what to do about it.


---

The everyday version


Picture this. You're on the family WhatsApp group, planning your cousin's wedding. It's been going on for weeks — aunts, uncles, cousins, everyone has opinions. Hundreds of messages a day. Menu debates, sangeet song lists, who's picking up the grandparents from the airport, which sweet shop is making the jalebi.

  

At some point WhatsApp is bursting at the seams. Imagine your phone got clever and replaced last week's chunk with a sticky note:


"Venue finalised: Hotel Sahara, Lucknow. Catering: Bikaner Sweets. Sangeet on the 14th. Cards being handled by uncle. Cousin bringing the outfit from Delhi."


The recent messages stay intact, exactly as written. The older ones become a gist.


That sticky note is great. It captures the decisions — who's doing what, what's been picked. But it also quietly drops the fine grain. The exact sweet box order — "two kilos of one  sweet, one kilo of another, skip the third one because Grandpa doesn't like it"? Reduced to "Bikaner Sweets, finalised." The specific time slot the priest gave for the ceremony? Paraphrased into something fuzzier.


Now imagine you come back to the group next week and ask, "what time did the priest say for the ceremony?" Your cousin, looking at the sticky note, answers confidently — but with the gist, not the exact time. You don't notice until the morning of the wedding when the groom's procession arrives 40 minutes off.


That's compaction.


---

The technical version

  

A Claude Code session is a growing list of messages — your prompts, the model's responses, tool calls, tool results — and that entire list gets re-sent to the model every turn. The model has a fixed context window (typically around 200K tokens). As cumulative tokens approach that ceiling, the harness intervenes: it slices off the older portion of the message history and replaces it with a single model-generated summary.

  

Recent turns stay verbatim.


  The next turn, the model sees:


  [ summary of turns 1–40 ]   ← compacted

  [ turns 41–60 verbatim ]    ← recent, intact

  [ your new message ]


  A few properties worth internalizing:


Threshold-driven, not turn-driven. Compaction fires on token usage, not message count. A session full of long tool outputs compacts much sooner than one with chatty back-and-forth.


Lossy and non-deterministic. The summary is itself produced by a model call — best-effort, not deterministic compression. Decisions, file paths, and stated intent usually survive. Verbatim text — regexes, config blocks, exact error messages, raw tool output — frequently does not.


Sticky. Once a session is compacted, the summary becomes part of its canonical history. When you resume via --continue or --resume, you inherit the summary. There's no "uncompact."


Per-session. Memory and CLAUDE.md are unaffected — they load fresh every turn from disk. They're durable in a way the transcript isn't.


---

Where it goes wrong


Three failure modes are worth naming, because if you don't know they exist, you'll get bitten by them:


Model drift. The summary emphasizes what seemed salient to the summarizer. Nuance, minority threads, and dissenting arguments get flattened. If you spent ten turns debating whether to use approach A or approach B, the summary likely says "decided on A" — and the reasoning you'd want to retrieve next month is gone. Like the family group quietly forgetting why you ruled out the first venue.


False confidence. This is the most dangerous one. The model still answers as if it remembers, but it's working from a paraphrase. "As we discussed earlier" can become a confident hallucination, with no obvious tell.

You'll only notice when the answer is subtly wrong — and by then, the wedding procession is already late.


Tool-output erosion. Long stdout blobs — test failures, logs, JSON dumps — compress hardest. If you pasted a 500-line stack trace and didn't act on it, the summary will reduce it to "test failed in module X." Good luck recovering the actual error.


---

What to actually do

  

The mental model that works: the session is great for in-flight work, but it's not durable storage. Plan accordingly.


1. Treat important decisions like a small shopkeeper's ledger. Write them down the moment you make them. Memory file. CLAUDE.md. A progress.md checkpoint in the repo. Anything that lives on disk and gets re-read fresh. The neighbourhood shopkeeper doesn't trust memory for the month's credit — he writes it in a notebook the same minute.


2. Manually checkpoint at logical boundaries. Ask Claude: "summarize where we are, what we've decided, and what's next." Then save that output yourself, in a location you control. It's exact, it's durable, and it survives any future compaction.


3. Trigger compaction explicitly with /compact before a known-long stretch. Choose where the boundary lands, instead of letting it happen mid-thought.


4. Move stable facts to CLAUDE.md. Project conventions, build commands, architectural decisions — anything that's true across sessions belongs there. It gets re-injected every turn rather than relying on transcript recall.


5. Keep sessions task-scoped. One focused task → one focused summary. Cramming a week of unrelated work into one mega-session means the compaction summary becomes vague, because the source material was vague.


6. Read the room. If a session has gone very long and Claude is starting to misremember, that's a signal — wrap up, save what matters, start fresh. Don't push through.


---

The takeaway


Compaction is the right design for the problem it solves. Without it, long sessions would hit a wall. With it, you get continuity at the cost of fidelity — and most of the time that trade is correct.


The cost only shows up when you treat the session like a perfect transcript. Don't. Treat it like a friend who came back from a long wedding-planning meeting and told you "don't worry, everything's sorted." They remember the gist, the vibe, the broad strokes. But for the exact ceremony time and the exact sweet order? You want the WhatsApp messages, or better still, a notebook you wrote in yourself. 


Disclaimer - Views are based on my usage/perception and may change as specifics may evolve. Always go by the official docs.

Monday, May 4, 2026

Claude Subagents: A Practical Guide with Working Code

 

Claude Subagents: A Practical Guide with Working Code

How to orchestrate multiple AI agents to solve complex problems faster


What Is a Subagent?

subagent is a Claude call that you launch from inside another Claude call—or from your own orchestration code—to handle a focused subtask. The parent agent breaks a problem into pieces, delegates them out, then assembles the results.

Think of it like managing a team: you don't do everything yourself. You break down the project, assign tasks to specialists who work in parallel, and integrate their outputs into a final deliverable.

In code, a subagent is just a regular Anthropic SDK call—there is no special API. What makes it a "subagent" is the pattern: parent spawns children, children return results, parent consolidates.


Why Subagents Matter

Three concrete benefits:

1. Parallel speed. If you need 4 independent analyses, running them in parallel with asyncio.gather() cuts wall-clock time from 4× to 1×.

2. Specialization. Each subagent gets a tightly focused system prompt. A "security reviewer" subagent performs better at security review than a generalist prompted with "also check security."

3. Context isolation. Subagents don't share context windows. The parent can fire off large parallel workloads without any single Claude call paying the token cost of everything combined.


The Three Core Patterns

PatternShapeWhen to use
Fan-out + ConsolidateParent → N parallel children → Parent synthesizesIndependent analyses on the same input
PipelineA → B → C (sequential)Each step needs the prior step's output
Fire and ForgetParent launches child, continues without waitingBackground tasks, non-critical enrichment

Pattern 1: Fan-out + Consolidate

Example: Reviewing a code snippet for security, style, and test coverage—simultaneously, in parallel.

Each specialist subagent receives the same code and returns a focused report. The parent synthesizes them into one final review.

                  ┌─── Security Agent ──┐
Parent (code) ───►├─── Style Agent ─────┼──► Parent (consolidates)
                  └─── Test Agent ───────┘

Full Working Script

See 01_fanout_code_review.py

The code can be seen at https://github.com/lachwaninitin/subagents-demo


Pattern 2: Pipeline

Example: Research → Draft → Edit

The output of each stage flows directly into the next. This is sequential by design—you can't draft before you research.

Research Agent → Draft Agent → Edit Agent → Final output

Full Working Script

See 02_pipeline_research.py

The code can be seen at https://github.com/lachwaninitin/subagents-demo



Pattern 3: Fire and Forget

Example: After generating a main response, kick off a background task (e.g., summarize for a log, translate to another language) without blocking the user-facing response.

Main response ──► user (immediately)
                  └──► Background agent (runs async, result logged)

Full Working Script

See 03_fire_and_forget.py

The code can be seen at https://github.com/lachwaninitin/subagents-demo



Prompt Caching with Subagents

When multiple subagents share the same large system prompt or context (e.g., all reviewing the same large document), prompt caching prevents re-paying that token cost on each call.

Mark stable content with cache_control: {"type": "ephemeral"}. The first call writes the cache; subsequent calls read from it at ~10% of the original cost.

See 04_cached_subagents.py for a working example where 4 subagents all analyze the same AIGP framework document.

The code can be seen at https://github.com/lachwaninitin/subagents-demo