Energy-Based Models and Natural Language Processing Applications
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Energy-based models: definition, partition function, strengths, and comparison tasks ? covered in Lecture 14
- The Ising model and product of experts ? covered in Lecture 14
- Comparing the generative families: VAE, diffusion, and GAN pipelines ? covered in Lecture 14
- Attention and transformers ? covered in Lecture 5
- Pretrained language models: GPT, BERT, ELMo ? covered in Lecture 1
15.1 Energy-Based Models: The Core Formulation
Here is a question worth sitting with before any math: could a single neural network score every possible image, so that photos of real dogs score higher than static noise? An energy-based model (EBM) is exactly that idea taken seriously — learn the probability distribution that generated your training data by learning a scoring function over all possible data points.
An energy-based model is a way to learn the probability distribution that generated a set of training data. As with every generative technique covered so far, we call the training data . The data could be anything — for images, the pixel values are simply the dimensions of , so an image with a million pixels is a point in a million-dimensional space. The model assigns a probability to every possible through a scoring function , where stands for the parameters of a neural network.
Think of like a credit score, but for data points. A bank's scoring function takes an applicant and returns one number summarizing how "loan-worthy" they are; here the network takes a data point and returns one number saying how much the point looks like genuine training data. High score means plausible; low score means implausible.
15.1.1 Why the Exponential Shape
The defining equation of an energy-based model reads:
Spoken aloud: "the probability of x is e raised to the power of f theta of x, divided by z theta." Each symbol has a job:
- is the model probability of a data point — a non-negative number, and across all these values behave like true probabilities.
- is the neural network output, called the energy up to sign. In physics-flavored texts the energy is defined as , so high probability corresponds to low energy; in this lecture we work directly with the score , where high score means high probability.
- is the normalizing constant, also called the partition function. It is a number that rescales the exponentials so everything fits into valid probability range. Formally, for continuous data it is the integral of the unnormalized scores over the whole input space:
and for discrete data (such as binary pixels) the same object is a sum over every possible configuration. This integral is what makes EBMs both powerful and painful, and Section 15.2 returns to that cost.
Why insist on the exponential shape? Two structural properties follow directly from it:
- Positivity. Because raised to any power is always positive, is automatically greater than or equal to zero — no matter what values the network produces. Even if the network outputs a wildly negative score like , then is a tiny positive number, never a negative probability. The speaker's own restatement: "since the output is written as exp of f theta x, the p theta x values are always greater than or equal to zero, because e to the power of anything is greater than or equal to zero."
- Normalizability. Dividing by the appropriate normalizing constant squeezes the values so they sum (or integrate) to one across the whole space, which is the defining property of a probability distribution.
A tiny numeric check. Suppose the input space has just three possible points and the network outputs scores , , . The exponentials are , , . Their sum gives the partition function . So , , and . All three are positive, and they add up to (the small excess is rounding). Notice two things: doubling the gap between scores would have made the top point even more dominant, because the exponential amplifies differences — and computing this was only easy because the input space had three points. Sense check: probabilities came out positive and summed to one, exactly as the exponential-plus-normalizer design promises.
15.1.2 The Flexibility That Defines EBMs
The key distinguishing feature of energy-based models, compared with every model discussed before them, is flexibility. Because is realized by a neural network, it can be arbitrarily complex in nature. You are not locked into a parametric family such as a Gaussian, whose density is forced into a specific bell shape; the network can carve out whatever shape the data demands — several islands of probability, long thin ridges, sharp spikes.
Picture the difference this way. Fitting a Gaussian to data is like insisting every landscape must be a single smooth hill; fitting an EBM is like letting the sculptor decide. The training process itself learns the distribution from one single requirement:
Data belonging to the training set should come out associated with high probability under , and any point that is not part of the training data should get lower probability. That single requirement drives everything else in this topic — the training tricks of Section 15.4 and the sampling machinery of Section 15.5 all exist to enforce it.
Scope: The formulation above assumes the network can represent the target distribution's structure and that you can eventually handle the partition function somehow. It does not assume anything about the dimensionality being small — and that is exactly where trouble starts, because 's sum or integral runs over all configurations of , which explodes exponentially with dimension. Nothing in the definition tells you how to train such a model; Sections 15.4 and 15.5 supply that machinery.
Pitfalls:
- Calling itself a probability. It is just a real-valued score — possibly negative, unbounded. Only after exponentiating and normalizing do you get a probability.
- Forgetting the sign convention. Physics texts define the energy as with ; here the score is with . Same mathematics, opposite sign. Always check which convention a source uses.
- Assuming the partition function is a fixed known number. It depends on , so every time the parameters move, the whole normalization changes too.
The flexibility is real but not free. The next section prices it honestly: sampling and likelihood evaluation become hard problems — yet a simple comparison trick rescues most practical uses.
An energy-based model defines : a neural score turned into a probability by exponentiation (guaranteeing positivity) and division by the partition function (guaranteeing unit total mass). Training aims to push scores up on real data and down everywhere else.
In the broader field, this scoring view is the shared skeleton behind Boltzmann machines, contrastive divergence, and modern score-based diffusion models — LeCun and colleagues formalized energy-based learning in 2006 precisely to give all of these one mathematical home. Wherever you later see a model described as "learning an energy," you are looking at this equation wearing different clothes.
15.2 Strengths and Trade-offs of Energy-Based Models
15.2.1 Three Hard Problems
Extreme flexibility is attractive, but a bunch of not-so-nice properties come with it:
- Sampling from is hard. Drawing a realistic data point out of the model is not a simple operation. For a Gaussian you have closed-form recipes; for with an arbitrary neural network inside, no such recipe exists, and Section 15.5 has to build one from statistical physics.
- Evaluating and optimizing the likelihood is hard because of the presence of in the denominator. You cannot even report how probable a single training point is without knowing that number.
- Computing numerically becomes very hard whenever the dimensionality of is large — think of images, where the pixel count runs into the thousands or millions. The normalizing constant involves a sum (or integral) over every possible configuration of pixels. A single grayscale image with just 100 binary-valued pixels already forces terms — more than the number of seconds since the Big Bang — and real images have thousands to millions of pixels. The count grows exponentially with dimension, so brute force is hopeless.
These are the defining trade-offs of the family: maximum expressive freedom, paid for with intractable normalization.
Scope: These three problems are not bugs in a particular implementation — they are consequences of the definition itself. Any model of the form , however clever the architecture, inherits them. What can differ is how a method works around them.
15.2.2 Relative Probabilities Are Enough
Why bother with EBMs at all? Because many tasks do not require knowing the explicit value of . You only need to compare two points. When you compare against for two points and , the normalizing constants cancel:
Spoken: "this is nothing but an exponential of f theta x minus f theta x prime." Walk through why the cancellation happens: both numerator and denominator contain exactly the same , because the partition function depends on the model — not on which point you are evaluating. Dividing the two fractions therefore divides the two exponentials and cancels the shared factor. You calculate the network output at both points and decide which one is more probable — no evaluation needed anywhere.
The ratio identity: for any two points and ,
The ratio exceeds one precisely when the score of beats the score of . Every symbol in this expression is computable by two forward passes of the network.
This mirrors a familiar trick from classical machine learning: the naive Bayes classifier. There you compare the joint probability of the attributes given rival classes, and whatever sits in the denominator — the overall data distribution — is a constant across all the comparisons being made. Whichever class gives the higher value wins. The same analogous reasoning applies here: once the model is trained, any point that comes from the training data will be associated with a higher probability than points coming from elsewhere. That is the beauty of energy-based models.
Q: If cannot be computed, how can the model be used at all? A: For many tasks you never need its explicit value. Comparing two probabilities — training point versus non-training point, or candidate versus candidate — cancels completely, exactly like the naive Bayes classifier comparing class posteriors while ignoring the constant data probability in the denominator.
Worked comparison. Suppose the trained network outputs for a genuine training image and for a noise patch. Then
The training-like point is about fifteen times more probable than the noise patch — a verdict reached with two network calls and one exponential, never touching . Sense check: a positive score gap gave a ratio above one, so the more "training-like" point indeed won.
15.2.3 Applications: Denoising and Anomaly Detection
Because comparisons are cheap, EBMs fit tasks built on relative probabilities — the ratio of probabilities matters more than the probabilities themselves.
Real-world: Anomaly detection. Feed a trained EBM a stream of points — for example, sensor readings from a factory line or network traffic records in a security operations center. An anomalous outlier will be deemed to have essentially no probability compared with all other points that belong to the training distribution, so outliers pop out immediately. Fraud detection teams exploit exactly this: transactions far outside the learned high-probability region get flagged before a human ever looks.
Real-world: Denoising. A corrupted input sits far from the high-probability region; the model can judge how "training-like" a repaired candidate is by direct comparison. Candidate repairs can be ranked against each other, and Section 15.3.1 shows the Ising model turning this idea into a full denoising procedure.
Exam note: Expect the ratio identity to be the workhorse argument for why intractable does not kill the method. Be ready to derive it in two lines and to name its applications: anomaly detection and denoising.
The normalizer blocks absolute probabilities but not comparisons. Whenever a question asks "which point is more likely?", EBMs answer directly; whenever it asks "how likely is this point exactly?", they struggle — and that distinction organizes everything that follows.
15.3 Basic Energy-Based Model Families
Before training methods, recall the basic EBM types introduced previously: the Ising model, product of experts, the Boltzmann machine, and its restricted cousin. This section is a guided tour of four stops on one family tree — all four are energy-based models, differing only in how they wire their compatibility terms together.
15.3.1 The Ising Model for Corrupted Images
In the Ising model (a name borrowed from statistical physics, where it describes interacting magnetic spins), the observed pixels are noisy pixels — call them . Each observed pixel is a noise-corrupted version of the real data, but the real data is not known to us. What we have is only the corrupted observations. The model thinks in terms of a small neighborhood — for instance a 3 by 3 patch of pixels around each location.
The joint distribution of the true pixels given the observed pixels is written as a particular function with two ingredients:
Here and are the compatibility functions you choose — each returns a non-negative number saying how compatible its two arguments are — and denotes the set of neighboring pixel pairs. The symbol means "proportional to": the right side has the right shape, and a normalizing constant over all candidate clean images would turn it into an exact probability.
The formula deserves a full derivation rather than an announcement. It follows from two modeling assumptions plus Bayes' rule:
Start from Bayes' rule with the noisy pixels observed and the true pixels unknown:
Since is fixed and known, is just a constant with respect to choosing , so . Now unpack the two factors:
- Corruption term. Assume each observed pixel was corrupted independently given the truth. Then the likelihood factors pixel by pixel:
Each is large when the observation plausibly arose from true value .
- Smoothness term. Assume the prior over clean images favors local agreement between neighbors. Then the prior factors over neighboring pairs:
Each is large when neighbors and hold similar values.
Multiplying the two gives exactly the displayed posterior.
Both ingredients carry meaning you can feel. First, there is dependence between each noisy pixel and its underlying true pixel: and are tied together for all values of , because the corrupted pixel you view depends on the -th original pixel — and that original pixel is exactly what you want to recover by running the model. Second, neighboring pixels tend to hold similar values: and tend to be alike. Physically, imaging data shows strong correlation between nearby points; a normal image has a small number of edges, so away from edges the local correlation is quite high.
Your goal is to maximize this posterior probability with respect to the unknown values — search over candidate clean images and keep the one whose product of compatibility scores is largest. Doing so yields the recovered, denoised image. As a quick sanity check of the structure: if you deleted every smoothness term , the model would still trust each observed pixel individually but would produce speckly results, because nothing would encourage neighbors to agree; delete the data terms instead and the model would return an over-smoothed blur. Denoising quality lives in the balance between the two products.
15.3.2 Product of Experts
A product of experts means you have multiple different trained models — the "experts" — and each expert makes its judgment independently. Pass any data point through all of them, then multiply the individual probability outputs together and divide by a fixed quantity:
Here are the experts, each a separate trained function returning a non-negative score for , and is the normalizer that makes the product behave like a probability. Once the experts are trained and fixed, that divisor remains constant, so you can again compare the resulting products between two points and decide which one is more likely:
It is the same relative-comparison logic as Section 15.2.2, applied across several independent judges. The intuition for why multiplication helps: each expert can enforce one property — one expert might demand "edges look like edges," another "textures look like textures," another "colors are plausible" — and a data point passes only if it satisfies every expert simultaneously. Multiplication acts like a logical AND on probabilities: a point that pleases three experts at each scores , while a point that displeases even one expert at collapses to near zero no matter how good the others are.
Two experts, one verdict. Let expert 1 score face-likeness and expert 2 score sharpness. For a genuine portrait : , , so the product is . For a blurred portrait : , , giving . The ratio says the sharp portrait is about fifteen times more probable under the combined experts — without ever computing . Sense check: the single failing expert dragged the whole product down, which is exactly the AND-behavior the design intends.
15.3.3 Boltzmann Machines and Their Deep Version
The Boltzmann machine is another member of the energy-based family. The observed data occupies the bottom layer of variables — pixel values — and the layers above represent progressively higher-level features such as corner and edge detectors, moving toward genuinely semantic information as you go up.
Structurally, this general layered arrangement resembles a multilayer perceptron (MLP) strongly — the resemblance with the so-called deep Boltzmann machine is easy to see. One historical point deserves emphasis, because it explains the shape of the entire field:
The deep idea behind the deep Boltzmann machine came from statistical physics, and its timing predates the multilayer perceptron. At the time, Boltzmann machines were very difficult to train because backpropagation algorithms were not available. Once backpropagation matured in the mid-1980s, MLPs became easy to train — and that is the branch of the family tree that flourished. The layered-representation idea was not new with deep learning; what changed was the arrival of a practical training algorithm.
15.3.4 Restricted Boltzmann Machines
RBMs — restricted Boltzmann machines — are energy-based models with latent variables. Those latent variables are nothing but hidden units: the visible variables live in the range zero to one, like pixel values, while the latent variables are units you have no access to — a hidden layer.
The joint distribution of and takes an exponential-family form whose terms reveal the restriction:
Read the structure carefully. The sum runs over every visible index and every hidden index , pairing original values with hidden values through weights . In the joint probability distribution there are no terms like . If terms like appeared, that would mean connections exist between visible units — between visible dimensions. Likewise there are no terms: no connections among the hidden units either. What you are seeing is a linear combination of the original values paired, term by term, with hidden values through weights .
That absence of intra-layer coupling is precisely why the word restricted appears in the name — a restriction has been put on the general Boltzmann machine, whose units may connect arbitrarily. There is also no recurrence relationship between the units, unlike the recurrent setups seen in RNNs. Textbook treatments often add bias terms for visible units and for hidden units inside the exponent, giving ; the lecture keeps only the cross-term core, and everything said here applies to both versions.
When trained on small training images, an RBM can generate lookalike samples — with the caveat that these are deliberately small-size demonstrations, so you recognize the scale limits of the demo rather than of the method.
Pitfalls:
- Reading the RBM restriction as "no weights anywhere." The restriction removes only same-layer connections (, ); the cross-layer weights are exactly where all the learning happens.
- Confusing the RBM's latent variables with RNN recurrence. RBM hidden units are static features per input; nothing feeds back in time.
- Mixing up the Ising model's two products with the RBM's cross-term sum. The Ising model ties observations to truths and neighbors to neighbors; the RBM ties visible units to hidden units only.
Four relatives, one skeleton: the Ising model couples noisy observations to truths and truths to neighbors; a product of experts multiplies independent judges; the Boltzmann machine stacks feature layers; and the RBM keeps only visible-to-hidden couplings. All four evaluate compatibility by products of terms — and all four inherit the partition-function burden that Section 15.4 begins to pay down.
These families were historically important stepping stones, but they share one practical weakness: training them well needs samples from the model itself. The next two sections build exactly that machinery.
15.4 Training an Energy-Based Model
Energy-based models deserve special care at training time, because the technique differs from everything learned so far. You have a set of training data points , and the goal is to maximize the model probability of those points with respect to the parameters :
Every other generative model in this course gave you a tractable loss you could hand to gradient descent directly. This one does not — and understanding why it does not is the fastest way to understand everything that follows.
15.4.1 The Numerator-Denominator Tug of War
Theta appears both in the numerator and in the denominator, and that creates a genuine tug of war. The tempting strategy is: increase the numerator, decrease the denominator. The problem is that depends on the numerator too — it sums the exponential of over all possible configurations:
Changing the thetas does not guarantee that your data point becomes relatively more likely compared with the rest, because as you increase the numerator's value at your data point, the denominator can rise as well, swallowing the gain.
Picture a tug of war over one rope: pulling your data point's score up (the numerator) also tightens every configuration that shares the same weights — including configurations the model already favors — so the denominator climbs too. A hill-climbing step can leave exactly where it started.
Concretely: suppose raising 's value doubles the score at your training point but also raises scores elsewhere in space enough to double the total integral. The ratio has not improved at all. Plain gradient ascent on this objective therefore gives no useful direction until we untangle the two terms — which taking logarithms accomplishes.
So the working goal is framed differently. After training, should be arranged such that for the known training points the score is high, and for the remaining points the score is low — high probability for training data, relatively low probability for everything else.
15.4.2 Contrastive Divergence
To bypass the evaluation of , a different technique is used: contrastive divergence. The idea runs as follows. At any training iteration you hold a particular, partially trained parameter value . Using that current model, you generate some samples out of the model being trained. Then you adjust the parameters so that the training data becomes more likely than typical samples from the model. "Sample from the model" means: draw points using whatever temporary value of theta you currently have. The update direction is set by the comparison — push for real training data above for the model-generated .
This is a procedure rather than a formula, so it is worth laying out as one:
Contrastive divergence, step by step
Purpose: sidestep computing or differentiating by replacing the intractable "everything else" with a finite batch of model-generated negative examples.
Inputs: training data points ; current parameters . Outputs: updated parameters .
Steps:
- Hold the current partially trained parameter value .
- Generate samples from the model defined by itself (Section 15.5 supplies the machinery).
- Compare: demand that real training points score higher than these fabricated points.
- Adjust along the direction that widens that gap, producing .
- Repeat from step 1 with the new parameters.
The parameter trajectory makes this concrete: you start at , generate samples using itself, compare those samples' probabilities against the training data under , and produce . Then at you once again create fresh samples, demand their probabilities sit below the probability of the real training samples, and step to . Step by step, the parameters move while fresh samples keep arriving from the moving model. The same contrastive-divergence concept returns when diffusion applications are discussed.
15.4.3 The Log-Likelihood Gradient
Take logs of the individual probability. The complicated ratio turns into something manageable:
Spoken: "originally it was e to the power of f theta x over z theta; if you take the log of that, you have this minus this, and you want to maximise this." The log turns the division into subtraction because . This quantity is the log likelihood of the data point under the model. Now differentiate it with respect to theta. Here is the complete derivation, with every algebraic move written out:
The only unresolved piece is . Expand it with the chain rule, writing the partition function as an integral over all configurations :
The derivative moves inside the integral (the network is smooth and its exponential decays fast enough for this interchange to be valid):
Now notice what the factor multiplying the gradient inside the integral is: by definition, . So the whole expression is an expectation under the model's own distribution:
Assembling the pieces gives the displayed result:
A quick sanity pass on this expression before trusting it: both terms are gradients with respect to , so they live in the same parameter space and can subtract — shapes agree. As a limiting case, if the model were already a perfect spike concentrated on itself, the model's own expected gradient would equal , the two terms would cancel, and the update would correctly go to zero — nothing left to learn.
Reading the gradient: The first term pushes the score up on real data. The second term — an expectation over the model's own distribution — pushes the score down on points the model itself believes in. Training succeeds when the positive term dominates on average: real data climbs the scoreboard while the model's fabrications sink.
To evaluate that second term you must draw samples from , and that sampling is not an easy thing when the distribution has no closed form. That requirement is what makes EBM training unlike any other method in this course — and it motivates the machinery of the next section.
Pitfalls:
- Trying to backpropagate through directly. Its gradient is the expectation term — you cannot compute it without samples, which is the very problem contrastive divergence works around.
- Forgetting that the negative samples must come from the current model. Stale samples from an old push the model away from regions it no longer believes in.
- Reading the two gradient terms as "good term" and "error term." Both are essential: without the second, the trivial solution "make huge everywhere" would win, which assigns high probability to everything and distinguishes nothing.
Log likelihood splits into a data-score term minus a log-partition term; differentiating yields "push up on real data, push down on model samples." The push-down term demands sampling from the model mid-training — the defining cost of EBMs and the bridge into MCMC and Langevin dynamics next.
15.5 Sampling from an Energy-Based Model
15.5.1 How Sampling Timing Separates EBMs from VAEs and GANs
Sampling plays a fundamentally different role in each generative family, and the contrast is worth pinning down precisely.
- VAE: during training there is no role for generating data samples. You first train the encoder and learn the latent distribution. Only after training is over do you look at the latent space — take the mean value, take the covariance matrix — and create a sample as the mean vector plus epsilon times the covariance matrix, where epsilon is a small random sample drawn from a standard distribution. That sampled latent value is passed through the decoder to generate new data. Sampling is restricted to generation time.
- GAN: the only sampling that plays a role in training is drawing a small-dimensional random vector — on the order of one hundred entries, say a 100-dimensional noise vector — and sending it through the generator to fabricate fake images. A discriminator then learns to discriminate true training data from generator-made data. The noise vector is tiny compared with the images it produces: a hundred numbers in, a full image out.
- EBM: you actually generate samples from the model itself, for the purpose of training the model itself. That is what makes EBM training more complex than VAE or GAN training.
Keep the timing straight and the families sort themselves out: VAEs sample only after training, GANs sample a small noise vector to feed their generator during training, and EBMs must draw full samples from their own evolving distribution throughout training. The sampler is not an optional add-on for an EBM — it sits inside the training loop that Section 15.4 derived.
15.5.2 Markov Chain Monte Carlo
Since the model changes from one iteration to the next (, then , then , and so on), and since admits no closed-form sampler, a statistical process is recruited to produce the samples: Markov Chain Monte Carlo, abbreviated MCMC. Each step of the chain depends only on the current point — that is the Markov property, the same memoryless structure seen in Markov decision processes — and randomness enters at every step, hence Monte Carlo, named after the famous casino.
The original procedure works like this:
- Initialize randomly (at or near zero).
- Add a noise perturbation to the current point to propose a candidate .
- Evaluate the network's probability output at the candidate and at the current point.
- If the candidate's probability value is greater than the current one, the new value becomes the candidate.
- Otherwise, keep the current point with a certain acceptance probability — concretely, the standard rule accepts a downhill move with probability . Note that this ratio needs no : it is exactly the comparison trick of Section 15.2.2 applied inside the sampler.
- Repeat these iterations many times to create your samples; then update the parameters based on the contrastive-divergence comparison and proceed to the next round.
Tracing three MCMC iterations. Let the current model score points via , and suppose the chain currently sits at with .
- Iteration 1. Noise gives candidate with . Since , accept outright: .
- Iteration 2. Candidate has . Downhill move: accept with probability . Drawing a uniform random number : if move to , else stay. Say — reject, so .
- Iteration 3. Candidate with score current — accept again.
After many such steps, the fraction of time the chain spends near any region converges to that region's probability under — high-probability neighborhoods get visited often, low ones rarely. Sense check: uphill moves always happened, downhill moves happened only sometimes, and the acceptance formula never touched .
The trouble: original MCMC is slow to converge. The chain may wander for thousands of steps before its visits reflect the true distribution, especially if starts far from any high-probability region. Every training iteration pays that cost again because the model — and hence the landscape it must explore — keeps changing. That bottleneck motivated a faster strategy rooted in statistical physics.
15.5.3 Langevin Dynamics and the Score Function
The alternative is Langevin sampling — again a principle coming out of statistical physics, originally used to model the movement of molecules depending on the temperature of the matter: molecules drift along forces and get jostled randomly by heat at the same time.
The modern recipe starts from a remarkable object: for any continuous distribution , suppose you can compute the gradient of the log probability with respect to :
This is called the score function. The important part to notice: you are taking the gradient with respect to the random variable itself — the input point — not with respect to the parameters. Everywhere else in deep learning the gradient flows toward weights; here it flows toward the data coordinates, pointing from wherever you stand in input space toward where probability mass increases. Following this gradient climbs the probability landscape. And there is a computational gift hiding here: substituting the EBM form,
because does not depend on at all. The score of an EBM is just the network's input-gradient — no partition function anywhere.
Starting from a prior distribution that is easy to sample from — it could be a Bernoulli distribution or a Gaussian distribution, whatever is convenient — you draw . Then each Langevin step updates the point as:
Walk through the three ingredients: is the current point; epsilon is a small step-size number scaling the gradient; and is nothing but a random Gaussian noise draw (with mean zero and identity covariance , meaning independent standard normals across dimensions), scaled by the square root of , which keeps the chain exploring instead of freezing at the nearest peak. Without the noise term the walk would climb deterministically to the closest maximum and stop; with it, the walk keeps drifting around the whole high-probability region, spending time in proportion to local probability — exactly what sampling means.
One Langevin step by hand. Suppose the model's score at the current point is and the step size is . The deterministic part contributes . The noise term scales a fresh standard-normal draw, say , by , contributing approximately . The update lands at : mostly climbing the probability slope, slightly jostled sideways by noise. Sense check: both terms scale down as , matching the guarantee below that small steps converge to true samples.
The guarantee: as epsilon tends to zero and t tends to infinity, approximates samples drawn from . While that limiting condition holds strictly only in the limit, practitioners observed something liberating — modifying the running random samples with this relationship for just a few iterations, t equal to 3, 4, or 5, is enough in practice. Modern energy-based models using Langevin sampling produce very high-quality outputs: actual face samples, and ImageNet samples generated from modern EBMs, look convincingly real.
15.5.4 Implementation Choices, the Energy Landscape, and Generation
Typically people implement the scoring network with CNN-based or ResNet-based architectures. One point distinguishes this usage from ordinary vision networks: you are not using the CNN to classify the data. Instead, the output of the CNN models the energy landscape of the data — a surface over input space where training data points sit at high probabilities and implausible points fall into low basins.
Picture the landscape as terrain seen from above: bright plateaus over realistic images, deep valleys over garbage. During training, based on the sampled points, the network learns to sculpt this landscape: training data points are pushed to high probability, and the samples generated by the partially trained model are pushed lower.
If this sounds familiar, it should. During GAN discriminator training you also wanted real data to yield a high discriminator output while generator-produced data yielded a low outcome. A similar principle and concept is applied in training energy-based models: the network is trained to predict high probability for training data compared with the samples it generates during the training process. The difference is what happens afterward — a GAN discards its discriminator at generation time, while an EBM reuses its landscape directly as the sampler's map.
Generation after training flips the sign of the game. You use the opposite of the Langevin sampling direction: start from a particular point and move toward regions of higher probability, making the generated data approach the quality-probability regime of the training data.
Scope and honest cost accounting: The beauty of EBMs is a flexible, unconstrained way of modelling a probability distribution. The con is that throughout training you must run Langevin/MCMC sampling with the partially trained model to manufacture the negative examples, and that is expensive — every parameter update carries a sampling bill that VAEs and GANs never pay.
Q: Why can't we sample from directly? A: There is no closed-form sampler for this distribution, and computing the normalizer is intractable in high dimension, so indirect chains — MCMC, then the faster Langevin procedure — construct samples step by step from the current model.
MCMC builds samples by proposing noisy candidates and accepting them with the ratio rule; Langevin dynamics replaces slow random wandering with gradient climbing plus calibrated noise, using the score function — which for an EBM is simply . Sampling is the engine room of EBM training, not a post-training luxury.
15.6 Where Generative Modeling Stands Today
15.6.1 The Full Model Family Tour
Stepping back, the course has now covered the major families of data-generating models: autoregressive models from the pre-midterm sessions; VAE, beta-VAE, and VQ-VAE — including hands-on assignment experience with those three; extensive time on GANs, starting from GAN basics and continuing through Wasserstein GAN, variants such as SN-GAN, and CycleGAN together with related image-to-image translation models; then diffusion models; and finally energy-based models.
That tour is worth keeping as a mental checklist, because each family answers the same question — how do I model ? — with a different trick:
- Autoregressive: factor the joint into sequential conditionals and predict left to right.
- VAEs: encode into a latent space and decode from it, matching a prior.
- GANs: two networks in an adversarial game, generator against discriminator.
- Diffusion: gradually corrupt data with noise, then learn to reverse the corruption step by step.
- EBMs: score every input's plausibility with one network and sample via MCMC/Langevin.
15.6.2 Desirable Properties Nobody Has Fully Achieved
Why so many models? Each comes with pros and cons, and depending on the scenario some models become more useful than others. The desirable property list for a perfect generative model reads like this: it should not take too much memory; inferencing should be fast; the training process should be stable; and it should generate data very fast, with enough diversity. No available model delivers all of these at once.
A quick scorecard shows why the field keeps several families alive at once: GANs generate fast but train unstably; VAEs train stably but blur; autoregressive models give exact likelihoods but crawl at generation time; diffusion models reach top quality but pay for it with many denoising steps; EBMs are maximally flexible but pay sampling bills throughout training. Pick your poison per application.
What has been reached today: we can create very high-quality data — provided we have access to lots of memory to store the models and lots of processing power to train them. And often the best-quality models generate data sequentially rather than in parallel.
Real-world: consider the top-performing broad-purpose systems offered by OpenAI using GPT technology. Generate an image with such a system and it takes a while — because it generates the data sequentially, and internally it must be using some variant of the diffusion model in many cases. A diffusion model has to remove the noise in steps, which makes it slower by construction. The wait you feel while an image materializes is the sound of dozens of denoising steps running one after another.
15.6.3 Hallucination Control Through Human Ratings
One more open problem: generally speaking, you want assurance that generated data is not hallucinated — meaning the output really is associated with high probability under the true data distribution, not merely plausible-looking. An interesting industry pattern has emerged: some models now return multiple candidate results and ask users to rate which one is good and which is not. Based on those judgments they retrain or fine-tune the model. Plausibly they are using something akin to contrastive divergence — computing relative probabilities of two candidates from user judgments and adjusting the parameters so that community opinion reshapes the model's probability landscape. Human thumbs-up and thumbs-down play the role that model-generated negative samples played in Section 15.4.
Exam note: Most questions come after the midterm; around twenty percent may come from earlier topics — calibrate revision accordingly. Be able to name each generative family, its defining trade-off, and why no single model yet combines low memory, fast inference, stable training, and fast, diverse generation.
15.7 Why Unsupervised Learning Matters for Language Data
15.7.1 Labels Are Scarce and Expensive
Here is the tension that launches the second half of this lecture: humanity produces more text every day than any labeling team could annotate in a lifetime. If learning requires labels, almost all of that text is wasted. The entire modern NLP stack exists to escape that trap.
This observation reaches beyond natural language processing and vision, and it opened this course back in the first session: look at the available digital data around us — there is lots of it, but its categorization is poor. Data accompanied by training labels is particularly powerful and valuable for supervised training, no doubt. But given the volume of data created by digital devices, only a very small fraction will ever carry category labels. Unless you employ unsupervised learning techniques, you simply cannot fully monetize the amount of data around us. That is the motivation behind so many model types that learn from raw data alone.
In NLP the same story repeats. Plenty of data exists, but it may not be machine-learning-grade data — meaning very curated data with training labels attached. Building such data is very expensive, whether for academic purposes or model development; annotating a single sentence for sentiment or entity tags costs human minutes, and useful corpora need millions of sentences. Curated resources do exist — certain datasets have been carefully assembled over years — but the vast bulk is raw digital exhaust: text generated by cameras and people through social media and similar channels. The question is how to learn from that not-so-ideal data.
15.7.2 Self-Supervised and Semi-Supervised Framings
Over the years, techniques have been developed to squeeze signal out of non-machine-learning-grade data. They typically operate in an unsupervised framework — or, more appropriately, a self-supervised one, where the raw data itself manufactures the training targets.
The self-supervised trick deserves a name-check because it powers everything from word2vec to BERT: hide part of the input, ask the model to reconstruct it, and the answer key comes free. No human ever labeled anything — "the next word" or "the masked word" is the label, generated by the corpus itself.
Alongside sits semi-supervised learning: primarily unsupervised, with most of the data unlabeled, plus a small subset that does carry training labels, used to fine-tune what unsupervised learning discovered. The valuable supervised data improves the model; its small volume is compensated by the cheap unlabeled mass.
Three regimes on one axis: supervised (all data labeled), semi-supervised (small labeled subset plus large unlabeled mass), and self-supervised/unsupervised (no labels at all; targets manufactured from the raw inputs themselves). Modern language models live mostly in the third regime, dipping into the second only at fine-tuning time.
15.7.3 The Road Map for Language Models
The topics lined up: word2vec, then GloVe, then context vectors (CoVe), then ELMo, and possibly BERT and GPT — starting from basics. Some of this repeats material from dedicated NLP courses, but the payoff is relating those ideas to the unsupervised-learning perspective developed here. Each stop on the road map adds one capability:
- word2vec: compact vectors learned by predicting words from their neighbors.
- GloVe: global co-occurrence counts folded into the same objective.
- CoVe: context-dependent vectors via supervised translation pretraining.
- ELMo: deep stacked contextual representations.
- GPT/BERT: transformer backbones pretrained self-supervised at scale.
Before the modern models, one almost zero-order concept anchors everything: word-to-word co-occurrence statistics — which is exactly where the next section starts.
Labels are scarce and expensive; raw text is abundant and cheap. Self-supervision turns the corpus into its own teacher, and semi-supervision spends a few expensive labels where they help most. Every model from here to the end of the lecture is a different answer to one question: how do we learn meaning without a human in the loop?
15.8 Word-to-Word Co-occurrence Matrices
15.8.1 Building the Matrix
Before any neural network appears, try the simplest possible question about language: which words show up together? Language is not random — words are not sprinkled arbitrarily through documents — so even raw counting should leak meaning.
Language is not random. Words are not sprinkled arbitrarily through documents; people organize them according to the inherent patterns of the language. So a productive first statistic is: given a large volume of text, capture which words occur with which other words. A word-to-word co-occurrence matrix tabulates, for every pair of words, how often they appear together.
The construction is mechanical. Pick a context definition — say, "within the same sentence" or "within a few words of each other." Then walk the corpus once: every time word occurs near word , add one to cell . Rows are indexed by words, columns by words again, and entry answers "how many times did word appear near word ?" The matrix is symmetric when the relation "near" has no direction.
The canonical toy example uses a handful of related words: water, steam, ice, and hot. Water, steam, and ice are three forms of the same substance — one at normal temperature, one at low temperature, one at high temperature — and hot is the adjective floating among them.
15.8.2 Reading Semantics Off the Counts
Now read the table the way the lecturer walked through it. The word water dominates: it appears a large number of times in the corpus, with the largest counts in its row — the displayed entry for its strongest partner dwarfed everything else nearby. Steam co-occurs with water heavily — several hundred joint occurrences across the relevant cells. Ice registers fair, more modest counts. Ice and steam barely co-occur with each other — they occupy opposite temperature ends, one speaking of cold and the other of heat, so a typical corpus puts them together rarely.
The hot row sharpens the semantic picture. Hot and ice co-occur only 17 times — nearly opposites. Hot and steam co-occur 1813 times — tightly related through the notion of heat. Hot and water also co-occur frequently, because people talk about "hot water" constantly.
A reading of the toy matrix. Sketching the counts discussed in class (exact digits vary by corpus; the ordering is what carries meaning):
| water | steam | ice | hot | |
|---|---|---|---|---|
| water | — | very high (hundreds) | moderate | high |
| steam | very high | — | very low | 1813 |
| ice | moderate | very low | — | 17 |
| hot | high | 1813 | 17 | — |
Read any row as that word's "company profile." Steam's profile says: lives with water, loves heat, shuns ice. Ice's profile says the opposite on the heat axis. Two words with similar profiles mean similar things. Sense check: hot–steam at 1813 versus hot–ice at 17 is a hundred-fold gap, and that gap is the semantics of "heat."
The conclusion: co-occurrence patterns convey semantic information. Words that are semantically related show up together; words that clash do not. Meaning, at this stage of the road map, is nothing more than the company a word keeps — a slogan usually attributed to the linguist J. R. Firth that this whole subfield quietly runs on.
15.8.3 The Storage Problem
One problem with acting on word co-occurrence directly: the matrix is enormous. If the vocabulary holds 1,000,000 words, representing the full co-occurrence structure takes about 4 terabytes of information. The arithmetic behind that figure is worth seeing once: a million-by-million matrix has entries; storing each as a 4-byte integer gives bytes, which is exactly 4 terabytes — before counting overhead, and most cells would be zero anyway since most word pairs never meet.
We want a succinct representation of words that preserves the relationship between words and the information they represent — without such huge volume. Several techniques exist for finding faithful compressed representations, and they connect to a broader self-supervised principle already met with RNNs:
Predict any part of the input from any other part. Predict the future from the past. Predict the future from the recent past. Predict the past from the present. Predict top from bottom. Predict what is occluded from what is visible. RNNs predict the future from the recent past; LSTMs carry more memory; transformer-based processing predicts the future from the entire past.
Every model on the coming road map — word2vec, GloVe, and beyond — is a different answer to the storage problem this section just quantified: compress the terabyte-scale co-occurrence table into small dense vectors while keeping what the counts reveal.
Co-occurrence counts carry meaning: related words share company (hot–steam at 1813), clashing words avoid it (hot–ice at 17). But the full matrix needs roughly four terabytes for a million-word vocabulary, so the next sections chase compact representations that preserve exactly those relationships.
15.9 One-Hot Embeddings and Their Limits
15.9.1 Constructing a One-Hot Vector
The obvious first attempt at representing words for a machine: give every word its own private dimension. It works, it is simple — and it fails in two instructive ways that motivate everything modern.
The first representation anyone tries is the one-hot embedding. For every word in the vocabulary, attach a zero-one vector: depending on the word's position in the dictionary, put a 1 in that position and zeros everywhere else.
Walk through a miniature vocabulary of four words:
- the first word encodes as ;
- the second as ;
- the third as ;
- the fourth as .
In a realistic dictionary, a word starting the alphabet lands a 1 at the front followed by zeros; a word late in alphabetical order — say one beginning with "z" — carries its 1 at the very end. The total dimension of these embeddings equals the number of distinct words in the dictionary. A real vocabulary with 20,000 entries makes each word vector 20,000 numbers long, almost all of them zero.
15.9.2 Two Failures: Memory Waste and Meaning Blindness
Failure one: memory waste. Every vector is extremely sparse — one entry is 1, the rest are zeros — so nearly all stored bits carry nothing. For a million-word dictionary you would ship a million floats per word to communicate exactly one fact about it: its index.
Failure two is the deeper wound, and it deserves the warning label the lecturer gave it:
Words that are close in meaning receive vector representations that are far apart. Take good and nice: under one-hot coding, good might carry its 1 at roughly the 250th location of the dictionary while nice sits past the six-thousandth mark — wherever alphabetical chance put them. The two vectors are then nearly orthogonal: their dot product is zero, their Euclidean distance is large, and no geometric operation on these vectors can detect that the words are near-synonyms.
Comparing good and nice under one-hot coding. Let the dictionary place good at position and nice at position . Then good is the vector with a single 1 at index 250, and nice is with a single 1 at index 6126. Compute their similarity: the dot product , because no position holds a nonzero entry in both vectors. Every pair of distinct words — good/nice, good/bad, cat/quantum — scores exactly zero similarity. One-hot geometry is semantically blind by construction. Sense check: distance between any two distinct one-hot vectors is always , so geometry carries zero semantic information whatsoever.
We want representations that are memory-efficient and preserve semantics — words closely related in meaning should hold similar representations. That demand spawned everything that follows.
One-hot embeddings waste memory (one meaningful bit per huge vector) and destroy semantics (all distinct words equidistant). The fix must be dense, low-dimensional, and learned — which is precisely the contract word2vec signs next.
As supporting background from the reference texts: one-hot inputs force a model to treat all tokens as mutually independent — every pair of one-hot vectors is orthogonal — so a model given only one-hots cannot share statistical strength between related words like "movie" and "film." Dense learned embeddings remove both defects at once, packing meaning into a few hundred floating-point dimensions where similar words land close together and interpretable directions emerge (the famous example: the vector from "man" to "woman" closely matches the vector from "king" to "queen").
15.10 N-gram Language Models
15.10.1 Unigram and Bigram Assumptions
Can a machine judge whether a sentence is plausible English? A language model does exactly that — it represents the language itself by assigning probabilities to word sequences, scoring "the cat sat" far above "sat cat the."
A language model represents the language itself — it assigns probabilities to word sequences. The earliest family is the n-gram model, named for how many consecutive words each probability factor is allowed to look at ("n-gram" = a chunk of n words). With the unigram as the simplest member, the model asserts that the joint probability of a string of words factors into a product of individual word probabilities:
Each is the k-th word of the sentence and each is estimated from the corpus by simple counting: the word's occurrences divided by the total number of words. Given a corpus, you count how many times individual words occur, assign each word its probability, and score any candidate sentence by multiplying the individual word probabilities — a cheap verdict on whether the sentence is likely.
The strong assumption here is that all words are independent, and that assumption is why unigrams cannot work that well. Word order carries no information under this model: "dog bites man" and "man bites dog" receive identical scores, because multiplication does not care about the order of its factors.
Scoring a sentence with unigram probabilities. Suppose a 10,000-word training corpus contains these counts: "I" appears 500 times, "love" 100 times, "machine" 50 times, and "learning" 50 times. Then , , , and . The unigram score of "I love machine learning" is
A tiny number, as any four-word product will be — what matters is comparison. The scrambled string "learning machine love I" scores exactly the same : the model literally cannot tell sense from nonsense. Sense check: multiplying four small probabilities gave an even smaller one, and permuting factors left it unchanged — both hallmarks of the independence assumption.
The bigram model relaxes one step: the next word depends on the previous one. The joint probability becomes a chain of conditional probabilities:
Each conditional like is again a count ratio from the corpus: how often followed , divided by how often appeared at all. Bigrams already restore some order sensitivity — can be large while is small — but they still see only one word back.
15.10.2 Relation to Neural Sequence Models
Place the n-gram assumptions on the same axis as the neural models, using "how many past words can influence the next prediction?" as the axis:
| Model | Conditioning span |
|---|---|
| Unigram | none (independent words) |
| Bigram | exactly 1 previous word |
| RNN | a limited span of recent words — on the order of dozens in practice |
| LSTM | substantially more memory than an RNN |
| Transformer | the entire past |
The narration cited a span of about sixty-odd past words for the RNN; treat that figure as an indicative remark about short-term memory rather than an exact specification — the honest statement is that an RNN's effective memory is limited and fades with distance. These are the classical stepping stones; newer models begin with word2vec.
Pitfall: assuming n-gram models are obsolete trivia. They remain the baseline every neural language model is compared against, their counting logic reappears inside attention scores, and exam questions love asking you to state exactly which independence assumption each model makes.
Unigrams multiply independent word probabilities (order-blind); bigrams chain one-step conditionals (order-aware, myopic). Each step up the ladder — bigram, RNN, LSTM, transformer — extends the conditioning span toward the whole past.
15.11 Word2vec: Learning Embeddings by Prediction
Word2vec answers the storage problem from Section 15.8. Here "word" means a natural-language unit of information, and word2vec builds embeddings — compact vectors that support prediction. Two popular designs exist: the continuous bag of words model (CBOW) and the skip-gram model. They are mirror images of each other: CBOW predicts the center word from neighbors, skip-gram predicts neighbors from the center word.
15.11.1 Continuous Bag of Words: Neighbors Predict the Center
The CBOW model defines a window around a given word. With a window size of 5 — specifically 2 words into the past and 2 words into the future — the network receives as inputs and calculates the probability of the central word :
Training on the corpus tunes the system so every word can be predicted well enough from its neighbors. CBOW does word prediction based on local context. Notice what "bag of words" means here: the four context words enter as an unordered set — their positions relative to each other do not matter, only that they surround the center.
15.11.2 Skip-gram: Center Predicts the Neighbors
The skip-gram model inverts the arrow. Given the n-th word, predict what happens in the neighborhood — the words at positions for a 5-window:
Window size is a dial. With a 5-window: predict 2 words to the left and 2 to the right. Shrink to a 3-window: given the central word, predict the immediate left and right words. Grow to a 7-window: predict the 3 preceding and the 3 following words. Both models carry a parameter — the window size — and both train by maximizing the log likelihood of these predicted probabilities over the corpus.
A practical reading of the dial: small windows keep predictions local (syntactic, part-of-speech-like information), while larger windows pull in topical, semantic similarity. Both models carry a parameter — the window size — and both train by maximizing the log likelihood of these predicted probabilities over the corpus.
15.11.3 Input Representations: A Live Question and Answer
Right before the architecture came a pointed comprehension check aimed at listeners who had taken an NLP course.
Q: What is the input representation of the words fed into word2vec — for CBOW or skip-gram specifically? What goes into the calculation? A: The words enter as vectors. Each word is represented by a vector whose size equals the size of the vocabulary, filled entirely with zeros and a single one — one-hot vectors. So both the skip-gram model and the CBOW model take one-hot vectors as input. The output side is a softmax probability, and the transformation learned in between constitutes the embeddings corresponding to either the skip-gram or the CBOW variant.
Note the shape of the correction: a first answer guessed "one by N, depending on the dimensions of the transform," and the resolution pinned the dimension to the vocabulary size — a detail worth remembering because the architecture below depends on it.
15.11.4 Training Objective and Negative Sampling
The supervision is manufactured by the corpus itself — entirely self-supervised or unsupervised in nature. For every word occurrence you know what surrounds it, so training pairs cost nothing to construct: slide the window across the corpus and each position hands you one prediction problem with its answer key attached.
Under CBOW, the goal is a transform that maximizes the probability of the observed data given the surrounding words. Mechanically: maximize the product of all the probabilities; take an so the product becomes a sum; prepend a minus sign to create a negative log likelihood; then minimize that with respect to all the parameters of the transform. That is how the transform gets learned:
One computational snag deserves its own spotlight:
The softmax denominator has to be calculated over each and every word in the vocabulary — a lot of calculations repeated at every step. With a 10,000-word vocabulary, every single training example requires summing 10,000 exponentials just to normalize one distribution; with millions of windows, that dominates the compute budget.
To train effectively, people use negative sampling, which sidesteps the full-denominator computation by contrasting the true neighbor against a handful of sampled non-neighbors — instead of asking "how does this word compare against the entire vocabulary?", it asks "can the model tell the real neighbor apart from a few random impostors?" A handful of binary comparisons replaces one enormous normalization, which is why negative sampling made word2vec trainable at industrial scale.
15.11.5 Skip-gram Architecture: The Embedding Matrix and the Context Matrix
Here is the basic skip-gram architecture, traced end to end. Let denote the vocabulary size and the chosen embedding dimension.
- Input. The one-hot vector of the i-th word in the vocabulary — call it , with a single 1 at position i and zeros elsewhere; .
- Embedding matrix. Multiply by a matrix , called the embedding matrix. Multiplying a one-hot by this matrix simply fetches the corresponding row: , yielding the hidden representation with entries. This row-fetch behavior is why one-hot inputs make sense despite their waste — they act as lookup indices into the matrix.
- Context matrix. A second matrix — the context matrix — maps the hidden vector toward predictions: , one score per vocabulary word.
- Softmax. The scores convert into probabilities of candidate neighbor words: .
Training adjusts both and via gradient descent on the negative log likelihood to maximize the probability of the true neighboring words.
Do not assume equals transpose. It does not. Historically the two acquired separate names — the embedding matrix and the context matrix — and they are learned independently, not tied by transposition. Forcing would halve the model's freedom for no reason; the two matrices play different roles even though they share dimensions reversed.
Skip-gram trace with real shapes. Take a vocabulary of words and embedding width . The word "river" is word 3400, so the input is a 10,000-long one-hot with a 1 at index 3400. Multiplying by (shape ) fetches row 3400: a 128-number vector . Then (with of shape ) yields 10,000 scores; after softmax, the model assigns probabilities to every possible neighbor. Parameter count: holds about million numbers and another million — tiny next to modern models, yet enough to capture usable word geometry. Choosing or simply widens every row and column of this pipeline proportionally. Sense check: collapses a length- vector to length (lookup), and expands back to length (prediction) — the two multiplications bracket the network exactly as described.
Once training finishes, given any particular word, whatever emerges at the hidden layer — that -dimensional vector — is the word2vec representation of the word according to skip-gram.
15.11.6 CBOW Architecture: Average Then Predict
Continuous bag of words runs the same machinery in the opposite direction. Take the neighboring words surrounding a target — say four context words around the center — and combine them by taking the average of their embedding vectors. Multiply that average by the embedding matrix to get the hidden vector; multiplying by the context matrix then yields the output distribution over the vocabulary, and training learns the parameters of and to reconstruct the central word. In one displayed textbook figure the hidden representation had 10 units — purely an illustration width, not a prescribed setting; working systems use hundreds of dimensions.
CBOW averaging step. Around the center word "bank", suppose the four neighbor embeddings are , , , and (toy two-dimensional vectors). The context vector is their average:
This single averaged vector plays the role that the one center word's embedding played in skip-gram, and everything downstream — context matrix, softmax, loss — proceeds identically. Sense check: averaging four same-scale vectors produced a same-scale vector, so no magnitude blow-up enters the softmax.
After training, the recipe for deployment is symmetrical: take the neighboring words, average their vectors, multiply by the trained matrix — and you get the embedding of the central word.
Both models share one more property worth stating directly: they calculate word embeddings purely from neighboring information, through a loss-minimization process with no nonlinearity anywhere — just linear transformations and the softmax.
Word2vec learns compact vectors by making words predict their neighbors: skip-gram goes center-to-neighbors through a row lookup in followed by the independent context matrix ; CBOW averages neighbor embeddings first and predicts the center. Inputs are always vocabulary-sized one-hots; outputs are always softmax distributions; the learned middle is the embedding.
15.12 Attention for Sequence-to-Sequence Translation
15.12.1 Encoder-Decoder with a Context Vector
Why does word-by-word translation fail? Because languages reorder everything: the adjective that precedes its noun in English may follow it in German, and a pronoun may need a whole phrase. The translator must be able to look back at all source words while emitting each target word — that looking-back mechanism is attention.
Next, a brief revisit of attention in machine translation — material touched in NLP as well as DNN contexts. Inputs are the source words through ; the target is the translated sentence . The basic engine is an encoder-decoder. A forward-directional RNN walks the source sentence producing hidden states , where T tracks the sentence length in the source language — it tries to predict the future from the past. A bidirectional RNN additionally runs over the sentence in reverse so that each position knows what happened before and after it.
The forward hidden state and the backward hidden state at each position are multiplied by learned weights and combined into a context vector. That context vector feeds the output RNN, which predicts the words of the translated language. The consequence: translation does not proceed word-to-word in isolation. Each translated word is produced based on the current word together with the context vector computed by the bidirectional RNN — the weights decide what type of attention to provide to words from the past and present.
15.12.2 Asynchronous Processing and the Landmark System
An important structural fact: this sequence-to-sequence modelling for language translation is asynchronous. You process the entire source sentence first, creating the context vector, and only then decode the destination-language sentence from it.
Writing the combination precisely: at decoding step , the context vector is a weighted average over all encoder states,
where is the number of source words, is the (bidirectional) hidden state for source position i, and is the attention weight telling the decoder how much source word i matters when producing target word t. The weights are computed and normalized so each column sums to one:
Here is the decoder's previous state; , , and are learned matrices and vector whose shapes make the bracketed expression a single scalar per source position. The inner plus dot product is called additive attention because the two transformed states are added before scoring.
Attention weights on three source positions. Suppose the decoder's previous state produces raw scores against the three encoder states. Exponentiating gives , whose sum is ; normalizing yields . The context vector is then — overwhelmingly a summary of the first source word, exactly as if the translator were staring at one word while glancing at the rest. Sense check: weights are non-negative and sum to one, so stays inside the convex hull of the hidden states no matter what values they take.
This encoder-decoder architecture with additive attention — associated with Bahdanau — was first trained using a parallel corpus of English to German. Hold that thought: this attention machinery returns shortly as the ingredient that builds richer word representations than word2vec can offer.
Pitfalls:
- Calling this processing synchronous. It is asynchronous by design: encode everything first, then decode — mixing the two phases is the classic misunderstanding.
- Thinking the context vector is fixed once computed. A fresh is formed at every decoding step, with new attention weights each time.
- Confusing these learned scalar weights with hard selections. Attention soft-routes information; nothing literally "picks" one word.
Encoder-decoder translation runs asynchronously: a bidirectional RNN encodes the source into hidden states, and at every output step an attention-weighted sum tells the decoder which source words matter now. This same machinery becomes the bridge to contextual embeddings next.
15.13 The Word Sense Disambiguation Problem
15.13.1 One Embedding per Word Is Not Enough
Here is the crack in word2vec, and it hides in plain sight: what happens to a word that means two completely different things? The embedding machinery hands it exactly one vector — so half of its life, the vector is simply wrong.
Whether you use CBOW or skip-gram, each word receives one unique embedding — the example given: "World Bank" associates the word bank with a single unit, a unique embedding. But some very common words change meaning with context. Compare:
- "I went to the bank for withdrawing some money."
- "I went to a river bank."
The word bank means completely different things in these two sentences — a financial institution in one, the sloping edge of a waterway in the other. Assigning the same word embedding to bank in both cases conveys something wrong, because the semantics of the word depend on the entire contextual information of the sentence where it occurs.
The scale of the problem is easy to underestimate. Linguists call such words polysemous, and they are not rare curiosities: high-frequency English words are almost all polysemous ("run", "light", "cell", "mean"). Since embeddings power downstream tasks — sentiment analysis, entity recognition, question answering — a single fixed vector for "bank" injects noise into every one of those systems whenever context picks the other sense.
Why neighbors cannot rescue a static vector. In training text, "bank" appears near money-words in some sentences and near river-words in others. Skip-gram therefore drags its single embedding toward a compromise position — pulled by both neighborhoods at once. Geometrically, if financial-bank would live at point and river-bank at point , the static embedding settles somewhere between them, near . It is close to neither sense precisely where it matters, yet it sits far from unrelated words like "quantum". The failure is structural, not a training artifact. Sense check: averaging two distinct meanings yields a vector matching neither — the geometric version of saying something that means nothing.
Pitfall: assuming more training data fixes this. More data sharpens the average but never splits it; no amount of corpus growth makes one vector occupy two places. The fix must come from architecture — representations conditioned on context.
So word2vec models cannot perform word disambiguation — handling a same word that means different things depending on context. Fixing this requires embeddings that incorporate contextual information about the entire sentence, even the entire document. That requirement drives the next two models: GloVe enriches the static embedding itself with global statistics, while CoVe and its successors make the embedding context-dependent.
One word, one embedding fails for polysemous words: "bank" needs different vectors beside "money" and beside "river." Static methods cannot disambiguate by construction — the escape route is contextual computation, which GloVe approaches from the counts side and CoVe attacks directly next.
15.14 GloVe: Global Vectors
15.14.1 Combining Local and Global Information
GloVe — global vectors — extends word2vec in a specific direction. Word2vec exploits only neighborhood information: whatever words occur immediately in the past and future, within the window. But often the meaning of a word depends on what happens globally across the whole corpus — "astronomer" may rarely sit within five words of "telescope," yet corpus-wide their association is unmistakable.
GloVe, introduced in 2014, aims to combine both the local information and the global information available from co-occurrence matrices. (A note on origins: the session credited it to Google; the standard attribution is Stanford's NLP group, whose researchers published it at EMNLP 2014 — word2vec, by contrast, is the Google contribution from 2013. Either way the model itself is unchanged.) Technically, GloVe merges the count-based factorization of the co-occurrence matrix with the context-prediction flavor of the skip-gram-style models: it trains embeddings that predict logarithms of global co-occurrence counts, so every cell of the giant Section 15.8 table gets squeezed into the vectors rather than ignored.
15.14.2 The Ratio Intuition: Ice, Steam, Solid, Fashion
The key observation uses a quartet of words: suppose there are two words, ice and steam, and probe words such as solid and fashion. The word solid is related to ice a lot more strongly than to steam — ice is solid. So the relationship strength should be captured by a ratio of co-occurrence probabilities. Define as the probability that probe word appears in the context of word , estimated from the co-occurrence matrix. Then:
Reading meaning off ratios. Using illustrative corpus estimates in the style of the original analysis:
| probe | ratio | ||
|---|---|---|---|
| solid | large | tiny | far greater than 1 |
| water | moderate | high | below 1 |
| fashion | minuscule | minuscule | roughly 1 |
Solid occurs around ice constantly and around steam almost never, so the ratio explodes upward — the pair ice/steam is being distinguished through the lens of solid. Fashion is unrelated to both, both probabilities collapse toward zero together, and their ratio settles near one — the neutral verdict. Water sits closer to steam than to ice, tipping its ratio below one. Sense check: each row is a single number summarizing how the two target words differ with respect to that probe, which is exactly the differential information raw probabilities drown out.
The intuition crystallizes: what carries meaning is the ratio of the co-occurrence probabilities, not the probabilities themselves. Ratios isolate the differential affinity between word pairs and wash out global frequency quirks — a hyper-frequent word like "the" inflates every raw probability, but leaves well-chosen ratios nearly untouched.
15.14.3 From Ratio Condition to Loss Function
GloVe designs the embedding structure so that a function of the linear difference between two word vectors reproduces that ratio:
Here and are the embedding vectors of the two compared words, is the separate context-vector embedding of the probe word, and denotes a dot product. Where the co-occurrence of with greatly exceeds that of with , the right side departs far from one, and the left side must follow.
The remaining design choices fall out with short algebra, none hidden. First, write the conditional probability as a normalized count, , where is the co-occurrence count of words i and j and . Substituting into the ratio, the normalization constants cancel:
Choosing turns the left difference into a quotient, which must now equal the count quotient on the right. Taking logarithms splits it back into a subtraction:
Both sides must equal some constant independent of the free index; symmetrizing by swapping the roles of word and context, adding learnable bias terms to absorb the constants, and regressing the dot products directly onto yields the training loss — minimize the weighted squared residuals over the whole matrix:
Here is a fixed weighting function that stops rare pairs (noisy counts near zero) and ultra-frequent pairs (like "the") from dominating the sum; a standard choice caps its growth and rises gently for small counts.
Every ingredient in has a role: the dot product wants to predict the log count; the biases absorb frequency effects; the weight balances rare against common pairs; and minimizing forces vector geometry to mirror the global co-occurrence structure built in Section 15.8.
The net effect: you go from a vocabulary-sized co-occurrence structure to a much smaller representation — is the dimensionality of the word vectors, like 300 — obtained by minimizing this whole function. Everything else in the expression consists of the one-hot-style indexing vectors and the counts from the co-occurrence matrix. Summing up the technique: GloVe effectively combines local information — captured by the ratio-of-probabilities side — with global information captured by the counting method, the co-occurrence matrix.
Pitfall: reading GloVe and skip-gram as unrelated competitors trained by different philosophies. They are close cousins — GloVe's loss can be viewed as a reweighted skip-gram objective; the practical distinction is that GloVe consumes precomputed global counts while skip-gram streams local windows.
GloVe turns the ratio intuition into algebra: exponentiate the difference of dot products, equate to count ratios, take logs, and least-squares-fit embeddings to log co-occurrence counts. Local prediction logic meets global counting, compressing terabyte-scale tables into 300-dimensional meaning.
15.15 CoVe: Context Vectors
15.15.1 Supervised Pretraining on Translation
CoVe's bet: if a model is forced to translate whole sentences well, its internal word states must already encode context — you cannot pick the right German word for "bank" without knowing which English sentence it lives in.
Word2vec and GloVe are two earlier solutions to representation learning; neither solves disambiguation. The CoVe model — context vector model — attacks it directly. CoVe takes as input the GloVe-encoded vectors — not the one-hot representations of words, but GloVe embeddings — and passes them through a bidirectional LSTM, learning attention as it trains on an English-to-German parallel machine-translation dataset.
Pause on the supervision split, because the session flagged it twice:
- Creating GloVe vectors out of the original one-hot embeddings is unsupervised / self-supervised learning — the corpus supplies everything; no human labels anywhere.
- Training the bidirectional LSTM that produces the context-aware states is supervised learning, because it leans on the English-to-German translation pairs: each source sentence comes paired with its human-translated target.
Inside the translation decoder, the outputs are calculated through a combination of LSTM, softmax, and tanh components — the German-side words emerge starting from English words as input, whose GloVe vectors pass through the attention network of Section 15.12.
15.15.2 The CoVe Representation and Task-Specific Heads
The CoVe representation of a word concatenates three things: the forward-directional BiLSTM hidden state, the backward-directional BiLSTM hidden state, and the GloVe vector of the word. Concatenation is the operative word — the context-aware LSTM outputs are glued onto the static GloVe embedding, so the final vector carries both "what this word means everywhere" (GloVe) and "what it means here" (BiLSTM states). If each hidden state has 300 entries and GloVe gives 300, the CoVe vector for one word is 900 numbers long, arranged as [forward | backward | GloVe].
Now disambiguation falls out for free. The phrase World Bank will be associated with a different word embedding depending on the sentence: "I went to a river bank" produces one CoVe representation, while "I went to the bank for withdrawing money" produces another — because the input sentences drive different hidden states in the forward and backward directions. Same input token, different surrounding sentence, different output vector. That is the beauty of the CoVe model.
The pipeline organizes into stages:
- A generic feature stage: GloPlus BiLSTM states pretrained on translation — reusable across tasks.
- A task-specific model built completely around the end task — sentiment analysis, part-of-speech tagging, or question answering — sitting on top of those features.
The generic part transfers; the head customizes. Empirically, GloVe plus CoVe performs significantly better than GloVe alone across various tasks — question answering, IMDb sentiment analysis, and two further benchmarks.
The evident limitation: because the contextual stage needs supervised translation pretraining — parallel corpora are themselves expensive labeled data — the general applicability of the scheme is somewhat constrained. This bottleneck is exactly what the next section's self-supervised giants remove.
Pitfall: assuming the BiLSTM states replace the GloVe vector. They concatenate with it; dropping the static component throws away general-purpose lexical knowledge the contextual states were never trained to encode on their own.
CoVe makes embeddings contextual by concatenating bidirectional-LSTM states (trained supervised on translation) with static GloVe vectors — so "bank" finally gets different vectors in different sentences. The price: dependence on scarce parallel corpora, which GPT-style self-supervised pretraining soon eliminates.
15.16 Deep Contextualized Representations and GPT
15.16.1 Stacking LSTMs for Multiple Granularities
RNN-based language models served successfully for many tasks — language translation, audio to speech and speech to audio conversions, text generation — but performance plateaued. The next leap came from going deeper: instead of the single bidirectional LSTM layer that CoVe used (past-to-present and present-to-pass directions combined), people stacked multiple layers of LSTM networks.
Depth bought granularity: lower layers capture something very concrete — word order, part-of-speech patterns, local phrases — while higher layers capture more abstract information like syntax-wide structure and semantic roles. One representation stack therefore holds a hierarchy of linguistic features, with each layer building on the abstraction of the one beneath it.
15.16.2 GPT: Transformers Replace LSTMs
The key innovation inside today's popular GPT models: replace LSTM calculations with transformer calculations. Two properties make transformers attractive here:
- Unbounded look-back. Transformers have the nice property of looking into the past forever — no fading memory. Where an RNN's influence from sixty words ago decays into noise, a transformer's attention can reach token one of the document as easily as the previous one.
- Multi-head attention. Beyond one attention mechanism, they admit multi-head attention: different heads calculate different things simultaneously, each head free to track its own kind of relationship — one head might follow subject–verb links while another follows topic drift.
GPT uses the standard transformer structure not once but 12 blocks stacked one after the other. Each block performs masked multi-head self-attention, followed by layer normalization, then a feed-forward network, and that composition repeats 12 times.
The mask is the load-bearing piece. In self-attention every position would normally see every other position; masking sets the scores for future positions to negative infinity before the softmax, so they receive zero weight after normalization. Concretely, when predicting token , positions are invisible. GPT strictly refuses to use any information from the future — everything is captured from the past alone, making the model autoregressive, generating left to right: predict the next token from all previous ones, append it, repeat.
15.16.3 One Architecture, Many Tasks
A second pillar of GPT: everything rests on unsupervised learning. The full model is pretrained on large volumes of raw corpus; only for fine-tuning is a small amount of supervised, labeled data used. Contrast this with the CoVe pipeline, where frozen contextual features feed separately built task-specific models — GPT does not do that. It fine-tunes one architecture on whatever downstream data arrives, updating the same weights rather than bolting on new heads over frozen features.
The representation proves remarkably versatile across problem formats:
- Classification of a single input — feed the document, read off a label.
- Contiguity checking: during pretraining, two sentences are placed together, and the model learns from raw text alone to classify whether the pair occurred one after the other in the source or sit far apart.
- Entailment and similarity: two inputs sit side by side — a premise and a hypothesis — using start and delimiter markers; pretrained GPT detects entailment and detects similarity between two sentences.
- Question answering: the same backbone learns QA given the training format, with only a small supervised set for fine-tuning.
So GPT learns representations that let one architecture solve a broad variety of problems — all built from the multi-head attention and masked attention blocks covered in the transformer material.
Pitfalls:
- Saying "GPT sees the whole sentence." It sees only the past of any prediction point — that is what the mask enforces and what makes generation possible at all.
- Confusing GPT's fine-tuning with CoVe's feature extraction. CoVe freezes its contextual stage and trains task models on top; GPT updates the pretrained network itself.
- Treating the twelve blocks as optional depth. Stacked layers are where the concrete-to-abstract feature hierarchy lives, exactly as in stacked LSTMs.
GPT stacks 12 masked-multi-head-attention transformer blocks, pretrains them self-supervised on raw text, and fine-tunes the single resulting model across classification, contiguity, entailment, similarity, and question answering — unbounded past-looking attention replaces both the LSTM and the separate task heads.
15.17 BERT Preview: Bidirectional Pretraining
15.17.1 Masked Language Modeling
BERT, contemporary with GPT, takes the opposite directional bet: it uses a bidirectional transformer for language understanding. Where GPT applies masked self-attention to bar future information and generates sequentially in autoregressive fashion, BERT ingests information flowing in both the forward and the backward direction — every word may look left and right during training.
Its signature training scheme is the masked language model: given the corpus, it probabilistically determines a few words to hide — about 15% of words — and tries to estimate the masked values given everything else present.
One masking step. Take the sentence "the capital of France is Paris." Suppose BERT hides France and Paris, producing "the capital of [MASK] is [MASK]." The model must fill both blanks using only the surrounding unmasked tokens — and it can only succeed by understanding direction-independent structure: what precedes a country's name pattern ("the capital of ___"), what a capital-of relation implies, and which entity fits after "is". No human supplied these labels; the corpus did, by deletion. Sense check: each prediction uses evidence from both sides of the blank, something GPT's mask structurally forbids at training time.
Predicting the hidden middles from both sides is exactly the "predict what is occluded from the visible" self-supervised task from the taxonomy in Section 15.8 — the same principle that drove word2vec's windows, now applied with full bidirectional attention instead of a fixed neighborhood.
The trade-off worth carrying into the next session: because every position sees both directions, BERT is a superb understanding engine (classification, similarity, QA over given text) but not a natural generator — nothing in its training asked it to produce the next word from the past alone. The discussion of BERT resumes next session, alongside vision applications of the generative toolkit.
BERT flips GPT's bet: bidirectional attention plus masked-language-model pretraining (~15% of tokens hidden) learns deep context from raw text — understanding without labels, generation sacrificed for comprehension. Full treatment arrives next session.
Exam Guidance Summary
This session's exam briefing, gathered in one place:
- Weighting: most questions relate to material covered after the midterm; only a few marks — around 20% or so — may come from pre-midterm topics. Calibrate revision time accordingly.
- Past papers: past years' question papers and their solutions have been shared; reviewing them is strongly encouraged as primary practice — question style repeats more than content does.
- Drill partner: ChatGPT is endorsed as a practice tool for working through the topics discussed — use it to generate extra problems and check your derivations line by line.
- Online quiz: the quiz is open — attempting it provides useful practice and revision ahead of the exam, with the better of two attempts counted.
- Final tips: tips for the finals will be shared in an upcoming session; watch for them.
- Permitted aid: a watermarked set of course material will be shared for printing and carrying into the exam room; this is expected to be the only permitted aid, but whatever the exam team announces is final — verify there before relying on it.
- Self-study boundary: the extra energy-based-model material beyond the core coverage is for your own knowledge; no specific questions will be asked from the parts not covered in session.
- Assignments: review your evaluated assignments promptly and request reevaluation where needed before course closure deadlines.
Exam note: Prioritize post-midterm material (roughly 80% of marks), drill with past papers first, use the quiz attempt as a timed rehearsal, and print the watermarked material once the exam team confirms it is permitted.
Key Industry Applications
Where the models of this lecture earn their keep:
- Anomaly detection: trained EBMs flag outliers as points with negligible probability relative to the training distribution — a direct industrial use of relative-probability comparison. Fraud teams, network-security monitoring, and industrial quality control all run on this pattern.
- Image denoising: the Ising-style formulation recovers true pixel values from noisy observations by maximizing the posterior over neighborhoods — the same mathematics behind medical imaging cleanup and low-light photography enhancement.
- Face and ImageNet synthesis: modern EBMs coupled with Langevin sampling generate convincing face samples and ImageNet-scale imagery, proving the sampling machinery scales beyond toy corpora.
- Large language assistants: OpenAI's GPT-style systems generate sequentially; image generation in such systems proceeds slowly through internal diffusion-like stepwise denoising — the visible wait is the denoising chain running.
- Human-feedback tuning: platforms presenting multiple generations for user rating and then fine-tuning mirror contrastive-divergence-style adjustments driven by judged relative probabilities — community thumbs replace model-sampled negatives.
- Machine translation: Bahdanau-style encoder-decoder models with additive attention, trained on English-to-German parallel corpora; the same machinery powers CoVe pretraining and every attention-based translator since.
- Text classification stacks: sentiment analysis (including the IMDb benchmark), part-of-speech tagging, and question answering built atop GloVe+CoVe or fine-tuned GPT/BERT-style representations.
- Embedding infrastructure: word2vec (CBOW and skip-gram) and GloVe remain the baseline industrial word representations, with negative sampling enabling efficient training at vocabulary scale — recommendation engines, search ranking, and ad-targeting systems all consume these vectors.
UDL Lecture 15 notes · Energy-Based Models and Natural Language Processing Applications
Sections Breakdown
Definition of energy-based models: p(x) = exp(f(x))/Z, positivity via exponentials, normalization via the partition function, and the flexibility of neural scoring.
Three hard problems of EBMs and why relative probability comparisons cancel Z, enabling anomaly detection and denoising.
The EBM family tree: Ising model for denoising, product of experts, Boltzmann machines, and restricted Boltzmann machines.
Training EBMs: the numerator-denominator tug of war, the contrastive divergence procedure, and the full log-likelihood gradient derivation.
Sampling machinery: how MCMC accepts and rejects candidates, the score function, and Langevin dynamics with worked numeric traces.
State of generative modeling: the full family tour, unavoidable trade-offs, sequential generation speed, and human-feedback tuning.
Label scarcity, self-supervised and semi-supervised framings, and the road map from word2vec to BERT.
Building word-to-word co-occurrence matrices, reading semantics off counts such as hot-steam versus hot-ice, and the four-terabyte storage problem.
One-hot embeddings: construction, memory waste, and meaning blindness shown through good-versus-nice arithmetic.
Unigram and bigram independence assumptions, the permutation-invariance pitfall, and conditioning spans up to transformers.
CBOW and skip-gram objectives, vocabulary-sized one-hot inputs, embedding and context matrices, negative sampling, and full architecture traces.
Encoder-decoder translation with bidirectional RNNs, additive attention weights, context vectors, and asynchronous processing.
Why a single static embedding fails for polysemous words like bank, and why more data cannot fix it.
GloVe: combining local windows with global co-occurrence counts, the ratio intuition, and the least-squares loss derivation.
CoVe: supervised translation pretraining with BiLSTMs concatenated onto static GloVe vectors for context-aware representations.
Stacked LSTMs for multiple granularities and GPT's twelve masked multi-head attention blocks fine-tuned across many tasks.
BERT's bidirectional transformer pretraining with masked language modeling at roughly fifteen percent masking.
Exam weighting across midterm topics, past-paper strategy, permitted aids, and revision priorities.
Where lecture mechanisms run in industry: anomaly detection, denoising, synthesis, translation, feedback tuning, and embedding infrastructure.
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
Energy-Based Models: The Core Formulation
Must-know: EBM probability is exp of the network score divided by the partition function Z_theta; positivity comes free from the exponential, normalization from Z.
?? Top pitfall: Treating f_theta(x) itself as a probability — it is an unbounded real-valued score, not a probability.
Self-check: Why is p_theta(x) always non-negative regardless of the network output?
Connects to: 15.2, 15.4.
Strengths and Trade-offs of Energy-Based Models
Must-know: The ratio of two model probabilities is exp(f(x) - f(x')); Z cancels because it depends on theta only.
?? Top pitfall: Assuming you must compute Z_theta before using the model — comparisons never need it.
Self-check: Why does Z_theta cancel in p(x)/p(x')?
Connects to: 15.1, 15.5, 15.3.1.
Basic Energy-Based Model Families
Must-know: Ising posterior factorizes into per-pixel corruption terms times neighbor smoothness terms; the RBM joint contains only cross terms w_ij x_i z_j with no x_i x_j or z_i z_j terms.
?? Top pitfall: Thinking 'restricted' removes all connections — it removes only same-layer couplings; visible-to-hidden weights remain.
Self-check: Which terms are absent from an RBM's joint distribution, and what does each absence forbid?
Connects to: 15.1, 15.2.2, 15.4.
Training an Energy-Based Model
Must-know: Gradient of log likelihood = grad f on real data minus expectation of grad f under model samples; the second term requires sampling from the current model.
?? Top pitfall: Trying to compute the second term without sampling — it is exactly where the intractable partition function hides after differentiation.
Self-check: Why does differentiating log Z_theta force you to sample from p_theta?
Connects to: 15.2, 15.5, 15.6.
Sampling from an Energy-Based Model
Must-know: Score function = gradient of log p w.r.t. x (not theta); for EBMs it equals grad_x f_theta(x); Langevin update adds epsilon*score + sqrt(2*epsilon)*Gaussian noise.
?? Top pitfall: Dropping the noise term — the chain then freezes at the nearest mode instead of sampling the whole distribution.
Self-check: Why does the score of an EBM not involve Z_theta?
Connects to: 15.2.2, 15.4, 15.6.
Where Generative Modeling Stands Today
Must-know: Most exam questions come after the midterm (~20% or so from pre-midterm topics); know each generative family and its defining trade-off.
?? Top pitfall: Assuming one model dominates on all criteria — every family sacrifices at least one desirable property.
Self-check: Why do GPT-style image generators respond slowly?
Connects to: 15.4, 15.5, 15.16.
Why Unsupervised Learning Matters for Language Data
Must-know: Only a tiny fraction of digital data carries labels; unsupervised/self-supervised techniques are required to monetize the rest; semi-supervised = mostly unlabeled plus small labeled subset for fine-tuning.
?? Top pitfall: Using 'unsupervised' and 'self-supervised' interchangeably — self-supervision explicitly constructs prediction targets from the inputs themselves.
Self-check: What distinguishes semi-supervised from self-supervised learning?
Connects to: 15.8, 15.11, 15.16.
Word-to-Word Co-occurrence Matrices
Must-know: Co-occurrence counts encode semantic relatedness; a 1,000,000-word vocabulary yields ~10^12 cells ≈ 4 TB at 4 bytes per entry.
?? Top pitfall: Memorizing exact cell digits instead of reading relative magnitudes — the ordering of counts is the signal.
Self-check: Why do ice and steam rarely co-occur in a typical corpus?
Connects to: 15.9, 15.11, 15.14.
One-Hot Embeddings and Their Limits
Must-know: One-hot dimension equals vocabulary size; distinct one-hot vectors are orthogonal (dot product zero), so no geometric similarity reflects meaning.
?? Top pitfall: Expecting vector distance between one-hot words to reflect semantic distance — it cannot, by construction all pairs sit at the same distance sqrt(2).
Self-check: What is the dot product of the one-hot vectors for 'good' and 'nice', and why?
Connects to: 15.8, 15.11.
N-gram Language Models
Must-know: Unigram joint = product of P(w_k); bigram joint chains P(w_k | w_{k-1}); each model's independence assumption determines what word order it can capture.
?? Top pitfall: Forgetting that unigram scores are permutation-invariant — 'dog bites man' equals 'man bites dog'.
Self-check: Why do unigrams assign identical scores to a sentence and any scrambling of it?
Connects to: 15.8, 15.11, 15.16.
Word2vec: Learning Embeddings by Prediction
Must-know: Inputs to CBOW and skip-gram are one-hot vectors of length V; W is V x d (row lookup), W' is d x V, and W' is NOT W transpose; training minimizes negative log likelihood with negative sampling avoiding the full softmax denominator.
?? Top pitfall: Assuming the context matrix equals the transpose of the embedding matrix — they are learned independently.
Self-check: What is the shape of h after multiplying a one-hot input by W, and why does one-hot multiplication act as a row lookup?
Connects to: 15.9, 15.10, 15.14.
Attention for Sequence-to-Sequence Translation
Must-know: Context vector c_t = sum_i alpha_{t,i} h_i with softmax-normalized additive scores; processing is asynchronous (encode fully, then decode).
?? Top pitfall: Treating the process as synchronous — the entire source sentence is encoded before decoding begins.
Self-check: Why does the context vector change at every decoding step?
Connects to: 15.15, 15.16.
The Word Sense Disambiguation Problem
Must-know: Word2vec cannot disambiguate: one embedding per word regardless of sentence context; polysemy demands contextual representations.
?? Top pitfall: Believing more training data can split a static embedding into two senses — only architectural change can.
Self-check: Give two sentences where 'bank' needs different embeddings and explain why word2vec cannot provide them.
Connects to: 15.11, 15.14, 15.15.
GloVe: Global Vectors
Must-know: Design condition F((w_i - w_j)^T w_k~) = p(k|i)/p(k|j); with F = exp this yields loss J = sum g(C_ij)(w_i^T w_j~ + b_i + b_j~ - log C_ij)^2.
?? Top pitfall: Attributing GloVe to Google — it is Stanford (2014); word2vec is the Google model.
Self-check: Why does the normalization constant C_i cancel in the probability ratio?
Connects to: 15.8, 15.11, 15.13.
CoVe: Context Vectors
Must-know: GloVe creation = unsupervised/self-supervised; BiLSTM training on translation pairs = supervised; CoVe vector = concat(forward BiLSTM, backward BiLSTM, GloVe).
?? Top pitfall: Saying CoVe replaces GloVe vectors — it concatenates them with the contextual LSTM states.
Self-check: Why does CoVe disambiguate 'bank' while GloVe alone cannot?
Connects to: 15.12, 15.13, 15.14, 15.16.
Deep Contextualized Representations and GPT
Must-know: GPT = 12 blocks of masked multi-head self-attention + layer norm + feed-forward; masking blocks all future information, making it autoregressive; one pretrained model fine-tunes on many tasks unlike CoVe's frozen-feature pipeline.
?? Top pitfall: Claiming GPT attends to the whole sentence — the mask forbids future positions at every prediction point.
Self-check: What does the mask in GPT's self-attention do, and why is it essential for generation?
Connects to: 15.12, 15.15, 15.17.
BERT Preview: Bidirectional Pretraining
Must-know: BERT = bidirectional transformer + masked language model (~15% of tokens hidden); GPT = masked (past-only) autoregressive generation; both pretrained self-supervised.
?? Top pitfall: Mixing up the two masks: GPT masks future positions to enable generation; BERT masks random tokens to force bidirectional reconstruction.
Self-check: What fraction of words does BERT typically mask, and what does it predict them from?
Connects to: 15.8, 15.16.
Exam Guidance Summary
Must-know: Most questions come after the midterm (~20% or so from earlier topics); review past years' papers and solutions; extra EBM material beyond session coverage is not examinable.
?? Top pitfall: Spending equal revision time on pre- and post-midterm material despite the skewed weighting.
Self-check: What fraction of marks may come from pre-midterm topics?
Key Industry Applications
Must-know: Relative-probability comparison (EBMs) is the engine of anomaly detection; Ising posteriors denoise images; negative-sampled word2vec/GloVe remain baseline embedding infrastructure.
?? Top pitfall: Listing applications without naming the mechanism behind each one.
Self-check: Which lecture mechanism directly supports anomaly detection?
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.