FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Token Probability Visualization

A token probability view maps logits to tokenizer-aligned next-token probabilities and shows ranking and omitted mass without claiming factual certainty.

Freshness: current•12 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

A token probability visualizer presents the model’s next-token distribution at each generation step, linked to the exact token IDs and tokenizer decoding used by the runtime. It applies a numerically stable softmax to logits, preserves the model’s original probabilities, and labels omitted mass so viewers can distinguish ranking from a complete distribution.

Learning outcomes

  • Convert a vector of next-token logits into a normalized distribution without numerical overflow.
  • Explain how tokenizer boundaries, sampling settings, and top-k truncation affect what a visualizer can claim.
  • Present probabilities and calibration evidence in a way that does not confuse model likelihood with truth.

Theory

At generation step tt, the language model produces a logit ziz_i for each candidate token ii in a vocabulary of size VV. A logit is an unnormalized score, not a probability. Softmax maps all scores for that step into nonnegative values whose sum is one. With temperature T>0T>0, the distribution is:

pi(t)=exp⁡(zi/T)∑j=1Vexp⁡(zj/T)p_i(t)=\frac{\exp(z_i/T)}{\sum_{j=1}^{V}\exp(z_j/T)}

The scores and temperature are dimensionless, so each pip_i is also dimensionless. Lowering TT sharpens the ranking and raising it flattens the distribution; neither operation teaches the model new facts. For numerical stability, subtract the maximum scaled logit from every exponent. This leaves the normalized probabilities unchanged while preventing exponentials of large positive values from overflowing.

For example, logits [2,1,0][2,1,0] at T=1T=1 yield probabilities of approximately [0.665,0.245,0.090][0.665,0.245,0.090]. A top-two panel should show the first two values and say that their combined mass is 0.910, with 0.090 omitted. Renormalizing only the displayed candidates would turn them into roughly 0.731 and 0.269, falsely suggesting that no other token was possible. When an inference API returns only a truncated candidate list, a client cannot infer omitted mass unless the API supplies it or provides the full distribution.

Probability bars need a stable identity as generation streams. Associate each result with a request, sequence, and step index, then map token IDs through the tokenizer version used by that model. A token may be a word fragment, punctuation, whitespace, or bytes that decode only with its neighbors. Show invisible boundaries explicitly when useful, and avoid presenting token fragments as if they were necessarily complete words. If a provider reports post-temperature or post-penalty scores, label that transformation; probabilities computed from raw logits may not match the sampler’s actual choice distribution.

A high probability means “the model assigned this token more mass than its alternatives at this step,” not “the statement is correct.” Calibration is a separate empirical property. For a held-out set, one common top-choice expected calibration error is:

ECE⁡=∑b=1B∣Sb∣N∣acc⁡(Sb)−conf⁡(Sb)∣\operatorname{ECE}=\sum_{b=1}^{B}\frac{|S_b|}{N}\left|\operatorname{acc}(S_b)-\operatorname{conf}(S_b)\right|

Here, SbS_b is a confidence bin containing ∣Sb∣|S_b| top-token predictions, NN is the number of evaluated predictions, accuracy is the fraction whose top token matches the observed next token, and confidence is their mean top-token probability. ECE summarizes mismatch over a dataset; it does not certify an individual completion. Calibration can also vary by domain, prompt style, and decoding configuration, so the evaluation set and binning method belong beside the chart.

Capture logits for one sequence step
Apply the runtime temperature and stable softmax
Rank token IDs while retaining original mass
Decode token pieces with tokenizer version
Render probabilities and coverage accessibly
Conceptual teaching model synthesized from:transformer-paper,hf-generation,guo-calibration-2017

Trade-offs

Computing softmax requires visiting every vocabulary score, an O(V)O(V) pass. Sorting all candidates is O(Vlog⁡V)O(V\log V); a bounded heap can select top kk in O(Vlog⁡k)O(V\log k) time while still summing all weights for exact top-k coverage. Transmitting the entire vector can dominate telemetry volume, so a service may send top candidates plus explicit residual mass. That compact format supports ranking and coverage, but not arbitrary entropy or calibration calculations over tokens it never received.

Live overlays make decoding easier to inspect but can mislead if requests race. Keep each step keyed to its sequence and monotonically increasing index, and discard late data from a previous request. Streaming updates can redraw a small candidate list after each token; for long generations, persist a sampled trace with model, tokenizer, temperature, penalties, and timestamp instead of logging every full vocabulary vector. In the UI, combine bar length with a numeric percentage and text label. Do not use hue as the only signal, and preserve a visible distinction between missing data and a true probability of zero.

Failure modes and misconceptions

  • Overflow or NaN in softmax. Exponentiating raw logits can overflow. Subtract the largest scaled logit, reject non-finite inputs, and verify that the normalization sum is finite and positive.
  • Top-k appears to be the whole vocabulary. A chart of only returned candidates hides the rest. Keep original probabilities and display their coverage; mark residual mass as unknown if the backend did not provide enough information.
  • Token text is misaligned. A decoder may join pieces differently from the stream boundary or a late update may belong to another prompt. Key records by request and step, and use the matching tokenizer revision.
  • Confidence is read as correctness. A sharp distribution can still place most mass on a wrong continuation. Use held-out calibration and task accuracy to assess reliability; do not color a token “true” because its probability is high.
  • Decoding controls are omitted. Temperature and repetition penalties change the sampling distribution. Record the effective post-processing settings so two charts are not compared as if they describe identical distributions.

Decision scenario

A team compares two model releases with a dashboard that shows only the five most likely tokens for each prompt. The newer model looks more decisive because the visible bars add to 100%. Inspection reveals that the browser renormalizes those five candidates after dropping the rest. Keep the raw probabilities, show the combined top-five coverage and residual mass, and compare calibration and task accuracy on the same held-out prompts before claiming that the new model is more certain. If the API supplies only already-renormalized top-five values, label them as a restricted distribution and do not use them for full-vocabulary entropy or calibration claims.

Implementation pattern

This browser-side example computes a stable top-kk view from a complete logit vector, keeps the returned mass separate from the full distribution, and renders numeric labels beside each bar. Production traces should also carry the model and tokenizer revisions plus decoding settings.

typescript
type Candidate = { tokenId: number; probability: number };
type TopView = { candidates: Candidate[]; coverage: number };
​
function topTokens(logits: Float32Array, k: number, temperature = 1): TopView {
if (!Number.isFinite(temperature) || temperature <= 0) throw new RangeError("temperature must be positive");
if (logits.length === 0 || !Number.isInteger(k) || k < 1) throw new RangeError("logits and k are required");
let max = -Infinity;
for (const logit of logits) {
if (!Number.isFinite(logit)) throw new Error("logits must be finite");
max = Math.max(max, logit / temperature);
}
let total = 0;
const weights = Array.from(logits, (logit) => {
const weight = Math.exp(logit / temperature - max);
total += weight;
return weight;
});
if (!Number.isFinite(total) || total <= 0) throw new Error("softmax normalization failed");
const candidates = weights.map((weight, tokenId) => ({ tokenId, probability: weight / total }))
.sort((a, b) => b.probability - a.probability).slice(0, k);
return { candidates, coverage: candidates.reduce((sum, item) => sum + item.probability, 0) };
}
​
function renderTopTokens(root: HTMLElement, view: TopView, decode: (id: number) => string): void {
const list = document.createElement("ol");
for (const item of view.candidates) {
const row = document.createElement("li");
const label = document.createElement("span");
label.textContent = `Token ${item.tokenId}: ${decode(item.tokenId)} (${(item.probability * 100).toFixed(1)}%)`;
const bar = document.createElement("progress");
bar.max = 1;
bar.value = item.probability;
bar.setAttribute("aria-label", `${(item.probability * 100).toFixed(1)} percent probability`);
row.append(label, bar);
list.append(row);
}
const note = document.createElement("p");
note.textContent = `Displayed candidates cover ${(view.coverage * 100).toFixed(1)}% of the distribution.`;
root.replaceChildren(list, note);
}
​
const view = topTokens(new Float32Array([2, 1, 0]), 2);
console.assert(Math.abs(view.coverage - 0.910) < 0.002);
Reflect before revealing the guide

Prerequisites & Related Concepts (4)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.