research24 min studyLesson 637 in Engineering

Cache the exact reference probability question

Bind precomputed completion scores to model, tokenizer, context, masks, and numerical policy so a fast reference path preserves the intended preference objective.

On this page

What you’ll understand

  • Define the complete identity of a cached reference log probability.
  • Check token alignment, termination, and sequence-sum conventions.
  • Validate cached and live paths with tolerances and explicit invalidation.

A DPO run reuses cached reference scores after its chat template changes. The text still looks similar, but token boundaries and completion masks differ, so the cached values answer another probability question. Precomputing reference log probabilities can save memory and repeated inference when the reference and scoring contract are fixed. It is valid only when the reused score belongs to the exact model, context, token sequence, and reduction that the training loss expects.

Identify the reference computation completely

A cache key should bind reference weight and adapter identities, tokenizer and vocabulary, chat template and special-token rules, exact prompt and response token IDs, truncation policy, attention and completion masks, and the score-reduction convention. Include implementation and numerical settings that affect the accepted reproducibility tolerance. A human-readable model name can move, and two adapters over the same base weights need not define the same reference. Preserve dataset and pair identities so chosen and rejected scores cannot be swapped by an ordering or join error. Content identity and schema checks are more meaningful than trusting a filename called reference.

Reference inference should use the declared evaluation behavior, including dropout and any mutable state. If the reference changes during training, a once-computed score is stale for the new objective unless the algorithm explicitly versions and refreshes it. Pinned TRL 0.23.1 documents precomputation and its reference-model configuration; inspect the chosen variant rather than assume every synchronization option is compatible with fixed cached values. A cache's correctness depends on the actual computation contract, not merely on whether the trainer accepts a column with the expected name.

ℓq(y∣x)=∑t=1Tmtlog⁡q(yt∣x,y<t)\ell_q(y\mid x)=\sum_{t=1}^{T}m_t\log q(y_t\mid x,y_{<t})
For the declared autoregressive tokenization, m_t∈{0, 1} selects the completion targets being scored, and natural logs sum to a sequence score in nats. If all response tokens including the chosen termination convention are selected, this is the corresponding conditional sequence log probability; arbitrary masking can instead define a partial score.↔ Scroll wide equations horizontally.

Verify targets, masks, and reduction together

The model predicts a next token from earlier context, so labels and logits must be aligned after the causal shift. Prompt tokens condition the response even when their likelihood terms are excluded from a completion-only sum. Padding and truncated tokens must not accidentally contribute. Appending EOS or duplicating a special token can change both the probability and which sequence is represented. Transformers 4.56.2 chat-template documentation describes how formatting already supplies required control tokens; tokenizing a rendered template with extra special tokens can duplicate them. Keep the rendered and tokenized artifacts available for small diagnostic examples.

Sequence sums and token means are different reductions. With unequal response lengths, a pair can reverse order after division by length, and substituting a mean into a sequence-ratio derivation changes the objective. Record whether normalization is absent, common across a batch, or specific to each response. Compare the policy and reference paths using the same target mask and reduction. A correct score for another tokenization is still the wrong score for this loss. Zero selected tokens should be an explicit invalid or separately handled case, never an unnoticed divide-by-zero or fabricated zero-length average.

K=(vq,vtok,vtemplate,xids,yids,m,vscore)K=(v_q,v_{\mathrm{tok}},v_{\mathrm{template}},x_{\mathrm{ids}},y_{\mathrm{ids}},m,v_{\mathrm{score}})
This illustrative semantic cache key binds reference q, tokenizer, template, exact context/response token IDs, mask m, and scoring configuration. Additional influencing settings belong in the versioned contract; the tuple alone provides no cryptographic integrity or automatic invalidation.↔ Scroll wide equations horizontally.

Compare live and cached paths before large-scale reuse

Validate a representative set of short, long, truncated, padded, and special-token examples against the live reference path. Check chosen/rejected joins, finite outputs, dtype, and a stated absolute or relative numerical tolerance. Different kernels and reduction orders may create small differences; a tolerance should reflect the supported implementation and the margin sensitivity, not conceal a mask or identity error. Record the reference scoring artifact and validation results with the training run. Invalidate or regenerate when any influencing input changes, and fail explicitly when a required score is missing or incompatible.

The cache lab isolates retention and reuse under a synthetic address stream. For each separate view, Reset, set both capacity C and stride s=4, predict the initial counts, then inspect. Capacity four gives twelve hits and four misses; capacity two gives zero hits and sixteen misses. This exact LRU instrument contains no model versions, token masks, scores, or validation tolerances. It shows a capacity effect only. The actual preference-training cache must establish semantic validity separately, because a stale score can be returned quickly and repeatedly without the cache noticing its changed meaning.

A token mean is not the original sequence sum

For one shared fictional prompt and normalized reference model, completion A is(a,EOS) with token log probabilities(−1,−1), and completion B is(b,c,EOS) with token log probabilities(−1,−0.6,−0.6). The distinct first tokens a and b each have probability exp(−1); remaining probability mass belongs to other tokens and completions. Score every listed completion target and use natural logs.

  1. A’s sequence sum is−2 nats and B’s is−2.2 nats, so A has the higher sequence probability. Their distinct first-token probabilities sum to2 exp(−1)≈0.73576, leaving positive mass for other first tokens; the later conditional probabilities also admit normalized branches.

  2. Their token means are−1 and−2.2/3≈−0.73333 nats/token. The mean-based ordering favors B, reversing the sequence-sum ordering.

  3. A cache produced with one reduction cannot be silently used by a loss requiring the other. Validate token IDs, masks, and reduction identity together before comparing policy/reference margins.

The result

The sums and means answer different questions and reverse the pair ordering in this example. That difference is semantic, not ordinary floating-point noise.

Explore the model

Interactive lab

Interactive lab · cache

Fast repeated lookup does not validate a score’s meaning

For each view: Reset, set both C and s=4, predict, then inspect the initial sixteen requests. C=4 produces 12 hits/4 misses; C=2 produces 0 hits/16 misses. This exact LRU trace has no model, tokenizer, mask, numerical tolerance, or reference score.

Fast repeated lookup does not validate a score’s meaningA fully associative LRU cache starts empty and requests address (i·s) mod 16. Hits move an address to the newest position; misses evict the oldest when full. Playback starts with 16 requests and adds two per second, capped at 4096 explicitly simulated requests. This toy stream is not a processor-cache benchmark. Current readings: Hits / requests: 0 / 16; Hit rate: 0%; Address-stream period: 16 addresses. All parameters are adjustable with the labeled controls below.Fully associative LRU cache after 16 deterministic requests: 0 hits and 16 misses.Most recent 16 requestsaddress = i × 3 mod 160M3M6M9M12M15M2M5M8M11M14M1M4M7M10M13MCurrent cache order · oldest → newest471013Latest address 13 · miss: inserted as newestToy address stream · period 16 · starts empty
Cached addressMiss / evictionMost recent request
Hits / requests
0 / 16
Hit rate
0%
Address-stream period
16 addresses
t = 0 s

A fully associative LRU cache starts empty and requests address (i·s) mod 16. Hits move an address to the newest position; misses evict the oldest when full. Playback starts with 16 requests and adds two per second, capped at 4096 explicitly simulated requests. This toy stream is not a processor-cache benchmark. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forReuse needs both capacity and semantic identity. A cache cannot detect a changed probability question unless the application versions and validates it.

Check your understanding

The reference weights stay fixed, but the tokenizer or completion mask changes. May old cached scores be reused without further validation?

Try it yourself

A response has selected token log probabilities−0.1,−0.2,−0.6. Compute its sequence sum and token mean. If EOS was accidentally omitted from scoring, what should a cache validator check?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Add first, divide only if the declared reduction calls for it, and inspect the termination contract.

Compare with the solution

The sum is−0.9 nats and the mean−0.3 nats/token. Check the intended EOS token, causal target alignment, completion mask, and reduction, then regenerate or validate affected scores under the corrected identity. A convenient old numeric value does not repair the missing target.

Take it with you

  • Cache the exact model/context/token/mask/reduction computation.
  • Sequence sums, token means, and partial masks are different scoring contracts.
  • Validate live and cached paths and invalidate on influencing changes.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.