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.
What Is Inference? ended with a sentence that looped. Run greedily for forty steps from the same prompt, GPT-2 produces 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 said this was a property of the model and the decoding rule together, not a bug in the forward pass. This chapter makes that claim testable. It follows a request through four objects:
text -> token ids -> embedding vectors -> ... -> logits -> probability distribution -> chosen token
Each step has its own rules and its own ways to fail. Correct arithmetic does not guarantee useful text, and varied text does not prove the probabilities were computed correctly.
Three measurements on GPT-2 give a taste of what is coming:
| Observation | Value |
|---|---|
| Largest error from a naive float32 softmax, on a real prompt, with no crash and probabilities still summing to one | 0.30 in absolute probability |
| Number of candidate tokens kept by top-p = 0.9, across six prompts | from 131 to 14,394 |
| Probability the model gave its own chosen token in the looping continuation | 0.34 at step 1, 0.99 at step 39 |
All three describe one checkpoint, chosen prompts and particular computations. None of them measures answer quality or how other models behave.
Where this sits
From Training to Execution identified exactly which artefact is running and showed that changing the tokeniser can change the model’s input without changing any weights. This chapter follows that input through the model’s first and last layers: text becomes ids, ids select embedding rows, the model produces scores, and a decoding rule picks one. To compare two generation results meaningfully, the tokeniser, the weights and the decoding settings must all be identified.
A note on terms. The Pi series has a separate embeddings volume about vectors used for matching and retrieval. Here, token embeddings means something narrower: the rows of a language model’s input lookup table. They are learned during training, but they are not a sentence-embedding system, and closeness between rows says nothing about retrieval quality.
The Inference Lab gains a sampling configuration and a select_token function, which together record and apply the rule that turns scores into a token.
Text to ids
The question. A model consumes integers, not characters. How does text become those integers, and does the conversion matter?
The mechanism. GPT-2 uses byte-level byte-pair encoding (BPE) with a vocabulary of 50,257 entries. The tokeniser splits text into pieces with a fixed pattern, represents each piece as UTF-8 bytes, and then applies learned merge rules that combine frequently co-occurring byte sequences into single tokens. (The original BPE idea, merging frequent adjacent units, is the background; GPT-2’s exact handling of spaces, punctuation and Unicode is specific to its implementation.)
Eleven examples. Here is what the pinned GPT-2 tokeniser does with eleven short inputs:
| 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 original text. Read the table slowly; each row teaches something:
- Spaces change token boundaries.
inferenceis two tokens;inferencewith a leading space is one, because the space is part of a learned token. So a trailing space at the end of a prompt is not neutral padding: it changes what the model sees. (Whether it changes GPT-2’s next-token ranking is untested here; exercise 2 tests it.) - Case changes identity, and sometimes count.
INFERENCEis three tokens;Inferenceandinferenceare two each. The model may learn that they are related, but the tokeniser does not promise it. - Numbers split by frequency, not by place value.
3.14159becomes3,.,14,159. That may matter for arithmetic tasks, but this table alone does not show any loss of accuracy. - Indentation costs tokens. Four spaces before
indentedproduce three standalone space tokens and thenind. Each is a complete vocabulary item. Indentation-heavy code uses more of the context budget, by an amount that depends on neighbouring text. - Unicode can split mid-character. The two characters in
推論become six ids. Decoding one id on its own may give a replacement character, because it holds only part of a UTF-8 character; decoding the full sequence restores the text. This says something about this tokeniser, not about the inherent cost of a language.
The consequence. None of this is a defect. But it means that a model’s behaviour depends on the exact id sequence, including any added special tokens and the tokeniser revision. Clients submit text; models consume ids. So context length, cache compatibility, billed tokens and token throughput only mean something under a named tokeniser and a stated counting convention. (Providers may count tokens differently from each other; this table only establishes GPT-2’s local counts.) That is why the tokeniser belongs in the artefact manifest from From Training to Execution.
Ids to vectors
The intuition. The first thing the model does with each id is look up a row in a table. That row is a vector of learned numbers that stands for the token.
The mechanism. With a vocabulary of \(V\) tokens and a hidden width of \(d\), the input embedding table \(E\) has one row per token:
For this checkpoint \(V = 50{,}257\) and \(d = 768\), so the table holds \(Vd = 38{,}597{,}376\) numbers. That is 31.0% of the model’s 124,439,808 parameters. For a small model, that is a striking share of memory. Larger architectures will have a very different fraction, and we did not measure them.
What a row is, and is not. A lookup ignores context. king fetches the same row whether the sentence is about chess or monarchy; the transformer layers build context-dependent states later. Still, comparing rows shows which tokens this checkpoint has placed near each other, measured by cosine similarity:
| 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 |
Spelling variants and related words sit close together. For contrast: cat and dog score 0.55, cat and the score 0.21; king and queen score 0.66, king and banana 0.26. These are hand-picked examples, an exploration of one table rather than a test of meaning.
One matrix used twice
GPT-2 uses the same table again at the very end. Its output head, which produces a score for every vocabulary entry, shares storage with the input table. This is called weight tying.
If \(\mathbf h\) is the model’s final hidden state and \(\mathbf e_i\) is row \(i\) of the table, the score for token \(i\) is their dot product:
- Memory saved. The experiment confirmed shared storage by checking tensor pointers. An untied output matrix would need another 38,597,376 float32 values: 154,389,504 bytes (154.4 MB, about 147.2 MiB).
- Work not saved. Computing all those scores is about 38.6 million multiply-accumulates (about 77.2 million FLOPs) per position. That is why it pays not to project every position when only the last one is needed. (This is an arithmetic count, not a timing.)
Note that the output score is a raw dot product, which depends on vector length as well as direction. It is not the cosine similarity used in the neighbour table, and it should not be read as a “semantic similarity”. Press and Wolf give research context for weight tying.
Vectors to scores
The model’s output for the next token is a vector of logits \(\mathbf z\in\mathbb R^V\): one unnormalised score per vocabulary entry. On six recorded GPT-2 prompts, every logit was negative, and the largest logit per prompt ranged from about −102.1 to −31.9.
That looks alarming, but mathematically it is harmless, as the next section shows.
Softmax ignores a common offset
Softmax maps scores to probabilities:
But computers are not mathematics
Exponentials of large numbers overflow, and exponentials of very negative numbers underflow to zero. A naive softmax that exponentiates first and divides second can fail:
| 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 |
(These failures are from the chapter’s Python example and a float32 overflow probe. Tensor libraries may instead return infinities or NaNs.)
The fix uses the invariance we just proved. Let \(m = \max_j z_j\) and subtract it before exponentiating:
The softmax that fails quietly
Crashes and NaNs are easy to catch. The dangerous case is a softmax that returns plausible-looking numbers that are wrong.
Why it can happen. IEEE-754 float32 has a smallest normal positive value of about \(1.175\times10^{-38}\). Below that, subnormal values reach down to about \(1.4\times10^{-45}\), but with fewer and fewer significant digits. Since \(e^{-100}\approx3.7\times10^{-44}\), exponentiating GPT-2’s logits directly lands right in that low-precision zone. (Some hardware flushes subnormals straight to zero, so the exact failure depends on the implementation.)
The experiment. We took real float32 logits from six GPT-2 prompts, computed torch.exp(logits32) and divided by the sum, then compared each result with torch.softmax(logits32). None produced NaNs, and every result summed to about one. But look at the errors:
| 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}\) |
Broadly, the lower the logits sit, the smaller the denominator and the larger the error, though not in strict order: Once upon a erred more than def fibonacci… despite a slightly higher maximum. For the last prompt, at least one token’s probability was off by about 0.30, yet the distribution still summed to one.
The consequence. A test that only checks “probabilities sum to one” will not catch this bug. A greedy decoder might still pick the same top token, while a sampler draws from a badly distorted distribution. (We have not shown that any real provider uses a naive softmax, or measured an effect on answer quality.)
It also shows why tidy unit-test inputs are not enough. The toy logits [2.0, 1.0, 0.5, 0.1] never touch subnormal arithmetic. The chapter’s pure-Python stable softmax agreed with a float64 PyTorch reference to within \(1.3\times10^{-15}\) on all 50,257 logits for each of the six prompts. That supports agreement on this workload, not a proof for every input or an error bound for float16 or bfloat16. A stronger test suite would include extreme offsets, ties, non-finite values, fully masked candidates and each target dtype. Quantization and Numerical Precision takes up reduced precision.
Scores to a distribution
For finite logits with at least one valid candidate, softmax gives the model’s next-token distribution. It is the model’s view, not a calibrated probability that something is true. Its shape matters, because it determines what the decoding rules below keep and sample. Six hand-chosen prompts show the range:
| 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 how spread out the distribution is. A point mass has entropy zero; a uniform distribution over all 50,257 tokens has \(\ln(50{,}257)\approx10.82\) nats. These prompts ranged from about 3.89 to 8.82. A low-entropy distribution is concentrated, not necessarily correct.
Two lessons from the table matter for the rest of the book.
The top next token is not the answer. After The capital of France is, GPT-2’s top next token was the (0.085); Paris ranked fifth (0.032). So greedy decoding does not say Paris next. That is a fact about a 124-million-parameter model from 2019, used here as an inspectable baseline, not an assistant. Faster or more faithful computation should leave this ranking alone, within a stated tolerance. Changing the weights, prompt, precision or decoding rule can change it. Judging whether one answer is better than another needs an evaluation task, not a next-token table.
Top-k and top-p cut the candidate list in different ways.
- Top-p = 0.9 keeps the smallest set of most-probable tokens whose probabilities add up to 0.9. Here that set ranged from 131 tokens to 14,394. The largest came from the one-word prompt
The, with no start-of-text token in front; even without it, the range is 131 to 1,956. - Top-k = 40 always keeps at most 40 tokens. But those 40 held 82% of the probability on the code prompt and only 38% on the technical one.
Neither is better in general. Top-k fixes a count; top-p fixes a probability target. Neither fixes how much probability is thrown away, the resulting entropy or the quality of the output. And with ties, masking or minimum-token rules, implementations can differ; this table measures the Lab’s rule.
Temperature
The intuition. Temperature is a dial between “always pick the favourite” and “pick almost anything”.
The mechanism. Divide the logits by \(T\) before the softmax:
A worked example. Here are the same saved logits for Once upon a, at five 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 |
Halving the temperature from 1.0 to 0.5 shrinks the 0.9 nucleus from 1,956 tokens to two. Doubling it to 2.0 widens it to 19,623. The model was not rerun: temperature reshapes the distribution after the computation. (Over many steps, of course, a different choice changes the next input, and so all later computation.)
Zero is a convention. The formula is undefined at \(T = 0\). Many APIs treat zero as “greedy”, but that is a convention, not a value of the formula. The Lab uses an explicit greedy flag instead, and breaks ties by choosing the lowest token id. That makes greedy selection deterministic for a given logit vector, though it does not guarantee identical logits across models, devices, batch shapes or kernels. The sampling path requires \(T > 0\).
From distribution to choice
The Lab’s sampler applies its rules in a fixed order:
flowchart LR
L[logits] --> T[divide by temperature]
T --> K[top-k mask]
K --> P[top-p mask<br/>over remaining candidates]
P --> N[normalise]
N --> D[seeded random draw]
D --> I[token id]
Order matters. Top-p is computed over the candidates that survive top-k, so reversing the two can select a different set. Other libraries use different processors, defaults and orders. To reproduce a sample from another framework you need its version and its effective generation configuration; recording top_p=0.9 alone is not enough.
The draw itself uses a fresh random.Random(seed). Same logits, same settings, same Python implementation and same seed give the same id.
A sanity check. On a toy four-token distribution, 10,000 different seeds gave empirical frequencies within 0.0076 of the expected probabilities, against a largest binomial standard error of about 0.0049. With top-k = 2, the two excluded tokens never appeared, and the two kept tokens came up about 0.741 and 0.260 of the time, against theoretical values near 0.731 and 0.269. Nothing looks wrong at this sample size, but this is a sanity check, not a statistical audit.
A deliberate shortcut. This prototype reseeds on every call. (The 40-step diversity experiment below builds a different seed from the run id and the step number.) A production runtime needs an explicit policy for per-request random streams, deterministic replay, and what cancellation or batching does to the sequence of random numbers. Correctness, Determinism and Reproducibility returns to this.
The loop, explained
We now have the tools to look inside the opening loop. A 40-step greedy run from the Chapter 1 prompt recorded, at every step, the probability of the chosen token, the entropy and the size of the 0.9 nucleus:
| 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 |
The values wobble from step to step, but the trend is plain. As the phrase repeats, the model grows more and more sure of its next token: above 0.91 from step 31 onwards, with a nucleus of one.
That pattern fits a simple story. Greedy decoding feeds the top token back into the prefix; the repeated prefix makes the same continuation even more likely; and the loop sustains itself. Holtzman and colleagues documented this kind of self-reinforcing degeneration. One trajectory is consistent with the story but does not prove the cause. That would need matched prompts, alternative decoding rules and repeated runs.
Does sampling escape the loop?
To compare decoding rules we need a measure of repetition. The distinct-trigram ratio of 40 generated tokens is the number of distinct three-token sequences divided by the 38 possible. A ratio of 1.0 means no trigram repeats. It does not mean the text is coherent, correct or useful.
| 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 |
(Greedy is deterministic, so it was run once; each sampled setting was run with eight seeds.)
Greedy had 8 distinct trigrams out of 38, a ratio of about 0.21. Every sampled setting repeated far less. But one unfiltered \(T=1\) sample contained the phrase “delegated as an recurrence model”: no repetition, and no sense either. That is the trap in a diversity-only score: it rewards nonsense that does not repeat. Factuality, task success, style and constraints are evaluated in later chapters.
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 fields, and select_token uses them to choose an id.
Recorded is not validated. The dataclass is frozen, so a configuration cannot change after creation, but nothing checks that it makes sense:
- The constructor does not validate temperature, or conflicts between
greedyand the sampling options. Some invalid settings fail only when a draw is attempted, and the greedy path skips sampling checks altogether. select_tokendoes not explicitly check for non-finite logits or an empty, fully masked candidate set.
A known mismatch to fix. The run() report in probability.py advertises top-k and top-p values in its metadata, but its sampled_index comes from an unfiltered sample_index(logits, seed=seed) call. The candidate sets it reports are descriptive; they were not applied to that draw. So this report must not be taken as evidence that filtered sampling works. Exercise 7 repairs and tests this before the Lab treats a recorded configuration as reliable provenance.
Together with the request record from What Is Inference? and the manifest from From Training to Execution, the Lab now has the fields needed to describe an experiment fully. No end-to-end run record containing all of them has been demonstrated yet.
The sampler runs on Python lists with Python’s random generator; it is not a GPU or concurrent-serving implementation. It also lacks production stop conditions, penalties, full validity checks and a versioned decoding-policy schema. A future tensor sampler must show parity with reference distributions and document how dtype, ties, masks and random streams change behaviour. It should not just adopt the interface and declare itself equivalent. Structured Outputs and Constrained Decoding covers constrained outputs, and Correctness, Determinism and Reproducibility covers reproducibility across environments.
Limits of this chapter’s evidence
- One small model, from 2019. The distributions and repetition behaviour are GPT-2’s. Entropy, rank and loop frequency were not measured for larger, instruction-tuned or contemporary models, and no claim is made about them.
- Six selected prompts. They were chosen to contrast, not to represent typical use.
Theis an especially short context. - One tokeniser. GPT-2’s byte-level BPE does not predict exact counts for other tokenisers, scripts or model families. The trailing-space effect and any effect of number splitting on arithmetic were not tested.
- Embedding neighbours are not a semantic benchmark. They describe one learned table; they do not test retrieval or sentence meaning.
- Repetition is not quality. Distinct trigrams measure local n-gram variety only, and eight samples per setting cannot rank decoding policies in general.
- No calibration claim. A next-token probability of 0.99 is not a 99% chance of a correct answer. No calibration dataset or scoring rule was evaluated.
- Numerics depend on dtype and implementation. The naive-softmax failure was shown in float32 and the reference comparison in float64. GPU kernels, float16, bfloat16, fused sampling and masking edge cases were not tested.
- The sampling sanity check is small. 10,000 draws on a toy distribution cannot show that every configuration is unbiased, and it did not test per-request random streams under concurrent generation.
What you should now be able to do
- Tokenise a string with GPT-2’s byte-level BPE and explain why a change of case or spacing can change the ids and their count.
- Say what the embedding table is and what it is not, and work out its share of a model’s parameters.
- Explain why softmax ignores a common shift in the logits, and why that makes subtracting the maximum safe.
- Give an example of a softmax that is wrong without crashing, and say what in the output would reveal it.
- Explain what temperature, top-k and top-p each change, and state the order in which the Lab applies them.
- Explain how a greedy repetition loop can arise without any arithmetic defect, and why a rising next-token probability is not a calibrated correctness claim.
So far we have treated the middle of the pipeline, from embedding vectors to logits, as a black box. The Transformer as a Computation opens it: what operations a transformer layer actually performs, how many parameters and FLOPs each one involves, and where the time of a forward pass goes.
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
- 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.
- Compare the next-token distributions for
The capital of France isand 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? - Add
min_pfiltering (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. - 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.
- Take the 14,394-token nucleus for
Theand 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? - 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.
- Inspect
probability.py’srun()output. Reproduce the mismatch between reported top-k/top-p settings and its unfilteredsampled_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
- Neural Machine Translation of Rare Words with Subword Units — Sennrich, Haddow and Birch (ACL 2016); primary research supporting learned subword units. It does not specify GPT-2’s byte-level implementation.
- Using the Output Embedding to Improve Language Models — Press and Wolf (EACL 2017); primary research motivating shared input/output embeddings and their parameter savings.
- The Curious Case of Neural Text Degeneration — Holtzman and colleagues; primary research on repetition under likelihood-focused decoding and nucleus sampling.
- GPT-2 tokenizer implementation — original implementation context for byte-level tokenisation and its model family; not evidence of the book’s local results.
- Transformers generation strategies — API-level context for sampling strategies. Exact processor ordering must be checked against the actual library version.
- PyTorch
log_softmax— numerical API reference; agreement with it on six prompts remains a book measurement.
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 |