FullStack AI Hub
Studio
AI & LLM Systems · 01. Transformer Architecture
12 min
6 steps
Intermediate

Encoder-Decoder, Decoding & Modern LLMs

Bridge Classic 2017 Cross-Attention to Modern Decoder-Only GQA stacks, and sample live next-token probabilities.

AI & LLM Systems01. Transformer ArchitectureLesson 4 of 4
12 minIntermediate6 steps

Encoder-Decoder, Decoding & Modern LLMs

Bridge Classic 2017 Cross-Attention to Modern Decoder-Only GQA stacks, and sample live next-token probabilities.

ARCHITECTURE
Enc-Dec 2017
KV HEADS
8 KV / 8 Q
KV CACHE / 8K
1024 MB
CROSS-ATTN
chat → cat
Encoder-Decoder Bridge · Modern LLM Evolution
Architecture Era & Attention Bridge
Encoder (Bidirectional K, V)Cross-Attention BridgeDecoder (Causal Q · Click)
68%Theblackcatsleepsquietly<BOS>Lechatnoirdortdoucement
Generating “chat” queries Encoder K/V → peaks at “cat” (68%). Click “chat” then “noir” to watch the adjective-noun swap!
2017 Paper → Modern LLM Stack
Topology
Encoder + DecoderDecoder-Only (Unified)
Position Encoding
Additive SinusoidalRoPE Rotary Phase
Normalization
Post-LayerNormPre-RMSNorm
Attention KV
MHA (1:1 Q/KV)GQA (4:1 – 8:1 Shared KV)
FFN Gate
ReLU (4 × d_model)SwiGLU (8/3 × d_model)
In This LessonStep 1 of 6
What You Will Master
  • ✓Trace how Classic 2017 Encoder-Decoder Cross-Attention aligns reordered source and target phrases (e.g., "black cat" → "chat noir")
  • ✓Explain why modern LLMs converged on Decoder-Only stacks with Grouped-Query Attention (GQA) for 4–8× smaller KV caches
  • ✓Predict how Temperature (T) sharpens or flattens softmax logits before next-token sampling
  • ✓Combine Top-K and Top-P (Nucleus) truncation to preserve creativity while eliminating tail hallucinations

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Encoder-Decoder (T5, Whisper)Sequence-to-sequence translation, audio transcription, and fixed-input summarizationBidirectional encoder + Cross-Attention bridge shines on alignment, but splits parameter budget in two
Decoder-Only + GQA (Llama 3)General-purpose chat, reasoning, coding, and long-context servingUnified next-token objective scales effortlessly; GQA shares KV heads to shrink decode memory 4–8×
Temperature Scaling (z / T)Controlling determinism (T ≤ 0.3 for code/JSON) vs creative diversity (T ≈ 0.8–1.0)High T (> 1.4) inflates improbable junk tokens unless paired with Top-P truncation
Top-P Nucleus SamplingAdaptive candidate pruning that shrinks dynamically when the model is confidentKeeps smallest prefix summing to p (e.g., 90%) and renormalizes—preventing incoherent tail picks

Step-by-Step Architectural Breakdown (6 Steps)

Full architectural walkthrough transcript and state transitions for Encoder-Decoder, Decoding & Modern LLMs.

STEP 01 · SETUPJump to step →

Classic 2017: Encoder-Decoder & Cross-Attention Alignment

The original 2017 *"Attention Is All You Need"* paper was built for machine translation using **two stacks**: a bidirectional **Encoder** reads the full English sentence (`The black cat sleeps quietly`) and exports rich **Keys & Values**; an autoregressive **Decoder** generates French word by word.

Between them sits the **Cross-Attention Bridge**: the Decoder supplies Queries (`Q_dec`) that attend over the Encoder’s Keys/Values (`K_enc, V_enc`). Click **`"chat"`** and then **`"noir"`** on the stage to watch the orange bridge cross over seamlessly to handle French adjective-noun inversion!

idea:Cross-Attention lets source and target sequences have completely different lengths and word orders—without any fixed positional lockstep.

Encoder-DecoderCross-AttentionSequence Alignment
STEP 02 · SOLUTIONJump to step →

Why Frontier LLMs Converged on Decoder-Only + GQA

Modern general-purpose LLMs (GPT-4, Claude, Llama 3, Gemma) dropped the separate Encoder entirely. Treating prompts and completions as one unified causal token stream uses **100% of parameters on every token** and unlocks in-context few-shot learning at trillion-token scale.

At inference time, however, caching separate K/V vectors for every attention head (**MHA**) fills GPU memory fast. **Grouped-Query Attention (GQA)** shares each KV head across 4–8 Query heads—cutting KV-cache RAM and HBM bandwidth by **4× to 8×** with virtually zero quality loss!

good:Slide the KV Heads control from 8 (MHA) → 2 (GQA) → 1 (MQA) on the stage to watch per-sequence KV-cache drop from 1,024 MB down to 128 MB.

Decoder-Only LLMGrouped-Query AttentionKV-Cache Compression
STEP 03 · TECHNIQUEJump to step →

From Final Residual Vector to Vocabulary Logits

After the last Transformer layer finishes, the model takes the final token’s hidden vector `[1, 4096]` and multiplies it by the **Unembedding Matrix ($W_{\text{lm\_head}}$)** to produce one raw real-valued score (**logit $z_i$**) for every token in the 128,256-word vocabulary.

Passing those logits through **`softmax(z_i / T)`** turns raw scores into a valid probability distribution summing to 100%. Click **`Sample Next Token`** on the stage to watch the Transformer generate tokens one autoregressive step at a time!

idea:Every generated token is appended back onto the input sequence (and its K/V vectors cached) to compute the very next probability distribution.

LM HeadRaw LogitsAutoregressive Decoding
STEP 04 · PROBLEMJump to step →

The High-Temperature Tail Problem

Raising **Temperature (`T > 1.3`)** divides logits by a larger number before `exp()`, flattening the probability curve so creative alternatives (`"attend"`, `"compress"`) can win. Unfortunately, raising `T` *also* inflates nonsense tail tokens like **`"banana"`**!

With `Top-P = 1.0` and `T = 1.8`, even a tiny 4% probability on junk tokens compounds across a 200-token response—almost guaranteeing a derailment or hallucinated token.

watch:Watch the bottom rows ("dream", "banana") stay unpruned when Top-P = 1.00 and Temperature = 1.80. One unlucky draw corrupts the rest of the autoregressive chain!

Temperature FlatteningLong-Tail NoiseAutoregressive Drift
STEP 05 · SOLUTIONJump to step →

Top-P Nucleus Sampling: Adaptive Tail Truncation

Fixed **Top-K** always keeps the same number of tokens—which is too narrow when 10 words are equally plausible, and too wide when only 1 factual answer (`"Paris"`) is right.

**Top-P (Nucleus) Sampling** sorts tokens by probability, keeps only the smallest prefix whose cumulative mass reaches `p` (typically `0.90`), masks every remaining tail token to `0`, and **renormalizes** the nucleus back to 100%. Look at the dashed red **Nucleus Cutoff** line on the chart!

good:Production APIs usually combine moderate Temperature (0.7–0.9) + Top-P (0.90–0.95) for creative tasks, or Temperature 0.0–0.2 for structured tool calls and code.

Top-P Nucleus SamplingTop-KProbability Renormalization
STEP 06 · RECAPJump to step →

Recap: From 2017 Attention to Production LLM Serving

You now hold the complete end-to-end Transformer blueprint: **BPE tokens → dense embeddings → RoPE rotary phase → Multi-Head GQA Attention (FlashAttention) → Pre-RMSNorm Residual Highway → SwiGLU FFN → LM Head Logits → Temperature/Top-P Sampling**.

Ready to see how this exact GQA KV-cache and autoregressive decode loop behaves on a cluster of production H100 GPUs? Advance straight into **Module 02: LLM Inference & KV Cache**!

good:Every modern inference optimization (PagedAttention, Continuous Batching, Speculative Decoding) exists specifically to serve the GQA KV-cache and autoregressive loop you just mastered.

Modern LLM StackEnd-to-End TransformerInference Bridge

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.