Categoría: Uncategorized

  • Continual Learning and Catastrophic Forgetting: Teaching a Network Something New Without Erasing What It Knew

    A Network That Overwrites Itself

    In 1989 Michael McCloskey and Neal Cohen trained a small neural network on simple arithmetic. First it learned the «ones» facts (1+1, 1+2 and so on up to 1+9). Then it learned the «twos» facts. After the second stage the network could no longer answer the ones problems, and the damage appeared after very little training on the new set. Its answers to old questions often looked more like a wrong number than the right one.

    They called the effect catastrophic interference, and the name stuck in its later form, catastrophic forgetting. They tried the usual adjustments (more hidden units, a different learning rate, changes to the training regime) and none of them removed it. Roger Ratcliff published a similar set of results in Psychological Review in 1990, and the problem became a standard objection to connectionist models.

    The cause is the same thing that makes neural networks useful. Knowledge is spread across shared weights. Every weight takes part in many inputs, so when gradient descent changes weights to fit new examples, it also changes the network’s response to old ones. Nothing in the loss function says the old answers should be kept, because the old data is no longer in the loss.

    Stability and Plasticity

    The tension has a name borrowed from Stephen Grossberg’s work on neural models in the 1980s: the stability-plasticity dilemma. A learner needs plasticity to absorb new information and stability to keep what it already has. A network with frozen weights forgets nothing and learns nothing. A network trained freely on each new batch learns everything and keeps only the most recent part.

    Ordinary deep learning sidesteps the dilemma. The full dataset is available, and training shuffles it so that every batch mixes examples from every class. The weights never drift far toward one subset because the next batch pulls them back. Continual learning is the setting where that shuffle is impossible: data arrives as a sequence of tasks or a stream that changes over time, and old data is gone or only partly stored.

    Neuroscience offered an early answer. James McClelland, Bruce McNaughton and Randall O’Reilly argued in 1995 that the brain uses two complementary systems. The hippocampus learns new episodes quickly and keeps them separate. The neocortex learns slowly, and new memories reach it through replay, interleaved with older ones, so the slow system never sees one topic in isolation. Much of the later machine learning work is an engineering version of that idea.

    Three Scenarios

    For years papers reported results that could not be compared, because «continual learning» meant different things in each one. Gido van de Ven and Andreas Tolias proposed a taxonomy in 2019, later published with Tinne Tuytelaars in Nature Machine Intelligence in 2022. It separates three scenarios.

    In task-incremental learning the model is told which task each test input belongs to. It can keep a separate output head per task, which makes the problem much easier. In domain-incremental learning the task stays the same but the input distribution shifts (the same digits, written in a new style, or the same road seen in winter instead of summer). In class-incremental learning new classes keep arriving, and at test time the model must choose among all classes it has ever seen, without being told which stage they came from.

    The distinction matters because methods that look strong in the first scenario can fail completely in the third. In their experiments on split MNIST, regularization methods did well when task identity was given and collapsed in the class-incremental version, while only methods that used replay kept accuracy above 90 percent there.

    Anchoring Important Weights

    One family of methods tries to protect old knowledge inside the loss function. The best known is Elastic Weight Consolidation (EWC), from James Kirkpatrick and colleagues at DeepMind, published in PNAS in 2017. After training on task A, EWC estimates how important each weight was for that task, using the diagonal of the Fisher information matrix. While training on task B it adds a quadratic penalty that pulls each weight back toward its old value, with a strength proportional to its importance.

    The authors described it as a spring attached to each parameter. Weights that mattered for task A behave as if held by stiff springs. Weights that barely affected it are free to move. They tested it on sequences of handwritten digit tasks and on Atari 2600 games learned one after another, where an agent without the penalty lost its earlier games almost entirely.

    Friedemann Zenke, Ben Poole and Surya Ganguli proposed Synaptic Intelligence at ICML 2017, which reaches a similar penalty by a different route. Each weight accumulates, during training, a measure of how much its movement reduced the loss. The appeal of both methods is that they store no old data. The weakness is that importance is estimated locally, around one solution, and the penalties pile up as tasks accumulate until the network has little room left to move.

    Distillation as Memory

    Zhizhong Li and Derek Hoiem took another route in «Learning without Forgetting» (ECCV 2016). Before training on a new task, they ran the new task’s images through the old network and recorded its outputs for the old tasks. During training, a knowledge distillation loss forces the updated network to keep producing those same outputs on those same images, while it learns the new labels.

    The old network becomes a teacher for its own successor. No old images are needed, only the old model’s responses to new images. On their experiments, starting from an ImageNet network and adding tasks such as PASCAL VOC, it beat plain fine-tuning and came close to joint training on both datasets. The limit is obvious once stated: if the new images look nothing like the old ones, the old network’s outputs on them say little about what it knew.

    Replay

    The most reliable family does what the brain model suggested. It keeps some old data, or something like it, and mixes it into training. iCaRL, by Sylvestre-Alvise Rebuffi, Alexander Kolesnikov, Georg Sperl and Christoph Lampert (CVPR 2017), stores a fixed budget of exemplars, 2,000 images in their CIFAR-100 experiments. The budget is split among all classes seen so far, so each class keeps fewer examples as new ones arrive. Exemplars are chosen by herding, a greedy procedure that picks images whose mean feature is close to the mean of the full class. Classification uses the nearest class mean of the exemplars, which holds up better than a softmax layer biased toward recent classes.

    When storing data is not allowed (medical records, user photos), the stored data can be replaced by a generator. Hanul Shin and colleagues proposed deep generative replay at NeurIPS 2017: a generative model learns to produce samples resembling past tasks, and those samples are interleaved with real data from the current task. David Lopez-Paz and Marc’Aurelio Ranzato’s Gradient Episodic Memory, from the same year, uses its memory differently. It allows a gradient step only if it does not increase the loss on stored examples, projecting the gradient when it would.

    Separate Parameters for Each Task

    A blunter approach gives each task its own part of the network. Progressive Neural Networks (Andrei Rusu and colleagues at DeepMind, 2016) freeze the network after each task and add a new column of layers for the next one, with lateral connections to the old columns so features can be reused. Forgetting is zero by construction. The cost is that the model grows with every task.

    PackNet, from Arun Mallya and Svetlana Lazebnik (CVPR 2018), keeps the size fixed. After training a task it prunes the less important weights, freezes the rest, and frees the pruned ones for the next task. Several tasks fit in one network, each using a binary mask. Both methods need to know at test time which task is being solved, which places them in the easiest of the three scenarios.

    Case: A Buffer and a Fresh Start

    In 2020 Ameya Prabhu, Philip Torr and Puneet Dokania published GDumb at ECCV, a method built as a challenge to the field. It has two parts. A sampler stores incoming examples in a fixed memory, keeping classes balanced. A learner, at test time, trains a network from scratch on whatever is in memory. There is no regularization, no distillation and no special continual learning machinery.

    GDumb matched or beat a long list of published methods, often by large margins, including in the settings those methods had been designed for. The authors’ conclusion was that many benchmarks had simplified the problem so far that it had little practical meaning. A good continual learner should at least beat retraining on a small buffer, and many did not.

    Losing the Ability to Learn

    Forgetting is the famous failure. A second one was documented later. Shibhansh Dohare, Richard Sutton, Rupam Mahmood and colleagues reported in Nature in 2024 that standard deep networks trained on long sequences of tasks gradually lose plasticity. Over hundreds or thousands of tasks, built from ImageNet and from reinforcement learning problems, their performance on new tasks fell until it was no better than a shallow network.

    Part of the cause was units that stopped responding at all, and weights that grew large. Their fix, continual backpropagation, reinitializes a small fraction of the least-used units at random as training goes on. In their framing, gradient descent alone is not enough to sustain learning indefinitely. It needs a small amount of injected randomness, which is closer to how evolutionary search maintains diversity than to how most networks are trained.

    Reflection

    The odd thing about catastrophic forgetting is that it is only catastrophic because of how we train. A network that forgets its old task after learning a new one is doing exactly what its loss function asks. The fixes that work best do not add a clever new rule to gradient descent so much as restore a little of the condition gradient descent always relied on: old and new examples seen together. Continual learning may turn out to be less about memory and more about deciding what small piece of the past is worth carrying forward.

    By: Max Johnson B.

  • Few-Shot and Meta-Learning: Training Models That Learn New Classes From a Handful of Examples

    Five Examples Are Not a Dataset

    A child who sees two or three pictures of an okapi can usually pick out the next one. A standard image classifier cannot do anything close to that. It needs hundreds or thousands of labeled images per class, and if a new class appears after training, the usual answer is to collect more data and train again.

    Plenty of real problems never supply that much data. A rare disease may have a few dozen confirmed cases in a hospital archive. A factory inspecting a new product line has no photos of its defects yet. A language with few speakers has little annotated text. Few-shot learning is the study of classifiers that have to work with a handful of labeled examples per class, often one or five.

    The usual vocabulary comes from the benchmarks. An «N-way K-shot» task gives the model N new classes with K labeled examples each (the support set) and then asks it to classify fresh examples of those classes (the query set). A 5-way 1-shot task means five classes and a single example of each.

    Omniglot and the Human Baseline

    The dataset that shaped the field is Omniglot, released by Brenden Lake, Ruslan Salakhutdinov and Joshua Tenenbaum. It has 1,623 handwritten characters from 50 alphabets, some historic, some invented for fiction, and each character was drawn by 20 different people recruited through Mechanical Turk. The design is the reverse of ImageNet: many classes, very few examples of each.

    Their 2015 paper in Science used it to compare people with machines on one-shot classification. The model they proposed, Bayesian Program Learning, represented each character as a small probabilistic program of pen strokes and reached an error rate comparable to the human participants. That result was a challenge to deep learning, since the networks of the time did much worse in the same setting. Much of the work that followed was an attempt to close the gap with neural networks instead of hand-built generative models.

    Episodes Instead of Batches

    The idea that made neural few-shot learning work is simple to state. If the model will be tested on small tasks with new classes, it should be trained on small tasks with new classes too. Oriol Vinyals and colleagues at DeepMind put it plainly in their 2016 NeurIPS paper on Matching Networks: test and train conditions must match.

    So training is organized in episodes. Each episode samples a few classes from the training set, a few support examples per class, and some queries. The model makes its predictions for that episode and gets a loss on the queries. The next episode uses different classes. Over thousands of episodes the model is not learning to recognize any specific class, since the classes keep changing. It is learning how to use a small support set.

    The same paper introduced miniImageNet, a subset of ImageNet with 100 classes and 600 images each, small enough to run on a modest budget. It became the standard benchmark, and most of the numbers in this area come from it.

    Comparing Instead of Classifying

    The first family of methods avoids learning a classifier at test time at all. It learns an embedding, a function that maps each image to a vector, and then classifies a query by comparing it with the support examples. Gregory Koch and colleagues used siamese networks for this in 2015, training a network to say whether two Omniglot characters were the same. Matching Networks went further and classified a query with an attention-weighted vote over the whole support set.

    Jake Snell, Kevin Swersky and Richard Zemel simplified the idea at NeurIPS 2017 with Prototypical Networks. Each class is reduced to one point, the mean of the embeddings of its support examples. A query goes to the class with the nearest prototype under squared Euclidean distance. That is the entire test-time procedure. On 5-way miniImageNet they reported 49.42% accuracy with one shot and 68.20% with five, which was the best published result at the time.

    The appeal is that nothing needs to be trained when a new class shows up. If the embedding has learned to put images of the same thing close together, a new class only needs a few examples to define its center.

    Learning an Initialization

    The second family treats the problem as optimization. Chelsea Finn, Pieter Abbeel and Sergey Levine proposed Model-Agnostic Meta-Learning (MAML) at ICML 2017. The goal is a set of starting weights from which a few gradient steps on a small support set give a good model for that task.

    Training has two loops. In the inner loop, the model takes one or a few gradient steps on the support set of a task, producing adapted weights. In the outer loop, those adapted weights are evaluated on the task’s query set, and the error is backpropagated through the inner steps to update the original starting weights. The outer loop does not ask for weights that are good on any one task. It asks for weights that become good quickly.

    The name «model-agnostic» means it works for any model trained by gradient descent, and the paper showed it on regression, image classification and reinforcement learning. On miniImageNet it reported 48.70% for 5-way 1-shot and 63.11% for 5-shot. The cost is the second-order term. Backpropagating through gradient steps requires second derivatives, which uses a lot of memory and time.

    First-Order Shortcuts

    The paper itself tested a first-order approximation that ignores those second derivatives and found that it performed almost as well. Alex Nichol, Joshua Achiam and John Schulman at OpenAI pushed this further in 2018 with Reptile. Reptile trains normally on a task for several steps, then moves the starting weights a little toward wherever that training ended. Repeat over many tasks and the starting point drifts toward a region from which all of them are easy to reach.

    Reptile has no inner and outer loss and no differentiation through the optimizer. It looks almost too plain to work, yet the authors reported results close to MAML on Omniglot and miniImageNet. They also gave an analysis showing that the update still contains a term that favors generalization across tasks, which is the effect MAML targets more directly.

    Case: A Good Embedding Was Most of It

    Around 2019 several groups looked closely at why these methods worked, and the answers were uncomfortable. Wei-Yu Chen and colleagues, in «A Closer Look at Few-shot Classification» (ICLR 2019), found that a plain baseline, trained as an ordinary classifier on the training classes and then fine-tuned on the support set, was competitive with meta-learning methods. With deeper backbones the differences between methods shrank. When the test classes came from a different domain (training on miniImageNet and testing on bird species), the baseline beat all the meta-learning algorithms they evaluated.

    Aniruddh Raghu, Maithra Raghu, Samy Bengio and Oriol Vinyals asked a related question about MAML at ICLR 2020: does it work because the inner loop adapts features quickly, or because the starting features are already good? They found feature reuse was the dominant factor. Their simplified version, ANIL (Almost No Inner Loop), adapts only the final layer and matches MAML. In a further variant they removed even that, and accuracy held.

    Yonglong Tian and colleagues at MIT and Google made the same point at ECCV 2020. They trained a standard network on all the training classes, froze it, and fit a linear classifier on each new task. That beat the specialized few-shot methods on the standard benchmarks, and self-distillation improved it further. Their title was a question, «A Good Embedding Is All You Need?», and the experiments mostly answered yes.

    Examples Inside a Prompt

    While vision researchers argued about episodes and inner loops, the phrase «few-shot» took on a second meaning. In 2020 Tom Brown and colleagues at OpenAI published «Language Models are Few-Shot Learners», the GPT-3 paper. Their model, with 175 billion parameters, was given a task description and a few worked examples directly in its input text, and then asked to complete a new one. No weights changed. The model inferred the task from the examples in the prompt, which the authors called in-context learning.

    This fits the meta-learning framing more closely than it first seems. Pre-training on a huge and varied corpus exposes the model to countless small implicit tasks, and the network learns to pick up patterns from its context. Some later research has studied in-context learning as a learned algorithm running inside the forward pass. The difference from MAML is where adaptation happens: in activations rather than in weights.

    Closing Thought

    The strange history of this field is that the methods built to learn how to learn were largely outperformed by models that had simply learned good representations from a lot of data. That is not a failure of the meta-learning idea. It says that «learning to learn» and «learning a lot» end up close together: a representation trained on enough varied classes already places new ones near the right neighbors, and a few examples are enough to mark where they sit. The hard part of learning from five examples was mostly done before the five examples arrived.

    By: Max Johnson B.

  • Active Learning: Letting the Model Choose Which Examples Get Labeled

    Unlabeled Data Is Cheap, Labels Are Not

    Most machine learning projects do not run short of data. They run short of labels. A hospital can have hundreds of thousands of chest X-rays in its archive, and a self-driving car fleet records more video in a day than any team could annotate in a year. What is scarce is the time of the person who has to look at each example and say what it is, and in medicine or law that person is expensive.

    The usual way to build a training set ignores this. Someone picks a random sample, sends it to annotators, and trains on whatever comes back. Random sampling is fair and simple, but it spends most of the budget on easy, redundant cases. The thousandth clear photo of a cat teaches a classifier almost nothing it did not learn from the first hundred.

    Active learning starts from a different question: if the model is allowed to choose which examples get labeled, can it reach the same accuracy with fewer labels? Burr Settles put this premise at the center of his 2009 survey of the field (a technical report from the University of Wisconsin-Madison that is still the standard introduction), and the honest answer is «often, but not always, and the conditions matter more than most papers admit.»

    The Loop

    The most common setting is pool-based active learning. There is a small labeled set, a large pool of unlabeled examples, and an oracle, usually a human annotator. The procedure repeats the same steps. Train a model on the labeled set. Score every example in the pool with an acquisition function that estimates how useful its label would be. Send the top examples to the oracle. Add the answers to the labeled set and train again.

    Everything interesting happens in the acquisition function. It has to predict the value of a label before the label exists, using only the current model and the unlabeled data. Different families of methods make that prediction in different ways, and most of the research in the field is an argument about which guess is best.

    Uncertainty Sampling

    The oldest and simplest idea is to ask about the examples the model is least sure of. David Lewis and William Gale described it in a 1994 SIGIR paper on text classification and called it uncertainty sampling. On a newswire categorization task, they reported that it reduced the amount of manually classified training data needed to reach a given effectiveness by as much as 500-fold.

    There are a few standard ways to measure uncertainty from a classifier’s predicted probabilities. Least confidence picks the example whose top class has the lowest probability. Margin sampling looks at the gap between the two most likely classes and picks the smallest gap. Entropy uses the whole distribution. For a binary problem they all select the same points; with many classes they can disagree.

    The weakness is that a model’s probabilities are often badly calibrated, and deep networks are known for being confident on inputs they get wrong. A point near the decision boundary looks uncertain, which is good. But a point that is simply noisy or ambiguous also looks uncertain, and labeling it again and again does not help.

    Disagreement Between Models

    A second family asks a committee instead of a single model. Query by committee, introduced by Seung, Opper and Sompolinsky at COLT in 1992, trains several models on the same labeled data and queries the examples where they disagree most. The intuition is about the space of hypotheses. Every label rules out the models that would have predicted it wrong, and a point that splits the committee in half rules out the most.

    Houlsby and colleagues turned a version of this into an information-theoretic criterion in 2011, called BALD (Bayesian Active Learning by Disagreement). BALD picks the example that maximizes the mutual information between its label and the model parameters. In plain terms, it wants points where each plausible model is confident but the models disagree with each other. That separates uncertainty that comes from not knowing enough (worth labeling) from noise that is in the data itself (not worth labeling).

    Yarin Gal, Riashat Islam and Zoubin Ghahramani brought this into deep learning at ICML 2017. They used dropout at test time as a cheap approximation to a Bayesian network, so that a single CNN could act as its own committee. On MNIST, starting from 20 labeled images, their best acquisition function (variation ratios) reached 5% test error with 295 labels and BALD needed 335, while random sampling needed 835. They also ran the method on skin lesion images from the ISIC 2016 challenge.

    Batches and Diversity

    The classic algorithms assume one query at a time. Deep networks are slow to retrain, so real systems ask for hundreds or thousands of labels per round. That breaks naive uncertainty sampling, because the top thousand uncertain images are often near-duplicates of each other, and labeling all of them wastes most of the batch.

    Ozan Sener and Silvio Savarese reframed the problem at ICLR 2018 as core-set selection: choose a subset of points such that a model trained on it is competitive on the rest of the data. Their bound reduces to the k-center problem in the network’s feature space, so the method picks points that cover the pool geometrically and ignores uncertainty entirely. They also reported that many uncertainty heuristics from the literature did not work well for CNNs in the batch setting.

    BADGE, from Jordan Ash and coauthors at ICLR 2020, combines both ideas. For each unlabeled point, it computes the gradient of the loss with respect to the last layer, using the model’s own predicted label as if it were true. The size of that gradient is large when the model is unsure, and the direction says what kind of update the point would cause. BADGE then runs k-means++ seeding on these vectors, which favors points that are both large and far from each other, without an extra parameter to balance the two.

    The Cold Start Problem

    Almost every method above depends on a model that is already somewhat good. At the very beginning, with ten or twenty labels, the model’s uncertainty estimates are close to meaningless, and choosing by them can be worse than choosing at random.

    Guy Hacohen, Avihu Dekel and Daphna Weinshall studied this at ICML 2022 in a paper titled «Active Learning on a Budget: Opposite Strategies Suit High and Low Budgets.» Their argument is that with a tiny budget you should label typical examples, the ones from dense regions that represent the data well, and only later switch to hard, atypical ones. Their method, TypiClust, clusters the data in a self-supervised embedding and picks the densest point in each cluster. With 10 labeled CIFAR-10 images chosen this way, a semi-supervised learner reached 93.2% accuracy, which the authors report as a 39.4% improvement over random selection.

    The result reverses the intuition of uncertainty sampling. Early on, the best question to ask is the easiest one.

    Case: Pedestrians at Night

    Active learning has been tested at industrial scale in autonomous driving, where data is plentiful and labeling every frame is impossible. Elmar Haussmann and colleagues at NVIDIA described a production system in a paper at the 2020 IEEE Intelligent Vehicles Symposium. It scored unlabeled frames by the uncertainty of an ensemble of object detectors, and the evaluation focused on night-time driving.

    They compared two ways of choosing new frames to label: their active learning pipeline and a selection made by human experts. Both improved the detector, but for pedestrians the actively selected data raised weighted mean average precision by 3.3%, against 1.1% for the manually curated data. For bicycles, the gain from active learning was 4.4 times the gain from manual selection. The difference was largest on large objects. Engineers who knew the domain well still picked less useful frames than an uncertainty score did.

    Random Sampling Is a Hard Baseline

    The literature has a reproducibility problem, and researchers inside the field have pointed it out. Munjal and coauthors, at CVPR 2022, reran several active learning methods (uncertainty-based, diversity-based and committee-based) under identical conditions. With a well-regularized model, every method improved, random sampling included, and the differences between methods became negligible. Many earlier gains were partly an artifact of weak baselines.

    Lowell, Lipton and Wallace raised a different issue at EMNLP 2019. A labeled set built by active learning is tied to the model that selected it. When they trained a different model on that data, which is what happens when a team upgrades its architecture a year later, it often did no better than the same model trained on a random sample, and sometimes worse. Since a labeled dataset usually lives longer than any single model, that matters.

    Active learning still pays off in many settings, but the benefit depends on the budget, the model, the regularization and the data, and a paper that shows a gain on one benchmark says less than it seems.

    A Final Observation

    A random sample is a neutral description of the world. An actively acquired dataset is not. It records what one particular model found confusing at one particular moment, and every downstream use inherits that point of view, including the test set if anyone is careless enough to draw it the same way. The practical consequence is simple. Whatever selection strategy a team uses for training labels, it should keep a slice of the budget for plain random sampling, because that slice is the only part of the data that can honestly say how the model performs on the world as it is.

    By: Max Johnson B.

  • Causal Inference in Machine Learning: Asking What Would Happen Instead of What Usually Happens

    Asthma as a Protective Factor

    In the 1990s, a group of researchers trained several models to predict which pneumonia patients were likely to die, so that low-risk patients could be treated at home. Rich Caruana, one of them, described what went wrong in a KDD 2015 paper. A rule-based model learned that patients with asthma had a lower risk of death. The rule was correct about the data. Asthmatic patients with pneumonia were usually sent straight to intensive care, and the aggressive treatment lowered their mortality below the average.

    A model that sent asthmatic patients home because of that rule would have removed the very treatment that produced the low risk. The rule-based model was readable, so a person caught it. The most accurate model in the study, a neural network, had probably learned the same pattern where nobody could see it.

    The model answered the question it was trained on: among patients like this, how often do they die? The hospital needed an answer to a different question: what happens to this patient if we treat them one way or the other? The first is prediction. The second is causal inference, and no amount of extra data of the first kind settles it.

    Case: Kidney Stones

    A 1986 study in the BMJ by C. R. Charig and colleagues compared two treatments for kidney stones. Open surgery succeeded in 78% of 350 patients. Percutaneous nephrolithotomy, a less invasive procedure, succeeded in 83% of 350 patients. The newer method looks better.

    Split the patients by stone size and the comparison flips. For small stones, open surgery succeeded in 81 of 87 cases (93%) against 234 of 270 (87%) for the other procedure. For large stones, it was 192 of 263 (73%) against 55 of 80 (69%). Open surgery wins in both groups and loses overall.

    This is Simpson’s paradox, and the explanation is in how patients were assigned. Doctors tended to use open surgery on large stones, which are harder to treat no matter what. Stone size affected both the choice of treatment and the outcome. A table of numbers cannot say whether to trust the overall figure or the split one. That depends on what causes what, and the data do not contain that information. A person has to bring it.

    Potential Outcomes

    One formal language for this comes from statistics. Jerzy Neyman used it for agricultural experiments in 1923, and Donald Rubin developed it for observational studies in a 1974 paper in the Journal of Educational Psychology. Each patient has two potential outcomes: the result they would have with the treatment and the result they would have without it. The causal effect for that patient is the difference.

    The difficulty is that only one of the two is ever observed. A patient who had open surgery did not also have the other procedure. Paul Holland, writing in 1986, called this the fundamental problem of causal inference. Every causal method is a way of filling in the missing half from other people who received the other treatment.

    A randomized experiment fills it in cleanly, because a coin flip decides who gets what, so the two groups are alike on average in everything, measured or not. Without randomization, the usual assumption is called unconfoundedness: once a set of measured variables is accounted for, treatment assignment is as good as random. It cannot be tested from the data. It is a claim about the world.

    Graphs and the do Operator

    Judea Pearl approached the same problem from computer science. He represented assumptions as a directed graph in which an arrow from A to B means A directly influences B. In the kidney stone study, stone size points to treatment and to outcome, and treatment points to outcome.

    Pearl separated two quantities that ordinary probability writes the same way. The probability of recovery given that a patient received a treatment describes the patients doctors chose for it. The probability of recovery given do(treatment) describes what would happen if everyone were assigned to it. His back-door criterion says which variables to adjust for to turn the first into the second. Here, adjusting for stone size is correct, so the split table gives the right answer. In a different graph, where the third variable is caused by the treatment, adjusting for it would create bias instead of removing it.

    In a 1995 paper in Biometrika, Pearl introduced the do-calculus, three rules for deciding whether an interventional quantity can be computed from observational data at all. In his 2018 book with Dana Mackenzie, The Book of Why, he arranges these questions on a ladder with three rungs: association (seeing), intervention (doing), and counterfactuals (imagining what would have happened). Standard supervised learning stays on the first rung.

    Case: LaLonde and the Job Training Program

    The most cited test of whether observational methods work comes from economics. The National Supported Work Demonstration was a job training program in the 1970s that randomly assigned applicants to training or to a control group, so the true effect on earnings was known. In a 1986 paper in the American Economic Review, Robert LaLonde threw away the randomized control group, replaced it with comparison people taken from large national surveys, and ran the standard econometric estimators of the time. Many of them failed to recover the experimental result, and different specifications gave very different answers.

    Paul Rosenbaum and Donald Rubin had proposed the propensity score in 1983: the probability that a person receives the treatment given their covariates. Rajeev Dehejia and Sadek Wahba applied it to LaLonde’s data in a 1999 JASA paper and got estimates much closer to the experimental benchmark.

    The story did not end there. Jeffrey Smith and Petra Todd argued in 2005 that the good result depended on which subsample of LaLonde’s data was used. The lesson students take from the debate is narrower than «matching works.» The estimator matters less than whether the comparison group resembles the treated group in the ways that drive the outcome.

    Machine Learning as the Estimator

    Once the causal question and its assumptions are fixed, what is left is estimation, and that is where machine learning fits well. Adjusting for confounders requires modeling how the outcome depends on them and how treatment depends on them.

    Simply plugging a flexible model into the old formulas causes trouble, because regularization biases the estimate in ways that do not average out. Victor Chernozhukov and six coauthors addressed this in «Double/Debiased Machine Learning,» published in The Econometrics Journal in 2018. They fit two machine learning models, one for the outcome and one for the treatment, and estimate the effect from the residuals of both. They also use cross-fitting, where the models are trained on one part of the data and evaluated on another. The result is an estimate with valid confidence intervals even when the models are random forests or neural networks.

    A second line of work asks whether the effect differs from person to person. Stefan Wager and Susan Athey extended random forests into causal forests (JASA, 2018). The trees split the data to find groups where the treatment effect differs, and the authors proved the estimates are consistent and approximately normal under unconfoundedness. Marketing teams use the same idea under the name uplift modeling, where the goal is to find customers whose behavior changes because of a discount, not customers who would have bought anyway.

    Shortcuts in Image Models

    Deep learning has its own version of the asthma rule. John Zech and colleagues (PLOS Medicine, 2018) trained convolutional networks to detect pneumonia in chest X-rays from three hospital systems. Performance on X-rays from a hospital not seen in training was significantly worse in three of five comparisons. The networks could also identify which hospital an image came from with over 99.9% accuracy. Since pneumonia rates differed between hospitals, recognizing the hospital was a cheap way to predict the disease.

    In causal terms, the hospital is a confounder that affects both the image and the label. The network learned a correlation that held in the training data and broke when the data came from somewhere else.

    Martin Arjovsky, Léon Bottou, Ishaan Gulrajani and David Lopez-Paz proposed Invariant Risk Minimization in 2019 as one response. If data come from several environments, a feature that predicts the label equally well in all of them is more likely to be causal than one whose usefulness changes. Their test case, Colored MNIST, ties the color of a digit to its label in training and reverses the link at test time. Later analyses found that the practical version of IRM often does no better than ordinary training, so the problem is far from solved.

    Learning the Graph From Data

    All of the methods above assume someone drew the graph. Causal discovery tries to recover it from data. The PC algorithm, developed by Peter Spirtes and Clark Glymour around 1991, tests conditional independences and removes edges between variables that turn out to be independent given others. In 2018, Xun Zheng and colleagues at NeurIPS reformulated the search over graphs as a continuous optimization problem, called NOTEARS, which can be solved with gradient methods.

    There is a hard limit. Observational data alone usually cannot distinguish between graphs that imply the same independences. A chain from A to B to C and a chain from C to B to A produce the same pattern, so the algorithm can return a set of equivalent graphs but not choose among them. Breaking the tie takes an experiment or an extra assumption.

    A Final Observation

    Every causal estimate in this post depends on something outside the data: a graph, an assumption of unconfoundedness, a randomized control group someone paid for. Machine learning has made the estimation step much more powerful, and it has not changed that. The kidney stone table is the same table whether one trusts the overall figure or the split one. What decides between them is a sentence a doctor can say and a dataset cannot: large stones were harder to treat and more often sent to surgery. Causal inference is the part of machine learning where the most important input is written down by a person.

    By: Max Johnson B.

  • Monte Carlo Tree Search: Choosing a Move by Playing Out Thousands of Games

    A Tree Too Large to Read

    Every board game can be drawn as a tree. The current position is the root, each legal move is a branch, and each branch leads to a new position with branches of its own. A program that could read the whole tree would play perfectly. No program can, so the classical approach in chess was to read a few moves ahead with minimax and alpha-beta pruning, then stop and score the positions at the edge of the search with a hand-written evaluation function (material, king safety, pawn structure).

    Go broke that recipe. The 2016 AlphaGo paper puts the typical breadth of the game at about 250 legal moves per position and its length at about 150 moves, against roughly 35 and 80 for chess. The bigger problem was the evaluation function. In chess, counting pieces gives a decent first guess of who is winning. In Go, nobody managed to write a formula that told a strong position from a weak one in the middle of a game, so even a deep search ended on scores that meant very little.

    Monte Carlo Tree Search (MCTS) gets around this by not writing an evaluation function at all. To judge a position, it plays the game out to the end many times, usually with fast and mostly random moves, and counts how often each side wins.

    Random Games as an Evaluation Function

    The idea that random playouts could say something about Go is older than the name. In 1993, Bernd Brügmann wrote a short report called «Monte Carlo Go» in which he treated move choice as an optimization problem and borrowed from simulated annealing. His program was weak, but the average result of many careless games turned out to carry real information about a position.

    For more than a decade the idea stayed on the margins. Then, in 2006, two groups turned it into a search method. Rémi Coulom presented a randomized tree search for his Go program Crazy Stone and gave the approach its name. In the same year, Levente Kocsis and Csaba Szepesvári published «Bandit Based Monte-Carlo Planning» at ECML, which introduced the UCT algorithm. The two lines of work were independent.

    The Four Steps

    MCTS builds its tree gradually, one simulated game at a time. Each iteration has four parts.

    1. Selection. Starting at the root, the algorithm walks down the part of the tree it has already built, choosing a child at each node according to a rule that balances good results against little-tried moves.

    2. Expansion. When it reaches a node with moves that have never been tried, it adds one (or a few) new child nodes to the tree.

    3. Simulation. From the new node, it plays a complete game with a cheap default policy, often uniformly random moves, until someone wins.

    4. Backpropagation. The result travels back up the path to the root. Every node on the way updates two numbers: how many times it was visited and how many of those visits ended in a win.

    After thousands of iterations, the program plays the move at the root with the most visits. The visit count is used instead of the raw win rate because a move with a high win rate over only a handful of visits may simply have been lucky.

    What makes this different from minimax is the shape of the tree. Minimax looks at every move to a fixed depth. MCTS grows the tree unevenly: promising lines get searched deeply, and poor ones stop receiving visits once the statistics make it clear they are poor.

    The Bandit Behind the Selection Rule

    The selection step hides a hard question. Should the algorithm keep visiting the move that looks best so far, or spend some visits on moves that might be better but have barely been tried? This is the multi-armed bandit problem, named after a gambler deciding which slot machine to play.

    Kocsis and Szepesvári took their answer from UCB1, a bandit strategy analyzed by Peter Auer, Nicolò Cesa-Bianchi and Paul Fischer in 2002. At each node, UCT picks the child that maximizes the average reward plus an exploration bonus. The bonus is a constant times the square root of the logarithm of the parent’s visit count divided by the child’s visit count. A rarely visited move gets a large bonus, which shrinks as its visit count rises.

    The constant controls the balance, and in practice it is tuned for each game. The theoretical result in the 2006 paper is what made UCT attractive: given enough simulations, the probability of choosing a suboptimal move at the root goes to zero. MCTS is also an anytime algorithm. It can be stopped after any number of iterations and still return its current best move, which suits games with a clock.

    Case: MoGo and Go Before Deep Learning

    The first strong MCTS programs were Go programs, and MoGo was one of the most successful. Sylvain Gelly and David Silver added an idea called RAVE (rapid action value estimation). Plain UCT learns about a move only from simulations where it was played at that exact node. RAVE also credits a move whenever it appeared later in the same simulated game, a heuristic known as «all moves as first.» The estimate is biased, but it arrives much faster, and the algorithm gradually shifts weight to the unbiased value as visits accumulate. Their AAAI 2008 paper reported that MoGo, with RAVE and heuristic knowledge, became the first program to reach master level in 9×9 Go.

    On August 7, 2008, MoGo, running on a supercomputer, beat the professional Kim Myungwan (8 dan) in a 19×19 game with a nine-stone handicap. Nine stones is a large handicap, and even games on the full board stayed out of reach for years.

    Neural Networks Inside the Tree

    AlphaGo, published by David Silver and colleagues in Nature in 2016, kept MCTS as its search procedure and replaced the weak parts with neural networks. A policy network trained on expert games gave each move a prior probability, so selection favored moves a strong player would consider. A value network estimated the winner from a position directly, and AlphaGo mixed that estimate with the result of fast rollouts. AlphaGo beat the European champion Fan Hui 5 to 0 in October 2015 and Lee Sedol 4 to 1 in March 2016.

    AlphaGo Zero (Nature, 2017) went further. It learned only from self-play, starting from the rules, and dropped random rollouts entirely: leaf positions were scored by the value network alone. Its selection rule, a variant called PUCT, multiplies the exploration bonus by the network’s prior for each move. The search and the network also trained each other. With 1,600 simulations per move during self-play, MCTS produced move distributions that were stronger than the raw network, and the network was then trained to imitate those distributions. The finished program beat the version of AlphaGo that played Lee Sedol 100 games to 0. A generalized version, AlphaZero (Science, 2018), applied the same recipe to chess and shogi.

    MuZero (Julian Schrittwieser and colleagues, Nature, 2020) removed the last piece of given knowledge, the rules themselves. It learns a model that predicts rewards, values and policies inside a learned representation and runs the tree search on that model. It matched AlphaZero in Go, chess and shogi and set a new state of the art on the Atari benchmark, where nobody hands the program a simulator.

    Search Outside of Games

    MCTS needs little from a problem: a way to list actions, apply them and score a finished sequence. In General Game Playing, programs receive the rules of a game they have never seen and must play it with no human tuning. CadiaPlayer, written by Yngvi Björnsson and Hilmar Finnsson at Reykjavik University, used Monte Carlo simulations instead of classical game tree search and won the AAAI competition in 2007 and 2008.

    Chemistry is a less obvious fit. In retrosynthesis, a chemist works backward from a target molecule, choosing reactions that break it into simpler precursors until everything can be bought. Marwin Segler, Mike Preuss and Mark Waller (Nature, 2018) treated each step as a move in a tree search. A policy network trained on millions of published reactions proposed likely transformations, another network filtered out implausible ones, and MCTS searched for complete routes. Their system solved almost twice as many molecules as a traditional rule-based computer search, about thirty times faster. In a blinded test, chemists judged its routes as roughly equivalent to routes reported in the literature.

    Shallow Traps

    MCTS has a known weakness, and chess exposes it. Raghuram Ramanujan, Ashish Sabharwal and Bart Selman (ICAPS 2010) studied what they called shallow traps: moves after which the opponent has a forced win within a few plies. Minimax finds these easily, because it checks every reply. MCTS averages over random continuations, and in a position where only one precise reply wins, most random games will miss it. The trap looks safe on average.

    The authors found that such traps are rare in Go but common in chess, including in grandmaster games. This helps explain why plain MCTS never threatened alpha-beta engines in chess, and why later work tried hybrids that run small minimax searches inside the MCTS tree. AlphaZero, which did beat strong chess engines, never relied on random playouts there. Its leaves were scored by a trained value network, which can learn to recognize a forcing line that random games would average away.

    A Final Observation

    The exploration bonus in UCT is a formula for admitting ignorance. It does not say a move is good. It says the program has not looked at it enough to know, and it attaches a number to that. Classical game engines had nothing like it: an evaluation function returned a confident score whether the position was well understood or not. MCTS lets a program be uncertain on purpose and spend its computation where that uncertainty is largest. AlphaGo and its successors changed almost every other part of the algorithm, but they kept that.

    By: Max Johnson B.

  • RLHF and Preference Optimization: Training Language Models on Which Answer People Prefer

    A Model That Imitates Everything It Read

    A language model trained only on next-token prediction learns to continue text the way text on the internet tends to continue. Ask it a question and it may answer, or it may produce three more questions, because a list of questions is a perfectly plausible continuation. It has no built-in idea that one continuation is helpful and another is not. It only knows which one is likely.

    Supervised fine-tuning on written demonstrations helps, but it has a ceiling. Someone has to write every good answer by hand, and the model learns to copy the style of those answers rather than to understand what made them good. There is also a practical asymmetry: most people cannot write an excellent summary of a legal document on demand, but almost anyone can read two summaries and say which one is better. Reinforcement learning from human feedback (RLHF) is built on that asymmetry.

    Comparisons Instead of Scores

    The idea predates chatbots. In 2017, Paul Christiano, Jan Leike and colleagues at OpenAI and DeepMind published «Deep Reinforcement Learning from Human Preferences» at NeurIPS. Their agents played Atari games and controlled simulated robots, and instead of receiving a reward from the environment, they received human judgments about pairs of short video clips: which of these two looks more like what I want?

    It needed very little human input. The paper reports that the method worked while humans gave feedback on less than 1% of the agent’s interactions with the environment, and that complex new behaviors could be trained with about an hour of human time. The best known example was a simulated robot learning to do a backflip, a behavior that is hard to write as a reward function but easy to recognize. According to OpenAI, it took around 900 bits of feedback from the evaluator.

    Asking for comparisons rather than numeric scores is a deliberate choice. People are inconsistent when asked to rate something from 1 to 10, and two raters rarely share the same scale. They are much more consistent when asked to pick one of two.

    The Reward Model

    Comparisons cannot be optimized directly, so the first step is to turn them into a function. A reward model, usually a copy of the language model with its output layer replaced by a single number, is trained to give the preferred response a higher score than the rejected one.

    The training objective comes from the Bradley-Terry model, proposed by Ralph Bradley and Milton Terry in 1952 for ranking items from paired comparisons. It says that the probability a person prefers response A over response B is the sigmoid of the difference between their scores. Training the reward model means maximizing the log-likelihood of the human choices under that assumption. Only the difference between two scores matters, so the absolute value of a reward means nothing on its own.

    Once trained, the reward model can score any new response in milliseconds. That is the point: a human cannot sit in the loop for millions of training steps, but a model of the human can.

    PPO and the KL Penalty

    The second step treats the language model as a policy. A prompt is the state, the generated response is the action, and the reward model provides the score at the end. The usual algorithm is Proximal Policy Optimization (PPO), introduced by John Schulman and colleagues in 2017, which limits how far each update can move the policy.

    Left alone, this optimization finds strange outputs. The reward model was trained on responses from the original model, and once the policy drifts into text that looks nothing like that distribution, the reward model’s scores stop meaning anything. To prevent this, the reward is reduced by a penalty proportional to the KL divergence between the current policy and the original supervised model. The model is pushed toward higher reward but kept close to the language it already knows how to produce. The strength of that penalty, usually called beta, is one of the most important settings in the whole pipeline.

    In practice this means running four models at once: the policy being trained, the frozen reference model, the reward model, and a value network that PPO uses to estimate expected reward. That cost, and PPO’s sensitivity to hyperparameters, explains much of what came later.

    Case: InstructGPT

    Two papers made RLHF work on language. In 2020, Nisan Stiennon and colleagues applied it to summarizing Reddit posts. OpenAI reported that a 1.3 billion parameter model trained with human feedback outperformed a 12 billion parameter model trained only with supervised learning, and labelers preferred the feedback models’ summaries to the human-written ones in the dataset.

    In 2022, Long Ouyang and colleagues published InstructGPT (NeurIPS 2022), the method behind the first version of ChatGPT. The pipeline had three stages: supervised fine-tuning of GPT-3 on demonstrations written by labelers, a reward model trained on rankings of model outputs, and PPO against that reward model. The headline result was that people preferred outputs from the 1.3 billion parameter InstructGPT model to those of the 175 billion parameter GPT-3, a model with roughly 100 times more parameters. The paper also reported better truthfulness and less toxic output, with small regressions on some public NLP benchmarks.

    That comparison is the one people remember. A large part of what users experienced as quality was not coming from more parameters. It came from rankings that labelers wrote for roughly 33,000 prompts.

    Reward Hacking

    A reward model is an approximation of what people want, and optimizing hard against an approximation eventually exploits its errors. Leo Gao, John Schulman and Jacob Hilton measured this in «Scaling Laws for Reward Model Overoptimization» (ICML 2023). They used a large fixed reward model as a stand-in for humans, trained smaller proxy reward models on its labels, and optimized policies against the proxies. The proxy score kept rising, while the score from the «gold» model rose, peaked, and then fell. Larger reward models delayed the drop but did not remove it.

    The errors that get exploited are often mundane. Stiennon’s team noticed that their labelers favored longer summaries, and the models converged to the longest length allowed. Prasann Singhal and colleagues later found that, in several standard setups, a reward based purely on response length reproduced most of the improvement RLHF gave over supervised fine-tuning. Mrinank Sharma and colleagues at Anthropic (ICLR 2024) found that both humans and preference models sometimes preferred convincingly written answers that agreed with the user over correct ones, which gives the training process a direct incentive toward sycophancy.

    Direct Preference Optimization

    In 2023, Rafael Rafailov, Archit Sharma, Eric Mitchell, Christopher Manning, Stefano Ermon and Chelsea Finn published «Direct Preference Optimization: Your Language Model is Secretly a Reward Model» at NeurIPS. Their observation was mathematical. The KL-constrained objective that RLHF optimizes has a known optimal solution: the best policy is the reference model’s distribution reweighted by the exponential of the reward divided by beta.

    That relationship can be inverted. Any policy implies a reward, equal to beta times the log ratio between the policy’s probability of a response and the reference model’s probability, plus a term that depends only on the prompt. Substitute that implied reward into the Bradley-Terry loss and the prompt-only term cancels, because Bradley-Terry only looks at differences. What remains is a loss written entirely in terms of the policy and the reference model: increase the log-probability ratio of the preferred response relative to the rejected one, passed through a sigmoid.

    DPO needs no separate reward model, no sampling during training, and no PPO. It looks like ordinary supervised training on pairs. Many open models adopted it quickly, and variants followed, including IPO (Azar and colleagues) and KTO (Ethayarajh and colleagues), which works from single responses labeled good or bad instead of pairs. DPO does not escape the underlying problem, though. It still learns from the same preference data, with the same biases toward length and agreement.

    Rewards From Rules and From Other Models

    Human comparisons are expensive, so later work replaced some of them. Anthropic’s Constitutional AI (Bai and colleagues, 2022) had a model critique and revise its own answers against a written list of principles, then used AI-generated preference labels for the reinforcement learning stage, an approach often called RLAIF.

    For tasks with checkable answers, the reward model can be dropped entirely. DeepSeekMath (Shao and colleagues, 2024) introduced Group Relative Policy Optimization (GRPO), which removes PPO’s value network: it samples several answers to the same question and uses each answer’s reward relative to the group’s average as its advantage. DeepSeek-R1 (2025) combined GRPO with rule-based rewards, checking whether a math answer is correct or whether code passes tests, rather than relying on a learned reward model. A rule is harder to fool than a neural network, but only a narrow set of tasks have rules.

    Closing Note

    The name suggests that RLHF teaches a model human values. What it teaches is narrower: the model learns to produce the response that a particular group of raters, reading quickly, would pick from a pair. Most of the time that is close to the response a careful person would want. The cases where it is not (longer is not better, agreeing is not the same as being right) are where the method’s real assumptions show up. Every preference dataset carries a description of its raters, and the model trained on it inherits that description along with the good answers.

    By: Max Johnson B.

  • Mixture of Experts: Large Models That Only Use Part of Themselves for Each Token

    Paying for Every Parameter

    In a standard dense neural network, every parameter takes part in every prediction. If a language model has 70 billion weights, all 70 billion are multiplied against each token it reads, whether the token is a word in a legal contract, a line of Python or a comma. Capacity and cost are tied together: a model that knows more also costs more to run, in a nearly fixed proportion.

    A mixture of experts (MoE) model breaks that link. Instead of one large feed-forward block, a layer holds many smaller blocks, the experts, plus a small network called a router that decides which of them should process the current input. Only the chosen experts run. The model can store a very large number of parameters while spending, per token, the compute of a much smaller one. Many of the largest open-weight language models released since 2024 are built this way, and the reasons it works (and the ways it misbehaves) say a lot about how these systems are trained.

    Local Experts in 1991

    The idea is older than deep learning. In 1991, Robert Jacobs, Michael Jordan, Steven Nowlan and Geoffrey Hinton published «Adaptive Mixtures of Local Experts» in Neural Computation. Their system trained several small networks together with a gating network that assigned each input to the expert most likely to handle it well. Because the experts competed for training cases, each one drifted toward a different region of the input space.

    They tested it on vowel discrimination, and the paper reports that the procedure split the task into subtasks, each simple enough for a very small expert network to solve. A companion paper by Nowlan and Hinton found that the modular version generalized better than a single backpropagation network across many variations of the problem. The motivation then was specialization and cleaner learning, not saving compute. That second motivation took another 26 years to arrive.

    Noisy Top-k Gating

    In 2017, Noam Shazeer and colleagues at Google published «Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer» at ICLR. They placed a layer with up to thousands of feed-forward experts between stacked LSTM layers and let a trainable gate pick a sparse set of them for each example. The largest configuration had 137 billion parameters, an enormous number for 2017, and the authors reported more than a thousandfold increase in model capacity with only minor losses in computational efficiency on GPU clusters.

    The gate works like this. It computes a score for every expert, keeps the top k scores, sets the rest to minus infinity and applies a softmax, so only k experts receive nonzero weight. The layer’s output is the weighted sum of those k experts’ outputs. Shazeer’s team added tunable Gaussian noise to the scores before taking the top k. The noise gives experts that are slightly behind a chance to be selected and receive gradient, which matters because an expert that is never chosen never learns.

    The Load Balancing Problem

    That last point is the central difficulty of the whole approach. Routing is learned, and learning is greedy. Early in training, a few experts happen to perform slightly better, so the router sends them more tokens, so they improve faster, so the router sends them even more. Left alone, the router collapses onto a handful of experts and the rest of the parameters sit idle. The model then has the memory cost of a huge network and the quality of a small one.

    The usual fix is an auxiliary loss added to the training objective that penalizes uneven routing. Shazeer’s 2017 paper used a term based on how much total gate weight each expert received across a batch. Later work simplified it to a product of two quantities per expert: the fraction of tokens actually sent to it and the average probability the router assigned to it. The loss is smallest when both are uniform. The coefficient has to be small (values around 0.01 are common), because a strong balancing term forces the router to spread tokens evenly even when an uneven split would produce better predictions.

    Switch Transformer and One Expert per Token

    Google’s next step, the Switch Transformer by William Fedus, Barret Zoph and Noam Shazeer (2021, later in JMLR), took sparsity further. Earlier designs such as GShard routed each token to two experts. Switch sent each token to exactly one, reasoning that this cuts both computation and the communication between devices. The authors reported large gains in pre-training speed over dense T5 models at the same compute, including about a fourfold speedup over a tuned T5-XXL, and trained models up to roughly 1.6 trillion parameters.

    Two practical details from that paper show up in almost every MoE system since. The first is the capacity factor. Hardware wants fixed tensor shapes, so each expert gets a buffer sized to the average number of tokens it would receive under perfect balance, multiplied by a factor such as 1.25. Tokens that arrive after an expert’s buffer is full are dropped: they skip the expert and pass through the layer’s residual connection unchanged. The second is selective precision. Most of the model trained in bfloat16, but the router ran in float32, because the exponentials in its softmax were a frequent source of training instability. A follow-up, ST-MoE (Zoph and colleagues, 2022), added a «router z-loss» that keeps the router’s raw scores small for the same reason.

    Case: Mixtral 8x7B

    The model that made MoE familiar outside large labs was Mixtral 8x7B, released by Mistral AI in December 2023 under the Apache 2.0 license. Each of its 32 layers has eight feed-forward experts, and the router sends each token to two of them. According to Mistral, the model has 46.7 billion parameters in total but uses 12.9 billion per token. The name can mislead: it is not eight 7B models glued together, since the attention layers and embeddings are shared and only the feed-forward blocks are duplicated.

    Mistral reported that Mixtral matched or outperformed Llama 2 70B and GPT-3.5 on most of the benchmarks they tested, with roughly a fifth of Llama 2 70B’s active parameters. The paper’s routing analysis is the more interesting part. The authors checked whether experts specialized by subject, using text from sources like arXiv papers, biology abstracts and philosophy, and found no clear pattern by topic. What they did find was that routing followed structure: consecutive tokens often went to the same expert, and some tokens in code (such as indentation) were assigned consistently. The experts divided the work along lines that made sense to the optimizer, not to a librarian.

    Finer Experts and a Bias Instead of a Loss

    DeepSeek’s line of models changed the recipe in two ways. The DeepSeekMoE paper (Dai and colleagues, ACL 2024) argued that eight or sixteen large experts are too coarse, because each one ends up covering a mix of unrelated knowledge. Its answer was fine-grained segmentation: split each expert into several smaller ones and activate more of them, so the compute per token stays the same while the number of possible combinations grows. It also isolated a few shared experts that every token passes through, so common knowledge does not have to be copied into every routed expert.

    DeepSeek-V3, described in a technical report released in December 2024, has 671 billion parameters with 37 billion active per token, trained on 14.8 trillion tokens using 2.788 million H800 GPU hours. Its most cited routing change is what the authors call auxiliary-loss-free load balancing. Each expert gets a bias term that is added to its score only when deciding which experts to select; the weights used to combine the outputs still come from the original scores. After each step, the bias of an overloaded expert is lowered and the bias of an underused one is raised, by a fixed small amount. Balance is enforced by a dial outside the gradient, so the language modeling loss is not pulled in two directions. A tiny sequence-level balance loss is kept only as a safety net against extreme cases.

    Memory and Communication

    Sparse computation does not mean sparse memory. All 46.7 billion of Mixtral’s parameters must be loaded to serve it, because any token might need any expert. On a single machine, an MoE model needs the memory of its total size and gives the speed of its active size. That trade is favorable for providers serving many users at once and less favorable for someone running a model on one consumer GPU.

    At larger scale, the experts live on different accelerators, an arrangement called expert parallelism. Every MoE layer then requires two all-to-all exchanges: tokens are sent to whichever devices hold their chosen experts and the results are sent back. GShard (Lepikhin and colleagues, ICLR 2021) was largely a paper about making this practical, and it trained a 600-billion-parameter multilingual translation model, covering 100 languages into English, on 2,048 TPU v3 cores in four days. Much of the engineering in recent MoE reports is about hiding this communication behind computation, because on real clusters the network, not the arithmetic, is often the bottleneck.

    A Final Observation

    The word «expert» invites a picture of a panel of specialists: one for medicine, one for law, one for code. The evidence points elsewhere. The 1991 vowel experiments, Mixtral’s routing analysis and DeepSeek’s push for finer granularity all show experts organizing around whatever division of labor lowers the loss and keeps the load even, which is often syntactic, positional or simply hard to name. A mixture of experts is better understood as a way of renting capacity: the model keeps a very large set of parameters and pays for a small slice of them at a time. The specialists are a metaphor that the training process never agreed to.

    By: Max Johnson B.

  • Diffusion Models: Generating Images by Learning to Remove Noise

    Learning to Undo Damage

    Ruining an image is easy. Add a little Gaussian noise to every pixel, then a little more, and after enough rounds the picture of a cat is indistinguishable from television static. Nobody needs a neural network for that part. The interesting question is whether a network can learn to run the process backwards, one small step at a time, until static turns into a cat that never existed.

    That is the whole idea behind diffusion models. It was first written down by Jascha Sohl-Dickstein and colleagues at ICML 2015, in a paper that borrowed its framing from nonequilibrium thermodynamics. The results were modest and the paper stayed fairly quiet for five years. Then in 2020 Jonathan Ho, Ajay Jain and Pieter Abbeel published «Denoising Diffusion Probabilistic Models» (DDPM) at NeurIPS, reported a state-of-the-art FID of 3.17 on unconditional CIFAR-10, and the field changed direction. Within two years the systems people used to turn text into pictures were almost all diffusion models.

    The Forward Process

    A diffusion model has two halves, and only one of them is learned. The forward process is fixed. Starting from a real image, it adds Gaussian noise over T steps according to a schedule. In the DDPM paper T was 1,000 and the amount of noise added per step grew linearly from 0.0001 to 0.02. By the last step almost nothing of the original image survives, and the result is very close to pure Gaussian noise.

    One property makes training cheap. Because each step adds Gaussian noise, the noisy image at any step t can be written directly in terms of the clean image: a scaled copy of the original plus a scaled sample of noise. You never have to simulate the 999 intermediate steps. To make a training example you pick a random t, draw one noise sample, and mix.

    Predicting the Noise

    The reverse process is where the network lives. In principle it should model the distribution of a slightly cleaner image given a noisier one. Ho and his coauthors showed that, after working through the variational bound, this reduces to something almost embarrassingly simple: show the network a noisy image and the step number t, and ask it to predict the exact noise that was added. The loss is the mean squared error between the predicted noise and the real one.

    They also found that dropping the weighting terms from the full bound gave better-looking samples, even though it gave up some likelihood. The network itself was a U-Net, the encoder and decoder architecture with skip connections that had become standard for segmentation, with the step number fed in as an embedding.

    Generation then means starting from pure noise and applying the network 1,000 times. At each step it estimates the noise, removes a portion of it, and adds back a smaller amount of fresh randomness. The output of one step is the input of the next.

    Score Matching

    A separate line of research reached the same place from another direction. The score of a probability distribution is the gradient of its log density with respect to the data. It is a vector field that points, from any location, toward regions where data is more likely. If you know the score everywhere, you can sample by following it with a bit of added noise, a procedure called Langevin dynamics.

    Aapo Hyvärinen introduced score matching in 2005 as a way to estimate this gradient without knowing the normalizing constant of the density. Pascal Vincent showed in 2011 that a denoising autoencoder trained on noisy data implicitly learns the score. Yang Song and Stefano Ermon built a generative model on this at NeurIPS 2019. Their key observation was that scores are badly estimated in empty regions far from the data, so they trained one network on many noise levels at once and sampled by annealing from large noise to small.

    Predicting the added noise and estimating the score turn out to be the same quantity up to a scaling factor. Song, Sohl-Dickstein, Kingma, Kumar, Ermon and Poole made this explicit at ICLR 2021 by describing both methods as discretizations of a stochastic differential equation that slowly turns data into noise. Reversing that equation requires only the score. The same framework gave a deterministic version, an ordinary differential equation with the same marginal distributions, which allowed exact likelihood computation. The paper reported an FID of 2.20 on CIFAR-10 and the first 1024 by 1024 samples from a score-based model.

    A Thousand Steps Is Too Many

    The obvious weakness was speed. A GAN produces an image in one forward pass. A DDPM needed a thousand. Much of the work since 2020 has gone into cutting that number without retraining from scratch.

    DDIM (Jiaming Song, Chenlin Meng and Stefano Ermon, ICLR 2021) kept the DDPM training objective but defined a non-Markovian reverse process that can skip steps. The authors reported samples of similar quality 10 to 50 times faster in wall-clock time. Viewing sampling as solving an ODE also opened the door to better numerical solvers, and dedicated samplers now get usable images in a few dozen steps or fewer. Distillation goes further: a student network is trained to match two or more steps of a teacher in one. Consistency models (Yang Song, Prafulla Dhariwal, Mark Chen and Ilya Sutskever, ICML 2023) train a network to map any point on a sampling trajectory directly to its endpoint, which makes single-step generation possible.

    Guidance

    An unconditional model produces random samples from whatever it was trained on. To ask for a specific class or a text prompt, the model needs conditioning, and conditioning alone tends to give images that only loosely follow the request.

    Prafulla Dhariwal and Alex Nichol introduced classifier guidance in «Diffusion Models Beat GANs on Image Synthesis» (NeurIPS 2021). A separate classifier, trained on noisy images, supplies a gradient that pushes each denoising step toward the desired class. With it they reached an FID of 2.97 on ImageNet at 128 by 128 and matched BigGAN-deep with as few as 25 forward passes per sample.

    Training a classifier on noisy images is awkward, though. Jonathan Ho and Tim Salimans proposed classifier-free guidance at a NeurIPS 2021 workshop. One network is trained with the condition dropped a small fraction of the time, so it learns both conditional and unconditional predictions. At sampling time the two predictions are combined, and the difference between them is amplified by a guidance weight. Raising the weight makes images follow the prompt more closely at the cost of diversity. Most text-to-image systems use this trick, and the guidance scale is one of the few knobs ordinary users touch.

    Diffusion in a Latent Space

    Running a U-Net a few dozen times over a full-resolution image is expensive, and most of that computation goes into pixel detail the eye barely notices. Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser and Björn Ommer addressed this in «High-Resolution Image Synthesis with Latent Diffusion Models» (CVPR 2022). They first train an autoencoder that compresses images into a smaller latent grid while keeping perceptual quality, then run the diffusion process in that latent space. A decoder turns the final latent back into pixels.

    The paper also added cross-attention layers to the U-Net, so conditioning inputs such as text embeddings or bounding boxes can steer the denoiser at every resolution. This design became Stable Diffusion. Its first versions diffused in a 64 by 64 latent to produce 512 by 512 images and used a frozen CLIP text encoder for the prompt. Because it was released with open weights and ran on consumer graphics cards, it was the version of diffusion most researchers and hobbyists first worked with. Later systems replaced the U-Net with Transformers operating on latent patches, following the Diffusion Transformer of William Peebles and Saining Xie (ICCV 2023), but the latent space idea stayed.

    Case: Training Images That Come Back

    A model that learns the score of its training distribution should, in theory, be able to reproduce training images. Nicholas Carlini and eight coauthors tested this at USENIX Security 2023 in «Extracting Training Data from Diffusion Models.» They generated large numbers of images from Stable Diffusion and Google’s Imagen using captions from the training data and searched for outputs that were near copies of training images. They extracted over a thousand training examples across the models they studied, including photographs of identifiable people and trademarked logos.

    The memorized images were mostly ones that appeared many times in the training set. Deduplicating data reduces the problem but does not remove it. The authors also reported that the diffusion models they tested leaked more training data than the GANs they compared against. For a technique so often described as generating something new, that is an uncomfortable result.

    Closing Thought

    The most unusual thing about diffusion models is how the learned part and the procedure are separated. The network is only ever trained to do one modest thing: look at a noisy input and estimate the noise. Everything else, the number of steps, the solver, the guidance weight, the choice between a random or a deterministic path, is decided after training. DDIM, better ODE solvers and classifier-free guidance all improved results by changing how a network is used rather than what it learned. Most of deep learning puts its effort into the training objective. With diffusion, a large share of the progress came from the sampler instead.

    By: Max Johnson B.

  • CLIP and Contrastive Multimodal Models: Teaching Images and Text to Share One Space

    A Thousand Labels Is a Small Vocabulary

    For most of the history of computer vision, a classifier knew exactly the categories it was trained on and nothing else. A model trained on ImageNet’s 1,000 classes could tell a Siberian husky from an Alaskan malamute, but if you asked it to find «a dog wearing a raincoat» it had no way to even represent the request. Adding a new category meant collecting new labeled images and retraining.

    The internet, meanwhile, is full of images that already come with text: captions, alt attributes, titles, surrounding paragraphs. That text is noisy and inconsistent, but it describes far more than 1,000 concepts. Contrastive multimodal models are built on a simple bet: if a network learns which caption goes with which image across hundreds of millions of examples, it will learn a visual vocabulary as wide as the language people use to describe pictures.

    Two Encoders and a Matching Game

    CLIP (Contrastive Language-Image Pre-training) was published by Alec Radford, Jong Wook Kim and colleagues at OpenAI in 2021 and presented at ICML that year. The architecture has two separate parts. An image encoder (a ResNet or a Vision Transformer) turns a picture into a vector. A text encoder (a Transformer) turns a caption into a vector of the same size. Both vectors are normalized, so comparing them is just a cosine similarity.

    Training uses a batch of N image-caption pairs. The model computes the similarity between every image and every caption, which gives an N by N matrix. The N correct pairs sit on the diagonal; everything else is a mismatch. The loss is a cross-entropy in both directions: each image has to pick its own caption out of the N candidates, and each caption has to pick its own image. A learned temperature parameter scales the similarities before the softmax.

    The batch is where the negatives come from, so batch size matters a lot. CLIP used batches of 32,768 pairs, which means every caption competes against more than 32,000 wrong images at each step. The training set, called WebImageText, held 400 million pairs collected from public sources on the internet.

    Classification Written as a Sentence

    The payoff is zero-shot classification. To classify an image into a set of categories CLIP has never been trained on as labels, you write each category as a sentence («a photo of a cat», «a photo of a truck»), encode all the sentences, and pick the one closest to the image embedding. The class list is just text, so you can change it at inference time.

    The paper reported that its best model, a ViT-L/14 at 336 pixel resolution, reached about 76 percent top-1 accuracy on ImageNet this way, roughly the same as the original ResNet-50 trained on ImageNet’s 1.28 million labeled images. CLIP saw none of those labels. The wording of the prompt turned out to matter: «a photo of a {label}» worked better than the bare class name, and averaging over dozens of templates helped further. People started calling this prompt engineering for vision.

    A second result got less attention at the time but may matter more. On variants of ImageNet with sketches, renditions and adversarially filtered photos, a standard ImageNet model loses much of its accuracy. Zero-shot CLIP lost far less. The authors argued that a supervised model learns shortcuts specific to one dataset, while a model trained on a broad distribution of web images and text has fewer of them to exploit.

    Scale Over Cleanliness

    Within weeks of CLIP, Google described ALIGN (Chao Jia and colleagues, also ICML 2021), which used the same dual-encoder idea with an EfficientNet image encoder and a BERT text encoder. Its dataset was 1.8 billion image and alt-text pairs with only minimal filtering. The message of ALIGN was that you can skip most of the expensive cleaning if you have enough data, because the contrastive objective averages out a lot of the noise.

    Neither OpenAI’s nor Google’s dataset was released. The LAION project filled that gap with LAION-5B (Schuhmann et al., NeurIPS 2022 Datasets and Benchmarks track), 5.85 billion image-text pairs filtered by CLIP similarity itself. The OpenCLIP project trained open models on it, which made it possible to study scaling laws for CLIP-style training in public. Later work such as DataComp (Gadre et al., 2023) turned the question around: hold the model and training recipe fixed, and compete only on how you filter the data. Filtering choices alone moved results by large margins.

    Replacing the Softmax With a Sigmoid

    The softmax in CLIP’s loss has a practical cost. Every image’s probability depends on every caption in the batch, so devices have to share all embeddings to compute it, and the memory grows with the square of the batch. In 2023 Xiaohua Zhai, Basil Mustafa, Alexander Kolesnikov and Lucas Beyer at Google proposed SigLIP, which treats every image-caption pair as an independent binary question: do these two belong together, yes or no? Each cell of the similarity matrix gets its own sigmoid loss.

    That change removes the global normalization. SigLIP trained well with smaller batches than CLIP needed, and it scaled to larger ones too. In one setup that kept a pre-trained image encoder frozen and trained only the text side, the authors reached 84.5 percent zero-shot ImageNet accuracy using four TPUv4 chips for two days. SigLIP encoders have since become a common choice as the vision component of open multimodal language models.

    An Embedding Space Other Systems Reuse

    The shared embedding space ended up being more useful than zero-shot classification. Image search is the direct application: encode a text query, find the nearest image vectors, no tags required. Content moderation and dataset filtering use the same trick, and LAION itself was built by keeping only pairs whose CLIP similarity passed a threshold.

    Generative models borrowed the text side. Stable Diffusion’s first versions conditioned image generation on the output of CLIP’s ViT-L/14 text encoder, and OpenAI’s DALL-E 2 generated images from CLIP image embeddings. Going the other way, LLaVA (Liu et al., 2023) connected a frozen CLIP image encoder to a language model through a small projection layer and trained the result to answer questions about images. Meta’s ImageBind (Girdhar et al., CVPR 2023) pushed the idea further, aligning audio, depth, thermal and motion data to the same space by pairing each one with images, so that modalities never seen together during training could still be compared.

    Case: An Apple Labeled «iPod»

    In March 2021, OpenAI researchers studying CLIP’s internal units found what they called multimodal neurons: single units that responded to a concept whether it appeared as a photo, a drawing or written text. One responded to spiders, to the word «spider» and to Spider-Man. The same property produced a strange weakness. When they stuck a handwritten paper note saying «iPod» on a Granny Smith apple, CLIP classified the photo as an iPod. They called these typographic attacks. Unlike most adversarial examples, they need no gradients and no computer, only a pen.

    The failure follows from the training signal. Web captions often repeat the text that appears inside an image, so reading the text is a reliable shortcut for matching captions. CLIP learned to read because reading helped, and it has no separate notion of «the object» versus «words written near the object.»

    What a Bag of Words Cannot Tell Apart

    Other limits show up in careful benchmarks. Yuksekgonul and colleagues (ICLR 2023) tested whether vision-language models understand word order and relations, for example whether they can distinguish «the horse is eating the grass» from «the grass is eating the horse.» CLIP-style models often could not. Their explanation was that the contrastive task rarely requires order: in a batch of random web pairs, getting the nouns right is almost always enough to find the matching caption, so the model has little reason to learn more. CLIP also struggled with counting objects and, in the original paper, scored poorly on handwritten digits (MNIST) despite its broad training.

    Bias came along with the web data. An audit by Agarwal and colleagues in 2021, using images from the FairFace dataset with extra labels added, found that photos of Black people were classified into non-human categories such as «gorilla» at a rate of about 14 percent, against under 8 percent for every other group. Changing the label set changed the outcome, which is the other side of zero-shot flexibility: whoever writes the class list also shapes the errors.

    Closing Thought

    CLIP’s objective never asks the model to understand an image. It asks only that the right caption score higher than the other captions in the batch. Everything the model learns, from recognizing dog breeds to reading text on an apple to ignoring word order, is whatever happened to be useful for winning that comparison against random internet captions. That makes the choice of negatives, and of data, the real specification of what these models know. A harder batch teaches a finer distinction; a lazier one lets the shortcut stand.

    By: Max Johnson B.

  • CMA-ES: An Evolution Strategy That Learns the Shape of the Problem

    Optimization With Only a Score

    Some optimization problems give you almost nothing to work with. You can hand the problem a vector of numbers and get back a single score, and that is all. There is no gradient, no formula you can differentiate, sometimes not even a guarantee that the same input returns the same score twice. Tuning the gains of a controller in a physics simulator looks like this. So does fitting the parameters of a chemical model, or choosing the learning rate and dropout of a neural network.

    The Covariance Matrix Adaptation Evolution Strategy, almost always shortened to CMA-ES, is one of the most respected tools for this kind of problem when the variables are continuous. Its standard form was published by Nikolaus Hansen and Andreas Ostermeier in 2001, in the journal Evolutionary Computation, under the title «Completely Derandomized Self-Adaptation in Evolution Strategies.» Twenty-five years later it is still a standard first choice, and a standard baseline, for hard black-box problems with a few dozen to a few hundred variables.

    Sampling From a Gaussian

    CMA-ES does not keep a population of individuals the way a genetic algorithm does. It keeps a probability distribution: a multivariate normal with a mean vector m, a global step size σ, and a covariance matrix C. Each generation it draws λ candidate solutions from that distribution, evaluates them, and sorts them from best to worst.

    The new mean is a weighted average of the best μ candidates, usually the top half, with better ones receiving larger weights. So the center of the search moves toward the region where good solutions were just found. That part alone is a fairly ordinary evolution strategy. What makes CMA-ES different is what it does next with the covariance matrix and the step size.

    The default population size is small. Hansen’s tutorial on the method recommends λ = 4 + ⌊3 ln n⌋, where n is the number of variables. For a 100-dimensional problem that gives 17 samples per generation. The suggested defaults for the other internal parameters are also derived from n, which is why practitioners rarely tune them.

    Learning the Shape of the Search

    Picture a long, narrow valley that runs diagonally across the search space. A plain random search with circular steps wastes most of its samples climbing the walls, because almost every direction points uphill except the one along the valley floor. To make progress it would need tiny steps, and tiny steps make the walk along the valley painfully slow.

    The covariance matrix fixes this. After each generation, CMA-ES looks at the steps that led to the selected candidates and nudges C so that those directions become more likely in the future. Over many generations the sampling distribution stretches into an ellipsoid aligned with the valley. The algorithm has, in effect, learned which combinations of variables move together.

    This is called the rank-μ update, because it uses information from all μ selected steps at once. On a convex quadratic function, the learned covariance tends toward a matrix proportional to the inverse of the Hessian. That is the same matrix a Newton or quasi-Newton method tries to approximate with derivatives. CMA-ES gets there using nothing but the ordering of sampled points.

    Evolution Paths

    The second idea in the 2001 paper is called cumulation. Instead of looking only at the current generation, CMA-ES keeps a running, exponentially fading sum of the recent movements of the mean. Hansen and Ostermeier call this the evolution path.

    The path carries information a single generation cannot. If the mean keeps moving in roughly the same direction, the steps add up and the path grows long. If it zigzags back and forth, consecutive steps cancel and the path stays short. The rank-one update adds the outer product of this path to the covariance matrix, which strengthens directions of consistent progress.

    The two updates complement each other. The rank-μ update is efficient with large populations, while the rank-one update with cumulation works well with the small default population. The modern algorithm uses both.

    Step-Size Control

    Shape is only half of the problem. The algorithm also has to decide how far to step overall, and a covariance matrix learned from past steps cannot answer that by itself, because it adapts too slowly.

    CMA-ES handles this with a second evolution path, built in a coordinate system where the current covariance has been factored out. The rule then compares the length of this path with the length expected under pure random selection. If the path is longer than expected, successive steps are pointing the same way and the step size is too small, so σ grows. If it is shorter, steps are cancelling each other and σ shrinks. The paper calls this cumulative step-size adaptation.

    The rule is short. It lets the algorithm take large steps far from the optimum and converge quickly once it gets close, without a manually designed schedule like the cooling schedule in simulated annealing.

    Invariance

    Hansen’s tutorial on the method names invariance as one of the governing principles of its design. CMA-ES only uses the ranking of candidates, never their raw scores, so its behavior does not change if the objective function is replaced by any strictly increasing transformation of itself. Squaring a positive objective or taking its logarithm makes no difference.

    It is also invariant, given a matching starting point and covariance, to rotations, translations and general linear transformations of the search space. A badly scaled, rotated problem is, for CMA-ES, the same problem as a well-scaled one once the covariance has adapted. This is why the 2001 paper reported speed-ups of several orders of magnitude on badly scaled, non-separable functions, and a factor of three to ten on moderately mis-scaled ones.

    There is a theoretical account of why this works. The Information-Geometric Optimization framework, published by Yann Ollivier and coauthors in the Journal of Machine Learning Research in 2017, shows that the rank-μ update of CMA-ES can be read as a natural gradient step on the parameters of the search distribution. The algorithm came first and the theory came later, which is a common order of events in this field.

    Restarts and Larger Populations

    With its default settings, CMA-ES behaves like a fast local search. On a function with many local optima it will often converge cleanly to the wrong one. The standard fix is to restart.

    Anne Auger and Nikolaus Hansen proposed IPOP-CMA-ES at the 2005 IEEE Congress on Evolutionary Computation. Each time the run stalls, it restarts with the population size doubled. Larger populations smooth over small bumps in the landscape and make the search more global. On the 25 test functions of the CEC 2005 special session on real-parameter optimization, IPOP-CMA-ES ranked first overall. A later variant, BIPOP-CMA-ES, alternates between large and small populations, and the two were among the best performers in the Black-Box Optimization Benchmarking workshops of 2009 and 2010.

    Case: An 867-Parameter Driver

    One well-known use in machine learning is the 2018 World Models paper by David Ha and Jürgen Schmidhuber. They trained a variational autoencoder to compress game frames and a recurrent network to predict what comes next. The part that actually chose actions was a small linear controller with 867 parameters, and they did not train it with gradients. They evolved it with CMA-ES, using a population of 64, on the CarRacing task. The agent reached an average score of 906 ± 21, which the authors reported as the first result to solve that environment.

    The choice made sense. A reinforcement learning reward is noisy and delayed, and 867 parameters is well within the range where CMA-ES is comfortable. Every candidate can also be evaluated on a separate CPU core, so the method parallelizes almost perfectly.

    Hyperparameter tuning is another natural fit. In 2016 Ilya Loshchilov and Frank Hutter compared CMA-ES with Bayesian optimization methods for tuning a convolutional network on MNIST, running evaluations on 30 GPUs in parallel, and argued that CMA-ES is a competitive option when many evaluations can run at once. Today the method is easy to try: the pycma library is maintained by Hansen, and the Optuna framework includes a CMA-ES sampler.

    The Quadratic Cost

    The weakness is the covariance matrix itself. For n variables it has about n²/2 free entries, and the standard algorithm needs memory and time per sample that grow quadratically with n. It also needs on the order of n² evaluations to learn a full matrix. With a few hundred variables this is fine. With tens of thousands it becomes impractical, which is why nobody trains the weights of a large neural network with standard CMA-ES.

    Several variants trade expressiveness for scale. In 2008 Raymond Ros and Nikolaus Hansen proposed sep-CMA-ES, which restricts C to a diagonal matrix and brings the cost down to linear. It loses the ability to learn correlations between variables, but in their experiments it needed fewer evaluations than full CMA-ES on several problems above a hundred dimensions, including the non-separable Rosenbrock function. Limited-memory versions such as LM-CMA, inspired by L-BFGS, keep a few vectors instead of a full matrix.

    Closing Thought

    What I find most interesting about CMA-ES is how little it assumes. It never reads the value of the objective, only the order of the candidates. And yet, from that ordering alone, it reconstructs something close to the curvature of the problem, the same information a second-order method gets from derivatives. A lot of «nature-inspired» optimizers are described by their metaphor. CMA-ES is better described by what it estimates, and that is probably why it has outlasted so many of them.

    By: Max Johnson B.