IV-45 / Part XI · Autoregressive Inference
From Logits to the Next Token
Compute stable probabilities directly from editable logits, select the greatest computed score, and explain compact-index ties, active vocabulary, rounding and nonfinite inputs.
Review the ideas this chapter uses
A model has produced several scores for what could come next. A larger score expresses a stronger preference, but a score is not yet a probability, and a probability is not yet a decision. We will compute the distribution from the scores, then apply one explicit rule to choose a token.
Learning objective: Calculate greedy selection and deterministic tie resolution.
From Logits to the Next Token
These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.
Complete results from this trace’s starting inputs
Starting inputs for these results
- V
- 3
- z0
- 1
- z1
- 0
- z2
- 0
- z3
- 0
- z4
- 0
nextID 97. nextProbability 0.5761168847658291. classCount 3. logsumexp 1.551444713932051. Validate all raw logits before selecting active classes. Inactive raw logits still validate and remain visible as metadata. This direct lesson has no text, target, loss, training, seed or sampling.. classCount 3. rawLogitCount 5
Validate all raw logits before selecting active classes
V in {3,4,5}; every raw z in [-40,40]; activeZ=rawZ[:V]
Inactive raw logits still validate and remain visible as metadata. This direct lesson has no text, target, loss, training, seed or sampling.
Inputs
- V
- 3
- z0
- 1
- z1
- 0
- z2
- 0
- z3
- 0
- z4
- 0
Outputs
- classCount
- 3
- rawLogitCount
- 5
Scores → stable probabilities → one greedy decision
A logit is an unnormalized score. This lab treats your finite logits as its complete inputs. It has no text, tokenizer, target, training or random draw. The active compact class count is 3; raw five-slot storage remains visible even when some slots are inactive.
Greedy chose compact row 0, a (ID97), with stored probability 0.5761168847658291. The maximum computed input logit is 1. Exact logit ties retain the smallest compact index; public IDs are labels, not sorting priorities.
Inspecting compact class 0, public ID97. This selector only reads the saved record; it leaves exercise answers unchanged.
Trace operation setup is selected above. A matching operation row below is marked current when present; class inspection is independent.
| Compact row | Raw logit | Active public ID | Computed active logit | Shifted | exp(shifted) | Probability | Greedy? |
|---|---|---|---|---|---|---|---|
| 0 | 1 | a / ID97 | 1 | 0 | 1 | 0.5761168847658291 | Yes |
| 1 | 0 | b / ID98 | 0 | -1 | 0.36787944117144233 | 0.21194155761708544 | No |
| 2 | 0 | EOS / ID512 | 0 | -1 | 0.36787944117144233 | 0.21194155761708544 | No |
| 3 | 0 | Inactive raw slot | Not computed | Not computed | Not computed | No probability | Not eligible |
| 4 | 0 | Inactive raw slot | Not computed | Not computed | Not computed | No probability | Not eligible |
For inspected class0, subtract saved maximum 1 to obtain 0, exponentiate to 1, then divide by saved denominator 1.7357588823428847 to obtain 0.5761168847658291. The denominator adds every active exponential left to right. logS=0.5514447139320511; logsumexp=max+logS=1.551444713932051.
Subtracting the maximum keeps every shifted logit nonpositive, so raw exp(40) is unnecessary here. No epsilon, clipping or display rounding is fed back into P; binary64 arithmetic still rounds. Tiny positive probabilities are retained. Stored probabilities can round to the same value for distinct input logits; greedy therefore compares the original computed inputs.
| Operation | Equation and reason | Actual inputs | Actual outputs |
|---|---|---|---|
| choice_max | max=max(z0,...,z[V-1]) All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability. | z0=1 z1=0 z2=0 | max=1 |
| choice_exp_0 | shifted=logit-max; term=exp(shifted) No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it. | c=0 logit=1 max=1 | shifted=0 term=1 |
| choice_normalize | running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS The denominator adds terms in ascending compact class order. Every actual running sum is saved. | term0=1 term1=0.36787944117144233 term2=0.36787944117144233 max=1 | running0=1 running1=1.3678794411714423 running2=1.7357588823428847 denominator=1.7357588823428847 logS=0.5514447139320511 lse=1.551444713932051 |
| choice_probability_0 | probability=term/S This stored binary64 probability is displayed without feeding its formatting back into arithmetic. | c=0 term=1 denominator=1.7357588823428847 | probability=0.5761168847658291 |
| choice_argmax | strict greater-than updates the winner; exact ties retain lowest compact index Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order. | z0=1 z1=0 z2=0 | nextRow=0 nextID=97 nextProbability=0.5761168847658291 |
Try V5 and z2=z3=1 with the other logits0: EOS512 wins at compact index2, even though ab256 has a smaller public ID. A later top-k/top-p sorting rule orders tied candidates by public ID; that is a different declared operation. Try V3 with z0=0, z1=5e-324, z2=0 to see distinct logits whose stored probabilities round to a tie. All five raw fields still validate when inactive.
Only score/probability and exact decision records are inspected here. A logit translation preserves ideal-real probabilities, but floating subtraction can change low bits. Argmax is a discrete decision, with no gradient asserted. The inspector retains rawZ[5], actual active arrays[V], scalar storage, axes, precision and provenance.
Inspect tensor shapes and full precision
All computed outputs
- nextID
- 97
- nextProbability
- 0.5761168847658291
- classCount
- 3
- logsumexp
- 1.551444713932051
- nextRow
- 0
- max
- 1
- denominator
- 1.7357588823428847
- logS
- 0.5514447139320511
- rawLogitCount
- 5
- setup_classCount
- 3
- setup_rawLogitCount
- 5
- choice_max_max
- 1
- choice_exp_0_shifted
- 0
- choice_exp_0_term
- 1
- choice_exp_1_shifted
- -1
- choice_exp_1_term
- 0.36787944117144233
- choice_exp_2_shifted
- -1
- choice_exp_2_term
- 0.36787944117144233
- choice_normalize_running0
- 1
- choice_normalize_running1
- 1.3678794411714423
- choice_normalize_running2
- 1.7357588823428847
- choice_normalize_denominator
- 1.7357588823428847
- choice_normalize_logS
- 0.5514447139320511
- choice_normalize_lse
- 1.551444713932051
- choice_probability_0_probability
- 0.5761168847658291
- choice_probability_1_probability
- 0.21194155761708544
- choice_probability_2_probability
- 0.21194155761708544
- choice_argmax_nextRow
- 0
- choice_argmax_nextID
- 97
- choice_argmax_nextProbability
- 0.5761168847658291
- finish_nextID
- 97
- finish_nextProbability
- 0.5761168847658291
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
RawZ
ModelRow=5 · float64 · display precision 8 · All five validated editable raw logits, including inactive slots.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
ClassIDs
Class=3 · int32 · display precision 0 · Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.
| Storage index | Value |
|---|---|
| 0 | 97 |
| 1 | 98 |
| 2 | 512 |
Z
Class=3 · float64 · display precision 8 · Actual finite computed input logits; no derived-input clipping.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
Shifted
Class=3 · float64 · display precision 8 · Z minus the saved active maximum.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | -1 |
| 2 | -1 |
Terms
Class=3 · float64 · display precision 8 · Actual exp(Shifted), before normalization.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0.36787944117144233 |
| 2 | 0.36787944117144233 |
Denominator
Scalar=1 · float64 · display precision 8 · Actual left-to-right sum of active shifted terms.
| Storage index | Value |
|---|---|
| 0 | 1.7357588823428847 |
LogS
Scalar=1 · float64 · display precision 8 · Natural logarithm of Denominator.
| Storage index | Value |
|---|---|
| 0 | 0.5514447139320511 |
LSE
Scalar=1 · float64 · display precision 8 · Saved max+LogS in binary64.
| Storage index | Value |
|---|---|
| 0 | 1.551444713932051 |
P
Class=3 · float64 · display precision 8 · Terms/Denominator for active classes only, without clipping or padding.
| Storage index | Value |
|---|---|
| 0 | 0.5761168847658291 |
| 1 | 0.21194155761708544 |
| 2 | 0.21194155761708544 |
NextRow
Decision=1 · int32 · display precision 0 · Lowest compact index among highest computed logits.
| Storage index | Value |
|---|---|
| 0 | 0 |
NextID
Decision=1 · int32 · display precision 0 · Public class ID gathered at NextRow.
| Storage index | Value |
|---|---|
| 0 | 97 |
NextProbability
Decision=1 · float64 · display precision 8 · Stored P gathered at the computed-logit winner.
| Storage index | Value |
|---|---|
| 0 | 0.5761168847658291 |
Change the actual logits in [-40,40] and the active prefix V3..5. The reset logits [1,0,0] favor a97. With V5 and all logits0, all five probabilities are equal and compact0 wins. With z2=z3=1 and the others0, the compact tie rule chooses EOS512 before ab256.
All five raw logits validate even when inactive. Nonfinite or out-of-range inputs show an unavailable result. This direct lesson performs no text processing, sampling, gradient or training. Raw edits, reset and trace selection clear answers; the independent class inspector leaves them unchanged.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
At reset, V=3 and the active logits are (1,0,0) for a, b and EOS. Let e=exp(1), the exponential of1. Their probabilities are (e,1,1)/(e+2), and the selected ID is97. Edit a score and follow its actual shift, exponential term and normalized probability before checking the winner. These controls are direct scores: this lesson does not run a neural block to produce them.
Use Active compact class to inspect to inspect one saved class while keeping the complete distribution visible. This selector preserves graded answers and stays within the actual active shape. Calculation step selects a saved trace operation independently of the class inspector. Raw score or V edits, Reset example and trace navigation clear grades so feedback belongs to the current calculation. The live arithmetic question follows the actual winning class, not whichever class you choose to inspect.
Review IV-44 — Prefill and Single-Token Decode for where a prefix’s final scores come from, and Book II’s VII.6 — Logits and softmax for logits and softmax. Book III’s III-16 — Multiclass Classification and Softmax Regression connects the same normalization to multiclass classification. No target, training step, seed or random sample is involved here.
Name each class before touching its score
A logit is a finite real score before normalization. A class is one possible output item; a token ID is its public integer name. The vocabulary is the ordered set of active classes. A compact index addresses an entry of the small array, independently of the public ID’s magnitude.
| Compact class c | Public ID | Piece | Active when |
|---|---|---|---|
| 0 | 97 | a | every supported V |
| 1 | 98 | b | every supported V |
| 2 | 512 | EOS, end of sequence | every supported V |
| 3 | 256 | ab | V=4 or5 |
| 4 | 257 | abab | V=5 |
Choose integer V=3,4,5; the active map is the first V entries of this table in this order. It is never sorted numerically by public ID. A tensor is an array with named dimensions; here active logits z and probabilities P have shape [V], axis Class. The full raw score storage has shape [5], axis ModelRow. All five fields z0,z1,z2,z3,z4 remain stored and validated even when only three participate. An inactive probability is absent, not a zero-probability member of the distribution.
For example, z2 is EOS’s score because compact class2 maps to public ID512. It is not the score of token ID2. The control V changes which entries actually enter the denominator. Increasing V can change every old probability without changing any old score: a newly active class contributes its own positive term.
Derive the stable distribution
For a class c, mathematical softmax is
The index j visits every active class in order; exp(x) means the exponential . The denominator normalizes relative positive weights to sum to1. Adding logits or dividing each score by their sum would not work: logits may be zero or negative, and their sum need not be a positive normalizer.
Direct exponentiation can create unnecessarily large numbers. Let m be the maximum active logit, d the shifted logits, w the exponential terms and S their sequential sum:
Here Sc denotes a running denominator before adding class c; it is not a separate probability. The implementation records every running value, then divides each term by the final S. In exact real arithmetic d is nonpositive, every w lies in (0,1], and at least one term is exp(0)=1. Thus 1≤S≤V, so division is well-defined. Finite intermediate checks still matter in software; mathematical formulas do not validate hostile inputs.
Why does subtracting m preserve the distribution? Factor exp(zc)=exp(m)exp(zc−m) in each numerator and in every denominator term. The common factor exp(m) cancels. This changes the numerical route without changing the real probability. The natural logarithm, ln, reverses exp. The saved log-sum-exp, abbreviated LSE, is
LSE is a useful normalization quantity, not a selected token or a loss. No observed target has been supplied to define a target loss. The trace distinguishes the maximum, each shift, each term, every running sum, logS, LSE, every P and the final selection operands.
Work the entire default in compact order
For V=3 with z=(1,0,0), m=1. The shifts are (1−1,0−1,0−1)=(0,−1,−1) and the terms are (1,1/e,1/e). Addition starts at0:
| Compact class | Public ID | Logit | Shift | Exponential term | Denominator after adding this term |
|---|---|---|---|---|---|
| 0 | 97 | 1 | 0 | 1 | 0+1=1 |
| 1 | 98 | 0 | −1 | 1/e | 1+1/e |
| 2 | 512 | 0 | −1 | 1/e | (1+1/e)+1/e=1+2/e |
Let Z=e+2. The final shifted denominator is S=1+2/e=Z/e. Dividing each saved term gives
The maximum is uniquely at compact class0. Its public ID is97 and its stored selection probability is P0=e/Z. Also logS=ln(1+2/e), so LSE=1+ln(1+2/e)=ln(e+2). The first four summaries are nextID, nextProbability, classCount, logsumexp, with exact real default expressions 97, e/Z, 3, ln Z.
These expressions are hand derivations. Stored arrays use binary64 arithmetic and library exp/ln, whose values are approximations. A printed decimal is another rounding layer. The model never uses a shortened printed probability as a later operand.
Greedy means greatest computed input logit
An argmax is an index achieving the greatest value. Greedy selection chooses that greatest-scoring class now, without considering a sequence of future decisions. It does not guarantee that a whole continuation will have the largest possible probability, and it does not draw a random item from P.
This lesson starts the winner at compact index0, visits later classes in ascending compact order and replaces the winner only for a strictly greater computed logit. Equal logits therefore keep the lowest compact index. Finally the winner is mapped to its public ID and its already calculated probability is saved. Choosing a class does not change that probability to1 or erase the other probabilities.
In exact real arithmetic exp is strictly increasing, so the greatest logit has the greatest softmax probability. In floating-point arithmetic two different logits can yield identical stored probabilities. This is why the implementation compares the actual input logits, not rounded display values and not an argmax reconstructed from P.
For a sharp counterexample, consider active scores (0, Number.MIN_VALUE, 0), V=3. Number.MIN_VALUE names the smallest positive binary64 number. Class1’s score is strictly larger than the other two. The shifted exponentials can all round to1 and the stored probabilities can all equal the same binary64 approximation to1/3. The correct winner under the declared rule is still b/98. A visible probability tie cannot override a strict score inequality. This case explains the contract; it is not a claim that a browser run was performed.
Transfer the rule to five classes and a public-ID trap
Set V=5 and all five scores to0. Maximum0 gives shifts0, five terms1 and running sums1,2,3,4,5. Each P=1/5, logS=ln5 and LSE=ln5. Compact index0 wins the exact tie, so nextID=97 with probability1/5. Equal scores require no random seed because the selection rule is deterministic.
Now keep V=5, set z2=z3=1 and the other three scores0. The maximum1 occurs at EOS/class2 and ab/class3. With q=exp(−1), terms are (q,q,1,1,q) and the ordered denominator is ((((0+q)+q)+1)+1)+q. In exact real arithmetic put Z=2e+3; then
Class2 is encountered before class3 and equal score1 does not replace it. The selected token is EOS/512, even though ab’s public ID256 is numerically smaller. “Lowest compact index” and “lowest public ID” are different policies for this map. The later top-k/top-p filtering lesson uses its separately declared score-descending, public-ID-ascending sorting rule. Do not import that future sorting rule into this greedy argmax.
EOS here is an output class and can win normally. This chapter records the choice. A generation loop must separately decide whether to stop and whether to feed a chosen token back to a model. IV-44’s terminal EOS policy is such a wrapper decision; direct probability normalization alone neither appends an input nor executes a decode call.
Change an active set, not an invisible score
Reset and keep raw scores (1,0,0,0,0). At V=3, P=(e,1,1)/(e+2). Raise V to4: a fourth actual term exp(−1) enters, giving probabilities (e,1,1,1)/(e+3). At V=5 they are (e,1,1,1,1)/(e+4). The winner remains a, but its probability falls because the denominator includes more competing items. Stored raw zeros for inactive fields were never probabilities padded onto the shorter row.
For an inactive-field experiment, keep V=3 and change valid z4 to40. Full raw storage changes, but active logits, active probabilities and selection do not depend on z4. Then change V to5: that same z4 becomes active and wins. Every raw z field still validates at V=3; an inactive nonfinite value is not an acceptable state. Compare the dependent outputs rather than claiming the entire record remains identical after a raw edit.
Tiny probabilities and translation need careful language
At V=3 set logits (−40,40,−40). The maximum40 gives shifts (−80,0,−80). Let q=exp(−80)>0. The ordered denominator is ((0+q)+1)+q; all probabilities are (q,1,q)/S. A narrow table may print the first and last values as0. They remain positive stored values in this bounded example and are not clipped to0. Likewise the large stored probability may round to1 while tiny other entries remain positive. Exact-real identities and rounded sums are different statements.
If the same finite constant k is added to every active logit, exact-real softmax stays unchanged: both numerator and denominator gain exp(k). LSE increases by k, and greedy order stays unchanged in real arithmetic. Try translating the reset active scores (1,0,0) to (3,2,2), all within the permitted bounds. Both have shifted row (0,−1,−1). Arbitrary floating-point additions can round unequal values together or change low bits, so translation is not a promise of universal bitwise equality. Do not feed display-rounded scores or probabilities back as if they were original inputs.
Validity and the limits of this decision
Raw V must be an actual finite integer3..5. All five z values must be actual finite numbers in [−40,40], checked in raw order even when inactive. Booleans, numeric strings, NaN and infinities are not numbers to coerce or repair. Nonnumeric/nonfinite values produce NONFINITE; finite out-of-domain values produce INVALID_INPUT. The state must have exactly its own declared data fields, without extra fields, symbols, missing entries or getters. An invalid draft must not leave an old successful result presented as its answer.
The direct chapter bounds make shifted differences at worst−80 and keep these exponential terms representable without clipping. The reusable numerical distribution helper also accepts finite derived logits for later lessons; it must not silently apply this raw control’s [−40,40] restriction to a later temperature-scaled calculation. Intermediate nonfinite arithmetic remains an error, not an excuse to manufacture a uniform distribution.
A derivative is a rate of change with respect to a continuous input. Softmax probabilities vary smoothly with finite logits. For fixed V, their familiar real derivative is ∂Pi/∂zj=Pi(I(i=j)−Pj), where I is1 when i=j and0 otherwise. Argmax changes abruptly when a winner changes; the discrete token ID, tie rule and class-count control are not differentiable outputs of this lesson. No derivative or finite-difference validation is claimed by displaying the probabilities.
The hand cases above provide mathematical expectations for later independent checks. Structural checks, independent Decimal expectations, smooth-probability finite differences, Python/TypeScript parity and browser interaction checks address distinct evidence. Reading a formula or a test declaration is not executing it.
Read the maintained direct Python source
These two disclosures show the entire actual local Python dependency closure for this chapter. They need NumPy and the standard library. No neural or tokenizer file is imported merely to obtain the literal five-ID map; the direct scores above are the actual numerical inputs.
1. Chapter wrapper — code/python/p11/iv45.py. derive_iv45 projects the direct calculation into the chapter’s detached record and supports defaults, a complete replacement JSON state, or - for JSON on standard input. Keep it beside its helper so the file-relative loader can find the maintained calculation.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV45 — From Logits to the Next Token, full canonical chapter record.
Keep choice_reference.py adjacent. NumPy and the standard library are the
only dependencies. Default, complete replacement JSON and '-' stdin all
return the full ordered record. All execution and checks remain DEFERRED.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
_path = Path(__file__).resolve().with_name("choice_reference.py")
_spec = importlib.util.spec_from_file_location("_p11_choice_reference", _path)
if _spec is None or _spec.loader is None:
raise ImportError(f"Cannot load canonical dependency: {_path}")
_helper = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_helper)
DEFAULT_IV45 = MappingProxyType(dict(_helper.DEFAULT_IV45))
@_helper.guarded
def derive_iv45(state):
"""Return the ordered raw/active distribution, greedy choice and full trace."""
return _helper.compute_choice(state)
def source_self_check():
"""DEFERRED wrapper-only checks; never invokes another file's self-check."""
assert __debug__, "Deferred checks require assertions enabled."
assert Path(_helper.__file__).resolve() == _path
state = dict(DEFAULT_IV45)
result = derive_iv45(state)
assert list(result) == ["status", "outputs", "steps", "tensors"]
summary = ["nextID", "nextProbability", "classCount", "logsumexp", "nextRow", "max", "denominator", "logS", "rawLogitCount"]
assert list(result["outputs"]) == summary + [f"{step['id']}_{key}" for step in result["steps"] for key in step["outputs"]]
assert result["outputs"]["nextID"] == 97 and result["outputs"]["classCount"] == 3
assert [step["id"] for step in result["steps"]] == ["setup", "choice_max", "choice_exp_0", "choice_exp_1", "choice_exp_2",
"choice_normalize", "choice_probability_0", "choice_probability_1", "choice_probability_2", "choice_argmax", "finish"]
assert [record["id"] for record in result["tensors"]] == ["RawZ", "ClassIDs", "Z", "Shifted", "Terms", "Denominator", "LogS", "LSE", "P", "NextRow", "NextID", "NextProbability"]
assert all(list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"] for step in result["steps"])
assert all(list(record) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"] for record in result["tensors"])
tensors = {record["id"]: record for record in result["tensors"]}
assert tensors["RawZ"]["values"] == [1, 0, 0, 0, 0] and tensors["ClassIDs"]["values"] == [97, 98, 512]
assert tensors["P"]["shape"] == [3]
assert all(record["dtype"] == ("int32" if record["id"] in ("ClassIDs", "NextRow", "NextID") else "float64") for record in result["tensors"])
assert all(record["precision"] == (0 if record["dtype"] == "int32" else 8) for record in result["tensors"])
inactive = derive_iv45({**state, "z3": 40, "z4": -40})
assert inactive["tensors"][1:] == result["tensors"][1:] and inactive["tensors"][0]["values"] == [1, 0, 0, 40, -40]
assert inactive["outputs"] == result["outputs"]
tied = derive_iv45(dict(V=5, z0=0, z1=0, z2=1, z3=1, z4=0))
assert len(tied["steps"]) == 15 and len(tied["tensors"]) == 12
assert tied["outputs"]["nextRow"] == 2 and tied["outputs"]["nextID"] == 512
for raw in ({}, {**state, "extra": 0}, [], None):
fault = derive_iv45(raw)
assert list(fault) == ["status", "code", "reason"] and fault["code"] == "INVALID_INPUT"
result["tensors"][1]["values"][0] = -1
result["steps"][0]["inputs"].clear()
result["outputs"].clear()
repeated = derive_iv45(state)
assert repeated["tensors"][1]["values"] == [97, 98, 512] and repeated["steps"][0]["inputs"]
assert repeated["outputs"]["nextID"] == 97 and state == dict(DEFAULT_IV45)
if __name__ == "__main__":
_helper.run(derive_iv45, DEFAULT_IV45)
2. Direct distribution — code/python/p11/choice_reference.py. choice_state checks V and every raw score before selecting the active prefix. compute_choice forms real float64 score arrays and int32 class IDs. direct_distribution checks dense inputs, stores the maximum and each shifted exponential, accumulates the denominator left to right, saves logS/LSE and every normalized P, then chooses from the original computed logits using strict greater-than. ChoiceTrace saves detached operand/result dictionaries; formatting a table is not part of this calculation.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Direct logits -> stable probabilities -> strict-logit greedy choice.
NumPy float64/int32 arrays are the actual storage. Scalar binary64 arithmetic
preserves exp, left-to-right denominator and division order. No neural/tokenizer
import is needed for the literal five-ID model contract. Full ordered chapter
records follow the owner-adopted A inventory. All execution remains DEFERRED.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np
ALL_IDS = (97, 98, 512, 256, 257)
DEFAULT_IV45 = MappingProxyType(dict(V=3, z0=1, z1=0, z2=0, z3=0, z4=0))
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
"""No coercion, bools, custom scalar conversions, infinities or NaNs."""
if type(value) not in (int, float):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = float(value)
except (OverflowError, ValueError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not math.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
def choice_state(state):
"""Validate all six own fields in raw order, including inactive logits."""
if type(state) is not dict:
raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly V,z0,z1,z2,z3,z4.")
if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV45):
raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive logits.")
checked = {}
for key in DEFAULT_IV45:
value = finite(state[key], key)
if key == "V":
if not value.is_integer() or not 3 <= value <= 5:
raise NumericalFault("INVALID_INPUT", "V must be an integer from 3 to 5.")
checked[key] = int(value)
else:
if not -40 <= value <= 40:
raise NumericalFault("INVALID_INPUT", f"{key} must be between -40 and 40.")
checked[key] = value
return checked
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return dict(status="unavailable", code=error.code, reason=str(error))
except (OverflowError, FloatingPointError) as error:
return dict(status="unavailable", code="NONFINITE", reason=str(error))
return call
class ChoiceTrace:
"""Finite detached scalar records; no implicit invocation of self-checks."""
def __init__(self):
self.steps = []
def add(self, identifier, label, equation, explanation, inputs, outputs):
if len(self.steps) >= 512:
raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
inputs={key: finite(value, key) for key, value in inputs.items()},
outputs={key: finite(value, key) for key, value in outputs.items()}))
def _dense(values, label):
"""Inspect both containers before either helper operand is read."""
if type(values) is np.ndarray:
if values.ndim != 1 or values.dtype.kind not in "iuf":
raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
elif type(values) not in (list, tuple):
raise NumericalFault("INVALID_INPUT", f"{label} must be an actual dense array.")
if not 3 <= len(values) <= 5:
raise NumericalFault("UNSUPPORTED_SIZE", f"{label} must have 3 to 5 entries.")
def _tensor(identifier, axis, values, provenance):
"""Serialize actual internal float64/int32 vectors into detached metadata."""
if type(values) is not np.ndarray or values.ndim != 1 or values.dtype not in (np.dtype(np.float64), np.dtype(np.int32)):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64/int32 vector storage.")
if not 1 <= len(values) <= 5:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier} requires 1 to 5 entries.")
flat = values.tolist()
for value in flat:
finite(value, identifier)
integer = values.dtype == np.dtype(np.int32)
return dict(id=identifier, shape=[len(flat)], axes=[axis], dtype="int32" if integer else "float64",
values=flat, provenance=provenance, precision=0 if integer else 8)
def direct_distribution(logits, class_ids, trace, prefix="choice"):
"""Dynamic V3..5 distribution; no slider bound on finite derived logits.
Prefix precedes both container guards; both descriptors precede entries.
Highest computed input logit wins; ties keep the lowest compact index.
"""
if type(prefix) is not str or not prefix:
raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")
_dense(logits, "logits")
_dense(class_ids, "classIDs")
if len(logits) != len(class_ids):
raise NumericalFault("SHAPE_MISMATCH", "logits and classIDs must have equal lengths.")
raw_z = logits.tolist() if type(logits) is np.ndarray else logits
raw_ids = class_ids.tolist() if type(class_ids) is np.ndarray else class_ids
V = len(raw_z)
z = np.array([finite(value, f"logits[{c}]") for c, value in enumerate(raw_z)], dtype=np.float64)
numeric_ids = [finite(value, f"classIDs[{c}]") for c, value in enumerate(raw_ids)]
checked_ids = []
for c, identifier in enumerate(numeric_ids):
if not identifier.is_integer() or identifier != ALL_IDS[c]:
raise NumericalFault("INVALID_INPUT", "classIDs must be the active prefix of [97,98,512,256,257].")
checked_ids.append(int(identifier))
ids = np.array(checked_ids, dtype=np.int32)
maximum_inputs = {f"z{c}": float(z[c]) for c in range(V)}
maximum = max(maximum_inputs.values())
trace.add(f"{prefix}_max", "Find the maximum active computed logit", "max=max(z0,...,z[V-1])",
"All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.",
maximum_inputs, dict(max=maximum))
shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
denominator, running = 0.0, {}
for c in range(V):
logit = float(z[c])
shift = finite(logit - maximum, "shifted logit")
term = finite(math.exp(shift), "shifted exponential")
shifted[c], terms[c] = shift, term
trace.add(f"{prefix}_exp_{c}", f"Exponentiate active class {c}", "shifted=logit-max; term=exp(shifted)",
"No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.",
dict(c=c, logit=logit, max=maximum), dict(shifted=shift, term=term))
denominator = finite(denominator + term, "denominator")
running[f"running{c}"] = denominator
if denominator <= 0:
raise NumericalFault("UNAVAILABLE", "The shifted exponential denominator must be positive.")
log_s = finite(math.log(denominator), "logS")
lse = finite(maximum + log_s, "logsumexp")
trace.add(f"{prefix}_normalize", "Accumulate terms and compute logsumexp",
"running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS",
"The denominator adds terms in ascending compact class order. Every actual running sum is saved.",
{**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
{**running, "denominator": denominator, "logS": log_s, "lse": lse})
for c in range(V):
term = float(terms[c])
probability = finite(term / denominator, "probability")
probabilities[c] = probability
trace.add(f"{prefix}_probability_{c}", f"Normalize active class {c}", "probability=term/S",
"This stored binary64 probability is displayed without feeding its formatting back into arithmetic.",
dict(c=c, term=term, denominator=denominator), dict(probability=probability))
next_row = 0
for c in range(1, V):
if float(z[c]) > float(z[next_row]):
next_row = c
next_id, next_probability = int(ids[next_row]), float(probabilities[next_row])
trace.add(f"{prefix}_argmax", "Choose the highest computed input logit",
"strict greater-than updates the winner; exact ties retain lowest compact index",
"Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order.",
maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
tensors = [
_tensor("ClassIDs", "Class", ids, "Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets."),
_tensor("Z", "Class", z, "Actual finite computed input logits; no derived-input clipping."),
_tensor("Shifted", "Class", shifted, "Z minus the saved active maximum."),
_tensor("Terms", "Class", terms, "Actual exp(Shifted), before normalization."),
_tensor("Denominator", "Scalar", np.array([denominator], dtype=np.float64), "Actual left-to-right sum of active shifted terms."),
_tensor("LogS", "Scalar", np.array([log_s], dtype=np.float64), "Natural logarithm of Denominator."),
_tensor("LSE", "Scalar", np.array([lse], dtype=np.float64), "Saved max+LogS in binary64."),
_tensor("P", "Class", probabilities, "Terms/Denominator for active classes only, without clipping or padding."),
_tensor("NextRow", "Decision", np.array([next_row], dtype=np.int32), "Lowest compact index among highest computed logits."),
_tensor("NextID", "Decision", np.array([next_id], dtype=np.int32), "Public class ID gathered at NextRow."),
_tensor("NextProbability", "Decision", np.array([next_probability], dtype=np.float64), "Stored P gathered at the computed-logit winner."),
]
return dict(classIDs=ids.tolist(), logits=z.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
nextRow=next_row, nextID=next_id, nextProbability=next_probability, tensors=tensors)
def compute_choice(state):
"""Full ordered IV45 record, including raw inactive metadata and every step."""
s = choice_state(state)
raw_z = np.array([s[f"z{c}"] for c in range(5)], dtype=np.float64)
class_ids = np.array(ALL_IDS[:s["V"]], dtype=np.int32)
trace = ChoiceTrace()
trace.add("setup", "Validate all raw logits before selecting active classes", "V in {3,4,5}; every raw z in [-40,40]; activeZ=rawZ[:V]",
"Inactive raw logits still validate and remain visible as metadata. This direct lesson has no text, target, loss, training, seed or sampling.",
s, dict(classCount=s["V"], rawLogitCount=5))
row = direct_distribution(raw_z[:s["V"]], class_ids, trace)
trace.add("finish", "Keep the distribution and greedy decision together", "nextID=classIDs[argmax computed activeZ]; nextProbability=P[nextRow]",
"The selected ID is a deterministic decision. Equal stored probabilities need not mean equal logits.",
dict(nextRow=row["nextRow"]), dict(nextID=row["nextID"], nextProbability=row["nextProbability"]))
outputs = dict(nextID=row["nextID"], nextProbability=row["nextProbability"], classCount=s["V"], logsumexp=row["lse"],
nextRow=row["nextRow"], max=row["max"], denominator=row["denominator"], logS=row["logS"], rawLogitCount=5)
for step in trace.steps:
outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
tensors = [_tensor("RawZ", "ModelRow", raw_z, "All five validated editable raw logits, including inactive slots."), *row["tensors"]]
return dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors)
def source_self_check():
"""DEFERRED helper checks; never calls any other file's self-check."""
assert __debug__, "Deferred checks require assertions enabled."
state = dict(DEFAULT_IV45)
trace = ChoiceTrace()
row = direct_distribution([1, 0, 0], [97, 98, 512], trace)
assert list(row) == ["classIDs", "logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability", "tensors"]
ndarray_row = direct_distribution(np.array([1, 0, 0], dtype=np.float64), np.array([97, 98, 512], dtype=np.int32), ChoiceTrace())
assert ndarray_row == row
assert direct_distribution((1, 0, 0), (97, 98, 512), ChoiceTrace()) == row
assert len(trace.steps) == 9 and trace.steps[0]["id"] == "choice_max"
denominator = math.e + 2
assert row["nextRow"] == 0 and row["nextID"] == 97
assert math.isclose(row["probabilities"][0], math.e / denominator, rel_tol=1e-14)
assert math.isclose(row["probabilities"][1], 1 / denominator, rel_tol=1e-14)
assert math.isclose(row["lse"], math.log(denominator), rel_tol=1e-14)
tied = direct_distribution([0, 0, 1, 1, 0], ALL_IDS, ChoiceTrace())
assert tied["nextRow"] == 2 and tied["nextID"] == 512
uniform = direct_distribution([0] * 5, ALL_IDS, ChoiceTrace())
assert uniform["probabilities"] == [0.2] * 5 and uniform["nextID"] == 97
rounded = direct_distribution([0, math.ulp(0.0), 0], ALL_IDS[:3], ChoiceTrace())
assert rounded["probabilities"] == [1 / 3] * 3 and rounded["nextID"] == 98
thin = direct_distribution([-40, 40, -40], ALL_IDS[:3], ChoiceTrace())
assert thin["probabilities"][0] > 0 and thin["probabilities"][2] > 0
derived_trace = ChoiceTrace()
shifted = direct_distribution([101, 100, 100], ALL_IDS[:3], derived_trace, "derived")
assert shifted["probabilities"] == row["probabilities"] and shifted["nextID"] == row["nextID"]
assert all(step["id"].startswith("derived_") for step in derived_trace.steps)
for patch, code in ((dict(V=True), "NONFINITE"), (dict(V=2), "INVALID_INPUT"),
(dict(V=3.5), "INVALID_INPUT"), (dict(z4=True), "NONFINITE"),
(dict(z4=41), "INVALID_INPUT"), (dict(z4=float("nan")), "NONFINITE"),
(dict(z4=10**1000), "NONFINITE")):
fault = guarded(compute_choice)({**state, **patch})
assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
class Hostile(dict):
def __getitem__(self, key):
raise AssertionError("Custom indexing must not be read")
assert guarded(compute_choice)(Hostile(state))["code"] == "INVALID_INPUT"
class HostileList(list):
def __getitem__(self, key):
raise AssertionError("Custom indexing must not be read")
for logits, ids, code in (([1, 0, 0], HostileList([97, 98, 512]), "INVALID_INPUT"),
(HostileList([1, 0, 0]), [97, 98, 512], "INVALID_INPUT"),
([1, 0, 0], [97, 98, 256], "INVALID_INPUT"),
([1, 0, 0], [99, float("nan"), 512], "NONFINITE"),
([1, float("nan"), 0], None, "INVALID_INPUT"),
([1, 0, 0], [97, 98, 512, 256], "SHAPE_MISMATCH"),
(np.array([True, False, False]), ALL_IDS[:3], "INVALID_INPUT"),
([1, True, 0], ALL_IDS[:3], "NONFINITE"),
([1, float("inf"), 0], ALL_IDS[:3], "NONFINITE"),
([1e308, -1e308, 0], ALL_IDS[:3], "NONFINITE"),
([1, 0], [97, 98], "UNSUPPORTED_SIZE")):
try:
direct_distribution(logits, ids, ChoiceTrace(), "bad")
except NumericalFault as error:
assert error.code == code
else:
raise AssertionError("Invalid helper boundary was accepted")
for prefix in (None, "", 0, True):
rejected_trace = ChoiceTrace()
try:
direct_distribution(HostileList(), None, rejected_trace, prefix)
except NumericalFault as error:
assert error.code == "INVALID_INPUT" and "prefix" in str(error)
assert not rejected_trace.steps
else:
raise AssertionError("Prefix must validate before containers")
assert _tensor("F", "Class", np.array([1.0], dtype=np.float64), "check")["dtype"] == "float64"
assert _tensor("I", "Class", np.array([97], dtype=np.int32), "check")["dtype"] == "int32"
row["tensors"][0]["values"][0] = -1
row["probabilities"][0] = -1
trace.steps[0]["outputs"].clear()
assert direct_distribution([1, 0, 0], ALL_IDS[:3], ChoiceTrace())["tensors"][0]["values"] == [97, 98, 512]
assert state == dict(DEFAULT_IV45)
_JSON_INT = int
def run(derive, defaults):
"""Default / full replacement JSON / '-' stdin; never invokes self-checks."""
class ParseFault(ValueError):
"""Only locally owned JSON profile/conversion faults."""
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as fault:
if type(fault) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members,
parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
else:
result = derive(state)
else:
result = derive(dict(defaults))
print(json.dumps(result, allow_nan=False, separators=(",", ":")))
Follow max to each shifted and term, then each running sum to denominator, and each division to probabilities. Follow nextRow separately from the original logits to nextID and nextProbability. This separation is what preserves the correct MIN_VALUE winner even if all stored probabilities coincide. The helper has no raw-control clipping for derived logits; explicit finite-intermediate checks still protect later reuse.
The wrapper resolves its adjacent helper through __file__. Declared wrapper/helper source_self_check routines are explicit; importing a file or asking for a normal result must not run other checks implicitly. These panels expose source to inspect, not a CLI output transcript or parity result.
Explain the five actual graded checks
The lab’s questions follow this order. Live prompts use current saved inputs and results, not rounded display values or the independent class inspector. Selecting an option reveals corrective feedback; an edit or trace selection clears the previous grades.
- Which statement distinguishes a logit, a softmax probability and greedy selection? A logit is the input score; stable softmax normalizes all active scores; greedy chooses the highest computed input logit. None of those steps trains a model, samples randomly or uses printed digits as numerical input. The selected stored probability stays its actual value rather than being changed to1.
- Which shapes describe V active classes selected from five validated raw logits?
RawZhas shape[5];ClassIDs,ZandPeach have shape[V]. Use the current V in the prompt, not an assumed reset3. EOS’s public ID512 does not require513 array entries. Inactive raw slots validate and remain visible metadata; they receive no made-up zero probabilities. - Which denominator and probability mechanism match the saved winning-class exponentiation? Read its actual logit, maximum, shifted value and term.
choice_normalizesaves every sequential running sum, final S and logS; the selected probability is the saved winning term divided by S, and LSE=max+logS. At reset the winning shift is0, term1 and S=1+2/e, giving P=e/(e+2). After an edit, use the newly saved values. Other active classes still contribute to S even though they did not win. No epsilon, raw-logit division or display rounding replaces that calculation. - Which greedy decision and tie rule match the current active logits? Read the current
Zarray and saved compact row/public ID. A unique highest computed score wins even when stored probabilities look tied. If several computed scores equal the maximum, the strict-greater scan keeps the lowest compact index. The live prompt explicitly distinguishes these cases. The V5 EOS/ab example selects compact2/public512 before compact3/public256; sorting by public ID or printed probabilities would answer a different question. - At V3 with
(0, Number.MIN_VALUE, 0), which ID wins if stored probabilities all round to thirds? b/98 wins because its actual positive binary64 input score exceeds the two exact zeros. Equal stored P does not create an input-logit tie. The implementation must not replace the subnormal by0, choose compact0 from rounded probabilities or interpret a tiny positive score as EOS. This transfer tests the numerical decision rule, not memorization of the reset winner.
Recap and bridge
- Active class order maps compact array entries to public token IDs; inactive scores remain validated raw storage.
- Max subtraction, exponentiation, an ordered sum and division produce the full saved distribution.
- Greedy selection compares computed logits and keeps the lowest compact index on exact ties.
- A probability display tie does not necessarily mean equal logits; a selected probability is not certainty.
- Normalization, token choice and a generation loop’s EOS policy are separate operations.
Next, IV-46 changes a distribution with temperature and candidate filtering, then samples using an explicit recorded random stream. That adds a different decision rule to the normalization mechanism established here.