Recurrent state and BPTT
Recurrent state carries information forward; BPTT carries responsibility backward, and truncation decides how far that responsibility can travel.
Long support conversations must be routed while preserving temporal context.
This chapter moves from unroll the recurrence to inspect before clipping. We will make the idea concrete in a small code example before placing it back inside a production system with a declared latency, cost, and operator-capacity budget.
Log gradient norms before applying the clip so exploding gradients remain visible. Detach state only at deliberate sequence or chunk boundaries.
Verify the behavior illustrated in truncated_bptt.py, then measure decision utility, slice reliability, and system latency.
A bidirectional model and globally normalized features use future events unavailable at authorization. An unsafe release must degrade to a named baseline or the last known-good version.
Build the idea one layer at a time.
A recurrent network reads a sequence like a running notebook: every new token updates a compact state that carries selected information forward.
At step t, an RNN combines the current input with the previous hidden state. Reusing the same transition at every step lets it handle variable-length histories, but training must send credit backward through every reused transition. That expanded computation is backpropagation through time, or BPTT.
Long chains multiply many Jacobians, so gradients can vanish or explode. Truncated BPTT limits the chain to manageable chunks: preserve the numerical state between chunks, detach its old graph, then backpropagate through only the current segment. Gradient clipping bounds an unstable update; it does not repair a bad data contract or an impossible memory task.
- padding/masks
- hidden state
- BPTT
- gradient clipping
Follow the reasoning before touching the code.
- 01
Unroll the recurrence
Write the state update for one step, then imagine copies connected across time. The parameters are shared even though each time step has its own activations.
- 02
Choose a credit horizon
Pick a chunk length long enough to cover useful dependencies and short enough for memory and stable optimization. Treat it as a model assumption to validate.
- 03
Inspect before clipping
Log gradient norms before applying the clip so exploding gradients remain visible. Detach state only at deliberate sequence or chunk boundaries.
import torch
rnn = torch.nn.GRU(3, 8, batch_first=True)
head = torch.nn.Linear(8, 1)
optimizer = torch.optim.Adam([*rnn.parameters(), *head.parameters()])
sequence = torch.randn(1, 12, 3)
state = None
for chunk in sequence.split(4, dim=1):
state = None if state is None else state.detach()
output, state = rnn(chunk, state)
loss = head(output[:, -1]).square().mean()
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(rnn.parameters(), 1.0)
optimizer.step()Carry state values across chunks while cutting the old autograd graph.
What to notice
- Detaching state keeps its values but removes paths into earlier chunks, which bounds graph memory.
- A chunk length of four means a loss cannot assign gradient credit through more than four new transitions in this loop.
YOUR TURN Pause and predict before revealing the answer.
Remove `state.detach()` and run many chunks. What resource grows, and why?
Need a hint?
Each state still points to the operations that created the previous state.
Check your reasoning
The autograd graph—and therefore activation memory—keeps growing across chunks because every new state remains connected to the full prior history.
Lessons 1 in this course.
Connect the chapter to the course’s quantitative spine.
Recurrent state carries information forward; BPTT carries responsibility backward, and truncation decides how far that responsibility can travel. The lstm cell-state update below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.
LSTM cell-state update
| Symbol | Meaning / shape / unit |
|---|---|
c_t | cell state |
f_t | forget gate |
i_t | input gate |
g_t | candidate state |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: c_t, f_t, i_t, g_t.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c11(inputs)
assert is_finite(value)Change one assumption and make the tradeoff visible.
Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.
BPTT context lab
Change truncation length and compare retained context with activation memory.
Assumption: Single recurrent layer; memory normalized to the 256-token configuration.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| 8-token signal | retained | 91.0% |
| 16-token signal | retained | 90.1% |
| 32-token signal | retained | 88.2% |
| 64-token signal | retained | 84.3% |
| 128-token signal | truncated | 5.0% |
Trace the complete operating path.
Carry the chapter’s central idea into the system: Recurrent state carries information forward; BPTT carries responsibility backward, and truncation decides how far that responsibility can travel. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Unroll the recurrence” into a written invariant and a failing test.
- 02
Promote truncated_bptt.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Inspect before clipping” as the release checkpoint: Log gradient norms before applying the clip so exploding gradients remain visible. Detach state only at deliberate sequence or chunk boundaries.
- 04
Serve or materialize behind explicit a declared latency, cost, and operator-capacity budget.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
A bidirectional model and globally normalized features use future events unavailable at authorization. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
Causal stateful risk model
Specify an LSTM with temporal splits, masking, BPTT diagnostics, and replay/online state parity.
- Causal sequence dataset
- Baseline and recurrent comparison
- Gradient/state diagnostics
- Late-event and state policy
Read primary material with a purpose.
Return to the opening failure.
Define causal cutoffs, keyed state, reset/TTL, duplicates, late events, and replay/online parity.
For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a masked sequence model with bptt, recurrent gates, and attention precursors.