Categoría: Uncategorized

  • Genetic Programming: Evolving Programs Instead of Numbers

    Searching for Programs Instead of Parameters

    Most optimization algorithms search for numbers. A genetic algorithm evolves a string of bits or a vector of real values, and a neural network adjusts millions of weights inside an architecture someone else designed. In both cases the shape of the solution is fixed ahead of time. The algorithm only fills in the blanks.

    Genetic programming asks for something more ambitious. The thing being evolved is a program: a formula, a decision procedure, a circuit, a set of instructions. The size and structure of the solution are not decided in advance. They emerge from the search.

    The idea has an early version in Nichael Cramer’s 1985 paper at the first International Conference on Genetic Algorithms, which represented simple sequential programs in a form that could be mutated and recombined. The field took its name and its standard form from John Koza, whose 1992 book Genetic Programming: On the Programming of Computers by Means of Natural Selection (MIT Press) set out the tree-based approach that most people still mean when they say GP.

    Programs as Trees

    In Koza’s formulation, a program is a tree. Internal nodes are functions such as addition, multiplication, sine or an if-then-else. Leaves are terminals: input variables and constants. The expression (x + 3) * sin(y) becomes a tree with a multiplication at the root, an addition on one side and a sine on the other.

    The designer chooses two sets before the run starts. The function set lists the operations the program may use, and the terminal set lists the inputs it may read. This choice matters a great deal. Give the search only arithmetic and it can never discover a periodic signal; give it fifty operators and the space becomes so large that progress slows to a crawl.

    Every function must also accept any value another node might produce. Koza called this closure. Division is the usual example: a random tree will sooner or later divide by zero, so GP systems use a «protected» division that returns a fixed value in that case (Koza used 1) instead of crashing.

    The first generation is random. A common recipe from Koza’s book is ramped half-and-half, which builds some trees to full depth and others with irregular shapes, across a range of depths, so the starting population contains small, large, bushy and thin programs.

    Crossover and Mutation on Trees

    Each program is run on a set of test cases and scored. Better programs are more likely to be selected as parents, usually through tournament selection, where a few individuals are drawn at random and the best of them wins.

    Subtree crossover is the signature operator. Pick a random node in each parent, cut there, and swap the two branches. The children are valid programs by construction, because any subtree can replace any other once closure holds. Mutation does the same thing with a single parent, replacing a random branch with a freshly generated one.

    Later research changed the representation without changing the principle. Cartesian GP, introduced by Julian Miller and Peter Thomson in 2000, encodes programs as graphs on a grid, which lets one node feed several others. Lee Spector’s PushGP uses a stack-based language where programs can manipulate their own code. Selection also got sharper: lexicase selection, studied by Thomas Helmuth, Lee Spector and James Matheson in a 2015 IEEE Transactions on Evolutionary Computation paper, picks parents by filtering on test cases one at a time in random order instead of averaging the errors, which keeps specialists alive that an averaged score would throw away.

    Bloat

    Run GP long enough and the programs grow. Trees get deeper and wider while fitness barely improves. This is called bloat, and it was noticed in the earliest runs.

    Much of the extra material is code that does nothing, such as adding x and then subtracting it, or a branch that can never execute. Early explanations blamed these «introns,» arguing that they protect useful code from destructive crossover. Sean Luke later showed that the causation probably runs the other way: inactive code accumulates because trees grow, not the reverse. William Langdon and Riccardo Poli proposed an explanation that does not depend on introns at all. For any program, there are far more large programs with the same behavior than small ones, so a search that drifts among equally fit solutions will tend to drift toward larger ones.

    Bloat is not a cosmetic problem. Large programs are slow to evaluate, hard to read, and more likely to overfit. Practitioners control it with depth limits, size penalties added to fitness, or multi-objective selection that treats size as a second objective. Luke and Liviu Panait compared several of these methods in a 2006 paper in Evolutionary Computation, and the simple depth limit Koza used in 1992 was competitive with the more elaborate alternatives.

    Symbolic Regression

    The most common use of GP today is symbolic regression: given data, find a formula that fits it. Unlike linear regression, the form of the formula is not given. Unlike a neural network, the answer is an equation a person can read.

    The best-known demonstration is a 2009 Science paper by Michael Schmidt and Hod Lipson at Cornell, «Distilling Free-Form Natural Laws from Experimental Data.» They recorded the motion of physical systems, from simple harmonic oscillators to a chaotic double pendulum, and used symbolic regression to search for quantities that stayed constant over time. The system recovered Hamiltonians, Lagrangians and conservation laws without being told what physics to look for. The method became a commercial tool called Eureqa.

    GP has also held up under systematic comparison. In 2021, William La Cava and colleagues published SRBench at NeurIPS, a benchmark of 14 symbolic regression methods on 252 datasets, including real-world regression tasks and physics equations with known answers. On the real-world data, Operon, a GP system that tunes constants with the Levenberg-Marquardt algorithm, produced the most accurate models, and four of the top five methods were GP-based. On the noiseless physics problems, AI Feynman, which is not a GP method, recovered the most exact equations, though its advantage shrank as noise was added. No single method won everywhere.

    Case: Patents, Antennas and Lenses

    Koza spent years trying to show that GP could produce results a human expert would respect. He set criteria for «human-competitive» results, one being that the result duplicates or improves on an invention that had been patented. A 2010 survey in Genetic Programming and Evolvable Machines counted at least 36 such results, including 15 that duplicated the function of a patented 20th-century invention, 6 that did the same for 21st-century patents, and 2 that were patentable new inventions. His group rediscovered six patented optical lens systems (GECCO 2005), and a patent for improved general-purpose controllers, filed with GP-generated designs, was issued in 2005 as U.S. Patent 6,847,851.

    A different group built a result that flew. For NASA’s Space Technology 5 mission, Jason Lohn, Gregory Hornby and Derek Linden evolved X-band antennas under tight requirements on beam width and bandwidth. They ran two algorithms, one of which used a GP-style tree representation that allowed the antenna’s arms to branch. The evolved designs outperformed the one produced by the mission’s antenna contractor, and an evolved antenna went to space on the ST5 spacecraft in 2006. It looks like a bent paperclip, and it is not a shape anyone would have sketched by hand.

    Case: Repairing Bugs With GenProg

    In 2012, Claire Le Goues, Michael Dewey-Vogt, Stephanie Forrest and Westley Weimer presented a study at ICSE with a memorable title: «A Systematic Study of Automated Program Repair: Fixing 55 out of 105 Bugs for $8 Each.» Their system, GenProg, takes a buggy C program and a test suite with at least one failing test. It evolves patches by copying, deleting and moving statements that already exist elsewhere in the program, and keeps a patch if all the tests pass.

    The paper helped start the field of automated program repair. It also led to one of the most useful critiques in the GP literature. In 2015, Zichao Qi, Fan Long, Sara Achour and Martin Rinard reanalyzed the patches at ISSTA. Because of errors in the test scripts, most reported patches did not pass the full test suite. Only 18 were plausible, and only 2 were correct. Many of the rest simply deleted the functionality that was failing. The authors built a system called Kali that only deletes code, and it found plausible patches for 27 defects, more than GenProg.

    Language Models as Mutation Operators

    Random subtree swaps are a crude way to edit code. A recent line of work replaces them with a large language model. In FunSearch, published in Nature in 2023 by Bernardino Romera-Paredes and colleagues at Google DeepMind, a population of Python programs is kept and scored by an automatic evaluator, and a pretrained language model writes new candidates by modifying the best ones.

    The structure is recognizably evolutionary: a population, variation, selection, an islands model to keep diversity. Applied to the cap set problem in combinatorics, FunSearch found a cap set of size 512 in eight dimensions, where the largest known had been 496, and it improved the asymptotic lower bound. It also found heuristics for online bin packing that beat the standard first-fit and best-fit rules. As in classic GP, the output is a program, short enough for a mathematician to read and analyze.

    Closing Thought

    Every genetic programming system depends on a fitness function, and in GP the fitness function is the specification. The search has no idea what the programmer wanted. It only knows which tests passed. GenProg’s deleted features, the bloated trees full of dead code, and the protected division that quietly returns 1 are all the same lesson: evolution finds whatever satisfies the test, including answers nobody intended. That is why FunSearch paired its language model with a strict evaluator, and why the hardest part of using GP is still writing a test that says exactly what you mean.

    By: Max Johnson B.

  • Simulated Annealing and Tabu Search: Two Ways to Climb Out of a Local Optimum

    Stuck at the Bottom of the Nearest Valley

    The simplest way to optimize something is to start with a solution, look at small changes to it, and keep any change that makes things better. This is local search, or hill climbing if you are maximizing. For a traveling salesman tour, a small change might be reversing a segment of the route. You repeat until no small change helps.

    The problem is where this process stops. It stops at a local optimum, a solution that is better than all of its neighbors but possibly much worse than the best solution overall. On a smooth bowl-shaped landscape that is fine. On the rugged landscapes of real combinatorial problems, with millions of small valleys, a greedy search falls into the first one it finds and never leaves.

    Simulated annealing and tabu search both start from this same local search loop. They differ in how they allow it to escape. Annealing escapes by accepting bad moves at random, with a probability that shrinks over time. Tabu search escapes by remembering where it has been and refusing to go back.

    Annealing in Metals and in Code

    Annealing is an old metallurgical process. A metal is heated and then cooled slowly, which gives its atoms time to settle into an ordered, low-energy crystal structure. Cool it too fast and the atoms freeze in a disordered state full of defects.

    In 1953, Nicholas Metropolis and colleagues published a Monte Carlo method for simulating a physical system at a fixed temperature. A random change to the system is proposed. If it lowers the energy, it is accepted. If it raises the energy by some amount Δ, it is accepted with probability exp(−Δ/T), where T is the temperature. At high temperature almost everything is accepted; at low temperature, uphill moves become rare.

    Scott Kirkpatrick, C. Daniel Gelatt and Mario Vecchi, working at IBM, turned this into an optimization method in a 1983 paper in Science titled «Optimization by Simulated Annealing.» Their idea was to treat the cost of a solution as energy and to lower T gradually during the search. Early on, the algorithm wanders across the landscape almost freely. Later, it behaves more and more like plain hill climbing. Vladimír Černý reached the same idea independently and published it in 1985 in the Journal of Optimization Theory and Applications, applied to the traveling salesman problem.

    The appeal is that the algorithm needs only a cost function and a way to generate neighbors. The same twenty lines of code work on permutations, graphs and bit strings.

    The Cooling Schedule

    Most of the practical difficulty of simulated annealing is one choice: how fast to lower the temperature. The common answer is geometric cooling, where T is multiplied by a constant such as 0.95 after a fixed number of moves. You also need a starting temperature high enough that most uphill moves are accepted at first, and a rule for when to stop.

    There is a theory behind this, and it is unusually clean. Stuart and Donald Geman showed in 1984 that if the temperature falls no faster than a constant divided by the logarithm of the iteration count, the search converges to a global optimum. Bruce Hajek sharpened this in 1988 with a necessary and sufficient condition: the constant must be at least the depth of the deepest local minimum that is not global, meaning the largest uphill climb needed to escape a trap.

    The catch is that logarithmic cooling is extremely slow. To halve the temperature you must square the number of iterations. For a realistic problem, the guaranteed schedule takes longer than exhaustive search would. So practitioners use fast schedules that carry no guarantee, and they tune them by experiment. The convergence theorem tells you the method is not arbitrary, but it does not tell you how to run it.

    Case: Placing Circuits on a Chip

    The first serious application was chip design. Placing thousands of circuit components on a chip so that the wires between them are short is a huge combinatorial problem. Their Science paper reported results on partitioning, placement and wiring of electronic systems, along with traveling salesman instances of several thousand cities.

    Carl Sechen and Alberto Sangiovanni-Vincentelli followed with TimberWolf, published in the IEEE Journal of Solid-State Circuits in 1985. It used annealing for standard cell, macro cell and gate array placement, plus global routing. On industrial circuits, they reported area savings of 15 to 62 percent over the layout programs in use at the time.

    Not every evaluation was so favorable. David Johnson, Cecilia Aragon, Lyle McGeoch and Catherine Schevon ran a long experimental study published in Operations Research in 1989. On graph partitioning, annealing beat the classic Kernighan-Lin heuristic on large sparse random graphs, but on graphs with geometric structure Kernighan-Lin won by a substantial margin. The authors described annealing’s success as mixed. That conclusion has held up: annealing is a dependable general method, and a good problem-specific heuristic often beats it.

    Tabu Search and Short-Term Memory

    Fred Glover introduced the term tabu search in a 1986 paper in Computers and Operations Research, «Future Paths for Integer Programming and Links to Artificial Intelligence,» and laid out its principles in a two-part article in the ORSA Journal on Computing starting in 1989. He described it as a metaheuristic superimposed on another heuristic, one that gets past local optimality by forbidding certain moves.

    The mechanism works like this. At each step, tabu search examines the neighborhood and moves to the best neighbor that is not forbidden, even if that neighbor is worse than the current solution. This alone would make the search cycle forever, stepping out of a valley and straight back in. To prevent that, it keeps a tabu list of recent moves, or attributes of recent moves, and forbids reversing them for a certain number of iterations, called the tabu tenure.

    If the search just swapped jobs A and B, swapping them back is tabu for, say, the next ten iterations. The search is forced to keep moving away from the local optimum it just left. What gets stored is usually an attribute, not a full solution, because attributes are cheap to compare.

    This basic version needs no randomness. It always takes the best allowed move, while annealing samples one random neighbor at a time.

    Aspiration, Intensification and Diversification

    Forbidding moves by attribute has a side effect. Sometimes a tabu move would lead to a solution better than anything found so far, and the tabu list blocks it only because of a coincidence of attributes. Aspiration criteria fix this. The most common one says a tabu move is allowed if it produces a new best solution.

    Glover also described longer-term memory. Intensification strategies return to regions where good solutions were found and search them more carefully, for example by fixing features that appear in most of the elite solutions. Diversification strategies push the search toward regions it has rarely visited, often by penalizing moves that have been used frequently. A frequency count per attribute is enough for both.

    So tabu search is closer to a framework than a single algorithm. A competitive implementation usually combines tabu lists, aspiration, frequency memory and restarts from elite solutions, tuned to the problem.

    Case: Job Shops and Quadratic Assignment

    Two results show how much a well-designed tabu search can do. Éric Taillard published Robust Tabu Search for the quadratic assignment problem in Parallel Computing in 1991. Instead of a fixed tabu tenure, it draws the tenure at random from a range, which removes the need to tune one exact value and makes cycling less likely. Robust Tabu Search became a standard reference method for the quadratic assignment problem, and later algorithms often use it as their local improvement step.

    Eugeniusz Nowicki and Czesław Smutnicki published «A Fast Taboo Search Algorithm for the Job Shop Problem» in Management Science in 1996. Their key contribution was a small, carefully chosen neighborhood: only swaps of adjacent operations on the critical path of the schedule, which are the only swaps that can shorten the total completion time. With a tiny neighborhood, each step is fast, and tabu memory keeps the search from circling. Their algorithm and its successor, i-TSAB, were for a long time the state of the art for minimizing makespan on standard job shop benchmarks.

    In both cases, most of the strength came from the problem structure. The tabu mechanism let the search exploit it without getting stuck.

    Randomness Versus Memory

    The two methods make an opposite bet. Simulated annealing assumes that random uphill moves, accepted less and less often, will shake the search loose from traps. Tabu search assumes that remembering recent history is enough to avoid revisiting the same traps, and it uses that memory to drive the search deliberately.

    In practice, annealing is easier to implement and needs only a cooling schedule. It also works well when neighborhoods are huge and only a random sample of moves can be evaluated. Tabu search evaluates the whole neighborhood, or a large part of it, at every step, so it fits problems where neighborhoods are small or can be scored incrementally.

    The two are often combined. Annealing can use a short tabu list to avoid immediate reversals, and tabu search can add random tenure or restarts. Both also serve as the local improvement step inside genetic algorithms, where the population explores broadly and the single-solution method refines the best individuals.

    A Final Observation

    The convergence theorem for simulated annealing is one of the cleanest results in the field, and almost nobody runs the algorithm the way the theorem requires. The useful version is the one that throws away its own guarantee. Tabu search never had a guarantee, and it became one of the strongest tools for scheduling anyway. For hard combinatorial problems, the better question to ask about a method is not whether it will find the optimum but how it decides to accept a worse solution. A search that never takes a bad step stops in the first valley. Which bad steps it takes, and why, decides most of what it can find.

    By: Max Johnson B.

  • Knowledge Distillation and Pruning: Getting a Small Model to Do a Large Model’s Job

    Models Larger Than Their Task Requires

    The most accurate neural networks are usually the largest ones, and large models are expensive to run. They need memory that a phone or a microcontroller does not have, they answer slowly, and at the scale of millions of requests per day, every extra millisecond and watt adds to the bill.

    Researchers noticed early that trained networks are heavily redundant. Much of what makes a network large is needed to train it well, not to represent what it learned. That observation led to a family of techniques, grouped under the name model compression, that start from a large trained model and produce a smaller one with nearly the same accuracy. The three main ones are knowledge distillation, pruning and quantization. This post focuses on the first two.

    Teachers and Students

    The core idea of distillation appeared in 2006, when Cristian Bucilă, Rich Caruana and Alexandru Niculescu-Mizil published a paper called «Model Compression.» They had large ensembles of models that were accurate but slow, and they showed that a single small neural network could be trained to imitate the ensemble’s predictions and keep most of its accuracy.

    Geoffrey Hinton, Oriol Vinyals and Jeff Dean gave the method its current form and name in «Distilling the Knowledge in a Neural Network» (2015). A large, already trained model is the teacher, and a smaller model is the student. The student is trained to reproduce the teacher’s outputs, not only the correct labels from the dataset.

    Soft Targets and Temperature

    Imitating a teacher works better than learning from labels alone because the teacher’s output contains more information than the label does. A label says an image is a dog and nothing else. A trained classifier’s output might say 90% dog, 9% wolf, 0.9% cat, and almost zero for truck. Those small probabilities encode which classes look alike, something the label alone never tells the student. Hinton called this «dark knowledge.»

    In a well-trained network, though, the wrong-class probabilities are often so tiny that they barely affect the loss. The fix is a temperature parameter T in the softmax. Dividing the logits by a temperature above 1 flattens the distribution, so the small probabilities become large enough to matter. The student is trained with the same temperature to match these softened outputs, usually alongside the ordinary loss on the true labels, with a weight balancing the two. At inference the temperature goes back to 1.

    Distilling Internal Representations

    Matching only the final outputs gives the student a limited signal. FitNets, from Adriana Romero and colleagues (ICLR 2015), added «hints»: the student is also trained to reproduce the teacher’s activations at an intermediate layer, through a small adapter that accounts for the difference in size. This made it possible to train students that were thinner and deeper than the teacher.

    Later methods transfer other internal quantities, such as attention maps or the relationships between examples in a batch. In Transformers, it is common to match hidden states and attention matrices layer by layer, as TinyBERT (Jiao and colleagues, 2020) does.

    DistilBERT

    The best-known example in language processing is DistilBERT, published in 2019 by Victor Sanh, Lysandre Debut, Julien Chaumond and Thomas Wolf at Hugging Face. The student has the same architecture as BERT-base with half the layers, 6 in place of 12, and was initialized by taking one layer out of every two from the teacher. It was trained with a combination of three losses: the usual masked language modeling loss, a distillation loss on the teacher’s softened output distribution, and a cosine loss that aligns the direction of the student’s hidden states with the teacher’s.

    The paper reports a model 40% smaller and 60% faster than BERT that retains 97% of its language understanding performance as measured on the GLUE benchmark. DistilBERT became one of the most downloaded models on the Hugging Face Hub, largely because it could run on CPUs at reasonable speed.

    Pruning

    Pruning removes parts of a trained network. The idea dates back to 1989, when Yann LeCun, John Denker and Sara Solla published «Optimal Brain Damage,» which used second-derivative information to estimate which weights could be deleted with the least effect on the error.

    The modern version is simpler. In 2015, Song Han and colleagues showed that removing the weights with the smallest absolute values, then retraining the remaining ones to recover accuracy, and repeating the cycle, could remove most of the connections in networks like AlexNet and VGG-16 without loss of accuracy. Their follow-up, «Deep Compression,» which won a best paper award at ICLR 2016, chained pruning with weight quantization and Huffman coding. It reduced the storage of AlexNet by 35 times, from 240 MB to 6.9 MB, and of VGG-16 by 49 times, from 552 MB to 11.3 MB, with no loss of accuracy.

    Unstructured and Structured Pruning

    There is an important practical distinction. Unstructured pruning deletes individual weights anywhere in the network. It reaches very high sparsity, but the result is a matrix of the same shape with many zeros in it, and ordinary hardware does not run a sparse matrix any faster unless the software and chips are built for it. The file gets smaller, and the speed often does not change.

    Structured pruning removes whole units: neurons, convolutional filters, attention heads or entire layers. The resulting network is smaller in the ordinary sense and runs faster on any hardware. The cost is that accuracy drops sooner, because removing a whole filter is a much coarser operation than removing scattered weights. Paul Michel and colleagues showed in 2019 that many attention heads in Transformers can be removed at test time with little effect, which made head pruning a common technique for language models.

    The Lottery Ticket Hypothesis

    If a pruned network works well, a natural question is whether the small network could have been trained directly from the start. For a long time the answer seemed to be no: sparse networks trained from scratch did worse than pruned ones.

    Jonathan Frankle and Michael Carbin proposed an explanation in «The Lottery Ticket Hypothesis,» which received a best paper award at ICLR 2019. They trained a network, pruned the smallest weights, and then reset the surviving weights to the exact values they had at initialization. Trained again from there, these sparse subnetworks, often 10 to 20% of the original size on MNIST and CIFAR-10, matched the accuracy of the full network. With a fresh random initialization, the same sparse structure did not.

    Their hypothesis is that a large random network contains small subnetworks whose initial weights happen to be well suited for training, the winning tickets, and that part of the benefit of a large network is that it holds many such candidates. On larger networks, later work found that the weights need to be rewound to a point early in training instead of to the very beginning. Finding the tickets still requires training the big network first, so the result is more important for understanding why over-parameterized networks train well than as a practical shortcut.

    Combining the Techniques

    Distillation, pruning and quantization act on different things, so they are usually combined. Distillation produces a smaller architecture. Pruning removes what is left of the redundancy. Quantization then stores each remaining weight with fewer bits, for example 8-bit integers in place of 32-bit floating-point numbers. A typical pipeline for deployment on a device applies all three, checking accuracy after each step.

    Distillation has also taken on a second role with large language models. A large model can generate answers, explanations or labels for a big set of inputs, and a much smaller model is then trained on that synthetic data. The student never sees the teacher’s internal probabilities, only its text, but the principle is the one from 2006: use an expensive model to teach a cheap one.

    Limits

    Compression always costs some accuracy. Average accuracy on a benchmark can stay almost unchanged while performance on rare cases gets worse. Sara Hooker and colleagues showed in 2019 that pruning affects a small subset of examples disproportionately, often atypical or underrepresented ones, even when the top-line accuracy barely moves. A student can also inherit its teacher’s errors and biases, since it is trained to copy them. And when the student is far smaller than the teacher, the gap can be too wide to bridge in one step, which is why some methods distill through an intermediate-size model first.

    Reflection

    Compression works because training a model and running it need different things. Training benefits from a large network, which has many possible paths to a good solution. Once the solution is found, most of that capacity is no longer needed. This is why the common practice is to train a large model first and then shrink it, and not to design a small model and train it directly. The lottery ticket experiments are the clearest evidence for this: the small network that works was inside the large one from the start, but it could only be identified after training the large one.

    By: Max Johnson B.

  • Retrieval-Augmented Generation: Giving a Language Model Documents to Read Before It Answers

    What a Language Model Does Not Know

    A large language model stores what it knows in its weights, and those weights stop changing when training ends. That has three consequences. The model knows nothing about events after its training cutoff. It knows nothing about private information, such as a company’s internal manuals or a hospital’s protocols. And when asked about something it has little information on, it often produces a fluent, confident and wrong answer, the behavior usually called hallucination.

    Retraining a model every time a document changes is too expensive to be practical. Retrieval-augmented generation (RAG) takes a different route. When a question arrives, the system searches a collection of documents for relevant passages, places them in the prompt together with the question, and asks the model to answer using that material. The knowledge sits in a database that can be updated at any time, and the model’s job shifts from recalling facts to reading and summarizing them.

    The 2020 Paper

    The name comes from «Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks,» by Patrick Lewis and colleagues at Facebook AI Research, University College London and New York University, presented at NeurIPS 2020. Their system combined two trained components: a retriever based on Dense Passage Retrieval (DPR), which searched an index of about 21 million Wikipedia passages, and BART, a sequence-to-sequence model that generated the answer conditioned on the retrieved passages. The two were fine-tuned together.

    The paper described the combination as parametric memory (the weights of the generator) plus non-parametric memory (the document index). It set state-of-the-art results on several open-domain question answering benchmarks and generated text that was more specific and factual than BART alone. It also pointed out a property that later became the main selling point: the index can be swapped to update what the system knows without retraining anything.

    Modern RAG systems rarely train the retriever and generator jointly. They connect an off-the-shelf embedding model, a vector database and a general-purpose language model. The principle is the same.

    Turning Documents Into a Searchable Index

    Before any question can be answered, the documents have to be prepared. They are first split into chunks, pieces of a few hundred words each. Chunking matters more than it seems. Chunks that are too large dilute the relevant sentence among unrelated text. Chunks that are too small lose the context needed to understand them (a paragraph that says «this method» without saying which one).

    Each chunk is then passed through an embedding model, which turns it into a vector of a few hundred to a few thousand numbers. The model is trained so that texts with similar meaning get nearby vectors. The vectors are stored in a vector database along with the original text. This step is done once, and repeated only for documents that change.

    Sparse and Dense Retrieval

    There are two families of search methods. Sparse retrieval matches words. Its standard algorithm is BM25, developed by Stephen Robertson and colleagues in the 1990s, which scores a document by how often the query’s terms appear in it, weighted by how rare each term is across the collection. It is fast, needs no training, and is very good with exact terms like product codes, names and error messages.

    Dense retrieval compares embeddings. Karpukhin and colleagues introduced DPR in 2020, training two BERT encoders, one for questions and one for passages, so that a question and the passage that answers it end up close together. On open-domain question answering datasets, DPR beat a strong BM25 system by 9 to 19 percentage points in top-20 retrieval accuracy. Dense retrieval can match a question to a passage that shares no words with it, which sparse methods cannot do.

    Each approach fails where the other works, so production systems often run both and merge the results, a setup called hybrid search. Searching millions of vectors exactly would be slow, so vector databases use approximate nearest neighbor indexes such as HNSW (Malkov and Yashunin), which trade a small loss in accuracy for a large gain in speed.

    Reranking and Building the Prompt

    The first retrieval step is tuned for speed and returns maybe 50 to 100 candidates. A second model, a reranker, then scores each candidate against the question more carefully. Rerankers are usually cross-encoders: they read the question and the passage together, which is more accurate than comparing two separately computed vectors but too slow to run on the whole collection.

    The top few passages are inserted into the prompt with an instruction along the lines of «answer using only the following sources and cite them.» The order matters. In «Lost in the Middle» (2023), Nelson Liu and colleagues showed that language models use information at the beginning and end of a long context much better than information in the middle, with accuracy dropping noticeably when the relevant passage was placed in the center.

    Ways RAG Fails

    RAG reduces hallucinations, but it does not eliminate them. Failures happen at each stage. The retriever can miss the relevant passage, and then the model answers from memory or invents something. The retriever can return a passage that looks related but is about something else, and the model follows it. The correct passage can be retrieved and then misread or ignored. And some questions need information scattered across many documents («what are the main themes in these 500 reports?»), which retrieving five chunks will not answer.

    A study from Stanford’s RegLab, by Varun Magesh and colleagues, tested commercial legal research tools built on RAG, whose vendors had advertised them as avoiding hallucinations. On about 200 legal queries scored by hand, the tools still gave incorrect or misgrounded answers a large share of the time: about 17% for Lexis+ AI and about 33% for Westlaw AI-Assisted Research. Those numbers were better than GPT-4 without retrieval, at 43%, but far from zero. In many cases the tools cited real documents that did not support the claim attributed to them.

    Refinements

    Much recent work targets those failure points. Query rewriting has a language model reformulate the user’s question, or break it into sub-questions, before searching. Self-RAG, from Akari Asai and colleagues (ICLR 2024), trains the model to decide when retrieval is needed and to critique whether the retrieved passages are relevant and whether its own answer is supported by them. GraphRAG, from Microsoft Research in 2024, uses a language model to extract entities and relationships from the documents into a knowledge graph and writes summaries of clusters in that graph, which helps with questions about the collection as a whole.

    Agentic approaches let the model run several searches in sequence, read the results, and decide what to look for next, closer to how a person researches a topic.

    RAG, Fine-Tuning and Long Context

    RAG is not the only way to adapt a model to new knowledge. Fine-tuning changes the weights, which works well for teaching a style, a format or a skill, but poorly for facts that change often, and it gives no source to cite. Context windows have grown to hundreds of thousands of tokens, so small collections can be placed directly in the prompt, at a higher cost per query and with the middle-of-context problem described above. For large or frequently updated collections, and wherever answers need to point to their sources, retrieval is still the practical option. Many systems combine the three.

    Evaluation

    A RAG system has to be evaluated in two parts. Retrieval is measured with metrics like recall at k: of the questions in a test set, how often is the passage with the answer among the top k results. Generation is measured on faithfulness (is every claim in the answer supported by the retrieved passages) and on whether the answer addresses the question. Looking only at the final answer hides which part is failing, and a wrong answer caused by bad retrieval needs a different fix than one caused by the model misreading a good passage.

    A Final Observation

    RAG changes where the difficulty of the problem is. The language model no longer has to know the answer, but the system has to find the right paragraph among millions, and most of the errors come from that search step. Search has been studied for decades in information retrieval, long before language models existed. A team building a RAG system will usually get more out of improving chunking, indexing and ranking than out of switching to a larger model.

    By: Max Johnson B.

  • Vision Transformers: Reading an Image as a Sequence of Patches

    An Architecture Borrowed From Language

    For most of the 2010s, computer vision meant convolutional neural networks. Convolutions build in two assumptions about images: nearby pixels are related, and a pattern means the same thing wherever it appears. Those assumptions are correct often enough that CNNs learned well from modest amounts of data, and every major vision benchmark was led by one.

    The Transformer came from machine translation and has neither assumption. It treats its input as a set of tokens and lets every token look at every other token through self-attention. In October 2020, a team at Google Research led by Alexey Dosovitskiy posted a paper titled «An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale,» later published at ICLR 2021. It asked what would happen if a standard Transformer were applied to images with as few changes as possible. The model was called the Vision Transformer, or ViT.

    From Pixels to Tokens

    A Transformer needs a sequence, and an image is a grid. Treating every pixel as a token is not practical, because self-attention compares every token with every other one, so its cost grows with the square of the sequence length. A 224 by 224 image has more than 50,000 pixels.

    ViT cuts the image into square patches instead, typically 16 by 16 pixels. A 224 by 224 image gives 196 patches. Each patch is flattened into a vector and passed through one linear layer to produce a patch embedding. These 196 vectors are the «words» of the title.

    Two more pieces are added. A sequence of patches has no inherent order, so a learned position embedding is added to each patch to tell the model where it came from. And an extra learnable token, the class token, is placed at the start of the sequence. After the Transformer layers, the output at that position is used as the representation of the whole image and fed to a classifier.

    Everything after that is a standard Transformer encoder: alternating layers of multi-head self-attention and small feed-forward networks, with residual connections and layer normalization. Nothing in it is specific to images.

    What Attention Sees in an Image

    In a CNN, a neuron in an early layer sees only a small neighborhood, and the network needs many layers before information from opposite corners of the image can meet. In a ViT, every patch can attend to every other patch in the very first layer.

    The original paper measured how far attention reaches in each layer. Some attention heads in the earliest layers already covered most of the image, while others stayed local, behaving a lot like convolutions. Deeper layers attended globally. Raghu and colleagues compared the internal representations of ViTs and ResNets in 2021 and found that ViTs have more uniform representations across layers and carry spatial information further into the network.

    The Need for Data

    The most important result in the ViT paper was about data. Trained on ImageNet alone, with about 1.3 million images, ViT was worse than a comparable ResNet. Without the built-in assumptions of convolution, the model had to learn from scratch that nearby patches are related, and 1.3 million images were not enough for that.

    With more data, the result reversed. Pre-trained on ImageNet-21k (14 million images), ViT matched the best CNNs. Pre-trained on JFT-300M, Google’s internal dataset of 300 million images, the largest model (ViT-H/14) reached 88.55% top-1 accuracy on ImageNet after fine-tuning, ahead of the best convolutional models of the time. The authors summarized it by saying that large-scale training trumps inductive bias.

    That left a practical problem, since almost nobody outside Google had 300 million labeled images.

    DeiT and Training on ImageNet Alone

    A few months later, Hugo Touvron and colleagues at Facebook AI showed that the data requirement was partly a matter of training recipe. Their Data-efficient image Transformers (DeiT), published at ICML 2021, trained a ViT on ImageNet only and reached 81.8% top-1 accuracy (83.1% at a higher input resolution), competitive with CNNs of similar size. The changes were heavy data augmentation, strong regularization and a longer, carefully tuned schedule.

    DeiT also introduced a distillation token. Alongside the class token, a second special token is trained to reproduce the prediction of a teacher network, and the best teachers turned out to be CNNs. The student Transformer picks up some of the convolutional network’s inductive bias through the teacher’s outputs.

    Swin and Hierarchical Designs

    Plain ViT has two limits for tasks beyond classification. It produces features at a single, coarse resolution, while object detection and segmentation need features at several scales. And the quadratic cost of global attention becomes too high for large images.

    Swin Transformer, from Ze Liu and colleagues at Microsoft Research Asia, addressed both. It computes self-attention only inside small local windows, so cost grows linearly with image size. Between consecutive layers, the windows are shifted so that information can flow across window borders. Patches are merged as the network gets deeper, which produces a pyramid of feature maps at decreasing resolution, like a CNN. Swin set records in object detection on COCO and semantic segmentation on ADE20K and received the Marr Prize for best paper at ICCV 2021.

    Self-Supervised Pre-Training: MAE and DINO

    The other way around the labeled data problem is to not use labels. Masked Autoencoders (MAE), from Kaiming He and colleagues at CVPR 2022, hide 75% of the patches of an image and train a ViT to reconstruct the missing pixels from the remaining quarter. The encoder only processes the visible patches, so pre-training is fast, and a ViT-H trained this way on ImageNet-1k alone reached 87.8% accuracy after fine-tuning.

    DINO, from Mathilde Caron and colleagues in 2021, trains a student network to match the output of a slowly updated teacher on different crops of the same image. A side effect got a lot of attention: the attention maps of the class token outlined objects in the image, although the model had never seen a segmentation label. DINOv2, released by Meta in 2023, scaled the approach to a curated set of 142 million images and produced features that work for classification, segmentation and depth estimation with no fine-tuning.

    The CNN Response

    ViT’s success raised the question of whether attention was the reason, or whether the improvements came from everything around it: bigger models, better augmentation, new training schedules. In «A ConvNet for the 2020s» (CVPR 2022), Zhuang Liu and colleagues took a standard ResNet and modernized it step by step, borrowing design choices from Swin such as larger kernels, fewer activation functions and layer normalization. The resulting ConvNeXt matched or beat Swin at similar size on ImageNet, detection and segmentation, using only convolutions.

    The conclusion most researchers took from this is that the two families are closer than the early results suggested. Convolutions remain efficient on small data and limited hardware. Transformers scale better with data and combine naturally with text and other modalities, since everything becomes tokens.

    ViT as a Backbone

    That last property explains where ViTs ended up. CLIP, from OpenAI in 2021, trains an image encoder (in its best versions a ViT) together with a text encoder so that matching images and captions get similar embeddings. Vision-language models that answer questions about pictures typically feed ViT patch embeddings into a language model. The Segment Anything Model (Kirillov and colleagues, 2023) uses a ViT pre-trained with MAE as its image encoder and was trained on 11 million images with over a billion masks. Diffusion models for image generation have also moved from convolutional U-Nets to Transformer backbones operating on patches.

    Closing Observation

    ViT is a useful case for a general question in machine learning: how much knowledge should the designer build into a model, and how much should be left for the data to teach it. Convolutions build in knowledge about images, and that helps when data is scarce. ViT removes most of it, does worse with little data, and does better once there is enough. Neither choice is right in general. The better one depends on how much data and compute are available, and for image models that amount grew very quickly in the years after 2020.

    By: Max Johnson B.

  • Graph Neural Networks: Deep Learning for Data Made of Connections

    Data That Does Not Fit in a Grid

    Convolutional networks work on images because an image is a regular grid: every pixel has the same number of neighbors, arranged in the same way. Recurrent networks and transformers work on text because a sentence is a sequence with a clear order. A lot of important data has neither structure.

    A molecule is a set of atoms connected by bonds. A social network is a set of people connected by friendships. A road network is a set of intersections connected by streets. A citation network, a power grid, a supply chain, a protein’s contact map: all of them are graphs, made of nodes and the edges between them. The number of neighbors varies from node to node, there is no natural ordering of the nodes, and the connections themselves carry most of the information. Graph neural networks (GNNs) are the family of models built for this kind of data.

    Message Passing

    Most GNNs follow one pattern, which Justin Gilmer and colleagues formalized in 2017 as message passing. Each node starts with a feature vector, for example the element type and charge of an atom. In each layer, every node collects messages from its neighbors, combines them with a function that does not depend on their order (such as a sum, mean or max), and uses the result to update its own vector.

    After one layer, each node’s representation contains information about its direct neighbors. After two layers, it includes neighbors of neighbors. After k layers, each node has a summary of its k-hop neighborhood. The same learned functions are applied at every node, similar to how a convolutional filter is applied at every position in an image, so the model works on graphs of any size and shape.

    The node representations can then be used in three ways. Node-level tasks predict something about each node, such as the topic of a paper in a citation network. Edge-level tasks predict whether a connection exists or what kind it is, such as whether a user will interact with an item. Graph-level tasks pool all node vectors into one and predict a property of the whole graph, such as whether a molecule is toxic.

    From the First GNNs to GCN

    Franco Scarselli and colleagues described a graph neural network model in 2009, in which node states were updated repeatedly until they reached a fixed point. A different line of work started from spectral graph theory. Bruna and colleagues in 2014 defined convolution on graphs through the eigenvectors of the graph Laplacian, the graph equivalent of Fourier analysis. It was mathematically elegant but expensive and tied to one specific graph.

    Thomas Kipf and Max Welling simplified this in their 2017 ICLR paper on graph convolutional networks (GCN). They approximated the spectral convolution so heavily that each layer became a simple operation: average the features of each node and its neighbors, with a normalization based on node degrees, then apply a linear transformation and a nonlinearity. It was cheap, easy to implement, and gave strong results on semi-supervised node classification in citation networks, where only a small fraction of nodes have labels. GCN is still the model most people learn first.

    GraphSAGE, Attention and Expressive Power

    GCN as originally described needs the whole graph at training time. GraphSAGE, from William Hamilton, Rex Ying and Jure Leskovec (2017), made GNNs work on very large and changing graphs by sampling a fixed number of neighbors for each node and learning aggregation functions that apply to nodes never seen during training.

    Graph attention networks (GAT), from Petar Veličković and colleagues in 2018, replaced the fixed averaging weights with learned attention: each node decides how much to listen to each neighbor, based on both of their features. This helps when some neighbors are much more relevant than others.

    A theoretical question followed: which graphs can a GNN tell apart? Keyulu Xu and colleagues showed in 2019 that standard message-passing GNNs are at most as powerful as the Weisfeiler-Lehman graph isomorphism test, a classic algorithm that iteratively relabels nodes based on their neighbors’ labels. There are simple pairs of non-identical graphs that the test, and therefore these GNNs, cannot distinguish. They proposed the Graph Isomorphism Network (GIN), which uses sum aggregation with a multilayer perceptron and reaches that upper bound. Much later research has tried to go beyond it by adding substructure counts, positional encodings, or higher-order message passing.

    Known Weaknesses

    Stacking many GNN layers does not work as well as stacking many CNN layers. The first reason is over-smoothing: each layer averages node features with their neighbors, and after many layers all nodes in a connected region end up with nearly the same representation, losing the information that distinguished them. The second is over-squashing: information from an exponentially growing neighborhood must be compressed into a fixed-size vector, so signals from distant nodes get lost. For these reasons most practical GNNs are shallow, often two to four layers.

    Many early models also assumed homophily, the tendency of connected nodes to be similar. That holds in citation networks, where papers cite related papers, but not in graphs where edges connect different kinds of things, such as fraudsters and their victims. Scaling is another challenge, since a node’s neighborhood can explode in size after a few hops in graphs with billions of edges. Graph transformers, which let every node attend to every other node and add information about the graph structure through positional encodings, are one response to over-squashing, at a higher computational cost.

    Molecules and Drug Discovery

    Chemistry is one of the most natural applications, because a molecule is a graph. Gilmer and colleagues introduced their message passing framework while predicting quantum chemical properties of small molecules, reaching accuracy close to that of expensive quantum calculations at a fraction of the cost.

    In 2020, Jonathan Stokes and colleagues at MIT published in Cell the discovery of halicin, an antibiotic identified with a message-passing neural network trained to predict whether molecules inhibit the growth of E. coli. After screening a drug repurposing library and then more than 100 million molecules from a larger database, they found a compound structurally different from existing antibiotics that was effective against several drug-resistant bacteria in lab and mouse experiments. GNNs are also used to predict material properties, and to reason about protein structure, where residues in contact form a natural graph.

    Maps, Weather and Recommendations

    In 2020, DeepMind described a GNN deployed in Google Maps to predict travel times. The road network was divided into «supersegments» of adjacent roads that share traffic, and the model learned how congestion spreads between them. According to DeepMind, it improved the accuracy of real-time arrival estimates by up to 50% in cities such as Berlin, Jakarta, São Paulo, Sydney, Tokyo and Washington D.C.

    GraphCast, published by Remi Lam and colleagues in Science in 2023, uses a GNN to forecast global weather up to ten days ahead. The Earth’s surface is represented as a multi-resolution mesh of nodes, and message passing over that mesh moves information around the globe. It outperformed the European Centre for Medium-Range Weather Forecasts’ high-resolution deterministic system (HRES) on 90% of 1,380 verification targets, and it produces a forecast in under a minute on a single TPU, compared to hours on a supercomputer for traditional numerical models.

    Recommendation systems are another major use, since users and items form a bipartite graph. PinSage, from Rex Ying and colleagues at Pinterest in 2018, applied GraphSAGE-style convolutions to a graph with billions of nodes to recommend pins. Banks and payment companies use GNNs for fraud detection, since fraudulent accounts often reveal themselves through their connections more than through their individual features.

    Reflection

    The main idea behind graph neural networks is that a node is described by its neighborhood as much as by its own features. An atom’s role depends on what it is bonded to, and a road’s traffic depends on the roads feeding into it. Convolutional networks relied on the same idea, with the neighborhood fixed by the pixel grid. GNNs let the data define the neighborhood, which is why the same kind of model can work on molecules, road networks and the whole planet’s atmosphere.

    By: Max Johnson B.

  • Neural Architecture Search: Letting Algorithms Design Neural Networks

    Architecture Design by Hand

    Every famous neural network was designed by people. AlexNet, VGG, ResNet and the Transformer came from researchers who tried ideas, trained models, read the results and tried again. How many layers, what kind of layers, how wide each one should be, where to put skip connections, which activation function to use: each decision was the result of intuition and a lot of trial and error.

    Neural architecture search (NAS) tries to automate that process. It treats the architecture itself as something to optimize: define a space of possible networks, search it with an algorithm, and evaluate candidates by training them and measuring their performance. Any NAS method can be described by three choices. The search space defines which architectures are possible. The search strategy decides which ones to try. The performance estimation strategy decides how to judge a candidate without spending too much compute on it. Thomas Elsken, Jan Hendrik Metzen and Frank Hutter used this framing in their 2019 survey, and it is still the standard way to compare methods.

    The Reinforcement Learning Approach

    The paper that started the modern field was «Neural Architecture Search with Reinforcement Learning» by Barret Zoph and Quoc Le at Google, presented at ICLR 2017. A recurrent neural network acted as a controller that generated a description of an architecture one decision at a time: filter size, stride, number of filters for each layer. That architecture was trained, its validation accuracy was used as a reward, and the controller was updated with a policy gradient method to produce better architectures over time. The networks it found were competitive with the best hand-designed ones on CIFAR-10, and the recurrent cell it found for language modeling beat the LSTM on Penn Treebank.

    The cost was enormous, because every sample meant training a network from scratch. The authors used hundreds of GPUs in parallel. The follow-up, NASNet (Zoph, Vasudevan, Shlens and Le, 2018), made the search more practical by searching for a small building block, a «cell,» instead of a whole network. The best cell was then stacked many times to build the full model, and a cell found on the small CIFAR-10 dataset transferred to ImageNet with state-of-the-art results. Even so, the search took on the order of 2,000 GPU days.

    Evolutionary Approaches

    Evolutionary algorithms were used on neural networks long before deep learning. NEAT, by Kenneth Stanley and Risto Miikkulainen in 2002, evolved both the weights and the topology of small networks. For modern deep networks, evolution usually searches only the architecture and leaves the weights to gradient descent.

    Esteban Real and colleagues at Google published AmoebaNet in 2019, using what they called regularized evolution, also known as aging evolution. It is a tournament-selection algorithm with one change: when a new architecture is added to the population, the oldest one is removed, not the worst. That forces the population to keep producing good architectures instead of relying on a single lucky one that happened to get a high score from a noisy evaluation. In a direct comparison with the reinforcement learning approach on the same search space, evolution reached similar or better accuracy and got there faster. The cost was still around 3,150 GPU days.

    Evolution has a natural advantage when there are several goals. NSGA-Net (Lu and colleagues, 2019) used NSGA-II to search for architectures that trade off accuracy against computational cost, returning a whole set of options instead of one network.

    Weight Sharing and One-Shot Models

    Thousands of GPU days put NAS out of reach for almost everyone outside a few large companies. The idea that changed this was weight sharing. ENAS (Pham and colleagues, 2018) observed that all architectures in a cell-based search space are subgraphs of one large graph containing every possible operation. If that «supernet» is trained once, each candidate architecture can inherit its weights from the supernet instead of being trained from scratch. The paper reported a search cost about 1,000 times lower than the original NAS.

    DARTS (Differentiable Architecture Search), from Hanxiao Liu, Karen Simonyan and Yiming Yang at ICLR 2019, went a step further. Instead of choosing one operation for each connection in the cell, DARTS places all candidate operations there at once and combines their outputs with a softmax over learnable weights. The architecture becomes continuous, so it can be optimized with gradient descent alongside the network weights. After the search, the operation with the largest weight on each edge is kept. DARTS found cells comparable to NASNet and AmoebaNet in 1.5 to 4 GPU days.

    The speed came with problems. Later studies found that DARTS often collapses toward architectures full of skip connections, which are easy to train in the supernet but perform poorly when trained alone. Supernet performance also did not always predict how well an architecture would do when trained on its own. Many variants since then have focused on fixing this instability.

    Hardware-Aware Search

    The best architecture depends on where it will run. A network for a phone has to meet a latency budget, and the number of floating-point operations is a poor proxy for real speed because it ignores memory access and hardware-specific kernels. MnasNet (Tan and colleagues, 2019) included latency measured on actual phones in the search objective. EfficientNet (Tan and Le, 2019) used a similar search to find a small baseline network, then scaled its depth, width and input resolution together with a fixed ratio, producing a family of models that was more accurate than previous networks at every size.

    Once-for-All (Cai and colleagues, 2020) trained a single large network in a way that makes many of its subnetworks usable directly, so a specialized model for a new device can be extracted without retraining. This moves most of the cost into one training run and makes deployment on many devices cheap.

    Is Search Better Than Random?

    As results piled up, a skeptical question appeared: how much of the performance comes from the search algorithm and how much from a well-designed search space? Liam Li and Ameet Talwalkar showed in 2019 that random search with weight sharing was competitive with DARTS and ENAS on standard benchmarks. Yang and colleagues reported in 2020 that on several popular search spaces, randomly sampled architectures already performed very well, and that details of the training pipeline mattered more than the search method.

    To make comparisons fair and cheap, researchers built tabular benchmarks. NAS-Bench-101 (Ying and colleagues, 2019) trained all of about 423,000 unique architectures in a fixed cell space and published their results, so a search algorithm can be tested by looking up accuracies instead of training anything. NAS-Bench-201 and others followed. These benchmarks made it possible to compare algorithms reproducibly, and they also made it clearer that many published gains were small.

    The Cost Question

    NAS also became an example in debates about the environmental cost of AI. In 2019, Emma Strubell, Ananya Ganesh and Andrew McCallum estimated the carbon emissions of training NLP models, and the scenario with the largest footprint was a Transformer found through NAS, estimated at roughly 626,000 pounds of CO2. The figure was widely quoted. In 2021, David Patterson and colleagues at Google argued that it was far too high for the actual search that had been run, because it assumed the full search was performed at the largest model size on older hardware. The disagreement is a useful reminder that estimates of AI’s energy use depend heavily on assumptions about hardware, data centers and exactly what was run.

    Where NAS Stands Now

    NAS produced real, widely deployed models, especially for mobile vision, and weight sharing and hardware-aware objectives are now standard tools. At the same time, the biggest architectural shift of recent years, the move to Transformers and their scaling, came from human design and experiments with scale, not from search. For large models, the practical questions are usually about scaling width, depth and data, and search is applied to smaller choices like the shape of attention blocks, activation functions or the configuration of mixture-of-experts layers. In industry, NAS is most common when a model has to fit a specific device under strict latency, memory or energy constraints.

    Reflection

    NAS started as an effort to have algorithms design networks without human input, and it ended up showing how much the human choices still matter. The search space is designed by people, and it often decides most of the result before the search even begins. The strongest work in the field is honest about that. It treats NAS as a way to search carefully through a space that experts defined, not as a replacement for the experts.

    By: Max Johnson B.

  • Bayesian Optimization and Hyperparameter Tuning: Making Every Expensive Experiment Count

    The Hyperparameter Problem

    Every machine learning model comes with settings that training does not learn on its own: the learning rate, the number of layers, the batch size, the amount of regularization, the depth of each tree in a boosted ensemble. These are hyperparameters, and they can make the difference between a model that works and one that does not.

    Finding good values is an optimization problem with an unpleasant objective function. Each evaluation means training a model and measuring its validation performance, which can take minutes, hours or days. There is no gradient available. The result is noisy, because random initialization and data shuffling change it from run to run. And some hyperparameters are continuous, some are integers and some are categorical choices. The question is how to find a good configuration while spending as few training runs as possible.

    Grid Search and Random Search

    The traditional approach was grid search: choose a few values for each hyperparameter and try every combination. It is simple and easy to parallelize, but the number of combinations grows exponentially with the number of hyperparameters, and it wastes most of its budget.

    James Bergstra and Yoshua Bengio showed why in a 2012 paper in the Journal of Machine Learning Research. In most problems, only a few hyperparameters really matter, and which ones matter depends on the dataset. A grid with 9 points over two hyperparameters tests only 3 distinct values of each. Nine random points test 9 distinct values of each. If only one of the two hyperparameters matters, random search explores it three times more thoroughly for the same cost. Their experiments found that random search matched or beat grid search on neural networks with a fraction of the budget. Random search has been the standard baseline since then.

    Both methods share a weakness: they ignore what they have already learned. The fiftieth trial is chosen with no knowledge of the first forty-nine.

    The Idea Behind Bayesian Optimization

    Bayesian optimization uses the results so far to decide where to look next. It has two components. The first is a surrogate model, a cheap probabilistic model of the expensive objective, fitted to all the evaluations made so far. The second is an acquisition function, which uses the surrogate to score every candidate point by how useful it would be to evaluate there.

    The loop is: fit the surrogate to the data, find the point that maximizes the acquisition function (cheap, since it only involves the surrogate), evaluate the real objective at that point (expensive), add the result to the data, and repeat. Much more computation goes into choosing each point than random search spends, but that is a good trade when each real evaluation costs hours of GPU time.

    The ideas go back to Jonas Mockus in the 1970s. Jones, Schonlau and Welch made it practical for engineering in 1998 with their Efficient Global Optimization (EGO) algorithm. Jasper Snoek, Hugo Larochelle and Ryan Adams brought it to machine learning in their 2012 NeurIPS paper «Practical Bayesian Optimization of Machine Learning Algorithms,» which showed it finding better hyperparameters than human experts on several models, including convolutional networks.

    Gaussian Processes as Surrogates

    The classic surrogate is a Gaussian process (GP). A GP defines a distribution over functions. After seeing some evaluations, it gives, for any untested point, both a predicted value (the mean) and an uncertainty (the variance). Near points already evaluated, the uncertainty is small. Far from them, it is large.

    How the GP generalizes between points is set by its kernel, which encodes assumptions such as how smooth the objective is. The Matérn 5/2 kernel, which Snoek and colleagues recommended, assumes a function that is smooth but not unrealistically so. The kernel’s own parameters, such as length scales, are typically fitted to the data or averaged over.

    GPs have limits. Their cost grows cubically with the number of observations, which is fine for a few hundred evaluations but not for tens of thousands. They also struggle with more than roughly 20 dimensions and with categorical or conditional hyperparameters (the number of units in layer three only matters if there is a layer three).

    Acquisition Functions: Exploration Versus Exploitation

    The acquisition function decides between exploitation (evaluating near the best result found so far, where the surrogate predicts good values) and exploration (evaluating where the surrogate is uncertain, since something better might be hiding there).

    Expected improvement (EI) is the most common. For each candidate point, it computes how much the result is expected to beat the current best, averaging over the surrogate’s uncertainty. A point with a slightly worse predicted mean but high uncertainty can have a higher EI than a point with a good mean and no uncertainty. Probability of improvement is a simpler version that ignores how large the improvement would be. The upper confidence bound (UCB) adds a multiple of the standard deviation to the mean and picks the highest. Srinivas and colleagues proved in 2010 that GP-UCB, with an appropriate schedule for that multiple, has sublinear regret, a formal guarantee that it keeps getting closer to the optimum.

    Tree-Structured Parzen Estimators and Other Surrogates

    Bergstra and colleagues introduced another approach in 2011, the Tree-structured Parzen Estimator (TPE). Instead of modeling the objective directly, TPE splits the observations into a good group and a bad group based on a quantile threshold and models the distribution of hyperparameter values within each group. It then samples candidates that are likely under the good distribution and unlikely under the bad one. TPE handles conditional and categorical spaces naturally and scales well, so it became the default algorithm in Hyperopt and later in Optuna, the framework from Akiba and colleagues presented at KDD 2019. SMAC, from Hutter, Hoos and Leyton-Brown, uses random forests as the surrogate for similar reasons.

    Stopping Bad Runs Early

    A different way to save compute is to not finish training for configurations that are clearly failing. Successive halving starts many configurations with a small budget (a few epochs), keeps the best half, doubles their budget, and repeats. Hyperband, from Li and colleagues (2017), runs successive halving at several trade-offs between the number of configurations and the budget per configuration, since it is not known in advance how early a good run can be recognized.

    BOHB, from Falkner, Klein and Hutter (2018), combined the two ideas: Hyperband decides how much budget each run gets, and a TPE-style model picks which configurations to try. Optuna implements the same principle through pruners, which stop trials whose intermediate validation scores fall below those of earlier trials at the same step.

    Tuning AlphaGo

    A concrete example comes from DeepMind. In a 2018 paper, Yutian Chen and colleagues described how they used Bayesian optimization to tune AlphaGo’s hyperparameters, including those of its Monte Carlo tree search, before the 2016 match against Lee Sedol. Each evaluation meant playing many self-play games. According to the paper, tuning raised the win rate against the untuned version from 50% to 66.5% in self-play, and the tuned version was the one used in the final match.

    Beyond hyperparameters, the same method is used wherever experiments are expensive: tuning chemical reaction conditions in self-driving laboratories, designing materials, calibrating simulators, placing sensors, and A/B testing configurations of web services.

    Limits and Practical Advice

    Bayesian optimization is most valuable when evaluations are expensive, the number of hyperparameters is moderate, and the budget is small (tens to hundreds of trials). With cheap evaluations and large parallel resources, random search with early stopping is often just as good and much simpler. In high dimensions, most of the surrogate’s effort goes into regions that do not matter.

    It also cannot fix a badly designed search space. If the learning rate range does not contain a good value, no algorithm will find one. Searching over the logarithm of scale parameters like learning rate and regularization strength, and setting ranges based on experience, often matters more than the choice of optimizer.

    Reflection

    Bayesian optimization makes sense because each training run is expensive. When evaluations are cheap, trying many random points works fine. When each one costs a day of GPU time, it is worth spending a lot of computation on deciding what to try next, and a surrogate that tracks both its predictions and its uncertainty is a principled way to do that. The same reasoning is spreading beyond machine learning to laboratories and factories, where each experiment costs real materials and time.

    By: Max Johnson B.

  • Multi-Objective Optimization: Pareto Fronts, NSGA-II and Choosing Among Good Trade-offs

    Problems With More Than One Goal

    Most optimization problems in textbooks have one number to minimize. Real design problems rarely do. A car should be light and also safe in a crash. An investment portfolio should have high expected return and low risk. A neural network for a phone should be accurate and also fast. Improving one of these goals usually makes another one worse.

    When objectives conflict, there is no single best solution. There is a set of solutions, each representing a different compromise, and the job of the optimizer changes from finding one answer to mapping out that set so a person can choose from it. This is multi-objective optimization, and evolutionary algorithms have become one of the main ways to do it.

    Pareto Dominance and the Pareto Front

    The central concept comes from the economist Vilfredo Pareto. A solution A dominates a solution B if A is at least as good as B on every objective and strictly better on at least one. If A is lighter and equally safe, B has no reason to exist. If A is lighter but B is safer, neither dominates the other, and both are legitimate options.

    The solutions that no other feasible solution dominates are called Pareto optimal. Plotted in objective space, they form the Pareto front: for two objectives, a curve showing the best possible value of one objective for each value of the other. Every point on the front is a trade-off where improving one goal requires giving up some of the other. Every point behind the front is simply worse than some point on it.

    Why Not Just Add the Objectives Together

    The obvious shortcut is to combine the objectives into one, for example 0.7 times cost plus 0.3 times weight, and optimize that. This weighted sum approach is common and sometimes fine, but it has two problems.

    The first is that the weights have to be chosen before seeing any solutions, and people are bad at saying in advance how many dollars a kilogram is worth. The second is mathematical. A weighted sum can only reach points on the convex parts of the Pareto front. If the front has a concave section (bulging in the wrong direction), no choice of weights will ever produce solutions there, even though they may be the most balanced options available. Other scalarization methods, like the epsilon-constraint method (optimize one objective while constraining the others below thresholds), avoid the second problem but still produce only one solution per run.

    Why Populations Fit This Problem

    Evolutionary algorithms work with a population of solutions, and a Pareto front is a population of solutions. A single run can therefore approximate the whole front at once, instead of needing one run per trade-off. The first attempt was David Schaffer’s VEGA in 1985, which selected parts of the population according to each objective separately. In 1989, David Goldberg suggested ranking individuals by Pareto dominance instead, and most later algorithms build on that idea.

    A multi-objective evolutionary algorithm has two goals of its own. The solutions should converge toward the true front, and they should spread out evenly along it, so the decision maker sees the full range of options and not a cluster of nearly identical ones.

    NSGA-II

    Kalyanmoy Deb and colleagues published NSGA-II in IEEE Transactions on Evolutionary Computation in 2002. It is one of the most cited papers in evolutionary computation, and it is still the default algorithm people reach for with two or three objectives.

    It combines three ideas. First, fast non-dominated sorting: the population is divided into layers. The first layer contains all solutions that nobody dominates. Remove them, and the non-dominated solutions among the rest form the second layer, and so on. Lower layers are better. The paper’s contribution was a sorting procedure that runs in O(MN²) time for M objectives and N individuals, faster than the earlier approach.

    Second, crowding distance. Within a layer, solutions are compared by how isolated they are: for each objective, the algorithm measures the gap between a solution’s two neighbors on the front. A solution in a sparse region has a large crowding distance and is preferred over one in a crowded region. Solutions at the extremes of the front get infinite distance, so they are always kept. This keeps the population spread along the front without extra parameters.

    Third, elitism. Parents and offspring are merged into one pool of size 2N, sorted into layers, and the best N survive. Layers are added whole until one does not fit, and that last layer is cut using crowding distance. Good solutions found earlier are never lost.

    Other Approaches: Indicators and Decomposition

    Not every algorithm uses dominance ranking as its main tool. SPEA2 (Zitzler, Laumanns and Thiele, 2001) uses a fitness based on how many solutions each individual dominates and is dominated by, plus a density estimate. MOEA/D, from Qingfu Zhang and Hui Li in 2007, breaks the multi-objective problem into many single-objective subproblems, each with a different weight vector, and solves them together, with neighboring subproblems sharing information. It avoids dominance sorting altogether and works well on problems where the front has a regular shape.

    Indicator-based algorithms optimize a quality measure of the whole set directly. The most important measure is the hypervolume, introduced by Zitzler and Thiele: the volume of objective space dominated by the solution set, bounded by a reference point. A larger hypervolume means the set is both closer to the front and more spread out. SMS-EMOA selects solutions by their contribution to the hypervolume. The downside is cost, because computing the hypervolume becomes expensive as the number of objectives grows.

    Many Objectives

    Once there are four or more objectives, the setting is usually called many-objective optimization, and dominance stops working well. With many objectives, almost any two random solutions are better than each other on at least one objective, so most of the population is mutually non-dominated. The first layer contains nearly everyone, sorting provides almost no selection pressure, and crowding distance does a poor job of spreading solutions in high-dimensional objective space.

    Deb and Himanshu Jain proposed NSGA-III in 2014 to address this. It keeps non-dominated sorting but replaces crowding distance with a set of reference points spread uniformly over a normalized hyperplane in objective space. Each solution is associated with its nearest reference direction, and the algorithm tries to keep at least one solution near each direction. The authors tested it on problems with 3 to 15 objectives. Visualizing the results becomes a problem in itself at that point, and methods like parallel coordinate plots are used to show them.

    Where It Gets Used

    Engineering design is the classic domain: aircraft wing shapes trading drag against structural weight, or car bodies balancing crashworthiness and mass. In energy systems, planners trade cost against emissions and reliability. In finance, Markowitz’s mean-variance portfolio theory is a two-objective problem at heart, and evolutionary methods extend it with realistic constraints like minimum lot sizes and limits on the number of assets.

    Machine learning uses it more and more. Neural architecture search often treats accuracy and inference latency or model size as separate objectives. NSGA-Net (Lu and colleagues, 2019) applied NSGA-II directly to this, returning a front of architectures from small and fast to large and accurate. Fairness research treats predictive accuracy and fairness metrics as competing objectives. In Python, the pymoo library by Julian Blank and Kalyanmoy Deb implements NSGA-II, NSGA-III, MOEA/D and many others.

    Choosing a Solution From the Front

    The algorithm hands back a set, but someone eventually has to build one car. That final choice is called multi-criteria decision making, and it is where human preferences come back in. One common approach is to look for knee points, places on the front where a small gain in one objective would cost a large loss in another. Another is to let the decision maker state preferences interactively and focus the search on the region they care about. Either way, the preferences are applied after the options are known.

    Reflection

    Multi-objective optimization does not decide how much one goal is worth compared to another. It shows every trade-off that is actually available and leaves the choice to the people who own the problem. Weighted sums make that choice before any results exist, often without anyone noticing. A Pareto front puts the price of every compromise in front of the decision maker, and that is a large part of why engineers use it.

    By: Max Johnson B.

  • Differential Evolution: An Optimizer Built on Subtracting One Solution From Another

    Optimization Without Gradients

    A lot of optimization in machine learning relies on gradients: compute how the error changes with each parameter, then take a step downhill. That works when the function is smooth and differentiable. Many real problems are not. The objective might come from a simulation, have discontinuities, be full of local minima, or be a black box that only returns a number for each input.

    Differential evolution (DE) was built for continuous problems of that kind. It needs nothing from the objective function except the ability to evaluate it. Rainer Storn and Kenneth Price introduced it in a 1995 technical report and published the full version in the Journal of Global Optimization in 1997. The algorithm is short enough to write in a few dozen lines, and it has remained one of the most competitive methods for continuous black-box optimization since then.

    The Core Idea: Difference Vectors

    DE keeps a population of candidate solutions, each one a vector of real numbers. What makes it distinctive is how it creates new candidates. Instead of adding random noise drawn from a fixed distribution, as many evolutionary strategies do, it uses the difference between two existing members of the population as the perturbation.

    Take three distinct population members, call them a, b and c. The mutant vector is a + F·(b − c), where F is a scaling factor, typically between 0.4 and 1. The difference (b − c) points from one solution to another somewhere in the population, and adding a scaled copy of it to a moves a in that direction.

    The effect is that step sizes and directions adapt on their own. Early in the run, the population is spread across the search space, so differences between members are large and the algorithm explores broadly. As the population converges toward a good region, the differences shrink and the steps become fine-grained. If the population stretches out along a narrow valley in the landscape, the difference vectors mostly point along that valley, so the search follows its shape. No explicit step-size schedule is needed.

    Crossover and Selection

    After mutation, DE mixes the mutant vector with the current population member it is trying to replace, called the target. In the standard binomial crossover, each coordinate of the new trial vector comes from the mutant with probability CR (the crossover rate) and from the target otherwise. One coordinate is always forced to come from the mutant, so the trial is never an exact copy of the target.

    Selection is then a one-on-one comparison. If the trial vector is at least as good as the target, it replaces it in the next generation. Otherwise the target survives. This greedy, local form of selection means the population’s best fitness can never get worse, and every member only competes with its own offspring, which helps preserve diversity compared to schemes where the best individuals take over the whole population.

    The whole loop is: for each member of the population, build a mutant from three others, cross it with the member, keep whichever is better. Repeat until the evaluation budget runs out.

    The Parameters and the Variants

    Basic DE has only three parameters: the population size NP, the scale factor F and the crossover rate CR. Storn and Price suggested starting points like NP equal to ten times the number of dimensions, F = 0.5 and CR = 0.9. These work reasonably often but not always. A low CR makes the algorithm change one or two coordinates at a time, which suits separable problems where variables can be optimized independently. A high CR changes many coordinates together, which is necessary when variables interact.

    The mutation rule also has variants, written in a naming scheme like DE/x/y/z. DE/rand/1/bin is the classic version above: random base vector, one difference vector, binomial crossover. DE/best/1/bin uses the best member of the population as the base, which converges faster but risks getting stuck early. DE/current-to-best/1 moves each member partly toward the best and partly along a random difference, and DE/rand/2 adds two difference vectors instead of one.

    Adaptive DE: JADE, SHADE and L-SHADE

    Since good parameter values depend on the problem, much of the research on DE since the mid-2000s has been about making the algorithm tune itself. SaDE, from Qin, Huang and Suganthan (2009), keeps a pool of mutation strategies and learns which ones are producing successful offspring. JADE, from Zhang and Sanderson (2009), introduced the current-to-pbest mutation, which moves toward one of the top p% of solutions instead of the single best, together with an external archive of recently replaced solutions and parameters sampled around values that recently worked.

    SHADE, from Ryoji Tanabe and Alex Fukunaga (2013), kept a history of successful F and CR values in a memory and sampled new parameters from it. The following year, the same authors added linear population size reduction: the run starts with a large population for exploration and removes the worst members on a linear schedule until only a handful remain for refinement at the end. That version, L-SHADE, ranked first in the CEC 2014 competition on single-objective real-parameter optimization, and many of the top entries in later CEC competitions, such as jSO, have been built on it.

    Constraints, Discrete Variables and Multiple Objectives

    Real engineering problems come with constraints: a beam must be strong enough, a circuit must stay under a power budget. DE handles them with the usual tools for evolutionary algorithms, such as penalty functions, or Deb’s feasibility rules, in which a feasible solution always beats an infeasible one and between two infeasible ones, the smaller violation wins.

    DE was designed for continuous variables, but integer and mixed variables can be handled by rounding when evaluating a solution, and permutation problems have been attacked with specialized encodings, though other algorithms are usually more natural there. For problems with several conflicting objectives, variants like GDE3 (Kukkonen and Lampinen) combine DE’s mutation with the Pareto-based selection used in multi-objective evolutionary algorithms.

    Where DE Is Used

    Storn’s early applications included the design of digital filters, and signal processing remains a common use. In power systems, DE has been used for economic load dispatch, deciding how much each generator should produce to meet demand at minimum cost. It shows up in antenna array design, parameter estimation for chemical kinetics and biological models (fitting a system of differential equations to measured data), structural design, and the tuning of controllers.

    In machine learning, it is used for hyperparameter tuning and for training small models where gradients are not available or not reliable. In image processing, DE is one of the metaheuristics commonly applied to find thresholds for image segmentation. And because it ships with SciPy as scipy.optimize.differential_evolution, it is often the first global optimizer someone in the Python ecosystem tries.

    Strengths and Limits

    DE’s advantages are simplicity, few parameters, rotation-invariant mutation (the difference vectors do not favor the coordinate axes, even though standard crossover does), and strong performance on rugged, multimodal continuous landscapes. It parallelizes easily, since the objective evaluations within a generation are independent.

    Its main limitation is the one shared by all population-based black-box methods: it needs many function evaluations, often tens of thousands. When each evaluation is a finite-element simulation that takes an hour, that is too expensive, and methods that build a surrogate model of the objective, like Bayesian optimization, are a better fit. On high-dimensional problems with smooth, cheap-to-compute gradients, gradient-based methods will be far more efficient. The no free lunch theorems also apply: no variant of DE is best on every problem, and it is easy to find benchmarks where CMA-ES or particle swarm optimization does better.

    Reflection

    The key idea in differential evolution is that the population itself stores information about the shape of the search space. The distances and directions between current solutions tell the algorithm how big a step to take and which way to point it. It does not need a separate model of the landscape. After almost thirty years, and thousands of papers about adapting F and CR, the core operator is still the same: take one solution, add the scaled difference between two others, and keep the result only if it is better.

    By: Max Johnson B.