Skip to content
LeetQuant
E06 Advanced Machine Learning

E06 · Advanced Machine Learning · Lesson 2 of 4

Sequence Models

Recurrent networks and why their gradients vanish or explode, LSTM and GRU gating, causal and dilated 1-D convolutions, attention and transformers at a conceptual level, and why sequence models so often fail to beat trivial baselines on returns.

18 min

Objective

A sequence model maps a history x1,…,xtx_1, \dots, x_t to a prediction about what comes next. You should be able to explain the gradient problem of plain RNNs with a one-line calculation, say what the LSTM forget gate fixes, compute the receptive field of a dilated convolution, write down scaled dot-product attention and justify the d\sqrt{d}, and argue, with numbers, why these models rarely help with predicting the sign of the next return.

Recurrent networks and vanishing gradients

A recurrent network carries a hidden state through time:

ht=tanh⁡(Wht−1+Uxt+b),y^t=Vht.h_t = \tanh\big(W h_{t-1} + U x_t + b\big), \qquad \hat y_t = V h_t .

The same WW and UU are used at every step (weight sharing across time). Training unrolls the recursion and backpropagates through all steps (backpropagation through time). The gradient of a loss at time TT with respect to an earlier state is a product of Jacobians:

∂hT∂ht=∏k=t+1Tdiag⁡(tanh⁡′(zk)) W.\frac{\partial h_T}{\partial h_t} = \prod_{k=t+1}^{T} \operatorname{diag}\big(\tanh'(z_k)\big)\, W .

Since tanh⁡′≤1\tanh' \le 1, the norm of this product is at most ∥W∥T−t\lVert W \rVert^{T-t}. If the largest singular value of WW is below 1, gradients from distant steps vanish geometrically; if above 1, they can explode. Exploding gradients are handled by gradient clipping (rescale the gradient when its norm exceeds a threshold). Vanishing gradients are structural: the network simply cannot learn dependencies more than a few dozen steps long.

Worked example

how far back can a scalar RNN see?

A one-unit linear RNN has ht=wht−1+uxth_t = w h_{t-1} + u x_t. How much does the gradient from step tt shrink or grow after 50 steps for w=0.9w = 0.9 and for w=1.1w = 1.1? Compare with an LSTM cell whose forget gate sits at f=0.98f = 0.98.

Show solution

Here ∂ht+50/∂ht=w50\partial h_{t+50} / \partial h_t = w^{50}.

  • w=0.9w = 0.9: 0.950≈0.00520.9^{50} \approx 0.0052. A signal 50 steps back contributes about 0.5% of its original gradient; with tanh⁡\tanh saturation it is smaller still.
  • w=1.1w = 1.1: 1.150≈1171.1^{50} \approx 117. The gradient explodes, so training without clipping is unstable.

There is no comfortable middle: you need ww very close to 1, and a non-linear network cannot hold that for every input.

The LSTM's memory cell (next section) is updated additively, ct=ft⊙ct−1+it⊙c~tc_t = f_t \odot c_{t-1} + i_t \odot \tilde c_t, so along the cell path ∂ct/∂ct−1=ft\partial c_t / \partial c_{t-1} = f_t, a gate the network learns per step. With f=0.98f = 0.98, after 50 steps the factor is 0.9850≈0.360.98^{50} \approx 0.36. The network can choose to remember, and it can do so without the instability of w>1w > 1.

LSTM and GRU gating, intuitively

An LSTM keeps a memory cell ctc_t next to the hidden state hth_t and controls it with three sigmoid gates, each a function of (ht−1,xt)(h_{t-1}, x_t) with values in (0,1)(0, 1):

  • forget gate ftf_t: how much of the old memory to keep;
  • input gate iti_t: how much of the candidate c~t=tanh⁡(Wcht−1+Ucxt+bc)\tilde c_t = \tanh(W_c h_{t-1} + U_c x_t + b_c) to write;
  • output gate oto_t: how much of the memory to expose, ht=ot⊙tanh⁡(ct)h_t = o_t \odot \tanh(c_t).

The cell update ct=ft⊙ct−1+it⊙c~tc_t = f_t \odot c_{t-1} + i_t \odot \tilde c_t is the key: memory is carried forward by multiplication with a learned gate and an addition, not by a squashing non-linearity, so gradients can survive many steps when ft≈1f_t \approx 1. Biasing the forget gate towards 1 at initialisation is a common trick.

A GRU merges the cell and hidden state and uses two gates: an update gate ztz_t that interpolates, ht=(1−zt)⊙ht−1+zt⊙h~th_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde h_t, and a reset gate that controls how much of ht−1h_{t-1} feeds the candidate h~t\tilde h_t. It has about three quarters of the LSTM's parameters and often performs the same.

Parameter count is worth knowing. Each LSTM gate and the candidate have a dh×(dh+dx)d_h \times (d_h + d_x) matrix and a bias, so an LSTM layer has 4 (dh(dh+dx)+dh)4\,(d_h(d_h + d_x) + d_h) parameters: with dx=10d_x = 10 inputs and dh=32d_h = 32 units that is 4×(32×42+32)=5,5044 \times (32 \times 42 + 32) = 5{,}504. The textbook GRU has three blocks, 4,1284{,}128. Compared with a few thousand daily observations, these are not small models.

1-D convolutions

A 1-D convolution slides a kernel of width kk along time: yt=∑j=0k−1ajxt−jy_t = \sum_{j=0}^{k-1} a_j x_{t-j} per channel, with the same weights at every position. Two rules for forecasting:

  • Causal padding. Pad only on the left so yty_t depends on xt,xt−1,…x_t, x_{t-1}, \dots and never on xt+1x_{t+1}. Symmetric ("same") padding, the default in many libraries, centres the kernel and silently uses the future.
  • Dilation grows the receptive field cheaply. Layer ℓ\ell skips 2ℓ−1−12^{\ell-1} - 1 steps between taps. With LL layers of kernel width kk and dilations 1,2,4,…,2L−11, 2, 4, \dots, 2^{L-1}, the receptive field is
1+(k−1) (2L−1).1 + (k-1)\,(2^{L} - 1) .

With k=2k = 2 and L=8L = 8 layers this is 256256 steps, about a year of daily data, from 8 layers of 2-tap filters. With k=3k = 3 and L=4L = 4 it is 1+2×15=311 + 2 \times 15 = 31.

A causal convolution stack is a non-linear autoregression with a fixed lookback. It trains in parallel across time (unlike an RNN) and its gradients do not pass through long products of the same matrix.

Attention and transformers, conceptually

Attention lets each position build its output as a weighted average of all (permitted) positions, with weights computed from content. Each position emits a query qq, key kk and value vv (linear maps of its input), and

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤d) V.\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\Big(\frac{Q K^{\top}}{\sqrt{d}}\Big)\, V .

Why d\sqrt{d}. If the dd components of qq and kk are independent with mean 0 and variance 1, then q⋅kq \cdot k has variance dd. Without scaling, scores for large dd have standard deviation d\sqrt{d}, the softmax saturates onto one position and its gradients vanish. Dividing by d\sqrt{d} restores unit variance.

Other essentials: a causal mask sets scores for future positions to −∞-\infty so a forecaster cannot look ahead; attention is permutation-invariant, so positional encodings must be added to say where each element sits; multi-head attention runs several attention maps in parallel on lower-dimensional projections; and a transformer block is attention plus a position-wise MLP, each wrapped in a residual connection and layer normalisation. Cost and memory grow as O(T2)O(T^2) in the sequence length.

Worked example

one attention read-out

A query q=(1,0)q = (1, 0) attends over three positions with keys k1=(1,0)k_1 = (1, 0), k2=(0,1)k_2 = (0, 1), k3=(1,1)k_3 = (1, 1) and scalar values v=(1,2,4)v = (1, 2, 4), with d=2d = 2. Compute the attention weights and the output. Then multiply every score by 4 (as happens when the dot products are not scaled and dd is large) and recompute the weights.

Show solution

Raw dot products: q⋅k=(1,0,1)q \cdot k = (1, 0, 1). Scaled by 2\sqrt{2}: (0.707,0,0.707)(0.707, 0, 0.707).

Softmax: e0.707=2.028e^{0.707} = 2.028 and e0=1e^{0} = 1, total 5.0565.056, so the weights are (0.401,0.198,0.401)(0.401, 0.198, 0.401). Output =0.401×1+0.198×2+0.401×4=2.40= 0.401 \times 1 + 0.198 \times 2 + 0.401 \times 4 = 2.40.

With scores multiplied by 4, (2.83,0,2.83)(2.83, 0, 2.83), the weights become (0.495,0.009,0.495)(0.495, 0.009, 0.495): position 2 is all but ignored and the softmax is close to saturated. Its gradient with respect to the scores, wi(δij−wj)w_i(\delta_{ij} - w_j), is then near zero for position 2. This is the failure the d\sqrt{d} scaling prevents.

Why sequence models often fail on returns

Sequence models shine when the sequence has rich, stable, learnable structure and there are many examples: text, speech, sensor data. Daily returns are close to the opposite.

  • Near-martingale. If the best predictor of the next return explains 0.1% of its variance, there is almost nothing for an expressive model to find, and a lot of noise for it to fit.
  • One path. Twenty years of one asset is one sequence of about 5,000 days. Sliding windows create thousands of training rows, but consecutive windows share all but one value, so the effective sample is far smaller than the row count.
  • Non-stationarity. Long lookbacks span regimes; the dependence a model learns in one may be absent in the next.
  • Fat tails. A few extreme days dominate a squared loss and therefore the gradient.

The script below simulates returns with a real but tiny AR(1) coefficient (ϕ=0.03\phi = 0.03) and GARCH-style volatility clustering, then forecasts the next return from the last 20 returns with a zero forecast, AR(1), a 20-lag linear model and an MLP on the 20-return window (the simplest non-linear sequence model; an LSTM fits the same windows).

import warnings
import numpy as np
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import r2_score

warnings.filterwarnings("ignore", category=ConvergenceWarning)   # we want it to overfit
rng = np.random.default_rng(1)
T, L = 12000, 20
# returns: weak AR(1) mean (phi = 0.03) plus GARCH(1,1)-style volatility clustering
r, s2 = np.zeros(T), np.full(T, 1e-4)
for t in range(1, T):
    s2[t] = 1e-6 + 0.08 * r[t - 1] ** 2 + 0.90 * s2[t - 1]
    r[t] = 0.03 * r[t - 1] + np.sqrt(s2[t]) * rng.standard_normal()

# each row is the window of the last L returns; the target is the next return
X = np.lib.stride_tricks.sliding_window_view(r[:-1], L)    # X[i] = r[i : i+L]
y = r[L:]                                                   # y[i] = r[i+L]
sd = r[:8000].std()                                         # training-period scale only
X, y = X / sd, y / sd
tr, te = slice(0, 8000 - L), slice(8000 - L, None)          # chronological split

ar1 = LinearRegression().fit(X[tr, -1:], y[tr])
lin = LinearRegression().fit(X[tr], y[tr])
mlp = MLPRegressor(hidden_layer_sizes=(64, 32), alpha=1e-3, max_iter=200,
                   random_state=0).fit(X[tr], y[tr])
preds = {
    "zero forecast": np.zeros(len(y[te])),
    "true AR(1) mean": 0.03 * X[te, -1],
    "fitted AR(1)": ar1.predict(X[te, -1:]),
    "linear, 20 lags": lin.predict(X[te]),
    "MLP, 20 lags": mlp.predict(X[te]),
}
for name, p in preds.items():
    print(f"{name:16s} test R^2 {r2_score(y[te], p):+.4f}")
print(f"MLP, 20 lags     train R^2 {r2_score(y[tr], mlp.predict(X[tr])):+.4f}")

# the same windows do predict the SIZE of the next move, because volatility persists
w = 0.94 ** np.arange(L)[::-1]                              # EWMA weights, newest last
ewma_vol = np.sqrt((X ** 2) @ w / w.sum())
print(f"corr(EWMA vol, next |r|) test {np.corrcoef(ewma_vol[te], np.abs(y[te]))[0, 1]:.3f}")

Output:

zero forecast    test R^2 -0.0002
true AR(1) mean  test R^2 -0.0005
fitted AR(1)     test R^2 -0.0004
linear, 20 lags  test R^2 -0.0041
MLP, 20 lags     test R^2 -0.5573
MLP, 20 lags     train R^2 +0.5426
corr(EWMA vol, next |r|) test 0.248

Three lessons. First, even the true model has a negative test R2R^2 on 3,980 days: its population R2R^2 is ϕ2≈0.0009\phi^2 \approx 0.0009, and the standard error of a correlation estimated from 3,980 points is about 1/3980≈0.0161/\sqrt{3980} \approx 0.016, so a true correlation of 0.030.03 is under two standard errors from zero. The test set cannot reliably tell the right model from "predict zero". Second, the flexible model fits half the training variance and is catastrophically worse than zero out of sample. Third, the windows are informative about volatility: a hand-set EWMA has correlation 0.250.25 with the next absolute return. Sequence structure in finance lives mostly in second moments, order flow and high-frequency data with millions of events, not in the sign of tomorrow's daily return.

Answering "would you use an LSTM to predict daily returns?" out loud

State the baselines first: zero (or the historical mean), AR(1) or a linear model on lags, and for volatility an EWMA or GARCH. Say the LSTM must beat them out of sample on a walk-forward split, by enough to survive costs, before it is used. Then explain why you expect it to struggle (low signal-to-noise, one overlapping path, regime change), and where you would use sequence models instead: volatility and volume forecasting, limit-order-book events, models sharing weights across thousands of assets so the effective sample is large, and text.

Knowledge check

A causal convolutional network has 6 layers, kernel width 3 and dilations 1, 2, 4, 8, 16, 32. How many past time steps (including the current one) can the top output see?

Knowledge check

Why can an LSTM carry information over many more time steps than a plain tanh RNN?

Knowledge check

A colleague's 1-D CNN predicts next-day returns with a test hit rate of 58% on daily data. The layers use padding='same'. What is the most likely explanation?

Key takeaways

  • Plain RNN gradients scale like ∥W∥T−t\lVert W \rVert^{T-t}: they vanish or explode. Clip for explosion; use gated cells for vanishing.
  • The LSTM cell path has derivative ftf_t, a learned gate, so memory can persist; a GRU does the same with fewer parameters.
  • Causal, dilated 1-D convolutions reach a receptive field of 1+(k−1)(2L−1)1 + (k-1)(2^{L} - 1) cheaply. Never use symmetric padding for forecasting.
  • Attention is a content-weighted average; d\sqrt{d} scaling keeps the softmax out of saturation; causal masks and positional encodings are mandatory for forecasting.
  • On daily returns, compare against zero, AR(1) and linear lags. The signal is so small that even the true model can look worthless on a few thousand test days, while a flexible model can look brilliant in sample and be disastrous out of sample.
  • Sequence structure is strongest in volatility, volume and high-frequency event data.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).