We will illustrate BPTT through a simple RNN with the following structure. The dimensions of the input and hidden states are only for illustration purposes.
For consistency with the code in file bptt_example_1.py, the time index begins at 0 instead of 1.
RNN structure for this section. $L$ is the final scalar loss for calculation of gradients.
Our RNN will be govered by the following structure
This equation breaks the gradient flow into two parts
Division of gradient flow for calculation of gradients of hidden state at $t$.
Gradient flow from \(L\) to \(h_{t}\) via \(a_{t+1}\): this incorporates gradient flow through all of \(l_{i}\)s for \(i > t\)
Gradient flow from \(L\) to \(h_{t}\) directly via \(l_{t}\): this component is separate since the gradient to \(a_{t+1}\) will not depend on \(l_{t}\)
Let's also look at the derivative with respect to the activation
This is valid because the first multiplier incorporates gradient flow through all \(l_{i}\)s for \(i > t\) and there is no other dependency for the gradient flow from \(h_{t}\) to \(a_{t}\) as they have a direct connection.
To summarize, for gradient calculation of hidden states and activations, we will start the calculation from the highest time index
we now consider the gradient calculation for \(W_{xh}\), \(W_{hh}\) and \(b_{h}\). Once we know the gradient at any \(a_{t}\), the gradient from here to the matrices can be calculated using the formulae from the dense layer