Token-Level Surprisal-Share Weighting
Token-Level Surprisal-Share Weighting
Back to reconstruction weighting and normalization
Implementation note: Current implementation: token-level surprisal-share weighting
This note identifies a teacher-forcing dilution failure mode in the standard reconstruction objective and derives a token-level weighting scheme that reallocates reconstruction pressure according to each token's share of the residual code length under the z-free base model.
The main derivation is written in the discrete CVAE setting, because that is where the exact latent expectation is easiest to analyze. The same weighting principle is also used in the current continuous implementation.
Motivation: Teacher-Forcing Dilution
Setup and notation
Consider a discrete CVAE with latent values trained under teacher forcing. For one example with , define:
- per-token z-conditioned NLL: \ell_{t} (z) = -\log p_\phi (y_{t} | x, z, y_{< t}),
- per-token z-free base-model surprisal: b_{t} = -\log p_\phi (y_{t} | x, y_{< t}).
Both use the same backbone ; the baseline simply omits the section from the input.
The current reconstruction loss averages uniformly over all supervised tokens with :
Two-regime structure under teacher forcing
TODO: restructure this note to make it more concise and more clear; this simple "strategy revealed by interpretation should be separated into a brief callout and it should be made clear that this is a simple model that applies only to simple settings."
Under teacher forcing, the solution sequence has two regimes:
-
Strategy-sensitive prefix (). The teacher-forced history y_{< t} does not yet determine the strategy. The base model has non-trivial uncertainty: . The z-conditioned model can reduce this uncertainty when matches the strategy used in , so varies across latent values.
-
Strategy-determined suffix (). The partial solution y_{< t} reveals the strategy. Continuation is nearly deterministic: and for all , because the teacher-forced prefix renders redundant.
The boundary is not a sharp cutoff but a useful abstraction. For synthetic-sequence tasks, it corresponds roughly to the first few solution tokens where the procedural strategy is manifested.
The dilution
Under the two-regime model, the token-averaged reconstruction becomes:
The variation of across latent values:
where is the mean per-informative-token difference. The factor is the dilution: the easy tokens contribute zero to the numerator but inflate the denominator.
Gradient Analysis
Posterior parameters
The reconstruction gradient on the posterior parameters of is:
Because (the probabilities sum to one), any component of that is constant across cancels. The effective gradient magnitude is proportional to the variation:
The KL gradient on is , independent of . The reconstruction signal dominates when:
for a constant set by the KL curvature. When t_0 / T << 1 and , the KL wins and the posterior collapses to the prior.
Token-Weighted Reconstruction Loss
Definition
Define per-token surprisal-share weights from the stop-gradiented z-free baseline NLL:
for supervised positions .
Equivalently, replace the uniform token average with a weighted average:
This is algebraically equivalent to the implementation form
with .
The full weighted reconstruction loss under the posterior:
The total objective:
Intuition
The latent variable should prioritize encoding information that helps predict tokens that remain uncertain under the z-free model ; i.e., branching tokens that are not already determined by and the teacher-forced prefix . The current weighting scheme operationalizes this by allocating reconstruction pressure in proportion to each token's share of the residual base-model surprisal inside the example.
Gradient improvement
Since for , the weighted reconstruction concentrates on the strategy-sensitive prefix:
The variation across latent values:
with no dilution factor. The posterior gradient is amplified by relative to the uniform-average loss. The z-parameter gradient is similarly amplified: the denominator is instead of , and late-token noise gradients are suppressed.
The reconstruction gradient on now dominates the KL when:
which is times easier to satisfy than the uniform-average condition.
Conditions For Effectiveness
When it works
-
Nonzero initial z-sensitivity. At initialization, z-token embeddings are random, producing small random differences in across at early positions. Under the standard loss, this signal is diluted by and may be too weak to overcome the KL pressure. Under the weighted loss, the signal is preserved at , potentially sufficient for the optimizer to bootstrap z-usage.
-
Non-trivial base-model uncertainty at early positions. The synthetic- sequence tasks have genuine strategy ambiguity: different strategies produce different early solution tokens for the same input . The base model (initialized from the entangled checkpoint) should have at these positions.
-
Self-adapting behavior. Early in training, the base model may be uncertain at many positions, making roughly uniform. As the backbone improves and late tokens become easy, the weights concentrate on the strategy-sensitive prefix. The reweighting strengthens exactly when dilution becomes the binding constraint.
When it may not suffice
-
Complete z-insensitivity. If the decoder produces for all at every position (including early tokens), the weighted variation is still zero. Reweighting amplifies existing z-variation but cannot create it from nothing. This limitation can be addressed by pairing the weighted loss with an architectural change that ensures nonzero (for example, z-conditioned layer normalization or a multi-token z-prefix).
-
Degenerate weights. If for all (including early tokens), the denominator and the loss degenerates. This would indicate that the task has no token-level strategy ambiguity, in which case disentanglement via reconstruction alone may be impossible.
-
Single-token z-conditioning. The z-token is a single token in the input sequence. Even with correct gradient scaling, its influence on early-position predictions is mediated by attention and may remain small. Reweighting is necessary for correct gradient balance but may not be sufficient to overcome an architectural bottleneck.
Implementation
Computing the baseline
The z-free baseline requires one additional forward pass per batch through the z-free input template:
<bos> <x> {x} </x> <y> {y} </y> <eos>
This is the original entangled-model format. The per-token NLL is computed under teacher forcing at supervised positions and detached before use as weights.
Two implementation policies are possible:
-
Frozen policy. Compute from a frozen reference model initialized from the entangled checkpoint. This keeps the weighting signal stable while the disentangled model is trained.
-
Dynamic policy. Compute from the current training backbone at each step (still stop-gradiented before use), so weights evolve with the model.
Current implementation status in this repository: the frozen policy is implemented; the dynamic policy is intentionally deferred.
Current status in this repository
This token-level weighting mechanism is currently implemented.
- Core weighting helper:
path:core/disentanglement/token_weighting.py - Weighted loss helpers:
path:core/disentanglement/losses.py - Discrete CVAE integration:
path:core/disentanglement/shared_discrete_cvae.py - Continuous CVAE integration:
path:core/disentanglement/continuous_cvae.py - Trainer/runtime wiring:
path:experiments/synthetic_sequences/disentangled/train_step.pypath:experiments/synthetic_sequences/disentangled/evaluation_runtime.py
- CLI flag:
--token-weighted-reconstruction-weightinpath:experiments/synthetic_sequences/disentangled/config.py
Relation to neighboring variants
- Distribution-Level Z-Free-Relative Reconstruction Rescaling Restores reconstruction scale globally, but does not change which token positions matter more.
- Example-level inverse-surprisal weighting Reweights whole examples by inverse base-model surprisal, rather than emphasizing high-surprisal positions inside each example.
- Inverse-surprisal token-weighted reconstruction ablation A low-surprisal token-level ablation that reverses the within-example weighting direction to test whether high-surprisal branching-token pressure is the important ingredient.
Among the current reconstruction variants, token weighting is the one most directly aligned with the intuition that should help where the z-free model still has room to improve.
Modifying masked_token_nll_per_example
The current implementation computes:
denom = active.sum(dim=1).clamp_min(1.0)
return (token_loss * active).sum(dim=1) / denom
The weighted variant replaces the uniform active mask with active * weights, where weights is the detached per-token baseline NLL:
weighted_active = active * weights.detach()
denom = weighted_active.sum(dim=1).clamp_min(eps)
return (token_loss * weighted_active).sum(dim=1) / denom
Cost
One additional forward pass per batch (z-free baseline). For the exact discrete CVAE with latent values, the training loop already performs forward passes per batch ( latent-conditioned and posterior). The baseline adds one more, increasing cost by .