Library

Volume 2 · GenAI Foundations & LLM Architecture

Notebook
Sign in

Section 1

Transformer Architecture

739 words · about 3 min

1.1 Core Architecture Pipeline

flowchart LR
    Input["Input Raw Text"] --> Tok["Tokenization\n(BPE / SentencePiece)"]
    Tok --> Emb["Embedding +\nPositional Encoding (RoPE)"]
    
    subgraph Blocks["N × Transformer Blocks"]
        direction TB
        MHA["Multi-Head Attention (MHA)"] --> Add1["Add & LayerNorm"]
        Add1 --> FFN["Feed-Forward Network (FFN)\n(SwiGLU / GeLU)"]
        FFN --> Add2["Add & LayerNorm"]
    end

    Emb --> Blocks
    Blocks --> Proj["Linear Head Projection"]
    Proj --> Softmax["Softmax Over Vocab"]
    Softmax --> Output["Next-Token Probabilities"]

Interview Tip: When asked “How do LLMs work?”, never stop at “transformers.” Confidently walk through the full pipeline:

  1. Tokenization into discrete vocabulary IDs
  2. Dense Vector Embedding + Rotary Positional Encoding (RoPE)
  3. Repeated stack of $N$ Transformer Blocks (Multi-Head Attention $\to$ LayerNorm $\to$ Feed-Forward $\to$ Residual connection)
  4. Linear output projection followed by Softmax over vocabulary space to yield autoregressive token probabilities.

1.2 Self-Attention Mechanism

Self-attention allows every token in an input sequence to dynamically weight and attend to every other token in parallel.

$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right) V$$

flowchart TD
    Token["Input Token Representation (X)"]

    subgraph Projections["Learned Linear Projections"]
        Q["Query (Q = X · W_Q)\n'What am I seeking?'"]
        K["Key (K = X · W_K)\n'What do I contain?'"]
        V["Value (V = X · W_V)\n'What info do I provide?'"]
    end

    Token --> Q & K & V

    Dot["Dot Product: Q · K^T"]
    Scale["Scale by 1/√d_k\n(Prevents Vanishing Gradients)"]
    SM["Softmax\n(Attention Weight Matrix)"]
    MatMul["Matrix Multiply with Value (V)"]
    Out["Context-Aware Token Representation"]

    Q & K --> Dot
    Dot --> Scale --> SM
    SM & V --> MatMul --> Out

Architectural Bottlenecks:

  • Quadratic Complexity ($O(n^2)$): Attention memory and compute scale quadratically with sequence length $n$. This bottleneck is the primary driver behind context window limits and optimizations such as FlashAttention, sliding-window attention, and RingAttention.
  • Inference KV-Cache: During generation, prior Key and Value matrices are cached in GPU memory so only new Query vectors need evaluation. For long context (128K+), the KV-cache quickly exceeds model weights in VRAM demand.

1.3 Multi-Head Attention

Multiple independent attention heads run in parallel (typically 32 to 128 heads), allowing the model to simultaneously focus on distinct contextual relationships:

  • Syntactic Heads: Track subject-verb agreement and grammar.
  • Semantic Heads: Link related concepts and thematic meaning.
  • Positional Heads: Track relative distance and token proximity.
  • Co-reference Heads: Resolve pronouns back to proper nouns.
  • Negation Heads: Detect scope and semantic negation (“no evidence of…”).

$$\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h) W_O$$

1.4 Feed-Forward Networks (FFN)

  • Position-wise MLP: Applied independently to each token after self-attention using non-linear activations (SwiGLU or GeLU).
  • Knowledge Storage: Represents approximately two-thirds of the transformer’s total parameter count, functioning as an associative memory store.

1.5 Positional Encoding

Because self-attention is permutation-invariant, positional encodings must explicitly inject order:

Method Used By Description
Sinusoidal Original Transformer Fixed trigonometric mathematical functions, zero learned weights
Learned Embeddings BERT, GPT-2 Static parameters trained with model; rigid maximum length ceiling
RoPE (Rotary Position Embedding) Llama 3, Mistral, modern LLMs Encodes relative distance via 2D rotation matrices; supports context extrapolation
ALiBi (Linear Biases) BLOOM Adds static distance penalties directly to attention logits without position vectors

1.6 Decoder-Only vs. Encoder-Decoder vs. Encoder-Only

Architecture Attention Pattern Models Primary Use Cases
Encoder-only Bidirectional (all-to-all) BERT, RoBERTa, DeBERTa Sentence embeddings, classification, token tagging
Decoder-only Causal (autoregressive / left-to-right) GPT-4o, Claude, Llama 3, Gemini Reasoning, dialogue, open-ended generation
Encoder-Decoder Cross-attention T5, BART, Whisper Translation, transcription, summarization

Why Decoder-Only Dominates Production:

  1. Empirical Scaling Laws: Autoregressive decoder-only models scale most efficiently with compute and data.
  2. In-Context Few-Shot Emergence: Emergent reasoning capabilities show highest fidelity in causal generative training.
  3. KV-Cache Reusability: Autoregressive architectures leverage incremental KV-caching during streaming inference.

Section 1 — Interview Q&A

Q: Explain how the attention mechanism works and why it matters architecturally.

A: Attention computes relevance scores between every token pair via $\text{softmax}(QK^T / \sqrt{d_k}) V$. Architecturally, this introduces three critical implications:

  • $O(N^2)$ Complexity: A 128K sequence requires billions of attention computations, requiring FlashAttention kernel tiling.
  • KV-Cache Footprint: KV-cache grows linearly with sequence length. For a 70B model at 128K context, KV tensors alone can consume 40+ GB of GPU VRAM, making inference memory-bound rather than compute-bound.
  • Positional Generalization: Modern encodings like RoPE dictate whether models can extrapolate beyond their pre-trained sequence limits.

Q: Why do most production LLMs use decoder-only architectures instead of encoder-decoder?

A: Decoder-only models scale more predictably under Chinchilla scaling laws, excel at generalized autoregressive text generation, and naturally support prompt-based in-context learning. Encoder-only architectures (BERT-family) remain specialized for search embeddings and high-throughput classification where generation is unnecessary.