Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

LLM & AI Cheat Sheet

Transformer Architecture

Input → Tokenization → Embedding + Positional Encoding
  → [Encoder: Multi-Head Attention → Add&Norm → FFN → Add&Norm] × N
  → [Decoder: Masked MHA → Cross-Attention → FFN] × N
  → Linear → Softmax → Output Probabilities

Key Concepts

ConceptWhatWhy It Matters
Self-AttentionQ·K^T/√d → softmax → VCaptures long-range dependencies
Multi-HeadParallel attention headsDifferent relationship types
Positional EncodingInject sequence orderAttention is permutation-invariant
KV CacheCache past K,V during generationAvoid recomputation, 10-100x speedup
Residual Connectionx + F(x)Gradient flow, training stability
Layer NormNormalize across featuresStabilizes training

Attention Formulas

Attention(Q,K,V) = softmax(QK^T / √d_k) × V
MultiHead = Concat(head_1, ..., head_h) × W^O
where head_i = Attention(QW_i^Q, KW_i^K, VW_i^V)

Complexity: O(n²d) time, O(n² + nd) memory

LLM Training Pipeline

1. Pre-training (next token prediction on massive corpus)
   → Foundation model (GPT, Llama, Mistral)
2. Supervised Fine-Tuning (SFT)
   → Instruction-following on curated examples
3. Alignment (RLHF / DPO / GRPO)
   → Human preferences → helpful, harmless, honest
4. Deployment (quantization, serving optimization)

RLHF vs DPO

RLHFDPO
ApproachTrain reward model → PPODirect preference optimization
ComplexityHigh (3 models)Lower (1 model)
StabilityCan be unstableMore stable
FormulaReward + KL penaltyLoss on preference pairs

Inference Optimization

TechniqueSpeedupTrade-off
KV Cache10-100xMemory
Quantization (INT8/INT4)2-4xSlight quality loss
Speculative Decoding2-3xExtra small model needed
Continuous Batching2-5xImplementation complexity
Flash Attention2-4xMemory efficient
PagedAttention1.5-3xVirtual memory for KV
Tensor ParallelismLinear w/ GPUsCommunication overhead

Quantization

FP32 → FP16/BF16 → INT8 → INT4
  4B     2B        1B     0.5B  (per param)

Post-Training (PTQ): Calibrate after training (GPTQ, AWQ, GGUF)
Quantization-Aware (QAT): Simulate during training

RAG (Retrieval-Augmented Generation)

Query → Embed → Vector Search → Retrieved Docs → LLM + Context → Answer

Components: Embedding model, Vector DB, Chunking strategy, Reranker
Chunking: Fixed-size, Recursive, Semantic
Vector DBs: Pinecone, Weaviate, Milvus, ChromaDB, FAISS

AI Agents

User → LLM → [Think → Act → Observe] loop → Response

ReAct: Reasoning + Acting (interleaved)
Chain-of-Thought: Step-by-step reasoning
Tool Calling: LLM invokes external tools/APIs
MCP: Model Context Protocol (standardized tool interface)
Multi-Agent: Multiple specialized agents collaborating

Tokenization

MethodUsed ByPros
BPEGPT, LlamaGood balance
WordPieceBERTLinguistic awareness
SentencePieceT5, mBARTLanguage-agnostic
UnigramSome modelsProbabilistic

Positional Encoding Types

TypeMax LengthExtrapolation
SinusoidalFixedPoor
LearnedFixedPoor
RoPEFlexibleGood
ALiBiVery longExcellent

Key Models Quick Reference

ModelParamsKey Feature
GPT-4/4o~1.8T (MoE)Multimodal, best reasoning
Claude 3.5UnknownLong context, safety
Gemini 1.5Up to 1T1M+ context, multimodal
Llama 38B-405BOpen source leader
Mistral/Mixtral7B-8x22BMoE, efficient
DeepSeek-V3671B MoEOpen, strong coding
Qwen 2.50.5B-72BMultilingual

Serving Systems

SystemKey Feature
vLLMPagedAttention, continuous batching
TensorRT-LLMNVIDIA optimized
TGIHuggingFace production
OllamaLocal, easy setup
SGLangStructured generation

Embeddings

Text → Embedding Model → Dense Vector (768-4096 dim)
Similarity: cosine(q, d) = (q·d) / (||q|| × ||d||)
Models: text-embedding-3-large (OpenAI), BGE, E5, GTE

Interview Quick Tips

  1. Know the transformer architecture cold (encoder, decoder, attention)
  2. Explain KV cache and why it matters for inference
  3. Compare RLHF vs DPO trade-offs
  4. Describe RAG pipeline with failure modes
  5. Discuss agent architectures (ReAct, tool calling)
  6. Know quantization types and trade-offs
  7. Understand scaling laws (Chinchilla)