Blog

  • Deep Learning Optimizers: How SGD, Momentum and Adam Decide the Next Step

    A Step Downhill

    Training a neural network comes down to a loop that repeats millions of times. The model makes predictions on a batch of data, a loss function measures how wrong they were, backpropagation computes the gradient of that loss with respect to every weight, and then something has to decide how far to move each weight and in which direction. That last piece is the optimizer.

    The gradient says which way is downhill locally. It does not say how big a step to take, and it says nothing about the shape of the terrain a few steps away. A loss surface for a network with millions of parameters has long narrow valleys, flat plateaus and saddle points, and a rule that works well in one region can bounce around or stall in another. Most optimizers in use today answer one question: given the gradients seen so far, what is a better step than the raw gradient times a constant?

    Noisy Gradients Since 1951

    The starting point is older than neural networks. In 1951 Herbert Robbins and Sutton Monro published «A Stochastic Approximation Method» in the Annals of Mathematical Statistics. They studied how to find the root of a function when you can only observe noisy measurements of it, and showed that a sequence of steps converges if the step sizes shrink at the right rate: their sum must be infinite, but the sum of their squares must be finite.

    Stochastic gradient descent (SGD) is that idea applied to a loss. Computing the exact gradient over a full dataset of a million images is expensive, so SGD estimates it from a small random batch. The estimate is noisy, but it is cheap, and thousands of cheap noisy steps beat a handful of exact ones. The noise may also help. Nitish Shirish Keskar and colleagues argued at ICLR 2017 that small batches tend to land in flatter minima than very large ones, and that flat minima generalize better.

    Plain SGD has one obvious weakness. A single learning rate applies to every parameter in every direction. In a valley that is steep across and shallow along its length, a step size large enough to make progress along the valley floor makes the weights oscillate from wall to wall.

    Momentum

    Boris Polyak proposed a fix in 1964 with what is now called the heavy ball method. Instead of stepping along the current gradient, the update keeps a running velocity: a decaying sum of past gradients. Components that keep pointing the same way accumulate and speed up. Components that flip sign from step to step, like the oscillations across a narrow valley, cancel out.

    Yurii Nesterov published a variant in 1983 that evaluates the gradient at the point where the momentum is about to carry the weights, rather than where they currently are. For smooth convex problems this «look ahead» gives a provably faster convergence rate. In 2013 Ilya Sutskever, James Martens, George Dahl and Geoffrey Hinton showed at ICML that SGD with well-tuned momentum, combined with careful initialization, could train deep and recurrent networks that had been thought to require second-order methods. A momentum of 0.9 became the default.

    A Learning Rate for Every Parameter

    Momentum still uses one global step size. In 2011 John Duchi, Elad Hazan and Yoram Singer published AdaGrad in the Journal of Machine Learning Research. AdaGrad divides each parameter’s step by the square root of the sum of all its past squared gradients. Parameters that receive large or frequent gradients get smaller steps; rare features, such as an uncommon word in a text model, get larger ones. This worked well for sparse problems.

    The flaw is that the sum only grows. After enough steps every learning rate shrinks toward zero and training stops, which is a problem for long non-convex runs. Geoffrey Hinton proposed RMSProp in a 2012 Coursera lecture (it was never published as a paper) that replaces the growing sum with an exponential moving average of squared gradients. Old gradients fade, so the effective learning rate can recover.

    Adam

    Diederik Kingma and Jimmy Ba combined the two ideas in «Adam: A Method for Stochastic Optimization,» posted in 2014 and presented at ICLR 2015. Adam keeps two moving averages per parameter: one of the gradient (the first moment, like momentum) and one of the squared gradient (the second moment, like RMSProp). The step is the first divided by the square root of the second.

    Because both averages start at zero, they are biased toward zero in the first iterations. Adam corrects this by dividing each average by one minus the decay rate raised to the step number, a small detail that matters most at the start of training. The paper’s suggested defaults were a learning rate of 0.001, decay rates of 0.9 and 0.999, and a tiny epsilon to avoid dividing by zero.

    Those defaults are forgiving. Adam often trains a new architecture reasonably well without much tuning, and that is a large part of why it spread. It also costs memory: two extra values stored for every weight, which for a model with tens of billions of parameters means tens of gigabytes before counting the model itself.

    Case: A Convex Problem Adam Gets Wrong

    In 2018 Sashank Reddi, Satyen Kale and Sanjiv Kumar of Google presented «On the Convergence of Adam and Beyond» as an oral at ICLR. They built a simple one-dimensional convex problem on which Adam converges to the worst possible point instead of the optimum. In their example a large, informative gradient appears only occasionally. The moving average of squared gradients forgets it quickly, so the large gradient’s effect is damped while the frequent small gradients pointing the wrong way dominate. They also identified an error in the convergence proof of the original Adam paper.

    Their fix, AMSGrad, keeps the maximum of the past second moment estimates so the effective step size can never increase. It came with a valid proof, though in practice it rarely beat Adam on real networks.

    A year earlier Ashia Wilson and colleagues reported at NeurIPS 2017 that adaptive methods like Adam often found solutions that generalized worse than those of well-tuned SGD with momentum on image classification and language tasks, even when they reached lower training loss. For several years this was why computer vision papers kept training with SGD while language models moved to Adam.

    Weight Decay Is Not L2 Regularization

    Part of that generalization gap had a mundane cause. Ilya Loshchilov and Frank Hutter showed in «Decoupled Weight Decay Regularization» (ICLR 2019) that the standard way of adding weight decay to Adam was wrong. With plain SGD, adding an L2 penalty to the loss and shrinking weights directly are mathematically the same thing. With Adam they are not: the L2 term passes through the adaptive scaling, so weights with large historical gradients are regularized less than intended.

    Their version, AdamW, applies the decay to the weights directly, outside the adaptive update. The change is a few lines of code. It closed much of the gap with SGD on image classification, and AdamW is now the default for training transformers.

    Schedules, Warmup and Large Batches

    The update rule is only half of an optimizer in practice. The other half is how the learning rate changes over time. Most large runs today use a warmup followed by a decay, often along a cosine curve.

    Warmup became prominent with a 2017 paper from Facebook by Priya Goyal and colleagues, «Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour.» Their baseline ResNet-50 run used batches of 256 images on 8 GPUs and took 29 hours. They scaled to batches of 8,192 on 256 GPUs and finished in one hour with matching accuracy. Two rules made it work: multiply the learning rate by the same factor as the batch size, and start with a small learning rate for the first few epochs before ramping up. Without the warmup the large initial steps destabilized training.

    Benchmarks That Rarely Crown a Winner

    Hundreds of optimizers have been proposed since Adam. In 2021 Robin Schmidt, Frank Schneider and Philipp Hennig tested fifteen of them on eight deep learning problems at ICML, analyzing almost 35,000 runs. No method dominated across tasks. Trying several optimizers with default settings worked about as well as carefully tuning one, and Adam remained a strong contender that newer methods did not consistently beat.

    The MLCommons AlgoPerf benchmark tried to make the comparison stricter by measuring the wall-clock time needed to reach a target on a fixed set of workloads, with tuning budgets defined in the rules. In its first competition, analyzed in an ICLR 2025 paper, Distributed Shampoo from a team at Meta won the externally tuned track, training about 28% faster than the baseline. Schedule-Free AdamW by Aaron Defazio and colleagues won the self-tuning track. Shampoo uses a preconditioner built from per-layer matrix statistics, a step toward second-order information that Adam’s per-parameter scaling ignores.

    Google researchers led by Xiangning Chen used program search, an evolutionary procedure over symbolic code, to discover Lion («EvoLved Sign Momentum») in 2023. Lion keeps only one momentum buffer and uses the sign of the update, so every parameter moves by the same magnitude. Muon, released by Keller Jordan in 2024 for speedrunning a small GPT training setup, orthogonalizes the momentum of each weight matrix using a few Newton-Schulz iterations. Researchers at Moonshot AI reported in 2025 that Muon reached roughly twice the compute efficiency of AdamW in their scaling experiments, and trained a 16 billion parameter mixture-of-experts model with it.

    Closing Thought

    Adam’s success is often explained by its update rule, but its age may matter as much. For almost a decade, architectures, initialization schemes, normalization layers and learning rate recipes were developed and tuned by people who were training with Adam. A new optimizer is not competing with Adam alone. It is competing with an entire set of design choices that grew up around Adam’s behavior and were kept because they worked with it. That is one reason methods that win on paper so often lose in practice. The ones that break through, like Muon, tend to arrive with their own recipe for everything else.

    By: Max Johnson B.

  • Physics-Informed Neural Networks: Training a Network on the Equation Instead of Only the Data

    Equations We Already Have

    Most machine learning starts from ignorance. A model that classifies photographs knows nothing about cats before training, so everything it learns has to come from examples. Physics and engineering are in a different position. The motion of a fluid, the spread of heat through a metal plate and the vibration of a bridge are described by partial differential equations that have been known and tested for more than a century. The Navier-Stokes equations do not need to be rediscovered from data every time someone wants to model airflow.

    What is often missing is everything around the equation. The initial state may be known only at a few sensor locations. A material coefficient may be unknown. The geometry may be awkward enough that building a good mesh for a classical solver takes days. Measurements are noisy and sparse. A purely data-driven network trained on such measurements will happily produce predictions that violate conservation of mass, because nothing told it that mass is conserved.

    Physics-informed neural networks (PINNs) are an attempt to put both sources of knowledge into one training objective. The network is fitted to whatever data exists, and it is also penalized wherever its output fails to satisfy the governing equation.

    An Idea From 1998

    The basic idea is older than the name. In 1998, Isaac Lagaris, Aristidis Likas and Dimitrios Fotiadis of the University of Ioannina published «Artificial Neural Networks for Solving Ordinary and Partial Differential Equations» in IEEE Transactions on Neural Networks. They wrote the solution as a trial function with two parts. One part had no free parameters and was built to satisfy the boundary or initial conditions exactly. The other part was a small feedforward network multiplied by a factor that vanished on the boundary, so it could change the interior without breaking the conditions. The network’s weights were then trained so the differential equation held at a set of points inside the domain.

    They compared the results against the Galerkin finite element method on several test problems. The work stayed fairly niche for almost two decades. Computing derivatives of a network with respect to its inputs had to be done by hand for each architecture, and the hardware and software to train larger networks did not exist yet.

    The Residual as a Loss Term

    The modern version came from Maziar Raissi, Paris Perdikaris and George Em Karniadakis at Brown University. Their preprints appeared in late 2017, and the combined paper, «Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations,» was published in the Journal of Computational Physics in 2019.

    The setup is simple to describe. A fully connected network takes coordinates as input, for example a position x and a time t, and outputs the value of the physical field at that point, say a velocity u(x, t). Because modern frameworks like TensorFlow and PyTorch support automatic differentiation, the derivatives of u with respect to x and t can be computed exactly for any input, with no finite difference grid. Plug those derivatives into the PDE and you get a residual: the amount by which the equation fails at that point. For a correct solution the residual is zero everywhere.

    Training then minimizes a sum of terms. One term measures the mismatch with observed data or with the initial and boundary conditions. Another measures the squared residual at thousands of «collocation points» scattered through the domain. Those points need no labels. The equation itself supplies the target, which is zero. In the paper the authors tested this on Burgers’ equation, the Schrödinger equation, the Allen-Cahn equation and the Korteweg-de Vries equation, among others.

    Inverse Problems

    The more interesting half of that paper concerns what the authors called data-driven discovery. Suppose the form of the equation is known but one of its coefficients is not, such as a viscosity or a diffusion constant. In a classical workflow you would guess the coefficient, run a solver, compare with measurements and repeat inside an outer optimization loop. With a PINN the unknown coefficient is simply another trainable parameter. Gradient descent adjusts it together with the network weights, and the value that makes the data and the equation agree is what training converges to.

    This is where the method is easiest to defend. A finite element solver needs a fully specified problem. A PINN can work with a partially specified one, where some boundary conditions are missing and some measurements are present in the interior, because the loss function does not care where its information comes from.

    Case: Smoke, Dye and a Hidden Pressure Field

    The best known demonstration is «Hidden fluid mechanics: Learning velocity and pressure fields from flow visualizations,» by Raissi, Alireza Yazdani and Karniadakis, published in Science in 2020. The input was only the concentration of a passive scalar, the kind of thing you see when dye or smoke is carried along by a flow. Velocity and pressure were never observed directly.

    The network was asked to output concentration, velocity and pressure at every point in space and time. The loss rewarded matching the observed concentration and penalized violations of the transport equation for the scalar and of the Navier-Stokes equations. Since the dye moves with the fluid, the only velocity and pressure fields consistent with both the images and the physics are the real ones (up to what the data can resolve). The authors showed examples including flow past a cylinder and blood flow in an intracranial aneurysm, and reported that the method tolerated low resolution and substantial noise in the input. In the aneurysm setting, quantities like wall shear stress are clinically relevant and hard to measure directly, which is the reason anyone would want to infer them from images.

    Competing Loss Terms

    People who tried PINNs on harder problems soon found that training often failed quietly. The network would fit the boundary conditions and settle on a smooth, wrong solution, or it would satisfy the PDE residual while ignoring the boundaries.

    Sifan Wang, Yujun Teng and Perdikaris traced part of this to the loss itself in «Understanding and Mitigating Gradient Flow Pathologies in Physics-Informed Neural Networks» (SIAM Journal on Scientific Computing, 2021). The residual term contains high-order derivatives of the network, and its gradients can be much larger than those of the boundary term. Gradient descent then spends almost all its effort on the residual, and the boundary conditions, which are what make the solution unique, barely get learned. Their remedy adapts the weight of each loss term during training using statistics of the back-propagated gradients, and they reported accuracy gains of roughly 50 to 100 times on several benchmark problems.

    Smooth Functions Come First

    A second difficulty comes from a general property of neural networks. Nasim Rahaman and colleagues showed in «On the Spectral Bias of Neural Networks» (ICML 2019) that networks learn low-frequency components of a function much faster than high-frequency ones. For image classification this is often harmless. For physics it is a problem, because shocks, thin boundary layers and fast oscillations are exactly the high-frequency features that matter.

    Aditi Krishnapriyan, Amir Gholami, Shandian Zhe, Robert Kirby and Michael Mahoney examined this in «Characterizing possible failure modes in physics-informed neural networks» (NeurIPS 2021). On simple one-dimensional convection, reaction and diffusion problems, a standard PINN worked for mild coefficients and broke down as the coefficients grew. They argued that the network was large enough to represent the solution and that the failure came from optimization: the PDE residual term made the loss landscape harder to navigate. Two fixes helped. Curriculum regularization starts training on an easy version of the equation and gradually increases the coefficient. A sequence-to-sequence formulation solves the problem in short time windows, one after another. Both reduced error by one to two orders of magnitude compared with ordinary PINN training.

    The Comparison With Finite Elements

    Early enthusiasm sometimes described PINNs as a replacement for classical solvers. Direct comparisons have not supported that. Tamara Grossmann, Urszula Julia Komorowska, Jonas Latz and Carola-Bibiane Schönlieb asked the question plainly in «Can physics-informed neural networks beat the finite element method?» (IMA Journal of Applied Mathematics, 2024). On Poisson, Allen-Cahn and semilinear Schrödinger equations the finite element method was faster and more accurate at producing the solution. PINNs had one advantage: once trained, evaluating the solution at new points could be quicker.

    A broader warning came from Nick McGreivy and Ammar Hakim of the Princeton Plasma Physics Laboratory in Nature Machine Intelligence (2024). They reviewed papers claiming that a machine learning method outperformed a standard numerical method on fluid-related PDEs and found that 79% of them (60 of 76) compared against a weak baseline, for example a solver run at much higher accuracy than needed, or a method that is not the efficient standard for that problem. They also found evidence of publication bias: negative results, where the network does worse, are rarely written up. This does not apply only to PINNs, but PINNs are a large share of that literature.

    Closing Thought

    The fair reading of these results is that a PINN is a poor solver and a good fitting method. When the problem is fully specified, decades of numerical analysis have produced tools that are faster, more accurate and come with error bounds that a trained network does not offer. The case for a PINN starts when the problem is not fully specified: a coefficient is unknown, the boundary is partly unobserved, and the only data are a few noisy measurements or a video of dye. In that situation a classical solver has nothing to start from, and the equation becomes what it is in the PINN loss, a strong prior on which explanations of the data are physically possible. Judged as a way to regularize a model with known physics, rather than as a faster way to solve equations we can already solve, the method has a clear place.

    By: Max Johnson B.

  • Spiking Neural Networks and Neuromorphic Computing: Computing With Pulses Instead of Numbers

    A Neuron That Talks in Pulses

    The artificial neuron in a standard deep network is a strange object if you compare it to the cell that inspired it. It takes a weighted sum of real numbers, passes the sum through a smooth function, and hands a real number to the next layer. It has no sense of time. Every unit produces an output on every forward pass, whether or not anything interesting happened.

    A biological neuron behaves differently. It accumulates electrical charge from its inputs, and when the voltage across its membrane crosses a threshold it fires a brief pulse, an action potential, then resets. Between pulses it is mostly quiet. The information it carries lives in when those pulses occur and how often, not in a continuous output value. Hodgkin and Huxley described the mechanism in detail in 1952 from recordings of the squid giant axon, work that earned them a share of the 1963 Nobel Prize in Physiology or Medicine.

    Spiking neural networks (SNNs) take this behavior seriously. Their units communicate with discrete events in time. Neuromorphic computing is the hardware side of the same idea: chips designed so that computation and energy use happen only when a spike arrives.

    Leaky Integrate-and-Fire

    The most common model in practice is far simpler than Hodgkin and Huxley’s four coupled equations. It goes back to Louis Lapicque, who in 1907 modeled a nerve membrane as a capacitor in parallel with a resistor. The leaky integrate-and-fire (LIF) neuron keeps one state variable, its membrane potential. Incoming spikes push the potential up by an amount set by the synaptic weight. Between inputs the potential decays back toward rest, which is the leak. If it crosses the threshold, the neuron emits a spike and the potential drops to a reset value.

    That is the whole model. The leak gives the neuron a short memory: two input spikes that arrive close together can push it over threshold, while the same two spikes spread far apart may not. So the unit is sensitive to timing in a way a ReLU never is.

    Rates, Timing and the Third Generation

    How should a number become a train of spikes? The simplest answer is rate coding. A pixel with intensity 0.8 fires often, a pixel with intensity 0.1 fires rarely, and the network reads the rate over a time window. Rate coding works, but it is wasteful, because representing a value precisely requires many spikes and a long window.

    The alternative is temporal coding, where the timing of a spike carries the information. A neuron that fires first in response to a stimulus might signal a strong input, and the rest of the network can react before the slower neurons have fired at all. Wolfgang Maass argued for the theoretical value of this in a 1997 paper in Neural Networks, «Networks of spiking neurons: The third generation of neural network models». He placed spiking networks after threshold gates (the first generation) and sigmoidal units (the second) and showed that a single spiking neuron can compute a specific function that a sigmoidal network needs hundreds of hidden units to compute. The label stuck. The practical advantage took much longer to show up.

    The Gradient Problem

    Backpropagation needs derivatives, and a spike has none worth using. The output of a spiking neuron as a function of its membrane potential is a step: zero below the threshold, one at it. Its derivative of a step is zero almost everywhere and undefined at the jump. Plug that into the chain rule and every gradient vanishes. For years the missing gradient was the main reason SNNs trailed ordinary deep networks.

    The fix that took hold is the surrogate gradient. In the forward pass the network spikes exactly as it should, with a hard threshold. In the backward pass the step function is replaced by a smooth stand-in, such as the derivative of a fast sigmoid, centered on the threshold. Emre Neftci, Hesham Mostafa and Friedemann Zenke laid this out as a tutorial in IEEE Signal Processing Magazine in 2019, under the title «Surrogate Gradient Learning in Spiking Neural Networks». Because an SNN unrolled over time looks a lot like a recurrent network, the same backpropagation through time machinery that trains LSTMs can then train it.

    The trick is mathematically impure. The gradient being followed belongs to a slightly different network than the one being run. It works well anyway, and most current SNN libraries are built around it.

    Learning From Spike Timing

    Neuroscience offers its own learning rule, and it needs no gradient at all. Spike-timing-dependent plasticity (STDP) strengthens a synapse when the input neuron fires shortly before the output neuron, and weakens it when the order is reversed. The rule is local. Each synapse only needs to know the timing of the two neurons it connects, which makes it attractive for hardware where shipping a global error signal around the chip is expensive.

    Peter Diehl and Matthew Cook showed in 2015 how far a mostly biological recipe could go. Their network, published in Frontiers in Computational Neuroscience, combined STDP with lateral inhibition and adaptive thresholds, learned from MNIST digits without using labels during training, and reached 95% accuracy with 6,400 excitatory neurons. For an unsupervised rule that is respectable. It is also far below what a small convolutional network trained with backpropagation achieves on the same data, and that gap has kept STDP more popular in neuroscience than in applied machine learning.

    Converting a Trained Network

    A third route skips spike-based training altogether. Train an ordinary network with ReLU activations, then map it onto spiking neurons so that each neuron’s firing rate approximates the original activation. Bram Rueckauer and colleagues pushed this approach to large models in a 2017 paper in Frontiers in Neuroscience, adding spiking equivalents for max pooling, softmax, batch normalization and Inception modules, and converting VGG-16 and Inception-v3 for ImageNet.

    Conversion produces accurate networks, but it inherits the cost of rate coding. To approximate a real-valued activation closely, a neuron must fire many times, so the converted network has to run for many timesteps before its output settles. A network that needs hundreds of steps to answer has spent much of the energy that spikes were supposed to save.

    Chips Built Around Events

    SNNs on a GPU are mostly a simulation. The GPU still processes dense tensors at every timestep. The energy argument only becomes real on hardware that does nothing when nothing spikes.

    IBM’s TrueNorth, reported by Paul Merolla and colleagues in Science in 2014, packed one million programmable spiking neurons and 256 million synapses into 4,096 cores on a 5.4 billion transistor chip. Running a real-time object detection demo on 400 by 240 pixel video at 30 frames per second, it drew 63 milliwatts. Intel’s Loihi, described by Mike Davies and colleagues in IEEE Micro in 2018, had 128 neuromorphic cores, about 130,000 neurons, and a learning engine in each core so that synaptic weights could change on the chip. In 2024 Intel assembled 1,152 of its second-generation Loihi 2 chips into Hala Point, a research system with up to 1.15 billion neurons and a maximum power draw of 2,600 watts.

    A different philosophy came from the University of Manchester. SpiNNaker, led by Steve Furber, uses large numbers of small conventional processor cores connected by a network built for sending millions of tiny messages at once. Its million-core machine was switched on in November 2018 and was designed to simulate biological neurons in real time, more a tool for brain research than a machine learning accelerator.

    Case: A Camera That Reports Only Changes

    The best match for spiking hardware turned out to be a sensor that also speaks in events. In 2008 Patrick Lichtsteiner, Christoph Posch and Tobi Delbruck published a 128 by 128 pixel vision sensor in the IEEE Journal of Solid-State Circuits. It has no frames. Each pixel works independently and emits an event only when the log intensity it sees changes by more than a threshold. A static scene produces almost no output. A moving edge produces a stream of events with latency as low as 15 microseconds, across a dynamic range above 120 dB, while the chip consumes 23 milliwatts.

    Feeding this data into a conventional network means first collecting events into fake frames, which throws away the timing the sensor worked to capture. An SNN can consume the event stream directly, and its sparse activity mirrors the sparse input. Gesture recognition, high-speed tracking and drone control with event cameras are among the applications where neuromorphic systems look strongest, because the data arrives in the shape the hardware expects.

    The Benchmark Problem

    The honest record is mixed, and some of the clearest evidence comes from the chip makers themselves. In a 2021 survey in Proceedings of the IEEE, Davies and coauthors reviewed results from the research community using Loihi. Their summary was that conventional feedforward deep networks showed modest benefit, if any, on the chip. The large gains in latency and energy appeared in networks that used what spiking hardware is good at: recurrence, precise timing, local plasticity, randomness and sparse activity, on problems such as constrained optimization, sparse regression and graph search.

    Comparisons are also hard to make fairly. Energy per inference depends on how many timesteps the network runs, how sparse its activity is on real inputs, and whether the cost of memory access and sensor interfacing is counted. A spiking network that matches a GPU’s accuracy but needs a long time window to do it may lose on both latency and energy.

    One Last Idea

    Most attempts to make deep learning cheaper start from the existing model and shrink it: fewer bits, fewer weights, smaller layers. Spiking networks start from the opposite assumption, that a computation should cost nothing when the input is not changing. That assumption fits a world full of cameras watching empty hallways and microphones listening to silence far better than it fits a benchmark of static photographs. The question for neuromorphic computing may be less whether spikes can beat dense networks on ImageNet, and more whether we have been measuring efficiency on the wrong kind of data.

    By: Max Johnson B.

  • Artificial Immune Systems: Borrowing Self and Nonself From Biology

    A Defense With No Central Command

    The vertebrate immune system has no organ that looks at the whole body and decides what to attack. Detection is spread over billions of cells, each carrying receptors that bind to a narrow range of molecular shapes, and each acting on local information. Somehow the result is a system that recognizes pathogens it has never met, remembers them for decades, and mostly leaves the body’s own tissue alone.

    To computer scientists around 1990, that sounded like a list of design goals for intrusion detection and adaptive search. Artificial immune systems (AIS) is the name for the family of algorithms that grew out of that resemblance.

    The field never produced a single algorithm. It produced several, each copied from a different piece of immunology, and they succeeded and failed for different reasons.

    What Immunology Had to Offer

    Four ideas from biology did most of the work. The first is negative selection. Young T cells mature in the thymus, and those whose receptors bind strongly to the body’s own proteins are destroyed before they are released. What survives is a population of detectors that, by construction, ignores self.

    The second is clonal selection, formalized by Frank Macfarlane Burnet in the late 1950s. When a B cell’s receptor binds an antigen, that cell multiplies. Its offspring mutate their receptor genes at a very high rate (somatic hypermutation), and the variants that bind better are favored. The third is Niels Jerne’s 1974 network theory, which proposed that antibodies recognize and regulate each other, not only foreign material. The fourth, and the most recent, is the danger theory that Polly Matzinger proposed in 1994: the immune system reacts to signs of damage, such as cells dying in an uncontrolled way, more than to foreignness itself.

    Negative Selection

    The first and best known AIS algorithm came from Stephanie Forrest, Alan Perelson, Lawrence Allen and Rajesh Cherukuri in «Self-Nonself Discrimination in a Computer,» presented at the IEEE Symposium on Research in Security and Privacy in 1994. The problem was detecting unauthorized changes to files, the kind a computer virus makes.

    The method copies the thymus. Self is a set of binary strings taken from the protected data. Candidate detectors are random strings of the same length. Each candidate is compared against every self string using a partial matching rule: two strings match if they agree in at least r contiguous positions. Any candidate that matches self is discarded, a step the authors called censoring. The survivors are kept as detectors. Later, if a detector matches a string from the monitored data, something has changed.

    The design was appealing. Each site could hold its own random detector set, so learning one site’s detectors told an attacker nothing about another’s, and the system never needed examples of attacks, only of normal data. The paper’s own analysis of how many detectors were needed already hinted at the cost: generating them by random sampling and rejection becomes expensive quickly as the self set grows.

    Case: A Sense of Self for Unix Processes

    Forrest, Steven Hofmeyr, Anil Somayaji and Thomas Longstaff then asked a sharper question in «A Sense of Self for Unix Processes» (IEEE Symposium on Security and Privacy, 1996). What should count as «self» for a running program? Their answer was the short sequences of system calls it makes. A privileged program such as sendmail opens, reads, writes and forks in patterns that are fairly stable from day to day.

    They recorded the sequences produced during normal operation, for windows of a few calls (they reported results for lengths 5, 6 and 11), and built a database of normal behavior for each program. During monitoring, sequences missing from the database were flagged. The method detected several known intrusions against sendmail and lpr.

    This system did not generate random detectors at all. It stored self directly and flagged departures from it. The immunological framing produced the important question (what is a program’s self?) and the answer turned out to be a simple lookup of observed behavior. Anomaly detection on system call traces later became a standard topic in host intrusion detection, usually with no immune vocabulary attached.

    The Scaling Wall

    Negative selection was tested at larger scale in the following years, and the results were discouraging. Steven Hofmeyr and Forrest built LISYS, a network intrusion detection system described in «Architecture for an Artificial Immune System» (Evolutionary Computation, 2000), which monitored TCP connections on a local network with distributed detectors. It worked in that setting. Jungwon Kim and Peter Bentley at University College London then tried negative selection on richer network traffic data and reported severe scaling problems: with realistic numbers of features describing each connection, generating enough detectors by random sampling was infeasible.

    Thomas Stibor, Philipp Mohr, Jonathan Timmis and Claudia Eckert made the critique more general in «Is Negative Selection Appropriate for Anomaly Detection?» (GECCO 2005). They examined both binary (Hamming) and real-valued versions of the algorithm. In Hamming space, the r-contiguous matching rule creates regions of nonself that no detector can ever cover, called holes, and the number of detectors needed grows badly with the problem size. In the real-valued case, they compared negative selection with a plain classifier built from self samples and with a one-class support vector machine. The one-class SVM needed only normal examples to perform well, while the negative selection approach needed both normal and anomalous examples to reach high accuracy, which removes the main reason for using it.

    Stibor’s later doctoral thesis concluded that negative selection is not appropriate for anomaly detection, particularly next to established statistical methods. Few subfields publish such a clear negative result about their founding algorithm.

    Clonal Selection as an Optimizer

    The clonal selection principle had a more comfortable life. Leandro de Castro and Fernando Von Zuben published CLONALG in «Learning and Optimization Using the Clonal Selection Principle» (IEEE Transactions on Evolutionary Computation, 2002). The algorithm keeps a population of candidate solutions, called antibodies, and measures each one’s affinity, which is just its fitness. The best antibodies are cloned, with more clones for higher affinity. Each clone is mutated at a rate inversely related to its affinity, so good solutions change little and poor ones change a lot. The best mutants replace their parents, and a few of the worst members are replaced by random new ones at each generation.

    As an optimizer, this is close to an evolution strategy with no crossover and fitness-dependent mutation. What CLONALG does well is keep several separate groups of good solutions alive at once, because each antibody and its clones form a local search that does not compete directly with the others. The paper tested it on pattern recognition, multimodal function optimization and the traveling salesman problem.

    Antibodies That Recognize Each Other

    Jerne’s network theory led to a different kind of algorithm. J. Doyne Farmer, Norman Packard and Alan Perelson published «The Immune System, Adaptation, and Machine Learning» in Physica D in 1986, one of the earliest papers to treat the immune system as a learning system. They compared a model of interacting antibodies with John Holland’s classifier systems.

    The idea that elements of the repertoire suppress each other became useful later in data analysis. De Castro and Von Zuben’s aiNet (2001) places a population of antibodies over a data set, lets them clone and mutate toward the data points they recognize, and then removes antibodies that are too similar to one another. What remains is a compressed set of prototypes that can then be clustered. An optimization version, opt-aiNet, by de Castro and Timmis (2002), used the same suppression step to keep a population spread over multiple optima and to let its size change during the run. Suppression here does the job that niching does in evolutionary algorithms: it keeps a population from collapsing onto one point.

    Danger Signals and Dendritic Cells

    The danger theory reached computing through Uwe Aickelin and Steve Cayzer in 2002, and became an algorithm when Julie Greensmith, Aickelin and Cayzer introduced the dendritic cell algorithm (DCA) at the ICARIS conference in 2005. Dendritic cells sample material from tissue while sensing signals around them: uncontrolled cell death counts as danger, controlled cell death as safe. When a cell has collected enough signal it migrates, and that context decides whether the response to what it carried is aggressive or tolerant.

    In the DCA, a population of artificial cells samples items (for example, process identifiers) together with input signals computed from system measurements. Each cell sums its signals with fixed weights, and when it migrates, the items it carried are labeled according to whether danger or safe context dominated.

    In 2009, Stibor, Robert Oates, Graham Kendall and Jonathan Garibaldi published «Geometrical Insights into the Dendritic Cell Algorithm» at GECCO. By writing the signal processing step as a dot product, they showed that it is a collection of linear classifiers, and they concluded that its applicability to more complex problems is highly limited. Later work by the DCA’s own authors accepted that the classification stage is equivalent to a statically weighted linear classifier, and turned to studying how the algorithm handles signals that arrive over time.

    Closing Thought

    Emma Hart and Jon Timmis looked back on the field in «Application Areas of AIS: The Past, the Present and the Future» (Applied Soft Computing, 2008) and asked whether applying AIS had been worth it. They did not dismiss the successful applications, but they argued that the field still had to find the kinds of problems where an immune approach offers something other methods do not, and they proposed features such problems might share.

    That diagnosis matches the history. The parts of AIS that lasted were questions, not algorithms. Asking what «self» means for a running program gave host intrusion detection one of its standard methods. Asking how a population can avoid collapsing onto one answer gave optimizers a suppression step. When the algorithms copied biology closely and then competed on accuracy, a one-class SVM or a linear classifier was usually waiting at the end of the analysis. A biological metaphor seems to pay off most when it points at a part of the problem nobody had named yet.

    By: Max Johnson B.

  • Ant Colony Optimization for Routing: Artificial Pheromone on Roads and Networks

    Two Bridges and a Colony of Argentine Ants

    In the late 1980s, Jean-Louis Deneubourg, Simon Goss and their colleagues at the Université Libre de Bruxelles ran a simple experiment with the Argentine ant (Linepithema humile). They connected a nest to a food source through a bridge with two branches, one of them twice as long as the other. No ant could see the whole bridge, and no ant measured anything. Within a few minutes, most of the traffic was on the short branch.

    The explanation is mechanical. Ants lay pheromone as they walk and tend to follow stronger trails. The ants that happened to pick the short branch came back sooner, so their branch got marked in both directions before the long one did. Newcomers were then slightly more likely to choose it, which added more pheromone, which attracted more ants. A small early difference grew into a clear preference.

    The same group reported a second result in 1989 that is less often quoted. When the short branch was added only after the colony had already settled on the long one, most ants stayed on the long one. Real pheromone fades slowly, so the colony could not unlearn its first choice. That detail turns out to matter a great deal once the idea is turned into an algorithm.

    From a Thesis in Milan to Ant System

    Marco Dorigo turned the bridge experiment into an optimization method in his 1992 doctoral thesis at the Politecnico di Milano. The journal version, written with Vittorio Maniezzo and Alberto Colorni, appeared in 1996 in the IEEE Transactions on Systems, Man, and Cybernetics under the name Ant System. Its first test problem was the traveling salesman problem: find the shortest closed tour that visits every city exactly once.

    The choice was natural. A tour is a sequence of edges in a graph, and an ant walking from city to city builds exactly that kind of sequence. Each edge carries a number, the artificial pheromone, that plays the role of the chemical trail. Many ants build tours in parallel, the good tours reinforce their edges, and the next generation of ants is biased toward those edges.

    What makes this different from a genetic algorithm or a particle swarm is where the memory lives. Nothing is stored in the individual ants. All the accumulated experience of the colony sits in a matrix of pheromone values on the edges of the graph, and every new solution is built from scratch by reading that matrix.

    The Transition Rule

    An ant standing in city i picks the next city j with a probability proportional to two quantities multiplied together. The first is the pheromone on the edge, raised to a power alpha. The second is a heuristic desirability, usually the inverse of the distance between the two cities, raised to a power beta. Cities already visited are excluded. With beta large and alpha small, the ant behaves almost like a greedy nearest-neighbor heuristic. With alpha large, it follows the colony’s history and ignores geography.

    After all ants finish their tours, two things happen to the matrix. Every pheromone value is multiplied by a factor smaller than one, which is evaporation. Then each ant deposits an amount inversely proportional to the length of its tour on the edges it used, so shorter tours leave stronger marks.

    Evaporation is the piece real ants lack in useful quantity. It caps how much one early lucky tour can dominate and lets edges that stop appearing in good solutions slowly lose their attraction. Without it, the algorithm repeats the mistake of the ants on the late bridge.

    Stagnation, ACS and MAX-MIN Ant System

    Ant System worked on small instances but lost to established heuristics on larger ones. The usual failure was stagnation: after enough iterations, pheromone concentrated on a handful of edges and every ant built nearly the same tour. Two variants from 1997 dealt with this in opposite ways.

    Ant Colony System, published by Dorigo and Luca Maria Gambardella in the IEEE Transactions on Evolutionary Computation, made the search greedier where it counts and more exploratory everywhere else. With a fixed probability, an ant takes the best-looking edge outright instead of sampling. Only the best tour found so far deposits pheromone at the end of an iteration. And every time an ant crosses an edge, it removes a little pheromone from it immediately, so ants in the same iteration are pushed away from each other’s choices.

    MAX-MIN Ant System, by Thomas Stützle and Holger Hoos (journal version in Future Generation Computer Systems, 2000), clamps every pheromone value between an upper and a lower bound. All edges start at the upper bound, which keeps early iterations exploratory, and only one ant (the best of the iteration or the best so far) updates the trail. The lower bound guarantees that no edge ever becomes impossible to choose. Stützle and Hoos reported that MMAS was among the best performing algorithms for the TSP and the quadratic assignment problem at the time.

    Local Search Does Much of the Work

    There is a part of this story that introductions to ACO tend to skip. On its own, the ant construction step does not produce competitive tours on large TSP instances. The versions that reached strong results all paired the ants with a local search, typically 2-opt or 3-opt, which takes each finished tour and repairs it by swapping edges until no simple improvement remains.

    Stützle and Hoos described the division of labor directly: MMAS was useful because it generated good starting tours that guided the local search toward promising regions. For the pure symmetric TSP, specialized methods such as Lin-Kernighan heuristics and exact solvers like Concorde remain the reference points, and ACO is not the tool someone picks to win that benchmark. Its value shows up when the problem carries constraints that those specialized methods were not built for.

    Capacities, Time Windows and Fleets

    Real routing is rarely one salesman. A distributor has a depot, a fleet of trucks with limited capacity, and customers who will only accept deliveries within certain hours. That is the vehicle routing problem, and its version with time windows is one of the most studied problems in operations research.

    ACO adapts to it with little change in spirit. An ant builds routes one customer at a time and returns to the depot when the next customer would exceed the truck’s capacity or miss its time window. Bernd Bullnheimer, Richard Hartl and Christine Strauss published an improved Ant System for the capacitated problem in the Annals of Operations Research in 1999. The same year, Gambardella, Éric Taillard and Giovanni Agazzi introduced MACS-VRPTW, which runs two colonies at once. One colony tries to serve all customers with fewer vehicles, and the other minimizes total distance for the current number of vehicles. Whenever the first colony finds a feasible solution with one truck fewer, both restart with the smaller fleet. The authors reported improvements on some of the best known solutions for the Solomon benchmark instances.

    Case: Supermarket Trucks in Switzerland

    Gambardella’s group at the IDSIA institute in Lugano took these algorithms out of the benchmark tables. A 2003 paper by Gambardella and colleagues describes two tools built on Ant Colony System, AntRoute and DyvOil. According to the authors, AntRoute was used by Migros, the Swiss supermarket chain, to plan daily deliveries with a fleet of hundreds of trucks supplying its stores. DyvOil was used by Pina Petroli, a heating oil distributor in the canton of Ticino with a fleet of 12 vehicles.

    Later work by the same group, including a 2005 paper by Roberto Montemanni, Gambardella and coauthors, addressed the dynamic version of the problem, where new orders arrive while the trucks are already on the road, and tested it on a case study set in Lugano. A 2007 article by Andrea Rizzoli, Montemanni, Enzo Lucibello and Gambardella in the journal Swarm Intelligence summarized these real-world applications.

    The dynamic case is where pheromone pays off. When an order appears mid-day, the algorithm does not start from zero. The pheromone matrix still holds what the colony learned about which customers belong together, and the ants rebuild routes around the new order from that starting point.

    Packets Instead of Trucks

    The second family of routing problems has no trucks at all. In a communication network, the question is which neighbor each node should forward traffic to, and the right answer changes as links congest and recover.

    Ruud Schoonderwoerd, Owen Holland, Janet Bruten and Léon Rothkrantz proposed Ant-Based Control for circuit-switched telephone networks in Adaptive Behavior (1997). Small agents traveled between random pairs of nodes and updated the routing tables of the nodes they passed, and calls were routed according to those tables. In their simulations it produced fewer failed calls than fixed shortest-path routing.

    Gianni Di Caro and Dorigo extended the idea to packet-switched networks with AntNet, published in the Journal of Artificial Intelligence Research in 1998. Forward ants travel toward a destination and record the delays they experience. Backward ants retrace the same path and use those measurements to update probabilistic routing tables at each node. The authors compared AntNet with six other routing algorithms on simulated networks under several traffic patterns and reported that it performed as well as or better than them in their tests. Here, too, evaporation does the essential job: a route that was fast an hour ago and is now congested stops receiving reinforcement and fades.

    Closing Thought

    The ants on the late bridge are the most useful part of this whole story. A real colony finds short paths because pheromone accumulates, and it gets stuck on long paths because pheromone does not leave quickly enough. The algorithm kept the accumulation and added the one thing biology supplied too weakly, a deliberate rate of forgetting.

    That is also why ACO fits routing better than it fits a static benchmark. On a fixed TSP instance, forgetting is mostly a guard against stagnation. On a road network where orders keep arriving, or a data network where links keep congesting, forgetting is what keeps the stored answer current. The parameter that controls evaporation is easy to treat as a tuning detail, but it decides how long the colony believes in yesterday’s best route.

    By: Max Johnson B.

  • k-Nearest Neighbors and Vector Search: Finding the Closest Point Among a Billion

    Classifying by Resemblance

    The k-nearest neighbors rule is the simplest classifier most people will ever meet. To label a new example, find the k training examples closest to it and let them vote. There is no training phase in the usual sense. The model is the dataset, kept whole, and every prediction is a search through it.

    The idea is old. Evelyn Fix and Joseph Hodges described it in a 1951 technical report for the US Air Force School of Aviation Medicine, as a nonparametric way to discriminate between populations without assuming their distributions. In 1967 Thomas Cover and Peter Hart gave it a theoretical footing in «Nearest Neighbor Pattern Classification» (IEEE Transactions on Information Theory). They proved that, as the number of samples grows without limit, the error of the single nearest neighbor rule is less than twice the Bayes error, the lowest error any classifier could reach on that problem. A rule with no parameters and no fitting gets within a factor of two of the best possible. The catch is in the phrase «as the number of samples grows», and most of the later history of the method is about that catch.

    Choosing k and the Distance

    Two decisions define the classifier. The first is k. With k equal to 1, the decision boundary follows every noisy point and mislabeled example in the training set. With a large k, the boundary smooths out, but small classes get outvoted by their neighbors. In practice k is picked by cross-validation, often an odd number in two-class problems so votes cannot tie, and neighbors are sometimes weighted by the inverse of their distance so the closest ones count more.

    The second decision matters more and gets less attention: what «close» means. Euclidean distance on raw features treats a column measured in meters and a column measured in millimeters very differently, so the millimeter column dominates. Scaling features is not optional for this method. Beyond scaling, the distance encodes everything the model believes about similarity. Two photographs that differ by a one-pixel shift are far apart in pixel space and nearly identical to a person. For decades this was why nearest neighbors on raw images worked badly, and it is why the method came back once neural networks started producing embeddings, vectors in which distance tracks meaning far better than pixels do. Most modern vector search compares embeddings by cosine similarity or inner product rather than by Euclidean distance.

    Distance Stops Discriminating

    In 1999, Kevin Beyer, Jonathan Goldstein, Raghu Ramakrishnan and Uri Shaft published «When Is Nearest Neighbor Meaningful?» at the International Conference on Database Theory. They showed that under broad conditions on how data is distributed, as the number of dimensions grows, the distance from a query to its nearest point approaches the distance to its farthest point. If almost every point sits at roughly the same distance, the «nearest» one is close to arbitrary. Their experiments found the effect showing up with as few as 10 to 15 dimensions.

    This result is often quoted as a death sentence for nearest neighbor methods in high dimensions, and the authors said explicitly that it was not. Real data rarely fills its space uniformly. Images, sentences and user histories sit near much lower dimensional structures, and well-trained embeddings are built so that related items cluster. The paper also made a sharper practical point: many proposed high-dimensional indexes had never been compared against a plain linear scan, and some of them lost.

    Trees That Split Space

    The first serious answer to «how do we avoid comparing the query against everything» was the k-d tree, introduced by Jon Bentley in 1975 in Communications of the ACM. It is a binary search tree that splits the data along one coordinate at each level, cycling through the coordinates. A nearest neighbor query descends to the leaf containing the query, then backtracks only into branches whose region could still hold something closer than the best point found so far. In two or three dimensions this prunes almost the whole tree, which is why k-d trees remain standard in graphics, robotics and geographic software.

    In a few hundred dimensions the pruning collapses. The sphere around the query that might hold a closer point intersects nearly every region, so the search visits most of the tree, and the overhead makes it slower than brute force. Exact search in high dimensions has no known shortcut that works in general. The methods that took over all accept a different contract: return points that are very probably among the nearest, and measure how often that is true with a number called recall.

    Hashing Similar Things Together

    Piotr Indyk and Rajeev Motwani formalized that contract in their 1998 STOC paper «Approximate Nearest Neighbors: Towards Removing the Curse of Dimensionality». Their tool was locality-sensitive hashing. An ordinary hash function scatters similar inputs to unrelated buckets on purpose. A locality-sensitive one does the opposite: similar inputs collide with high probability, dissimilar ones rarely. For cosine similarity, one such family is a random hyperplane, where each vector gets a bit depending on which side of the plane it falls.

    Concatenating several such bits gives a bucket key, and building several independent tables raises the chance that a true neighbor shares a bucket with the query in at least one of them. The query then compares itself only against the points in its buckets. LSH came with provable guarantees, which made it attractive in theory. In practice it often needs many tables, and therefore a lot of memory, to reach high recall, and benchmarks over the following decades mostly favored the two families that came next.

    Compressing Vectors Into Codes

    The second family attacks memory instead of comparisons. Hervé Jégou, Matthijs Douze and Cordelia Schmid introduced product quantization in IEEE TPAMI in 2011. A vector is cut into several sub-vectors, each sub-vector is replaced by the index of its nearest centroid in a small codebook learned with k-means, and the whole vector becomes a short code of a few bytes. Distances between a query and millions of codes can then be computed with table lookups. Combined with an inverted file, which first assigns vectors to coarse clusters and searches only the clusters nearest the query, this made billion-scale search fit in the memory of one machine.

    Jégou and Douze, with Jeff Johnson at Facebook AI Research, released «Billion-scale similarity search with GPUs» in 2017. Their GPU k-selection ran nearest neighbor search 8.5 times faster than the previous GPU state of the art, and they built an approximate k-nearest-neighbor graph over one billion vectors in under 12 hours on four GPUs. The code became the FAISS library, which is still one of the most widely used tools in this area.

    Navigable Small World Graphs

    The third family stores the data as a graph in which each point links to some of its neighbors, and answers a query by greedy walking: start somewhere, move to whichever neighbor is closer to the query, stop when no neighbor improves. Yury Malkov and Dmitry Yashunin’s Hierarchical Navigable Small World graphs (arXiv 2016, published in IEEE TPAMI in 2020) added layers to this walk. Each point is assigned a random maximum level, with exponentially fewer points at each higher level, much like a skip list. A search starts at the sparse top layer, takes long jumps across the dataset, then drops down layer by layer for finer steps. The authors report that this gives logarithmic scaling, and that a heuristic for choosing which neighbors to link, one that favors links pointing in different directions over links to a tight cluster, improves results on clustered data and at high recall.

    HNSW became the default index in most vector databases, with one weakness: the graph lives in RAM. DiskANN, from Suhas Jayaram Subramanya and colleagues at Microsoft Research (NeurIPS 2019), moved the graph to an SSD and kept only compressed vectors in memory. On the SIFT1B benchmark, a single workstation with 64 GB of RAM served more than 5,000 queries per second with mean latency under 3 milliseconds and over 95 percent 1-recall@1.

    Case: A Language Model With a Lookup Table

    In «Generalization through Memorization» (ICLR 2020), Urvashi Khandelwal and colleagues at Stanford and Facebook took a trained transformer language model and stored the hidden representation of every context in its training data, paired with the word that followed it. At prediction time, the model’s current context is used as a query, its nearest stored contexts are retrieved with FAISS, and the words that followed them form a second distribution that is mixed with the model’s own prediction.

    Nothing was retrained. On Wikitext-103, perplexity fell from 18.65 for the base model to 16.12 with nearest neighbor retrieval alone, and to 15.79 when a cache model was added, a new state of the art at the time. The gains were largest on rare patterns, such as factual knowledge and names, which a network struggles to store in its weights but which a lookup returns exactly. The same paper showed a model could be adapted to a new domain by swapping the datastore rather than the weights.

    Closing Thought

    The nearest neighbor rule never learned anything. It needed someone else to supply a distance in which closeness meant similarity, and for fifty years nobody could supply one for images or text, so the method sat in textbooks as a baseline. Deep learning supplied the missing ingredient instead of replacing the method. Today the division of labor is almost the reverse of what early researchers expected: the network learns the geometry, and a search index over that geometry does the remembering. That changes what a model failure looks like. When a system built this way gives a wrong answer, the fault may sit in the embedding, in the data that was stored, or in an index that returned the 95 percent of neighbors it promised and missed the one that mattered.

    By: Max Johnson B.

  • Optical Character Recognition and Document AI: Teaching Machines to Read Paper

    Text Locked Inside a Picture

    A scanned invoice looks like a document to a person and like a grid of pixels to a computer. Nothing in the file says that a certain cluster of dark dots is the letter «R», that a row of them forms the word «Total», or that the number to its right is the amount someone has to pay. Optical character recognition (OCR) is the task of turning that image back into text. Document AI is the broader task of working out what the text means: which number is the date, which is the tax, which block is a table and which is a footnote.

    The two problems used to be handled by separate tools. OCR produced a stream of characters, and some other program, often a pile of hand-written rules, tried to pull fields out of it.

    Reading Checks With Convolutions

    One of the first large commercial uses of neural networks was reading handwriting. In 1998 Yann LeCun, Léon Bottou, Yoshua Bengio and Patrick Haffner published «Gradient-Based Learning Applied to Document Recognition» in the Proceedings of the IEEE. The paper described LeNet-5, a convolutional network for recognizing handwritten digits.

    The paper also described a full system for reading the amounts written on bank checks. It combined convolutional character recognizers with what the authors called graph transformer networks, which searched over the possible ways of cutting a written amount into characters and picked the most consistent reading. According to the abstract, the system was deployed commercially and read several million checks per day.

    That detail is easy to skip, but it says something about where deep learning came from. Long before image classification contests, convolutional networks were earning money by reading digits that bank clerks would otherwise have typed by hand.

    Tesseract and the Classic Pipeline

    Printed text was handled by a different line of engines. Tesseract, probably the best known, was developed at Hewlett-Packard between 1984 and 1994. It was entered in the 1995 UNLV Annual Test of OCR Accuracy as an HP research prototype, then sat unused until HP released it as open source in late 2005. Ray Smith, its original developer, described its design in a 2007 paper at the International Conference on Document Analysis and Recognition (ICDAR).

    The classic Tesseract pipeline shows what OCR looked like before deep learning took over. First the page is binarized into black and white. Then the engine finds connected blobs of ink, groups them into text lines (including lines that are slightly curved or skewed), splits lines into words and words into candidate characters. Each candidate is matched against learned character shapes, and a dictionary helps choose between close alternatives.

    Every stage in this chain can fail on its own. A coffee stain merges two letters into one blob. A tight font makes «rn» look like «m». An error early in segmentation cannot be repaired later, because the classifier only ever sees the pieces it was given.

    Lines Instead of Characters

    The fix was to stop cutting text into characters at all. In 2015 Baoguang Shi, Xiang Bai and Cong Yao proposed the CRNN, published in IEEE Transactions on Pattern Analysis and Machine Intelligence in 2017. A convolutional network reads an image of a whole word or line and produces a sequence of feature columns from left to right. A bidirectional LSTM reads those columns, and a Connectionist Temporal Classification (CTC) layer turns the output into text.

    CTC was built for speech, where nobody marks which audio frame belongs to which sound. A text line has the same problem in space. CTC lets the network learn from an image and its transcript alone, adding a special blank symbol and summing over every alignment that collapses to the correct string. The authors pointed out that the model could be trained on word-level labels, with no annotation of where individual characters were. Tesseract moved in this direction too: version 4, released in 2018, added an LSTM based line recognizer.

    Transformers came next. TrOCR (Minghao Li and colleagues at Microsoft, AAAI 2023) used a pre-trained image transformer as the encoder and a pre-trained text transformer as the decoder, generating wordpieces one at a time. It dropped both the convolutional backbone and the external language model, and the paper reported state-of-the-art results on printed, handwritten and scene text.

    Case: Two Words per CAPTCHA

    By the mid 2000s, large book digitization projects were running into a hard limit. OCR handled clean modern print well, but old, faded or damaged pages produced words no engine could read with confidence. Luis von Ahn and colleagues at Carnegie Mellon turned this into a security system. Their paper «reCAPTCHA: Human-Based Character Recognition via Web Security Measures» appeared in Science in 2008.

    The idea was to show each user two words. One was a control word whose answer was known. The other was a word that OCR programs had failed to read. If the user typed the control word correctly, their answer for the unknown word counted as a vote, and a reading was accepted once it collected enough votes (the paper used a threshold of 2.5 votes). The authors reported word accuracy above 99 percent, matching the standard of professional transcribers who type each text twice and compare. At the time the system ran on more than 40,000 websites and had transcribed over 440 million words.

    The case is a reminder that for most of OCR’s history the hard examples were solved by people. The machine did the easy pages and passed the rest to someone else.

    Layout Is Part of the Meaning

    Reading text correctly is only half the job. Consider a receipt. The string «12.50» could be the price of one item, the subtotal, the tax or the total, and the only clue is where it sits on the page and what is written next to it. A language model that sees the OCR output as one flat sequence loses that information.

    LayoutLM (Yiheng Xu and colleagues at Microsoft Research Asia, KDD 2020) addressed this directly. It took the BERT architecture and added two-dimensional position embeddings: alongside each word, the model receives the coordinates of the word’s bounding box on the page. It was pre-trained on about 11 million scanned documents from the IIT-CDIP collection using a masked language modeling task, so the model learned that words in certain positions tend to go with certain other words.

    The gains were large on tasks where layout matters. On FUNSD, a form understanding benchmark, LayoutLM reached an F1 score of 0.79, against 0.71 for RoBERTa-Large, which sees only the text. On the SROIE receipt extraction task it reached 96.0 percent.

    Skipping the OCR Step

    LayoutLM still depends on an OCR engine to supply the words and their boxes, and whatever that engine gets wrong reaches the model as fact. Donut (Geewook Kim and colleagues at NAVER CLOVA, ECCV 2022) removed the dependency. It is a transformer that reads the raw document image and writes its output directly, often as structured text such as a list of fields and values. The authors listed three reasons for dropping OCR: its computational cost, its poor flexibility across languages and document types, and the way its errors propagate into everything downstream.

    Training such a model needs a huge amount of document images with known text, so the team also released SynthDoG, a generator of synthetic documents in several languages. Pre-training taught Donut to read; fine-tuning taught it particular tasks such as receipt parsing, document classification or answering questions about a page.

    Question answering is now one of the main ways these systems are evaluated. DocVQA, introduced by Minesh Mathew, Dimosthenis Karatzas and C. V. Jawahar at WACV 2021, asks questions about real document images, and answering many of them requires reading a table or connecting a label to a value printed elsewhere on the page. Large multimodal language models have since been trained on the same kind of data, and many document pipelines now send the page image straight to one of them.

    Case: A Scanner That Rewrote the Numbers

    In 2013 the German computer scientist David Kriesel noticed that numbers in documents scanned on Xerox WorkCentre machines did not always match the originals. A 6 could become an 8. This happened only when scanning, not when copying, and the altered pages looked completely normal.

    The cause was not OCR but the JBIG2 compression standard. In one of its modes, JBIG2 finds patches of the image that look alike and stores a single copy, reusing it everywhere it appears. On small, low resolution print, a 6 and an 8 were similar enough to be treated as the same patch. Xerox confirmed that JBIG2 was responsible and released a patch that disabled the pattern matching option.

    The scanner did exactly what document models are now asked to do: it decided which marks on a page were the same symbol. It just did it without saying so.

    Reflection

    Old OCR failed loudly. When Tesseract misread a smudged line, the output was a string of broken characters like «T0taI: $1Z.5O», and any person who looked at it knew to check the paper. The Xerox case shows the other kind of failure, where the system replaces one clean symbol with another clean symbol and nothing looks wrong. Models that go straight from image to fluent, structured output tend to fail in that second way, because they produce text that looks finished even when the image was unclear. As these systems take over invoices, contracts and medical forms, the useful question is less how often they are right and more whether a person can tell when they are wrong. A confidence score per field, or a link back to the exact region of the page each value came from, can be worth more than another point of benchmark accuracy.

    By: Max Johnson B.

  • Speech Recognition: From Aligning Sounds to Transcribing 680,000 Hours of Audio

    Sound Has No Spaces

    Automatic speech recognition takes an audio signal and returns the words that were spoken. Written text arrives already cut into letters and words. Speech does not. A recording is a continuous wave, sampled thousands of times per second, and nothing in it marks where one word ends and the next begins. People also blur sounds together, drop syllables, hesitate, restart sentences and talk over each other.

    Most systems do not work on the raw wave. They first convert it into a spectrogram, usually on the mel scale, which spaces frequencies the way human hearing does. The audio becomes a sequence of short frames, typically one every 10 milliseconds, and each frame is a vector describing how much energy sits in each frequency band. A three second clip is about 300 frames. The sentence spoken in it might be eight words, or forty characters.

    That mismatch is the central problem. The input is long, the output is short, and nobody has told the model which frames belong to which letter.

    Hidden Markov Models and Forced Alignment

    For roughly three decades the answer was a pipeline. An acoustic model scored how well each frame matched small units of sound, usually context dependent phones. A pronunciation dictionary mapped words to sequences of phones. A language model, normally an n-gram model, scored how likely a word sequence was. A hidden Markov model tied everything together by treating speech as a walk through phone states, and a decoder searched for the word sequence with the best combined score.

    For most of that period the acoustic model was a Gaussian mixture model. In 2012 Geoffrey Hinton and colleagues from the University of Toronto, Microsoft, Google and IBM published a joint article in IEEE Signal Processing Magazine reporting that deep neural networks, used in place of the Gaussian mixtures, reduced error rates substantially across several large tasks. The hybrid DNN and HMM system became the industry standard almost immediately.

    The hybrid still needed a frame level alignment to train on. Someone, or more often an older model, had to decide that frames 41 to 47 were the sound /k/. Every component was trained separately, and each one brought its own assumptions and its own expert knowledge.

    Connectionist Temporal Classification

    In 2006 Alex Graves, Santiago Fernández, Faustino Gomez and Jürgen Schmidhuber presented Connectionist Temporal Classification (CTC) at ICML. The paper’s subtitle states the goal: labelling unsegmented sequence data with recurrent neural networks. CTC lets a network learn from pairs of audio and transcript without any alignment between them.

    The trick is an extra output symbol called the blank. At every frame the network outputs a probability distribution over the characters plus the blank. A sequence of frame outputs is turned into text by a fixed rule: merge repeated symbols, then delete blanks. So «hh_e_ll_llo» and «h_eel_l__o» both collapse to «hello». The blank is what allows a double letter, because «ll» with nothing between them would merge into a single «l».

    Many frame sequences collapse to the same transcript. CTC defines the probability of a transcript as the sum over all of them, and a dynamic programming algorithm, similar to the forward and backward passes used for hidden Markov models, computes that sum efficiently. The loss is the negative log of this probability. The network never learns where each letter is. It only learns to put its probability mass on paths that collapse to the right answer.

    In the original paper, a bidirectional LSTM trained with CTC on the TIMIT phoneme benchmark outperformed both a baseline HMM and a hybrid HMM and RNN system.

    The Independence Assumption

    CTC has a known weakness. It treats each frame’s output as conditionally independent of the others, given the audio. The network cannot directly use the fact that it just emitted «q» to make «u» more likely. Any knowledge of spelling or grammar has to come from the acoustic evidence alone or be added afterward.

    In practice CTC models are almost always decoded with a beam search that adds an external language model. Baidu’s Deep Speech (Hannun and colleagues, 2014) used exactly this recipe: a recurrent network trained end to end with CTC on several thousand hours of speech, decoded together with an n-gram language model, and no phone dictionary anywhere.

    Graves proposed a fix in 2012 called the RNN Transducer. It adds a prediction network that reads the labels emitted so far, so each output depends on previous outputs as well as on the audio. Transducers keep the property that matters most for live dictation: they process audio left to right and can emit words as they arrive. This is why they became common in streaming, on device recognition.

    Listening, Attending and Spelling

    A different route came from machine translation. Listen, Attend and Spell (Chan, Jaitly, Le and Vinyals, ICASSP 2016) used an encoder to read the spectrogram and an attention based decoder to produce characters one at a time, each step conditioned on everything produced so far. There is no blank symbol and no explicit alignment. The attention weights learn, in effect, where to look in the audio for the next character.

    Attention models write more fluent text because the decoder is itself a language model. The cost is that they need the whole utterance before decoding starts, and they can fail in ways CTC does not, such as skipping a phrase or repeating one when attention loses its place. Many production systems combined both: a shared encoder trained with a CTC loss and an attention loss at the same time, where the CTC term pushes alignments to stay monotonic.

    Case: Human Parity on Switchboard

    In October 2016 Microsoft researchers led by Wayne Xiong released a paper titled «Achieving Human Parity in Conversational Speech Recognition». They measured professional transcribers on the Switchboard benchmark, recorded telephone conversations between strangers, and found a word error rate of 5.9 percent. Their own ensemble of acoustic and language models reached the same figure, and the journal version later reported 5.8 percent.

    The result was real, but it was a result about one benchmark. Switchboard is English telephone audio from the 1990s, and models had been tuned on it for over twenty years. A system that matched people there could still struggle badly on a noisy kitchen recording, a heavy accent or a medical dictation.

    Weak Supervision at Scale

    Two lines of work attacked that brittleness. One was self-supervision. wav2vec 2.0 (Baevski, Zhou, Mohamed and Auli, NeurIPS 2020) pre-trained a model on 53,000 hours of unlabeled audio by masking parts of the signal and asking the network to identify the right hidden segment. Fine-tuned on just ten minutes of labeled speech, it reached word error rates of 4.8 and 8.2 percent on the clean and other test sets of LibriSpeech.

    The other line was OpenAI’s Whisper (Radford, Kim, Xu, Brockman, McLeavey and Sutskever, ICML 2023). Instead of clean, carefully transcribed corpora, the authors collected 680,000 hours of audio paired with transcripts found on the internet. Those transcripts were imperfect, which is what «weak supervision» refers to. About 117,000 hours covered 96 languages other than English, and 125,000 hours were translation data, audio in one language paired with English text.

    The model itself is a standard encoder and decoder transformer. It takes 30 second windows of log mel spectrogram and generates text tokens. Special tokens at the start of the output tell it the language, whether to transcribe or translate into English, and whether to predict timestamps, so one network handles all these tasks. The paper reported that on LibriSpeech Whisper performed about the same as a strong supervised model, but across other English datasets it made far fewer errors without being trained on any of them. The authors described the result as approaching human accuracy and robustness.

    Case: Sentences That Were Never Spoken

    A decoder that writes fluent text can also write fluent text that is not in the audio. In 2024 Allison Koenecke and colleagues presented «Careless Whisper: Speech-to-Text Hallucination Harms» at the ACM FAccT conference. They ran Whisper on more than 13,000 audio segments from AphasiaBank, recordings of people with aphasia and of a control group. In experiments from 2023, roughly 1 percent of transcriptions contained whole phrases or sentences that did not exist in the audio, and 38 percent of those hallucinations included explicit harms such as violent language, invented associations or false authority. Hallucinations were more frequent for speakers with longer pauses between words. The authors noted that the hallucination rate dropped in later versions of the service.

    This was not the first fairness problem found in recognition. Koenecke had also led a 2020 study in PNAS testing commercial systems from Amazon, Apple, Google, IBM and Microsoft. Averaged across the five, the word error rate was 0.35 for Black speakers and 0.19 for white speakers, and the gap remained on identical phrases spoken by both groups.

    Closing Thought

    The two kinds of error tell you something about the architectures behind them. A CTC model that cannot hear a word tends to produce garbled letters, and the garbage is visible to anyone who reads it. A decoder that is also a language model tends to fill the gap with something plausible, and plausible text is exactly the kind a reader does not check. Word error rate counts both mistakes the same way, but they are not equally dangerous. In a medical note or a court transcript, an obviously broken sentence prompts someone to listen to the recording again. A clean sentence that was never said does not.

    By: Max Johnson B.

  • Human Pose Estimation: Finding the Skeleton Inside a Photograph

    A Skeleton Drawn Over a Picture

    Human pose estimation is the task of locating a person’s joints in an image or video: shoulders, elbows, wrists, hips, knees, ankles, and usually a few points on the face. The output is a small set of coordinates that can be connected into a stick figure. In 2D the coordinates are pixel positions. In 3D they are positions in space, usually measured relative to the hips.

    People do this without thinking. For a computer it is hard. Limbs hide behind the torso or behind other people. Clothing changes the visible outline of the body. A raised arm and a lowered arm can look almost identical from the side. When several people stand close together, the model has to decide not only where the elbows are but which elbow belongs to which person.

    The output is tiny. A video of someone exercising becomes a few dozen numbers per frame, and a physiotherapy app, a sign language system or a sports analytics tool can work on those numbers without caring about the lighting or what the person is wearing.

    Kinect and the Depth Camera

    The first time pose estimation reached millions of homes was the Kinect sensor for the Xbox 360, released in 2010. The method behind it was published by Jamie Shotton and colleagues at Microsoft Research at CVPR 2011, where it won the best paper award. It did not use deep learning. It used a depth camera and a randomized decision forest.

    The trick was to turn pose estimation into per-pixel classification. Each pixel in the depth image was assigned to one of 31 body parts using simple features that compared the depth at nearby offsets. Joint positions were then estimated by finding the densest clusters of pixels for each part. To train the forest, the team rendered a very large set of synthetic depth images of bodies with different shapes and poses, built from motion capture data. The system ran at around 200 frames per second on the console’s hardware, which left most of the machine free for the game itself.

    The limitation was the sensor. Depth made separating the person from the background almost free, but it only worked indoors, at short range, with that hardware.

    Heatmaps Instead of Coordinates

    The first well-known deep learning approach was DeepPose, by Alexander Toshev and Christian Szegedy at Google (CVPR 2014). It treated the problem as regression: a convolutional network looked at the image and directly output the x and y coordinates of each joint, followed by a cascade of networks that refined each estimate on a zoomed crop.

    Direct regression turned out to be hard to train well. The same year, Jonathan Tompson and colleagues (NeurIPS 2014) had the network predict a heatmap for each joint instead: an image-sized map where the value at each pixel is the likelihood that the joint is there. Training targets became small Gaussian blobs centered on the annotated joints. This kept the spatial structure of the image all the way to the output, and it let the network express uncertainty, for example two bright spots when it could not tell a left wrist from a right one.

    Heatmaps became the standard for years. Convolutional Pose Machines (Wei et al., CVPR 2016) refined them over several stages, each stage seeing the previous stage’s beliefs. The Stacked Hourglass network (Newell, Yang and Deng, ECCV 2016) repeatedly downsampled and upsampled the features so that the model could combine the global layout of the body with precise local detail.

    Top-Down and Bottom-Up

    Images with many people forced a choice between two pipelines. The top-down approach runs a person detector first, crops each person, and estimates a single pose inside every box. It is accurate, since each crop is normalized in scale, but its cost grows with the number of people, and it fails when the detector misses someone or merges two people into one box.

    The bottom-up approach finds every joint in the image first and then groups them into people. The best-known example is OpenPose, from Zhe Cao, Tomas Simon, Shih-En Wei and Yaser Sheikh at Carnegie Mellon (CVPR 2017). Besides joint heatmaps, their network predicted Part Affinity Fields: 2D vector fields that point along each limb, from shoulder to elbow, from elbow to wrist. To decide whether a given elbow and wrist belong to the same arm, the algorithm integrates the field along the line between them. If the vectors line up with that line, the pair is probably a real limb. The OpenPose documentation notes that the runtime for body keypoints does not depend on how many people are in the image, which made it popular for crowded scenes.

    Keeping the Resolution High

    On benchmarks, top-down methods kept winning. A surprisingly plain design called Simple Baselines (Xiao, Wu and Wei, ECCV 2018) took a ResNet and added a few deconvolution layers to produce heatmaps, and it matched or beat far more complicated architectures. HRNet (Sun, Xiao, Liu and Wang, CVPR 2019) changed the backbone itself: instead of shrinking the image and then recovering resolution, it kept a high-resolution branch alive through the whole network and exchanged information with lower-resolution branches in parallel.

    Transformers arrived later. ViTPose (Xu, Zhang, Zhang and Tao, NeurIPS 2022) used a plain Vision Transformer as the encoder with a light decoder on top. Its largest version, with a ViTAE-G backbone, reached 80.9 AP on the COCO test-dev set as a single model. The paper compares this with the previous best entry, UDP++, which reached 80.8 AP by ensembling 17 models.

    On the other end of the scale, models such as Google’s BlazePose (Bazarevsky et al., 2020) were designed to run in real time on phones, predicting 33 keypoints including points on the hands and feet for fitness and yoga applications.

    Scoring a Pose

    Measuring success is less obvious than it seems, because a few pixels of error on a hip is not the same as a few pixels on an eye. The MPII Human Pose dataset (Andriluka, Pishchulin, Gehler and Schiele, CVPR 2014) contains about 25,000 images taken from YouTube videos, with over 40,000 annotated people across 410 activities and 16 joints per person. It is usually scored with PCKh@0.5: a joint counts as correct if it lands within half the length of the person’s head segment from the true position.

    COCO uses 17 keypoints and a metric called Object Keypoint Similarity (OKS). OKS plays the role that intersection over union plays in object detection. It turns the distance for each keypoint into a score between 0 and 1, scaled by the size of the person and by a per-keypoint constant that reflects how consistently human annotators label that joint. Eyes get a tight tolerance and hips a looser one, because people disagree more about where a hip is. Average precision is then computed over a range of OKS thresholds. Each keypoint also carries a visibility flag, so a joint hidden behind another person can still be labeled with a guessed position.

    Lifting a Pose Into 3D

    Recovering depth from a single photo is ambiguous in principle: many 3D poses project to the same 2D image. The standard training data comes from motion capture studios. Human3.6M (Ionescu, Papava, Olaru and Sminchisescu, TPAMI 2014) recorded 3.6 million 3D poses from professional actors performing everyday scenarios, synchronized with ordinary video cameras.

    A useful result came from Julieta Martinez and colleagues at ICCV 2017. Instead of predicting 3D joints from pixels, they fed only the 2D joint coordinates into a small fully connected network and asked it to output the 3D positions. Given ground-truth 2D joints, this simple lifting network reached an average error of roughly 4.5 centimeters per joint on Human3.6M. With 2D joints from a real detector the error rose substantially. Their conclusion was that a large part of the remaining error in 3D pose estimation came from the 2D detection step, not from reasoning about depth.

    The caveat is that Human3.6M was recorded in one studio with a handful of actors. Models that look excellent on it can struggle outdoors, with unusual camera angles, or with body shapes the actors did not cover.

    Case: Two Hundred Frames of a Mouse

    One of the most productive uses of pose estimation has nothing to do with humans. Neuroscientists who study behavior used to track animals by attaching reflective markers or by labeling video frame by frame. In 2018, Alexander Mathis, Mackenzie Mathis and colleagues published DeepLabCut in Nature Neuroscience. It took a network pre-trained on human pose and ImageNet data and fine-tuned it on body parts the researcher chose: the paw of a mouse, the tip of a fly’s leg, the whiskers of a rat.

    The key finding was the amount of labeling required. With roughly 200 labeled frames, the tracking accuracy on new frames was comparable to that of a human annotator. The network already knew what limbs and joints look like in general, and only needed to learn the specific animal.

    Closing Thought

    Every pose estimation system starts by deciding what a body is. COCO says it is 17 points. MPII says 16. BlazePose says 33. Those lists were chosen by people for practical reasons, and the model can only report the joints it was given. A hand is a single wrist point in COCO, so a system built on it cannot tell a fist from an open palm. A body that does not match the template, such as a person with an amputation or someone seated in a wheelchair, still gets a full skeleton drawn over it, with the missing parts guessed. The coordinates look precise either way. Before trusting the output of a pose model, it is worth asking which skeleton it was taught and whether the people in front of the camera fit inside it.

    By: Max Johnson B.

  • Neural Radiance Fields and 3D Gaussian Splatting: Rebuilding a Scene From a Pile of Photos

    Photos From Places the Camera Never Stood

    Take fifty photos while walking around a statue in a park. A classic photogrammetry pipeline will turn them into a mesh with a texture painted on top, and the result usually looks fine from a distance and wrong up close: leaves become flat blobs, glass turns opaque, and anything shiny looks like plastic. The task that Neural Radiance Fields set out to solve is slightly different. The goal is not a clean mesh. The goal is to produce a new photograph from a viewpoint where nobody held a camera, and to make it look like a real photograph.

    This problem is called novel view synthesis, and for decades it was handled with light fields, image-based rendering and multi-plane images. In 2020 a paper by Ben Mildenhall, Pratul Srinivasan, Matthew Tancik, Jonathan Barron, Ravi Ramamoorthi and Ren Ng changed what people expected from it. «NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis» was presented as an oral at ECCV 2020 and received a Best Paper Honorable Mention. Three years later, a very different method called 3D Gaussian Splatting reached similar quality at real-time frame rates. The two papers make opposite bets about how a scene should be stored, and comparing them is the clearest way to understand the field.

    A Scene Stored Inside a Network

    NeRF represents a whole scene with one fully connected network. The input is a 3D position plus a viewing direction (five numbers in total, since a direction can be written with two angles). The output is a density at that point and the color emitted from that point toward the viewer. Density depends only on position, while color is allowed to depend on direction as well, which is how the model reproduces reflections and highlights that move when the camera moves. In the original paper the network has eight layers of 256 units, and the scene lives entirely in its weights. There are no voxels, no triangles and no point cloud.

    The only training data is a set of photos with known camera poses. In practice those poses usually come from a structure-from-motion tool such as COLMAP, which matches features across images and estimates where each camera was. If the poses are wrong, NeRF has no way to fix them, and the reconstruction blurs.

    Volume Rendering as the Loss

    To produce a pixel, NeRF shoots a ray from the camera through that pixel and samples points along it. At each point it asks the network for density and color, then blends the colors front to back, with each sample weighted by its own density and by how much light survived the samples in front of it. This is the standard volume rendering equation from computer graphics, written as a sum.

    The important property is that every step of this sum is differentiable. The rendered pixel can be compared with the real pixel in the photo, and the error flows back through the blending into the network weights. Nobody tells the model where surfaces are. Surfaces appear because putting density in the right places is the only way to make every training photo come out right at the same time.

    Sampling uniformly would waste most queries on empty air, so NeRF uses two networks. A coarse network evaluates 64 samples per ray, and its output guides where a fine network places 128 more samples, concentrated near the surfaces the coarse pass found.

    The Positional Encoding Trick

    Fed raw coordinates, an MLP produces blurry scenes. Neural networks prefer smooth functions, a tendency called spectral bias, and a photograph full of bark texture and text on signs is not smooth. NeRF’s fix is to pass each coordinate through sines and cosines at increasing frequencies before it enters the network: ten frequency bands for position and four for direction. With this mapping, small changes in position can produce large changes in the input, and the network can represent fine detail.

    The authors showed in their ablations that removing this encoding visibly degrades results. A companion paper by Tancik and colleagues at NeurIPS 2020, «Fourier Features Let Networks Learn High Frequency Functions in Low Dimensional Domains», gave the theoretical explanation using neural tangent kernel analysis. The idea of mapping low-dimensional inputs to a high-frequency feature space has since spread to many other coordinate-based networks.

    The Speed Problem

    The original NeRF was slow at everything. Training a single scene took roughly one to two days on an NVIDIA V100, and rendering one image meant hundreds of network evaluations for each of hundreds of thousands of pixels. The quality was striking, but nobody was going to walk around a NeRF in a headset.

    The follow-up work attacked this from several sides. Plenoxels (Fridovich-Keil and colleagues, CVPR 2022) removed the neural network entirely and optimized a sparse voxel grid directly, which showed that most of NeRF’s quality came from differentiable volume rendering rather than from the MLP. Instant-NGP by Thomas Müller, Alex Evans, Christoph Schied and Alexander Keller (SIGGRAPH 2022) replaced most of the large MLP with a multiresolution hash table of learned feature vectors feeding a very small network. Training dropped from days to seconds or minutes, and the paper won a SIGGRAPH best paper award. On the quality side, Mip-NeRF (Barron and colleagues, 2021) reasoned about cones instead of thin rays to remove aliasing, and Mip-NeRF 360 extended it to unbounded outdoor scenes. Mip-NeRF 360 gave the best images of its time, but it still needed up to 48 hours of training per scene and rendered at a small fraction of a frame per second.

    Millions of Gaussians Instead of a Network

    In 2023, Bernhard Kerbl, Georgios Kopanas, Thomas Leimkühler and George Drettakis published «3D Gaussian Splatting for Real-Time Radiance Field Rendering» in ACM Transactions on Graphics (SIGGRAPH 2023). It keeps the training setup of NeRF (posed photos and a rendering loss) and drops the neural network.

    The scene becomes a large set of 3D Gaussians, which are ellipsoid-shaped blobs. Each Gaussian has a position, a covariance written as a rotation and a scale (so it can be stretched into a needle or flattened into a disc), an opacity, and a color stored as spherical harmonic coefficients so that it can change with viewing direction. Optimization starts from the sparse point cloud that COLMAP already produces. During training, the method clones Gaussians in regions that are under-reconstructed, splits large ones that cover too much detail, and removes ones that become nearly transparent. A finished scene often contains millions of them.

    Rendering does not march rays. Each Gaussian is projected onto the screen as a 2D ellipse, the screen is divided into 16 by 16 pixel tiles, the Gaussians in each tile are sorted by depth on the GPU, and their colors are blended front to back. This is rasterization, the same family of operations that graphics hardware was built for, and the whole pipeline is still differentiable. The paper reports real-time rendering (at least 30 frames per second) at 1080p on unbounded scenes, with quality comparable to Mip-NeRF 360 and training measured in minutes.

    Case: A Neighborhood From 2.8 Million Images

    Scaling these methods to a city is a different problem from scaling them to a statue. Block-NeRF, a CVPR 2022 paper from Matthew Tancik and colleagues at UC Berkeley and Waymo, reconstructed a neighborhood of San Francisco from 2.8 million images collected by Waymo vehicles over about three months. A single network could not hold that, so the authors split the area into blocks, trained a separate NeRF for each one, and blended the neighboring blocks at render time.

    The images were taken at different times of day, under different weather, with cars and pedestrians moving through them. Block-NeRF borrowed appearance embeddings from earlier work (NeRF in the Wild) so each image could have its own lighting without corrupting the shared geometry, and it masked out moving objects. For Waymo the use is concrete: a reconstructed street can be re-rendered from new viewpoints to test autonomous driving software in simulation.

    Explicit Points Bring Explicit Problems

    Gaussian splatting is fast because the scene is explicit, and that also brings the main drawbacks. Millions of Gaussians, each with dozens of spherical harmonic coefficients, take a lot of memory, and a large outdoor scene can reach hundreds of megabytes. A whole line of research now works on compressing and pruning splats. Gaussians also do not define a clean surface, so extracting a mesh for physics or 3D printing requires additional methods.

    Both families share other limits. They need many photos with accurate poses, and with too few views they produce «floaters», small clouds of density hanging in the air that look right from the training cameras and wrong from anywhere else. The base methods assume a static scene. Lighting is baked into the colors, so you cannot move the sun in a reconstructed garden without extra modeling. Dynamic and relightable variants exist, but they add complexity that the original papers avoided.

    On the practical side, splatting moved into products quickly. Phone apps such as Niantic’s Scaniverse, Polycam and Luma AI let people capture splats with a phone, and Zillow has started showing splat-based tours on some of its real estate listings.

    A Final Observation

    The neural network was the most visible part of NeRF, and it turned out to be the part that could be removed. Plenoxels removed it, and Gaussian splatting removed it more completely, yet both kept the same core: a differentiable renderer and a loss that compares rendered pixels with real photos. What NeRF contributed was the idea of reconstructing a scene by making a renderer reproduce the evidence, letting geometry fall out of that pressure. The representation inside can be a network, a grid or a cloud of ellipsoids, and the field keeps swapping it for whatever the hardware runs fastest.

    By: Max Johnson B.