← Inference From First Principles

Tokens, Embeddings and Probability

From text to token ids to a vector per token to scores over the vocabulary, and the rules that turn scores into a choice. Measured on a real model.

Chapter 1 ended with a sentence that looped. Forty greedy steps from the same prompt produce this:

An inference engine takes a trained model and a request, and it must turn them into a model that can be used to generate a model that can be used to generate a model that can be used to generate a model that can be used to generate a model that can be used to generate

We called that a property of this model-and-decoder combination, rather than evidence that the forward-pass implementation is defective. This chapter makes the distinction testable. We follow four objects through the request: token ids obtained from text, input embedding vectors looked up by id, logits computed for each possible next token, and a probability distribution from which a decoding rule chooses. Each transition has its own invariants and failure modes. Correct tensor arithmetic does not guarantee useful text, and a diverse continuation does not establish that the underlying probabilities are correct.

Three observations organise the chapter. On six recorded GPT-2 prompts, a naive float32 softmax returned distributions that summed to approximately one while differing from a stable reference by as much as 0.30 in absolute probability. At top-p = 0.9, the number of retained candidates varied from 131 to 14,394 across those prompts. In one 40-token greedy continuation, the probability the model assigned to its selected next token was about 0.34 at step 1 and 0.99 at step 39. These are measurements of one checkpoint, specific prompts, and particular computations—not measurements of calibration, answer quality, or how all modern models behave.

Where this sits

Chapter 2 asked which artefact is executed and showed how changing its tokeniser can alter the model-facing input without changing the weights. This chapter follows that input through the first and last layers: text becomes token ids, ids select embedding rows, the model produces logits, and the decoder makes a choice. The tokeniser, weights and decoding configuration must be identified together before two generation results can meaningfully be compared.

The Pi series has a separate embeddings volume concerned with vector representations used for matching and retrieval. Here, token embeddings are the rows of a language model’s input lookup table. They are learned during language-model training; they do not by themselves constitute a sentence-embedding system, nor does cosine proximity in the table establish semantic retrieval quality. The distinction will matter when we connect the Inference Lab to retrieval and agent workloads.

The Inference Lab piece added here is a sampling configuration and a select_token function. The configuration records whether decoding is greedy and, when sampling, the temperature, top-k, top-p and seed. The dataclass is immutable, but its constructor does not validate every combination: some invalid settings fail only when selection is attempted, and the greedy branch bypasses sampling-parameter checks. That distinction between recorded configuration and validated request is an engineering obligation, not a detail to hide.

Request pipeline

Text to ids

A text-only GPT-2-style model receives token ids, not raw characters. GPT-2 uses byte-level byte-pair encoding (BPE) with a vocabulary of 50,257 entries. Its tokeniser partitions text with a pre-tokenisation pattern, represents each piece as UTF-8 bytes, and uses learned merge rules to combine frequent byte sequences. The original BPE idea of merging frequent adjacent units is useful background, but it does not by itself fully specify GPT-2’s treatment of spaces, punctuation or Unicode. Eleven inputs run through the pinned GPT-2 tokeniser make these effects concrete:

Text Token ids Pieces
inference 259, 4288 in · ference
inference (leading space) 32278 inference
Inference 818, 4288 In · ference
INFERENCE 1268, 24302, 18310 IN · FER · ENCE
tokenisation 30001, 5612 token · isation
unbelievably 403, 6667, 11203, 1346 un · bel · iev · ably
3.14159 18, 13, 1415, 19707 3 · . · 14 · 159
2026-10-21 1238, 2075, 12, 940, 12, 2481 20 · 26 · - · 10 · - · 21
indented (four spaces) 220, 220, 220, 773, 4714 · · · ind · ented
naïve café 2616, 38776, 40304 na · ïve · café
推論 162, 236, 101, 164, 104, 244 six byte-level fragments

All eleven decode back to exactly the text that went in. Several things in the table are worth reading slowly.

Spaces affect token boundaries. In the recorded example, inference is two tokens while inference is one because the leading space becomes part of a learned token. A trailing space may likewise change how the tokeniser represents the end of a prompt; it is not necessarily a separate, neutral character. We have not measured whether that particular change alters this checkpoint’s next-token ranking. Exercise 2 isolates the effect instead of assuming it.

Case changes token identity and sometimes token count. INFERENCE is three tokens here, while Inference and inference are two each. The model receives different ids and learned vectors; it may learn their relationship from training data, but the tokeniser does not encode a guarantee that their meanings or next-token distributions will match.

Number boundaries follow merge statistics, not arithmetic place value. In this tokenizer, 3.14159 becomes 3, ., 14, 159, and the date separates into digit groups and punctuation. This fragmentation is relevant when investigating numeric tasks, but the table alone cannot establish a degradation in arithmetic accuracy. That would require a separate, task-specific experiment.

Indentation contributes to token count, but not as a fixed cost. The string indented becomes five tokens: three standalone spaces, ind, and ented. This is not “three tokens and half of a fourth”; each listed token is a complete vocabulary item. Indentation-heavy code can consume additional context budget under this tokeniser, but the cost depends on adjacent text and the learned merges.

Unicode can be split into byte-level fragments. The two Han characters in 推論 become six GPT-2 token ids. When each id is decoded separately, the result may be a replacement character because a single token does not contain a complete UTF-8 character; decoding the full id sequence reconstructs the original text. Byte-level processing is not restricted to non-Latin writing systems, and the recorded token count is evidence about this tokeniser, not an inherent cost of a language.

Nothing in the table is itself a tokeniser defect. The engineering consequence is that model execution depends on the exact id sequence, including added special tokens and the tokeniser revision. A client may submit text, but a model consumes ids. Context length, cache compatibility, billed token counts and token throughput must therefore be interpreted under a named tokeniser and a declared counting convention. For serving APIs, different providers may count or bill tokens differently; this table establishes only the local GPT-2 counts. The tokeniser belongs in Chapter 2’s artefact manifest.

Ids to vectors

For the token-content path, the model begins by looking up an input embedding for each token id. GPT-2 also incorporates learned positional embeddings before the transformer blocks; the lookup below describes the token embedding component, not the entire initial hidden state. With vocabulary size \(V\) and hidden width \(d\), the input table \(E\) has one row per vocabulary entry:

\[ E \in \mathbb{R}^{V \times d}, \qquad \mathbf{x}_t = E[\text{id}_t] \]
For this GPT-2 checkpoint, \(V = 50{,}257\) and \(d = 768\), giving \(Vd = 38{,}597{,}376\) elements in the input token-embedding table. That is **31.0% of its 124,439,808 unique model parameters** as counted by the PyTorch parameter iterator. GPT-2 also ties that table to its output head; the 31.0% figure counts the shared storage only once. This is a striking memory trade-off for this small model, not an estimate of the embedding fraction of larger architectures.

A row lookup is context-independent: king indexes the same stored row regardless of whether the surrounding sentence discusses chess or monarchy. The transformer layers produce context-dependent hidden states downstream. Nearest-neighbour comparisons between the input rows nevertheless reveal which tokens this checkpoint places near each other under cosine similarity. The experiment below is an exploration of its trained parameters, not a test of sentence semantics:

Token Nearest rows, by cosine similarity
king kings 0.73 · King 0.70 · queen 0.66 · King 0.60 · prince 0.59
Paris Paris 0.83 · France 0.63 · French 0.58 · London 0.58
running Running 0.74 · Running 0.67 · running 0.65 · ran 0.63 · run 0.63
inference inferred 0.63 · implication 0.63 · infer 0.60 · assertion 0.54

In these selected examples, spelling variants and related terms often have high cosine similarity: cat/ dog scored 0.55, while cat/ the scored 0.21; king/ queen scored 0.66, versus 0.26 for king/ banana. The neighbour list is selected, not a random sample or a retrieval benchmark. A cosine of 0.66 does not prove an equivalence of meaning, and it must not be confused with the raw dot product used by GPT-2’s output head.

One matrix used twice

GPT-2 uses this matrix a second time in its output head. With weight tying, the vocabulary projection has shape \(V\times d\) and shares the input embedding table’s storage. If \(\mathbf h\) is the final hidden state and \(\mathbf e_i\) is row \(i\), the corresponding logit is their dot product, not a normalised cosine similarity:

\[ z_i = \mathbf{e}_i \cdot \mathbf{h}, \qquad \mathbf{z} = E\,\mathbf{h} \in \mathbb{R}^{V} \]
The experiment checked actual shared storage through the underlying tensor pointers. An untied output matrix of this size would require another \(38{,}597{,}376\) float32 values, or **154,389,504 bytes (154.4 MB, about 147.2 MiB)**, in addition to the input table. The matrix-vector projection performs about 38.6 million multiply-accumulates (approximately 77.2 million FLOPs under the usual two-FLOP convention) per position when fully evaluated. That motivates avoiding unnecessary all-position output projections in naive generation, but it is an arithmetic estimate, not a hardware timing result. Weight tying is a known language-model design choice; Press and Wolf give research context for it. The raw dot product reflects both direction **and magnitude**, so calling it a semantic similarity score would be misleading.

Vectors to scores

The next-token output is a logit vector \(\mathbf z\in\mathbb R^V\), one unnormalised score per vocabulary entry. On the six recorded GPT-2 prompts, the maximum logit ranged from approximately −102.1 to −31.9, and all recorded logits were negative. Those signs and magnitudes are properties of these model outputs, not a universal constraint on language-model logits. For an ordinary softmax, it is differences between finite logits—not their common offset—that determine probabilities.

That is not a quirk of this model, it is a property of the function that consumes them. Softmax maps scores to probabilities:

\[ p_i = \frac{e^{z_i}}{\sum_{j=1}^{V} e^{z_j}} \]
Adding the same constant \(c\) to every logit multiplies the numerator and every term of the denominator by \(e^{c}\), which cancels:
\[ \frac{e^{z_i + c}}{\sum_j e^{z_j + c}} = \frac{e^{c}\,e^{z_i}}{e^{c}\sum_j e^{z_j}} = p_i \]
Softmax is **mathematically invariant** to adding the same finite constant to all logits. In finite-precision arithmetic, however, directly exponentiating large positive values can overflow and exponentiating very negative values can underflow. The stable implementation subtracts the largest logit *before* exponentiation. This preserves the exact mathematical distribution while greatly improving numerical behaviour; it does not guarantee meaningful results for NaNs, infinities, or every extreme low-precision case.

The softmax that fails quietly

A naive softmax exponentiates every logit, sums the exponentials, then divides. Its failure mode depends on the arithmetic and runtime: Python’s math.exp may raise on large positives and the sum can vanish on large negatives, while tensor libraries may instead propagate infinities or NaNs. Here is what the chapter’s Python example and float32 overflow probe establish:

Logits Naive result Stable result
[2.0, 1.0, 0.5, 0.1] correct correct
[1000, 1001] OverflowError 0.269, 0.731
[−1000, −1001] ZeroDivisionError (every exponential underflows to 0) 0.731, 0.269
[88, 89, 90] correct in 64-bit; in 32-bit \(e^{89}\) overflows correct

For finite logits, let \(m=\max_j z_j\). Subtracting \(m\) gives at least one exponent equal to \(e^0=1\), preventing a zero denominator caused solely by all logits being shifted far into the negative range and ensuring no exponential argument is positive:

\[ p_i = \frac{e^{z_i - m}}{\sum_j e^{z_j - m}} \]
Overflow, division by zero, and NaNs are relatively easy to detect if a caller checks for them. More dangerous is **silent numerical distortion**. IEEE-754 float32 has a smallest positive *normal* value near \(1.175\times10^{-38}\); smaller positive *subnormal* values can represent numbers down to roughly \(1.4\times10^{-45}\), but with reduced significant precision. Since \(e^{-100}\approx3.7\times10^{-44}\), direct exponentiation of GPT-2 logits in this range can lose substantial information before normalisation. Some hardware and kernels may flush subnormals to zero, making the exact failure mode implementation-dependent.

The recorded float32 experiment applied torch.exp(logits32) and then divided by the sum, using logits from six GPT-2 prompts. All six outputs avoided NaNs and their probabilities summed to approximately one, yet some individual probabilities differed materially from torch.softmax(logits32). The table reports the maximum absolute difference, not model error against a labelled answer:

Prompt Maximum logit Denominator Largest probability error
The −31.9 \(1.1 \times 10^{-12}\) \(6.5 \times 10^{-9}\)
2 + 2 = −91.0 \(3.1 \times 10^{-39}\) \(1.0 \times 10^{-4}\)
def fibonacci… −96.4 \(7.3 \times 10^{-42}\) \(8.6 \times 10^{-3}\)
Once upon a −96.1 \(9.2 \times 10^{-42}\) \(2.3 \times 10^{-2}\)
The capital of France is −100.2 \(2.0 \times 10^{-43}\) \(6.3 \times 10^{-2}\)
An inference engine takes… −102.1 \(1.1 \times 10^{-44}\) \(3.0 \times 10^{-1}\)

For the technical prompt, at least one token’s naive probability differed from the stable float32 reference by about 0.30. Normalisation preserved an apparently valid sum despite large rounding and underflow errors. This does not establish that a real provider uses that naive implementation, and it does not quantify a resulting answer-quality failure. It establishes something testable and consequential: checking only that probabilities sum to one will not catch this class of numerical bug. A greedy decoder may retain the same argmax while a sampling distribution changes substantially.

This is a concrete case where convenient unit-test logits are insufficient. The toy test on [2.0, 1.0, 0.5, 0.1] does not exercise subnormal arithmetic. The chapter’s pure-Python stable computation agreed with a float64 PyTorch softmax reference, within a maximum absolute difference of \(1.3\times10^{-15}\), over 50,257 logits for each of six prompts. That supports agreement on this workload; it is not a proof over all finite inputs or an error bound for float16/bfloat16 kernels. A stronger test matrix would include extreme offsets, tied logits, non-finite inputs, all-masked candidates, and each target numerical dtype. Chapter 12 examines reduced precision.

Scores to a distribution

For a finite logit vector with at least one valid candidate, softmax supplies a model-implied next-token distribution, not a calibrated probability of a fact being true. Its shape helps explain what particular decoding rules will retain or sample. The six prompts below were hand-chosen to show contrasting contexts; the table preserves their recorded GPT-2 measurements:

Prompt Top token (probability) Entropy (nats) Tokens in 0.9 nucleus Mass in top 40
The capital of France is the (0.085) 6.00 1,503 0.53
2 + 2 = 3 (0.102) 5.12 1,171 0.69
Once upon a time (0.177) 5.90 1,956 0.52
The \n (0.014) 8.82 14,394 0.14
An inference engine takes a trained model and a model (0.072) 6.51 1,333 0.38
def fibonacci(n):\n if n < 0 (0.175) 3.89 131 0.82

Entropy, \(H=-\sum_i p_i\ln p_i\), measures the dispersion of this model distribution. A uniform distribution over 50,257 tokens has entropy \(\ln(50{,}257)\approx10.82\) nats; a point mass has entropy zero. The measured range here was about 3.89–8.82 nats. Entropy alone cannot establish factual correctness, usefulness, uncertainty calibration, or the diversity of an entire generated sequence.

Two features of the table matter for everything downstream.

Next-token rank is not answer evaluation. After The capital of France is, GPT-2’s top next token was the (0.085), while Paris ranked fifth (0.032). Under greedy decoding, the immediate next token is therefore not Paris. The checkpoint is a 124-million-parameter model from 2019, used here as an inspectable teaching baseline rather than an assistant benchmark. Better scheduling or numerically faithful computation should preserve the chosen logits within a stated tolerance; changing the weights, prompt, precision, or decoding policy can change the ranking. To claim one response is a better answer would require an evaluation task, not this single next-token table.

Top-p and top-k constrain candidates in different ways. Top-p = 0.9 retains the shortest probability-ranked prefix whose cumulative mass reaches 0.9; on these prompts its size ranged from 131 to 14,394. The largest set came from the one-token prompt The, with no explicit start-of-text token prepended. Excluding it still leaves sizes from 131 to 1,956. Top-k = 40 always retains at most 40 candidates, but those 40 held 82% of the original probability mass on the code prompt and only 38% on the technical one. With ties, masking, or minimum-token rules, implementations can vary; this table measures the Lab’s explicit rule.

Neither filter is automatically better. Top-k states a candidate-count limit; top-p states a cumulative-probability target. Both settings are meaningful, but neither fixes the amount of mass excluded, the resulting entropy, or output quality across contexts. Their interactions with temperature, other filters and renormalisation must be specified to reproduce a draw.

Nucleus size variation across prompts

Temperature

Temperature divides the logits before the softmax:

\[ p_i(T) = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}} \]
For **strictly positive** \(T\), dividing logits by \(T\) sharpens the distribution when \(T<1\) and flattens it when \(T>1\). As \(T\to0^+\), all probability concentrates on the unique largest-logit entry, or splits across tied maxima; as \(T\to\infty\), a finite unmasked vocabulary tends to uniform. At \(T=1\), logits retain their original softmax distribution. The following numbers come from the *same saved GPT-2 logits* for `Once upon a`, transformed at different temperatures:
Temperature Top-1 probability Entropy (nats) Tokens in 0.9 nucleus
0.25 0.948 0.21 1
0.5 0.744 0.98 2
1.0 0.177 5.90 1,956
1.5 0.025 8.75 11,187
2.0 0.006 9.66 19,623

With fixed logits, temperature changes the resulting probability distribution without recomputing the model. Here the size of the top-p = 0.9 set ranges from one token at \(T=0.25\) to 19,623 at \(T=2\); changing \(T\) from 1.0 to 0.5 reduces it from 1,956 to two. Over multi-token generation, however, a different sampled token changes the next input and therefore later forward passes and logits. The separation is between computation and selection at an individual step, not a guarantee that an entire continuation is unchanged.

The temperature formula is undefined at \(T=0\). Many APIs treat zero temperature as a request for greedy decoding, but this is a convention, not a mathematical value of the softmax expression. The Lab instead uses an explicit greedy flag and resolves tied maximum logits by the lowest token index. This makes greedy selection deterministic for a fixed finite logit vector; it does not by itself guarantee bitwise reproducibility across models, devices, batch shapes or kernels. The sampling path still requires \(T>0\).

From distribution to choice

The chapter’s sampler applies temperature → top-k mask → top-p mask → normalise → random draw. Internally, top-p computes softmax over the logits remaining after top-k, which is equivalent to renormalising that candidate set before accumulating probability. Reversing the order can select different candidates. Other frameworks may use different processors, defaults and orders, so their documented version and effective generation configuration belong in a comparison. Merely recording top_p=0.9 is insufficient to reproduce a sample when other processors are active.

The final choice uses a uniform random draw from a fresh random.Random(seed) instance. For the same finite logits, effective settings, Python implementation and seed, the selector returns the same id. In the toy frequency check, 10,000 distinct seeds gave a maximum absolute empirical deviation of 0.0076 from the expected four-token distribution, with a largest binomial standard error around 0.0049. Under top-k = 2, the two excluded ids occurred zero times, and the included ids were drawn at about 0.741 and 0.260 against theoretical probabilities near 0.731 and 0.269. These observations provide a basic sanity check, not an audit of the random-number generator or a formal distributional guarantee.

The check did not reveal an obvious discrepancy at this sample size. It cannot establish that all configurations are unbiased, and it does not test a stateful per-request random stream during concurrent generation. This prototype reseeds the generator on each call; the 40-step diversity experiment deliberately constructs different seeds from the run id and step. A production runtime instead needs an explicit policy for independent per-request streams, deterministic replay and how cancellation or batching affects RNG consumption. Chapter 39 returns to those questions.

The loop, explained

We can now examine the chapter’s opening loop without mistaking model probability for measured accuracy. A 40-step greedy generation from the Chapter 1 prompt recorded the selected token’s conditional probability, entropy and top-p = 0.9 nucleus size at every step. The first selected token ( a) had probability 0.34 and a nucleus of 959; at step 13 the selected-token probability was 0.62; at step 23 it was 0.90 with a nucleus of one. Values fluctuate from step to step, but in this continuation they eventually become very concentrated, exceeding 0.91 from step 31 onward. The table displays selected observations from the saved trajectory:

Step Token Probability Entropy (nats) 0.9 nucleus
1 a 0.34 4.76 959
5 be 0.49 3.50 178
13 be 0.62 2.66 113
23 to 0.90 0.59 1
31 to 0.98 0.15 1
39 to 0.99 0.08 1
40 generate 0.97 0.32 1

Greedy loop trajectory

In this one continuation, later repetitions coincide with much higher probabilities for the selected tokens and lower entropies at several displayed steps. This is consistent with the self-reinforcing degeneration examined by Holtzman and colleagues; it is not, by itself, a causal experiment showing that repetition always raises confidence. The generated prefix influences the next-token distribution, and greedily feeding the highest-ranked token back into that prefix can sustain a loop. To test the causal role of decoding, we need matched prompts with alternative selection policies and repeated trajectories.

A different sampling rule may escape the observed loop, but is not guaranteed to do so. We therefore compare the distinct-trigram ratio of 40 generated tokens: the number of distinct contiguous three-token sequences divided by the 38 possible trigrams. A ratio of 1.0 means no trigram repeated; it does not mean the text is coherent, correct, or useful. Greedy decoding is deterministic here and was run once; each stochastic configuration used eight seeds:

Selection rule Runs Mean distinct-trigram ratio Range
Greedy 1 0.21 –
\(T = 1.0\) 8 1.00 1.00 – 1.00
\(T = 1.0\), top-p 0.9 8 1.00 1.00 – 1.00
\(T = 0.7\), top-p 0.9 8 0.93 0.82 – 1.00

The greedy sequence had eight distinct trigrams among 38, for a ratio of about 0.21. In the eight recorded runs for each sampled setting, the ratios were higher; the unfiltered \(T=1\) sample nevertheless included the incoherent phrase “delegated as an recurrence model”. The metric detects repetition, not quality. A diversity-only score would misleadingly reward nonsensical but unrepeated output. Evaluation of factuality, task success, style and constraints belongs to the later chapters. Nor do eight seeds establish that a particular sampler always outperforms greedy generation.

What the numbers do not show

  • One small model, from 2019. These distributions and repetition behaviours are GPT-2-specific. We have not measured entropy, rank, or loop frequency for larger, instruction-tuned, or contemporary models, so we make no directional claim about their results.
  • Six selected prompts. These are useful contrasts, not a representative sample of model use; The is a particularly short context.
  • One tokeniser. GPT-2’s byte-level BPE and merge rules do not predict exact counts for other tokenisers, scripts, or model families.
  • Embedding neighbours are not a semantic benchmark. The displayed cosine neighbours describe one trained lookup table; they do not test retrieval or sentence-level meaning.
  • Repetition is not quality. Distinct trigrams measure only local n-gram variety; eight sampled continuations are too few to establish a general decoding-policy ranking.
  • No calibration claim. A 0.99 next-token model probability is not an observed 99% answer-correctness rate. No calibration dataset or scoring rule was evaluated.
  • Numerics depend on dtype and implementation. The naive failure was demonstrated in float32 and the Python reference comparison in float64. GPU, float16, bfloat16, fused sampling kernels and masking edge cases were not tested.

Inference Lab increment

The Lab now has SamplingConfig and select_token:

@dataclass(frozen=True)
class SamplingConfig:
    greedy: bool = False
    temperature: float = 1.0
    top_k: int | None = None
    top_p: float | None = None
    seed: int = 0

def select_token(logits, config: SamplingConfig) -> int: ...

SamplingConfig.describe() returns the five declared selection fields, and select_token uses them to choose an id. A frozen dataclass is not a validated generation policy. The dataclass does not validate temperature or conflicts between greedy and sampling options; the selection boundary also lacks explicit checks for non-finite logits and empty or fully masked candidate sets. Some errors appear only during a draw. Moreover, probability.py’s run() report advertises top-k and top-p values in its metadata even though sampled_index is generated by an unfiltered sample_index(logits, seed=seed) call. Its reported candidate sets are descriptive, not applied to that draw. Do not use this demonstration report as if it proved filtered-sampling conformance. The chapter adds a specification to repair and test that mismatch before the Lab treats the recorded configuration as reliable provenance. Combining this chapter’s configuration with Chapters 1 and 2 provides the fields needed to describe an experiment; the current code has not yet demonstrated an end-to-end run record containing all of them.

The CPU sampler operates on Python lists and a Python random generator; it is not a GPU or concurrent-serving implementation. It also lacks production stop conditions, penalties, exhaustive validity checks and a versioned decoding-policy schema. A future tensor sampler must demonstrate parity against specified reference distributions and document how dtype, ties, masks and RNG streams change behaviour; it should not merely inherit the interface and declare equivalence. Chapter 35 addresses constrained outputs, while Chapter 39 examines reproducibility across execution environments.

What you should now be able to do

  • Tokenise a string with GPT-2’s byte-level BPE and explain why a change in case or spacing can change token ids and token count.
  • Say what the embedding table is and what it is not, and find its share of a model’s parameters.
  • Explain why softmax is invariant to shifts in the logits and why that makes subtracting the maximum safe.
  • Show an example of a numerically wrong but non-crashing softmax and say what in the output would reveal it.
  • Explain what temperature, top-k and top-p each change, and reproduce the exact order in which the Lab applies them.
  • Explain why a greedy repetition loop can arise without an arithmetic defect, and distinguish a next-token probability trajectory from a calibrated correctness claim.

Key terms

  • Token: a discrete unit of text defined by a particular tokeniser.
  • Byte-pair encoding (BPE): a subword-tokeniser training method that repeatedly merges frequent adjacent units; GPT-2 uses a byte-level variant with additional pre-tokenisation rules.
  • Embedding table: the learned matrix mapping token ids to vectors.
  • Weight tying: reusing one parameter matrix for input token embeddings and the output projection, rather than storing two independent matrices.
  • Logit: an unnormalised output score; for ordinary softmax, relative differences determine probabilities.
  • Softmax: the map from logits to probabilities.
  • Subnormal number: a floating-point value smaller than the smallest normal number, with reduced precision.
  • Entropy: \(-\sum_i p_i\ln p_i\), the spread of a distribution, not a standalone correctness or calibration measure.
  • Temperature: a divisor applied to the logits before softmax.
  • Top-k, top-p: restrictions of the candidate set by count or by cumulative probability.
  • Nucleus: the set of tokens kept by top-p.
  • Greedy decoding: selecting the highest-scoring token at every step.

Reader exercises

  1. Prove that subtracting the maximum leaves at least one exponential equal to one when all logits are finite. In float32, find an experimentally observed logit gap beyond which the smaller token underflows to zero, and record the software, dtype and kernel rather than claiming a universal threshold.
  2. Compare the next-token distributions for The capital of France is and the same string with a trailing space. How much does the entropy change and does the top token change? What does that imply for prompt templates?
  3. Add min_p filtering (retain tokens above a stated fraction of the largest probability), define exactly where it occurs in the filtering pipeline, and compare candidate counts on the six recorded distributions. Test an all-masked edge case.
  4. Run the 40-step trajectory with \(T=0.3\), top-p = 0.9 and several independent seeds. Report the first step (if any) at which the sampled token’s probability exceeds 0.9, and count repeated trigrams across runs. Do not infer answer quality from either statistic.
  5. Take the 14,394-token nucleus for The and prepend GPT-2’s end-of-text token as a start marker. Does it narrow? What does that say about the single-token result above?
  6. Repeat the embedding experiment on another available checkpoint. Check for tied storage explicitly, calculate the token-embedding fraction without double-counting, and compare raw dot products with cosine similarities.
  7. Inspect probability.py’s run() output. Reproduce the mismatch between reported top-k/top-p settings and its unfiltered sampled_index. Change the implementation so the report explicitly distinguishes candidate-set diagnostics from the effective sampling policy, and add an automated test that fails when the recorded effective policy and selected token disagree.

References

Evidence in this chapter

Claim Classification and limit
GPT-2 uses a byte-level BPE tokeniser; BPE learns frequent subword merges Established background; exact GPT-2 behaviour is implementation-specific
Softmax is invariant to a common finite logit shift Mathematical identity; floating-point stability is a separate implementation question
Weight tying can reuse an input matrix for output projection Established design pattern; Press and Wolf provide primary research
Greedy decoding can enter repetitive loops Established research background; the displayed 40-token path is one book observation
Eleven tokenisation examples round-trip under the pinned GPT-2 tokeniser Local book result; no cross-tokeniser generalisation
GPT-2 input embedding has 38,597,376 elements (31.0% of parameters) and tied output storage Local book result; one checkpoint
Six prompts produced only negative logits; maxima from −102.1 to −31.9 Local book result; not a constraint on logits generally
Naive float32 softmax deviated from torch.softmax by up to about 0.30 without NaNs Local book result; not answer correctness or a provider finding
Pure-Python stable softmax and float64 PyTorch reference agreed to \(1.3\times10^{-15}\) Local book result; six prompts, not all possible inputs
Top-p = 0.9 candidate sets ranged from 131 to 14,394 Local book result; six chosen prompts
In a greedy trajectory, selected-token probabilities became high during repeated output Local book result; one path, not calibration or proven causality
Sampling produced higher distinct-trigram ratios than greedy here Local book result; eight seeds per sampled condition, repetition only
The example report fully validates and applies its advertised sampler configuration Not established; run() reports filters without applying them to sampled_index
Output quality, probability calibration, GPU numerics, other tokenisers, provider behaviour Not measured