A machine logs its status as a stream of events such as ready, move and wait, and the next event depends on what happened before and in which order. Counting the events throws the order away, and a feed-forward network expects a fixed number of inputs, while sessions differ in length. A recurrent network reads the stream one step at a time and carries a summary forward. This lesson traces that computation by hand, shows how its shared weights are trained, introduces the gated cells used in practice, and sets out the bookkeeping of padding, masks and teacher forcing that keeps training honest, with sequences and weights constructed for teaching.
Key terms
Recurrent neural network and hidden state
Definition A recurrent neural network (RNN) reads a sequence of input vectors in in order. Starting from an initial hidden state in , usually the zero vector, the simple recurrent cell computes for
with of shape , of shape , in , and tanh applied to each entry. The hidden state depends only on , the parameters and the inputs . An output layer reads it, for example next-symbol scores with of shape , followed by a softmax. The same parameters are used at every step, so their number, for the cell, does not depend on , and one network handles sequences of any length. A whole sequence, such as one machine session, is one example, and its steps are dependent parts of that example, not separate independent examples.
In plain words The hidden state is the network’s running summary of everything it has read so far. Each step folds the new input into the previous summary with the same weights. The summary has a fixed size and is learned, not a record of every past event, so information that a later prediction needs can be lost. The state starts fresh at the beginning of each independent sequence. Carrying it from one machine’s session into another’s mixes unrelated examples, unless the task deliberately treats them as one continuous stream.
Example Take scalar inputs and states, , with , , and , and give three observed statuses the chosen codes , and . The codes are a convenience for hand calculation, not a claim that the statuses are ordered. Then
The second input is 0, yet is not, because the earlier state still contributes. The same three inputs in the order , , end at , so the final state depends on the order and not only on which inputs occurred. The reversed order , , happens to be the negative of the original sequence, and because tanh is odd and , every state changes sign and the sequence ends at about .
Backpropagation through time
Definition Backpropagation through time (BPTT) computes the gradient of a sequence loss by unrolling the recurrence into one computation graph, with one copy of the cell per step, and applying the chain rule backward from the last step to the first. A shared parameter is used at every step, so its gradient is the sum of the contributions of all its uses. For the cell above and a loss , let be the direct derivative of the step loss, the zero vector for a step without a loss, and set . Going backward for , the gradient of with respect to is
where is the entrywise product, and the parameter gradients are
Truncated BPTT stops the backward pass after a fixed number of steps. It saves memory and time, but no gradient then reaches back across the cut, although the state values still do.
In plain words The unrolled network looks like a deep network with one layer per time step, except that every layer has the same weights. Each copy produces its own gradient for those weights, and the true gradient is their sum. A gradient that keeps only the last step’s direct use misses every path through earlier states. Along a long path the derivative is a product of many factors, so it can shrink toward zero or grow out of control, which is why long-range dependencies are hard to learn and why gradient clipping is often used to limit the size of an update.
Example For an exact hand calculation, drop the tanh and use the scalar linear recurrence with , inputs and , , and the loss . Then , and . Since ,
The use of at step 1 contributes and its use at step 2 contributes , so keeping only the direct use at the last step would give half the gradient. For , the use at step 2 gives , and the use at step 1 adds nothing because . Central differences confirm both values. In this recurrence the derivative of with respect to is , about for and about 3325 for .
Long short-term memory
Definition A long short-term memory (LSTM) cell carries two vectors of width , a cell state and a hidden state . Let be the vector that stacks on top of . In the common form with a forget gate, the cell computes three gates and a candidate,
and then updates
Here is the logistic sigmoid applied to each entry, so every gate entry lies strictly between 0 and 1, and each of the four matrices has shape . The forget gate scales the old cell state, the input gate scales the candidate, and the output gate controls how much of the cell state appears in the hidden state. All gates are learned functions of the current input and the previous hidden state. In this form an LSTM cell has parameters, four times as many as a simple recurrent cell of the same widths.
In plain words The cell state is a lane that runs through time with only entrywise scaling and addition. A forget gate near 1 keeps a value, a forget gate near 0 erases it, and the input gate decides how much new content enters. The direct path from to multiplies by the forget gate entries and nothing else, so gradients along it can travel much further than through repeated multiplication by and tanh derivatives. That helps without guaranteeing anything, because the gates are learned and can close or saturate, and the memory a cell of fixed width can hold is limited.
Example Take one coordinate with old cell value 2, forget gate 0.8, input gate 0.1 and candidate . The new cell value is , and with output gate 0.5 the hidden value is . If the forget gate stayed at 0.9 and the input gate at 0 for 20 steps, the value 2 would decay to , so retention is soft rather than perfect. With a forget gate near 0 and an input gate near 1 the old value is almost erased and replaced by the candidate.
Gated recurrent unit
Definition A gated recurrent unit (GRU) keeps a single state and uses two gates. With stacking and , one common form computes the update gate and the reset gate , then a candidate from the input and the reset previous state,
where stacks and , and finally the blend
Each coordinate of the new state lies between the old state and the candidate, and in this convention is the share given to the candidate. The original GRU and several software libraries write instead, so that their is the share kept from the old state. Because , negating the weights and bias of the update gate turns one convention into the other, and both describe the same family of models. In the form written here a GRU cell has parameters.
In plain words The update gate decides, coordinate by coordinate, how much of the state to replace, and the reset gate decides how much of the old state the candidate may use. When the update gate is near 0, this page’s convention copies the state almost unchanged, which lets information and gradients pass many steps. A GRU has one state instead of two and fewer parameters than an LSTM of the same width, and neither cell is better on every task. Because the two conventions name the gate in opposite ways, read the formula rather than the gate’s name.
Example With old state 0.4, candidate and update gate 0.25, the new state is , a quarter of the way from the old state to the candidate. Reading the same value 0.25 in the other convention gives , three quarters of the way. For and a simple recurrent cell has parameters, a GRU cell and an LSTM cell .
Sequence padding and sequence mask
Definition Sequence padding appends placeholder positions to sequences of unequal lengths so that a batch fits one array of shape with . In this batch-first layout the hidden states form an array of shape . Some libraries put the time axis first, so the layout has to be checked, not guessed. The sequence mask is the array with when step of sequence holds a real observation and at padding. For per-step losses the masked mean is
defined when at least one position is valid. It weights every valid step equally, so long sequences count more than short ones, and averaging within each sequence first is a different choice that has to be declared. Padded positions never become targets. A recurrence whose final state is used either stops at each sequence’s length or keeps the state unchanged at masked steps, when .
In plain words Padding exists only to make the arrays rectangular. The mask records which cells are real, and every loss, average and final state has to respect it. Dividing by all cells would make the reported loss depend on how much padding a batch happens to contain.
Example Pad two sequences of lengths 3 and 1 to . The mask rows are and , so there are 4 valid targets, not 6. With valid losses 0.2, 0.4, 0.6 and 0.8 the masked mean is , while dividing by all 6 cells would report about 0.333 without any prediction changing. Now feed the short sequence, input 1 followed by two padding zeros, to the scalar network of the first card. The state after the real step is . Running the recurrence through the padding would continue to and then , while the masked update keeps as the final state.
Teacher forcing
Definition Teacher forcing trains a next-symbol model by feeding it the observed previous symbols. For an observed sequence preceded by a start symbol , the input at step is , the target is , and the training loss is
where stands for . This is the negative log-likelihood of the sequence under the factorization of into the product of the conditionals , so teacher forcing is maximum likelihood estimation for such a model. The model must be causal, meaning the prediction for step may depend only on . At generation time the observed symbols do not exist, and the input at each step is the model’s own previous output.
In plain words During training the model always sees the true history and is graded one step at a time. During generation it sees its own guesses, and one wrong guess changes every later input and state. The teacher-forced loss therefore measures one-step prediction from correct histories. If generation is the intended use, generated sequences need their own evaluation, including how the model stops and how early mistakes spread. A bidirectional network, whose states also read later positions, would see the very symbol it is asked to predict and cannot be trained this way for next-symbol prediction.
Example For the constructed session START, READY, MOVE, STOP, the inputs are START, READY and MOVE and the targets are READY, MOVE and STOP, shifted by one position. Feeding READY at the step that must predict READY would hand the model the answer, and the training loss would look excellent while teaching nothing usable. At generation time, if the model’s first output were WAIT instead of READY, its second input would be WAIT, a history that teacher-forced training on this session never supplied.
Check yourself
- A batch holds three sequences padded to five steps, with input width 4, hidden width 6 and true lengths 5, 3 and 2. In the batch-first layout with the simple recurrent cell, give the shapes of the input array, the hidden-state array, and , the number of cell parameters, and the denominator of the masked mean loss with one target per real step.
Show the answer
The input array is and the hidden-state array is . The weight matrices are of shape and of shape , and the bias has 6 entries, so the cell has parameters. That number depends on neither the batch size nor the padded length, because the same parameters serve every sequence and every step.
There are valid targets, so the masked mean divides the summed valid losses by 10, not by the cells of the padded array.
- A next-event predictor uses, at step , the centered average of a measurement as a feature for predicting . With the measurements 3, 5, 10 and 8, compute the feature at and explain what is wrong. How should the windows and the evaluation be fixed?
Show the answer
The feature at is . It contains , which is exactly the value to be predicted, so the target leaks into the input. At prediction time is not yet known, and a model trained with this feature would rely on information it will never have.
The fix is a window whose right edge is the prediction origin, such as the trailing average , which at is . Every window has to be rebuilt this way, the model refitted, and the earlier scores discarded, since they measured the leaky procedure. Overlapping windows from one session should also stay in one data role, with a split by session or by time, because a random split of overlapping windows puts nearly identical inputs on both sides.
- Use the linear recurrence with , inputs and , , and the loss . Find , and , the derivative of with respect to split into its two uses, and the derivative with respect to . What would a gradient that keeps only the last step’s direct use of report?
Show the answer
The states are and , so . Since and ,
The use at step 1 contributes and the use at step 2 contributes . The derivative with respect to is , all of it from step 2, because the use of at step 1 multiplies .
A gradient that keeps only the direct use at step 2 would report 2.1 and miss the 0.35 that flows through , about 14 percent of the true value. Central differences agree with 2.45 and 0.14.