Week 08 · Recurrent sequence models
Learn a delayed copy task and relate the delay to repeated Jacobians.
← Week 7 · Subject contents · Week 9 →
Learn a delayed copy task and relate the delay to repeated Jacobians.
Work through the problem
A recurrent network computes hₜ=tanh(Wₓxₜ+Wₕhₜ₋₁+b) and uses the final state to predict a label. The backward derivative through a gap of d steps includes d local Jacobian factors. When their effective gain is below one, distant information gets a weaker training signal.
The task below puts a bit in the first slot and zeros thereafter. Train a small recurrent classifier separately for delays of 3 and 18. Measure the gradient reaching the first input at initialization as well as held-out accuracy after a fixed budget. The toy task measures memory under this setup.
Run the Python lab
import torch
from torch import nn
torch.set_num_threads(1)
for length in [4,19]:
torch.manual_seed(19)
x = torch.zeros(192,length,1)
labels = torch.arange(len(x))%2
x[:,0,0] = 2*labels-1
rnn, head = nn.RNN(1,8,batch_first=True),nn.Linear(8,1)
def forward(data):
return head(rnn(data)[0][:,-1])[:,0]
sample = x[:2].clone().requires_grad_()
gradient = torch.autograd.grad(forward(sample).sum(),sample)[0][:,0].abs().mean()
opt = torch.optim.Adam(list(rnn.parameters())+list(head.parameters()),lr=.02)
for _ in range(100):
opt.zero_grad()
nn.functional.binary_cross_entropy_with_logits(forward(x[:128]),labels[:128].float()).backward()
opt.step()
acc = ((forward(x[128:])>0)==labels[128:]).float().mean()
print(length-1,f"first input gradient {gradient.item():.3g}, accuracy {acc.item():.2f}")
Output from the lab
3 first input gradient 0.00878, accuracy 1.00
18 first input gradient 1.38e-07, accuracy 1.00
Practice
- What would a GRU change?
Check your reasoning
- Its gates can preserve parts of the hidden state over time. Keep the dataset and training budget comparable when testing it.
← Week 7 · Subject contents · Week 9 →
Further reading · Goodfellow, Bengio, and Courville · Deep Learning