Many-to-one and many-to-many training
Choose the output pattern from the target, then make padding mathematically invisible to both state selection and loss.
Long support conversations must be routed while preserving temporal context.
This chapter moves from declare target alignment to normalize by real targets. 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.
Sum loss only over valid positions and divide by the number of valid targets. This keeps batch composition from changing the effective objective.
Verify the behavior illustrated in last_valid_state.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.
The same recurrent encoder can answer once for a whole sequence or answer at every step. The hard part is aligning each answer with the right evidence and mask.
Many-to-one tasks compress a history into one decision, such as classifying a complete support conversation. Many-to-many tasks attach targets to several positions, such as labeling every event or predicting the next token. The output shape follows the supervision: one target per sequence versus one target per valid time step.
Variable lengths introduce padding, which is storage rather than data. A many-to-one model should select the last valid state, not the last padded slot. A many-to-many loss should exclude padded targets from its reduction. Otherwise short sequences contribute fabricated examples and can dominate a batch.
- gradient clipping
- LSTM gates
- teacher forcing
- state TTL
Follow the reasoning before touching the code.
- 01
Declare target alignment
For every output position, state exactly which input prefix it may use and which target it predicts. This catches one-step shifts and future access.
- 02
Carry lengths or masks
Preserve the true sequence length through collation. Use it for state selection, attention masking, and loss reduction rather than inferring validity from feature values.
- 03
Normalize by real targets
Sum loss only over valid positions and divide by the number of valid targets. This keeps batch composition from changing the effective objective.
import torch
states = torch.tensor([
[[1., 0.], [2., 0.], [3., 0.]],
[[4., 1.], [5., 1.], [0., 0.]],
])
lengths = torch.tensor([3, 2])
row = torch.arange(states.size(0))
last_valid = states[row, lengths - 1]
assert torch.equal(last_valid, torch.tensor([[3., 0.], [5., 1.]]))
logits = torch.nn.Linear(2, 1)(last_valid)
print(logits.shape)Gather the final real state for a padded many-to-one batch.
What to notice
- Indexing `states[:, -1]` would return padding for the second sequence.
- The gathered tensor has one vector per sequence, so the classifier produces a many-to-one output of shape `[batch, 1]`.
YOUR TURN Pause and predict before revealing the answer.
For token labeling, what mask and denominator should replace the final-state gather?
Need a hint?
Each position before its sequence length is a real supervised example.
Check your reasoning
Use a `[batch, time]` boolean mask such as `position < length`, multiply or index the per-token losses by it, then divide their sum by `mask.sum()`.
Lessons 1, 2, 3 in this course.
Connect the chapter to the course’s quantitative spine.
Choose the output pattern from the target, then make padding mathematically invisible to both state selection and loss. 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: Choose the output pattern from the target, then make padding mathematically invisible to both state selection and loss. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Declare target alignment” into a written invariant and a failing test.
- 02
Promote last_valid_state.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Normalize by real targets” as the release checkpoint: Sum loss only over valid positions and divide by the number of valid targets. This keeps batch composition from changing the effective objective.
- 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.