# DMXSF > Learn large language model (LLM) algorithms with tutorials, runnable labs, and paper explainers on Transformers, training, inference, RAG, and agents. A continuously maintained tutorial on LLM algorithms. It is organized in four parts, chapters follow a learning order, and every page states what you will be able to do afterwards and what to read first. Pages connect through prerequisites and related reading. ## Where to start - [Knowledge map](https://dmxsf.com/en/wiki/map.md): The whole wiki on one page: every page of the four parts and twelve chapters. Hover or tap a page to highlight what it builds on and what builds on it, overlay a study route, and see how far you have read. - [LLM glossary](https://dmxsf.com/en/glossary.md): Plain definitions of the terms you meet when learning large language models: Transformer, attention, KV cache, RoPE, LoRA, RLHF, RAG, MoE and more, each linked to a full lesson in the wiki. - [Companion code: run the course's algorithms yourself](https://dmxsf.com/en/code.md): The DMXSF companion repository provides 61 Python labs for a laptop CPU, covering all 66 wiki articles with runnable material and checking their core formulas and mechanisms. - [dmxsf/dmxsf](https://github.com/dmxsf/dmxsf): Repository ## Getting Started - [Getting Started](https://dmxsf.com/en/wiki/start.md): New to large language models? Build an end-to-end picture first, then pick one of four study routes (weekend crash course, application development, engineering or research), and see how this wiki is organized and meant to be read. - [What Is a Large Language Model? From Next-Word Prediction to General Assistants](https://dmxsf.com/en/wiki/start/what-is-an-llm.md): A large language model (LLM) is a neural network, usually a Transformer, trained on huge amounts of text to predict the next token; pre-training, post-training and inference decoding turn it into an assistant that can chat, write code and reason. - [LLM Learning Roadmap: A Map of the Wiki and Four Study Paths](https://dmxsf.com/en/wiki/start/learning-roadmap.md): See how the wiki's four parts and twelve chapters fit together, then pick a path by goal: a 10-hour weekend crash course, an 8-week application path, a 14-week engineering path or a 16-week research path, each with weekly reading, exercises and deliverables. - [Learning Resources Map: Courses, Books and Repositories to Pair with This Wiki](https://dmxsf.com/en/wiki/start/resources.md): A map of public courses, books, explainers, code repositories and Chinese-language resources to pair with this wiki, grouped by learning goal: what each adds, what background it assumes and which wiki pages to read with it. Every link was opened and checked in November 2026. - [LLM Cheat Sheet: Estimating Parameters, Compute, Memory and Decoding Speed](https://dmxsf.com/en/wiki/start/cheat-sheet.md): One page for the estimates you reuse most: counting parameters, training compute (about 6ND), memory for weights, training state and the KV cache, the bandwidth bound on decoding speed, and the LoRA and pass@k formulas, each with a standard-library script checked against published numbers. ## Foundations - [Foundations](https://dmxsf.com/en/wiki/foundations.md): Language modeling, neural networks, information theory, tokens and embeddings, and optimizers: the lowest-level primitives of an LLM, and the reason behind almost every design decision that follows. - [Python and tensor shapes: from a table to a linear layer](https://dmxsf.com/en/wiki/foundations/tensors-and-shapes.md): Start with a table of numbers, name the position and feature axes, and calculate a dot product and bias before running a linear layer in standard Python. - [From Language Modeling to Next-Token Prediction](https://dmxsf.com/en/wiki/foundations/next-token-prediction.md): Language modeling estimates the probability of a text and uses the chain rule to split it into a product of "predict the next token given the prefix"; training uses cross-entropy, evaluation uses perplexity, and the causal mask hides future tokens. - [Neural Network Basics: From Linear Layers to Backpropagation](https://dmxsf.com/en/wiki/foundations/neural-network-basics.md): A neural network chains linear maps and nonlinearities. Backpropagation (the chain rule) gives the loss gradient for every parameter, and training steps against it. This page builds a two-layer net in NumPy, checks its gradients, and runs learning-rate and initialization experiments. - [Information Theory Refresher: Entropy, Cross-Entropy and KL Divergence](https://dmxsf.com/en/wiki/foundations/information-theory.md): Entropy measures how surprising a distribution is on average, cross-entropy is the cost of coding data from p with a code built for q, and KL divergence is the excess over the optimum. A language model's training loss is cross-entropy; perplexity is its exponential. - [Tokenizers and Embeddings: BPE, Vocabulary Size and the Embedding Table](https://dmxsf.com/en/wiki/foundations/tokenizer-and-embeddings.md): An LLM only processes integers: a tokenizer splits text into tokens with a subword algorithm such as BPE and maps them to ids, then each id is looked up in a vocabulary-size by hidden-size embedding table. Vocabulary size trades off sequence length, parameters and long-tail coverage. - [Optimizers and Training Stability: AdamW, Warmup, Mixed Precision, Loss Spikes](https://dmxsf.com/en/wiki/foundations/optimizers-and-training-stability.md): Large-model pretraining almost always uses AdamW with linear warmup plus cosine (or WSD) decay, gradient clipping and mixed precision. This page explains what each hyperparameter is for and gives a checklist for loss spikes and NaNs. ## Model Architecture - [Model Architecture](https://dmxsf.com/en/wiki/architecture.md): From the bottleneck of RNNs to attention, then the complete Transformer block, RoPE, GQA, MoE, long context, and the state space models and hybrids that trade the KV cache for a fixed-size state: the structure of modern LLMs and the reasoning behind each choice. - [From RNNs to Attention: Why the Transformer Appeared](https://dmxsf.com/en/wiki/architecture/from-rnn-to-attention.md): An RNN squeezes history into one fixed-size state and computes it step by step, so gradients pass through a long chain of multiplications. Attention lets every position read every other position directly, in parallel. Experiments measure vanishing gradients, gating and the copy bottleneck. - [Attention Basics: How a Transformer Reads Context](https://dmxsf.com/en/wiki/architecture/attention-basics.md): Understand Q/K/V, scaled dot-product attention and multi-head attention through intuition, a worked numeric example and a minimal code sample. - [Positional Encoding Explained: Absolute, Relative and RoPE](https://dmxsf.com/en/wiki/architecture/positional-encoding.md): Self-attention cannot see token order, so positional encodings tell the model where a token is or how far apart two tokens are: sinusoidal and learned encodings are added to the input, relative biases and ALiBi act on attention scores, and RoPE rotates queries and keys. - [Transformer Block Explained: Attention, FFN, Residuals and LayerNorm](https://dmxsf.com/en/wiki/architecture/transformer-block.md): A Transformer block is multi-head attention plus a feed-forward network (FFN), each wrapped in a residual connection and LayerNorm. This page gives the equations, Pre-Norm versus Post-Norm, a parameter count (about 12d²) and runnable PyTorch code. - [Modern LLM Architecture: From GPT-2 to Llama, Qwen and DeepSeek](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture.md): Almost every mainstream open LLM is a refined decoder-only Transformer: Pre-Norm with RMSNorm, a SwiGLU feed-forward network, RoPE positions and GQA attention, and some add mixture of experts (MoE) to grow parameters without growing compute in proportion. - [Efficient Attention: MQA, GQA, MLA and FlashAttention](https://dmxsf.com/en/wiki/architecture/efficient-attention.md): Attention has two bottlenecks: the KV cache that decoding rereads at every step, and the N×N score matrix of training and prefill. MQA, GQA and MLA shrink the KV cache; FlashAttention cuts memory traffic with tiling and online softmax, and its output is identical to standard attention. - [Mixture of Experts (MoE): Routing, Load Balancing and Sparse Activation](https://dmxsf.com/en/wiki/architecture/mixture-of-experts.md): A mixture-of-experts layer swaps the feed-forward network for many experts and routes each token to only k of them, so total parameters grow while per-token compute stays small. This page computes total and active parameters for Mixtral and DeepSeek-V3 and lets you try load balancing. - [Long Context: Position Extrapolation, Training Recipes and Cost](https://dmxsf.com/en/wiki/architecture/long-context.md): Extending a context window from 4K to 128K takes three fixes: RoPE extensions (PI, NTK-aware scaling, YaRN) for unseen positions, staged continued training on long text, and a budget for attention compute and KV cache. This page covers all three with formulas, code and two interactive tools. - [State Space Models and Hybrids: Trading the KV Cache for a Fixed-Size State](https://dmxsf.com/en/wiki/architecture/state-space-and-hybrid.md): Linear attention, state space models (Mamba) and the gated delta rule compress history into a fixed-size state: memory stays flat as context grows, but capacity is limited by the state size. Hybrids keep a few attention layers for exact recall; Jamba's KV cache is 1/8 of Mixtral's. ## Compute and Systems - [Compute and Systems](https://dmxsf.com/en/wiki/systems.md): GPU compute and bandwidth, the roofline model, numerical precision and collective communication. The same algorithm can differ tenfold in speed with another implementation, batch size or precision, so the hardware limits have to be understood first. - [LLM hardware basics: CPUs, GPUs, memory, and moving data](https://dmxsf.com/en/wiki/systems/hardware-basics.md): Follow a model request through disk, host and device memory, and CPU and GPU work. Estimate tensor storage and copy time to distinguish capacity, bandwidth, and compute before diagnosing inference. - [GPUs and the Roofline Model: Why Big Models Are Bound by Memory Bandwidth](https://dmxsf.com/en/wiki/systems/gpu-and-roofline.md): A GPU is limited by two walls: how many operations it can do per second (compute) and how many bytes it can move per second (memory bandwidth). The roofline model uses arithmetic intensity to tell which wall an operator hits first. This page derives it and measures it on a CPU. - [GPU kernels: from tiled matrix multiplication to fusion](https://dmxsf.com/en/wiki/systems/gpu-kernels.md): GPU kernel tuning combines thread-level memory access, on-chip reuse, and output stores. Derive the logical traffic of tiled matrix multiplication with edge masks, check it with a CPU experiment, and trace practical limits from staging buffers to register spills. - [Numerical Precision: Three Ways FP16, BF16 and FP8 Training Goes Wrong](https://dmxsf.com/en/wiki/systems/numerical-precision.md): Floating-point formats split a few bits between exponent (range) and mantissa (precision). Low-precision training fails in three ways: overflow, underflow (small gradients become 0) and swamping (small terms vanish in sums). Real Qwen2.5-0.5B data shows how large each is and what fixes it. - [Collective Communication: Why All-Reduce Has So Many Algorithms](https://dmxsf.com/en/wiki/systems/collective-communication.md): Collective communication is the plumbing of multi-GPU training. This page simulates five all-reduce algorithms and checks them element by element, compares rounds and traffic with the alpha-beta model, then shows how topology, summation order and MoE all-to-all change the choice. ## Pre-training - [Pre-training](https://dmxsf.com/en/wiki/pretraining.md): The training pipeline, data engineering (filtering, deduplication, mixing), scaling laws, the compute and memory ledger and distributed parallelism: the engineering and scientific decisions that turn raw text into usable weights for a base model. - [The LLM Training Pipeline: From Data to Deployment](https://dmxsf.com/en/wiki/pretraining/training-pipeline.md): A map of the pipeline from data preparation, pretraining, SFT and preference alignment to evaluation and release, with the public data scale of each stage, plus a 0.86M-parameter byte-level GPT that trains on a laptop CPU to test data mixture, resuming and leakage. - [Pretraining Data Engineering: Filtering, Deduplication and Mixing](https://dmxsf.com/en/wiki/pretraining/data-engineering.md): A pretraining corpus is filtered, deduplicated and mixed step by step, and every step throws data away. This page shows what FineWeb, Gopher, DCLM and Llama 3 drop and why, then runs MinHash near-duplicate removal on a demo corpus: how many words may change before a copy stops counting. - [Scaling Laws: How to Split Compute Between Parameters and Data](https://dmxsf.com/en/wiki/pretraining/scaling-laws.md): From Kaplan to Chinchilla: why loss falls as a power law in parameters, data and compute, how to split a compute budget between parameters and tokens, and why today's models are trained on far more data than the compute-optimal amount. - [The Compute and Memory Ledger of Training: FLOPs, MFU and Memory Budgets](https://dmxsf.com/en/wiki/pretraining/compute-and-memory.md): How many FLOPs, GPU hours and bytes of memory does training a model need? This page works out where 6ND comes from, what MFU measures, why model states cost 16 bytes per parameter, how activation memory scales, and how to sanity-check reported GPU hours. - [Distributed Training: Data, Tensor and Pipeline Parallelism](https://dmxsf.com/en/wiki/pretraining/distributed-training.md): Data parallelism splits the batch, tensor parallelism the matrices inside a layer, pipeline parallelism the stack of layers; ZeRO and FSDP shard optimizer state, gradients and parameters. Runnable checks verify gradient averaging, ring all-reduce traffic, the Megatron split and the bubble formula. ## Post-training and Alignment - [Post-training and Alignment](https://dmxsf.com/en/wiki/post-training.md): SFT, LoRA, reward models, reinforcement learning basics (policy gradients, advantages, PPO), preference optimization (RLHF and DPO) and reinforcement learning for reasoning: how a base model is shaped into something useful and controllable that learns to solve problems deliberately. - [SFT Data: Construction and Quality Control](https://dmxsf.com/en/wiki/post-training/sft-data.md): How to weigh the quantity and quality of SFT data and check it: measured effects of data size, label noise, the loss mask and mixed-in general data (Qwen2.5-0.5B on banking77), plus rule filters, near-duplicate removal and contamination checks on Alpaca, Alpaca-cleaned and Dolly. - [LoRA Fine-Tuning in Practice](https://dmxsf.com/en/wiki/post-training/lora-finetuning.md): Over fifty training runs of Qwen2.5-0.5B on banking77: the formula, the parameter count and a from-scratch implementation, then learning rate, rank, target modules, epochs, full fine-tuning and QLoRA compared, and the pitfalls of merging and deployment, with code and numbers behind every claim. - [Reward Models: Turning Human Preferences into a Score to Optimize](https://dmxsf.com/en/wiki/post-training/reward-models.md): A reward model scores a prompt-and-response pair with one number, trained on pairwise comparisons; RLHF, rejection sampling and best-of-n all use it. This page derives the Bradley–Terry loss, measures the accuracy ceiling set by label noise, and reproduces overoptimization in simulation. - [Reinforcement Learning Basics: Policy Gradients, Advantages and PPO](https://dmxsf.com/en/wiki/post-training/rl-fundamentals.md): Policy gradients, baselines, GAE, PPO clipping and the KL penalty are the toolkit behind RLHF and reasoning RL. This page measures each on a toy task small enough to enumerate exactly: how baselines cut variance, why clipping is not a trust region, and where the KL belongs. - [Preference Optimization: From RLHF to DPO](https://dmxsf.com/en/wiki/post-training/preference-optimization.md): After SFT a model follows instructions, but its answers are not always the ones people prefer. Preference optimization aligns it using comparisons: RLHF trains a reward model and optimizes with PPO, while DPO reduces the pipeline to a classification-style loss on preference pairs. - [Reinforcement Learning for Reasoning: RLVR and GRPO](https://dmxsf.com/en/wiki/post-training/reasoning-rl.md): Since o1 and DeepSeek-R1, making a model think longer before answering has become the main line of post-training. Why verifiable rewards (RLVR) can replace a reward model, how GRPO drops the value model, and the recipe and pitfalls of R1-Zero and R1. - [Reasoning RL systems: asynchronous rollouts and policy lag](https://dmxsf.com/en/wiki/post-training/rollout-and-training.md): Reasoning RL joins generation, grading, learning, and weight publication. Asynchronous execution overlaps work and introduces policy lag. A runnable scheduling simulation separates elapsed time, accepted batches, and discarded trajectories. ## Inference and Serving - [Inference and Serving](https://dmxsf.com/en/wiki/inference.md): Decoding and sampling, the KV cache, quantization, inference serving, continuous batching and speculative decoding: how to run LLMs fast and cheaply, and how to see the trade-offs between latency, throughput and memory. - [Your first inference service: put a model function behind HTTP](https://dmxsf.com/en/wiki/inference/first-inference-service.md): Run a local inference endpoint, send JSON, and interpret status codes. Follow the model function, runtime, server, and client before learning streaming and deployment. - [Decoding and Sampling: Temperature, Top-k, Top-p and Beam Search](https://dmxsf.com/en/wiki/inference/decoding-and-sampling.md): Decoding turns the model's output distribution into tokens: greedy picks the most likely one, temperature sharpens or flattens the distribution, top-k and top-p cut off the unlikely tail, and beam search keeps several candidates. Together they set how deterministic and diverse the output is. - [KV Cache and Inference Performance](https://dmxsf.com/en/wiki/inference/kv-cache.md): Understand how the KV cache removes repeated computation from autoregressive decoding, and master the trade-offs between latency, throughput, memory and request scheduling. - [Prefix Caching and PD Disaggregation: Pay for Repeated Compute Once](https://dmxsf.com/en/wiki/inference/prefix-caching.md): Prefix caching reuses the KV cache of system prompts, shared documents, and chat history across requests (RadixAttention, CacheBlend, LMCache). PD disaggregation places compute-bound prefill and bandwidth-bound decoding on different hardware; DistServe, Splitwise, and Mooncake show when it pays off. - [Model Quantization: INT8, INT4, GPTQ and AWQ Explained and Measured](https://dmxsf.com/en/wiki/inference/quantization.md): Quantization stores weights, activations or the KV cache in fewer bits. This page starts from the memory budget, builds up from scales and groups, measures INT8 and INT4 on Qwen2.5-0.5B, implements SmoothQuant, AWQ-style scaling, GPTQ and KV-cache quantization, and ends with a selection guide. - [LLM Inference Serving: Latency Metrics, Measuring, and Choosing an Engine](https://dmxsf.com/en/wiki/inference/serving.md): A serving system has to balance time to first token, time per output token and total throughput. This page measures where one request's time goes with llama.cpp, shows why laptop benchmarks need a warm-up, and compares llama.cpp, Ollama, vLLM and SGLang. - [Continuous Batching and PagedAttention: How a Server Handles Many Requests at Once](https://dmxsf.com/en/wiki/inference/continuous-batching.md): Every decode step reads all the weights, so putting several requests in one batch raises throughput almost for free. This page measures concurrency, continuous batching, paged KV caches and prefix caching with llama.cpp to show how one GPU serves many requests. - [Speculative Decoding: Draft with a Small Model, Verify with a Large One](https://dmxsf.com/en/wiki/inference/speculative-decoding.md): Speculative decoding lets a small, fast draft model guess the next few tokens and the large model verify them in one parallel forward pass, with an accept-and-correct rule that keeps the output distribution unchanged. This page derives the expected speedup and lets you tune it interactively. ## Applications - [Applications](https://dmxsf.com/en/wiki/applications.md): Prompt engineering, structured outputs and function calling, RAG, agents, and MCP and the tool ecosystem: the engineering methods that turn a model that can talk into a product that is reliable, measurable and easy to iterate on. - [Your first agent: a read-only tool and a bounded loop](https://dmxsf.com/en/wiki/applications/first-agent.md): Use a tiny library lookup to distinguish a function call, a fixed workflow, and an agent loop. Run action, observation, and stopping cases in standard Python. - [Prompt Engineering: A Systematic Guide to Specs, Layers, Examples and Evaluation](https://dmxsf.com/en/wiki/applications/prompt-engineering.md): Design the prompt as a task interface: write a task spec, layer system, examples and context, separate format errors from wrong judgments with an eval set, and use data to decide when few-shot, chain-of-thought or structured output pays off. Includes a runnable ticket-triage experiment. - [Structured Outputs and Function Calling: From JSON Mode to Constrained Decoding](https://dmxsf.com/en/wiki/applications/structured-output-and-function-calling.md): A program can use model output reliably through prompt conventions, JSON mode, JSON Schema constrained decoding, and validate-and-retry. This page explains how token masks guarantee a format, how function-call messages flow, and why format limits can hurt reasoning. - [RAG in Practice: Chunking, Hybrid Retrieval, Reranking and Evaluation](https://dmxsf.com/en/wiki/applications/rag.md): How to build a retrieval-augmented generation system that works: clean and chunk documents, combine dense and BM25 retrieval with RRF, rerank with a cross-encoder, assemble the context, and measure every step with Hit@k and MRR on a small runnable corpus. - [Agents and Tool Calling in Practice: From Function Calling to ReAct Workflows](https://dmxsf.com/en/wiki/applications/agents-and-tool-calling.md): An agent lets the model decide the next step in a loop, and its reliability comes from the code around the loop: validation, write confirmation, step limits and evaluation. Build one with Qwen3-4B, measure on 12 support cases what guardrails catch, and learn prompt injection, MCP and pass^k. - [Agent context and memory: budgets, versions, and state](https://dmxsf.com/en/wiki/applications/context-and-memory.md): Context engineering fits instructions, tool history, and retrieved evidence into a model call. Long-term memory keeps confirmed preferences across sessions. Test whole tool turns, version precedence, deletion, and replay. - [Agent Evaluation: You Are Grading the System, Not the Model](https://dmxsf.com/en/wiki/applications/agent-evaluation.md): Agent evaluation grades the whole system — model, prompts, tools, loop, environment. An episode is tasks, trials, trajectories, and outcomes; pass^k measures reliability, stateful graders check final states, and cost is accounted per successful task. - [MCP and the Tool Ecosystem: How It Works and What to Do When Tools Pile Up](https://dmxsf.com/en/wiki/applications/mcp-and-tool-ecosystem.md): MCP, the Model Context Protocol, is the open protocol that connects AI applications to external tools and data; its 2026-07-28 revision is stateless. This page shows the protocol in real messages, measures what 96 tool definitions cost in tokens, and compares three ways to pick a tool. ## Multimodal - [Multimodal](https://dmxsf.com/en/wiki/multimodal.md): How vision and language are aligned, and how images are generated: from CLIP, LLaVA and the token cost of an image to how diffusion and flow matching build images, robot actions and text from noise, the core structures and limits of multimodal models. - [Multimodal LLMs: How an Image Becomes Tokens](https://dmxsf.com/en/wiki/multimodal/multimodal-llms.md): A vision-language model cuts an image into patches, turns them into visual tokens with a vision encoder and a projector, and feeds them to a language model. Measured here are CLIP's contrastive loss, LLaVA's two training stages, token and KV cache costs, and how resolution affects small text. - [Diffusion Models and Flow Matching: Generating Images, Actions and Text from Noise](https://dmxsf.com/en/wiki/multimodal/diffusion-and-flow-matching.md): Diffusion models turn data into Gaussian noise with a known process and train a network to undo it step by step; flow matching regresses a velocity field instead, so sampling is an ODE solve. This page builds DDPM, DDIM, flow matching and reflow on 2-D data and measures steps against quality. - [World models and planning: from prediction to closed-loop control](https://dmxsf.com/en/wiki/multimodal/world-models.md): A world model predicts how actions change state. A planner compares candidate sequences and corrects its plan with observations. This tutorial explains latent dynamics and verifies replanning after a map error with a grid simulator. ## Evaluation - [Evaluation](https://dmxsf.com/en/wiki/evaluation.md): How to show that a model got stronger: what benchmarks measure, the statistics of evaluation (pass@k, confidence intervals, sample size), LLM-as-a-Judge, building an evaluation set with reliable labels, and how benchmark contamination arises and is detected. - [LLM Evaluation Methodology: Benchmarks, Contamination and a Workflow](https://dmxsf.com/en/wiki/evaluation/llm-evaluation.md): Evaluating an LLM means estimating its performance on a whole class of tasks from a finite set of questions. This page covers what MMLU, HumanEval, GSM8K and MT-Bench measure, how to detect contamination, why a mature evaluation has four layers, and a workflow you can adopt. - [The Statistics of Evaluation: pass@k, Confidence Intervals and Sample Size](https://dmxsf.com/en/wiki/evaluation/eval-statistics.md): A benchmark score is an estimate from a finite set of questions and carries error. Learn the unbiased pass@k estimator, confidence intervals for accuracy, paired comparison of two models and how many questions detecting a gap takes, with runnable code and interactive widgets. - [LLM-as-a-Judge: Using a Model as the Grader, Its Biases and Calibration](https://dmxsf.com/en/wiki/evaluation/llm-as-judge.md): LLM-as-a-Judge lets a strong model score answers or compare them in pairs: cheap and scalable, but prone to position bias, length bias and misjudged math. Covers the judging modes, bias mitigation, measuring agreement with humans, and Bradley–Terry ranking. - [Building Evaluation Sets: Question Sources, Label Quality and Item Information](https://dmxsf.com/en/wiki/evaluation/building-eval-sets.md): An evaluation set is only as good as its coverage, labels, discrimination and freshness. This page designs one from the decision it supports, then simulates how label errors lower scores and inflate sample sizes, why Cohen's kappa tracks class balance, and which items separate models. - [Benchmark Contamination: How It Happens, How to Detect It, How to Avoid It](https://dmxsf.com/en/wiki/evaluation/benchmark-contamination.md): Benchmark contamination means evaluation questions, answers or paraphrases of them ended up in a model's training data, so scores measure memory instead of ability. A small experiment with known ground truth measures the dose-response and what n-gram and model-based detectors catch or miss. - [Production evaluation for LLMs: replay, canaries, and rollback](https://dmxsf.com/en/wiki/evaluation/production-evaluation.md): Production evaluation connects model quality, system reliability, and user outcomes. Compare versions on paired requests, set release gates for critical slices, and use shadow traffic, canaries, and randomized experiments to answer different release questions. ## Safety and Alignment Risks - [Safety and Alignment Risks](https://dmxsf.com/en/wiki/safety.md): LLMs make up plausible content, get hijacked by prompt injection, are talked past guardrails by jailbreaks, and repeat training-data secrets. This chapter sorts these risks into reproducible categories with threat models, measurements and defenses; most defenses are system design. - [Prompt Injection and Jailbreaks: The Security Boundaries of LLM Applications](https://dmxsf.com/en/wiki/safety/prompt-injection-and-jailbreaks.md): Prompt injection makes a model treat untrusted content as instructions; a jailbreak makes it ignore its safety training. Attackers, targets and defenses differ. This page gives the threat models, six architectural defenses and a runnable worst-case simulation of what each defense stops. - [Hallucination and Calibration: Why Models Sound Sure and Are Wrong](https://dmxsf.com/en/wiki/safety/hallucination-and-calibration.md): Hallucination is fluent output that contradicts the facts or the sources a model was given. This page covers two taxonomies, the floor set by facts seen only once, why binary grading rewards guessing, and three runnable simulations of calibration, temperature scaling and abstaining. - [Memorization and Privacy: What Models Remember, How to Measure and Reduce It](https://dmxsf.com/en/wiki/safety/memorization-and-privacy.md): Language models can memorize rare training snippets verbatim, and attackers can prompt them back out. A small experiment with known secrets measures how copies, attacker context and training strength change memorization, and compares deduplication with goldfish loss. ## Frontier - [Frontier](https://dmxsf.com/en/wiki/frontier.md): The fastest-moving directions in LLMs and the lasting questions behind each. For now: test-time compute (how inference compute buys accuracy), synthetic data (when model-made data helps or collapses) and mechanistic interpretability (finding features and circuits inside the network). - [Test-Time Compute: Spending Compute on Inference](https://dmxsf.com/en/wiki/frontier/test-time-compute.md): Test-time compute is extra computation spent while answering each question: voting over samples, verifier selection, revision, search and RL-trained long chains of thought. A reproducible simulation shows what caps the gain, what a fooled verifier does and why wall-clock time differs. - [Synthetic Data and Self-Improvement: When Models Make Data, and When It Collapses](https://dmxsf.com/en/wiki/frontier/synthetic-data-and-self-improvement.md): Synthetic data is generated by a model or a program and then used for training. It keeps helping only with an outside signal: a verifier, a stronger teacher or fresh real data. Two experiments show recursive training losing the tail and only a verifier letting self-training bootstrap. - [Mechanistic Interpretability: Superposition, Sparse Autoencoders and Circuits](https://dmxsf.com/en/wiki/frontier/interpretability.md): Mechanistic interpretability reverse-engineers a trained network into a readable algorithm. Three CPU experiments cover superposition and sparse autoencoders for finding features, the logit lens and activation patching for locating causes, and why the choice of ablation changes the answer. ## Blog - [DeepSeek-V4.1-Flash: Getting the Global KV Cache Down to 890 Bytes per Token](https://dmxsf.com/en/blog/deepseek-v41-flash-pushing-the-limits-of-kv-cache-compression.md): DeepSeek-V4.1-Flash cuts the global KV cache to 890 bytes per token, about 1/4 of V4-Flash and 1/437 of DeepSeek-V1, with a causal encoder-decoder, cross-layer sharing in CSA2 and an FP4 main KV. This post explains the paper and rebuilds its numbers from the public configs. - [MiniMax Sparse Attention: per-GQA-group block selection that cuts attention compute 28.4× at 1M context](https://dmxsf.com/en/blog/minimax-sparse-attention.md): MSA (MiniMax, 2026) adds an index branch to GQA that picks top-k KV blocks per group and attends exactly over only those. On a 109B MoE it matches full attention while cutting per-token attention compute 28.4× at 1M context. We verify the FLOPs figure and the coverage limits of block selection. - [Attention Residuals: Letting Each Layer Pick What to Read From the Layers Before It](https://dmxsf.com/en/blog/attention-residuals.md): Attention Residuals (AttnRes) is Kimi's March 2026 fix for residual connections: it swaps the fixed weight-1 sum over earlier layers for softmax attention over their outputs. This post reviews the paper, recomputes its numbers and tests the idea on a small model. - [GDPO: Why Multi-Reward RL Should Normalize Each Reward on Its Own](https://dmxsf.com/en/blog/gdpo-group-reward-decoupled-normalization-policy-optimization.md): GDPO is NVIDIA's January 2026 fix for multi-reward RL. GRPO sums the rewards before normalizing, which can collapse different reward combinations into one advantage; GDPO normalizes each reward first. This post re-enumerates the paper's counts and flags claims that do not check out. - [mHC: Keeping a Wider Residual Stream Stable With Doubly Stochastic Mixing](https://dmxsf.com/en/blog/mhc-manifold-constrained-hyper-connections.md): mHC (Manifold-Constrained Hyper-Connections) is DeepSeek's fix for hyper-connections: Sinkhorn-Knopp turns the residual mixing matrix into a doubly stochastic one, keeping multi-layer gain bounded, for a reported 6.7% extra training time. This post reviews it and checks the math in code. - [DeepSeek-V3.2: Sparse Attention, Scaled-Up Reinforcement Learning and Synthetic Agent Tasks](https://dmxsf.com/en/blog/deepseek-v32-pushing-the-frontier-of-open-large-language-models.md): DeepSeek-V3.2 adds DeepSeek Sparse Attention to V3.1-Terminus by continued training: a lightning indexer picks 2048 tokens per query, so core attention drops from O(L²) to O(Lk). Then scaled-up GRPO and 1,800+ synthetic environments. I recompute the numbers and rebuild DSA in miniature. - [GSPO: Moving Importance Ratios and Clipping From Tokens to Whole Responses](https://dmxsf.com/en/blog/gspo-group-sequence-policy-optimization.md): GSPO (Group Sequence Policy Optimization), from the Qwen team in 2025, replaces GRPO's per-token importance ratios and clipping with one length-normalized ratio per response, and reportedly needs no Routing Replay for MoE models. This post reviews it and verifies its gradients in code. - [SmolVLA: A small open vision-language-action model for affordable robotics](https://dmxsf.com/en/blog/smolvla.md): SmolVLA is an approximately 450M-parameter open VLA trained on community robotics data. It targets affordable hardware through action chunking, a compact backbone and asynchronous inference. - [Qwen3 Technical Report: One Model, Two Modes, a Thinking Budget and Strong-to-Weak Distillation](https://dmxsf.com/en/blog/qwen3-technical-report.md): Qwen3 (2025) is a family of eight Apache-2.0 open models, six dense and two MoE. One checkpoint has thinking and non-thinking modes, thinking can be capped by a budget, and small models are distilled from large ones. This post recomputes all parameter counts and runs a budget experiment. - [Does RL expand reasoning capacity? Evidence from pass@k](https://dmxsf.com/en/blog/does-reinforcement-learning-really-incentivize-reasoning-capacity.md): Using large-k pass@k, this study finds RL improves small-k success while base models often match or exceed coverage at large k, suggesting RL redistributes existing ability more than creating new reasoning. - [DAPO: An Open-Source Reasoning RL System and the Four Tricks That Keep GRPO Stable on Long Chains of Thought](https://dmxsf.com/en/blog/dapo-open-source-llm-reinforcement-learning-system-at-scale.md): DAPO, open-sourced by ByteDance Seed and partners, adds Clip-Higher, dynamic sampling, token-level loss and overlong reward shaping to GRPO and reaches 50 on AIME 2024 (avg@32) from a Qwen2.5-32B base, against 30 for naive GRPO. Code checks the mechanisms and numbers behind each trick. - [GR00T N1: A Data Pyramid and a Dual-System Model for Generalist Humanoid Robots](https://dmxsf.com/en/blog/gr00t-n1-an-open-foundation-model-for-generalist-humanoid-robots.md): GR00T N1 (NVIDIA, 2025) pairs an Eagle-2 vision-language model with a flow-matching DiT action head and pretrains on a data pyramid of real robots, simulation, neural videos and human video. This post recomputes its parameters, the Eq. (1) sign, the data tallies and the results. - [Qwen2.5-VL: Dynamic resolution, temporal grounding and visual agents](https://dmxsf.com/en/blog/qwen25-vl-technical-report.md): Qwen2.5-VL spans 3B, 7B and 72B, combining dynamic-resolution vision, video temporal grounding and document parsing with GUI and tool-use capabilities. - [Native Sparse Attention: Trainable compression, selection and sliding windows](https://dmxsf.com/en/blog/native-sparse-attention.md): NSA combines compressed global tokens, selected important blocks and local sliding windows. Its trainable, hardware-aligned design targets long-context speed without losing global information. - [s1: Curated data and budget forcing for test-time scaling](https://dmxsf.com/en/blog/s1-simple-test-time-scaling.md): s1 selects 1K high-quality, difficult and diverse trajectories from 59K candidates, fine-tunes Qwen2.5-32B and controls reasoning length through budget forcing with Wait. - [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://dmxsf.com/en/blog/deepseek-r1-reasoning-via-reinforcement-learning.md): DeepSeek-R1 shows that large-scale reinforcement learning with automatically checkable rewards lets a base model grow long chains of thought; a cold start and four stages make it usable. We recompute the paper's data and cost tables, list what does not add up, and cover later corrections. - [MiniMax-01: Lightning Attention and million-token context](https://dmxsf.com/en/blog/minimax-01-scaling-foundation-models-with-lightning-attention.md): MiniMax-01 combines seven Lightning Attention layers with one softmax layer per eight, using a 456B-parameter MoE with 45.9B active parameters and reporting inference contexts up to four million tokens. - [rStar-Math: Self-evolved MCTS for mathematical reasoning](https://dmxsf.com/en/blog/rstar-math.md): rStar-Math co-evolves a 7B policy and process reward model over four rounds. MCTS generates stepwise trajectories and step preferences train the verifier, reaching 58.8% on MATH without GPT-4 distillation. - [Cosmos: A world foundation model platform for physical AI](https://dmxsf.com/en/blog/cosmos-world-foundation-model-platform.md): Cosmos combines video tokenizers, diffusion and autoregressive world models, and data pipelines for robotics and autonomous driving prediction, synthetic data and policy evaluation. - [DeepSeek-V3 Technical Report: MoE, MLA, FP8 and Low-Cost Training](https://dmxsf.com/en/blog/deepseek-v3-technical-report.md): DeepSeek-V3 is a 671B-parameter MoE model that activates 37B per token. It adds auxiliary-loss-free balancing and multi-token prediction to MLA and DeepSeekMoE, and trains with FP8 and DualPipe on 2048 H800 GPUs in 2.788M GPU hours. This post covers methods, numbers and limits. - [Qwen2.5: 18T tokens, a broad model family and a practical post-training recipe](https://dmxsf.com/en/blog/qwen25-technical-report.md): Qwen2.5 scales pretraining to 18T tokens across dense models from 0.5B to 72B plus MoE variants. The report covers data filtering, long context, large-scale SFT, offline DPO and online GRPO. - [π0: A Flow-Matching Action Expert on PaliGemma for Controlling Many Robots with Action Chunks](https://dmxsf.com/en/blog/pi0-a-vision-language-action-flow-model-for-general-robot-control.md): π0 (Physical Intelligence, 2024) adds a roughly 300M flow-matching action expert to the 3B PaliGemma and generates 50-step continuous action chunks at up to 50 Hz. The experts share self-attention, so prefix keys and values are computed once. This page recomputes sizes and tests the cache. - [Differential Transformer: Subtract two attention maps to suppress noise](https://dmxsf.com/en/blog/differential-transformer.md): Differential Transformer computes two softmax attention maps and subtracts them to cancel shared noise. The paper reports improvements in language modeling, long-context retrieval and hallucination metrics. - [Scaling LLM Test-Time Compute Optimally: Spending Inference Compute by Difficulty Can Beat a Bigger Model](https://dmxsf.com/en/blog/scaling-llm-test-time-compute-optimally-can-be-more-effective-than-scaling-model-parameters.md): Snell et al. (2024) study how to spend inference compute on MATH: the best method depends on question difficulty, and allocating by difficulty needs up to about 4 times less compute than best-of-N. I recompute the paper's FLOPs exchange rate and replicate a small part with Qwen2.5. - [The Llama 3 Herd of Models: data, scale and the engineering recipe of a 405B dense model](https://dmxsf.com/en/blog/the-llama-3-herd-of-models.md): Meta's Llama 3 paper (2024) gives the full recipe for three dense Transformers (8B, 70B, 405B): 15T tokens of pre-training, 128K context, 4D parallelism on 16K H100s, and six rounds of SFT, rejection sampling and DPO. This post recomputes its tables and flags numbers that do not add up. - [FlashAttention-3: Asynchrony and low precision on Hopper](https://dmxsf.com/en/blog/flashattention-3-fast-and-accurate-attention-with-asynchrony-and-low-precision.md): FlashAttention-3 uses warp specialization to overlap GEMMs with softmax on Hopper and adds block-quantized FP8 for higher throughput, while retaining an exact FP16 path. - [FineWeb: Extracting, Deduplicating and Filtering a 15T-Token Open Web Corpus, One Ablation at a Time](https://dmxsf.com/en/blog/the-fineweb-datasets-decanting-the-web-for-the-finest-text-data-at-scale.md): The FineWeb paper (Hugging Face, 2024) documents a 15T-token English web corpus: Trafilatura extraction, per-snapshot MinHash dedup, tuned filters, and FineWeb-Edu (1.3T) from a classifier trained on Llama-3-70B labels. We check the dedup math and flag where paper, table and code disagree. - [OpenVLA: An Open-Source Vision-Language-Action Model on Llama 2 7B and Two Vision Encoders](https://dmxsf.com/en/blog/openvla-an-open-source-vision-language-action-model.md): OpenVLA (Kim et al., 2024) fine-tunes Llama 2 7B with fused DINOv2 and SigLIP vision encoders on 970k real robot trajectories, and beats the 55B RT-2-X by 16.5 points across 29 tasks. This page rebuilds its parameter counts and success tables and tests which gaps exceed the noise. - [Chameleon: Early-fusion token modeling for images and text](https://dmxsf.com/en/blog/chameleon-mixed-modal-early-fusion-foundation-models.md): Chameleon trains one Transformer from scratch over discrete image and text tokens. Its 7B and 34B models handle interleaved multimodal input and output instead of attaching vision to a frozen LLM. - [DeepSeek-V2: Compressing the KV Cache with MLA and Cutting Training Cost with DeepSeekMoE](https://dmxsf.com/en/blog/deepseek-v2-strong-economical-efficient-mixture-of-experts.md): DeepSeek-V2 (DeepSeek-AI, 2024) is a 236B-parameter MoE model that activates 21B per token: Multi-head Latent Attention (MLA) shrinks the inference cache and DeepSeekMoE lowers training cost. This post rechecks 93.3%, 236B and 21B, and verifies MLA's absorption and decoupled RoPE numerically. - [Phi-3: Small models and the textbook-quality data strategy](https://dmxsf.com/en/blog/phi-3-technical-report.md): Phi-3-mini trains 3.8B parameters on 3.3T tokens using heavily filtered and synthetic textbook-quality data. It demonstrates local deployment potential while acknowledging capacity limits in factual knowledge. - [Gemma: Gemini-derived techniques in 2B and 7B open models](https://dmxsf.com/en/blog/gemma-open-models-based-on-gemini-research-and-technology.md): The first Gemma release provides 2B and 7B base and instruction-tuned weights using Gemini-derived techniques, alongside responsible-AI tooling and local deployment support. - [BitNet b1.58: Ternary weights turn matrix multiplication into addition and subtraction](https://dmxsf.com/en/blog/bitnet-b158.md): BitNet b1.58 trains Transformer weights in {-1,0,1}, about 1.58 bits each, with 8-bit activations. It approaches LLaMA-quality results at 3B scale while targeting weight bandwidth and multiplication cost. - [Genie: Learning interactive 2D worlds from unlabeled video](https://dmxsf.com/en/blog/genie-generative-interactive-environments.md): Genie learns latent actions and a video world model from unlabeled platformer videos, turning images into controllable 2D environments without ground-truth action labels. - [DeepSeekMath: Math Corpus, GRPO and a Unified View of Reinforcement Learning](https://dmxsf.com/en/blog/deepseekmath-pushing-the-limits-of-mathematical-reasoning.md): DeepSeekMath 7B continues pretraining on 120B tokens of web math, then uses GRPO, reinforcement learning without a value model, to reach 51.7% on MATH with no tools or voting. This post covers the corpus pipeline, ablations, GRPO's math and a unified view of SFT, RFT, DPO, PPO and GRPO. - [Mixtral of Experts: An Open MoE That Matches Llama 2 70B with 13B Active Parameters](https://dmxsf.com/en/blog/mixtral-of-experts.md): Mixtral 8x7B keeps Mistral 7B's architecture but replaces every feed-forward layer with 8 experts and routes each token to 2: about 47B parameters in total, about 13B used per token. This post covers the architecture, the benchmark evidence, the routing analysis and which claims deserve a discount. - [RAG survey: three paradigms, four abilities, and a recount of the paper's tables](https://dmxsf.com/en/blog/rag-survey.md): Gao et al.'s survey sorts retrieval-augmented generation into Naive, Advanced and Modular RAG. This page recounts its Tables I and II, flags two entries that disagree with the original papers, and reruns RGB's four abilities on 50 fictional companies. - [Mamba: linear-time sequence modeling with selective state spaces](https://dmxsf.com/en/blog/mamba-linear-time-sequence-modeling-with-selective-state-spaces.md): Mamba makes a state space model's Δ, B and C depend on the current token (selection) and runs it with a hardware-aware scan: linear cost in length, fixed-size state at inference. We recompute its parameters and Table 3, then compare LTI and selective SSMs on selective copying. - [GAIA: A benchmark for tool-using general AI assistants](https://dmxsf.com/en/blog/gaia-a-benchmark-for-general-ai-assistants.md): GAIA contains 466 questions with verifiable answers that require reasoning, web browsing, multimodal understanding and tools. It measures complete task execution rather than isolated knowledge recall. - [Mistral 7B: Sliding-window attention, GQA and a rolling KV cache](https://dmxsf.com/en/blog/mistral-7b.md): Mistral 7B combines grouped-query and sliding-window attention with a rolling KV cache. It delivers strong 7B results while bounding direct cache cost and propagating information across layers. - [StreamingLLM: Keep the First Few Tokens in the KV Cache and Sliding Windows Stop Breaking](https://dmxsf.com/en/blog/efficient-streaming-language-models-with-attention-sinks.md): StreamingLLM (ICLR 2024) finds that language models dump much of their attention on the first few tokens, the attention sinks; evict them from a sliding-window KV cache and perplexity explodes. Keeping 4 initial tokens fixes it with no fine-tuning, but it does not extend the context. - [vLLM and PagedAttention: Managing the KV Cache Like Paged Memory](https://dmxsf.com/en/blog/vllm-pagedattention.md): The vLLM paper (SOSP 2023) brings operating-system paging to the KV cache: fixed-size blocks, on-demand allocation, a block table, copy-on-write sharing. This post checks the paper's numbers and shows the real range behind the headline 2-4x, what it was compared with, and where it stops applying. - [YaRN: Extending RoPE Models to a 128K Context Window with Light Fine-Tuning](https://dmxsf.com/en/blog/yarn-efficient-context-window-extension-of-large-language-models.md): YaRN extends a RoPE model's context window by interpolating each rotary dimension according to how many turns it makes within the training length and adding a softmax temperature tied to ln s. 400 to 600 fine-tuning steps take Llama 2 to 128K. This post covers PI, NTK-aware and the evidence. - [RT-2: Transferring Web Knowledge to Robot Control with a Vision-Language-Action Model](https://dmxsf.com/en/blog/rt-2-vision-language-action-models-transfer-web-knowledge-to-robotic-control.md): RT-2 (Brohan et al., 2023) writes robot actions as integer tokens from 0 to 255 and co-fine-tunes PaLI-X and PaLM-E on them together with web image-text data. It matches RT-1 on seen tasks and roughly doubles it on unseen ones. This page checks the action vocabulary and Tables 4 to 6. - [Llama 2: An open base model and a detailed recipe for dialogue and safety](https://dmxsf.com/en/blog/llama-2-open-foundation-and-fine-tuned-chat-models.md): Llama 2 introduced 7B, 13B and 70B base and chat models trained on 2T tokens. Its lasting value is the unusually detailed account of SFT, reward models, rejection sampling, PPO and safety evaluation. - [FlashAttention-2: Better parallelism and work partitioning](https://dmxsf.com/en/blog/flashattention-2-faster-attention-with-better-parallelism-and-work-partitioning.md): FlashAttention-2 preserves exact attention while reducing non-matrix operations, increasing sequence parallelism and improving warp-level work partitioning for higher GPU utilization. - [RetNet: Parallel training and recurrent inference through retention](https://dmxsf.com/en/blog/retentive-network-a-successor-to-transformer-for-large-language-models.md): RetNet replaces softmax attention with multi-scale retention, supporting parallel training, recurrent decoding and chunkwise processing with fixed-size inference state. - [Lost in the Middle: Models Use the Start and End of a Long Context Best](https://dmxsf.com/en/blog/lost-in-the-middle.md): Liu et al. (2023) moved the answer around inside long inputs and found a U-shaped curve: accuracy is highest at the start or end and lowest in the middle. With 20 documents GPT-3.5-Turbo loses 22.0 points between its best and worst position. This post recomputes the results and discusses RAG. - [Let's Verify Step by Step: Scoring Every Reasoning Step Beats Checking Only the Final Answer](https://dmxsf.com/en/blog/lets-verify-step-by-step.md): OpenAI compares outcome and process supervision on MATH. A reward model trained on 800K human step labels (PRM800K) solves 78.2% of problems at best-of-1860, against 72.4% for an outcome reward model and 69.6% for majority voting. A small simulation shows why step labels save data. - [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://dmxsf.com/en/blog/dpo-direct-preference-optimization.md): DPO replaces 'reward model plus PPO' with one classification-style loss: given only preference pairs and a frozen reference model, it optimizes the same KL-constrained objective as RLHF. This post checks the derivation, runs a toy world for the frontier and training dynamics, and covers limits. - [GQA: Turning Multi-Head Checkpoints into Grouped-Query Attention for 5% of Pretraining Compute](https://dmxsf.com/en/blog/gqa-grouped-query-attention.md): GQA lets groups of query heads share one key/value head, between multi-head (MHA) and multi-query attention (MQA); MHA checkpoints convert by mean-pooling heads plus about 5% extra pretraining. On T5-XXL it nears MHA quality at close to MQA speed. We check Table 1 and compute Llama 3's KV cache. - [QLoRA: Fine-Tuning a 65B Model on One 48 GB GPU by Quantizing the Base to 4 Bits](https://dmxsf.com/en/blog/qlora-efficient-finetuning-of-quantized-llms.md): QLoRA (Dettmers et al., 2023) quantizes a frozen base model to 4-bit NormalFloat and trains LoRA adapters on top, so a 65B model fine-tunes on one 48 GB GPU. This breakdown explains NF4, double quantization and paged optimizers, rebuilds NF4 in code and tests 4-bit data types on Qwen2.5. - [LLaVA: Text-Only GPT-4 Writes 158K Visual Instructions and a Language Model Learns to See](https://dmxsf.com/en/blog/llava-visual-instruction-tuning.md): LLaVA connects a frozen CLIP ViT-L/14, one linear projection and Vicuna: stage 1 trains only the projection, stage 2 tunes it with the language model on 158K visual instructions written by text-only GPT-4. This post covers the method, rechecks the tables and re-runs stage 1 at small scale. - [GPT-4: Predictable scaling, multimodal input and capability limits](https://dmxsf.com/en/blog/gpt-4-technical-report.md): The GPT-4 report emphasizes predictable loss scaling, image input and safety evaluation while withholding architecture, data and compute details. It also explains why specific capabilities may remain unpredictable. - [Diffusion Policy: Generating Robot Action Sequences by Conditional Denoising](https://dmxsf.com/en/blog/diffusion-policy-visuomotor-policy-learning-via-action-diffusion.md): Diffusion Policy (Chi et al., 2023) writes a robot's visuomotor policy as an observation-conditioned diffusion model: it denoises a sequence of future actions from noise, executes the first few, then replans. This post rechecks the 46.9% headline and tests multimodality and horizons on a toy task. - [LLaMA: Train Smaller Models for Longer, on Public Data Only](https://dmxsf.com/en/blog/llama-open-and-efficient-foundation-language-models.md): LLaMA is a family of 7B to 65B foundation models from Meta (2023), trained on public data only. The paper reports LLaMA-13B beating GPT-3 175B on most benchmarks. This post covers the inference-budget argument, data, architecture, training cost and evidence, and which claims need a discount. - [Toolformer: Scoring Tool Calls by How Much They Cut the Loss, So a Language Model Learns When to Ask for Help](https://dmxsf.com/en/blog/toolformer-self-supervised-tool-use-for-language-models.md): Toolformer lets a language model decide when to call a calculator, QA system, search engine, translator or calendar: a call is kept only if its result clearly lowers the loss on the next tokens. This post covers the method, rechecks the tables and measures the filter on two Qwen2.5 models. - [DreamerV3: One Set of Hyperparameters for 150+ Tasks with a World-Model Agent](https://dmxsf.com/en/blog/dreamerv3-mastering-diverse-domains-through-world-models.md): DreamerV3 (Hafner et al., 2023) learns a world model and trains an actor and critic on imagined latent trajectories. With symlog, twohot regression, free bits and percentile return normalization, one hyperparameter set beats or matches specialists on 150+ tasks and finds a Minecraft diamond. - [Constitutional AI: a written list of principles lets the model critique, rewrite and grade its own answers](https://dmxsf.com/en/blog/constitutional-ai-harmlessness-from-ai-feedback.md): Constitutional AI swaps human harmlessness labels for a written list of principles: a model critiques and revises its own answers, then ranks answer pairs under those principles (RLAIF). It explains the method, rechecks the paper's numbers and re-runs the labeling step at small scale. - [Fast Inference from Transformers via Speculative Decoding](https://dmxsf.com/en/blog/speculative-decoding-fast-inference-from-transformers.md): In speculative decoding a small draft model guesses several tokens, the large model verifies them in one parallel pass, and a sampling rule keeps the output distribution unchanged. This post reads the paper's formulas, recomputes its Tables 1 and 4, and explains the 1.4x to 3.4x measured on T5-XXL. - [ReAct: Treating Thought as an Action So a Language Model Can Reason and Act in One Trace](https://dmxsf.com/en/blog/react-reasoning-and-acting.md): ReAct treats thought as an action: a model alternates thoughts, tool calls and observations in one trace, from a few examples and without parameter updates. This post covers the paper's four tasks, rechecks its tables, and compares four prompts with Qwen3-4B on a fictional wiki. - [Flow Matching: Regress a Fixed Path's Vector Field and Train Continuous Normalizing Flows Without Simulation](https://dmxsf.com/en/blog/flow-matching-for-generative-modeling.md): Flow Matching (Lipman et al., 2022) turns generative modeling into regression: pick a probability path from noise to data, regress its vector field, and never solve an ODE in training. Gaussian paths include diffusion, and OT paths are another choice. Code compares both on a 2D checkerboard. - [FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://dmxsf.com/en/blog/flashattention-fast-and-memory-efficient-exact-attention.md): FlashAttention computes exact attention block by block in the GPU's on-chip SRAM, so the N×N score matrix never goes to GPU memory. HBM accesses fall from Θ(Nd+N²) to Θ(N²d²/M); BERT trains about 15% faster, GPT-2 3.0 to 3.5 times faster than HuggingFace. A breakdown of the paper. - [Chinchilla: Why a 70B Model on 1.4T Tokens Beats the 280B Gopher at the Same Compute](https://dmxsf.com/en/blog/chinchilla-training-compute-optimal-large-language-models.md): For a fixed training budget, how big should the model be and how many tokens should it see? DeepMind's 400-model study says parameters and data should grow together (about 20 tokens per parameter); the 70B Chinchilla then beat the 280B Gopher at equal compute. Numbers re-checked here. - [InstructGPT: Training Language Models to Follow Instructions with Human Feedback](https://dmxsf.com/en/blog/instructgpt-rlhf.md): OpenAI's 2022 InstructGPT paper: supervised fine-tuning on about 13,000 human demonstrations, a reward model trained on human rankings of about 33,000 prompts, then PPO. A 1.3B InstructGPT beat the 175B GPT-3 in labeler evaluations. This breakdown checks the data, loss and results, and their limits. - [Chain-of-thought prompting: exemplars with intermediate steps let large models solve multi-step problems](https://dmxsf.com/en/blog/chain-of-thought-prompting.md): Chain-of-thought (CoT) prompting writes the intermediate steps into few-shot exemplars so a model reasons before it answers; with eight exemplars PaLM 540B rises from 17.9% to 56.9% on GSM8K. It rechecks the paper's tables and compares direct answers, filler dots and CoT on Qwen2.5 models. - [LoRA: Freeze the Pretrained Weights, Train Only a Low-Rank Update](https://dmxsf.com/en/blog/lora-low-rank-adaptation.md): LoRA (Hu et al., 2021) freezes the pretrained weights and trains only a low-rank update ΔW=BA: about 10,000 times fewer trainable parameters on GPT-3 175B, a 350GB checkpoint shrinking to 35MB, no extra latency after merging, and quality on par with full fine-tuning. Method, experiments, caveats. - [Decision Transformer: Reinforcement Learning as Conditional Sequence Modeling](https://dmxsf.com/en/blog/decision-transformer-reinforcement-learning-via-sequence-modeling.md): Decision Transformer (Chen et al., 2021) recasts offline RL as conditional sequence modeling: a causal GPT trained on return, state and action tokens, prompted with a target return. We recompute its tables, rerun its shortest-path toy, and show where return conditioning fails. - [RoFormer: Writing Position into the Attention Dot Product with Rotations](https://dmxsf.com/en/blog/roformer-rotary-position-embedding.md): RoFormer's rotary position embedding (RoPE) rotates queries and keys by position, so their dot product depends only on relative position, with no extra parameters. It later became standard in open LLMs such as LLaMA. We check its formulas, its mixed small-scale results and its properties in code. - [CLIP: Contrastive Learning on 400 Million Image-Text Pairs, and a Classifier You Define in One Sentence](https://dmxsf.com/en/blog/clip-learning-transferable-visual-models.md): CLIP trains an image encoder and a text encoder with contrastive learning on 400 million image-text pairs, so a classifier can be defined by a sentence. This post walks through the method, rechecks the paper's numbers and runs zero-shot, few-shot and typographic-attack tests on CIFAR-10. - [Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity](https://dmxsf.com/en/blog/switch-transformers-scaling-to-trillion-parameter-models.md): The Switch Transformer simplifies mixture-of-experts routing to top-1, balances load with an expert capacity and an auxiliary loss, and pre-trains up to 7x faster than T5 at equal FLOPs per token. This page recomputes the paper's numbers and simulates capacity overflow. - [ViT: An Image Is Worth 16x16 Words, Fed Straight to a Transformer](https://dmxsf.com/en/blog/vit-an-image-is-worth-16x16-words.md): ViT drops convolutions: it cuts an image into fixed-size patches, projects each into a token, adds position embeddings and feeds a standard Transformer encoder. It trails ResNets on small data but, pre-trained on JFT-300M, reaches 88.55% on ImageNet with about a quarter of BiT-L's compute. - [Learning to Summarize: A Reward Model from Human Preferences, Optimized with PPO](https://dmxsf.com/en/blog/learning-to-summarize-from-human-feedback.md): OpenAI ran the full RLHF pipeline on Reddit TL;DR summaries: collect human pairwise comparisons, train a reward model, then optimize the policy with KL-penalized PPO. A 1.3B human-feedback model beat a supervised model 10 times larger. Code checks the KL optimum and over-optimization. - [DDPM: Add Noise Step by Step, Learn to Remove It Step by Step, and Train with a Simple Noise-Prediction Loss](https://dmxsf.com/en/blog/ddpm-denoising-diffusion-probabilistic-models.md): DDPM models generation as fixed forward noising plus learned reverse denoising: the network predicts each step's noise and trains with an unweighted mean squared error, reaching FID 3.17 on CIFAR-10. Code checks the forward closed form, endpoint KL and loss weights on 2D toy data. - [GPT-1, GPT-2, GPT-3: From Fine-Tuning to In-Context Learning, Recomputed from the Papers](https://dmxsf.com/en/blog/gpt-series-evolution.md): GPT-1, GPT-2 and GPT-3 are three scale-ups of one decoder-only Transformer; what changes is how a task reaches the model: fine-tuning, zero-shot text, or few-shot examples in the context. This page rechecks the papers' numbers and measures perplexity and in-context learning on GPT-2. - [SimCLR: Strong augmentation, a projection head and large batches](https://dmxsf.com/en/blog/simclr-a-simple-framework-for-contrastive-learning-of-visual-representations.md): SimCLR treats two augmentations of an image as positives and others as negatives with NT-Xent. Ablations establish augmentation composition, nonlinear projection and batch size as central design choices. - [Scaling Laws for Neural Language Models](https://dmxsf.com/en/blog/scaling-laws-for-neural-language-models.md): OpenAI's 2020 paper trained Transformers of 768 to 1.5 billion parameters on WebText2 and found that loss falls as a power law in parameters, data and compute, almost regardless of shape. At a fixed budget, grow the model first (size ∝ compute^0.73). A breakdown that checks the numbers. - [MuZero: Planning with a learned model without knowing the rules](https://dmxsf.com/en/blog/muzero-mastering-atari-go-chess-and-shogi-without-rules.md): MuZero learns latent transitions, rewards and values useful for planning instead of receiving environment rules. MCTS over this learned model matches AlphaZero in board games and advances Atari performance. - [T5: Casting Every NLP Task as Text-to-Text and Systematically Comparing Transfer Learning's Knobs](https://dmxsf.com/en/blog/t5-exploring-the-limits-of-transfer-learning.md): T5 casts translation, classification and summarization as text in, text out, trains one encoder-decoder with one loss, and compares architectures, objectives, datasets and scale. Denoising beats language modeling, corrupting spans is cheaper, and large clean C4 beats repeated small data. - [ZeRO: Partition the Model States Across GPUs So Data Parallelism Can Hold 100B+ Parameters](https://dmxsf.com/en/blog/zero-memory-optimizations-toward-training-trillion-parameter-models.md): ZeRO notes that data parallelism stores full copies of parameters, gradients and optimizer states on every GPU: 16 bytes per parameter with mixed-precision Adam. It partitions them in three stages, with unchanged communication in the first two and 50% more in the third. We recompute its Table 1. - [RoBERTa: A robustly optimized BERT recipe](https://dmxsf.com/en/blog/roberta-a-robustly-optimized-bert-pretraining-approach.md): RoBERTa keeps BERT’s architecture but uses more data, larger batches, longer training, dynamic masking, byte-level BPE and no NSP, showing the original model was undertrained. - [BERT: pre-training a bidirectional Transformer by filling in masked words, then one thin output layer per task](https://dmxsf.com/en/blog/bert-pre-training-of-deep-bidirectional-transformers.md): BERT pre-trains a deep bidirectional Transformer encoder by restoring masked words, then adds one output layer per task and fine-tunes everything, setting records on 11 NLP tasks. It rechecks the paper's tables, parameter counts and training budget, and probes bert-base-uncased three ways. - [World Models: Compress the World into a Generative Model and Let the Agent Train in Its Own Dream](https://dmxsf.com/en/blog/world-models-ha-schmidhuber.md): World Models (Ha and Schmidhuber, 2018) split an agent into a VAE for vision, an MDN-RNN for memory and a tiny linear controller trained by evolution strategies, even inside the model's own dream. Code checks the parameter counts and replays dream training on CartPole. - [AlphaZero: Only the Rules, Self-Play from Scratch, Mastering Chess, Shogi and Go](https://dmxsf.com/en/blog/alphazero-mastering-chess-and-shogi-by-self-play.md): AlphaZero used one algorithm and one set of hyperparameters, given only the rules, to learn chess, shogi and Go from random play via self-play with a neural network and Monte Carlo tree search (MCTS), and beat each world-champion program. This post checks shapes, match statistics and search volume. - [AdamW: Decoupling Weight Decay from Adam's Adaptive Update](https://dmxsf.com/en/blog/decoupled-weight-decay-regularization-adamw.md): L2 regularization and weight decay are equivalent in SGD but not in Adam: the L2 gradient is rescaled by the second-moment estimate, so weights with large gradients are decayed less. AdamW applies the decay directly to the weights. We verify the propositions in code and check PyTorch's convention. - [PPO: Clipping the Policy Update So One Batch of Data Can Be Reused for Many Epochs](https://dmxsf.com/en/blog/ppo-proximal-policy-optimization-algorithms.md): PPO makes policy gradients reusable: a clipped probability-ratio objective allows several minibatch epochs on one batch of data, with TRPO-like stability from first-order optimization only. A CartPole experiment compares no clipping with epsilon 0.1, 0.2 and 0.3, 8 seeds each. - [Attention Is All You Need: the Transformer, with self-attention instead of recurrence and convolution](https://dmxsf.com/en/blog/attention-is-all-you-need.md): The original Transformer paper: an encoder-decoder built only from multi-head self-attention and feed-forward layers, 28.4 BLEU on WMT 2014 English-German. We recompute its parameter counts, costs and BLEU claims, then train a tiny Transformer to copy digits. - [ResNet: Residual connections make very deep networks trainable](https://dmxsf.com/en/blog/deep-residual-learning-for-image-recognition.md): ResNet recasts layers as residual functions with identity shortcuts, addressing deep-network degradation. Its 152-layer model reports 3.57% ImageNet top-5 error and residual learning became a default building block. - [U-Net: Contracting and expanding paths with skip connections](https://dmxsf.com/en/blog/u-net-convolutional-networks-for-biomedical-image-segmentation.md): U-Net combines a context-encoding contracting path, a resolution-restoring expanding path and skip connections. Elastic augmentation enables strong biomedical segmentation with few annotated images. - [Seq2Seq: Encoder-decoder learning for variable-length sequences](https://dmxsf.com/en/blog/sequence-to-sequence-learning-with-neural-networks.md): Seq2Seq uses one deep LSTM to encode a variable-length input and another to generate output. Reversing source sentences improves optimization, reaching 34.8 BLEU on WMT14 English-French. - [GAN: Learning a data distribution through a minimax game](https://dmxsf.com/en/blog/generative-adversarial-nets.md): GANs train a noise-to-sample generator against a real/fake discriminator. The paper derives the optimal discriminator and a JS-divergence equilibrium, while practice uses a non-saturating generator loss. - [VAE: Reparameterized variational inference for generative modeling](https://dmxsf.com/en/blog/auto-encoding-variational-bayes.md): VAEs jointly train an approximate posterior encoder and generative decoder with the ELBO. Reparameterization z=mu+sigma*epsilon makes sampling differentiable and underpins continuous-latent generative modeling. - [DQN: Learning to Play Atari from Pixels with a Convolutional Q-Network and Experience Replay](https://dmxsf.com/en/blog/dqn-playing-atari-with-deep-reinforcement-learning.md): DQN pairs Q-learning with a convolutional network and experience replay, learning from raw pixels with one architecture and hyperparameter set on seven Atari games. It beat all prior methods on six and a human expert on three. Code checks parameters, normalized scores and a CartPole replay ablation. ## Optional - [llms-full.txt](https://dmxsf.com/en/llms-full.txt) - [sitemap.xml](https://dmxsf.com/sitemap.xml) - [llms.txt (中文)](https://dmxsf.com/llms.txt) - [llms.txt (Español)](https://dmxsf.com/es/llms.txt) - [llms.txt (Français)](https://dmxsf.com/fr/llms.txt) - [llms.txt (日本語)](https://dmxsf.com/ja/llms.txt) - [llms.txt (हिन्दी)](https://dmxsf.com/hi/llms.txt)