LLM Deep Dive • Part II of III

From Transformer to Modern LLMs

The architectural refinements and engineering innovations that enable today's systems. From decoder-only to Flash Attention and beyond.

10 chapters~25 min read16 interactive visualizations
Chapter 4

The Decoder-Only Revolution

The original Transformer was an encoder-decoder architecture designed for translation. The encoder processed the source sentence with bidirectional attention (each position attends to all others). The decoder generated the target sentence autoregressively, with causal attention (each position only attends to previous positions) plus cross-attention to the encoder outputs.

Modern LLMs almost universally use decoder-only architectures. Why did encoder-decoder lose?

The Case for Decoder-Only

Unified Training: With decoder-only, everything is next-token prediction. You don't need paired data (source-target). Any text works.

Task Flexibility: Encoder-decoder assumes a clear input/output split. Decoder-only treats everything as a sequence to continue. Want translation? Prompt with "Translate to French: [text]". Want summarization? "Summarize: [text]". The task is implicit in the prompt.

Compute Efficiency: No separate encoder phase. During inference, you're running one forward pass per generated token, not encoder + decoder.

Interactive: Architecture Comparison

Compare how encoder-decoder and decoder-only architectures process the same task.

Architecture Comparison

Encoder-only vs Decoder-only vs Encoder-Decoder

Decoder-Only

Examples
GPT-4ClaudeLLaMAMistral
Best For
Text generationChatCodeReasoning
Attention Pattern

Causal masking (each token only sees previous)

Bidirectional
Causal
Attention Mask ()
The
cat
sat
on
mat
The
cat
sat
on
mat
Rows: query tokens • Columns: key tokens
Data Flow
Input
Decoder Stack
Causal Self-Attention
Next Token
Quick Comparison
AspectEncoder-OnlyDecoder-OnlyEnc-Dec
ContextFull bidirectionalLeft-to-right onlyBoth
GenerationLimitedNativeNative
UnderstandingExcellentGoodExcellent
2024 TrendEmbeddings/RAGDominantSeq2seq niche
Why Decoder-Only Dominates: Despite encoder-only models excelling at understanding, decoder-only models can do everything (including understanding) by framing tasks as generation. Simpler architecture + unified training objective = easier scaling.

The GPT Progression

GPT-1 (2018, 117M parameters) demonstrated that pre-training on next-token prediction followed by fine-tuning could achieve strong results. The insight: unsupervised pre-training provides a good initialization.

GPT-2 (2019, 1.5B parameters) showed zero-shot capabilities. Without any task-specific training, it could perform basic question answering, summarization, and translation. OpenAI initially declined to release the full model due to concerns about misuse.

GPT-3 (2020, 175B parameters) was the breakthrough that launched the current era. Few-shot learning worked: give the model a few examples in the prompt, and it could perform tasks it was never explicitly trained for. This was genuinely surprising.

GPT-4 (2023) introduced multimodality (images) and likely uses a Mixture of Experts architecture (though OpenAI hasn't confirmed details). Estimated at 1.7T parameters.

Chapter 5

Tokenization — The Often-Overlooked Foundation

Tokenization might be the most underappreciated component of LLMs. It determines how text is chunked into the discrete units the model processes, and it has profound implications for model behavior.

The challenge: characters are too granular (long sequences, sparse learning signal), words are too sparse (huge vocabularies, out-of-vocabulary problems). Subword tokenization finds the middle ground.

Byte Pair Encoding (BPE)

BPE is elegantly simple. Start with a vocabulary of individual characters (or bytes). Iteratively find the most frequent adjacent pair of tokens and merge them into a new token. Repeat until you reach your target vocabulary size.

The result: common words become single tokens ("the" → "the"), rare words get split into subwords ("unconstitutional" → "un" + "constitu" + "tional"), and you can always fall back to individual characters for anything unknown.

Interactive: Tokenization Playground

Type any text to see how it gets tokenized. Compare different tokenizers and see the "token tax" for different languages.

Tokenization Playground

See how text gets split into tokens

44 characters9 words
Tokenized Output19 tokens
The
·
quick
·
brown
·
fox
·
jumps
·
over
·
the
·
lazy
·
do
g
.
Tokenizer Comparison
TokenizerTokensTokens/WordEfficiency
GPT-2192.11
47%
GPT-4192.11
47%
LLaMA192.11
47%
Claude192.11
47%
The Token Tax: Different languages and content types require different numbers of tokens. Code and non-English text often require 2-3× more tokens than English prose, making them more expensive to process.

Interactive: BPE Merge Visualization

Watch BPE build a vocabulary by iteratively merging the most frequent pairs.

BPE Merge Visualization

Watch how BPE builds a vocabulary by merging frequent pairs

Step 0 / 3
Tokenized Corpus
th
ca
sa
o
th
ma
Total tokens: 17
Most Frequent Pairs
"a" + ""×3
"t" + "h"×2
"h" + ""×2
"c" + "a"×1
"s" + "a"×1
Vocabulary10 tokens
achmost
Merge Progress0%
How BPE Works: Starting with individual characters, BPE iteratively merges the most frequent adjacent pair into a new token. Common words become single tokens ("the"), while rare words are split into subwords. The merge order determines the final tokenization.

The Real-World Impact

Tokenization quirks have real consequences:

  • Token fertility: English averages ~1.3 tokens per word. Some languages require 2-3x more tokens for the same content, making them more expensive to process.
  • Arithmetic failures: Numbers often get tokenized inconsistently. "1234" might be one token but "12345" might be "123" + "45". This makes arithmetic unreliable.
  • Code handling: Whitespace-sensitive languages (Python) need careful tokenization to preserve indentation semantics.
Chapter 6

Modern Positional Encoding — RoPE, ALiBi, and Beyond

Sinusoidal positional encodings worked, but they had limitations. The biggest: extrapolation. Train on sequences up to 2048 tokens, and performance degrades on longer sequences. The model hasn't seen those position values before.

RoPE: Rotary Position Embeddings

RoPE, used by LLaMA and many others, encodes position through rotation. Instead of adding positional information to embeddings, RoPE applies rotation matrices to query and key vectors.

The key insight: when you take the dot product of two rotated vectors, the result depends only on their angle difference—which is proportional to the position difference. Position becomes relative, encoded in the geometry of the operation itself.

Interactive: RoPE Rotation Visualizer

Visualize how RoPE encodes position through rotation. The dot product between Q and K depends only on their relative position.

RoPE Rotation Visualizer

See how Rotary Position Embeddings encode position

2D Rotation (dim 0, 1)
0.0°x (dim 0)y (dim 1)
Gray: original • Rose: after RoPE rotation
Rotation Matrix
For position 0, dimension pair 0:
cos(θ) = 1.0000
-sin(θ) = 0.0000
sin(θ) = 0.0000
cos(θ) = 1.0000
Frequency (θd)1.00e+0
Angle (m × θd)0.0000 rad
Angle in degrees0.0°
All Dimension Pairs at Position 0
Dim 0-1
0°
Dim 2-3
0°
Dim 4-5
0°
Dim 6-7
0°
Dim 8-9
0°
Dim 10-11
0°
Dim 12-13
0°
Dim 14-15
0°
Lower dimensions rotate faster (higher frequency). Click to select.
Position-Dimension Angle Matrix
d0
d1
d2
d3
d4
d5
d6
d7
pos 0
pos 1
pos 2
pos 3
pos 4
pos 5
pos 6
pos 7
Color intensity = |sin(angle)|. Notice patterns: low dims cycle fast, high dims cycle slow.
Why RoPE Works: By encoding position as rotation, the relative position between tokens becomes a rotation difference. When computing Q·K^T, these rotations create position-aware attention that's inherently translation-equivariant and extrapolates better to longer sequences than absolute embeddings.

ALiBi: Attention with Linear Biases

ALiBi takes a radically different approach: no learned positional encoding at all. Instead, it adds a linear penalty to attention scores based on distance: positions farther apart get lower attention scores.

Different heads use different slopes, allowing some to focus locally and others to attend more globally. ALiBi extrapolates perfectly to any length (with the assumption that recency matters), though it can't learn arbitrary position-dependent patterns.

Chapter 7

Attention Variants for Efficiency

The KV-cache is both a blessing and a curse. During autoregressive generation, we cache the key and value tensors from previous tokens to avoid recomputation. Essential for reasonable inference speed. But memory consumption scales with: layers × heads × head_dim × sequence_length × batch_size.

For a 70B model serving a 128K context, the KV-cache alone can consume 80+ GB—often more than the model weights themselves.

Multi-Query and Grouped-Query Attention

Multi-Query Attention (MQA) shares a single key and value head across all query heads. KV-cache shrinks by a factor of the number of heads. Quality degrades slightly (5-10%).

Grouped-Query Attention (GQA) is the compromise. Groups of query heads share KV heads. LLaMA 2 70B uses 64 query heads with 8 KV groups—an 8× reduction in KV-cache with quality within 1% of full attention after uptraining.

Interactive: KV-Cache Memory Calculator

Calculate KV-cache memory requirements for different model configurations and attention variants.

KV-Cache Memory Calculator

Calculate memory requirements for different attention variants

1K128K
164
KV-Cache
2.00 GB
512.00 KB per token
Model Weights (est.)
384.0 MB
32 layers × 32 heads
Total Memory
2.38 GB
Fits in A100-80GB
Memory Breakdown
Model WeightsKV-CacheAvailable
Formula
KV-Cache = 2 × layers × kv_heads × head_dim × seq_len × batch × bytes_per_element

Sliding Window Attention

Sliding window attention restricts each token to only attend within a fixed window. O(n × w) complexity instead of O(n²), and the KV-cache has a fixed maximum size regardless of sequence length.

The trick: information can still propagate across the full sequence through layer stacking. With window w and L layers, the effective receptive field is L × w. Mistral uses this with "attention sinks"—always attending to the first few tokens to anchor the representation.

Interactive: Sliding Window Receptive Field

See how information propagates through layers with sliding window attention. The effective receptive field grows with depth.

Sliding Window Attention

See how receptive field grows through layers

Receptive Field Growth (Token T7)
Input
0
1
2
3
4
5
6
7
8
9
10
11
Layer 1
0
1
2
3
4
5
6
7
8
9
10
11
can see 3-7
Layer 2
0
1
2
3
4
5
6
7
8
9
10
11
can see 0-7
Layer 3
0
1
2
3
4
5
6
7
8
9
10
11
can see 0-7
Layer 4
0
1
2
3
4
5
6
7
8
9
10
11
can see 0-7
Query token
In receptive field
Not visible
Sliding Window Attention
Window Size4
Direct Attention CostO(4)
Effective Receptive Field8 tokens
After 4 layers4 × 4 = 16
Full Attention (Comparison)
Attention RangeAll previous
Direct Attention CostO(8)
Memory Savings50%
KV-Cache Size8 vs 4
Attention Mask Comparison
Full Causal Attention
O(n²) memory
Sliding Window (w=4)
O(n × w) memory
Window Size
4
Total Receptive
8
Memory Reduction
2.0×
Coverage
100%
Sliding Window Magic: With window size W and L layers, a token can attend to W×L positions through information propagation. Mistral uses W=4096, so with 32 layers, effective context is 131K tokens while keeping O(n×W) memory — enabling long sequences without the quadratic cost.
Chapter 8

Mixture of Experts — Scaling Parameters Without Scaling Compute

Here's the scaling dilemma: more parameters generally mean better performance, but more parameters also mean more compute per token. Mixture of Experts (MoE) breaks this link.

Replace the dense FFN with N expert FFNs. A router network selects the top-k experts for each token. Most parameters are inactive for any given token—you get the capacity of a large model with the compute cost of a smaller one.

Mixtral: A Concrete Example

Mixtral 8x7B has 8 experts with top-2 routing. Total parameters: 46.7B. Active parameters per token: ~12.9B. It matches or exceeds LLaMA 2 70B on most benchmarks while using similar compute to a 13B dense model.

Interactive: MoE Routing Visualization

Watch how tokens get routed to different experts. See load balancing in action.

MoE Routing Visualization

Loading...

The Load Balancing Challenge

Without careful design, the router might learn to always use the same few experts— "expert collapse." An auxiliary load balancing loss encourages even distribution:

L_aux = α × N × Σ(fraction_i × router_prob_i)

The infrastructure implications are significant. All expert parameters must fit in memory (or be distributed with expert parallelism), but compute scales only with active parameters. This creates an unusual memory-compute trade-off.

Chapter 9

Flash Attention — IO-Aware Algorithm Design

Flash Attention is perhaps my favorite example of infrastructure-aware algorithm design. The insight: on modern GPUs, compute is cheap but memory bandwidth is expensive.

An H100 has 3,958 TFLOPS of FP16 compute but only 3.35 TB/s of HBM bandwidth. Standard attention computes the n×n attention matrix, writes it to HBM, reads it back for softmax, writes again, reads for the final matmul. All that memory movement dominates runtime.

The Tiling Solution

Flash Attention never materializes the full n×n matrix. It processes Q, K, V in tiles that fit in SRAM (the GPU's fast on-chip memory). The key enabler is online softmax—computing softmax incrementally as new blocks arrive, tracking running statistics rather than needing all values upfront.

Interactive: Memory Access Patterns

Compare standard vs Flash Attention memory access patterns. See how tiling dramatically reduces HBM traffic.

Flash Attention Memory Access

Compare standard vs IO-aware attention

Step 1/6Load Q, K matrices to HBMREAD
HBM (GPU Memory)
~2 TB/s bandwidth
Q
Q
K
K
Stores full n×n attention matrix
SRAM (On-chip)
~19 TB/s bandwidth
Underutilized
HBM
Slow
Many transfers
SRAM
Fast
Q (Query)
K (Key)
V (Value)
S (Scores)
P (Softmax)
O (Output)
Memory Complexity
O(n²)
HBM Reads
O(n²)
Speedup
Max Sequence
~8K
IO-Aware Algorithm: Flash Attention never materializes the full n×n attention matrix in HBM. By computing softmax in blocks within fast SRAM and using online softmax tricks, it reduces memory IO from O(n²) to O(n²/M) where M is SRAM size — trading extra FLOPs for much faster wall-clock time.

The results are dramatic:

  • Memory: O(n) instead of O(n²)
  • Speed: 2-9× faster depending on sequence length
  • Efficiency: Flash Attention 2 achieves 50-73% of theoretical FLOPS

This is the kind of algorithm you get when systems engineers and ML researchers collaborate closely. The math is the same—the implementation just respects the hardware reality.

Chapter 10

Training at Scale

Training a 70B+ parameter model requires careful orchestration of parallelism strategies. No single GPU can hold the model, and naive approaches waste compute or run out of memory.

The Parallelism Strategies

Data Parallelism: Each GPU holds a full model copy and processes different batches. Gradients are synchronized via all-reduce. Scales compute but not memory.

Tensor Parallelism: Split individual layers horizontally across GPUs. The attention and FFN weight matrices are sharded. Requires communication every layer—needs fast NVLink (400-900 GB/s).

Pipeline Parallelism: Split layers vertically—different GPUs own different layers. Communication only at stage boundaries. InfiniBand (200-400 Gb/s) is sufficient. Uses micro-batching to hide pipeline bubbles.

Interactive: Parallelism Strategies

Visualize how different parallelism strategies distribute model and data across GPUs.

Parallelism Strategy Visualizer

Compare DP, TP, PP, and FSDP approaches

Data Parallelism

Same model on each GPU, different data batches. Gradients synchronized.

GPU Distribution
GPU 0
L0
L1
L2
L3
Batch 0
GPU 1
L0
L1
L2
L3
Batch 1
GPU 2
L0
L1
L2
L3
Batch 2
GPU 3
L0
L1
L2
L3
Batch 3
Advantages
  • +Simple to implement
  • +Linear scaling
  • +Works with any model
Challenges
  • Each GPU needs full model
  • Memory limited by single GPU
  • Gradient sync overhead
Memory/GPU
~140 GB
Communication
AllReduce gradients
Best For
Small models
Typical Scale
1-8 GPUs
Common Combinations (3D Parallelism)
LLaMA 70B
TP=8 within node
PP=1, DP for batch
GPT-3 175B
TP=8, PP=8
64 GPUs minimum
Training at Scale
FSDP + TP hybrid
1000s of GPUs
Combining Strategies: Real-world training uses multiple parallelism types together. TP within a node (fast NVLink), PP across nodes, and FSDP for memory efficiency. The goal: maximize GPU utilization while fitting the model.

ZeRO: Memory Efficiency for Data Parallelism

ZeRO (Zero Redundancy Optimizer) eliminates memory redundancy in data parallelism. Standard DDP stores optimizer states, gradients, and parameters on every GPU. ZeRO shards them:

  • Stage 1: Shard optimizer states (4× memory reduction for Adam)
  • Stage 2: Also shard gradients
  • Stage 3: Also shard parameters (requires gather before forward/backward)

Scaling Laws: The Chinchilla Revolution

In 2022, DeepMind's Chinchilla paper upended conventional wisdom. GPT-3 (175B params, 300B tokens) was undertrained. The compute-optimal ratio is roughly 20 tokens per parameter.

Chinchilla (70B params, 1.4T tokens) matched GPT-3's performance with 4× fewer parameters— smaller, faster to run, trained with the same compute budget but allocated differently.

Interactive: Scaling Law Explorer

Explore the compute-optimal frontier. See where different models fall relative to the Chinchilla-optimal line.

Scaling Law Explorer

Explore the Chinchilla compute-optimal frontier

0.1 (GPT-2)100 (LLaMA 3)
Parameters (Billions)
Training Tokens (Billions)
Optimal Parameters
2.9B
For 1.0 × 10²¹ FLOPs
Optimal Tokens
58B
~20× parameter count
Tokens per Param
20.0
Chinchilla optimal: 20
The Chinchilla Revolution: GPT-3 (175B params, 300B tokens) was massively undertrained. Chinchilla (70B params, 1.4T tokens) achieved similar performance with 60% fewer parameters by training longer. Modern models like LLaMA 3 push even further, training on 200+ tokens per parameter for better inference efficiency.
Chapter 11

Inference Optimization

Training costs are one-time. Inference costs are forever. For widely-used models, inference optimization matters enormously for both cost and user experience.

The KV-Cache Lifecycle

During autoregressive generation, each new token requires attending to all previous tokens. Without caching, you'd recompute K and V for the entire context on every step—O(n²) total compute.

With KV-caching, you compute K and V once per token and store them. Each generation step then only needs O(n) compute. The trade-off: memory consumption grows linearly with context length.

Interactive: Token Generation Animation

Watch the autoregressive generation process step by step. See the KV-cache grow as tokens are generated.

Token Generation Animation

Watch autoregressive generation with KV-cache growth

Step 0 / 6
Generated Sequence
Thequickbrownfox
KV-Cache
4 entries
P0
P1
P2
P3
?
?
?
?
?
?
Prompt Tokens
4
Generated Tokens
0
KV-Cache Size
4
Cache Growth
0%
Current Step
Press Generate to start. The model will predict one token at a time, caching K/V for reuse.
Why KV-Cache Matters: Without caching, each new token would require recomputing K and V for all previous tokens — O(n²) total compute. With caching, we only compute K/V for the new token and reuse cached values — O(n) total, but memory grows linearly.

PagedAttention: Virtual Memory for KV-Cache

PagedAttention (introduced in vLLM) applies virtual memory concepts to KV-cache management. Instead of pre-allocating the maximum possible sequence length, allocate memory in small blocks on demand.

A page table maps logical KV positions to physical memory blocks. Benefits:

  • Near-zero memory fragmentation
  • Memory allocated only as needed
  • Prefix sharing: requests with common prefixes share KV blocks

Interactive: PagedAttention Visualization

See how PagedAttention manages memory dynamically, allocating and recycling blocks as sequences progress.

PagedAttention Visualizer

Watch dynamic KV-cache block allocation

Physical Memory Pool24 blocks × 16 tokens each
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Active Requests
No active requests. Click "Add Request" to start.
Memory Utilization
0%
Used Blocks
0
Free Blocks
24
Active Requests
0
PagedAttention Benefits: Traditional KV-cache pre-allocates maximum sequence length per request, wasting memory. PagedAttention allocates small blocks on-demand and recycles them when requests complete — achieving near-zero fragmentation and enabling prefix caching for shared prompts.

Speculative Decoding

Speculative decoding uses a small, fast "draft" model to propose multiple tokens, then the large "target" model verifies them in parallel. If the draft matches, you've generated multiple tokens in essentially one target forward pass.

Typical speedups: 2-3× for latency. Works best when the draft model is a good approximation— you can use a quantized version of the target, a distilled variant, or a specialized small model.

Interactive: Speculative Decoding Demo

Watch how draft and target models work together to accelerate generation.

Speculative Decoding Demo

Draft model proposes, target model verifies

Phase: Idle
Generated Sequence
The capital of France is
Draft Model (7B)Fast, smaller
Waiting to draft tokens...
Target Model (70B)Accurate, larger
Waiting to verify...
Process Flow
1
Draft K tokens
2
Verify in parallel
3
Accept prefix
4
Resample
Accepted Tokens
0
Rejected Tokens
0
Acceptance Rate
0%
Speedup (est.)
1.0×
How It Works: A small draft model quickly generates K candidate tokens. The large target model verifies them all in a single forward pass (parallel). We accept the longest matching prefix and resample from there — achieving 2-3× speedup while maintaining exact output distribution.
Chapter 12

Long Context — The Frontier

Standard attention is O(n²) in both memory and compute. At 128K tokens, that's 16 billion attention elements per layer. The quadratic wall is the fundamental bottleneck for long-context processing.

Interactive: Quadratic Complexity Visualizer

See how attention complexity scales with sequence length. The quadratic growth quickly becomes prohibitive.

Attention Complexity Visualizer

See how O(n²) quadratic complexity scales

4K32K128K1M+
Standard Attention O(n²)
16.8M
operations
Linear Attention O(n)
4.1K
operations
Quadratic vs Linear
4.1K×
more operations for quadratic
Attention Matrix
32.0 MB
for full n×n matrix (FP16)
Feasibility
Standard
Works with Flash Attention
Scaling Comparison
SequenceO(n²) OpsO(n) OpsMemory (n²)
1.0K1.0M1.0K2.0 MB
4.1K16.8M4.1K32.0 MB
16.4K268.4M16.4K512.0 MB
65.5K4.3B65.5K8.0 GB
262.1K68.7B262.1K128.0 GB
1.0M1.1T1.0M2048.0 GB
The Quadratic Wall: At 128K tokens, standard attention requires 16 billion operations and 32 GB just for the attention matrix. This is why Flash Attention, sparse patterns, and state space models are essential for long-context processing.

Sparse Attention Patterns

Sparse attention reduces complexity by only computing a subset of attention pairs:

  • Longformer: Local sliding window + global tokens
  • BigBird: Random + window + global patterns
  • Theoretical result: sparse patterns can be universal approximators

Interactive: Sparse Attention Patterns

Compare different sparse attention patterns and their coverage of the full attention matrix.

Sparse Attention Patterns

Compare full vs sparse attention strategies

Full Attention

Every token attends to every other token. Baseline approach.

Complexity
O(n²)
GPT-2BERTStandard Transformers
Attention Pattern
Rows: query • Columns: key (causal masking applied)
0
1
2
3
4
5
6
7
8
9
10
11
0
1
2
3
4
5
6
7
8
9
10
11
Attends
Masked
Sparsity
46%
Active Connections
78
Full Attention Would Be
78
Memory Savings
1.8×
Pattern Comparison
PatternComplexityLong ContextTrade-off
Full AttentionO(n²)❌ LimitedQuality baseline
Sliding WindowO(n × w)⚠️ Local onlyFast but may miss long-range
Dilated/StridedO(n × w)✓ ExpandedBetter coverage, fixed pattern
LongformerO(n × w + g × n)✓ Global + LocalBest of both worlds
BigBirdO(n × (w + g + r))✓ Global + LocalRandom helps coverage
Sparse Attention Trade-offs: Full attention captures all relationships but is O(n²). Sparse patterns reduce complexity to O(n) but must carefully choose which connections to keep. Longformer/BigBird combine local context (sliding) with global tokens for the best coverage at linear cost.

State Space Models and Alternatives

State Space Models like Mamba offer a different paradigm: O(n) training and inference with O(1) memory during inference. They use structured recurrence that can be computed efficiently via convolution during training.

Hybrid approaches like Jamba combine SSM layers with Transformer layers, getting benefits of both architectures.

RAG: Sidestepping the Problem

Retrieval-Augmented Generation avoids the long-context problem entirely. Instead of fitting everything into context, retrieve relevant chunks from an external knowledge base and include only those.

Trade-offs: latency (retrieval adds time), retrieval quality (wrong chunks = wrong answers), and complexity (another system to maintain).

Chapter 13

Practical Infrastructure Decisions

Let's translate all this technical understanding into practical deployment decisions. After years of deploying ML models, I've learned that the gap between "works in notebook" and "works in production" is vast.

Memory Planning

Start with back-of-envelope calculations:

  • Model weights: params × bytes_per_param (2 for FP16, 1 for INT8)
  • KV-cache: 2 × layers × kv_heads × head_dim × seq_len × batch × bytes
  • Activations: varies, but budget 10-20% overhead

Parallelism Strategy Selection

Rules of thumb:

  • < 15B: Single GPU or simple data parallelism
  • 15-70B: Tensor parallelism within a node (NVLink required)
  • 70-200B: Add pipeline parallelism across nodes
  • > 200B: Full 3D parallelism (DP + TP + PP)

Interactive: Deployment Calculator

Plan your deployment: enter model specs and requirements, get hardware recommendations.

LLM Deployment Calculator

Plan hardware requirements for your deployment

Model Weights
13.0 GB
Total KV-Cache
20.0 GB
2.0 GB per request
GPUs Required
1× A100 80GB
Parallelism
Single GPU
Performance Estimates (approximate)
Prefill Latency (TTFT)
368 ms
Token Latency (ITL)
0.1 ms
Est. Throughput
6686 tok/s
Recommendations
  • KV-cache dominates memory; consider GQA model or shorter context
Deployment Checklist
Fits on single GPU
NVLink available (for TP)
Meets throughput target
Memory headroom (>10%)

Key Metrics to Track

Time to First Token (TTFT): Interactive latency. Users notice delays beyond 500ms. Critical for chat applications.

Inter-Token Latency (ITL): Streaming smoothness. Should stay under 50ms for natural-feeling output.

Throughput: Tokens per second across all requests. The key metric for cost optimization. Continuous batching and speculative decoding can dramatically improve this.