Score next tokens with contrastive decoding

Why it matters Contrastive decoding and related expert-minus-amateur tricks improve open-ended generation quality without retraining.

Contrastive decoding prefers tokens a large expert model likes much more than a small amateur model does, which removes generic, repetitive choices. A plausibility filter keeps it from picking tokens the expert itself finds unlikely.

Write contrastive_scores(expert_logits, amateur_logits, alpha). Both inputs are length-V logits. Let p_e and p_a be their softmax probabilities. Plausible tokens are those with p_e >= alpha * max(p_e). For plausible tokens, score = log p_e - log p_a; all other tokens get -inf. Return (scores, best) where best is the index of the highest score (lowest index on ties).

Signaturedef contrastive_scores(expert_logits, amateur_logits, alpha)

Example

contrastive_scores([2, 1, 0], [2, -1, 0], 0.5) keeps only token 0, so scores is about [-0.2378, -inf, -inf] and best is 0.

Understand the idea

Large and small language models share the same boring habits (repeating phrases, generic words), but only the large model has the extra knowledge. Contrastive decoding subtracts the small model's opinion to cancel the shared habits, like removing background noise by subtracting a recording of the empty room.

Example: expert probabilities [0.665, 0.245, 0.090], amateur [0.844, 0.042, 0.114]. Log ratios: token 0 = ln(0.665 / 0.844) = -0.238, token 1 = ln(0.245 / 0.042) = 1.762, token 2 = -0.238. Token 1 wins with a loose filter. With alpha 0.5, only tokens with p_e >= 0.33 survive, which leaves token 0.

Rule: plausible = p_e >= alpha * max p_e; score = log p_e - log p_a on plausible tokens, -inf elsewhere.

The filter is essential: without it, a token the expert gives 0.1% can win just because the amateur gives it 0.0001%. Related ideas compare a model with an earlier layer of itself instead of a separate small model.

Shapes and data flow

expert_logits, amateur_logits (V,) -> log-probs (V,) -> mask (V,) -> scores (V,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplecontrastive_scores([2.0, 1.0, 0.0], [2.0, -1.0, 0.0], 0.5)
  • Sample 2: loose filtercontrastive_scores([2.0, 1.0, 0.0], [2.0, -1.0, 0.0], 0.1)
  • Test 3: expert agreescontrastive_scores([0.0, 3.0, 1.0, -2.0], [0.0, 1.0, 1.0, -5.0], 0.1)