Recurrent neural networks: reading one word at a time
A language model predicts the next word from its context , the words that came before it. The models we can build from counts or from a feed-forward network all look at a fixed number of previous words. A recurrent neural network (RNN) reads the words one at a time instead and keeps a running summary of everything it has read. We'll run a small RNN over the sentence "we sat on the bank of the river", compute its first two steps by hand, and then look at the ways the same network can be used: one answer for a whole sentence, one answer per word, and a language model whose context is the entire sentence so far.
A fixed window cuts the sentence off
An n-gram model estimates the probability of the next word from the last words. It makes the Markov assumption: everything earlier is dropped from the context.
A neural language model keeps the same window. It looks up a vector of learned numbers for each of the context words, its word embedding, places the vectors side by side and passes them through a feed-forward network [1]. The input layer has one slot per position, so the window size has to be chosen before training. In practice these models saw five to ten previous words [2].
With a window of three words, predicting the last word of our sentence means predicting it from "bank of the". The words "we sat on" are outside the window, and they are the ones that say this is a bank someone can sit on. Widening the window adds another block of input weights for every extra position and still cuts a longer sentence off somewhere. Elman described the same limit in 1990: a model that sees a sequence as one long input "imposes a rigid limit on the duration of patterns" and expects every input to have the same length [3].
A hidden state carries the past forward
An RNN processes the sentence one step per word. At step it reads the embedding of word and combines it with its hidden state , a vector that summarizes the words it has read so far. The result is the new state :
The simplest version, often called an Elman network, computes the new state with one layer:
The matrix weighs the new word, weighs the previous state, and is a bias. The hyperbolic tangent, , squashes each number of the sum into the range from to . Before the first word the state is all zeros, .
Elman's 1990 network had this structure. It copied the hidden layer at each step into a set of "context units", which fed back into the hidden layer together with the next input [3]. An earlier network by Michael Jordan, which Elman built on, had fed back its outputs instead. Because the hidden layer is trained, what it carries forward is learned too.
Working through "we sat"
To follow the arithmetic, we can give every vector two numbers. Take these weights, with :
and these embeddings for the first two words, written as rows to save space:
At the first step the previous state is zero, so only the word contributes:
At the second step the new word and the previous state both enter the sum:
The state depends on "sat" through and on "we" through . Had the sentence started with a different word, would differ and so would .
The same weights at every step
Each later word goes through the same computation with the same , and . Drawn out over the whole sentence, the RNN becomes a chain of identical steps, called the unrolled network:
The shading shows the two numbers of each state, from (light) to (dark). If we write one step as a function , so that , then unrolling three steps gives
so the state after any word depends on every word before it [4]. The state after "river" is a function of all eight words.
Sharing the weights also fixes the size of the model. With word embeddings of numbers and a state of numbers, holds weights, holds and holds , whatever the length of the sentence. With , that is numbers, for a sentence of eight words or eighty.
What the state encodes is learned from the task. Elman trained a network with 150 hidden units to predict the next word in a stream of 27,354 words from 10,000 short generated sentences, with every word given as a code that said nothing about its meaning. When he averaged the hidden states for each of the 29 words and clustered them, nouns and verbs separated, and the nouns split into animate and inanimate, then into humans, animals, foods and breakable objects [3]. The network had found these classes from word order alone.
Acceptors and encoders read the final state
Once the chain has read the sentence, there are several ways to take an answer from it. The simplest uses only the last state. An RNN used this way is an acceptor: it reads the whole sequence and makes one prediction from , for example the topic or the sentiment of the sentence, and the loss is computed from that single prediction [4]. The name comes from finite-state acceptors, which read a string to the end and then accept or reject it.
An encoder also keeps only the final state but doesn't make a decision from it. It hands to another model as a fixed-size vector standing for the whole sentence, to be combined with other information there.
Either way, a sentence of any length becomes a vector of numbers, which a feed-forward classifier can take as input.
Transducers read every state
A transducer makes a prediction from the state after every word, so it produces one output per input. Part-of-speech tagging works this way. Each word gets a tag such as PRON for a pronoun, DET for a determiner such as "the", or ADP for a preposition such as "on" or "of":
The tag for "bank" is predicted from , which depends on "we sat on the bank". In a hidden Markov model tagger, by contrast, the probability of each tag depends only on the tag before it. Training a transducer computes a loss at every step and adds the losses up [4].
A language model without the Markov assumption
A language model is a transducer whose output at step is a guess at word :
An output matrix with one row per vocabulary word turns the state into one score per word, and softmax turns the scores into probabilities:
Since depends on every word so far, the context of each prediction is the whole sentence up to that point. Nothing is cut off, so the probability of a sentence is the exact chain-rule product, with no Markov approximation:
We can follow one prediction in our two-number network. Continuing the computation through "we sat on the bank of the" gives . To see the arithmetic, we shrink the vocabulary to four words. The row of for "river" is , so its score is . The rows for "lake", "road" and "sat", , and , give scores of , and . Softmax turns the four scores into river , lake , road and sat .
In 2010, Mikolov and colleagues used this kind of simple recurrent network as the language model of a speech recognizer, with a sigmoid in place of and between 30 and 500 hidden units [2]. They measured perplexity, the geometric mean of over the words of held-out text, where lower means better predictions. Trained on 6.4 million words of newspaper text, a single RNN reached a perplexity of 171, against 221 for a 5-gram model trained on the same words. A mix of three RNNs and the 5-gram model, with the RNNs still updating as they read the test data, cut the recognizer's word error rate from 13.5% to 11.1%, about 18% fewer errors. The cost was training time: the largest models took several weeks to train.
How is a loop trained?
Training should raise the probability of each correct next word. For the step that predicts "river", the loss is
and the loss for the sentence adds one such term per step:
In a feed-forward network each weight belongs to one layer, and its effect on the loss passes through the layers above it once. Here depends on at all seven steps behind "river" and on at every step after the first: shapes , which feeds into , and so on up to , and it acts again at each of those steps. The chain of uses grows with every word in the sentence. To adjust either matrix, the error at "river" has to be traced back through a loop that ran seven times.
References
- Bengio, Y., et al. (2003). A neural probabilistic language model. Journal of Machine Learning Research 3. jmlr.org ↩
- Mikolov, T., et al. (2010). Recurrent neural network based language model. Proceedings of Interspeech 2010. doi:10.21437/Interspeech.2010-343 ↩
- Elman, J. L. (1990). Finding structure in time. Cognitive Science 14(2). doi:10.1207/s15516709cog1402_1 ↩
- Goldberg, Y. (2016). A primer on neural network models for natural language processing. Journal of Artificial Intelligence Research 57. doi:10.1613/jair.4992 ↩
Want to keep up with AI? Follow us on X (opens in a new tab) and Instagram (opens in a new tab), or check out our shirts.