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 KK latent values trained under teacher forcing. For one example (x,y)(x, y) with y=(y1,…,yT)y = (y_1, \dots, y_{T}), 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 ϕ\phi; the baseline simply omits the angle.lzangle.rzkangle.l/zangle.rangle.l z angle.r z_{k} angle.l / z angle.r section from the input.

The current reconstruction loss averages uniformly over all supervised tokens S\mathcal{S} with ∣S∣=T|\mathcal{S}| = T:

R(z)=1/T∑t∈Sℓt(z).R(z) = 1 / T \sum_{t \in \mathcal{S}} \ell_{t} (z).

Two-regime structure under teacher forcing

This is simple interpretation is approximate and applies only to

TODO: restructure this note to make it more concise and more clear; this simple "strategy revealed by t0t_0 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 (t≤t0t \leq t_0). The teacher-forced history y_{< t} does not yet determine the strategy. The base model has non-trivial uncertainty: bt>0b_{t} > 0. The z-conditioned model can reduce this uncertainty when zz matches the strategy used in yy, so ℓt(z)\ell_{t} (z) varies across latent values.

  • Strategy-determined suffix (t>t0t > t_0). The partial solution y_{< t} reveals the strategy. Continuation is nearly deterministic: bt≈0b_{t} \approx 0 and ℓt(z)≈0\ell_{t} (z) \approx 0 for all zz, because the teacher-forced prefix renders zz redundant.

The boundary t0t_0 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:

R(z)=1/T∑t=1t0ℓt(z)+1/T∑t=t0+1Tℓt(z)⏟≈0.R(z) = 1 / T \sum_{t=1}^{t_0} \ell_{t} (z) + \underbrace{1 / T \sum_{t=t_0 + 1}^{T} \ell_{t} (z)}_{\approx 0}.

The variation of R(z)R(z) across latent values:

R(z)−R(z′)=1/T∑t=1t0[ℓt(z)−ℓt(z′)]=t0/T⋅δzz′,R(z) - R(z') = 1 / T \sum_{t=1}^{t_0} [\ell_{t} (z) - \ell_{t} (z')] = t_0 / T \cdot \delta_{z z'},

where δzz′=1/t0∑t≤t0[ℓt(z)−ℓt(z′)]\delta_{z z'} = 1 / t_0 \sum_{t \leq t_0} [\ell_{t} (z) - \ell_{t} (z')] is the mean per-informative-token difference. The factor t0/Tt_0 / T is the dilution: the T−t0T - t_0 easy tokens contribute zero to the numerator but inflate the denominator.

Gradient Analysis

Posterior parameters ξ\xi

The reconstruction gradient on the posterior parameters ξ\xi of qξ(z∣x,y)q_\xi (z | x, y) is:

(∂Lrecon)/(∂ξ)=∑z(∂qξ)/(∂ξ)⋅R(z).(\partial \mathcal{L}_\mathrm{recon}) / (\partial \xi) = \sum_{z} (\partial q_\xi) / (\partial \xi) \cdot R(z).

Because ∑z∂qξ/∂ξ=0\sum_{z} \partial q_\xi / \partial \xi = 0 (the probabilities sum to one), any component of R(z)R(z) that is constant across zz cancels. The effective gradient magnitude is proportional to the variation:

∥∂Lrecon∂ξ∥∼max⁡z≠z′∣R(z)−R(z′)∣=t0T∣δ∣.\left\lVert \frac{\partial \mathcal{L}_\mathrm{recon}}{\partial \xi} \right\rVert \sim \max_{z \neq z'} |R(z) - R(z')| = \frac{t_0}{T} |\delta|.

The KL gradient on ξ\xi is O(β)O(\beta), independent of TT. The reconstruction signal dominates when:

t0/T∣δ∣>β⋅Ct_0 / T |\delta| > \beta \cdot C

for a constant CC set by the KL curvature. When t_0 / T << 1 and β=O(1)\beta = O(1), 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:

πt=sg⁡(bt)∑s∈Ssg⁡(bs)+ϵ\pi_t = \frac{\operatorname{sg}(b_t)}{\sum_{s \in \mathcal{S}} \operatorname{sg}(b_s) + \epsilon}

for supervised positions t∈St \in \mathcal{S}.

Equivalently, replace the uniform token average with a weighted average:

Rπ(z)=∑t∈Sπt ℓt(z).R^\pi (z) = \sum_{t \in \mathcal{S}} \pi_t \, \ell_t(z).

This is algebraically equivalent to the implementation form

Rw(z)=∑t∈Swt⋅ℓt(z)∑t∈Swt+ϵ,R^w (z) = \frac{\sum_{t \in \mathcal{S}} w_{t} \cdot \ell_{t} (z)}{\sum_{t \in \mathcal{S}} w_{t} + \epsilon},

with wt=sg⁡(bt)w_t = \operatorname{sg}(b_t).

The full weighted reconstruction loss under the posterior:

Lreconπ=Ez∼qξ(z∣x,y)[Rπ(z)].\mathcal{L}_\mathrm{recon}^\pi = \mathbb{E}_{z \sim q_\xi (z | x, y)}[R^\pi (z)].

The total objective:

J=Lreconπ+β⋅KL(qξ(z∣x,y),pϕ(z∣x))+auxiliary terms.\mathcal{J} = \mathcal{L}_\mathrm{recon}^\pi + \beta \cdot \mathrm{KL}(q_\xi (z | x, y), p_\phi (z | x)) + \mathrm{auxiliary\ terms}.

Intuition

The latent variable should prioritize encoding information that helps predict tokens that remain uncertain under the z-free model p(y∣x)p(y \mid x); i.e., branching tokens that are not already determined by xx and the teacher-forced prefix y<ty_{<t}. 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 wt≈0w_{t} \approx 0 for t>t0t > t_0, the weighted reconstruction concentrates on the strategy-sensitive prefix:

Rw(z)≈(∑t=1t0bt⋅ℓt(z))/(∑t=1t0bt).R^w (z) \approx (\sum_{t=1}^{t_0} b_{t} \cdot \ell_{t} (z)) / (\sum_{t=1}^{t_0} b_{t}).

The variation across latent values:

Rw(z)−Rw(z′)=(∑t=1t0bt⋅[ℓt(z)−ℓt(z′)])/(∑t=1t0bt)=O(∣δ∣),R^w (z) - R^w (z') = (\sum_{t=1}^{t_0} b_{t} \cdot [\ell_{t} (z) - \ell_{t} (z')]) / (\sum_{t=1}^{t_0} b_{t}) = O(|\delta|),

with no t0/Tt_0 / T dilution factor. The posterior gradient is amplified by T/t0T / t_0 relative to the uniform-average loss. The z-parameter gradient is similarly amplified: the denominator is ∑t≤t0bt\sum_{t \leq t_0} b_{t} instead of TT, and late-token noise gradients are suppressed.

The reconstruction gradient on ξ\xi now dominates the KL when:

∣δ∣>β⋅C,|\delta| > \beta \cdot C,

which is T/t0T / t_0 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 ℓt(z)\ell_{t} (z) across zz at early positions. Under the standard loss, this signal is diluted by t0/Tt_0 / T and may be too weak to overcome the KL pressure. Under the weighted loss, the signal is preserved at O(∣δ∣)O(|\delta|), 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 xx. The base model (initialized from the entangled checkpoint) should have bt>0b_{t} > 0 at these positions.

  • Self-adapting behavior. Early in training, the base model may be uncertain at many positions, making wtw_{t} 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 ℓt(z)=ℓt(z′)\ell_{t} (z) = \ell_{t} (z') for all z,z′z, z' 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 ∂ℓt/∂ψ\partial \ell_{t} / \partial \psi (for example, z-conditioned layer normalization or a multi-token z-prefix).

  • Degenerate weights. If bt≈0b_{t} \approx 0 for all tt (including early tokens), the denominator sumwt≈0sum w_{t} \approx 0 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 btb_{t}

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 btb_{t} is computed under teacher forcing at supervised positions and detached before use as weights.

Two implementation policies are possible:

  • Frozen policy. Compute btb_{t} 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 btb_{t} 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.py
    • path:experiments/synthetic_sequences/disentangled/evaluation_runtime.py
  • CLI flag: --token-weighted-reconstruction-weight in path:experiments/synthetic_sequences/disentangled/config.py

Relation to neighboring variants

Among the current reconstruction variants, token weighting is the one most directly aligned with the intuition that zz 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 KK latent values, the training loop already performs K+1K + 1 forward passes per batch (KK latent-conditioned and 11 posterior). The baseline adds one more, increasing cost by 1/(K+1)1 / (K + 1).

Built with LogoFlowershow