Working with Sequences

Dive into Deep Learning · §8.1

Working with Sequences
autoregression · fixed windows vs. latent state · chain rule · Markov models · stationarity · multistep rollout error

Why Sequence Data Breaks the i.i.d. Assumption

Motivation & Core Mental Model

  • Variable length and strict temporal ordering: A document, speech waveform, or vital-sign stream has length T that varies across examples, and permuting the order (“Thank you for your” \to “your thank for you”) destroys its meaning.
  • Internal statistical dependence: While separate trajectories may be drawn independently, consecutive entries x_t within a sequence depend strongly on their prefix x_{<t} = (x_1, \ldots, x_{t-1}).
  • The multistep forecasting gap: On x_t = \sin(0.01t) + \epsilon_t, a linear model on 4 past values achieves near-optimal 1-step MSE (\approx 0.05) yet fails when rolled out 64 steps ahead (MSE \approx 0.25).

Taxonomy of Sequence Learning Problems

Problem Formulation

  • Supervised sequence mappings: Tasks may map a variable-length sequence to a single category (Sequence-to-Label), expand a fixed input into a sequence (Fixed-to-Sequence), or transduce an input sequence \mathbf{x}_{1:T} into an unaligned target sequence \mathbf{y}_{1:T'} (Sequence-to-Sequence).
  • Unsupervised density estimation: Modeling the joint probability P(x_1, \ldots, x_T) requires zero external labels because every entry x_t serves as the supervised target for its own prefix x_{<t}.
  • Dual utility: A joint sequence distribution supports both candidate likelihood ranking (e.g., ASR rescoring) and ancestral generation.

Autoregressive Forecasting and Growing Prefixes

Autoregressive Models

P(x_t \mid x_1, \ldots, x_{t-1}) = P(x_t \mid x_{<t}), \qquad \hat{x}_t = \mathbb{E}[x_t \mid x_{<t}]

  • Why “autoregressive”: Both the conditioning features x_{<t} and the regression target x_t come from the exact same underlying series.
  • The variable-dimension obstacle: At t = 2, x_{<2} has 1 feature; at t = 500, x_{<500} has 499 features. Fixed-input predictors require a constant feature dimension.
  • Two compression strategies: Either truncate x_{<t} to a fixed window of m recent steps or update a recursive latent state \mathbf{h}_{t-1}.

Fixed Windows vs. Latent Autoregressive State

Two Compression Strategies

Both strategies cast sequence forecasting as fixed-input prediction, differing in how they bound memory:

  • Strategy 1 — Fixed m-Step Window: Condition strictly on the m most recent observations (x_{t-m}, \ldots, x_{t-1}) and discard x_{\le t-m-1}: \hat{x}_t = f(x_{t-m}, \ldots, x_{t-1}) Simple and parallelizable across all t, but enforces a hard memory horizon of m steps (the foundation of n-gram models).
  • Strategy 2 — Latent Autoregressive Summary: Maintain a fixed-dimension vector \mathbf{h}_t \in \mathbb{R}^h updated recursively at every step: \mathbf{h}_t = g(\mathbf{h}_{t-1}, x_t) Predictions read out \hat{x}_{t+1} = f(\mathbf{h}_t), summarizing arbitrarily long histories in O(1) space (the foundation of RNNs and state space models).

The Chain Rule Factors Joint Sequence Probabilities

Probabilistic Foundation

P(x_1, \ldots, x_T) = \prod_{t=1}^T P(x_t \mid x_{<t})

  • Exact equivalence: Modeling one-step conditionals P(x_t \mid x_{<t}) completely specifies the joint probability over the entire sequence.
  • Log-domain scoring: Multiplying hundreds of probabilities in (0, 1) underflows float32 to 0.0; we instead sum log-probabilities \sum_{t=1}^T \log P(x_t \mid x_{<t}).
  • Causal left-to-right ordering: Factoring forward in time aligns with physical causality and enables step-by-step ancestral sampling.

The Markov Condition: Bounded Memory Horizons

Statistical Assumptions

P(x_t \mid x_1, \ldots, x_{t-1}) = P(x_t \mid x_{t-m}, \ldots, x_{t-1})

  • m^\textrm{th}-order Markov condition: The future x_t is conditionally independent of the distant past x_{\le t-m-1} given the m most recent observations.
  • First-order case (m = 1): Each entry depends solely on its immediate predecessor, P(x_{1:T}) = P(x_1)\prod_{t=2}^T P(x_t \mid x_{t-1}).
  • Approximation vs. tractability: Natural language is never truly Markov, yet bounded windows make count tables and finite-context models tractable.

Stationarity: Time-Homogeneous Transition Dynamics

Statistical Assumptions

  • Time-invariant conditional law: Fitting a single shared predictor f across all steps t \in \{m+1, \ldots, T\} assumes the transition distribution P(x_t \mid x_{t-m:t-1}) does not drift with t.
  • Stationary dynamics vs. evolving values: A fixed transition rule does not force the marginal P(x_t) to stay constant—a novel’s closing paragraph differs from its opening line because the same rule evaluates on a different context.
  • Pooling sliding windows: Stationarity justifies extracting T - m training pairs from a single length-T trajectory.

Synthetic Benchmark: A Noisy Sine Wave

Controlled Ground-Truth Experiment

To test fixed-window autoregression where the true dynamics are known analytically, we generate T = 1000 steps of a noisy sine wave with period 2\pi / 0.01 \approx 628 steps:

  • Data-generating process: x_t = \sin(0.01\,t) + \epsilon_t, \qquad \epsilon_t \stackrel{\textrm{i.i.d.}}{\sim} \mathcal{N}(0, 0.2^2)
  • Signal-to-noise scale: The noiseless wave changes by at most 0.01 per step (|\cos(0.01t)| \cdot 0.01 \le 0.01), whereas the additive white noise has standard deviation \sigma = 0.2 (20\times larger than a single step’s signal increment) and irreducible variance \sigma^2 = 0.04.
  • Train/validation split: The first num_train = 600 windows (~1 full period) form the training set; the remaining windows test out-of-sample forecasting.

Turning a Time Series into Sliding Lag Windows

Supervised Feature Construction

def lag_features(self):
    """Features (x_{t-m}, ..., x_{t-1}) and labels x_t for t > m."""
    features = [self.x[i : self.T-self.m+i] for i in range(self.m)]
    return d2l.stack(features, 1), d2l.reshape(self.x[self.m:], (-1, 1))

def get_dataloader(self, train):
    i = slice(0, self.num_train) if train else slice(self.num_train, None)
    return self.get_tensorloader(self.lag_features(), train, i)
  • Vectorized lag stacking: Slicing four shifted views of self.x builds the (T - m) \times m = 996 \times 4 feature matrix paired with target column \mathbf{y} \in \mathbb{R}^{996 \times 1}.
  • Chronological split: Rows 1\text{--}600 (t = 5\text{--}604) train the model; rows 601\text{--}996 (t = 605\text{--}1000) evaluate out-of-sample forecasting.

Training a Linear Autoregressor on Four Lags

Model & One-Step Evaluation Setup

We fit an ordinary linear regression model \hat{x}_t = w_1 x_{t-4} + w_2 x_{t-3} + w_3 x_{t-2} + w_4 x_{t-1} + b by minimizing 1-step mean squared error over 5 epochs of minibatch SGD (\eta = 0.01, batch size 16):

model = d2l.LinearRegression(lr=0.01)
trainer = d2l.Trainer(max_epochs=5)
trainer.fit(model, data)
features, labels = data.lag_features()
with torch.inference_mode():  # prediction only: record no gradients
    onestep_preds = d2l.numpy(model(features))

One-Step Evaluation Protocol: In onestep_preds = model(features), every prediction \hat{x}_t, even in the validation region t > 604, is conditioned on the four true observed values (x_{t-4}, x_{t-3}, x_{t-2}, x_{t-1}) from the dataset.

One-Step-Ahead Forecasts Track the Ground Truth

One-Step-Ahead Results

Conditioned on the four true preceding measurements at every step, the linear model tracks the underlying sine wave cleanly across both training and validation splits:

  • Near-optimal 1-step denoising: Across the entire trajectory t \in [5, 1000], the 1-step predictions (magenta dashed curve) smooth out the \sigma = 0.2 Gaussian fluctuations and follow the true wave phase.
  • Generalization beyond t = 604: Because the sine wave’s transition dynamics are stationary, the linear rule fitted on the first 600 steps transfers seamlessly to steps 605\text{--}1000 whenever ground-truth lag windows are supplied.

Multistep Rollout: Feeding Predictions Back In

Autoregressive Rollout Mechanics

When true observations stop at t = 604, forecasting \hat{x}_{605}, \ldots, \hat{x}_{1000} requires an autoregressive rollout that substitutes each predicted value \hat{x}_{t+k} into the input window for all subsequent steps:

\begin{aligned} \hat{x}_{t+1} &= f(x_{t-3}, x_{t-2}, x_{t-1}, x_t) \\ \hat{x}_{t+2} &= f(x_{t-2}, x_{t-1}, x_t, \hat{x}_{t+1}) \\ \hat{x}_{t+3} &= f(x_{t-1}, x_t, \hat{x}_{t+1}, \hat{x}_{t+2}) \\ \hat{x}_{t+4} &= f(x_t, \hat{x}_{t+1}, \hat{x}_{t+2}, \hat{x}_{t+3}) \\ \hat{x}_{t+5} &= f(\hat{x}_{t+1}, \hat{x}_{t+2}, \hat{x}_{t+3}, \hat{x}_{t+4}) \end{aligned}

  • Self-conditioned horizon: By step t + m + 1 (k = 5 for m = 4), zero true observations remain in the window; the model runs purely on its own outputs.
multistep_preds = data.x.clone()
with torch.inference_mode():
    for i in range(data.num_train + data.m, data.T):
        multistep_preds[i] = model(
            multistep_preds[i-data.m : i].reshape(1, -1))
multistep_preds = d2l.numpy(multistep_preds)

Catastrophic Rollout Failure Beyond Step 604

Multistep Rollout Results

Despite its low 1-step validation error, rolling the exact same linear model forward from t = 604 without fresh observations fails completely to reproduce the sine wave:

  • No oscillation: Starting from the level of the final observed window (x_{601}, x_{602}, x_{603}, x_{604}), the rollout curve (magenta) never turns upward or downward with the wave.
  • Slow exponential decay to a fixed point: Instead of oscillating with period 628, the trajectory flattens immediately and drifts monotonically toward a constant asymptote while the true series completes another half-cycle.

Why One-Step MSE Learns a Moving Average

Statistical Diagnosis of the Failure

w, b = model.get_w_b()
print(f'weights on x[t-{data.m}], ..., x[t-1]:',
      d2l.numpy(d2l.reshape(w, -1)).round(3))
weights on x[t-4], ..., x[t-1]: [0.25  0.249 0.23  0.254]
  • 1-step MSE rewards noise averaging: Weights w_i \approx 0.25 cut white-noise variance fourfold (\sigma^2/4 = 0.01) with negligible 1-step phase bias (\sim 10^{-4}).
  • Why 1-step MSE rejects the true oscillator: The exact noiseless recurrence x_t = 2\cos(0.01)x_{t-1} - x_{t-2} amplifies noise variance 5\times (5\sigma^2 = 0.20).
  • Fixed-point rollout collapse: Fed its own outputs, a moving average cannot oscillate and decays toward x^* = b / (1 - \sum w_i).

Vectorized k-Step-Ahead Rollout Across All Starts

Measuring Degradation Across Horizons

To measure forecast quality as a function of lookahead horizon k \in \{1, 4, 16, 64\}, k_step_pred rolls the model forward k steps simultaneously from every valid starting index in the series:

def k_step_pred(model, x, m, k):
    """Predictions 1, 2, ..., k steps ahead from every start position."""
    n = len(x) - m - k + 1                       # number of start positions
    columns = [x[i : i + n] for i in range(m)]   # observed lags
    for j in range(k):
        preds = model(d2l.stack(columns[j : j + m], 1))
        columns.append(d2l.reshape(preds, -1))
    return columns[m:]                           # entry j-1: j steps ahead
  • Phase delay and amplitude damping: At k = 1 and k = 4, forecasts hug the wave; by k = 16 and k = 64, the forecast is a visibly damped copy of the series delayed by \approx k time steps.

Analytical Phase-Lag Error Growth with Horizon k

Quantitative Horizon Analysis

Because the 4-lag moving average predicts roughly the level of the series k steps earlier (\hat{x}_{t+k} \approx \sin(0.01\,t)), its k-step MSE equals the baseline 1-step noise floor (0.05) plus the mean squared distance the sine wave travels over k steps:

\textrm{MSE}(k) \approx 0.05 + \frac{1}{2\pi}\int_0^{2\pi} \bigl(\sin(a + 0.01\,k) - \sin a\bigr)^2\,da = 0.05 + 1 - \cos(0.01\,k)

x = d2l.numpy(data.x)
for k in steps:
    err = d2l.numpy(preds[k-1]) - x[data.m+k-1 : data.T-steps[-1]+k]
    print(f'{k:2d} steps ahead: mean squared error {(err**2).mean():.3f}')
print(f'variance of the series: {x.var():.3f}')
 1 steps ahead: mean squared error 0.048
 4 steps ahead: mean squared error 0.049
16 steps ahead: mean squared error 0.066
64 steps ahead: mean squared error 0.246
variance of the series: 0.496

Two Distinct Rollout Failure Modes:

  1. Short-horizon objective mismatch (seen here): The averaging model damps perturbations (\sum w_i < 1), so errors do not explode; rather, 1-step training never rewarded learning the curvature needed at k = 64.
  2. Compounding rollout drift (exposure bias): In models that amplify perturbations (such as autoregressive text generators or physics simulators), each step’s prediction error shifts the input distribution at step t+1, causing errors to compound rapidly over long rollouts.

Concept Check: Autoregression & Rollout Dynamics

Check Your Understanding

Work through these three calculations to verify your grasp of autoregressive factorization and rollout behavior:

  1. Chain Rule vs. Markov Factorization: Write out the exact 4-step factorization of P(x_1, x_2, x_3, x_4) under (a) the general chain rule and (b) a 2^\textrm{nd}-order Markov model (m = 2). Which factor changes?
  2. Exact Moving-Average Rollout Limit: Suppose a 4-lag linear model has exact weights w_1 = w_2 = w_3 = w_4 = 1/4 and bias b = 0, and the last 4 observed values are (0.2, 0.4, 0.6, 0.8). What is the 1-step prediction \hat{x}_{t+1}, and to what exact constant does the infinite rollout converge?
  3. Noise vs. Curvature Trade-Off: If we reduce the noise standard deviation from \sigma = 0.2 down to \sigma = 0 and fit m = 2 lags, what weights (w_1, w_2) on (x_{t-2}, x_{t-1}) will linear regression learn, and how will its 400-step rollout behave?

Answers:

  1. (a) P(x_1)\,P(x_2 \mid x_1)\,P(x_3 \mid x_1, x_2)\,P(x_4 \mid x_1, x_2, x_3). (b) Only the fourth factor changes, dropping x_1 to become P(x_4 \mid x_2, x_3).
  2. \hat{x}_{t+1} = 0.5 (immediately reversing the upward trend). Because x_{t-3} + 2x_{t-2} + 3x_{t-1} + 4\hat{x}_t is a conserved invariant under \hat{x}_t = \frac{1}{4}\sum_{i=1}^4 x_{t-i}, the rollout converges to (1(0.2) + 2(0.4) + 3(0.6) + 4(0.8)) / 10 = 6.0 / 10 = 0.60.
  3. Exact oscillator weights: With \sigma = 0, w_1 = -1 (on x_{t-2}) and w_2 = 2\cos(0.01) \approx 1.9999 (on x_{t-1}), achieving zero 1-step error and oscillating perfectly forever during rollout.

Summary: Key Concepts in Sequence Modeling

Section Takeaways

Concept Mathematical Form Key Property / Complexity Practical Pitfall
Chain-Rule Factorization P(x_{1:T}) = \prod_{t=1}^T P(x_t \mid x_{<t}) Exact for any joint distribution; score via \sum_t \log P(x_t \mid x_{<t}) Direct product \prod_t P(x_t \mid x_{<t}) underflows float32 on long sequences
Fixed-Window Markov AR P(x_t \mid x_{<t}) = P(x_t \mid x_{t-m:t-1}) Fixed input width m; parallelizable across all T - m windows Hard blindness to any dependency more than m steps in the past
Latent Autoregressive State \mathbf{h}_t = g(\mathbf{h}_{t-1}, x_t), \hat{x}_{t+1} = f(\mathbf{h}_t) O(1) state dimension h summarizes unbounded prefix x_{\le t} Sequential update dependency across t; lossy state bottleneck
Stationarity (Time-Homogeneity) P(x_t \mid x_{t-m:t-1}) independent of t Justifies pooling sliding windows from all t into one dataset Fails under regime shifts if transition dynamics drift over time
1-Step vs. k-Step Rollout \hat{x}_{t+k} = f(\hat{x}_{t+k-m}, \ldots, \hat{x}_{t+k-1}) After k > m steps, predictor runs purely on self-generated inputs Low 1-step loss rewards local noise smoothing over long-range dynamics