Skip to content
AI360XpertBeta
Playgrounds

Modern ML

Transformer Decoding

Change the decoding settings and trace how the next-token distribution becomes a sequence.

Guided steps 1 / 5

Stage 1 of 5: The distribution

Count-based first-order bigram model, not Transformer inference.

Next-step greedy; requested T/K/P 1/9/1; effective 1/9/1; API T 1; current context the.

Current next-step preview after the. Axis maximum 1.

Current next-step preview after "the": model leads at 61.36919315403424 percent; 9 positive choices. Solid bars use final probabilities; hatched removals use untruncated heights. Axis maximum 1. Current completed prefix has suffix period 0; sampling can escape detected repetition.

Vocabulary 2 “model”, rank 1; count 5/8; numerator 5.02; denominator 8.18; conditional 0.6136919315403423; log -0.4882622169110179; shifted 0; scaled 0; exp 1; denominator partial 1.0079681274900398; K true, after K 0.6136919315403425; cumulative K 0.6136919315403425; P true, crossing false; final 0.6136919315403424; CDF [0,0.6136919315403424).

Generated so far

the
occurrence 0: the (prompt)

1 total tokens, 1 prompt, 0 generated, 0 completed transitions; budget 20 total. Every transition appears in the corpus.

  • In play
  • Inspected vocabulary token
Run experiment
Top probability61.4%Top probability: 61.4 %

Which count row supplies this decision?

At every step the model scores each token in its vocabulary. Greedy decoding takes the tallest bar and nothing else. Press Step to build a sentence.

  1. log P(next | current)
  2. softmax
  3. argmax
Count model

Only the final token conditions the next count row.

Check this stage

Check your understanding

Trace a fixed count model from corpus occurrences to a next-token distribution, temperature, rank and mass cuts, and a recorded generation decision.

This lab demonstrates decoding operations on a count-based, first-order bigram model. It is not a Transformer or a complete neural language model. Its distribution depends only on the final token; the preceding Full Transformer Block supplies no trained logits to this experiment.

Where do the scores come from?

The complete fixed corpus is:

  • the model reads the sentence
  • the model writes the sentence
  • the sentence teaches the model
  • a model reads a word
  • a word follows a word
  • the model writes a word
  • the model writes a sentence

Each sentence is split on the literal ASCII space, then empty pieces are removed. There is no general whitespace tokeniser, case folding or punctuation stripping. Tabs and newlines within a string would remain inside tokens. Sentence boundaries contribute no transition; there are no BOS or EOS tokens. Repeated adjacent occurrences count repeatedly, as do repeated sentences. Empty sentences contribute nothing; singleton sentences add vocabulary but no transition.

Vocabulary is lexically sorted: a, follows, model, reads, sentence, teaches, the, word, writes. These indices are stable identities. A probability rank changes with context; a generated occurrence has its own position, even when its spelling repeats.

The raw row after the contains five model and three sentence observations. Lidstone smoothing adds 0.02 to each of nine counts: denominator 8 + 9 × 0.02 = 8.18. Thus model receives 5.02/8.18, sentence receives 3.02/8.18, and each other token receives 0.02/8.18. Logits here are the natural logarithms of these conditional probabilities. An unknown context or a vocabulary token with no outgoing observations receives the uniform smoothed row. Counting is distinct from optimiser training; generation never updates the counts.

What does Step actually record?

Generation starts with one prompt token, the. The first two stages choose the first stable maximum greedily. Temperature enables sampling; Top-K and Top-P become effective at their respective stages. Editable settings remain when returning to earlier stages, but inactive mechanisms use their displayed defaults. Explore freely enables the final policy consistently for both preview and Step.

Each Step records the incoming prefix, final conditioning token, requested and effective settings, strategy, draw protocol, selected vocabulary identity and outgoing prefix. Select an occurrence or transition to inspect its historical incoming distribution. Next-step preview instead uses the current final token and controls. A sampled output belongs to the row that produced it, not automatically to the following row.

Changing settings keeps the actual prefix and recorded decisions. Rewind removes one completed transition and restores the preceding decision. Stepping afterwards branches from that prefix. The manual budget is twenty total tokens: one prompt and at most nineteen generated tokens, not twenty transitions and not an EOS rule.

Why does greedy cycle here?

With fixed counts, fixed settings, stable tie resolution, no additional constraints and continued generation, this first-order model maps each current token to one successor. A walk on that finite state set eventually revisits a state and cycles. From the, it reaches the model writes a word follows a word follows.

A finite vocabulary alone does not prove that every general Transformer generation must cycle: its state is not merely the last token. Changed settings, context, constraints and stopping rules also change the argument. The lab detector reports the smallest period from one through four for which the last two blocks match. A repeated sampled suffix may subsequently escape; a zero detector result does not mean the whole text has no repetition.

How does temperature change the row?

The API uses effective temperature max(requested T, 0.001) for finite requests. The visible slider is 0.1–2.0, initially 1. The computation subtracts the largest logit, divides each shifted value by effective T, exponentiates, accumulates in vocabulary input order and divides by that sum. Stable sorting then produces descending probability rank, retaining input order on exact ties. Every intermediate and denominator partial is available under the hood.

A common finite shift leaves softmax unchanged mathematically, subject to floating arithmetic. Probability ratios are exp((li−lj)/T). At T=1, log conditional probabilities recover the smoothed distribution mathematically, with possible final-bit differences. A low positive temperature is not universally greedy: ties share the limiting mass, and finite-temperature sampling can choose another token. Very small terms can underflow to zero. High temperature approaches uniformity for fixed finite logits, but finite T need not be exactly uniform or yield meaningless output.

NaN and infinite logits, duplicate identities and finite subtraction/scaling overflow are rejected. Negative infinity is not an exclusion mechanism in this API; filtering represents exclusion explicitly by zero. Empty transforms return empty; sampling an empty or invalid distribution fails explicitly. Requested and API-effective T are distinct from stage-effective T.

What do Top-K and Top-P remove?

Top-K validates descending probability order, rounds finite K with Math.round, and clamps it from one to vocabulary size. Its visible range is 1–9, initially 9. It keeps a ranked prefix, sums its mass, zeroes the rest and divides survivors by that denominator. Retained rank membership can include computed zeros after underflow; the Tokens kept metric counts strictly positive final probabilities.

Top-P uses the renormalised Top-K distribution in this lab. Its visible range is 0.1–1, initially 1. It accumulates in ranked order and includes the first token whose cumulative mass is greater than or equal to P. The API clamps finite P to [0,1]; zero keeps the first entry, one retains all support. K=1 agrees with first-argmax decoding under the same stable tie and valid sampler assumptions. Filters reject unsorted, negative, nonfinite, zero-mass and non-unit distributions; unit sums use tolerance 1e-12.

Order is not a universal framework convention. For probabilities [0.6,0.25,0.15], K=2 then P=0.7 first renormalises to [0.6/0.85,0.25/0.85,0], so the first token alone crosses 0.7. P first keeps two tokens, and subsequent K=2 keeps both. Compare these with identities, incoming distribution, thresholds and tie order fixed. Neither order establishes language quality or saves model-forward computation. Removed tokens are not thereby incorrect, unsafe or implausible.

For this fixed finite-logit temperature family and fixed P, spreading cumulative mass can increase the nucleus count. Merely calling two arbitrary distributions flatter does not justify that conclusion. Inspect raw probabilities rather than bar heights.

Which random draw chooses the token?

At each completed position, a new Mulberry32 generator receives prefix.length × 1337, truncated and coerced unsigned to 32 bits. The lab takes its first draw. It does not continue one PRNG stream and provides no seed control. The same position uses the same draw across settings, supporting a paired comparison, but chosen tokens and subsequent conditional rows can diverge.

The sampler walks the final CDF in array order with half-open intervals [lower,upper). Draw zero selects the first positive interval; an exact cumulative boundary selects the next positive interval. Zero-mass tokens cannot be drawn. Draws must be finite and in [0,1). A floating accumulation gap within the unit-sum tolerance falls back to the last positive token, never an excluded one. Inspection records the actual draw, interval, sum and fallback. These are probabilities and one realised decision, not empirical sampling frequencies.

What do the bars and metrics mean?

Bars rank by the untruncated temperature distribution. Survivors use final renormalised heights; hatched removals retain untruncated heights. This is a mixed comparison encoding, not one distribution. The inspected vocabulary identity has the selection role when retained; native selectors and raw values remain available for removed tokens. Labels are omitted below sixty pixels per bar. The probability axis automatically chooses 0.25, 0.5 or 1 to contain all displayed heights; a scale change is not a probability change.

Top probability is the current preview's highest final probability. Effective choices is exp(−sum p ln p), omitting zero terms, on a nonnegative normalised row. Off-corpus mass sums final probability on raw transitions absent from this tiny corpus. Loop period is the short suffix test. Tokens kept counts positive final probabilities. Current preview metrics and historical inspection have separate labels.

An unobserved bigram can be valid language. Zero off-corpus mass establishes neither grammaticality, meaning, factuality, usefulness nor generalisation. The 0.15 caution threshold is a lab policy, not a safety boundary or numerical divergence. The challenge retains its predicate: at least twelve total tokens, no detected short repeated suffix, zero unsupported transitions. From the initial prompt, eleven sampled steps with T=1, K=3, P=1 give one reproducible solution, not a universal best setting.

How can an experiment be reproduced?

Share stores the displayed guided stage, requested controls, inspection selections and the bounded schedule of actual historical policies. Replay uses each decision's own settings and original per-position draw protocol; final controls plus a step count cannot reproduce a mixed-settings prefix. Invalid or oversized shared schedules restore the prompt with feedback. Links open guided; guesses and recovery stay in memory.

The broad-distribution preset saves the entire preceding experiment, including original guided stage, sandbox, settings, selected identities, prediction and actual history. Recovery restores it after further edits. Mathematical, stage, mode, history and selection changes clear predictions; inspection disclosure, Help, presentation, motion and resize preserve them. Reset defaults the experiment at the retained guided stage and clears history, prediction and recovery. Mark explored records local exploration only.

Beam search, repetition penalties, full-context autoregression, context windows and EOS remain quiz context. Beam search prunes partial hypotheses and cannot guarantee globally optimal text. None is implemented as an additional mode here.

The nucleus sampling paper, NLTK smoothing documentation and SciPy softmax documentation provide the primary mechanism context; this lab's explicit policies define its actual computation.

Stage recap

  1. The distribution

    At every step the model scores each token in its vocabulary. Greedy decoding takes the tallest bar and nothing else. Press Step to build a sentence.

  2. Greedy repeats

    Keep pressing. Each token has exactly one most-likely successor, so greedy decoding is a walk on a fixed map over nine tokens — it has to come back to a token it has already visited, and after that it repeats forever.

  3. Temperature

    Sample instead of taking the maximum; a repeated suffix may escape or recur. Temperature divides the logits first: below 1 it sharpens toward greedy, above 1 it flattens. Effective choices counts how many tokens are really in play.

  4. Top-K

    Flattening has a cost: mass moves onto continuations the corpus never contained. Top-K keeps a fixed number of the highest-scoring tokens and zeroes the rest, which cuts the tail off wherever it is.

  5. Top-P (Nucleus)

    Top-P keeps tokens until their cumulative probability reaches P, so it takes a count determined by the ranked mass, including the crossing token. Watch it hold on more tokens for this fixed-logit temperature family as T rises; inspect the mass.

Reference

Logits
the raw scores the model produces for every token. Here they are log P(next | current) from bigram counts over a seven-sentence corpus
Softmax
turns logits into a distribution that sums to 1
Temperature
divides the logits before softmax. T < 1 sharpens toward greedy, T > 1 flattens toward uniform
Greedy
take the stable argmax; this fixed first-order successor map eventually cycles if generation continues
Top-K
keep the K highest-scoring tokens, zero the rest, renormalise. A fixed count, whatever the shape
Top-P
keep tokens until the cumulative probability reaches P. A fixed mass, so the count adapts to the shape
Effective choices
exp(H) of the final distribution: 1 if one token takes everything, 9 if all nine are equally likely
Off-corpus mass
final probability on unobserved raw bigrams in this tiny corpus; valid language can include such pairs

Break it on purpose

In this fixed first-order model, taking the maximum makes a walk on a fixed successor map, which on a finite vocabulary has to close into a loop — here it locks into "a word follows" by the ninth token. Raise the temperature instead and the opposite happens: probability mass slides onto continuations the corpus never contained, and the sampler starts joining words that have never followed each other.