Top-2 Logit Analysis for Accuracy Across Hardware

When a model selects an unexpected token, the gap between the top two candidates at that step is a useful first measurement. A small gap indicates that the model is uncertain, and sampling at that step is close to a coin flip. A large gap indicates that the model is confident. Plotting the gap across all generation steps shows which steps are stable and which are sensitive to small numeric changes.

Step 1: dump logits offline

The TensorRT-LLM run.py script can write both context and generation logits to disk.

#!/bin/bash
# dump_logits.sh
# Generates a npy array on disk with the generated logits

script="run.py"
engine_dir="r8_trt_logits/8-gpu/"
input_csv="tokenizer_input.csv"

mpirun -np 8 --allow-run-as-root python ${script} \
  --input_file ${input_csv} \
  --output_csv outputs.csv \
  --output_logits_npy logits.npy \
  --top_p 1.0 \
  --temperature 1.0 \
  --max_output_len 100 \
  --engine_dir "${engine_dir}"

The flags have the following roles:

  • --input_file reads the tokenized input prompts from a CSV file.
  • --output_csv writes the generated text.
  • --output_logits_npy writes the per-step logits as a .npy file.
  • --top_p 1.0 --temperature 1.0 keeps the full distribution with no truncation.
  • --max_output_len 100 generates 100 output tokens.
  • mpirun -np 8 runs the engine across 8 GPUs with tensor parallelism.

The engine must be built with --gather_generation_logits, otherwise it does not return generation logits.

The resulting logits.npy has shape (batch_size, beam_size, token_gen_steps, vocab_size). For greedy decoding with beam_size=1 and batch_size=1, a 100-token generation produces a tensor of shape (1, 1, 100, vocab_size).

Step 2: analyze the deltas

The following script loads the dump and plots the gap:

# analyze_logits.py
import numpy as np
import torch
import pandas as pd
import matplotlib.pyplot as plt
import sys


def diff2(logits_at_step, step=-1):
    """Difference between the top-2 logits at a single step."""
    top2 = torch.topk(logits_at_step, 2).values
    print(f"step {step}: top2={top2}")
    return abs(top2[0].item() - top2[1].item())


def plot(values):
    df = pd.Series(values)
    df.plot(
        ylabel="diff of top two probabilities",
        xlabel="token generation steps",
        legend=False,
    )
    plt.hlines(y=0.0, xmin=0, xmax=len(values),
               colors='red', linestyles='-', lw=1,
               label='no diff in probs')


def main():
    gen_logits = torch.from_numpy(np.load(sys.argv[1]))
    batch_sz, beam_sz, token_gen_steps, vocab_size = gen_logits.shape
    print(f"logits shape: {gen_logits.shape}")

    logits_diff = []
    probs_diff = []
    for step in range(token_gen_steps):
        logits_at_step = gen_logits[0][0][step]
        logits_diff.append(diff2(logits_at_step, step))

        probs_at_step = torch.softmax(logits_at_step, dim=-1)
        probs_diff.append(diff2(probs_at_step, step))

        # When probabilities are exactly tied (which shouldn't happen in fp32):
        if probs_diff and probs_diff[-1] == 0:
            past_ids = torch.argmax(gen_logits[0][0], dim=1)[:step]
            print(f"  TIE at step {step}; previous tokens: {past_ids}")

    plot(probs_diff)
    plt.legend(loc="upper right")
    plt.show()


if __name__ == "__main__":
    main()

The script runs as python analyze_logits.py logits.npy.

It computes two values per step:

  • logits_diff is the gap between the top two raw logits. It measures the model’s confidence in raw units.
  • probs_diff is the gap between the top two probabilities after softmax. It measures how close the step is to a coin flip.

Reading the plot

Most plots contain three kinds of steps. The thresholds below are working heuristics, not fixed constants.

High-confidence steps have a probs_diff above 0.3. Greedy decoding and sampling produce the same token. On simple prompts, a well-trained model spends most of its steps in this range.

Borderline steps have a probs_diff between 0.05 and 0.3. The model prefers one token, but sampling can still select the second. Temperature affects the output at these steps.

Coin-flip steps have a probs_diff below 0.05. The top two tokens are nearly tied, so a different hardware path or a small numeric difference can change the sampled token. Divergence between CPU and Neuron, or between BF16 and FP32, tends to occur at these steps.

The shape of the whole curve also characterizes the model:

  • When nearly every step is high-confidence, the prompts lie well within what the model has learned, and its outputs repeat across runs.
  • When coin-flip steps are frequent, sampling produces varied outputs from run to run.
  • A bimodal curve indicates confident early steps, constrained by the prefix, followed by open-ended later steps.

Cross-hardware validation

When a Neuron model is validated against a GPU model, this analysis identifies where divergence is expected. The relevant quantity is the logit gap, because the numeric noise enters through the logits. Near a logit value of 20, one BF16 ULP is 0.125. When the top-two logit gap is within a few ULPs, the two hardware paths can rank the top two tokens differently, and neither result is incorrect. For two nearly tied tokens, a logit gap of 0.125 corresponds to a probability gap of at most about 0.06, so such steps already fall in the coin-flip range.

The validation procedure is as follows:

  1. Run the model on GPU as the reference and dump the logits.
  2. Run the model on Neuron as the target and dump the logits.
  3. For each step, read logits_diff from the reference run.
  4. If logits_diff is well above the expected logit error, for example several BF16 ULPs at the logit’s magnitude, the tokens are expected to match.
  5. If logits_diff is within that error, a token mismatch is acceptable.

Consider a run that diverges at step 47. If step 47 is a coin-flip step, the divergence is expected. If step 47 is a high-confidence step, the divergence indicates a real bug. The script distinguishes between the two cases. The compare_logits utility complements this check by measuring how the two logit tensors differ at a given step.

Probabilities or logits

The analysis can use either the raw logits or the probabilities after softmax.

The logits diff is easier to compare against the resolution of the data type. Near a logit value of 20, one BF16 ULP is 0.125, so a gap of 1.2 is well above the noise.

The probabilities diff maps directly to sampling behavior. If the top two tokens have probabilities 0.6 and 0.4, the diff is 0.2, and sampling at temperature 1.0 selects the second token 40% of the time.

Both values are inexpensive to compute, so the script records both.

Extending the analysis

With probs_diff available for every step, several further analyses require only a few lines of code.

A histogram of probs_diff across all steps summarizes the model’s confidence on a set of prompts. When most of the mass lies near zero, the output depends heavily on the sampling settings.

Per-step entropy, −Σ p log p over the full distribution, captures more information than the top-two gap.

Top-K agreement between two models compares the top-K token sets from two models at each step. It provides a finer measure of agreement than argmax alone.

Confidence after specific tokens tests whether the model becomes less confident after it produces certain tokens. This analysis can expose systematic sampling instability.

Practical notes

Memory. A 100-step generation with a 128k vocabulary in FP32 occupies about 50 MB per request. Storing the dump as float16 halves this, provided the analysis tolerates the lower precision.

MPI and multiple GPUs. In a tensor-parallel model, only rank 0 holds the gathered logits. The dump should be written from rank 0 only, otherwise each rank writes a partial copy.

Beam search. With beam_size > 1, the dump contains one distribution per beam. The analysis still applies, but each beam has its own confidence curve.

Sampling parameters. The dump contains the logits before top-p, top-k and temperature are applied. The analysis can therefore be repeated with different sampling settings without running the model again.


If you found this useful, please cite this post using

Senthilkumar Gopal. (Apr 2024). Top-2 Logit Analysis for Accuracy Across Hardware. sengopal.me. https://sengopal.me/posts/top-2-logit-analysis-for-accuracy-across-hardware

or

@article{gopal2024top2logitanalysis,
  title   = {Top-2 Logit Analysis for Accuracy Across Hardware},
  author  = {Senthilkumar Gopal},
  journal = {sengopal.me},
  year    = {2024},
  month   = {Apr},
  url     = {https://sengopal.me/posts/top-2-logit-analysis-for-accuracy-across-hardware}
}