The neural notebook
← All chapters

IV-40 / Part X · Language Modeling

Autoregressive Next-Token Prediction

Compute a causal next-token distribution from a disclosed one-token affine model, distinguish IDs from rows, and score observed transitions without inventing a first-token probability.

Review the ideas this chapter uses

Suppose we have already read aba. We want three numbers describing what could come next: a, b or the end of the sequence. Those numbers must use information already available when the prediction is made. We will build them from a deliberately small rule, then separately ask how much probability that rule assigned to the transitions we actually observed.

Learning objective: Form a causal conditional distribution p(xt∣x<t)p(x_t\mid x_{<t}).

Compute it yourself

Autoregressive Next-Token Prediction

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
T
3
x0
97
x1
98
x2
97
e00
1
e01
0
e10
0
e11
1
u00
1
u01
0
u02
0
u10
0
u11
1
u12
0
b0
0
b1
0
b2
0
contextLength3
nextID97
nextProbability0.5761168847658291
conditionalNLL3.102889427864102
Content embedding E [2,2]
Output weights U [2,3]
Output biases [3]

contextLength 3. nextID 97. nextProbability 0.5761168847658291. conditionalNLL 3.102889427864102. Validate the full state and disclose the receptive field. All stored token slots and all thirteen parameters are checked, even when inactive. The full observed prefix is visible, but this affine toy uses only its current token.. contextLength 3. transitionCount 2. receptiveField 1

Validate the full state and disclose the receptive field

contextLength=T; transitionCount=T-1; receptiveField=1

All stored token slots and all thirteen parameters are checked, even when inactive. The full observed prefix is visible, but this affine toy uses only its current token.

Inputs

T
3
x0
97
x1
98
x2
97
e00
1
e01
0
e10
0
e11
1
u00
1
u01
0
u02
0
u10
0
u11
1
u12
0
b0
0
b1
0
b2
0

Outputs

contextLength
3
transitionCount
2
receptiveField
1

A causal distribution from the observed current token

A logit is a score before normalization. The three prediction classes are a (public ID97, compact class0), b (98, class1), EOS (end of sequence, 512, class2). Public IDs name tokens; compact rows index tensors. PAD768 is a storage sentinel with no prediction class.

This disclosed affine toy has a one-token receptive field: only the current observed a/b token enters E[2,2], then its two features multiply U[2,3] and receive Bias[3]. E has no EOS or PAD input row. This calculation has no attention, training or parameter update.

Inspecting physical row 0, compact class 0. Numeric tensor row 0. View selectors change only the inspection; the exercises use the starting inputs.

Selected saved trace operation: setup. A matching operation row is marked current only when it belongs to the inspected row below. Trace and view selectors are independent; all trace operations remain selectable above.

Full observed sequence: [0: a / 97] [1: b / 98] [2: a / 97] . Prefix available at position 0: a. Saved receptive start/end are 0/0; only this current token is used.

Observed continuation likelihood GIVEN x0 is 0.04491922384515635; conditional NLL is 3.102889427864102 nats. At T1 the empty product is1 and sum0 by definition; the next distribution still has three real classes. No probability is assigned to the given first token.

Selected affine row_0_affine_0: products 1 and 0 sum to 1; bias 0 gives logit 1.

Probability row for physical position 0 — saved values without display rounding
Compact classPublic IDLogitShiftedexp(shifted)Probability
0a (97)1010.5761168847658291
1b (98)0-10.367879441171442330.21194155761708544
2EOS (512)0-10.367879441171442330.21194155761708544

Saved maximum=1; S=1.7357588823428847; ln(S)=0.5514447139320511; LSE=1.551444713932051. Probabilities use shifted terms divided by S, with no epsilon or clipping.

Highest computed logit selects a (ID97), stored probability 0.5761168847658291. Exact logit ties choose the lowest compact class. Rounded probabilities can appear tied even when computed logits differ.

Observed target b (ID98, compact class1) has target logit 0, probability 0.21194155761708544. NLL=(m−targetLogit)+ln(S) uses saved gap 1 plus saved ln(S) 0.5514447139320511, giving 1.551444713932051 nats. Weight 1 gives contribution 1.551444713932051. This observed target contributes to the objective.

Saved operations for physical row 0 — saved values without display rounding
Saved stepActual operandsActual results
row_0_input
t=0
publicID=97
inputRow=0
receptiveStart=0
receptiveEnd=0
h0=1
h1=0
row_0_affine_0
c=0
h0=1
h1=0
u0=1
u1=0
bias=0
product0=1
product1=0
sum=1
logit=1
row_0_affine_1
c=1
h0=1
h1=0
u0=0
u1=1
bias=0
product0=0
product1=0
sum=0
logit=0
row_0_affine_2
c=2
h0=1
h1=0
u0=0
u1=0
bias=0
product0=0
product1=0
sum=0
logit=0
row_0_max
z0=1
z1=0
z2=0
max=1
row_0_exp_0
c=0
logit=1
max=1
shifted=0
term=1
row_0_exp_1
c=1
logit=0
max=1
shifted=-1
term=0.36787944117144233
row_0_exp_2
c=2
logit=0
max=1
shifted=-1
term=0.36787944117144233
row_0_normalize
term0=1
term1=0.36787944117144233
term2=0.36787944117144233
max=1
denominator=1.7357588823428847
logS=0.5514447139320511
lse=1.551444713932051
row_0_probability_0
c=0
term=1
denominator=1.7357588823428847
probability=0.5761168847658291
row_0_probability_1
c=1
term=0.36787944117144233
denominator=1.7357588823428847
probability=0.21194155761708544
row_0_probability_2
c=2
term=0.36787944117144233
denominator=1.7357588823428847
probability=0.21194155761708544
row_0_argmax
z0=1
z1=0
z2=0
nextRow=0
nextID=97
nextProbability=0.5761168847658291
row_0_target
targetID=98
targetRow=1
targetLogit=0
max=1
logS=0.5514447139320511
probability=0.21194155761708544
weight=1
gap=1
nll=1.551444713932051
contribution=1.551444713932051
Inspect the shared content embedding and output parameters

E

Content=2 × Feature=2 · float64 · precision 8. All four editable content embedding entries; no EOS or PAD row.

E row-major storage — saved values without display rounding
Storage indexValue
01
10
20
31

U

Feature=2 × Class=3 · float64 · precision 8. All six editable output weights; feature-last h[2] times U[2,3].

U row-major storage — saved values without display rounding
Storage indexValue
01
10
20
30
41
50

Bias

Class=3 · float64 · precision 8. All three editable output biases, added after the two-product sum.

Bias row-major storage — saved values without display rounding
Storage indexValue
00
10
20

The full-precision inspector contains every saved tensor, its named axes, dtype and provenance. Common logit shifts preserve the real mathematical distribution, NLL and derivative; floating shifts can round away differences.

Inspect tensor shapes and full precision

All computed outputs

contextLength
3
nextID
97
nextProbability
0.5761168847658291
conditionalNLL
3.102889427864102
likelihood
0.04491922384515635
receptiveField
1
setup_contextLength
3
setup_transitionCount
2
setup_receptiveField
1
row_0_input_inputRow
0
row_0_input_receptiveStart
0
row_0_input_receptiveEnd
0
row_0_input_h0
1
row_0_input_h1
0
row_0_affine_0_product0
1
row_0_affine_0_product1
0
row_0_affine_0_sum
1
row_0_affine_0_logit
1
row_0_affine_1_product0
0
row_0_affine_1_product1
0
row_0_affine_1_sum
0
row_0_affine_1_logit
0
row_0_affine_2_product0
0
row_0_affine_2_product1
0
row_0_affine_2_sum
0
row_0_affine_2_logit
0
row_0_max_max
1
row_0_exp_0_shifted
0
row_0_exp_0_term
1
row_0_exp_1_shifted
-1
row_0_exp_1_term
0.36787944117144233
row_0_exp_2_shifted
-1
row_0_exp_2_term
0.36787944117144233
row_0_normalize_denominator
1.7357588823428847
row_0_normalize_logS
0.5514447139320511
row_0_normalize_lse
1.551444713932051
row_0_probability_0_probability
0.5761168847658291
row_0_probability_1_probability
0.21194155761708544
row_0_probability_2_probability
0.21194155761708544
row_0_argmax_nextRow
0
row_0_argmax_nextID
97
row_0_argmax_nextProbability
0.5761168847658291
row_0_target_gap
1
row_0_target_nll
1.551444713932051
row_0_target_contribution
1.551444713932051
transition_0_likelihood
0.21194155761708544
transition_0_conditionalNLL
1.551444713932051
row_1_input_inputRow
1
row_1_input_receptiveStart
1
row_1_input_receptiveEnd
1
row_1_input_h0
0
row_1_input_h1
1
row_1_affine_0_product0
0
row_1_affine_0_product1
0
row_1_affine_0_sum
0
row_1_affine_0_logit
0
row_1_affine_1_product0
0
row_1_affine_1_product1
1
row_1_affine_1_sum
1
row_1_affine_1_logit
1
row_1_affine_2_product0
0
row_1_affine_2_product1
0
row_1_affine_2_sum
0
row_1_affine_2_logit
0
row_1_max_max
1
row_1_exp_0_shifted
-1
row_1_exp_0_term
0.36787944117144233
row_1_exp_1_shifted
0
row_1_exp_1_term
1
row_1_exp_2_shifted
-1
row_1_exp_2_term
0.36787944117144233
row_1_normalize_denominator
1.7357588823428847
row_1_normalize_logS
0.5514447139320511
row_1_normalize_lse
1.551444713932051
row_1_probability_0_probability
0.21194155761708544
row_1_probability_1_probability
0.5761168847658291
row_1_probability_2_probability
0.21194155761708544
row_1_argmax_nextRow
1
row_1_argmax_nextID
98
row_1_argmax_nextProbability
0.5761168847658291
row_1_target_gap
1
row_1_target_nll
1.551444713932051
row_1_target_contribution
1.551444713932051
transition_1_likelihood
0.04491922384515635
transition_1_conditionalNLL
3.102889427864102
row_2_input_inputRow
0
row_2_input_receptiveStart
2
row_2_input_receptiveEnd
2
row_2_input_h0
1
row_2_input_h1
0
row_2_affine_0_product0
1
row_2_affine_0_product1
0
row_2_affine_0_sum
1
row_2_affine_0_logit
1
row_2_affine_1_product0
0
row_2_affine_1_product1
0
row_2_affine_1_sum
0
row_2_affine_1_logit
0
row_2_affine_2_product0
0
row_2_affine_2_product1
0
row_2_affine_2_sum
0
row_2_affine_2_logit
0
row_2_max_max
1
row_2_exp_0_shifted
0
row_2_exp_0_term
1
row_2_exp_1_shifted
-1
row_2_exp_1_term
0.36787944117144233
row_2_exp_2_shifted
-1
row_2_exp_2_term
0.36787944117144233
row_2_normalize_denominator
1.7357588823428847
row_2_normalize_logS
0.5514447139320511
row_2_normalize_lse
1.551444713932051
row_2_probability_0_probability
0.5761168847658291
row_2_probability_1_probability
0.21194155761708544
row_2_probability_2_probability
0.21194155761708544
row_2_argmax_nextRow
0
row_2_argmax_nextID
97
row_2_argmax_nextProbability
0.5761168847658291
conditional_likelihood
0.04491922384515635
conditional_conditionalNLL
3.102889427864102

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

ClassIDs

Class=3 · int32 · display precision 0 · Compact prediction class c=0,1,2 maps to public ID a=97,b=98,EOS=512; PAD is excluded.

Storage indexValue
097
198
2512

EmbeddingIDs

Content=2 · int32 · display precision 0 · Embedding row r=0,1 maps only to a=97,b=98; EOS is never an active input.

Storage indexValue
097
198

E

Content=2 × Feature=2 · float64 · display precision 8 · All four editable content embedding entries; no EOS or PAD row.

Storage indexValue
01
10
20
31

U

Feature=2 × Class=3 · float64 · display precision 8 · All six editable output weights; feature-last h[2] times U[2,3].

Storage indexValue
01
10
20
30
41
50

Bias

Class=3 · float64 · display precision 8 · All three editable output biases, added after the two-product sum.

Storage indexValue
00
10
20

InputIDs

Position=3 · int32 · display precision 0 · Observed active prefix; the first token is given, not assigned a model probability.

Storage indexValue
097
198
297

InputRows

Position=3 · int32 · display precision 0 · Compact a/b embedding row for each observed current token.

Storage indexValue
00
11
20

ReceptiveStart

Position=3 · int32 · display precision 0 · Inclusive receptive-field start; only the current position is read.

Storage indexValue
00
11
22

ReceptiveEnd

Position=3 · int32 · display precision 0 · Inclusive receptive-field end, equal to the current position.

Storage indexValue
00
11
22

H

Position=3 × Feature=2 · float64 · display precision 8 · Actual E row gathered from the current observed token only.

Storage indexValue
01
10
20
31
41
50

Logits

Position=3 × Class=3 · float64 · display precision 8 · Actual pre-softmax logits in compact a,b,EOS class order.

Storage indexValue
01
10
20
30
41
50
61
70
80

Shifted

Position=3 × Class=3 · float64 · display precision 8 · Each saved logit minus that row's maximum.

Storage indexValue
00
1-1
2-1
3-1
40
5-1
60
7-1
8-1

Terms

Position=3 × Class=3 · float64 · display precision 8 · exp(Shifted), from the shared stableSoftmax; no masked classes.

Storage indexValue
01
10.36787944117144233
20.36787944117144233
30.36787944117144233
41
50.36787944117144233
61
70.36787944117144233
80.36787944117144233

Max

Position=3 · float64 · display precision 8 · Maximum of the three logits for each computed row.

Storage indexValue
01
11
21

Denominator

Position=3 · float64 · display precision 8 · Left-to-right sum from zero of the three shifted exponential terms.

Storage indexValue
01.7357588823428847
11.7357588823428847
21.7357588823428847

LogS

Position=3 · float64 · display precision 8 · Natural log of the shifted exponential denominator.

Storage indexValue
00.5514447139320511
10.5514447139320511
20.5514447139320511

LSE

Position=3 · float64 · display precision 8 · Saved max+LogS; not subtracted from a target logit to compute NLL.

Storage indexValue
01.551444713932051
11.551444713932051
21.551444713932051

P

Position=3 × Class=3 · float64 · display precision 8 · Terms/Denominator, actual binary64 probabilities before display rounding.

Storage indexValue
00.5761168847658291
10.21194155761708544
20.21194155761708544
30.21194155761708544
40.5761168847658291
50.21194155761708544
60.5761168847658291
70.21194155761708544
80.21194155761708544

NextRows

Position=3 · int32 · display precision 0 · Argmax computed logit; exact logit ties choose the lowest row a,b,EOS.

Storage indexValue
00
11
20

NextIDs

Position=3 · int32 · display precision 0 · Public prediction IDs mapped from NextRows; these are not teacher-forced inputs.

Storage indexValue
097
198
297

TargetPositions

Transition=2 · int32 · display precision 0 · Observed next-token position selected only after each causal distribution.

Storage indexValue
01
12

TargetIDs

Transition=2 · int32 · display precision 0 · Observed continuation IDs x1 through x(T-1); x0 is given.

Storage indexValue
098
197

TargetRows

Transition=2 · int32 · display precision 0 · Compact prediction class for each observed next target.

Storage indexValue
01
10

TargetLogits

Transition=2 · float64 · display precision 8 · Actual logit gathered at the compact target class, after the causal prediction.

Storage indexValue
00
10

TargetProbability

Transition=2 · float64 · display precision 8 · Actual saved probability gathered for a non-PAD target; never used as a rounded NLL input.

Storage indexValue
00.21194155761708544
10.21194155761708544

NLL

Transition=2 · float64 · display precision 8 · Factored (max-targetLogit)+LogS in natural-log units, including manually masked computed rows.

Storage indexValue
01.551444713932051
11.551444713932051

Weights

Transition=2 · int32 · display precision 0 · Effective numeric 0/1 weights of computed target rows only.

Storage indexValue
01
11

Contributions

Transition=2 · float64 · display precision 8 · Weight*NLL; manual mask zero is a real weighted zero, not an uncomputed PAD loss.

Storage indexValue
01.551444713932051
11.551444713932051

Start with observed a,b,a. The authored parameters are E identity2, U rows(1,0,0)/(0,1,0), and zero bias. For current a, feature products give logits(1,0,0); for b they give(0,1,0). Put e=exp(1), Z=e+2: the winning class has probability e/Z and each other class1/Z.

Observed transitions b|a and a|b each use probability1/Z, giving conditional likelihood1/Z² and NLL2lnZ GIVEN the first a. The final current a predicts next a with e/Z; it has no observed next target. With T1, continuation product1 and loss0 are empty identities, while the next distribution remains real.

Try editing x2 with T3: earlier logits stay fixed, but row1's selected target loss can change. Then edit x0 while holding x2 fixed: final logits stay fixed because this toy sees one token. Open the E/U/bias groups to edit all thirteen parameters; the model checks every raw slot even when T makes it inactive. This is a small conditional model, not a Transformer or trained text generator.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. At position t, which token may this one-token causal conditional use to predict the next token?
2. Prediction IDs are a=97, b=98, EOS=512. With two features and current inputs restricted to a/b, which shapes and maps are correct?
3. Current transition_0 has previousLikelihood=1, target probability=0.21194155761708544, previousNLL=0, nll=1.551444713932051. Which saved result and rule are correct?
4. Set T=3 and hold all parameters fixed. If only x2 changes between a and b, which earlier values are guaranteed unchanged?
5. At T=3, change x0 while keeping x2 and every parameter fixed. What can the final next-token prediction demonstrate about longer context?

Reset uses T=3, x0=97, x1=98, x2=97, meaning a,b,a. The final next-token choice is a. Change only x2 to b and compare earlier distributions with their observed-target losses. The distinction matters: a later token can change what an earlier prediction is scored against without entering that prediction’s calculation.

Start with IV-26 — Causal, Bidirectional and Padding Attention for causal information access and IV-39 — Byte-Pair Encoding: A Full Merge Trace for public token IDs. Book II’s II.9 — Matrix × vector explains matrix–vector products; Book III’s III-40 — From Linear Model to Artificial Neuron and III-41 — Composition and Learned Representations explain fixed neurons and composition. Here the new ingredient is a conditional distribution over the next item. Parameters are hand-set and editable; no training takes place.

What is conditioned on?

A token is one item in a sequence. A prefix is the part already observed. Conditional probability, written p(v∣u)p(v\mid u), means the probability assigned to outcome v when u is supplied. The vertical bar reads “given.” Autoregressive prediction repeatedly uses an observed prefix to predict its next item; it does not authorize reading the answer before computing the prediction.

The learning objective uses xtx_t as the item being predicted and x<tx_{<t} for all preceding items. The lab instead labels a row by its current input position t, starting at zero. Row t predicts xt+1x_{t+1} from tokens available through xtx_t. These are the same next-token alignment with indices shifted by one.

This lab’s receptive field, the set of input positions that can affect a prediction, contains only the current position t. The visible prefix may contain several tokens, but only xtx_t enters the arithmetic. Earlier tokens are deliberately ignored. This is a one-token affine conditional, not the full Transformer assembled later in IV-43. Causality restricts available information; it does not require a model to use every available item.

Names, rows and every shape

A vocabulary lists possible next items. This authored example has prediction IDs 97=a, 98=b and 512=EOS, where EOS means end of sequence. Its prediction-class map is 97→0, 98→1, 512→2. A public ID names an item; a compact row addresses a small array. ID512 does not require 513 rows.

Current inputs can only be a or b. Their embedding, a numerical representation obtained by lookup, comes from E with shape [2,2]: two content-token rows and two feature columns. There is no EOS input row here. The output matrix U has shape [2,3], axes Feature and Class. Bias b has shape [3], one additive offset per class. A tensor is an array with named dimensions; [2,3] means two rows of three values. All real arithmetic is binary64, also called float64; IDs and row indices use exact int32 integers.

At reset:

E=(1001),U=(100010),b=(0,0,0).E=\begin{pmatrix}1&0\\0&1\end{pmatrix},\qquad U=\begin{pmatrix}1&0&0\\0&1&0\end{pmatrix},\qquad b=(0,0,0).

Let r be the input’s compact content row, h its two-feature embedding, f a feature index 0 or 1, and c a prediction-class index 0,1,2. The logit zcz_c is an unrestricted score before probabilities:

hf=E[r,f],zc=h0U[0,c]+h1U[1,c]+bc.h_f=E[r,f],\qquad z_c=h_0U[0,c]+h_1U[1,c]+b_c.

This is affine because it combines a linear weighted sum with a bias. A row h with shape [1,2] times U [2,3] yields logits [1,3]; the repeated feature dimension 2 is summed. This is the feature-last row form of the matrix times column-vector notation reviewed in Book II. For T active positions, the collected embeddings have shape [T,2] and logits/probabilities [T,3], with position first and class second.

The editable parameter groups are Content embedding E [2,2], Output weights U [2,3] and Output biases [3]. Controls e00,e01,e10,e11 address the four E entries; u00,u01,u02,u10,u11,u12 address the six U entries; b0,b1,b2 address the class biases. In each two-digit name the first digit selects the row and the second the column. Reset example restores the disclosed state. Calculation step, Previous step and Next step select saved operands; they do not generate extra tokens or update weights. Inspect tensor shapes and full precision exposes stored values beyond a formatted table.

Work the affine rule before normalizing

For input a, h=(1,0). Each class records both products, their sum and its bias:

ClassFeature-0 productFeature-1 productSum plus bias
a1·1=10·0=01+0+0=1
b1·0=00·1=00+0+0=0
EOS1·0=00·0=00+0+0=0

For input b, h=(0,1): a uses 0·1+1·0+0=0; b uses 0·0+1·1+0=1; EOS uses 0·0+1·0+0=0. Thus the default three input rows a,b,a give logits (1,0,0), (0,1,0), (1,0,0). None reads its next target to obtain these values.

Softmax turns three logits into three positive relative weights summing to one. Let exp(v) mean eve^v, where e=exp(1); let ln be the natural logarithm, which reverses exp. For each row define maximum m, shifted logits d, exponential terms w and denominator S:

m=max⁡czc,dc=zc−m,wc=exp⁡(dc),S=w0+w1+w2,Pc=wc/S.m=\max_c z_c,\quad d_c=z_c-m,\quad w_c=\exp(d_c),\quad S=w_0+w_1+w_2,\quad P_c=w_c/S.

The subscript c selects a class, and max selects the largest of the three scores. At a: m=1, d=(0,−1,−1), w=(1,1/e,1/e). Add terms from zero in class order: 0+1=1, then 1+1/e, then S=1+2/e. Define Z=e+2, so S=Z/e. Dividing gives P=(e/Z,1/Z,1/Z). At b the terms are (1/e,1,1/e) and P=(1/Z,e/Z,1/Z). These symbolic expressions are exact real arithmetic; displayed decimals are rounded views.

Why subtract the maximum? Multiplying all numerator and denominator terms by exp(−m) leaves every ratio unchanged. Shifted logits are nonpositive, so exp never receives a large positive argument. At least one term is exp(0)=1, ensuring a positive denominator. No class is masked in this lesson.

Score only transitions we observed

The default has two observed transitions and a third distribution ready for an unknown next item:

RowVisible prefixActual inputObserved next targetAssigned target probability
0aab1/Z
1abba1/Z
2abaanoneno observed-target score

The last row still has a full distribution. Its argmax is selected using the highest computed logit, which has the highest probability in exact softmax arithmetic: here a with stored probability e/Z. Exact logit ties choose the lowest compact class: a before b before EOS. Argmax selects one class; it does not turn its probability into certainty or sample a generated continuation.

The likelihood of the observed continuation, meaning the probability this model assigns to it, is

p(x1=b,x2=a∣x0=a)=p(b∣a) p(a∣b)=1Z1Z=1Z2.p(x_1=b,x_2=a\mid x_0=a) =p(b\mid a)\,p(a\mid b)=\frac1Z\frac1Z=\frac1{Z^2}.

This is explicitly given the first token. We have neither a beginning-of-sequence input nor a distribution assigning a probability to x0x_0. Multiplying a fabricated first-token probability would answer a different question. The conditional chain rule factors a continuation into successive next-token probabilities; the one-token model replaces dependence on the entire prefix with its declared current-token dependence.

Negative log-likelihood (NLL) is minus the natural log of the assigned target probability. Products become sums because ln(uv)=ln(u)+ln(v). For target class y, compute it stably as

ℓ=(m−zy)+ln⁡S.\ell=(m-z_y)+\ln S.

Here y is a compact class index, zyz_y the target’s score and ℓ a row’s loss. Each default observed target has score0: ℓ=(1−0)+lnS=lnZ. The total is lnZ+lnZ=2lnZ. Do not take the log of a rounded printed probability. The final unobserved distribution has no target loss to add.

The first four summaries are contextLength, nextID, nextProbability and conditionalNLL. Reset gives 3,97,e/Z,2lnZ. The observed likelihood is 1/Z² and receptiveField is 1. With T=1 there are zero observed transitions: the empty product is 1 and empty NLL sum is 0, while a genuine next distribution remains. This convention supplies no evidence of predictive success.

Real edits and useful counterexamples

Change only x2 from a to b. Rows0 and1 keep logits (1,0,0) and (0,1,0). Row1’s target becomes b, so its probability becomes e/Z and its loss lnZ−1. Row2’s current input becomes b, so its distribution becomes (1/Z,e/Z,1/Z). The observed continuation now has likelihood e/Z² and total NLL2lnZ−1. The unchanged earlier logits demonstrate causality even though one earlier loss changes.

Reset, then change only x0 to b. Row2 still reads a and retains (1,0,0). A learner expecting the entire earlier story to affect this row has found the toy’s limitation: it cannot distinguish longer histories ending in the same token.

Stored probabilities can round to the same value even when computed logits differ. For the binary64 logit row (0, Number.MIN_VALUE, 0), Number.MIN_VALUE is the smallest positive representable value; b is strictly greater than a and EOS. Exponentiation and normalization can nevertheless store three equal probabilities 1/3. Selection compares the actual logits and chooses b, retaining its actual stored probability. A display tie must not create an artificial argmax tie. The argmax trace therefore saves all three logit operands.

For a parameter edit, reset and set u02=1. At input a, EOS gains score 1·1+0·0+0=1, so logits are (1,0,1), terms (1,1/e,1), denominator 2+1/e, and P=(e,1,e)/(2e+1). The a/EOS tie selects a. This recomputes probabilities; it is not a learned update.

T is an integer 1..3, every x slot must be 97 or98, E/U entries lie in [−2,2], and biases in [−4,4]. All 13 parameters and even inactive x slots validate before computation. An invalid unused row remains an invalid state. Two products of magnitude at most4 plus bias at most4 give |z|≤12; hence ℓ≤24+ln3. No clipping, epsilon or silent repair is needed within this domain.

At T=1 the inspector omits the empty transition/target tensor block entirely. InputIDs, InputRows, ReceptiveStart, ReceptiveEnd, H, Logits and P still describe the real active prediction. Both receptive-field endpoints equal the current position; they are not the beginning and end of the whole visible prefix.

The two view selectors, Physical position / loss row to inspect and Compact prediction class to inspect, choose which saved row and affine class to explain. They change neither inputs nor predictions. The probability table keeps all three classes visible; the class selector picks the saved two-product calculation. Exercises refer to the starting inputs, independently of these view choices.

Read the maintained Python calculation

The chapter entry point is the actual wrapper, rather than a second example implementation:

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.

"""IV-40 — Autoregressive Next-Token Prediction, canonical NumPy source.

A disclosed one-token receptive field uses h=E[current a/b row], then
z[c]=(h[0]*U[0,c]+h[1]*U[1,c])+bias[c]. Earlier prefix tokens are visible
context but outside this model's receptive field. A future target NEVER enters
these logits. Public IDs a=97,b=98,EOS=512 name prediction classes0,1,2;
E has only two content rows because EOS is never a current input here.

Hand default: let e=exp(1), Z=e+2. For a,b,a the logit rows are
[1,0,0],[0,1,0],[1,0,0]. The observed transitions b|a and a|b each have
P=1/Z and NLL=ln(Z). Their actual conditional chain is
P(x1,x2|x0)=1/Z**2 with total NLL=2ln(Z); no probability for x0 is
invented. The final next distribution chooses a with probability e/Z.
For T=1 the observed-transition product is the empty product1 and its NLL0;
this is a definition, not evidence that prediction succeeded.

Keep language_reference.py beside this file. The file-relative loader works
from any process cwd. All source/self-checks remain unexecuted under the hold.
"""
import importlib.util
import math
from pathlib import Path
from types import MappingProxyType

_helper_spec = importlib.util.spec_from_file_location(
    "_p10_language_reference", Path(__file__).resolve().with_name("language_reference.py"))
if _helper_spec is None or _helper_spec.loader is None:
    raise ImportError("Cannot load the adjacent canonical language_reference.py.")
_helper = importlib.util.module_from_spec(_helper_spec)
_helper_spec.loader.exec_module(_helper)
DEFAULT_IV40 = MappingProxyType(dict(_helper.IV40_DEFAULTS))


@_helper.guarded
def derive_iv40(state):
    """Validate all fields, compute causal rows, then score observed transitions."""
    return _helper.derive40(state)


def source_self_check():
    """DEFERRED owner-only assertions; never called on import or CLI query."""
    s = dict(DEFAULT_IV40)
    result = derive_iv40(s)
    assert result["status"] == "defined"
    o = result["outputs"]
    Z = math.e + 2
    assert o["contextLength"] == 3 and o["nextID"] == 97
    assert math.isclose(o["nextProbability"], math.e / Z)
    assert math.isclose(o["likelihood"], 1 / Z ** 2)
    assert math.isclose(o["conditionalNLL"], 2 * math.log(Z))
    one = derive_iv40({**s, "T": 1})
    assert one["outputs"]["conditionalNLL"] == 0 and one["outputs"]["likelihood"] == 1
    # Even a slot beyond T must validate before any computation.
    assert derive_iv40({**s, "T": 1, "x2": 512})["code"] == "INVALID_INPUT"
    assert derive_iv40({**s, "T": 1, "e11": float("nan")})["code"] == "NONFINITE"
    assert derive_iv40({**s, "e11": 10 ** 10000})["code"] == "NONFINITE"
    assert list(result) == ["status", "outputs", "steps", "tensors"]
    assert len(result["steps"]) == 45 and len(result["tensors"]) == 28
    assert len(one["steps"]) == 15 and len(one["tensors"]) == 20
    assert not any(t["id"] in ("NLL", "TargetIDs", "TargetPositions") for t in one["tensors"])
    original_logits = next(t["values"] for t in result["tensors"] if t["id"] == "Logits")
    future = derive_iv40({**s, "x2": 98})
    future_logits = next(t["values"] for t in future["tensors"] if t["id"] == "Logits")
    assert future_logits[:6] == original_logits[:6]
    past = derive_iv40({**s, "x0": 98})
    assert next(t["values"] for t in past["tensors"] if t["id"] == "Logits")[6:] == original_logits[6:]
    # Each call owns its detached records; an earlier result cannot change.
    saved = result["tensors"][0]["values"][:]
    changed = derive_iv40({**s, "e00": 2})
    changed["tensors"][0]["values"][0] = -999
    assert result["tensors"][0]["values"] == saved


if __name__ == "__main__":
    _helper.run(derive_iv40, DEFAULT_IV40)

Its shared helper contains the state validation, compact lookup, affine products, stable probabilities and observed-transition reduction:

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.

"""Part X canonical NumPy boundaries and one-token conditional mathematics.

Public prediction IDs (97, 98, 512) name a, b, EOS; compact classes are
(0, 1, 2). Only a and b can be current inputs, so E has TWO rows. EOS
requires no input embedding here. PAD=768 is storage, never a class/gather.
All source is authored under the runtime hold: no reference or self-check run.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np

CLASS_IDS = (97, 98, 512)
CONTENT_IDS = (97, 98)
PAD = 768
PARAMETER_DEFAULTS = MappingProxyType(dict(
    e00=1, e01=0, e10=0, e11=1,
    u00=1, u01=0, u02=0, u10=0, u11=1, u12=0,
    b0=0, b1=0, b2=0,
))
IV40_DEFAULTS = MappingProxyType(dict(T=3, x0=97, x1=98, x2=97, **PARAMETER_DEFAULTS))
IV41_DEFAULTS = MappingProxyType(dict(s0=97, s1=98, s2=512, s3=768,
                                       m0=1, m1=1, m2=1, **PARAMETER_DEFAULTS))
IV42_DEFAULTS = MappingProxyType(dict(
    z00=1, z01=0, z02=0, z10=0, z11=1, z12=0, z20=0, z21=0, z22=1,
    y0=97, y1=98, y2=512, m0=1, m1=1, m2=1,
))


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    """No coercion of bool/string; catch huge Python integers before binary64 use."""
    if type(value) not in (int, float) and not isinstance(value, (np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    try:
        number = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.") from error
    if not math.isfinite(number):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    return number


def language_state(state, chapter):
    """Validate the complete own raw state before sequence semantics or lookup.

    An exact dict has no inherited fields, descriptors or overridden getters.
    In particular, arbitrary Mapping objects and dict subclasses are rejected.
    Copy a read-only DEFAULT_IVxx with dict(DEFAULT_IVxx) before making edits.
    """
    if type(chapter) is not int or chapter not in (40, 41, 42):
        raise NumericalFault("INVALID_INPUT", "Use language chapter 40, 41 or 42.")
    defaults = {40: IV40_DEFAULTS, 41: IV41_DEFAULTS, 42: IV42_DEFAULTS}[chapter]
    if type(state) is not dict or any(type(key) is not str for key in state):
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named own scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extras, including inactive slots.")
    checked = {}
    for key in defaults:
        if type(state[key]) not in (int, float):
            raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
        value = finite(state[key], key)
        if key == "T":
            low, high, integer = 1, 3, True
        elif key.startswith(("x", "s", "y")):
            choices = CONTENT_IDS if key.startswith("x") else (*CLASS_IDS, PAD) if key.startswith("s") else CLASS_IDS
            if value not in choices:
                raise NumericalFault("INVALID_INPUT", f"{key} must be one of the declared public token IDs.")
            checked[key] = int(value)
            continue
        elif key.startswith("m"):
            low, high, integer = 0, 1, True
        elif key.startswith("z"):
            low, high, integer = -40, 40, False
        elif key.startswith("b"):
            low, high, integer = -4, 4, False
        else:
            low, high, integer = -2, 2, False
        if not low <= value <= high or (integer and not value.is_integer()):
            raise NumericalFault("INVALID_INPUT", f"{key} must be {'an integer ' if integer else ''}between {low} and {high}.")
        checked[key] = int(value) if integer else value
    if chapter == 41:
        slots = [checked[f"s{t}"] for t in range(4)]
        if slots[0] not in CONTENT_IDS:
            raise NumericalFault("INVALID_INPUT", "The first slot must be a or b.")
        padding_seen, eos_seen = False, False
        for identifier in slots:
            if identifier == PAD:
                padding_seen = True
            elif padding_seen:
                raise NumericalFault("INVALID_INPUT", "PAD must form a contiguous tail; do not silently trim or reorder.")
            elif eos_seen:
                raise NumericalFault("INVALID_INPUT", "EOS may appear once, only as the last non-PAD token.")
            elif identifier == 512:
                eos_seen = True
    return checked


def parameters(state):
    """Actual parameter arrays: content E[2,2], output U[2,3], bias[3]."""
    E = np.array([[state[f"e{r}{d}"] for d in range(2)] for r in range(2)], dtype=np.float64)
    U = np.array([[state[f"u{d}{c}"] for c in range(3)] for d in range(2)], dtype=np.float64)
    bias = np.array([state[f"b{c}"] for c in range(3)], dtype=np.float64)
    return E, U, bias


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


_JSON_INT = int


def run(derive, defaults):
    """No arg: defaults; one complete JSON state: replacement; '-': JSON stdin.

    This CLI never invokes source_self_check. Importing a wrapper likewise only
    declares its callable reference; it does not derive a lesson or run 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=(",", ":")))


def affine_values(E, U, bias, identifier):
    """Two explicit products, their sum and bias; never read a future target.

    The separate product arrays retain the exact operands/results for the adopted
    trace adapter. No dot()/BLAS reduction changes the addition order.
    """
    if identifier not in CONTENT_IDS:
        raise NumericalFault("INVALID_INPUT", "Only a or b has an active input embedding.")
    row = CONTENT_IDS.index(identifier)
    h = E[row].copy()
    product0 = np.empty(3, dtype=np.float64)
    product1 = np.empty(3, dtype=np.float64)
    sums = np.empty(3, dtype=np.float64)
    logits = np.empty(3, dtype=np.float64)
    for c in range(3):
        product0[c] = finite(float(h[0]) * float(U[0, c]), "first affine product")
        product1[c] = finite(float(h[1]) * float(U[1, c]), "second affine product")
        sums[c] = finite(float(product0[c]) + float(product1[c]), "affine sum")
        logits[c] = finite(float(sums[c]) + float(bias[c]), "affine logit")
    return row, h, product0, product1, sums, logits


def stable_values(logits):
    """Stable three-class normalization; shifted exponentials are actual values.

    With |z|<=40 the smallest exp is exp(-80)>0, and 1<=S<=3. The
    shifted maximum contributes exp(0)=1; no epsilon/clipping is necessary.
    """
    if type(logits) is not np.ndarray or logits.shape != (3,) or logits.dtype != np.dtype(np.float64):
        raise NumericalFault("SHAPE_MISMATCH", "A logit row requires float64 storage of shape [3].")
    maximum = max(finite(float(logits[c]), "logit") for c in range(3))
    shifted = np.empty(3, dtype=np.float64)
    terms = np.empty(3, dtype=np.float64)
    probabilities = np.empty(3, dtype=np.float64)
    denominator = 0.0
    for c in range(3):
        shifted[c] = finite(float(logits[c]) - maximum, "shifted logit")
        terms[c] = finite(math.exp(float(shifted[c])), "shifted exponential")
        denominator = finite(denominator + float(terms[c]), "softmax denominator")
    log_sum = finite(math.log(denominator), "log shifted exponential sum")
    lse = finite(maximum + log_sum, "logsumexp")
    for c in range(3):
        probabilities[c] = finite(float(terms[c]) / denominator, "class probability")
    # Strict greater-than preserves the lowest compact class on exact ties.
    argmax = 0
    for c in range(1, 3):
        if float(logits[c]) > float(logits[argmax]):
            argmax = c
    return maximum, shifted, terms, denominator, log_sum, lse, probabilities, argmax


def target_nll(maximum, target_logit, log_sum):
    """Factored NLL independently from P: (m-z_y)+log(S), never -log(P)."""
    gap = finite(maximum - target_logit, "target gap")
    return gap, finite(gap + log_sum, "negative log likelihood")


def source_self_check():
    """DEFERRED: an owner must explicitly call this after lifting the hold.

    These assert declarations exercise numerical boundaries/storage directly;
    they are neither an oracle nor a replacement for independent D assurance.
    """
    s = language_state(dict(IV40_DEFAULTS), 40)
    E, U, bias = parameters(s)
    assert E.shape == (2, 2) and E.dtype == np.dtype(np.float64)
    assert U.shape == (2, 3) and bias.shape == (3,)
    _, _, p0, p1, sums, logits = affine_values(E, U, bias, 97)
    assert logits.tolist() == [1.0, 0.0, 0.0]
    assert (p0 + p1).tolist() == sums.tolist()
    m, shifts, terms, total, log_sum, lse, probabilities, argmax = stable_values(logits)
    assert m == 1 and argmax == 0 and shifts.tolist() == [0.0, -1.0, -1.0]
    assert terms[0] == 1 and math.isclose(total, 1 + 2 / math.e)
    assert math.isclose(sum(probabilities), 1) and lse == m + log_sum
    assert target_nll(m, 0.0, log_sum)[1] == 1 + log_sum
    for bad in (True, np.bool_(True), "1", float("nan"), float("inf"), 10 ** 10000):
        try:
            language_state({**dict(IV40_DEFAULTS), "e11": bad}, 40)
        except NumericalFault as error:
            assert error.code == "NONFINITE"
        else:
            raise AssertionError("Inactive/bool/huge/nonfinite parameter accepted")
    for patch in ({"T": 1.5}, {"x2": 512}, {"e11": 3}, {"extra": 0}):
        try:
            language_state({**dict(IV40_DEFAULTS), **patch}, 40)
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Invalid exact state accepted")
    tiny = float.fromhex("0x0.0000000000001p-1022")
    near = np.array([0.0, tiny, 0.0], dtype=np.float64)
    near_values = stable_values(near)
    assert near_values[7] == 1
    assert near_values[6][0] == near_values[6][1] == near_values[6][2]
    assert stable_values(np.zeros(3, dtype=np.float64))[7] == 0
    for bad_stage in (99, True):
        try:
            language_state(dict(IV40_DEFAULTS), bad_stage)
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Invalid chapter accepted")
    try:
        distribution(None, "bad", LanguageTrace())
    except NumericalFault as error:
        assert error.code == "SHAPE_MISMATCH"
    else:
        raise AssertionError("Non-array logit row accepted")
    row = distribution(near, "near", LanguageTrace())
    for bad_weight in (2, True, "0", float("nan")):
        try:
            target_loss(row, 97, bad_weight, "bad", LanguageTrace())
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT"
        else:
            raise AssertionError("Invalid target weight accepted")
    class GetterDict(dict):
        def __getitem__(self, key):
            raise AssertionError("Validation read a user getter")
    try:
        language_state(GetterDict(IV40_DEFAULTS), 40)
    except NumericalFault as error:
        assert error.code == "INVALID_INPUT"
    else:
        raise AssertionError("Mapping subclass accepted")


class LanguageTrace:
    """Detached finite StepRecords, in declaration order, with flat output aliases."""
    def __init__(self):
        self.steps = []
        self.outputs = {}

    def add(self, identifier, label, equation, explanation, inputs, outputs):
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        inputs = {key: finite(value, key) for key, value in inputs.items()}
        outputs = {key: finite(value, key) for key, value in outputs.items()}
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=outputs))
        self.outputs.update({f"{identifier}_{key}": value for key, value in outputs.items()})

    def result(self, summary, tensors):
        # Signed first aliases precede ALL flattened step outputs. No state update.
        outputs = {key: finite(value, key) for key, value in {**summary, **self.outputs}.items()}
        return dict(status="defined", outputs=outputs, steps=self.steps, tensors=tensors)


def tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    """Require real shaped NumPy storage, then detach in dense row-major order."""
    if type(shape) is not list or type(axes) is not list or not 1 <= len(shape) <= 4 or len(shape) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if any(type(axis) is not str or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
    if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    if dtype not in ("float64", "int32"):
        raise NumericalFault("INVALID_INPUT", f"{identifier}: require float64 or int32 storage.")
    if type(values) is not np.ndarray or values.shape != tuple(shape) or values.dtype != np.dtype(dtype):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: shaped storage and declared dtype must agree.")
    flattened = []
    for index, value in enumerate(values.reshape(-1, order="C")):
        number = finite(value, f"{identifier}[{index}]")
        if dtype == "int32":
            if not number.is_integer() or not -2147483648 <= number <= 2147483647:
                raise NumericalFault("INVALID_INPUT", f"{identifier}[{index}] must be int32.")
            number = int(number)
        flattened.append(number)
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype=dtype,
                values=flattened, provenance=provenance, precision=0 if dtype == "int32" else 8)


def class_row(identifier):
    if identifier not in CLASS_IDS:
        raise NumericalFault("INVALID_INPUT", "A prediction target must be a=97, b=98 or EOS=512; PAD is not a class.")
    return CLASS_IDS.index(identifier)


def content_row(identifier):
    if identifier not in CONTENT_IDS:
        raise NumericalFault("INVALID_INPUT", "A computed input must be a=97 or b=98; E has only two content rows.")
    return CONTENT_IDS.index(identifier)


def distribution(logits, prefix, trace):
    """Bind actual NumPy stable row values to the owner-adopted ordered record."""
    maximum, shifted, terms, denominator, logS, lse, probabilities, next_row = stable_values(logits)
    trace.add(f"{prefix}_max", "Find the row maximum", "m=max(z0,z1,z2)",
              "Every class is allowed. This maximum is a numerical stabilizer, not a target lookup.",
              dict(z0=logits[0], z1=logits[1], z2=logits[2]), dict(max=maximum))
    for c in range(3):
        trace.add(f"{prefix}_exp_{c}", f"Shift and exponentiate class {c}", "shifted=z_c-m; term=exp(shifted)",
                  "Subtract the same maximum from all classes. At least one term is exactly exp(0)=1; no clipping or epsilon is used.",
                  dict(c=c, logit=logits[c], max=maximum), dict(shifted=shifted[c], term=terms[c]))
    trace.add(f"{prefix}_normalize", "Sum shifted terms and save logsumexp", "S=(term0+term1)+term2; logS=ln(S); LSE=m+logS",
              "The shared stableSoftmax adds the three terms left to right from zero. LSE is saved, while NLL will use the factored max-minus-target form.",
              dict(term0=terms[0], term1=terms[1], term2=terms[2], max=maximum),
              dict(denominator=denominator, logS=logS, lse=lse))
    for c in range(3):
        trace.add(f"{prefix}_probability_{c}", f"Normalize class {c}", "P_c=term_c/S",
                  "This is the stored binary64 probability, before any display formatting; class rows are compact indices, not public IDs.",
                  dict(c=c, term=terms[c], denominator=denominator), dict(probability=probabilities[c]))
    next_id, next_probability = CLASS_IDS[next_row], float(probabilities[next_row])
    trace.add(f"{prefix}_argmax", "Select the most probable next class", "argmax computed logits; on an exact logit tie keep the smallest compact class",
              "Order is a,b,EOS. Stored probabilities may round to an apparent tie even for unequal logits. Keep the selected class probability; never feed the prediction back as a teacher-forced input.",
              dict(z0=logits[0], z1=logits[1], z2=logits[2]),
              dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
    return dict(logits=logits.copy(), max=maximum, shifted=shifted, terms=terms,
                denominator=denominator, logS=logS, lse=lse, probabilities=probabilities,
                nextRow=next_row, nextID=next_id, nextProbability=next_probability)


def affine_distribution(state, t, public_id, prefix, trace):
    """A current-token-only calculation: no target argument exists here."""
    E, U, bias = parameters(state)
    input_row, h, product0, product1, sums, logits = affine_values(E, U, bias, public_id)
    trace.add(f"{prefix}_input", f"Read observed current token at position {t}",
              "r=contentRow(currentID); h=E[r,:]; receptiveStart=receptiveEnd=t",
              "Only the observed current token enters this one-token affine conditional. A later target is not an operand; older prefix tokens are outside this declared field.",
              dict(t=t, publicID=public_id), dict(inputRow=input_row, receptiveStart=t, receptiveEnd=t, h0=h[0], h1=h[1]))
    for c in range(3):
        trace.add(f"{prefix}_affine_{c}", f"Output affine for compact class {c}",
                  "product0=h0*u0; product1=h1*u1; sum=product0+product1; logit=sum+bias",
                  "Both products, their sum and the bias addition are actual operands and results. No target or predicted previous token enters this affine.",
                  dict(c=c, h0=h[0], h1=h[1], u0=U[0, c], u1=U[1, c], bias=bias[c]),
                  dict(product0=product0[c], product1=product1[c], sum=sums[c], logit=logits[c]))
    row = distribution(logits, prefix, trace)
    row.update(inputRow=input_row, h=h)
    return row


def target_loss(row, target_id, weight, prefix, trace):
    """Look up the observed class AFTER prediction, retaining real masked NLL."""
    if isinstance(weight, (bool, np.bool_)) or not isinstance(weight, (int, float, np.integer, np.floating)) or weight not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "Target loss weight must be numeric 0 or 1.")
    target = class_row(target_id)
    target_logit, probability = float(row["logits"][target]), float(row["probabilities"][target])
    gap, nll = target_nll(row["max"], target_logit, row["logS"])
    contribution = finite(weight * nll, "weighted NLL")
    trace.add(f"{prefix}_target", "Score the observed next target after prediction", "gap=m-z_y; nll=gap+logS; contribution=weight*nll",
              "NLL is negative log likelihood in nats (natural-log units). It is computed from logits, not -log of a rounded probability or a rounded LSE subtraction. A manual zero weight leaves the actual NLL visible.",
              dict(targetID=target_id, targetRow=target, targetLogit=target_logit, max=row["max"], logS=row["logS"], probability=probability, weight=weight),
              dict(gap=gap, nll=nll, contribution=contribution))
    return dict(targetID=target_id, targetRow=target, targetLogit=target_logit,
                probability=probability, gap=gap, nll=nll, weight=weight, contribution=contribution)


def reduce_loss(losses, trace):
    """Both numerator and denominator use the effective numeric masks."""
    count, loss_sum = 0, 0.0
    for k, loss in enumerate(losses):
        weight, nll, contribution = loss["weight"], loss["nll"], loss["contribution"]
        previous_count, previous_sum = count, loss_sum
        count += weight
        loss_sum = finite(previous_sum + contribution, "weighted loss sum")
        trace.add(f"reduce_{k}", f"Accumulate computed loss row {k}",
                  "count=previousCount+weight; contribution=weight*nll; lossSum=previousLossSum+contribution",
                  "The effective numeric mask controls both numerator and denominator. Uncomputed PAD rows never enter this list.",
                  dict(k=k, weight=weight, nll=nll, previousCount=previous_count, previousLossSum=previous_sum),
                  dict(validCount=count, contribution=contribution, lossSum=loss_sum))
    if count == 0:
        raise NumericalFault("UNAVAILABLE", "No valid target remains: every target is PAD or has effective mask 0. Mean NLL and perplexity are undefined.")
    mean_nll = finite(loss_sum / count, "mean NLL")
    perplexity = finite(math.exp(mean_nll), "perplexity")
    trace.add("reduction", "Average over valid targets and exponentiate", "meanNLL=lossSum/validCount; perplexity=exp(meanNLL)",
              "The denominator counts effective targets, not storage slots or all computed rows. Perplexity is an exponential of mean NLL, not an arithmetic mean of inverse probabilities.",
              dict(validCount=count, lossSum=loss_sum), dict(meanNLL=mean_nll, perplexity=perplexity))
    return dict(validCount=count, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity)


def class_tensors():
    return [tensor("ClassIDs", [3], ["Class"], np.array(CLASS_IDS, dtype=np.int32),
                   "Compact prediction class c=0,1,2 maps to public ID a=97,b=98,EOS=512; PAD is excluded.", "int32")]


def parameter_tensors(state):
    E, U, bias = parameters(state)
    return [
        tensor("EmbeddingIDs", [2], ["Content"], np.array(CONTENT_IDS, dtype=np.int32),
               "Embedding row r=0,1 maps only to a=97,b=98; EOS is never an active input.", "int32"),
        tensor("E", [2, 2], ["Content", "Feature"], E, "All four editable content embedding entries; no EOS or PAD row."),
        tensor("U", [2, 3], ["Feature", "Class"], U, "All six editable output weights; feature-last h[2] times U[2,3]."),
        tensor("Bias", [3], ["Class"], bias, "All three editable output biases, added after the two-product sum."),
    ]


def distribution_tensors(rows, axis):
    """Only actual computed rows enter these arrays; no PAD numeric padding."""
    if not rows:
        return []
    n = len(rows)
    return [
        tensor("Logits", [n, 3], [axis, "Class"], np.stack([r["logits"] for r in rows]), "Actual pre-softmax logits in compact a,b,EOS class order."),
        tensor("Shifted", [n, 3], [axis, "Class"], np.stack([r["shifted"] for r in rows]), "Each saved logit minus that row's maximum."),
        tensor("Terms", [n, 3], [axis, "Class"], np.stack([r["terms"] for r in rows]), "exp(Shifted), from the shared stableSoftmax; no masked classes."),
        tensor("Max", [n], [axis], np.array([r["max"] for r in rows], dtype=np.float64), "Maximum of the three logits for each computed row."),
        tensor("Denominator", [n], [axis], np.array([r["denominator"] for r in rows], dtype=np.float64), "Left-to-right sum from zero of the three shifted exponential terms."),
        tensor("LogS", [n], [axis], np.array([r["logS"] for r in rows], dtype=np.float64), "Natural log of the shifted exponential denominator."),
        tensor("LSE", [n], [axis], np.array([r["lse"] for r in rows], dtype=np.float64), "Saved max+LogS; not subtracted from a target logit to compute NLL."),
        tensor("P", [n, 3], [axis, "Class"], np.stack([r["probabilities"] for r in rows]), "Terms/Denominator, actual binary64 probabilities before display rounding."),
        tensor("NextRows", [n], [axis], np.array([r["nextRow"] for r in rows], dtype=np.int32), "Argmax computed logit; exact logit ties choose the lowest row a,b,EOS.", "int32"),
        tensor("NextIDs", [n], [axis], np.array([r["nextID"] for r in rows], dtype=np.int32), "Public prediction IDs mapped from NextRows; these are not teacher-forced inputs.", "int32"),
    ]


def target_tensors(losses, axis):
    if not losses:
        return []
    n = len(losses)
    return [
        tensor("TargetLogits", [n], [axis], np.array([r["targetLogit"] for r in losses], dtype=np.float64), "Actual logit gathered at the compact target class, after the causal prediction."),
        tensor("TargetProbability", [n], [axis], np.array([r["probability"] for r in losses], dtype=np.float64), "Actual saved probability gathered for a non-PAD target; never used as a rounded NLL input."),
        tensor("NLL", [n], [axis], np.array([r["nll"] for r in losses], dtype=np.float64), "Factored (max-targetLogit)+LogS in natural-log units, including manually masked computed rows."),
        tensor("Weights", [n], [axis], np.array([r["weight"] for r in losses], dtype=np.int32), "Effective numeric 0/1 weights of computed target rows only.", "int32"),
        tensor("Contributions", [n], [axis], np.array([r["contribution"] for r in losses], dtype=np.float64), "Weight*NLL; manual mask zero is a real weighted zero, not an uncomputed PAD loss."),
    ]


def derive40(state):
    """Actual continuation chain, conditioned on the already-given first token."""
    s = language_state(state, 40)
    trace = LanguageTrace()
    T, transition_count = s["T"], s["T"] - 1
    ids = np.array([s[f"x{t}"] for t in range(T)], dtype=np.int32)
    rows, losses = [], []
    trace.add("setup", "Validate the full state and disclose the receptive field", "contextLength=T; transitionCount=T-1; receptiveField=1",
              "All stored token slots and all thirteen parameters are checked, even when inactive. The full observed prefix is visible, but this affine toy uses only its current token.",
              s, dict(contextLength=T, transitionCount=transition_count, receptiveField=1))
    likelihood, conditional_nll = 1.0, 0.0
    for t in range(T):
        row = affine_distribution(s, t, int(ids[t]), f"row_{t}", trace)
        rows.append(row)
        if t < transition_count:
            # Only the completed causal row can be scored against its next token.
            loss = target_loss(row, int(ids[t + 1]), 1, f"row_{t}", trace)
            losses.append(loss)
            previous_likelihood, previous_nll = likelihood, conditional_nll
            likelihood = finite(previous_likelihood * loss["probability"], "conditional likelihood")
            conditional_nll = finite(previous_nll + loss["nll"], "conditional NLL")
            trace.add(f"transition_{t}", f"Include observed transition {t} to {t + 1}",
                      "likelihood=previousLikelihood*targetProbability; conditionalNLL=previousNLL+nll",
                      "Only after computing the causal distribution does the observed next token select a class. The first token is given, so no first-token or BOS probability is invented.",
                      dict(t=t, previousLikelihood=previous_likelihood, probability=loss["probability"], previousNLL=previous_nll, nll=loss["nll"]),
                      dict(likelihood=likelihood, conditionalNLL=conditional_nll))
    trace.add("conditional", "Finish the observed continuation conditional on the first token",
              "likelihood=product of observed transition probabilities; conditionalNLL=sum of transition NLLs",
              "At T=1 there are no transitions: the empty product is 1 and the empty sum is 0 by definition. The current next-token distribution still exists; empty data is not predictive success.",
              dict(transitionCount=transition_count), dict(likelihood=likelihood, conditionalNLL=conditional_nll))
    last = rows[-1]
    tensors = [
        *class_tensors(), *parameter_tensors(s),
        tensor("InputIDs", [T], ["Position"], ids, "Observed active prefix; the first token is given, not assigned a model probability.", "int32"),
        tensor("InputRows", [T], ["Position"], np.array([r["inputRow"] for r in rows], dtype=np.int32), "Compact a/b embedding row for each observed current token.", "int32"),
        tensor("ReceptiveStart", [T], ["Position"], np.arange(T, dtype=np.int32), "Inclusive receptive-field start; only the current position is read.", "int32"),
        tensor("ReceptiveEnd", [T], ["Position"], np.arange(T, dtype=np.int32), "Inclusive receptive-field end, equal to the current position.", "int32"),
        tensor("H", [T, 2], ["Position", "Feature"], np.stack([r["h"] for r in rows]), "Actual E row gathered from the current observed token only."),
        *distribution_tensors(rows, "Position"),
    ]
    # No zero-length Transition tensor and no fake last-row NLL for T=1.
    if transition_count > 0:
        tensors.extend([
            tensor("TargetPositions", [transition_count], ["Transition"], np.arange(1, T, dtype=np.int32), "Observed next-token position selected only after each causal distribution.", "int32"),
            tensor("TargetIDs", [transition_count], ["Transition"], np.array([r["targetID"] for r in losses], dtype=np.int32), "Observed continuation IDs x1 through x(T-1); x0 is given.", "int32"),
            tensor("TargetRows", [transition_count], ["Transition"], np.array([r["targetRow"] for r in losses], dtype=np.int32), "Compact prediction class for each observed next target.", "int32"),
            *target_tensors(losses, "Transition"),
        ])
    return trace.result(dict(contextLength=T, nextID=last["nextID"], nextProbability=last["nextProbability"],
                             conditionalNLL=conditional_nll, likelihood=likelihood, receptiveField=1), tensors)


def derive41(state):
    """Separate physical storage metadata from compact, real computed rows."""
    s = language_state(state, 41)
    trace = LanguageTrace()
    slots = np.array([s[f"s{t}"] for t in range(4)], dtype=np.int32)
    input_ids, target_ids = slots[:-1].copy(), slots[1:].copy()
    target_rows = np.empty(3, dtype=np.int32)
    requested = np.array([s[f"m{t}"] for t in range(3)], dtype=np.int32)
    padding, computed, effective = (np.empty(3, dtype=np.int32) for _ in range(3))
    positions, rows, losses = [], [], []
    trace.add("setup", "Validate four physical slots and three requested masks", "physicalSlots=4; physicalRows=3; classCount=3; receptiveField=1",
              "Non-PAD tokens form a prefix starting with a/b; optional EOS is the last non-PAD token. PAD is storage only. All thirteen parameters are validated, including unused rows.",
              s, dict(physicalSlots=4, physicalRows=3, classCount=3, receptiveField=1))
    for t in range(3):
        input_id, target_id, requested_mask = int(input_ids[t]), int(target_ids[t]), int(requested[t])
        is_padding = int(target_id == PAD)
        # The PAD sentinel controls existence; a target class never enters affine.
        row = None if is_padding else affine_distribution(s, t, input_id, f"row_{t}", trace)
        loss = None if row is None else target_loss(row, target_id, requested_mask, f"row_{t}", trace)
        target_row = -1 if loss is None else loss["targetRow"]
        is_computed, effective_mask = (0, 0) if row is None else (1, requested_mask)
        target_rows[t], padding[t], computed[t], effective[t] = target_row, is_padding, is_computed, effective_mask
        explanation = (
            "This row uses the actual observed input, even if the preceding prediction disagrees. Manual mask 0 preserves its true logits, probability and NLL, then excludes its contribution and count."
            if row is not None else
            "The target is PAD: no embedding gather, class probability or NLL is computed. targetRow=-1 is metadata, never a gather index. An EOS input in this ignored physical row needs no embedding."
        )
        trace.add(f"row_{t}_alignment", f"Physical row {t}: observed input and next target",
                  "inputID=s[t]; targetID=s[t+1]; computed=1-isPadding; effectiveMask=computed*requestedMask", explanation,
                  dict(t=t, inputID=input_id, targetID=target_id, requestedMask=requested_mask),
                  dict(targetRow=target_row, isPadding=is_padding, computed=is_computed, effectiveMask=effective_mask))
        if row is not None:
            positions.append(t)
            rows.append(row)
            losses.append(loss)
    # A zero effective count faults before allocating any nonexistent loss tensor.
    summary = reduce_loss(losses, trace)
    K = len(rows)
    tensors = [
        *class_tensors(), *parameter_tensors(s),
        tensor("Slots", [4], ["PhysicalSlot"], slots, "All four physical storage slots, including the untrimmed PAD tail.", "int32"),
        tensor("InputIDs", [3], ["PhysicalRow"], input_ids, "Physical row t reads actual slot s[t], not a previous argmax.", "int32"),
        tensor("TargetIDs", [3], ["PhysicalRow"], target_ids, "Physical row t targets s[t+1]; PAD768 remains visible storage metadata.", "int32"),
        tensor("TargetRows", [3], ["PhysicalRow"], target_rows, "Compact target class for non-PAD rows; -1 marks PAD and is never gathered.", "int32"),
        tensor("RequestedMask", [3], ["PhysicalRow"], requested, "All three learner-requested numeric 0/1 masks, before structural PAD exclusion.", "int32"),
        tensor("IsPadding", [3], ["PhysicalRow"], padding, "1 exactly when the physical row targets PAD768.", "int32"),
        tensor("Computed", [3], ["PhysicalRow"], computed, "1 for a real non-PAD target, including a manually masked row; 0 for uncomputed PAD.", "int32"),
        tensor("EffectiveMask", [3], ["PhysicalRow"], effective, "Requested mask for a computed row; zero for PAD. Both numerator and denominator use this mask.", "int32"),
        tensor("ComputedPositions", [K], ["ComputedRow"], np.array(positions, dtype=np.int32), "Explicit compact computed-row index to physical row t map; no fake PAD numeric rows.", "int32"),
        tensor("InputRows", [K], ["ComputedRow"], np.array([r["inputRow"] for r in rows], dtype=np.int32), "Compact a/b embedding rows for computed positions only.", "int32"),
        tensor("H", [K, 2], ["ComputedRow", "Feature"], np.stack([r["h"] for r in rows]), "Current observed input embeddings for computed positions only; no EOS or PAD embedding."),
        *distribution_tensors(rows, "ComputedRow"), *target_tensors(losses, "ComputedRow"),
    ]
    return trace.result(summary, tensors)


def derive42(state):
    """Direct stable NLL and its analytic weighted-mean logit derivatives."""
    s = language_state(state, 42)
    trace = LanguageTrace()
    logits = np.array([[s[f"z{t}{c}"] for c in range(3)] for t in range(3)], dtype=np.float64)
    ids = np.array([s[f"y{t}"] for t in range(3)], dtype=np.int32)
    masks = np.array([s[f"m{t}"] for t in range(3)], dtype=np.int32)
    rows, losses = [], []
    trace.add("setup", "Validate direct logits, target IDs and numeric masks", "rowCount=3; classCount=3; logits in [-40,40]; masks in {0,1}",
              "Every row is computed, even with manual mask zero. Public IDs map to three compact prediction classes; PAD is not available here.",
              s, dict(rowCount=3, classCount=3))
    for t in range(3):
        row_logits = logits[t].copy()
        trace.add(f"row_{t}_logits", f"Read all three logits for row {t}", "z=[z_t0,z_t1,z_t2]",
                  "These are editable finite scores, not probabilities. The target is consulted only after the complete probability distribution is computed.",
                  dict(t=t, z0=row_logits[0], z1=row_logits[1], z2=row_logits[2]),
                  dict(z0=row_logits[0], z1=row_logits[1], z2=row_logits[2]))
        row = distribution(row_logits, f"row_{t}", trace)
        rows.append(row)
        losses.append(target_loss(row, int(ids[t]), int(masks[t]), f"row_{t}", trace))
    summary = reduce_loss(losses, trace)
    gradient = np.empty((3, 3), dtype=np.float64)
    for t in range(3):
        for c in range(3):
            weight, target = losses[t]["weight"], losses[t]["targetRow"]
            probability = float(rows[t]["probabilities"][c])
            indicator = int(c == target)
            factor = finite(weight / summary["validCount"], "mean-gradient factor")
            difference = finite(probability - indicator, "probability minus one-hot")
            # Store positive exact zero on masked rows, not signed zero from 0*x.
            value = 0.0 if weight == 0 else finite(factor * difference, "logit gradient")
            gradient[t, c] = value
            trace.add(f"gradient_{t}_{c}", f"Mean-loss derivative for row {t}, class {c}",
                      "indicator=1(c==targetRow); factor=weight/count; difference=P-indicator; gradient=factor*difference",
                      "One-hot means 1 at the target class and 0 elsewhere. A masked row has exact zero derivatives. This analytic derivative is a calculation, not independent numerical validation or a parameter update.",
                      dict(t=t, c=c, weight=weight, validCount=summary["validCount"], probability=probability, targetRow=target),
                      dict(indicator=indicator, factor=factor, difference=difference, gradient=value))
    tensors = [
        *class_tensors(),
        tensor("TargetIDs", [3], ["Row"], ids, "Observed public target IDs for the three direct-logit rows; no PAD.", "int32"),
        tensor("TargetRows", [3], ["Row"], np.array([r["targetRow"] for r in losses], dtype=np.int32), "Public targets mapped explicitly to compact class rows 0,1,2.", "int32"),
        *distribution_tensors(rows, "Row"), *target_tensors(losses, "Row"),
        tensor("dLogits", [3, 3], ["Row", "Class"], gradient, "Analytic weighted-mean NLL derivative (weight/count)*(P-oneHot); exact zero on masked rows, no parameter update."),
    ]
    return trace.result(summary, tensors)

Follow the input ID to its content row, the two products to each class logit, and the maximum/shift/terms to P. Only afterward follow the observed target to its probability and NLL. The UI, operation trace and tensor inspector consume the same derived record; trace selection explains saved operands rather than introducing another predictor. Source inspection and the exact hand expressions above do not constitute execution or Python/TypeScript parity evidence.

In Python, derive_iv40 is the wrapper and derive40 is its shared implementation. language_state validates the complete state. affine_distribution gathers the content row and records products; distribution uses stable_values for shifted softmax and logit-based selection. Only then does target_loss read the observed next target. The likelihood multiplication and conditional_nll addition follow the hand chain above. LanguageTrace and the tensor helpers detach the displayed record from the working NumPy arrays.

Keep language_reference.py beside the wrapper: its loader resolves from __file__, the file location, rather than guessing from the current directory. The wrapper supports defaults with no state argument, one complete replacement JSON state, or - for JSON on standard input. A partial object is not a patch. The callable source_self_check is declared separately and is not automatically run by importing or querying the wrapper.

Five corrective checks matched to the lab

These outlines follow the five actual graded questions in order. Live values refer to the starting inputs and update after edits, independently of the inspection selectors.

  1. At position t, which token may this one-token causal conditional use? The observed current token x(t) is already in the prefix. Its embedding alone enters this affine rule. A printed later target is still future information for this row; the full displayed prefix does not expand the one-token field.
  2. Which shapes and maps are correct for IDs97,98,512 with two features and a/b current inputs? E has shape [2,2] for a/b content rows, U [2,3] for compact a/b/EOS classes0/1/2, and bias [3]. Public ID512 does not allocate513 rows. EOS needs no current-input row here and PAD is not a prediction class.
  3. Which rule matches the current saved transition, or the T=1 empty case? When T>1, use transition_0: multiply its saved previousLikelihood by its actual target probability, and add its saved nll to previousNLL. At reset that first step is 1·(1/Z)=1/Z and 0+lnZ=lnZ; the second observed step completes 1/Z² and 2lnZ. Do not add probabilities, multiply NLLs or invent a first-token probability. When T=1 there is no transition_0: the observed continuation has empty product1 and empty sum0, while a real next-token distribution remains. Neither identity measures successful first-token prediction.
  4. At T=3, what remains fixed if only x2 changes? Both row0 and row1 logits stay fixed with parameters held fixed. Row1 subsequently scores its target x2, so its selected probability and NLL may change or may coincide for tied classes. Row2 uses the edited current token. A change in earlier logits would leak future information.
  5. At T=3, what does changing x0 while holding x2 and all parameters fixed demonstrate? Final logits stay fixed because the final affine reads only x2. This is the limited receptive field of this toy, not proof that earlier words cannot matter in language. Earlier observed transitions can change while the final distribution stays fixed.

Recap and bridge

  • Public IDs name items; compact rows address arrays, with two input rows and three output classes.
  • Each row predicts the next token from its disclosed one-token receptive field.
  • Softmax normalizes actual affine logits, and target selection occurs afterward.
  • Observed transition probabilities multiply; their NLLs add, conditional on the first token.

Next, IV-41 — Teacher Forcing and Shifted Targets keeps actual sequence inputs aligned with shifted targets and explains which stored positions contribute to the loss.