# Backpropagation through time

Backpropagation through time (BPTT) is a gradient-based technique for training certain types of recurrent neural networks. It can be used to train Elman networks. The algorithm was independently derived by numerous researchers.[1][2][3]

## Algorithm

BPTT unfolds a recurrent neural network through time.

The training data for a recurrent neural network is an ordered sequence of ${\displaystyle k}$ input-output pairs, ${\displaystyle \langle \mathbf {a} _{0},\mathbf {y} _{0}\rangle ,\langle \mathbf {a} _{1},\mathbf {y} _{1}\rangle ,\langle \mathbf {a} _{2},\mathbf {y} _{2}\rangle ,...,\langle \mathbf {a} _{k-1},\mathbf {y} _{k-1}\rangle }$. An initial value must be specified for the hidden state ${\displaystyle \mathbf {x} _{0}}$. Typically, a vector of all zeros is used for this purpose.

BPTT begins by unfolding a recurrent neural network in time. The unfolded network contains ${\displaystyle k}$ inputs and outputs, but every copy of the network shares the same parameters. Then the backpropagation algorithm is used to find the gradient of the cost with respect to all the network parameters.

Consider an example of a neural network that contains a recurrent layer ${\displaystyle f}$ and a feedforward layer ${\displaystyle g}$. There are different ways to define the training cost, but the total cost is always the average of the costs of each of the time steps. The cost of each time step can be computed separately. The figure above shows how the cost at time ${\displaystyle t+3}$ can be computed, by unfolding the recurrent layer ${\displaystyle f}$ for three time steps and adding the feedforward layer ${\displaystyle g}$. Each instance of ${\displaystyle f}$ in the unfolded network shares the same parameters. Thus the weight updates in each instance (${\displaystyle f_{1},f_{2},f_{3}}$) are summed together.

## Pseudocode

Pseudocode for a truncated version of BPTT, where the training data contains ${\displaystyle n}$ input-output pairs, but the network is unfolded for ${\displaystyle k}$ time steps:

Back_Propagation_Through_Time(a, y)   // a[t] is the input at time t. y[t] is the output
Unfold the network to contain k instances of f
do until stopping criteria is met:
x := the zero-magnitude vector // x is the current context
for t from 0 to n − k do      // t is time. n is the length of the training sequence
Set the network inputs to x, a[t], a[t+1], ..., a[t+k−1]
p := forward-propagate the inputs over the whole unfolded network
e := y[t+k] − p;           // error = target − prediction
Back-propagate the error, e, back across the whole unfolded network
Sum the weight changes in the k instances of f together.
Update all the weights in f and g.
x := f(x, a[t]);           // compute the context for the next time-step


BPTT tends to be significantly faster for training recurrent neural networks than general-purpose optimization techniques such as evolutionary optimization.[4]