Semantics/Neural Networks and Neural Language Models

Lesson 3.33,262 words

Neural Networks and Neural Language Models

A neural network is a stack of units, each a weighted sum passed through a non-linearity — a single unit on its own is logistic regression. We build the network up from that unit: the activation functions that give it power, the XOR problem that forces a hidden layer, the feedforward forward pass in matrix form, and the Bengio-style feedforward neural language model that concatenates word embeddings and predicts the next word with a softmax.

╌╌╌╌

An n-gram language model predicts the next word by counting: it stores how often the cat gets was followed by each word and normalizes. That works until the context is one it never saw, and in a large vocabulary almost every long context is unseen — the counts are sparse and the estimate collapses. A neural language model replaces the count table with a function. It represents each context word as a dense vector, feeds those vectors through a small network, and reads a next-word distribution off a softmax. Because similar words get similar vectors, a context the model never saw can borrow strength from one it did. The rest of this lesson builds this model.

The model is a neural network: a stack of simple computing units, each a logistic regression classifier in its own right. We start with that single unit.

The unit

The building block is one unit. It takes real-valued inputs , forms a weighted sum with a set of weights and a bias , and passes the result through a non-linear function. Written with the dot product, the weighted sum is

a single real number. The unit then applies a non-linear activation function to get its output, the activation value . For a lone unit that activation is the whole network's output, which we write :

A neural unit takes inputs (and a bias carried as a weight on a input), forms the weighted sum , and passes it through the activation to produce the output .

The bias is a weight on a dummy input clamped at . That convention lets us fold into and write every layer uniformly as a matrix multiply, which matters once we stack units.

Activation functions

The activation is what makes a network more than linear algebra. Three choices dominate.1

The sigmoid maps any real value into , squashing outliers toward or and staying nearly linear near the origin:

It is differentiable everywhere — handy for learning — and it is the same function that turns a logistic regression score into a probability. Substituting the weighted sum gives the full output of a sigmoid unit, .

The tanh is a rescaled sigmoid ranging over :

Being centered at zero, it usually trains better than the sigmoid at internal layers.

The rectified linear unit or ReLU is the simplest and most common, the identity for positive inputs and zero otherwise:

The three standard activations. The sigmoid saturates toward and ; tanh saturates toward and ; ReLU is flat below and linear above it, so its slope never shrinks for large positive .

The differences matter for learning. The sigmoid and tanh saturate: for large their outputs flatten and their derivatives fall near zero. Since training propagates an error signal backward by multiplying local derivatives, a chain of near-zero derivatives shrinks the signal until it vanishes — the vanishing gradient problem. ReLU has derivative for all positive , so it avoids this failure, which is why it is the default at internal layers.

The XOR problem

A single unit is a linear classifier, and linear classifiers have a hard limit. The classic demonstration is that no single unit can compute the logical XOR of two binary inputs.2 AND and OR are easy — a perceptron (a unit with a hard threshold and no non-linearity, outputting when and otherwise) computes each with the right weights. XOR it cannot.

The reason is geometric. A unit's decision boundary is the set where , which for two inputs is a straight line. It splits the plane into a positive side and a negative side. For AND and OR you can draw such a line; for XOR the two positive points and sit on one diagonal and the two negative points and on the other, so no single straight line separates the classes. XOR is not linearly separable.

AND and OR are linearly separable — one line cuts the positive points (filled) from the negative (open). XOR is not: its positive points and and negative points , interleave, so no single line works.

The fix is a hidden layer. Stack a second layer of units on top of the first and XOR becomes solvable — Goodfellow's construction uses two ReLU units in a middle layer feeding one output unit.2 The hidden units transform the input into new coordinates, an space, in which the two positive input points collapse together and the classes become linearly separable. Forming a representation of the input in which the final linear readout can succeed is the hidden layer's whole job. That is the recurring theme of neural networks, and it only works because the units are non-linear — a stack of purely linear units collapses back to a single linear map, as we show below.

Worked example: the XOR network, unit by unit

Goodfellow's XOR network is small enough to run by hand, and doing so shows the hidden layer building the separable representation. Two ReLU hidden units feed one output unit, with these weights and biases:2

The hidden layer computes , and the output . Take . The pre-activation is , and ReLU clips the negative coordinate, so . Then — correct, since . Run all four inputs:

XOR

The decisive row pair is the middle two. In the input space, and sit on opposite corners; the hidden layer maps both to the same point . The two positive cases have been collapsed onto one location, and now a single line in -space — the readout — separates the positives (at , where ) from the negatives (at and , where ). The hidden layer did not classify; it mapped the input into a space where the final linear unit could.

The XOR hidden layer as a change of coordinates. In the input -space (left) the two positive points and cannot be split from the negatives by one line. The ReLU hidden layer maps them to the same point in -space (right), where a single line separates positives from negatives.

Feedforward networks

A feedforward network is a multilayer network with no cycles: each layer's outputs feed the next, never backward. It has three kinds of layers — an input layer, one or more hidden layers, and an output layer — and in the standard architecture each layer is fully connected, so every unit reads every output of the layer below.3 (Historically these are also called multi-layer perceptrons or MLPs, though modern units are not perceptrons.)

A 2-layer feedforward network. The input (with a bias input ) connects through weight matrix to the hidden layer , which connects through to the output layer . Every unit reads every output of the layer below.

Collecting each hidden unit's weight vector as a row of a matrix and its bias into a vector , the entire hidden layer is one matrix operation followed by an element-wise activation. For an input and a hidden layer of units,

where (or ReLU, or tanh) is applied to each coordinate. Element is the weight from input to hidden unit , so the -th coordinate is just the familiar .

The output layer applies a second weight matrix to the hidden vector, producing an intermediate score vector , and then a softmax normalizes those scores into a probability distribution over the output classes:

Put together, a two-layer network — one hidden layer, one output layer — computes

By the convention of counting only layers with weights (not the input), this is a 2-layer network, and logistic regression — one weight layer, one softmax — is a 1-layer network. A neural classifier is thus logistic regression run on features that the earlier layers learned, rather than features a human designed by hand.

The forward pass in matrix form

Deeper networks reuse the same two operations at every layer. Writing bracketed superscripts for layer index and for the input, an -layer network computes its output by a single loop, each layer a matrix multiply plus an activation.3

Algorithm:Forward(x)\textsc{Forward}(\mathbf{x}) — forward pass through an nn-layer feedforward network
  1. 1
    a[0]x\mathbf{a}^{[0]} \gets \mathbf{x}
  2. 2
    for i=1i = 1 to nn do
  3. 3
    z[i]W[i]a[i1]+b[i]\mathbf{z}^{[i]} \gets \mathbf{W}^{[i]}\mathbf{a}^{[i-1]} + \mathbf{b}^{[i]}
    affine map
  4. 4
    a[i]g[i](z[i])\mathbf{a}^{[i]} \gets g^{[i]}(\mathbf{z}^{[i]})
    element-wise activation
  5. 5
    return y^a[n]\hat{\mathbf{y}} \gets \mathbf{a}^{[n]}

The activation differs by layer: an internal layer uses ReLU or tanh, and the final layer uses softmax for multiclass output or the sigmoid for a binary decision.

Why the non-linearity is not optional

Without activations, the stack collapses to one linear map. Suppose two layers were purely linear, and . Substituting,

The composition is a single affine map . This generalizes to any depth: without non-linear activations a deep network is just a notational variant of one linear layer, and all the representational power of depth is lost. The non-linearity is what lets each hidden layer bend the space into a form the next layer can use.

The feedforward neural language model

Now the target application. A neural language model predicts the next word from the previous ones, exactly the task of an n-gram model, but it represents the context by embeddings rather than word identity.4 Like the n-gram model it makes a Markov approximation, using only the last words:

The architecture is the feedforward network of Bengio and colleagues.4 Take a window of the previous words. Each word is first a one-hot vector of length — all zeros except a single at the word's index in the vocabulary. Multiplying a one-hot vector by an embedding matrix selects one column, the -dimensional embedding of that word. The embeddings are concatenated into the embedding layer , passed through a hidden layer, and finished with a softmax over the whole vocabulary.

The feedforward neural language model with a window of words. One-hot inputs select columns of to give embeddings, concatenated into , mapped through to the hidden layer and through to a softmax over the vocabulary; here the winner is the index for "fish".

Writing the semicolon for concatenation, the model with a window of computes

where each is the one-hot vector of a context word, so is its embedding. Output node gives , the probability that the next word is the -th vocabulary item.

Worked example: shapes and the forward pass

Fix the sizes to trace the forward pass end to end. Say the vocabulary is , the embedding dimension , the window , and the hidden layer . The one-hot of each context word is a -vector with a single . Multiplying by selects one column, a -vector — no arithmetic actually happens, it is a table lookup. Concatenating three gives . Then maps that to the hidden layer , and maps to the score vector , one score per vocabulary word, which softmax normalizes.

The parameter count is dominated by the two matrices touching the vocabulary. The embedding matrix has weights; the output matrix has ; the hidden matrix only . The softmax over classes is the expensive step at both training and inference, which is why later models economize on it — and why the byproduct , cheap to store, is the piece most often reused elsewhere.

One matrix serves all positions rather than a separate matrix per slot: over a long text every word turns up in every position, and we want a single vector per word regardless of where it lands. The embeddings can be pretrained (initialized from word2vec or GloVe and either frozen or fine-tuned) or learned from scratch during language-model training. Either way the parameter set is .

Training

Training is the same procedure as logistic regression, scaled up: a cross-entropy loss minimized by stochastic gradient descent, with the gradient supplied by backpropagation.5

For language modeling the classes are the vocabulary words, and only one is correct at each step — the actual next word . With a one-hot gold vector the multiclass cross-entropy collapses to the negative log probability the model assigns to that one correct word:

This is the negative log likelihood loss. Minimizing it pushes probability mass onto the word that actually occurred. Substituting the softmax makes the score of the correct word explicit, , so the loss rises whenever a wrong word's score competes with the right one's.

Worked example: softmax, loss, and its gradient

Take a toy vocabulary of three words and suppose the output scores at one step are , with the true next word fish (index ). Exponentiate: , , , summing to . The softmax is

The loss is nats. Had the model been certain and correct () the loss would be ; had it put all mass on a wrong word the loss would diverge. The gradient of this loss with respect to the scores has a clean closed form, — the prediction minus the one-hot gold vector. Here , so

The negative component on the true word raises its score next step; the positive components on the two wrong words lower theirs. That single vector, , is the error signal backpropagation carries into every earlier layer, which is why the same subtraction appears at the output of every softmax classifier.

The gradient of this loss with respect to every parameter is computed by backpropagation — backward differentiation over the network's computation graph, applying the chain rule from the loss back to each weight. In outline: the loss's derivative at the output simplifies to (prediction minus gold), and that error signal is multiplied by each layer's local derivative on the way back, giving for every parameter including the embeddings. The full derivation belongs to the deep-learning treatment of backpropagation; here it is enough that the gradient is exact and cheap to compute.

With the gradient in hand, SGD updates each parameter by a small step against it. Over a long training text the model slides a window across the corpus, predicting each word from its predecessors and taking one step per position.

Algorithm:Train-NLM(corpus w1wT, η)\textsc{Train-NLM}(\text{corpus } w_1 \ldots w_T,\ \eta) — SGD for the neural language model
  1. 1
    initialize θ={E,W,U,b}\theta = \{\mathbf{E}, \mathbf{W}, \mathbf{U}, \mathbf{b}\} with small random values
  2. 2
    repeat
  3. 3
    for t=N,N+1,,Tt = N, N+1, \ldots, T do
  4. 4
    e[ExtN+1;;Ext1]\mathbf{e} \gets [\mathbf{E}\mathbf{x}_{t-N+1}; \ldots; \mathbf{E}\mathbf{x}_{t-1}]
    look up and concatenate context embeddings
  5. 5
    hσ(We+b)\mathbf{h} \gets \sigma(\mathbf{W}\mathbf{e} + \mathbf{b})
    hidden layer
  6. 6
    y^softmax(Uh)\hat{\mathbf{y}} \gets \mathrm{softmax}(\mathbf{U}\mathbf{h})
    next-word distribution
  7. 7
    Llogy^iL \gets -\log \hat{y}_{i}
    ii = index of the true word wtw_t
  8. 8
    gθL\mathbf{g} \gets \nabla_\theta L
    backpropagation
  9. 9
    θθηg\theta \gets \theta - \eta\,\mathbf{g}
    gradient-descent step
  10. 10
    until converged
  11. 11
    return θ\theta

Because the gradient reaches , the update tunes the embeddings while learning to predict, so a good next-word predictor and a good set of word vectors fall out of the same objective. The learned is a byproduct usable as word representations elsewhere — the same idea that underlies vector semantics. Optimization here is non-convex, so weights start from small random values (not zero), inputs are normalized, and regularizers such as dropout curb overfitting; these are the standard neural-net training practices, treated in full in the deep-learning course.

Measuring a language model: perplexity

A language model is scored on held-out text by perplexity, the exponential of the average per-word cross-entropy. For a test corpus ,

Perplexity is the model's average branching factor — a perplexity of means the model is, on average, as uncertain as if choosing uniformly among words. And it is nothing but the training loss, averaged and exponentiated, so minimizing cross-entropy minimizes perplexity. On the same corpus a neural language model reaches lower perplexity than an n-gram model of comparable order, a quantitative consequence of the statistical-sharing argument below.

From Bengio to the transformer

The feedforward language model of this lesson is the direct ancestor of every model that followed. Three public developments trace the line from it to the modern era.

The original neural LM (Bengio et al., 2003).6 The architecture here is Bengio and colleagues' A Neural Probabilistic Language Model. Their central claim was that fighting the curse of dimensionality in language required learning a distributed representation for words jointly with the probability function, so that a sentence similar to one in training — similar in the embedding space — inherits its probability. They reported perplexity improvements of over the best smoothed trigram models on the Brown and AP News corpora, the first clear win of a neural LM over n-grams, and the paper that established learned word embeddings a decade before word2vec.

Weight tying (Press and Wolf, 2017; Inan et al., 2017).7 The model has two big vocabulary-sized matrices: the input embedding and the output matrix . Independent work showed that sharing them — using as the output projection — cuts parameters by up to half and consistently lowers perplexity, because the two matrices learn compatible geometry anyway. Tied embeddings became standard in later language models and remain common in transformer LMs.

Scaling the same objective. The feedforward LM's fixed window is its main limitation. Removing it, while keeping the two commitments made here — words as learned vectors, training by cross-entropy — produced the recurrent language model, which carries a state across the whole sequence, and then the transformer, which lets every position attend to every other. Both are, at the loss level, this lesson's classifier: a softmax over the vocabulary trained by negative log likelihood, with a richer function feeding the scores. The GPT family (Radford et al., 2018 onward; Brown et al., 2020) is a decoder-only transformer trained on precisely this objective at scale — the same next-word cross-entropy, over a much larger context and corpus.8

Why embeddings cure sparsity

Return to the opening problem. An n-gram model treats words as atomic symbols with nothing in common: cat and dog are as unrelated as cat and the. So a model that saw I have to make sure that the cat gets fed learns a probability for fed after the cat gets and nothing about the dog gets — a distinct context, unseen, estimated from a back-off or a zero.4

The neural model shares strength through the embedding space. cat and dog land near each other because they appear in similar contexts, so the hidden layer sees nearly the same input whether the context word is cat or dog. Having learned to assign fed high probability after the cat gets, the model generalizes the same prediction to the dog gets — a context it never observed — because the two contexts are close in the space it built. The count table could not do this; the embedding does it automatically.

This is why neural language models generalize better and handle longer histories than n-gram models, at the cost of being slower and less interpretable — for small tasks an n-gram model is still a reasonable choice. The feedforward model here is the simplest of the family: its window is fixed, so it cannot see beyond words back. Lifting that limit is the subject of the next lessons. A recurrent network carries a running state across the whole sequence, and the transformer lets every position attend to every other — but both keep the two commitments made here: represent words as learned vectors, and train by gradient descent on a cross-entropy loss.

Footnotes

  1. Jurafsky & Martin, Speech and Language Processing (3rd ed.), §7.1 — Units: the weighted-sum-plus-bias unit, the sigmoid, tanh, and ReLU activations, and the saturation that motivates ReLU.
  2. Jurafsky & Martin, §7.2 — The XOR Problem: Minsky and Papert's proof that a single perceptron cannot compute XOR, the linear-separability argument, and the two-layer ReLU solution that forms a separable hidden representation. 2 3
  3. Jurafsky & Martin, §7.3 — Feedforward Networks: fully-connected layers, the matrix form , the softmax output, the -layer forward pass, and the collapse of stacked linear layers to a single affine map. 2
  4. Jurafsky & Martin, §7.5 — Feedforward Neural Language Modeling: the Bengio-style architecture, one-hot inputs times a shared embedding matrix , concatenation into the embedding layer, forward inference, and the cat/dog generalization example. 2 3
  5. Jurafsky & Martin, §7.6–§7.7 — Training Neural Nets and the neural language model: the cross-entropy / negative-log-likelihood loss, backpropagation over the computation graph, and SGD over the corpus with .
  6. Bengio, Ducharme, Vincent, and Jauvin (2003), A Neural Probabilistic Language Model, JMLR — the feedforward neural language model with jointly-learned distributed word representations, and its perplexity improvements over smoothed n-gram models on the Brown and AP News corpora.
  7. Press and Wolf (2017), Using the Output Embedding to Improve Language Models, EACL; and Inan, Khosravi, and Socher (2017), Tying Word Vectors and Word Classifiers, ICLR — sharing the input embedding and output projection matrices to reduce parameters and lower perplexity.
  8. Radford, Narasimhan, Salimans, and Sutskever (2018), Improving Language Understanding by Generative Pre-Training; and Brown et al. (2020), Language Models are Few-Shot Learners, NeurIPS — decoder-only transformer language models trained with the next-word negative-log-likelihood objective at scale.

╌╌ END ╌╌