Practical technical guides / AI engineering

Align Generated Token Scores Before Comparing Model Output Likelihoods

Sequence log-probabilities from generate() are easy to misalign: prompt offsets, pad steps after EOS and processed scores. A worked example with exact numbers.

By Sandeep Belgavi · Published 2026-11-21

Sequence log-probabilities from generate() are easy to misalign: prompt offsets, pad steps after EOS and processed scores. A worked example with exact numbers.

Why this goes wrong quietly

Sequence log-probabilities are a common building block. Teams use them to rank sampled answers, to flag low-confidence replies for review, to compare two prompts on the same reference answer, and to compute perplexity on a held-out set. With Hugging Face Transformers the usual route is to call generate with return_dict_in_generate=True and output_scores=True, then compute_transition_scores. The library returns numbers in the right shape. The mistakes happen in the few lines around that call: which columns of sequences are generated tokens, which positions a finished row actually chose, and what kind of score you summed.

None of these mistakes raises an error. They produce plausible numbers that rank answers in the wrong order, and the error grows with batch size and answer length. This guide works through each one with a small synthetic example whose numbers you can reproduce without a model.

What the API returns

The facts below come from the Transformers generation documentation and the source of generation/utils.py, read on 21 November 2026:

  • sequences contains the prompt followed by the generated tokens. For decoder-only models, the documented example slices generated tokens as outputs.sequences[:, input_length:], where input_length is inputs.input_ids.shape[1], the padded prompt width. For encoder-decoder models it is 1, because the decoder starts from one start token.
  • scores is a tuple with one tensor per generation step, each of shape batch by vocabulary. The documentation calls these processed prediction scores, meaning after logits processors such as temperature, top-k and repetition penalties have been applied. Raw logits are available separately with output_logits=True.
  • compute_transition_scores(sequences, scores, normalize_logits=...) aligns by taking the last len(scores) columns of sequences, gathers the score of each chosen token, and returns a tensor with one value per row and step. Without beam indices it does not mask anything.
  • In greedy search and sampling, once a row has produced its end-of-sequence token, the loop keeps going for the other rows and assigns the pad token to the finished one. The source does this with next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences).

The last two facts combine into the most common bug. A finished row still has a score at every later step, the score of the pad token, and summing the row includes them.

A worked example

The companion example models two rows, each a help-desk reply about a refund at the fictional Belgavi's Book Store, with a six-token vocabulary and five generation steps. The prompts are left-padded to a width of four. Row 0 generates refund issued <eos> and stops at step 2. Row 1 generates five tokens and ends with <eos> at step 4. The raw logits are synthetic numbers chosen so the pad token is moderately likely at the steps after row 0 finished, which is roughly what happens with real models that have seen padding during training.

def finished_mask(generated, eos=1):
    mask = []
    for row in generated:
        live, m = True, []
        for tok in row:
            m.append(live)
            if tok == eos:
                live = False
        mask.append(m)
    return mask

def sequence_logprob(transition_scores, mask):
    return [sum(v for v, keep in zip(row, m) if keep)
            for row, m in zip(transition_scores, mask)]

With log-softmax applied to the raw logits at temperature 1, the measured results are:

  • Row 0 summed over all five steps: -3.5509. Summed over the three steps it chose, up to and including <eos>: -1.7011.
  • Row 1: -2.9797 either way, because it used every step.

Unmasked, row 1 looks more likely than row 0. Masked, row 0 is more likely. Any ranking, threshold or review queue built on the unmasked number is ranking the padding.

The second misalignment: slicing by unpadded length

With left padding, every row's generated tokens start at the same column, the padded prompt width. A tempting mistake is to slice each row by its own prompt length without padding, perhaps because that length is already stored with the request. In the example, row 0's prompt has three real tokens and one pad, so slicing at 3 returns six positions instead of five. Its first "generated" token is then the last prompt token, and every score is paired with the token after the one it belongs to. The example's check reports six and five positions where five and five were expected.

The safe rule is to never compute generated positions yourself. Use the alignment that compute_transition_scores uses, the last len(scores) columns, and assert that the count matches before summing anything.

The third mistake: comparing incomparable scores

Processed scores depend on the generation configuration. In the example, row 1's masked log-probability is -2.9797 at temperature 1 and -1.6104 at temperature 0.7, with the same tokens and the same raw logits. Lower temperature sharpens the distribution, so the chosen tokens look more probable. That is fine if you want to know how likely the sampler was to produce this answer. It is wrong if you want the model's likelihood of the answer, which is what most comparisons assume.

The tokenizer matters too. Two models with different tokenizers split the same answer into different numbers of tokens, so per-token averages and sums are not on the same scale. Even with one tokenizer, a sum over tokens favours short answers, because every token adds a negative number. Decide whether you compare sums, per-token means or a length-normalised score, and use the same choice everywhere.

The example's guard refuses a comparison when the tokenizer fingerprint, the score kind or the temperature differ, or when the number of scores does not match the number of generated steps:

def check_comparable(a, b):
    problems = []
    for key in ('tokenizer_sha256', 'score_kind', 'temperature'):
        if a[key] != b[key]:
            problems.append(f'{key} differs: {a[key]} vs {b[key]}')
    if a['steps'] != len(a['scores']) or b['steps'] != len(b['scores']):
        problems.append('scores length does not match generated steps')
    return problems

A procedure that holds up

  1. Record the model identifier, tokenizer fingerprint, generation configuration and library version with every score you store.
  2. Decide which score you mean. For model likelihood, request raw logits, or score the finished text in a separate forward pass with the model in evaluation mode, which also removes sampling settings from the question.
  3. Take generated positions from the score alignment, not from your own prompt lengths, and assert the shapes.
  4. Mask every position after a row's first end-of-sequence token, and decide whether the end token itself counts. Counting it is usual for whole-answer likelihood, because stopping is a choice the model made.
  5. Compare only within one recorded configuration, and choose sum, mean or a length penalty explicitly.

Scoring in a separate forward pass deserves a note. It is often simpler and less fragile than reusing generation scores: concatenate prompt and answer, run the model once, take log-softmax at each answer position, and gather the answer tokens. It costs one extra forward pass per answer, and it gives the same number regardless of how the answer was produced.

Where beam search differs

With beam search, pass beam_indices from the generation output. In that case compute_transition_scores uses them to pick the right beam at each step and does mask steps after a beam finished, setting their scores to zero. The documented example shows that the summed transition scores, divided by output length raised to the length penalty, reconstruct sequences_scores. The companion example models only greedy-style rows. Check the version you have installed before assuming either behaviour, because these internals have changed across releases.

Failure modes to test

  • A batch where rows finish at different steps. Assert that each row's sum equals the sum over its own positions only.
  • A batch with left padding and prompts of different lengths. Assert that generated positions start at the padded width for every row.
  • The same answers scored at two temperatures. Assert that your comparison code refuses or normalises them rather than comparing.
  • An answer that hits the maximum number of new tokens without an end token. Decide whether it is comparable at all, since the model never chose to stop.
  • Two models with different tokenizers. Assert that per-token comparisons are refused, and that any comparison is made on a text-level measure.

When you do not need any of this

If you only need to know whether an answer is acceptable, a likelihood is a weak signal anyway. A model can be confident and wrong. Task-specific checks, such as validating that a refund amount in the answer matches the order record, are more useful than a probability threshold. Use sequence likelihoods for what they measure well: comparing candidate texts under one model and one configuration, and tracking drift in that model over time.

Verification checklist

  • Shapes asserted: number of generated positions equals the number of score steps for every row.
  • Post-end positions masked, with a test that changes their scores and expects no change in the result.
  • Score kind, temperature and tokenizer recorded and checked before any comparison.
  • A known-answer test reproduces the example's -1.7011 and -2.9797 from the synthetic tables, so a refactor that breaks the mask is caught.

Run the example yourself

The synthetic score tables, the mask, the misaligned slice and the comparability guard, with six tests. No model or torch is needed. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources read 21 November 2026. Original explanation, measurements and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.

Related on this site: