Blog

  • Normalizing Flows: Generative Models That Can Be Run Backwards

    A Generator With an Exact Likelihood

    Most generative models make a trade. A GAN produces sharp images but cannot tell you how probable any particular image is. A variational autoencoder gives you a number, but only a lower bound on the true likelihood. Normalizing flows refuse that trade. They generate samples and they also compute the exact probability density of any input, and they do it with one network.

    The trick is invertibility. A flow takes a sample from a simple distribution, usually a standard Gaussian, and pushes it through a chain of transformations until it looks like data. Because every transformation can be undone, you can also take a real image, run the chain backwards, and land on the exact Gaussian point that would have produced it. Once you know that point, its probability under the Gaussian is a formula you learned in a statistics course.

    The price of this property is architectural. Every layer must be invertible, and you must be able to compute how much it stretches or squeezes space. Most of the history of flows is the story of finding layers that satisfy both conditions without being too weak to model anything interesting.

    The Change of Variables Formula

    Suppose a function f maps a data point x to a latent point z. If f stretches a small region of space, probability mass gets spread thinner, so the density drops. If it compresses a region, the density rises. The amount of stretching at a point is measured by the determinant of the Jacobian, the matrix of all partial derivatives of f. The log-likelihood of x is the log-density of z under the Gaussian plus the log of the absolute value of that determinant.

    That equation is the whole training objective. You feed real data through the network, compute the two terms, and maximize their sum by gradient descent. There is no discriminator and no bound with a gap you cannot measure.

    The difficulty is computational. The determinant of a general D by D matrix costs on the order of D cubed operations. For a 256 by 256 color image, D is close to 200,000. Computing that determinant once per image per training step is out of the question, so flows are built from layers whose Jacobians have a special structure, most often triangular, where the determinant is the product of the diagonal.

    Coupling Layers

    The idea of building densities by composing simple invertible maps had appeared in statistics papers by Esteban Tabak and colleagues around 2010 and 2013. The version that made it practical for deep learning came from Laurent Dinh, who introduced NICE in 2014 and then, with Jascha Sohl-Dickstein and Samy Bengio, Real NVP, published at ICLR 2017. Around the same time, Danilo Rezende and Shakir Mohamed used flows at ICML 2015 to make the approximate posteriors of variational inference more flexible, and the name «normalizing flow» spread from that paper.

    The coupling layer in Real NVP works like this. Split the input into two halves. Leave the first half unchanged. Use it as input to an ordinary neural network, which outputs a scale and a shift, and apply them to the second half: multiply by the exponential of the scale, add the shift. To invert the layer, you take the unchanged first half, recompute the same scale and shift, subtract and divide. The inner network never needs to be inverted, so it can be as large and nonlinear as you like.

    The Jacobian of this layer is triangular, and its log-determinant is the sum of the scale outputs. One layer only changes half the variables, so the next layer swaps the roles of the halves. Stack enough of these and every dimension gets transformed many times, each step cheap to compute in both directions.

    Glow and the 1×1 Convolution

    In 2018, Diederik Kingma and Prafulla Dhariwal at OpenAI published Glow at NeurIPS. Real NVP had mixed the two halves between layers with fixed permutations. Glow replaced them with an invertible 1×1 convolution, a learned linear map across channels. Since it acts only on the channel dimension, its determinant is cheap, and the paper parameterized the weight matrix through an LU decomposition to make it cheaper still. Glow also dropped batch normalization in favor of a simpler «actnorm» layer with per-channel scale and bias.

    The likelihoods improved. On 32 by 32 ImageNet, test bits per dimension went from 4.28 with Real NVP to 4.09 with Glow. What drew more attention were the faces. Trained on CelebA-HQ at 256 by 256 pixels, Glow produced realistic portraits, and because each face had an exact latent code, you could interpolate between two people or move along a direction associated with smiling or age.

    Autoregressive Flows

    A second family takes its structure from autoregressive models. In a masked autoregressive flow (Papamakarios, Pavlakou and Murray, NeurIPS 2017), each dimension is transformed using a scale and shift computed from all the dimensions that come before it. The Jacobian is again triangular. Evaluating the density of a data point is fast and parallel, because all the earlier values are known. Sampling is slow, because each dimension has to wait for the previous ones.

    The inverse autoregressive flow, introduced by Kingma and collaborators in 2016, flips the arrangement. Sampling becomes parallel and density evaluation becomes sequential. Neither design is fast in both directions, so the choice depends on whether you mostly evaluate densities or mostly draw samples.

    Case: Parallel WaveNet

    The second option went into production at DeepMind. The original WaveNet produced speech with high quality but generated audio one sample at a time, at 24,000 samples per second, which was far too slow to serve. In Parallel WaveNet (van den Oord and colleagues, ICML 2018), the team trained an inverse autoregressive flow to imitate a pretrained WaveNet, a form of distillation where the slow autoregressive model is the teacher and the flow is the student.

    Because the flow generates all samples of a waveform in parallel, the paper reports generation more than 20 times faster than real time, and a speedup of more than 1000 times over the original WaveNet, with no measurable loss in quality. The flow’s own weakness, slow likelihood evaluation, did not matter, because the student was trained by comparing its samples with the teacher’s judgments rather than by maximizing likelihood on recordings.

    Case: Sampling Molecules and Lattices

    Physics has a problem that flows fit well. Many systems have a known energy function, and the probability of a configuration follows the Boltzmann distribution, proportional to the exponential of minus the energy. Knowing the formula does not mean you can sample from it. Molecular dynamics and Markov chain Monte Carlo move in small steps and can spend enormous compute time stuck in one valley before crossing to another.

    Frank Noé, Simon Olsson, Jonas Köhler and Hao Wu published «Boltzmann generators» in Science in 2019. Their flow learns a map from a Gaussian to the configuration space of a molecular system and produces independent samples in one shot. Since the flow’s density is exact, each sample can be reweighted by the ratio between the true Boltzmann probability and the flow’s probability, so the results stay unbiased even when the flow is imperfect. They demonstrated it on condensed matter systems and a small protein.

    Lattice field theory took the same route. Michael Albergo, Gurtej Kanwar and Phiala Shanahan proposed in 2019 to use a Real NVP flow as the proposal distribution in a Metropolis sampler for a scalar field theory, with an accept or reject step correcting any error. Their motivation was critical slowing down, where standard samplers for lattice QCD become very expensive near the continuum limit. Later work by the same group built flows that respect gauge symmetry by construction. In both fields, the exact density is what makes the correction step possible.

    From Discrete Layers to Continuous Flows

    Coupling and autoregressive layers are restrictive. Each one has to be designed so its Jacobian stays triangular. In 2018, Ricky Chen and colleagues proposed neural ordinary differential equations, and FFJORD (Grathwohl and colleagues, ICLR 2019) used them to define a continuous normalizing flow. Instead of a stack of layers, a network defines a velocity field, and a point moves along it from noise to data over continuous time. The change in log-density becomes an integral of the trace of the Jacobian, which FFJORD estimated with a random projection trick (Hutchinson’s estimator), removing the need for triangular structure.

    The cost moved to the ODE solver, which made training slow. Flow matching, by Yaron Lipman and colleagues at ICLR 2023, removed most of that cost. Rather than simulating the ODE during training, the network regresses directly onto a target velocity along a chosen path between noise and data, in the simplest case a straight line. The resulting models are close cousins of diffusion models, and the paper showed that diffusion paths are special cases of its framework. Stable Diffusion 3, described by Patrick Esser, Robin Rombach and colleagues at ICML 2024, is trained with this straight-line formulation, called rectified flow.

    A Final Observation

    The exact likelihood turned out to be less useful in one place than people expected. In 2019, Eric Nalisnick and colleagues at DeepMind trained Glow on CIFAR-10, a set of photos of animals and vehicles, and found that it gave higher likelihood to SVHN, a set of house numbers it had never seen. The pattern repeated for other dataset pairs and for VAEs and PixelCNNs as well. Their analysis tied it to simple statistics of the images, like their variance, rather than their content. A precise number for how probable an image is did not mean the model knew whether the image belonged to its world.

    Where flows have held up is in settings where the density is used for computation rather than as a judgment of meaning: reweighting a molecular sample, correcting a Markov chain, comparing against a known energy. That is a narrower job than the one flows were first pitched for, and their descendants in image generation have mostly dropped strict invertibility. In physics, where an unbiased answer is worth more than a pretty one, being able to run the generator backwards is still the property people need.

    By: Max Johnson B.

  • Variational Autoencoders: Learning a Space of Possible Data Instead of a Single Copy

    A Compressor That Can Also Invent

    An ordinary autoencoder is a pair of networks trained on a simple task. The encoder squeezes an input, say a 64 by 64 face, into a short vector of numbers, and the decoder tries to rebuild the original face from that vector. If the reconstruction is good, the short vector must hold most of what mattered about the image. It has a strange weakness. Pick a random vector, hand it to the decoder, and the output is usually garbage.

    The reason is that nothing in the training asks the codes to be organized. The encoder is free to scatter faces across the code space in isolated clusters, with large empty regions between them that the decoder never saw during training.

    The variational autoencoder, or VAE, changes the training so that the code space becomes something you can sample from. It was introduced by Diederik Kingma and Max Welling in «Auto-Encoding Variational Bayes» (posted in December 2013 and presented at ICLR 2014), and in parallel by Danilo Rezende, Shakir Mohamed and Daan Wierstra at ICML 2014. Both papers arrived at the same model from the side of probabilistic inference rather than compression.

    Latent Variables and an Intractable Integral

    The probabilistic story goes like this. Assume every image x was produced by first drawing a hidden vector z from a simple distribution, usually a standard Gaussian, and then passing z through a decoder network that outputs a distribution over images. Training the model means making the observed images likely. The probability of one image is an average over every z that could have produced it, which is an integral over the whole latent space with a neural network inside it. Nobody can compute that integral exactly.

    The other direction is just as hard. Given an image, which z probably generated it? That is the posterior distribution, and by Bayes’ rule it also depends on the same impossible integral. Classical variational inference approximates it with a separate optimization for each data point, which is far too slow for millions of images.

    Kingma and Welling’s move was to train a second network, the encoder, that looks at an image and directly outputs the parameters of an approximate posterior: a mean and a variance for each latent dimension. One forward pass replaces a per-image optimization. This is called amortized inference: the cost of learning to infer is paid once and shared across all inputs.

    The Evidence Lower Bound

    The training objective is the evidence lower bound, usually shortened to ELBO. It is a quantity that sits below the true log probability of the data, so pushing it up pushes the true value up as well. It splits into two terms that are easy to read.

    The first is a reconstruction term: sample a z from the encoder’s distribution, decode it, and measure how well the result matches the input. The second is a Kullback-Leibler divergence between the encoder’s distribution and the standard Gaussian prior. This second term penalizes the encoder for placing codes far from the origin or for making them too narrow. Each image gets mapped to a small cloud of codes, and the KL term pushes all of those clouds to overlap with one shared bell curve.

    That pressure is what fills the empty regions. Because the clouds overlap, the decoder learns to produce something sensible across the whole neighborhood of the prior, and sampling z from a standard Gaussian gives plausible new images.

    The Reparameterization Trick

    There is a technical obstacle in the middle of all this. The reconstruction term requires sampling z, and a random sampling step has no gradient. Backpropagation cannot tell the encoder how to change its mean and variance if the only thing between them and the loss is a dice roll.

    The fix is short. Instead of sampling z directly from a Gaussian with mean μ and standard deviation σ, sample a noise value ε from a standard Gaussian, which does not depend on any parameter, and compute z = μ + σε. The randomness now enters from the side, and z is a deterministic, differentiable function of μ and σ. Gradients flow through it like through any other layer. The resulting estimator, which the paper named Stochastic Gradient Variational Bayes, can be optimized with the same stochastic gradient methods used for any network.

    This one line of algebra made deep latent variable models trainable with standard tools.

    Case: Molecules Drawn From a Continuous Space

    One of the best known applications came from chemistry. In 2018 Rafael Gómez-Bombarelli and colleagues published «Automatic Chemical Design Using a Data-Driven Continuous Representation of Molecules» in ACS Central Science. They trained VAEs on molecules written as SMILES strings, the text notation chemists use to describe a structure. One model learned from about 108,000 small molecules in the QM9 dataset, the other from 250,000 drug-like molecules taken at random from the ZINC database, with latent spaces of 156 and 196 dimensions.

    The attraction was that a discrete search over molecules became a continuous one. The authors trained a property predictor on top of the latent codes and then moved through the space with gradient-based optimization toward codes with better predicted properties, decoding the results back into candidate molecules. They chose a VAE over a plain autoencoder for the reason described above: a plain autoencoder left large dead areas that decoded into invalid strings.

    The results also show the limits. Depending on where they sampled, the fraction of decoded strings that were valid SMILES ranged from about 70 percent down to below 1 percent, and every output had to be checked with cheminformatics software such as RDKit. A smooth latent space did not guarantee that the decoder respected the grammar of chemistry, and much of the later work on molecular generation focused on decoders that build graphs or follow grammar rules so that invalid outputs cannot occur.

    Posterior Collapse

    VAEs have a characteristic failure. If the decoder is powerful enough to model the data on its own, the cheapest way to satisfy the ELBO is to ignore z entirely. The encoder outputs the prior for every input, the KL term drops to zero, and the decoder generates plausible data without using any information from the code. The code becomes useless.

    Samuel Bowman and colleagues ran into this when they paired a VAE with a recurrent language model decoder in «Generating Sentences from a Continuous Space» (CoNLL 2016). Without intervention, their model stored very little information in the latent variable. They used two remedies. KL annealing starts training with the KL weight at zero and raises it gradually, so the encoder learns to put information in z before the penalty applies. Word dropout replaces some of the decoder’s input words with an unknown token, which weakens the decoder and forces it to rely on the code. They reported that lowering the keep rate increased the information in z while the overall likelihood got somewhat worse.

    Turning the KL Weight Up

    If lowering the KL weight helps a VAE use its code, raising it does something else. In β-VAE (Higgins et al., ICLR 2017, from DeepMind), the KL term is multiplied by a factor β greater than one. The stronger pressure toward an independent Gaussian prior encouraged the model to dedicate separate latent dimensions to separate factors of variation. On images of simple shapes, one dimension might come to control position, another scale, another rotation. The price was blurrier reconstructions.

    This «disentanglement» line of research grew quickly, and in 2019 Francesco Locatello and colleagues tested it at scale in «Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations» (ICML 2019). They reimplemented six methods and six disentanglement metrics and trained more than 12,000 models on seven datasets. Their theoretical result was that unsupervised disentanglement is impossible without inductive biases on both the model and the data. Empirically, the methods did enforce the properties their losses encouraged, but well disentangled models could not be identified without some supervision, and random seeds and hyperparameters often mattered more than the choice of method.

    Discrete Codes and a Compressor for Diffusion

    Two later developments moved VAEs from being the generator to being a component. In «Neural Discrete Representation Learning» (NIPS 2017), Aaron van den Oord, Oriol Vinyals and Koray Kavukcuoglu replaced the continuous Gaussian code with a codebook of learned vectors. The encoder output is snapped to the nearest codebook entry, and gradients skip over the non-differentiable snapping step by being copied straight from the decoder input to the encoder output. The authors noted that this VQ-VAE avoids posterior collapse even with a strong autoregressive decoder. Those discrete codes later became tokens for transformer-based image and audio generators.

    The second development is the latent diffusion model of Rombach and colleagues (CVPR 2022), the architecture behind Stable Diffusion. Running diffusion directly on pixels is expensive, so they first train an autoencoder that compresses an image by a factor of 8 in each spatial direction, and the diffusion model works on those compressed codes. One of their variants is regularized with a slight KL penalty toward a standard normal, the same term as in a VAE, but with a weight small enough that its job is to keep the latent space well behaved rather than to allow sampling from the prior.

    Closing Thought

    The KL term in a VAE is often described as a regularizer, but it is easier to understand as a budget. It measures how many bits about the input the code is allowed to carry beyond what the prior already says. Set the budget near zero and the decoder learns to manage without the code. Raise it and the code becomes cleaner and more compressed while the reconstructions get blurrier. Posterior collapse, β-VAE, KL annealing and the tiny KL weight in latent diffusion are all choices about the same number. A VAE does not decide on its own what its latent space should mean. That decision is mostly made by whoever chooses how much information the code is allowed to carry.

    By: Max Johnson B.

  • Word Embeddings: How word2vec and GloVe Turned Meaning Into Geometry

    A Word Is a Point in Space

    A computer does not know that «cat» and «kitten» have anything in common. To a program, words are strings of characters, and the classic way to feed them to a model was the one-hot vector: a list as long as the vocabulary, all zeros except for a single 1 in the position assigned to that word. With a vocabulary of 100,000 words, every word becomes a vector of 100,000 numbers, and every pair of words is exactly as far apart as every other pair. «Cat» is as distant from «kitten» as it is from «carburetor.»

    A word embedding replaces that list with a short, dense vector, typically a few hundred numbers, learned from text. The goal is that words used in similar ways end up near each other. Once that works, distance means something, and a model that learned a fact about «kitten» can apply part of it to «cat» without ever having seen the second word in that context.

    The Company a Word Keeps

    Zellig Harris argued in his 1954 paper «Distributional Structure» that words with similar meanings tend to occur in similar environments. J. R. Firth put it more memorably in 1957: «You shall know a word by the company it keeps.»

    The first computational versions counted. Build a huge table where each row is a word and each column is a context word, fill it with co-occurrence counts from a corpus, and compress it with a matrix factorization such as singular value decomposition. Latent Semantic Analysis, popular in information retrieval in the 1990s, worked this way.

    Neural networks entered with Yoshua Bengio and colleagues, whose 2003 paper «A Neural Probabilistic Language Model» (Journal of Machine Learning Research) learned a vector for each word at the same time as it learned to predict the next word. The problem was cost: training on large corpora with the hardware of the time was slow.

    Skip-gram and CBOW

    In 2013 Tomas Mikolov, Kai Chen, Greg Corrado and Jeffrey Dean at Google published «Efficient Estimation of Word Representations in Vector Space.» Their move was to throw away most of the network. Instead of a full language model with hidden layers, they proposed two shallow architectures that do almost nothing except learn the vectors.

    The continuous bag-of-words model (CBOW) takes the words around a position and tries to predict the word in the middle. Skip-gram does the reverse: given one word, predict the words within a small window around it. In the sentence «the cat sat on the mat,» skip-gram with a window of two would train «sat» to predict «the,» «cat,» «on» and «the.»

    Each word has an input vector and an output vector, and the prediction is a dot product followed by a softmax. The paper reported that high quality vectors could be learned from a 1.6 billion word dataset in less than a day.

    Negative Sampling

    The softmax in skip-gram still had a hidden cost. To compute the probability of one context word, the model has to normalize over the whole vocabulary, so every training step touches hundreds of thousands of output vectors.

    A second 2013 paper, «Distributed Representations of Words and Phrases and their Compositionality» (Mikolov, Sutskever, Chen, Corrado and Dean, NIPS 2013), replaced it with negative sampling. Instead of asking «which of all words is the context?», the model answers a yes-or-no question: is this pair of words a real pair from the text, or a fake pair made by drawing a random word? Each step updates the true context word and a handful of random «negative» words, between 2 and 20 depending on the size of the dataset. The same paper added subsampling of very frequent words like «the» and «of,» which carry little information and would otherwise dominate training, and a simple method to learn vectors for phrases such as «New York Times.»

    Google released vectors trained this way on roughly 100 billion words of Google News text: 300 dimensions for about 3 million words and phrases.

    Case: King Minus Man Plus Woman

    The result that made word2vec famous was arithmetic. Take the vector for «king,» subtract «man,» add «woman,» and the nearest word to the result is «queen.» The same pattern held for capitals and countries, verb tenses and comparatives. Mikolov’s group built a test set of 19,544 analogy questions of this kind to measure it.

    The example deserves some caution. In 2020, Malvina Nissim, Rik van Noord and Rob van der Goot pointed out in Computational Linguistics («Fair Is Better than Sensational: Man Is to Doctor as Woman Is to Doctor») that the standard analogy code never returns any of the input words. For many queries, the vector closest to «king minus man plus woman» is still «king» itself, and the code skips it to show the next candidate. When the input words are allowed, analogy accuracy on the standard benchmark drops. Still, a model that was only asked to predict neighbors produced directions that line up with gender and royalty, and nobody told it about either.

    GloVe and the Matrix Underneath

    Jeffrey Pennington, Richard Socher and Christopher Manning at Stanford came at the problem from the counting side. Their GloVe model (EMNLP 2014) starts from a global table of how often each pair of words occurs together, then fits vectors so that the dot product of two word vectors approximates the logarithm of their co-occurrence count.

    Their motivating example uses ratios. On a 6 billion token corpus, «solid» appears with «ice» far more often than with «steam,» giving a ratio of about 8.9. «Gas» goes the other way, around 0.085. «Water,» which relates to both, and «fashion,» which relates to neither, both give ratios close to 1. The ratio filters out words that do not distinguish the two, and GloVe is designed so that differences between vectors capture those ratios. Stanford released vectors trained on 6, 42 and 840 billion tokens.

    The two camps turned out to be closer than they looked. Omer Levy and Yoav Goldberg showed at NIPS 2014 that skip-gram with negative sampling is implicitly factorizing a word-context matrix of pointwise mutual information, shifted by a constant that depends on the number of negative samples. The neural method and the counting method were solving related problems by different routes.

    Subwords and Unseen Words

    Both word2vec and GloVe assign one vector to each word in the training vocabulary and nothing to anything else. A misspelling, a rare technical term or a new inflection of a known verb gets no vector at all. In languages like Finnish or Turkish, where one root produces dozens of surface forms, this is a serious gap.

    fastText, from Piotr Bojanowski, Edouard Grave, Armand Joulin and Tomas Mikolov at Facebook (Transactions of the ACL, 2017), handles it by representing each word as a bag of character n-grams. «Where» becomes pieces like «<wh», «whe», «her», «ere» and «re>», plus the whole word. The word vector is the sum of its piece vectors. An unseen word can still be embedded from the pieces it shares with known words, and words that share a root share part of their representation. The team later released pre-trained fastText vectors for 157 languages, which made embeddings available for many languages that had little labeled data.

    A harder limit remains. Each word still gets a single vector, so «bank» in «river bank» and in «bank account» is one point, somewhere between the two senses. Contextual models such as ELMo (2018) and BERT fixed this by computing a new vector for every occurrence of a word from the whole sentence, though the input layer of every transformer is still a table of learned token vectors.

    Case: Thermoelectrics Hidden in Abstracts

    One of the more surprising uses came from materials science. In 2019 Vahe Tshitoyan and colleagues at Lawrence Berkeley National Laboratory published in Nature a word2vec model trained on about 3.3 million abstracts of materials science papers. It had no labels and no property data.

    The vectors still picked up structure from the field, including relationships that resemble the periodic table. The researchers then ranked chemical compounds by how close their vectors were to the word «thermoelectric.» By training the model only on papers up to a given year and checking what was published afterward, they showed that the method would have flagged several materials years before they were reported as thermoelectrics. The model had absorbed indirect associations that no single paper stated outright.

    Bias Learned From the Corpus

    The same mechanism that finds hidden chemistry also finds stereotypes. In 2016, Tolga Bolukbasi and coauthors at Boston University and Microsoft Research showed (NIPS 2016) that the Google News vectors completed «man is to computer programmer as woman is to» with «homemaker,» and that gender bias could be traced to a single direction in the embedding space. They proposed projecting that direction out of words that should be gender neutral.

    A year later, Aylin Caliskan, Joanna Bryson and Arvind Narayanan published in Science a test modeled on the psychological Implicit Association Test. Applied to GloVe vectors trained on web text, it reproduced known human associations, from harmless ones (flowers are more pleasant than insects) to gender and racial stereotypes. Hila Gonen and Yoav Goldberg later showed (NAACL 2019) that debiasing by projection often hides the bias from simple measurements while leaving it recoverable from the neighborhoods of words.

    A Final Observation

    The thermoelectric study and the «homemaker» analogy are the same experiment. In both, a model was trained to predict which words appear near which, and in both it recovered associations that were present in the text but never written as a sentence. In one case people called it discovery. In the other they called it bias. The model has no way to tell the two apart, because an embedding does not store what is true about the world. It stores how people have written about it, and the decision about which of those regularities to trust stays with whoever reads the vectors.

    By: Max Johnson B.

  • 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.