Skip to main content
Natural Language Processing

Perplexity and Neural Language Models

Published: 2026-08-13
Level: postgraduate
Audience: Postgraduate students in Natural Language Processing

5.1 Language Modeling Recap and the Evaluation Question

5.1.1 The Language Modeling Task

Hook: Your phone keyboard suggests the next word while you type. How does it know that "I always order pizza with cheese and" is most likely followed by a topping — and not by "Tuesday"? That guessing skill is exactly what a language model is, and this session's question is how to measure how good the guessing is.

A language model (an LM) is a system that assigns a probability to a sequence of words. The probability is a score between 0 and 1 that says "how much does this string of words sound like the language we trained on." A high score means the sequence reads naturally; a low score means it looks odd. The core task, in one line: given the words seen so far, predict the probability of the next word. This one skill powers machine translation, spelling correction, and speech recognition — all of them pick the most natural-sounding option among candidates.

The previous session built these models the statistical way, with n-grams. Both the n-gram approach and the neural approach need one thing above all: a corpus (a large body of plain text used as training data). The key point is that you do not need labeled data. A language model learns from raw text alone — there are no labels to collect, because the text itself provides the answer: every word is a "next word" you can train on. If you are building a language model for English, any English text works — Wikipedia articles, newspaper articles, anything in textual format. The same training corpus requirement holds for neural language models, coming later in this session.

The n-gram recipe from last time: a bigram probability conditions the next word on the previous word, a trigram on the previous two, and a unigram on nothing at all. In symbols, the bigram probability is and the trigram is , each estimated by counting how often the pattern appears in the corpus and dividing. Unigram is the fallback when no higher-order counts exist.

Scope: the zero-probability disaster. The classic problem with plain n-grams is zero probability: a combination that never occurred in the training data gets probability exactly zero. Because a sentence's probability is a product of per-word probabilities, one zero factor wipes out the whole sentence score — and it also breaks evaluation, since perplexity divides by that probability. This is why every real n-gram system applies a fix from the next section.

5.1.2 Zero-Probability Fixes: Laplace Smoothing, Interpolation, Back-Off

Laplace smoothing (add-one smoothing) is the simplest fix: give every unseen event a small non-zero count. The smoothed bigram probability adds 1 to every pair count and adds the vocabulary size (the number of different words) to the denominator:

The catch: smoothing changes the data slightly, which can distort probabilities that are otherwise well estimated. Add-one is a blunt instrument — with a big vocabulary the "+" in the denominator is large, and common pairs lose more probability than feels fair. That is why two other techniques matter.

Interpolation combines all the n-gram orders at once — trigram, bigram, and unigram — each with a weight. The verbal recipe: give more weight to the higher-order n-grams because they capture the context better. The weights , , (the Greek letter lambda) are hyperparameters set by the developer, with the single constraint that they sum to one. This matches the standard form in the reference material: weights the trigram, the bigram, and the unigram.

The lambdas can also be learned from held-out cross-validation data rather than hand-set; that was mentioned as possible in real-world use but not required here. Whatever their source, the constraint is what keeps the blend a proper probability distribution.

Worked example: interpolated estimate with real numbers. Suppose the weights are , , (sum , as required). For predicting the word after the context "pizza with", the three orders give: trigram , bigram , and unigram . The interpolated estimate is:

Sense-check: 0.44 sits between the highest component (0.6) and the lowest (0.1), pulled toward the trigram because it has the largest weight — exactly what "give more weight to higher-order n-grams" means. The zero problem is gone because the unigram probability is never zero, so the blend never collapses to zero.

Back-off is the alternative: when the count for a higher-order gram is missing, back off to the next lower gram. If the trigram is unseen, fall back to the bigram; if that fails too, the unigram. Think of it as a ladder of context: start at the top rung, and step down only when the current rung has no evidence. Both interpolation and back-off exist to kill the zero-probability problem by borrowing strength from lower-order statistics. The difference between them is when they borrow: back-off switches down only when needed, while interpolation always blends all orders.

Pitfalls:

  • One zero is enough to destroy a whole sentence score — never ship a raw n-gram model without a fix.
  • Smoothing shifts probability from common events to rare ones; heavy smoothing (large ) can badly distort good estimates.
  • Interpolation weights must sum to exactly 1; anything else is not a probability.
  • Back-off needs a discounting scheme so that the probabilities still sum to 1 after mass is redistributed.

Recap + bridge. Language modeling is next-word prediction trained on unlabeled text, and zero probabilities are the enemy of n-gram models. The fixes — Laplace smoothing, interpolation, back-off — matter because evaluation builds on the same probabilities. One closing point frames the rest of the session: everything about evaluation that follows applies to all language models. Large language models are nothing but neural language models — transformers, GPT, BERT, even agentic AI all rest on deep learning architectures. So the evaluation measures below work for n-gram models and LLMs alike.

Real-world & domain connection. Language models are the hidden judge inside everyday text systems. Spelling checkers use them to choose "minutes" over "minuets" in context, speech recognizers use them to pick "I saw a van" over the identically sounding "eyes awe of an", and machine translation uses them to rank fluent candidates. Modern LLMs are the same idea scaled to billions of parameters, which is why the evaluation question that comes next in this session is asked about them too.

5.2 Intrinsic Versus Extrinsic Evaluation

5.2.1 Two Ways to Evaluate

Hook: Two cars look identical on paper — same horsepower reading, same spec sheet. Which one wins the actual race? The same question applies to language models: do we judge the number on the bench, or the model in the real task? Evaluation in NLP answers both.

Any evaluation has two ingredients. First, test on a test dataset: a model may work well on training data, but it must also run well on unseen data. A model that only memorizes its training text is useless. Second, pick an evaluation measure — the number that tells you how well the model ran on that unseen data. The standard measures are likelihood, log likelihood, entropy — and the most popular, perplexity, which the next section builds up.

There are two levels of evaluation, and the contrast is the classic black-box/white-box contrast from software testing. Intrinsic evaluation measures the internal components of the model itself. Perplexity is intrinsic: it scores the language model directly, with no outside task involved. Extrinsic evaluation scores the model by plugging it into a real application — spell checking, speech recognition, or a machine translation (MT) system — and checking whether the end product is good. If the language model produces a good English-to-Hindi translation inside an MT system, that is extrinsic evidence: the whole system works, so the model inside it did its part.

Scope: extrinsic evaluation has two drawbacks. You have to wait until the entire system is built before you can evaluate anything, and it tells you nothing about the individual components: if the translation is bad, you do not know whether the language model or some other part failed. To test the language model component on its own, you use perplexity. Black box = only functionality matters; white box = evaluate each component separately. Extrinsic is the gold standard but slow; intrinsic is fast but only a guide — the two can even disagree, so trust the extrinsic test when stakes are high.

The two levels line up neatly:

Dimension Intrinsic evaluation Extrinsic evaluation
What it measures The model's own scores (perplexity) The end product's quality (e.g., translation accuracy)
Needs a full system built? No Yes
Blames components? Yes, the model alone No — a bad result does not say which part failed
Speed Fast Slow (days of task testing)
When to use Quick pilot checks, model selection Final verdict on a real task

To compare two car engines, the true test is a real race (extrinsic), but it takes days to set up; a dynamometer reading in the garage (intrinsic) is fast and a decent hint. Same idea here: run the cheap intrinsic score to filter ideas, then pay for the expensive extrinsic test on the survivors.

Exam note: know the pair and their mapping — intrinsic = white box = scores the model directly (perplexity is the prime example); extrinsic = black box = scores the model through a real application like machine translation. Be ready to state why extrinsic evaluation is slow and why it cannot tell you which component failed.

Perplexity remains the popular measure even today, for LLMs and transformers everywhere, to check model efficiency or accuracy. When a new model is announced, its perplexity on a standard test set is one of the first numbers reported.

5.2.2 The Perplexity Name

Real-world & domain connection. There is an AI research tool named Perplexity, used for summarizing research papers. The name is likely borrowed from this evaluation measure — a fitting brand choice, since the tool's job is to digest text the way a language model would, and "perplexity" is the very number that measures how well a model understands text. The measure itself also powers the model selection workflow in industry: evaluation tools compute perplexity automatically at scale, and the model with the lower perplexity on your corpus is the one you ship.

5.3 Perplexity: Inverse Probability and the Nth Root

5.3.1 Predicting the Next Word: Why Unigram Fails

Hook: Play the Shannon game (named after Claude Shannon). Cover the next word in "I always order pizza with cheese and ___" and bet on what it is. A good model bets heavily on a topping — "mushrooms", "pepperoni" — while a weak model spreads its bet thinly across everything. Perplexity turns exactly this "how surprised is the model?" idea into one number.

A language model predicts the next token given a set of words. Take the phrase "I always order pizza with cheese and —". The probability of the next word is computed given all previous words. Since keeping the entire history is impossible, the model makes a Markov assumption (the session calls it the hidden Markov model assumption): the current word depends on the previous one word, the previous two words, or no words at all.

Unigram is terrible for this task. If you predict the next word without looking at any previous words, "fried rice" is as likely as anything else, because no context constrains it. Unigram is only used when nothing better is available. Bigram looks at the previous word "and" and asks: how often does "mushrooms", "pepperoni", or "fried rice" follow it? Better, but "and" is followed by many words in the corpus, so the model is still unsure. Trigram looks at "cheese and" — now the next word is much more constrained. The idea: the more useful context you feed in, the better the probability you can predict, and the better the probability, the better the language model.

What does "good" mean concretely? A good model assigns high probability to the correct word and, just as important, is not confused. If all candidate words get equal probability, the model cannot decide which to pick. If the correct word gets 0.5, the next gets 0.2, and the third 0.1, the choice is easy. Higher probability for the correct word means a good model.

Q: We saw something similar in the DNN course last semester — RNN models that predict the next words of a sentence. How is this different? A: It is the same idea. An RNN is a neural network, so that was a neural language model. You started with a simple feedforward network, then LSTM, then GRU. Those architectures predict the next word, and they can be used for other tasks as well. After the n-gram models, the next part of this session is exactly that: neural language modeling with feedforward networks, RNNs, and other deep networks.

A second student asked about ties between candidate words, and a third connected the idea to what they already knew from machine learning:

Q: If two words get the same probability, how does the model decide? A: We do not want the model to be confused. If the bigram gives equal probabilities, check the trigram — the word before that — to break the tie and get higher probabilities for the truly likely word. The quality of a language model is precisely this: the highest probabilities should go to the words most likely to occur after the given sequence. If the model cannot make one word stand out, it is a low-quality model. Interpolation is also a technique you can use to improve it.

Q: So there are two broad categories of language models — n-gram (unigram, bigram, trigram, ...) and neural (RNN and so on)? And perplexity is like the confusion matrix or accuracy from ML — an evaluation measure? A: Yes to both. N-gram and neural are the two categories, and neural language models are covered today. Perplexity is the evaluation measure, playing the same role as a confusion matrix or accuracy does for classification.

Finally, a student asked about the possible values of the measure itself:

Q: What is the range of perplexity values, since probabilities can be arbitrarily small? A: That is coming up. The rule to remember first: perplexity should be as low as possible.

5.3.2 Why Inverse Probability: Length Normalization

Why not just use the sentence probability directly as the score? The sentence probability is a product (joint probability) of the individual word probabilities — "we compute the multiplication joint probabilities". And a prediction can be a single word, a group of words, a sentence, a paragraph, or even a whole document — ChatGPT sometimes returns a PPT or a CSV summary of a document. The same idea applies at every length.

Here is the problem. Suppose one model predicts "I like cats" and another predicts "I like cute cats very much". Both sentences are correct, but the longer sentence gets a lower probability just because it has more words. A longer sentence has more multiplication factors, each below 1, so its product shrinks. That does not mean the second model is worse. Raw probability cannot compare models fairly when the outputs differ in length.

The fix is a length-normalized score: convert the whole-sentence probability into an average per-word confusion measure, and that is perplexity. In words: take the probability of the sequence of words, raise it to the power minus one over N, where N is the length of the sentence — the number of words whose probabilities were multiplied. Since the exponent is , it is the Nth root. This is the geometric mean across the N words of the inverse probabilities.

By the chain rule, the sentence probability is the product of per-word probabilities, each conditioned on the words before it:

Perplexity inverts that product and takes the Nth root:

With a Markov assumption the conditioning context shrinks — for a bigram model each factor becomes , and for a unigram model simply . The minus sign in the exponent is what turns "high probability" into "low perplexity"; the averages over the length, so long and short sentences become comparable.

Lowering perplexity is equivalent to maximizing probability. A good model gives high probability to correct words, so a good model has low perplexity, because perplexity is the inverse. Always aim to minimize it. And N is simply the number of words in the sentence.

5.3.3 Reading Perplexity Values

Perplexity makes models comparable even when the sentences differ in length — that is its main advantage.

Now the range question. Probability always lies between 0 and 1, but perplexity does not, because of the inverse and the root. Perplexity can take any whole-number value, depending on the sentence length, the probabilities, and the quality of the model. What does a perplexity of 10 mean? The model cannot decide among 10 different candidate words for the most likely next word. That is the intuitive reading. Ideally you want perplexity of 1 or 2 at most — the model is then deciding between very few words. A reasonable numeric range in practice is 10 to 400 at the maximum; higher than that is a bad model, and lower is always better.

One notation note: writing the exponent is just another way of writing the Nth root. For a number, an exponent of means the square root. So is the Nth root of .

Visual intuition. Picture perplexity as a bar chart of "effective choices per word." On the horizontal axis sit models of increasing context (unigram, bigram, trigram); on the vertical axis sits perplexity. The bars fall sharply as context grows — on Wall Street Journal text, the classic figures are 962 for a unigram model, 170 for a bigram, and 109 for a trigram. The landmark to notice is that adding one word of context roughly divides the number by two to six; the takeaway is that context is what buys certainty, and the height of the bar is literally "how many equally likely words the model is torn between."

5.3.4 Worked Example 1: "I love NLP models"

Worked example: perplexity of "I love NLP models". Take the sentence "I love NLP models". The model predicts a probability for every word using bigram, trigram, unigram, or the softmax output of a neural language model: , , , . The sentence probability is the product of these individual probabilities.

The slide supplies the product: . The sentence has 4 words, so . Perplexity is one divided by the probability, taken to the Nth root:

Step by step: . The fourth root of 400 is 4.47, because and .

In plain words: the Nth root of the reciprocal of the sentence probability. Interpreting the result: a perplexity of 4.47 means the model is as uncertain as if it were choosing between 5 equally likely words at each position. Final answer: . Sense-check: the model is sharp but not perfect — between 4 and 5 candidates per position is a very reasonable next-word guesser, which is exactly what a perplexity in the small single digits should feel like.

Lower perplexity is better, and there is a computational angle too: if the model has to choose among only a few words at each step, the next-word search takes less time.

5.3.5 Worked Example 2: Random Digit Generator

Worked example: the random digit generator. To see the capital N at work generically, take a random sequence generator that emits digits from 0 to 9. Each of the N positions has 10 equally likely choices, so each word has probability , and the probability of a length-N sequence is multiplied N times:

The N cancels — perplexity is 10, independent of length. Final answer: . Is that good? No. Among the digits 0 to 9, the model cannot select which comes next; every digit is equally likely. A perplexity of 10 says the model is choosing randomly among 10 candidates — the number is called the branching factor.

The re-explanation that followed: suppose the model did not give to every digit. Suppose it gave the digit 9 a probability of and spread small values like 0.1 and 0.2 across the rest. Then we would know the model expects 9 next, and it would be a good model. Equal probabilities everywhere means the model has no opinion, and a perplexity of 10 flags exactly that.

5.3.6 More Context, Lower Perplexity

A natural question: how does perplexity relate to the n-gram order? A 15-gram model will have lower perplexity than a lower-order n-gram model. Higher gram, lower perplexity. The reason is context: the more previous words you attend to, the better the model predicts the next word. This idea of attending to more context is exactly how the attention mechanism came into existence — all these ideas were borrowed from the earlier models. (Attention is covered post mid-sem, and the DNN course touched on it.)

But there is a catch. A 10-gram needs counts for 10-word sequences, and those may simply not exist in your training data. That is why the Markov assumption exists in the first place: to make the model computable with the data you actually have. So while higher-order grams almost always — "99%" — give lower perplexity, data sparsity is the price.

5.3.7 Student Questions and Answers

Several students asked follow-up questions about the examples and the measure. The confusion points, deduplicated:

Q: In the worked example, the individual probabilities shown add up to 1.05, but probabilities should sum to 1. Why? A: You are not adding — it is a joint probability, a multiplication. And these are conditional probabilities estimated from the training corpus: . Conditional probabilities for different contexts do not have to sum to 1. Each one is a separate distribution over the vocabulary for its own context. So no sum-to-one check applies here.

One student worried that the example probabilities were invented; another asked where they come from:

Q: But the probabilities in the example are given — they are assumed? A: No, you are evaluating the model, so you cannot assume anything. Your model is predicting those probabilities, and they are always there. That is exactly what you are evaluating: how well the model assigns probabilities to words.

Q: How do we get the probability for each word in the first place? A: From the model. For n-gram models these probabilities come from training-data counts, which the previous session covered; for neural models they come from the softmax output. The comparison slide on n-gram versus neural was deferred to after the neural language model discussion.

The next question targeted the role of perplexity itself — a misconception that is worth spelling out:

Q: Is not the next word what we need to predict? A: We are not predicting here; we are evaluating. The question is how good the model is at giving probabilities to words. Perplexity is not used to predict the next word; it is used to evaluate whether the model's predictions are good. Think of classification: you train a decision tree or an SVM, then you evaluate it with accuracy, precision, recall. During evaluation you do not classify — you check whether the classification the model performed is good. Perplexity plays the same role for language models.

A student asked how to read the "5 equally likely words" phrase; the answer compared it with familiar classifier metrics:

Q: How can you say the model faces 5 equally likely words? A: It is an explanation of the value, not a literal fact about the model. Compare: a model with 50% accuracy is able to classify correctly 50% of the examples. Precision of 8 out of 10 means 8 classes classified correctly and 2 not. The "5 equally likely words" statement is the same kind of reading of the perplexity number.

Next came practical questions about using perplexity in the real world and whether ground truth text is needed:

Q: How does this work in the real world? Is a ground truth needed for perplexity? A: There is an evaluation tool (the name was garbled in the audio) and other tools that measure the perplexity of models automatically — you cannot do it manually at large scale. If you have two models, whichever has the lower perplexity value is the better model and you pick that one. And evaluation is never done on one sentence like "I love NLP models"; it is taken across thousands of examples and averaged. And no, no ground truth is needed: perplexity is just a value computed from the model's own probabilities.

The discussion then turned to the extreme values of the scale, and to the temperature parameter:

Q: Does a perplexity of 1 mean the model is 100% sure at each position which word comes next? A: Yes. But there is a reason real systems avoid perplexity 1. LLMs have a temperature parameter that controls variety. We want some creativity — we do not want the model to answer every greeting the same way; we want variety like "hello", "good morning", "hi", "how are you". So usually you do not want perplexity of 1, even though 1 means the model is sure of every word.

Two students asked about comparing commercial models, and about the probabilities being hidden inside them:

Q: If I take an OpenAI model versus a Gemini model and compute perplexity on my own task or corpus, can I decide which model to use? A: Yes, that is exactly how perplexity is used as a common evaluation measure — the model with the lower perplexity on your corpus is the one you choose.

Q: But we do not have the probabilities for those models — they are internal to the models. A: The models do have these probabilities — they predict words through softmax and other internal probabilities. And you do not compute perplexity manually. There is an API that evaluates the perplexity of a model, just like the sklearn libraries expose APIs that compute metrics for you. The manual example only explains how it works.

A student confirmed the measure's scope, and another pushed on whether higher-order grams always win:

Q: Can perplexity be used for neural language models too, not just n-grams? A: Yes, it is used for them as well.

Q: Will a 15-gram model always have lower perplexity than a lower-order n-gram model? A: Exactly. Higher gram, lower perplexity, because more context words make a better predictor. That desire for more context is how the attention mechanism came into existence. But having 10-gram counts available in your dataset is a luxury — the training data may not contain those counts, which is why the Markov assumption is made. Still, higher grams will almost always give lesser perplexity.

The random digit example drew one more question — why a perplexity of 10 counts as a bad model:

Q: In the 0-to-9 random example, why is a perplexity of 10 a bad model? A: Because every digit is equally likely. The model cannot say which digit has higher probability; it generates randomly, sometimes right, sometimes wrong. If instead the model gave the digit nine a probability of seven tenths and spread 0.1, 0.2, and so on over the rest, it would know 9 should be predicted next. Equal probabilities everywhere mean the model is not good — that is why 10 is bad here.

The last question was about length fairness — the very property the Nth root was built for:

Q: Is this metric agnostic to the length of the test sentence — can two models be compared even if the sentences differ in length? A: Yes, agnostic, because of the N parameter. The probabilities will differ based on the corpus, but taking the Nth root — a geometric mean — normalizes for length. It is the same normalization idea as cosine similarity, where you divide by the length of the vector so the length does not affect the score.

Recap + bridge. Perplexity is the Nth root of the inverse sentence probability: a length-normalized, per-word average of the model's confusion, read as "how many equally likely words the model is choosing between." Lower is always better, and minimizing perplexity is the same as maximizing probability. Perplexity is the evaluation measure for n-gram models and neural language models alike — which is why the next section builds the neural machinery that makes those models work.

Real-world & domain connection. Perplexity is still the headline intrinsic score for modern language models: when a new model or a new LLM is announced, its perplexity on a standard test set is one of the first numbers reported. In production, model selection between commercial models (an OpenAI model versus a Gemini model, say) is done by computing perplexity on your own corpus and picking the lower value — and the evaluation is computed automatically by tools and APIs, never by hand.

5.4 Neural Network Foundations

5.4.1 Neurons, Brains, and the AI Winter

Hook: Why does a system built from tiny arithmetic units act intelligent? The answer given in this session is training — and the evidence comes from an unexpected place: the brain. The neuron analogy is the thread that ties the whole section together, so it is worth understanding before the math.

The neural network architecture is based on the neurons of the brain: simple units with interconnections. A memorable analogy: the brain has neuroplasticity, and research shows that age does not automatically reduce memory — what matters is how much stimulation and training you give your brain. The more you train it, the stronger it stays. The same logic explains why today's large language models and agentic AI systems behave intelligently: enormous amounts of training, bombarding them with knowledge, making them learn. Hold the biology lightly, though — a neuron here is just a small function of numbers; the biology is a hint, not the truth.

There is a historical context worth knowing: the field had an AI winter. In the 1990s nothing much was happening in AI — not because the ideas were wrong, but because of two missing ingredients: compute power and data. Now we have data and compute, so these neural algorithms can be implemented efficiently. The core idea itself is simple.

5.4.2 ML Versus DL: Who Finds the Features?

The difference between machine learning and deep learning: in ML you must do feature engineering — hand-craft the features and hardcode them. In neural networks, the model learns its own features from the data.

Two classic examples. To predict the cost of a flat (an Andrew Ng example), you give features: number of rooms, square feet area, location, facilities provided — and the model decides the cost. To classify whether a person plays tennis (classification), you give the weather: is it raining, is it dry, and so on — the model decides play or not. In both, you supply the features. In a neural network, you give an image and it learns all the features automatically; you give text, and through word embedding it learns features and finds context words on its own.

Q: What is the difference between ML and DL? A: In ML we need to give the features explicitly; in neural networks we do not have to explicitly mention features — the network learns them from the data. Layers are not the distinguishing factor; the distinguishing factor is feature learning.

5.4.3 The Neuron as Sum of Products

The simple neural unit looks like linear regression. The input is not features in the hand-crafted sense — it is your training examples. In word embedding, the individual words of the sentence are the inputs; in language modeling, likewise. The weights are learned by the network, and there is a bias term. The pre-activation output is:

Name each symbol: are the input values (the features of one example), are the weights that say how much each input matters, is the bias (one extra number added at the end — the unit's baseline leaning), and is the weighted sum.

This is called SOP — sum of products: products of weights and inputs added together, plus the bias. Note that is not the final output ; it is the intermediate value. The raw sum of products is linear: add more neurons and you still get a sum of products. To get probabilities between 0 and 1, apply the sigmoid at the output side, exactly like logistic regression; and the loss is cross-entropy, as in logistic regression. So the pattern everywhere is: weighted sum of products first, then a nonlinear activation function to produce the final output.

Visual intuition. Picture the unit as a small diagram: three arrows (inputs ) each pass through a weight () into a circle marked , which sums them; the result flows into a curved squashing function, and the output comes out the right side. Numbers flow left to right: weigh, sum, squash. Without the bend of the activation, stacking units would just give one big straight line — the network would gain nothing from depth.

5.4.4 Sigmoid and the Other Activation Functions

The sigmoid is the most popular nonlinear activation, written with the symbol :

Here is Euler's number, the base of natural logarithms. Its most interesting property concerns training. When you take the partial derivative with respect to the weights, the derivative of the sigmoid is sigmoid times one minus sigmoid:

That elegant derivative matters because gradient descent computes the derivative of the loss with respect to each and every weight (, , and so on). A clean derivative makes that work pleasant. A second nice property: the sigmoid's outputs are always between 0 and 1. Sigmoid is used even up to the transformers — transformer blocks contain feedforward networks, and in many hidden-layer places sigmoid is still used.

Worked example: the sigmoid unit, giving 0.70. Take the weights , the bias , and the input values . Compute , then apply sigmoid:

Step 1 — multiply each input by its weight: ; ; .

Step 2 — add the products: .

Step 3 — add the bias: .

Step 4 — apply the sigmoid: .

Final answer: — a 70% probability for the positive class in a binary classification. Sense-check: the output is between 0 and 1 and above 0.5, so the unit leans toward "yes" fairly confidently. For multi-class problems you repeat the machinery per class.

Other activations exist, and today's LLMs use several. Tanh is used, though not as popular. Instead of the range 0 to 1, tanh maps to values between -1 and +1:

The most common modern alternative is ReLU and its variant leaky ReLU. For ReLU: if the input is negative, the output is given as zero; for positive values, the output is z itself (the maximum of 0 and z). Leaky ReLU differs on the negative side: instead of exactly zero, it gives a small (lower) slope for negative inputs, so the left side is not completely flat:

GELU (Gaussian Error Linear Unit) is another function used in today's LLMs, similar in spirit to ReLU with a smooth variation. Do not memorize the formulas for tanh, leaky ReLU, and GELU — what you should know is softmax, covered next.

Worked example: the same two scores through three activations. Feed and through each activation: ; ; ; ; . Final answers: sigmoid and tanh both saturate toward their limits, while ReLU passes 2 straight through and zeroes out -2. Sense-check: this contrast is exactly why ReLU's constant slope for positive inputs helps deep networks learn fast.

Pitfalls: sigmoid and tanh "saturate" — far from zero their slope is nearly flat, so gradients shrink and learning stalls (the vanishing-gradient trap). ReLU mostly avoids that, but a unit stuck at negative inputs can "die" and output zero forever. Also remember the bias is not optional: without , the unit can only draw decision boundaries through the origin.

In a full architecture: hidden layers typically use sigmoid, and the output layer uses softmax when the problem is multi-class, like predicting the next word. If the output is binary, the output neuron can use sigmoid. Softmax and sigmoid are the most common pair in transformers even today: softmax at the output side, sigmoid in the hidden nodes.

5.4.5 Softmax for Multi-Class Output

Softmax is the workhorse for picking one word out of a large vocabulary:

The numerator exponentiates the raw score ; the denominator is the sum of exponentiated scores over all classes, so the outputs form a probability distribution that sums to 1. Each is computed as a sum of products for its class. With the normalized values you can tell which class has the highest probability — that one is predicted. In language modeling, the highest-probability word becomes the next token. Here is the number of classes (the vocabulary size in language modeling).

Why not just use the raw without dividing? Because unnormalized values do not let you compare across classes properly; normalizing by the total turns the vector of numbers into a probability distribution and makes the highest one pickable.

Worked example: softmax on six raw scores. Suppose the raw scores are . Step 1 — exponentiate each: , , , , , . Step 2 — sum the denominator: . Step 3 — divide each exponential by the total: . Final answer: the fifth class wins with about 74% of the probability mass, and all six values sum to 1. Sense-check: the largest score (3.2) received by far the largest probability — softmax sharpens a lead into a clear winner.

Two students probed the normalization idea from opposite directions:

Q: Why do we need softmax at all? Why can't we use sigmoid? A: Sigmoid is for two classes. With many classes you would have to use sigmoid again and again, each output treating its class as independent — and the probabilities would not sum to one. Softmax takes a vector of numbers, normalizes it, and produces a probability distribution whose entries sum to one. Then the class with the highest probability gets picked. Sigmoid is a subset of softmax — the two-class case.

Q: Without normalizing, could a "probability" come out higher than one? A: No — each value stays between zero and one. The point of normalization is different: larger inputs should get higher probability, and the sum must be one, so that the class with the highest probability stands out as the prediction.

A final question asked what softmax actually changes about the raw scores:

Q: With the raw Z values it is hard to tell which is the correct one. Does softmax fix that? A: Yes. From the raw Z values alone it is difficult to distinguish the winner. After applying softmax, one value stands out as highest, and that becomes the predicted next token in word language modeling. The same function appears everywhere: multi-class sentiment analysis, image recognition (predicting whether an image is a dog, a building, a cat, or a human — the class with the highest softmax probability is the answer). That is why softmax is the most popular function in transformers and neural architectures, and it is what language modeling uses at the output.

5.4.6 Why Multiple Perceptrons: XOR

Why more than one perceptron? Because some data is not linearly separable. The XOR problem: with two inputs and , no single line can separate the outputs. No matter how much you manipulate the weights, a single linear perceptron cannot solve XOR.

The analogy is the SVM kernel trick: kernels transform the data to a high-dimensional space where the two classes become separable. Adding perceptrons does something similar inside the network — more perceptrons give the network the capacity to separate non-linear data.

Concretely: send and to two hidden nodes and , not just one. The function becomes more complex, and the network must learn more weights — before, only the weights from and ; now also , , and . Each connection adds a weight, and bias is included at every step. With the extra neuron, the XOR problem becomes solvable.

Worked example: a 2-layer ReLU network solves XOR. XOR fires when the two inputs differ: and give 1; and give 0. The green corners and red corners alternate around the square, so no single straight line can separate them. Now use two hidden ReLU units: (fires when at least one input is on) and (fires only when both are on), then combine them as :

Step 1 — input : , , so . Correct.

Step 2 — input : , , so . Correct.

Step 3 — input : , , so . Correct.

Step 4 — input : , , so . Correct.

Final answers: 0, 1, 1, 0 — all four match XOR. Sense-check: the second hidden unit acts like an "both on" detector, and subtracting twice its value cancels exactly the case that a plain OR would get wrong. The hidden layer's new features are what make the problem linearly separable — remove the hidden layer and XOR fails again.

Many real-world problems cannot be solved by a single perceptron — that is why we build a network of them. Mimicking the human brain: more perceptrons, more complexity, but real problems become solvable. This is why it is called a deep neural network, not a deep neuron.

5.4.7 Architecture Guidelines

A neural network has an input layer, one or more hidden layers, and an output layer. In classic ML algorithms, input connects straight to output; the hidden layers are what neural networks add. Terminology: a perceptron or neuron — the word neuron is typically used when an activation function is added, which is why the field is called neural networks. Hidden neurons live in the hidden layer, so "multi-layer" when there are several.

How many hidden layers, and how many neurons each? Andrew Ng's feedforward-network guidelines, recalled from the DNN course:

  • The output layer size is fixed by the problem: one neuron for regression or binary classification, and for multi-class, one neuron per class with softmax. In language modeling, multi-class, the number of output neurons equals the number of words/tokens you want to predict.
  • The input layer size equals the number of input tokens/features.
  • Hidden layer size: take the number of input neurons and use one or two more — if you have 128 inputs, each hidden layer should have at least 129 or 130 neurons.
  • Powers of two (64, 128, 256, ...) are a common and convenient choice for hidden sizes.
  • Start small: begin with one hidden layer. If it already gives very good accuracy — 90% or 99% — stop there. More hidden layers mean more complexity, less explainability, and more resources consumed. The universal approximation theorem says even one hidden layer can approximate many functions, but multiple layers are advisable for harder problems.
  • The "one or two more than the inputs" rule is a guideline for calculation's sake, not a hard restriction.

Q: Is there a restriction on the number of neurons in a hidden layer? Must it be a power of two — 64, 128, 256? A: No, it is not necessary. You can have more, and you can even use odd numbers like 150 or 200. The guideline exists for calculation's sake; you should typically not have fewer than the input count.

5.4.8 Feedforward and Backpropagation

Q: What are feedforward and backpropagation? A: (A student's answer, confirmed correct:) In feedforward we calculate the weights and biases and compute the loss compared to the ground truth; once we know the loss, in backpropagation we go back and adjust the weights so the loss is minimized. (Refinement:) Feedforward is used both during training and at inference. During training, it runs first — you start with certain random weights, and forward propagation computes the network's output. During inference, after all weights have been learned, feedforward applies those learned weights to get the final output. The forward algorithm is simply: multiply weights by inputs, apply the activation function, and move to the next layer. What the student described — comparing loss against ground truth and adjusting weights — is the backpropagation part.

The notation: superscripts indicate the layer number, subscripts indicate the node within a layer. Take a tiny network: 3 input nodes, 3 hidden nodes, 1 output node. For the first node of the second layer (the hidden layer), compute the sum of products over (the bias), , , each with its weight, then apply the activation — which can be leaky ReLU, sigmoid, tanh, or any activation function:

Here is the activation of node 1 in layer 2; the weight connects the bias input to that node, and , connect the two real inputs. The bias is written as a fake input with a weight attached — nothing changes mathematically, it is just tidier to write. Repeat for all three hidden nodes. Then the output node computes its own sum of products over the hidden outputs with the next layer's weights, applies the activation (sigmoid here), and produces . That is the whole forward pass: multiply, sum, activate, move forward. With more hidden layers, the same logic repeats; everything stays densely connected.

A notation note: Andrew Ng uses the symbol (theta) for weights instead of — the same thing, just a different letter.

In a fully connected network, every node of one layer connects to every node of the next, so the weights form a matrix rather than a vector. Every node in every layer is connected to every node in every next layer — that is why these are called dense networks.

A neat implementation fact: the entire neural network architecture boils down to two operations — multiplication and addition, over and over. Real-world: that repetitive matrix computation is why Google built the TPU (Tensor Processing Unit) as a competitor to GPUs. GPUs serve generic applications; TPUs are specialized, and there are TPUs for training time and TPUs for inference time, because the two phases have different requirements (training needs backpropagation, partial derivatives, and matrix computation).

Backpropagation is where the "real value" lives. It starts with the loss at the final output — say you predict and compare it with the ground truth; the error, or delta, comes from all the earlier layers and weights. The final loss could be caused by any neuron or weight in any earlier layer, which is why you propagate it backward. Gradient descent then optimizes each weight by taking the partial derivative of the loss with respect to that weight:

where (the Greek letter eta) is the learning rate — how big each update step is. For binary classification the loss is cross-entropy; taking partial derivatives with respect to each weight gives a chain of derivative terms, which is why the elegant sigmoid derivative is so convenient at the hidden layers. Backpropagation through time is the recurrent version, mentioned only in passing here. The session noted that deep learning loss surfaces are non-convex, but did not go further — all the gory partial-derivative mathematics belongs to the DNN course.

Q: But how do you actually get the weight values — where do they come from? What training data is needed? A: Step one: initialize all weights to random values. Then run forward propagation. Then, during backpropagation, compute the error and update the weights with gradient descent — the standard update is . To compute an error you need the ground truth: for supervised learning, you need labeled data, with actual labels. Language modeling and text classification feed on exactly this machinery, as the next section shows.

Recap + bridge. A neuron is a sum of products plus bias, passed through a nonlinear activation; many neurons in layers form a feedforward network trained by backpropagation and gradient descent. Sigmoid and softmax are the two activations to know — sigmoid for yes/no outputs, softmax for picking one class out of many. The next section points this machinery at language: neural language models built from embeddings, hidden layers, and a softmax over the vocabulary.

Real-world & domain connection. The "multiply and add" insight explains modern hardware: GPUs (and Google's specialized TPUs) are built to accelerate exactly these matrix operations, with separate TPUs for training and inference because the two phases have different compute profiles. Every deep learning framework — and every LLM underneath — runs this same forward-pass/backward-pass loop, scaled up.

5.5 Neural Language Models

5.5.1 The Recipe

Hook: What makes ChatGPT able to finish your sentence? The short answer is three ideas you have already met, combined: a neural network, the next-word prediction task from language modeling, and word embeddings. Nothing more — and the next part of this session shows exactly how the three fit together.

A neural language model is the combination of three ideas already covered: (1) the neural network architecture, (2) the concept of computing next-word probabilities from language modeling, and (3) word embeddings. Three together equal neural language modeling. The "Attention Is All You Need" paper — the transformer paper, motivated by machine translation — is fundamentally about neural language modeling.

One honest note: simple feedforward language models work wonderfully for many problems. You do not need a transformer for every task.

And a unifying claim: all of generative AI — LLMs included — boils down to predicting the probability of a set of tokens. LLMs are just larger neural language models: more data, more parameters, bigger architectures.

5.5.2 From Words to Embeddings: A Sentiment Analysis Walkthrough

Take a real-world classification problem: sentiment analysis of a movie review — good, bad, okay, or neutral; for simplicity, binary: the movie is good or not good. Two routes exist. With logistic regression you hand over features: who is the actor, who is the producer, the storyline, and so on. With deep learning you give the review text itself; the model learns the features automatically, using embeddings.

Word embeddings are the bridge: each word becomes a vector of numbers, learned via skip-gram SGNS, TF-IDF, frequency-based counts, and (post mid-sem) contextual embeddings. These vectors are the input to the model instead of hand-made features.

The pipeline for the feedforward version: each word of the review is converted to an embedding vector. The input layer has as many slots as the longest review has words; the hidden layer has one or two more nodes; and because this is binary sentiment classification, the output is a single neuron with sigmoid. The weights are learned during training on reviews labeled positive or negative — that is the backpropagation step. Once the weights are learned, a new review (say, a hotel review: "dessert is good") passes through the network, and the output probability decides: higher probability means positive sentiment.

Q: To make this concrete with the e-commerce review example: training data has a labeled review, happy, assigned probability 0.75; the model's initial output is 0.5. Is this error what backpropagation uses to fix the weights? A: Correct. The error is propagated backward and the weights get fixed through backpropagation.

5.5.3 Sentence Embeddings: Mean and Max Pooling

How do you combine individual word embeddings into a sentence embedding (also called a review embedding or phrase embedding)? Two simple techniques. Worked example with toy two-dimensional embeddings, for the words of "dessert is good" plus "the":

  • "the":
  • "dessert":
  • "is":
  • "good":

Mean (average) pooling: element-wise average across all words. In general, for word vectors :

Max pooling: element-wise maximum, where each component of the sentence embedding takes the largest value of that component across all words:

Worked example: pooling the four toy vectors. First component of the mean: . Second component: . So the mean sentence embedding is [0.675, 0.5].

For max pooling: first component . Second component . So the max sentence embedding is [1.1, 1].

Final answers: mean pooling gives [0.675, 0.5]; max pooling gives [1.1, 1]. Sense-check: every pooled value is between the smallest and largest raw component in its dimension, and the max version keeps the strongest signal per dimension. Either way, four word vectors collapse into one fixed-size vector.

Both are used; max pooling is more popular, but mean works fine. These toy vectors are two-dimensional only for the demonstration — real embeddings have 768 or 1024 dimensions.

Real-world: Hugging Face already provides a sentence-transformers API that computes sentence embeddings automatically, so you rarely implement pooling yourself.

Students asked three clarifying questions about embeddings and pooling:

Q: Do we also need to generate word embeddings again for sentence embedding? A: No. The word embeddings are already stored individually. The sentence embedding is computed from the word embeddings; no new learning is needed.

Q: In a dense network, does every feature of the embedding connect to the next layer? A: Yes. Every feature connects to every neuron of the next layer — that is what dense means. Large models like GPT-4, GPT-5, Llama, and Claude Sonnet all use dense representations because they do not want to lose any information; every connection is available to the model. How to reduce those connections and shrink the model (small language models, tiny language models, parameter-efficient fine-tuning) is a next-semester topic.

Q: With mean pooling, can different sentences end up with the same sentence embedding? A: It can happen. If the sentences have the same words, they have the same embedding; with a large overlap of words, the embeddings come out similar. That is actually a feature: similar sentences should lie close to each other in the embedding space. The max-pooling approach gives the same kind of behavior.

5.5.4 Fixed-Length Inputs and Padding

Neural networks need fixed-size inputs, but sentences vary in length. The simple solution: compute the maximum sentence length in your training data and use that as the input length. Shorter sentences get padded with zeros for the remaining slots. (LSTM pipelines use the same padding idea.) On average, the longest English sentences are about 10 to 12 words, so the fixed length stays modest; and if you want to restrict it further, you can split a long sentence into two parts and feed it as two separate inputs.

5.5.5 The Feedforward Language Model

Language modeling as a neural problem: given a set of words as input, predict the most likely next word. The input is a window of words — three words, a window of five, or the whole sentence, depending on the algorithm — converted to word embeddings and fed to a feedforward network. Because the output must pick one word out of the whole vocabulary, the output layer uses softmax, with one output neuron per vocabulary word. The softmax probabilities over the entire vocabulary sum to 1, and one word has the highest value — say the word shown as "9" in the slide's example — so that word is predicted as the next token.

Then the process slides forward: feed the next three words ("all the fish ...") and predict again, repeating until the end of the sentence. This loop is exactly how text generation works at scale: ChatGPT appears to type, but behind the scenes it takes the output of the current step and feeds it back as input for the next step, predicting one token after another, generating a whole sequence.

Q: Is the sentence embedding what the model learns in the language modeling case? A: No. The sentence embedding is just a mathematical function of the word embeddings — mean or element-wise max. You do not learn any weights for it. What the model learns are the word (or token) embeddings and the network weights. Modern systems do not even use whole words: they tokenize into subword pieces, for example breaking "sizes" into "size" and "s", giving each subword its own embedding. The word-embedding algorithm runs over small chunks of words in a sentence; the sentence embedding is computed by combining them, not learned.

Q: So effectively there are two models — one for word embeddings and one for predicting the next word? A: Yes, exactly. Interestingly, in the transformer paper they are learned together — the paper discusses learning the word-embedding part and the language-modeling part jointly. Both routes are possible.

5.5.6 Weight Matrices W and U

In the feedforward language model, the weights come in two matrices. W is the matrix of weights from the input layer to the hidden layer; U is the matrix of weights from the hidden layer to the output layer.

Worked example: counting the output weights. Suppose the hidden layer has 10 units and the vocabulary has 50,000 words. Every hidden unit connects to every vocabulary word, so U is 50,000 × 10 = 500,000 weights — a matrix, not a vector. Final answer: 500,000 weights must be learned, just for the output layer. Sense-check: the output layer must produce one score per vocabulary word, so its size is fixed by the vocabulary — which is why the weight count explodes with the vocabulary size.

Students examined the slide's numbers and notation one by one. First, a large number on the slide:

Q: What does the number "35992545" on the slide mean? A: That is the one-hot encoding value — the binary representation of the position of that word in the entire unique vocabulary. It is the token ID.

Next, how the matrices are sized, and what the vocabulary count really is:

Q: So the W matrix has size equal to the token ID encoding size? A: Yes — the vocabulary-size dimension of the weight matrix follows from the token ID encoding.

Q: Is the 50,000 the number of all possible English words? A: It is the entire vocabulary — the unique words of your corpus.

A student then connected the design back to the n-gram comparison, and another asked about the missing bias:

Q: Is it fair to say that, compared to n-gram models which just count, these semantic vector representations are the main function here? A: Yes. The n-gram model was doing the counting; here the word embeddings are the semantic vector representations that capture meaning, and they are the key difference.

Q: Where is the bias in the diagram? A: There is a bias in the computations. To keep diagrams clean, the bias is written as with a weight attached, instead of drawn separately.

Finally, a student asked whether a full numeric walkthrough of the network would come:

Q: Will there be a numerical example of this network? A: Not in the exam. A numerical example means taking partial derivatives at every step, computing each weight update, like the skip-gram negative sampling walkthrough earlier. The detailed numerical walkthrough comes post mid-sem with contextual word embeddings.

Recap + bridge. A neural language model converts a window of words into embeddings, pushes them through a feedforward network, and reads a softmax distribution over the whole vocabulary: the highest-probability word is the prediction, and sliding the window forward generates text. The weights live in two matrices, W and U, whose sizes are set by the input and the vocabulary. The next section contrasts this machinery with the n-gram approach — and shows why embeddings change everything.

Real-world & domain connection. This is the seed of the transformer: swap the fixed window for attention, scale the data and parameters, and the same forward pass becomes GPT, Claude, and every modern LLM. Even ChatGPT's conversational output is one token-prediction loop repeated — the output of one step becomes the input of the next.

5.6 N-Gram Versus Neural Language Models

5.6.1 Semantic Generalization: The "Dog Gets Fed" Example

Hook: What happens when a language model meets a sentence it has never seen? The n-gram model fails cleanly — and the neural model succeeds. The whole difference between the two families is one word: semantics.

The n-gram model predicts the next word given prior words under the Markov assumption. The feedforward model does the same from a window of word embeddings. The deciding difference: embeddings capture semantics, not just syntax. An n-gram model sees only word identity; it cannot compare words for similarity. To an n-gram model, "cat" and "dog" are as unrelated as "cat" and "Tuesday" — both are just different symbols with no connection.

Worked example: "the cat gets fed" generalizes to "the dog gets fed". Training data contains: "I have to make sure that the cat gets fed." At test time the model sees: "I forgot to make sure that the dog gets fed."

Step 1 — the test sentence reaches the position "the dog gets ___". The neural language model looks up the embedding of "dog" and finds it sits close to the embedding of "cat" — the two words appear in similar contexts, so their vectors point in nearly the same direction.

Step 2 — because the "cat" pattern is close by, the model transfers the training evidence: the next word after "the cat gets" was "fed", and "dog" behaves like "cat".

Step 3 — the neural model predicts "fed" with no trouble. The n-gram model, in contrast, has never seen the sequence "dog gets" — its count for that bigram is zero — and cannot generalize; it fails.

Final answer: the neural model predicts "fed"; the n-gram model cannot. Sense-check: this is the core advantage of neural language models — knowledge about one word transfers to similar words through their embeddings.

Exam note: the cat/dog "gets fed" example is the standard demonstration that embeddings capture semantics: the neural language model generalizes from a similar word in the training data, while the n-gram model cannot because it has never counted that exact word pair.

Beyond that: n-gram models cannot handle very long histories of context, while neural models can; neural models generalize better and are more accurate. The side-by-side comparison:

Dimension N-gram model Neural model / LLM
History length Short (a few words) Longer contexts, learned
Similar words Treated as unrelated symbols Shared via embeddings (semantic similarity)
Generalization None — unseen pairs get zero Transfers knowledge across similar words
Accuracy (next word) Lower Higher
Speed and cost Fast, cheap, light Slower; needs GPUs, more data and energy
Interpretability Easy — read the counts Hard to interpret
Best for Small, fast, simple tasks Large, rich, production tasks

When to pick which: for a small, fast, interpretable deployment, the n-gram model can still win; for production-grade quality at scale, the neural model is the choice.

5.6.2 Cost, Data, and Interpretability

The neural side pays for its power. Complexity and time: you need GPUs. Real-world price check: an NVIDIA H100 was recently priced around 40 lakh rupees, and an A100 around 10 to 12 lakh rupees. Running LLMs locally needs such hardware; otherwise you call an API and pay as you go — something like 15 USD per month for a subscription.

Environmental cost: LLMs consume a lot of energy and create a large carbon footprint — comparable, in the session's analogy, to a flight. (Flights create a large carbon footprint, but we still need to travel; the same tension applies to LLMs.) The session's speaker mentioned preferring search engines because they cause less carbon footprint than models like ChatGPT or Claude, while admitting to using the models sometimes.

Interpretability: n-gram models are the most interpretable — you can read the counts. LLMs are almost zero-interpretable: the weights do not tell you why the model returned a particular sentence.

Training data: n-gram models need comparatively much smaller data; LLMs need enormous amounts. Context: LLMs handle long contexts, with commercial providers advertising large context-window token limits — one figure mentioned was 500 million tokens. That number is almost certainly mis-stated in the lecture audio: typical commercial context windows are far smaller (tens of thousands to a couple of million tokens). Either way, you pay per token for that context. Quality is better for LLMs. Deployment is easier for n-gram models and expensive and heavy for LLMs.

Pitfalls: the GPU price check and the context-window figure are ballpark numbers that change quickly — treat them as order-of-magnitude intuition, not quotes. And do not read "higher accuracy" as "always better": for a small task on modest hardware, the cheap n-gram model is often the right engineering choice, and interpretability may matter more than peak quality.

The summary split: n-gram models are good for small, fast, interpretable deployments; neural/LLMs are for production-ready, large-scale implementations. Which model to use when — and the pros and cons in production — is a next-semester topic in NLP applications courses.

Recap + bridge. The deciding difference between the two families is semantics: embeddings let neural models share knowledge between similar words, at the price of GPUs, data, energy, and interpretability. Everything built in this session — perplexity for evaluation, neural networks as the engine, embeddings as the fuel — comes together in the large language models that power modern AI, which are simply this recipe scaled up.

Real-world & domain connection. In industry, the trade-off is a daily decision. Lightweight n-gram-style scoring still appears in small on-device tools and fast fallbacks, while production text systems — search, translation, assistants — run LLMs on GPU clusters (or via API) where quality justifies the cost. The hardware economics shown here, from H100 and A100 price points to pay-as-you-go API subscriptions, are what teams weigh when choosing between local deployment and calling an API.

Exam Guidance Summary

This session's exam-relevant material, gathered in one place:

  • Perplexity is the evaluation measure for language models; expect to work the perplexity formula numerically. Know what capital N is (number of words in the sentence), how the Nth root normalizes length, and how to read the result ("5 equally likely words" style interpretations).
  • Know softmax: it is used at the output of every multi-class network, including language modeling. Its formula and the fact that its outputs sum to 1 are exam-relevant.
  • No backpropagation math problems will be asked in this NLP course — that material belongs to the DNN course. The same holds for the loss computation and weight learning details.
  • No numerical example on neural language models is in the exam. The detailed numerical walkthrough of embeddings (with partial derivatives at every step, like the skip-gram negative sampling example) comes post mid-sem with contextual word embeddings.
  • You do not need to memorize the tanh, leaky ReLU, and GELU formulas — they were presented as extra information. Sigmoid's properties (range 0 to 1, derivative sigmoid times one minus sigmoid) and softmax are the ones to know.
  • Know the practical architecture guidelines: hidden layer neurons one or two more than the inputs, powers of two as convenient sizes, start with one hidden layer, output neurons equal to the vocabulary size for language modeling, single output neuron with sigmoid for binary classification.
  • Know the comparison axes between n-gram and neural language models: semantic generalization (the cat/dog "gets fed" example), context length, data size, interpretability, deployment cost, and accuracy.
  • There is an NLP quiz — check the calendar along with assignments, quizzes, and webinars.

Key Industry Applications

How this session's ideas show up in real products:

  • Perplexity is the standard evaluation measure in industry for LLMs and transformers, from n-grams to GPT-class models. It is computed automatically by evaluation tools and APIs (in the spirit of sklearn's API calls) — never by hand at scale.
  • Model selection workflow: to choose between two commercial models (e.g., an OpenAI model versus a Gemini model) for your own task, compute perplexity on your corpus and pick the lower value.
  • Temperature parameter in LLMs: controls output variety; explains why production systems do not target perplexity of 1, which would make every word deterministic.
  • The Perplexity research tool (AI-powered research-paper summarization) likely borrowed its name from this measure.
  • Hugging Face provides a sentence-transformers API that computes sentence embeddings automatically; mean pooling and max pooling are the underlying techniques.
  • Google Ngram is the most popular text corpus for n-gram language modeling; many other corpora are used as well.
  • "Attention Is All You Need" (the transformer paper, motivated by machine translation) is built on neural language modeling.
  • NVIDIA H100 (about 40 lakh INR) and A100 (about 10–12 lakh INR) GPUs are the hardware of local LLM deployment; API access is the pay-as-you-go alternative at roughly 15 USD per month.

NLP Lecture 5 Notes · Perplexity and Neural Language Models

Natural Language Processing· postgraduate· 2026-08-13

Sections Breakdown

1Language Modeling Recap and the Evaluation Question

Recap of the language modeling task (assigning probabilities to word sequences from an unlabeled corpus) and the three zero-probability fixes for n-gram models: Laplace smoothing, interpolation with lambdas summing to one, and back-off.

2Intrinsic Versus Extrinsic Evaluation

Evaluation of a language model has two levels: intrinsic evaluation (perplexity) scores the model directly like a white-box component test, while extrinsic evaluation (spell checking, speech recognition, MT) scores the model through the real end application like a black-box test.

3Perplexity: Inverse Probability and the Nth Root

Perplexity is the length-normalized inverse sentence probability: raise the product of word probabilities to the power -1/N (the Nth root, a geometric mean) so sentences of different lengths are comparable, and read it as the effective number of equally likely word choices per position; lower is always better.

4Neural Network Foundations

A neuron is a weighted sum of inputs plus a bias, passed through a nonlinear activation: sigmoid for yes/no outputs, softmax for many-class outputs, with tanh, ReLU, and leaky ReLU as alternatives. Multiple perceptrons in layers (needed for XOR) form feedforward networks trained by backpropagation and gradient descent.

5Neural Language Models

A neural language model combines a neural network, next-word probabilities, and word embeddings: words become embedding vectors, sentences become fixed-size vectors by mean or max pooling (with zero padding to a fixed length), and a feedforward network with a softmax over the vocabulary predicts the next token from a sliding window.

6N-Gram Versus Neural Language Models

The deciding difference between n-gram and neural language models is semantics: word embeddings let neural models generalize across similar words (cat to dog in the 'gets fed' example), while n-gram models cannot; the neural side pays with GPU cost, huge data, energy, and interpretability.

7Exam Guidance Summary

Exam guidance carried through from the lecture: work the perplexity formula numerically, know softmax and sigmoid properties, no backpropagation or neural-LM numerical problems in this NLP course, and know the n-gram versus neural comparison axes.

8Key Industry Applications

Industry applications carried through from the lecture: perplexity as the standard LLM evaluation metric computed by APIs, model selection by lower perplexity, temperature for variety, sentence-transformers pooling APIs, Google Ngram corpus, the transformer paper, and GPU/API economics of local LLM deployment.

Postgraduate students in Natural Language Processing

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.

Language Modeling Recap and the Evaluation Question

Must-know: Interpolation blends trigram, bigram, and unigram probabilities with weights lambda_1, lambda_2, lambda_3 that must sum to 1; the higher-order terms get more weight because they capture more context.

Top pitfall: A single zero probability in the product wipes out the whole sentence probability and breaks perplexity, so smoothing, interpolation, or back-off is mandatory.

Self-check: If lambda_1 = 0.5, lambda_2 = 0.3, lambda_3 = 0.2 and the trigram/bigram/unigram estimates are 0.6, 0.4, 0.1, what is the interpolated probability?

Connects to: Intrinsic Versus Extrinsic Evaluation

Intrinsic Versus Extrinsic Evaluation

Must-know: Perplexity is an intrinsic (white-box) measure that scores the language model directly; extrinsic (black-box) evaluation runs the model inside a real application and cannot blame individual components.

Top pitfall: Trusting an intrinsic score over a real-task test: perplexity can disagree with task accuracy, and extrinsic evaluation needs the whole system built before any verdict.

Self-check: Why can extrinsic evaluation not tell you whether the language model or another component failed in a bad translation?

Connects to: Language Modeling Recap and the Evaluation Question, Perplexity: Inverse Probability and the Nth Root

Perplexity: Inverse Probability and the Nth Root

Must-know: Perplexity PP(W) = P(w_1,...,w_N)^(-1/N): a perplexity of 4.47 means the model is as uncertain as if choosing among about 5 equally likely words at each position; lower is better, and perplexity 10 from a uniform digit model is the branching factor reading.

Top pitfall: Treating perplexity as a prediction tool instead of an evaluation measure: it evaluates how well the model assigns probabilities, like accuracy does for classification; also confusing the joint product with a sum-to-one distribution.

Self-check: A test sentence of 4 words has joint probability 0.0025. What is the perplexity, and what does the value mean?

Connects to: Language Modeling Recap and the Evaluation Question, Intrinsic Versus Extrinsic Evaluation, Neural Network Foundations

Neural Network Foundations

Must-know: Sigmoid sigma(z) = 1/(1+e^{-z}) maps to (0,1) with derivative sigma'(z) = sigma(z)(1-sigma(z)); softmax normalizes exponentials so probabilities sum to one and picks the highest class; hidden layers are typically one or two neurons more than the input count, with powers of two as convenient sizes.

Top pitfall: Treating the pre-activation z as the final output (the activation must follow), or using sigmoid per-class for multi-class problems instead of one softmax over all classes.

Self-check: With w = [0.2, 0.3, 0.9], b = 0.5, x = [0.5, 0.6, 0.1], what is sigma(w.x + b)?

Connects to: Perplexity: Inverse Probability and the Nth Root, Neural Language Models

Neural Language Models

Must-know: Mean pooling s = (1/N) sum of word vectors and max pooling s_j = max over words give a fixed-size sentence embedding with no learned weights; the output layer of a feedforward LM is a softmax with one neuron per vocabulary word, and its weight matrix U has size vocabulary x hidden.

Top pitfall: Thinking the sentence embedding is learned by the model: it is a mathematical function (mean or max) of the word embeddings, so no weights are learned for it.

Self-check: For the vectors [1,0], [0.5,1], [1.1,0.1], [0.1,0.9], what are the mean-pooled and max-pooled sentence embeddings?

Connects to: Perplexity: Inverse Probability and the Nth Root, Neural Network Foundations, N-Gram Versus Neural Language Models

N-Gram Versus Neural Language Models

Must-know: Know the comparison axes between n-gram and neural language models: semantic generalization (the cat/dog 'gets fed' example), context length, data size, interpretability, deployment cost, and accuracy.

Top pitfall: Believing the neural model always wins: for small, fast, interpretable deployments the n-gram model can still be the right tool, and the 500-million-token context figure from the lecture is far above typical commercial limits.

Self-check: Why can a neural language model predict 'fed' after 'the dog gets' when the training corpus only contains 'the cat gets fed'?

Connects to: Language Modeling Recap and the Evaluation Question, Perplexity: Inverse Probability and the Nth Root, Neural Language Models

Exam Guidance Summary

Must-know: Perplexity formula and its 'N equally likely words' reading, softmax formula with outputs summing to one, sigmoid properties (range 0 to 1, derivative sigma(1-sigma)), and the n-gram versus neural comparison axes.

Top pitfall: Expecting backpropagation math or neural-LM numerical examples on this NLP course's exam: both are explicitly out of scope.

Self-check: Which formulas must you be able to reproduce numerically, and which are explicitly not examinable?

Connects to: Perplexity: Inverse Probability and the Nth Root, Neural Network Foundations, Neural Language Models, N-Gram Versus Neural Language Models

Key Industry Applications

Must-know: Perplexity is computed automatically by industry tools and APIs for model selection (lower wins), and production systems avoid perplexity 1 because the temperature parameter must preserve output variety.

Top pitfall: Computing perplexity by hand at scale: real evaluations run across thousands of examples through automated tools and APIs.

Self-check: How would you choose between an OpenAI model and a Gemini model for your own corpus?

Connects to: Intrinsic Versus Extrinsic Evaluation, Perplexity: Inverse Probability and the Nth Root, Neural Language Models, N-Gram Versus Neural Language Models

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.