The neural notebook
← All chapters

IV-42 / Part X · Language Modeling

Cross-Entropy, NLL and Perplexity

Derive factored stable target NLL, valid-token means, perplexity and every weighted logit gradient, with complete hand examples and honest floating-point limits.

Review the ideas this chapter uses

Two predictors can choose the same next token while assigning very different probabilities to the observed answer. We need a score that notices this difference, combines several observations and remains computable when probabilities are very small. We will derive that score directly from three editable logit rows, then show exactly how each score changes when a logit moves.

Learning objective: Compute token NLL, sequence loss, average and perplexity.

Compute it yourself

Cross-Entropy, NLL and Perplexity

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
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
validCount3
lossSum1.6543341417961532
meanNLL0.5514447139320511
perplexity1.7357588823428847
Direct logits row 0
Direct logits row 1
Direct logits row 2

validCount 3. lossSum 1.6543341417961532. meanNLL 0.5514447139320511. perplexity 1.7357588823428847. Validate direct logits, target IDs and numeric masks. Every row is computed, even with manual mask zero. Public IDs map to three compact prediction classes; PAD is not available here.. rowCount 3. classCount 3

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.

Inputs

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

Outputs

rowCount
3
classCount
3

From three logits to loss and its exact analytic derivative

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.

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.

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 a (ID97, compact class0) has target logit 1, probability 0.5761168847658291. NLL=(m−targetLogit)+ln(S) uses saved gap 0 plus saved ln(S) 0.5514447139320511, giving 0.5514447139320511 nats. Weight 1 gives contribution 0.5514447139320511. This observed target contributes to the objective.

Saved gradient_0_0: target indicator 1, weight/count factor 0.3333333333333333, probability-minus-indicator -0.4238831152341709, derivative -0.14129437174472362. One-hot is1 at the target class and0 elsewhere; a masked row has exact zero derivatives.

Analytic derivative of weighted mean NLL — saved values without display rounding
Rowd/d logit ad/d logit bd/d logit EOS
0-0.141294371744723620.070647185872361810.07064718587236181
10.07064718587236181-0.141294371744723620.07064718587236181
20.070647185872361810.07064718587236181-0.14129437174472362
Saved operations for physical row 0 — saved values without display rounding
Saved stepActual operandsActual results
row_0_logits
t=0
z0=1
z1=0
z2=0
z0=1
z1=0
z2=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=97
targetRow=0
targetLogit=1
max=1
logS=0.5514447139320511
probability=0.5761168847658291
weight=1
gap=0
nll=0.5514447139320511
contribution=0.5514447139320511

Effective count=3, weighted loss sum=1.6543341417961532, mean NLL=0.5514447139320511 nats, perplexity=1.7357588823428847. The denominator counts effective target weights. If none remain, the entire result becomes UNAVAILABLE rather than zero mean or perplexity1.

Weighted reduction and selected analytic derivative — saved values without display rounding
Saved stepActual operandsActual results
reduce_0
k=0
weight=1
nll=0.5514447139320511
previousCount=0
previousLossSum=0
validCount=1
contribution=0.5514447139320511
lossSum=0.5514447139320511
reduce_1
k=1
weight=1
nll=0.5514447139320511
previousCount=1
previousLossSum=0.5514447139320511
validCount=2
contribution=0.5514447139320511
lossSum=1.1028894278641022
reduce_2
k=2
weight=1
nll=0.5514447139320511
previousCount=2
previousLossSum=1.1028894278641022
validCount=3
contribution=0.5514447139320511
lossSum=1.6543341417961532
reduction
validCount=3
lossSum=1.6543341417961532
meanNLL=0.5514447139320511
perplexity=1.7357588823428847
gradient_0_0
t=0
c=0
weight=1
validCount=3
probability=0.5761168847658291
targetRow=0
indicator=1
factor=0.3333333333333333
difference=-0.4238831152341709
gradient=-0.14129437174472362

Perplexity is exp(mean NLL), a geometric measure of inverse target probability. Different tokenizers change the prediction units, so their perplexities are not directly comparable. A gradient here is a sensitivity, not an independent validation or a learning step.

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

validCount
3
lossSum
1.6543341417961532
meanNLL
0.5514447139320511
perplexity
1.7357588823428847
setup_rowCount
3
setup_classCount
3
row_0_logits_z0
1
row_0_logits_z1
0
row_0_logits_z2
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
0
row_0_target_nll
0.5514447139320511
row_0_target_contribution
0.5514447139320511
row_1_logits_z0
0
row_1_logits_z1
1
row_1_logits_z2
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
0
row_1_target_nll
0.5514447139320511
row_1_target_contribution
0.5514447139320511
row_2_logits_z0
0
row_2_logits_z1
0
row_2_logits_z2
1
row_2_max_max
1
row_2_exp_0_shifted
-1
row_2_exp_0_term
0.36787944117144233
row_2_exp_1_shifted
-1
row_2_exp_1_term
0.36787944117144233
row_2_exp_2_shifted
0
row_2_exp_2_term
1
row_2_normalize_denominator
1.7357588823428847
row_2_normalize_logS
0.5514447139320511
row_2_normalize_lse
1.551444713932051
row_2_probability_0_probability
0.21194155761708544
row_2_probability_1_probability
0.21194155761708544
row_2_probability_2_probability
0.5761168847658291
row_2_argmax_nextRow
2
row_2_argmax_nextID
512
row_2_argmax_nextProbability
0.5761168847658291
row_2_target_gap
0
row_2_target_nll
0.5514447139320511
row_2_target_contribution
0.5514447139320511
reduce_0_validCount
1
reduce_0_contribution
0.5514447139320511
reduce_0_lossSum
0.5514447139320511
reduce_1_validCount
2
reduce_1_contribution
0.5514447139320511
reduce_1_lossSum
1.1028894278641022
reduce_2_validCount
3
reduce_2_contribution
0.5514447139320511
reduce_2_lossSum
1.6543341417961532
reduction_meanNLL
0.5514447139320511
reduction_perplexity
1.7357588823428847
gradient_0_0_indicator
1
gradient_0_0_factor
0.3333333333333333
gradient_0_0_difference
-0.4238831152341709
gradient_0_0_gradient
-0.14129437174472362
gradient_0_1_indicator
0
gradient_0_1_factor
0.3333333333333333
gradient_0_1_difference
0.21194155761708544
gradient_0_1_gradient
0.07064718587236181
gradient_0_2_indicator
0
gradient_0_2_factor
0.3333333333333333
gradient_0_2_difference
0.21194155761708544
gradient_0_2_gradient
0.07064718587236181
gradient_1_0_indicator
0
gradient_1_0_factor
0.3333333333333333
gradient_1_0_difference
0.21194155761708544
gradient_1_0_gradient
0.07064718587236181
gradient_1_1_indicator
1
gradient_1_1_factor
0.3333333333333333
gradient_1_1_difference
-0.4238831152341709
gradient_1_1_gradient
-0.14129437174472362
gradient_1_2_indicator
0
gradient_1_2_factor
0.3333333333333333
gradient_1_2_difference
0.21194155761708544
gradient_1_2_gradient
0.07064718587236181
gradient_2_0_indicator
0
gradient_2_0_factor
0.3333333333333333
gradient_2_0_difference
0.21194155761708544
gradient_2_0_gradient
0.07064718587236181
gradient_2_1_indicator
0
gradient_2_1_factor
0.3333333333333333
gradient_2_1_difference
0.21194155761708544
gradient_2_1_gradient
0.07064718587236181
gradient_2_2_indicator
1
gradient_2_2_factor
0.3333333333333333
gradient_2_2_difference
-0.4238831152341709
gradient_2_2_gradient
-0.14129437174472362

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

TargetIDs

Row=3 · int32 · display precision 0 · Observed public target IDs for the three direct-logit rows; no PAD.

Storage indexValue
097
198
2512

TargetRows

Row=3 · int32 · display precision 0 · Public targets mapped explicitly to compact class rows 0,1,2.

Storage indexValue
00
11
22

Logits

Row=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
60
70
81

Shifted

Row=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
6-1
7-1
80

Terms

Row=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
60.36787944117144233
70.36787944117144233
81

Max

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

Storage indexValue
01
11
21

Denominator

Row=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

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

Storage indexValue
00.5514447139320511
10.5514447139320511
20.5514447139320511

LSE

Row=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

Row=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.21194155761708544
70.21194155761708544
80.5761168847658291

NextRows

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

Storage indexValue
00
11
22

NextIDs

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

Storage indexValue
097
198
2512

TargetLogits

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

Storage indexValue
01
11
21

TargetProbability

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

Storage indexValue
00.5761168847658291
10.5761168847658291
20.5761168847658291

NLL

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

Storage indexValue
00.5514447139320511
10.5514447139320511
20.5514447139320511

Weights

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

Storage indexValue
01
11
21

Contributions

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

Storage indexValue
00.5514447139320511
10.5514447139320511
20.5514447139320511

dLogits

Row=3 × Class=3 · float64 · display precision 8 · Analytic weighted-mean NLL derivative (weight/count)*(P-oneHot); exact zero on masked rows, no parameter update.

Storage indexValue
0-0.14129437174472362
10.07064718587236181
20.07064718587236181
30.07064718587236181
4-0.14129437174472362
50.07064718587236181
60.07064718587236181
70.07064718587236181
8-0.14129437174472362

At reset logits favor the matching a,b,EOS target by1. Subtract row maximum1, exponentiate shifted scores0,-1,-1, and sum S=1+2/exp(1). Target NLL is ln(S), mean NLL is ln(S), and perplexity is S. Logarithms use base e, so NLL is measured in nats.

The analytic mean-loss derivative is (mask/count)*(P-oneHot). With three active default rows, the target derivative is (exp(1)/(exp(1)+2)-1)/3 and each other class derivative1/(3*(exp(1)+2)). These sensitivities describe the current objective; they do not perform an update or independently validate it.

Set m0=0 to inspect real probabilities/NLL beside exact zero row gradients. Leave only m1=1: the denominator is1. Set all logits to0: every target has NLLln3 and perplexity3 when any mask remains active. With all masks0, the objective is unavailable. Direct logits are bounded to±40 so shifted exponentials and perplexity remain finite; no probability clipping is needed. Use the saved factored NLL, not the log of a displayed rounded probability.

Check your understanding

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

1. What do negative log likelihood (NLL) and perplexity measure in this lab?
2. At reset each target has the maximum logit1 and the other two logits0. Put S=1+2/exp(1). Which mean NLL and perplexity are correct?
3. Current row0/class0: probability=0.5761168847658291, target class=0, indicator=1, weight=1, effective count=3. Which derivative and scaling match the saved mean-loss record?
4. Add the same constant to all three logits within one row, keeping targets and masks fixed and staying in bounds. What should the mathematics predict?
5. Set every logit to0 and masks to [0,1,0], keeping any allowed targets. Which denominator, loss and perplexity follow?

Reset gives each of three targets its row’s largest logit: rows (1,0,0), (0,1,0), (0,0,1), with target IDs97,98,512. The mean NLL is ln(1+2/e), where e=exp(1), and perplexity is 1+2/e. Change a target while keeping logits fixed: probabilities stay fixed but the selected target probability and loss change. Toggle a mask to compare a row’s real NLL with its weighted contribution.

Review IV-41 — Teacher Forcing and Shifted Targets for shifted targets and the count denominator. The direct Book II prerequisites are VII.4 — Cross entropy and negative log-likelihood and VII.7 — Numerical stability: log-sum-exp and stable softmax: their authoritative source-map slugs are cross-entropy-nll and stable-logsumexp. Book III’s III-16 — Multiclass Classification and Softmax Regression connects these ideas to multiclass softmax regression. This lab isolates an objective; it does not run an optimizer, train a Transformer or independently validate its own analytic derivatives.

Vocabulary and the axes you are editing

A logit is a real score before probability normalization. Softmax converts a row of scores into positive class probabilities summing to one. A target identifies the class that actually occurred. Negative log-likelihood (NLL) is the negative natural logarithm of its assigned probability. A smaller NLL rewards assigning more probability to the observed outcome; it is not the same quantity as the fraction of correct argmax choices.

A natural logarithm, ln, reverses exp: ln(exp(v))=v. Here exp(v) means eve^v, with e=exp(1). A loss measured using ln has units called nats. A base-two logarithm would use bits instead and would require a correspondingly different inverse when converting to perplexity. All formulas in this lesson use natural logs.

There are three rows, indexed t=0,1,2, and three prediction classes, indexed c=0,1,2. The public target IDs a/97,b/98,EOS/512 map to these compact classes. Each yt control stores a public ID; write ktk_t for its compact class index. There is no PAD in this lesson. Logits z, probabilities P and the final logit gradient each have shape [3,3], axes Row and Class. A shape gives the length along each axis, so this means three position rows of three class values. Targets, masks and row NLLs each have shape [3]. Real arrays are float64; IDs, class indices and numeric 0/1 masks use int32.

The control z01, for example, is row0’s class1 score, not token ID1. y0=98 selects compact class1 in that row. The mask m0 chooses whether row0 contributes to the objective; it never removes class0 from any softmax. All three probability rows and their NLLs are computed even when a row’s mask is0.

The Direct logits row 0, Direct logits row 1 and Direct logits row 2 groups contain all nine score controls. The Observed target selectors edit y0,y1,y2; Requested target mask selectors edit m0,m1,m2. Reset example restores all three rows, targets and masks. Trace navigation selects a saved operation; an edit starts a new calculation and clears graded answers. The tensor inspector gives the full stored Logits, P, NLL, Weights, Contributions and dLogits values.

Derive stable probabilities and NLL one operation at a time

For one row, temporarily suppress t and write its scores as z0,z1,z2z_0,z_1,z_2. Let k be the compact target class. The mathematical probability and loss are

Pc=exp⁡(zc)∑j=02exp⁡(zj),ℓ=−ln⁡Pk=ln⁡ ⁣(∑j=02exp⁡(zj))−zk.P_c=\frac{\exp(z_c)}{\sum_{j=0}^{2}\exp(z_j)},\qquad \ell=-\ln P_k=\ln\!\left(\sum_{j=0}^{2}\exp(z_j)\right)-z_k.

Here j is just an index visiting all classes in the sum; ℓ is this row’s NLL. Direct exponentiation is unnecessary. Find the largest score m, subtract it from every score, exponentiate those differences and sum:

m=max⁡(z0,z1,z2),dc=zc−m,vc=exp⁡(dc),S=∑c=02vc,Pc=vc/S.m=\max(z_0,z_1,z_2),\quad d_c=z_c-m,\quad v_c=\exp(d_c),\quad S=\sum_{c=0}^{2}v_c,\quad P_c=v_c/S.

Why is this the same distribution? Write exp(zcz_c)=exp(m)exp(zc−mz_c-m). Every numerator and the complete denominator share exp(m), so it cancels. At least one d is0 and all are nonpositive, making 1≤S≤3. Taking the log of the factored sum gives log-sum-exp, abbreviated LSE:

LSE=m+ln⁡S,ℓ=(m−zk)+ln⁡S.\mathrm{LSE}=m+\ln S,\qquad \boxed{\ell=(m-z_k)+\ln S}.

The helper records LSE but computes NLL in the boxed, factored order. It first forms the score gap m−zkz_k, then adds lnS. Subtracting a large rounded zkz_k from a separately rounded LSE can lose a small result through cancellation. Taking −ln of a printed rounded P can be worse: a display may print zero for a positive tiny probability. This calculation needs neither clipping nor an artificial epsilon.

Cross-entropy compares a target probability distribution with a predicted one. A one-hot target distribution QcQ_c is1 for c=k and0 elsewhere. Its cross-entropy −∑cQcln⁡Pc-\sum_c Q_c\ln P_c retains only −lnPkP_k, precisely this row’s NLL. The word “distribution” for a one-hot target does not mean the model’s probabilities are one-hot. The model keeps all three probabilities.

Work all three default rows by hand

Let e=exp(1), Z=e+2 and S=1+2/e=Z/e. Let r=e/Z and q=1/Z be the large and small predicted probabilities; this scalar q is not the one-hot target distribution QcQ_c.

t; target ID→classLogitsm; all shiftsAll exponentialsOrdered sum; probabilitiesTarget score; LSE; NLL
0; 97→0(1,0,0)1; (0,−1,−1)(1,1/e,1/e)((0+1)+1/e)+1/e=S; (r,q,q)1; 1+lnS; (1−1)+lnS=lnS
1; 98→1(0,1,0)1; (−1,0,−1)(1/e,1,1/e)((0+1/e)+1)+1/e=S; (q,r,q)1; 1+lnS; (1−1)+lnS=lnS
2; 512→2(0,0,1)1; (−1,−1,0)(1/e,1/e,1)((0+1/e)+1/e)+1=S; (q,q,r)1; 1+lnS; (1−1)+lnS=lnS

Each probability is an actual division by S: for example 1/S=e/Z=r and (1/e)/S=1/Z=q. The one-hot target picks the r in each row. Since lnS=lnZ−1, all three losses have that exact symbolic value. No decimal evaluation is being claimed.

Let wt=mtw_t=m_t be the numeric 0/1 mask at position t; C the included target count; L the weighted loss sum; μ the mean NLL; and PP the perplexity. For C>0:

C=∑t=02wt,L=∑t=02wtℓt,μ=L/C,PP=exp⁡(μ).C=\sum_{t=0}^{2}w_t,\quad L=\sum_{t=0}^{2}w_t\ell_t,\quad \mu=L/C,\quad \mathrm{PP}=\exp(\mu).

At reset each weighted contribution is 1·lnS=lnS. C=1+1+1=3, L=(0+lnS)+lnS+lnS=3lnS, μ=3lnS/3=lnS and PP=exp(lnS)=S=1+2/e. These are validCount, lossSum, meanNLL and perplexity. exp(L) would be S³, a sequence-length-dependent quantity rather than this per-target perplexity.

What perplexity says, and what it does not

For binary masks, exp(mean negative log probability) is the reciprocal geometric mean of the included target probabilities. A geometric mean multiplies C values and takes the C-th root. Thus a constant probability 1/3 on every observed target gives PP3. A small perplexity says this predictor assigned high probabilities to these observations under this tokenization and mask policy. It does not measure comprehension, factual truth, safety or percentage accuracy.

Set all nine logits to0. Each row has m=0, shifts (0,0,0), terms (1,1,1), S=3 and P=(1/3,1/3,1/3). Every target score is0, so NLL=(0−0)+ln3=ln3. With any nonempty choice of masks, μ=ln3 and PP3, regardless of which valid targets you select. Different targets can matter greatly for nonuniform rows; equality here follows from equal probabilities.

Perplexities from different tokenizers are not directly comparable: one token can represent one byte, several bytes or a larger piece, changing the number and difficulty of prediction events. Comparing models also requires the same evaluated data, conditioning, vocabulary and masking conventions. Changing which hard examples count can lower an average without changing any parameter.

An edited target and a complete masked example

Reset, then change only y0 from97 to98. Row0’s P remains (r,q,q), but its selected target probability changes from r to q. Its NLL becomes (1−0)+lnS=1+lnS=lnZ. Rows1 and2 keep NLLlnS. With all masks1, C=3, L=(lnS+1)+lnS+lnS=3lnS+1, μ=lnS+1/3 and PP=S·exp(1/3).

Now set m1=m2=0, keeping m0=1. All three real NLLs still exist. Their contributions are lnS+1, 0·lnS=0 and 0·lnS=0. C=1+0+0=1, L=lnS+1, μ=lnS+1 and PP=exp(lnZ)=Z. Dividing by three would incorrectly report (lnS+1)/3. Masked real rows have true zero contribution, not an uncomputed PAD loss.

Set m0=0 too: C=0 makes the whole result unavailable with code UNAVAILABLE and a no-valid-target reason. There is no mean0, PP1 or defined mean gradient. This is a denominator failure, not perfect certainty.

Derive every logit derivative

A gradient lists the rate of change of a scalar quantity with respect to each adjustable number, holding other inputs fixed. Here the scalar is μ, and we differentiate with respect to logits, not embeddings or matrix parameters. The notation ∂μ/∂zt,c\partial\mu/\partial z_{t,c} means how μ changes for a tiny change in the score at position t, class c.

Differentiate the unfactored smooth real expression LSE−targetLogit. For a row, derivative of exp(zcz_c) is exp(zcz_c); derivative of ln A is1/A times the derivative of A. Therefore the LSE derivative is exp(zcz_c)/sum exp(zjz_j)=PcP_c. Subtracting the target score contributes−1 for the target class and0 for the others. Define I(c=kt)I(c=k_t) to be that indicator, equal to1 when the class matches and0 otherwise. Fixed masks and targets make C constant with respect to logits, so

∂μ∂zt,c=wtC(Pt,c−I(c=kt)).\frac{\partial\mu}{\partial z_{t,c}} =\frac{w_t}{C}\bigl(P_{t,c}-I(c=k_t)\bigr).

The factor w/C is the row’s objective weight, the difference P−I is its class correction, and their product is the stored derivative. The use of max in stable evaluation does not make this underlying softmax loss nonsmooth at tied logits; it is an algebraically equivalent evaluation of smooth log-sum-exp. Argmax selection itself is a different, discrete operation.

At reset, each factor is1/3. All nine differences and derivatives are

P−I=(r−1qqqr−1qqqr−1),dLogits=((r−1)/3q/3q/3q/3(r−1)/3q/3q/3q/3(r−1)/3).P-I=\begin{pmatrix}r-1&q&q\\q&r-1&q\\q&q&r-1\end{pmatrix},\qquad \mathrm{dLogits}=\begin{pmatrix} (r-1)/3&q/3&q/3\\q/3&(r-1)/3&q/3\\q/3&q/3&(r-1)/3 \end{pmatrix}.

For row0: (1/3)·(r−1), (1/3)·(q−0), (1/3)·(q−0); row1 moves the −1 correction to class1, and row2 to class2. Each row total is (r−1+2q)/3=0 because r+2q=(e+2)/Z=1. The target derivative is negative: raising its logit locally lowers NLL. Other class derivatives are positive: raising a competing score locally increases NLL.

In the edited example with y0=98 and only m0=1, C=1. Row0’s indicator is (0,1,0), differences (r,q−1,q), factor1 and gradient (r,q−1,q). Rows1 and2 have factor0 and gradients (0,0,0) exactly, although their probabilities/NLLs remain computed. No gradient is taken with respect to the discrete mask or target ID. Computing an analytic gradient and explaining it is not independent numerical validation, and no optimization step follows here.

Common shifts, bounds and honest numerical limits

Add10 to every logit of default row0: (11,10,10). Its new maximum11 gives the same shifts (0,−1,−1), S and P. Its target score11 yields NLL=(11−11)+lnS=lnS, and its gradient is unchanged. More generally, adding a common real constant a to a row gives (m+a)−(zcz_c+a)=m−zcz_c. All ratios, NLLs and logit derivatives stay invariant in exact real arithmetic.

Floating-point storage adds a qualification: a shift can round away a score difference if it is too small relative to the new magnitude. Maximum subtraction cannot recover a difference already lost during input representation. Values printed to a few decimals can also hide distinctions still present in stored logits. The inspector’s precision and the exact algebra answer different questions.

Each logit must be finite and lie in [−40,40], each target must be97,98 or512, each mask numeric0 or1. All fields validate, even a masked row’s logits. Since any maximum-to-target gap is at most80 and lnS≤ln3, 0≤NLL≤80+ln3. The mean obeys the same bound for a positive count, so PP≤3exp(80), finite in binary64. Shifted exponents range from−80 through0 and their terms stay positive in this domain. An invalid target, mask2, an out-of-range logit or all-zero masks cannot be repaired with clipping or an arbitrary epsilon.

Finite values do not guarantee perfect relative precision in every result. For a very dominant target, adding tiny exponential terms to 1 can round S to exactly 1. The computed winning NLL and its target-class derivative can then round to zero even while off-target probabilities remain positive. That is a binary64 precision limit, not deliberate clipping or evidence of mathematical certainty. Exact row-sum and shift identities above describe real arithmetic; stored results can differ through rounding.

Use Physical position / loss row to inspect and Compact prediction class to inspect to select one saved derivative factor, indicator and product. The full derivative table still contains all nine entries. These view selectors do not change logits, targets, masks or graded questions. The trace picker remains a separate choice of saved operation.

For the concrete domain-edge case, set row0 logits to (40,−40,−40), target y0=97, and masks m0=1,m1=0,m2=0. The maximum is40 and shifts are (0,−80,−80), giving terms (1,exp(−80),exp(−80)). Both small terms are strictly positive. In binary64, each sequential addition of exp(−80) to1 can nevertheless round back to1. The stored S can therefore be1, the stored target probability1 and the computed NLL=(40−40)+ln(1)=0. With only this target included, C=1 and the computed mean0 gives PP=exp(0)=1. The target gradient P−1 can be0 while each off-target probability and gradient remains the positive represented exp(−80).

The exact real denominator is1+2exp(−80), so the exact NLL is ln(1+2exp(−80))>0. This example exposes lost tiny denominator additions and near-one subtraction; it does not use clipping, and it is not an observed test result. It has one real target, unlike the unavailable zero-target case. The exact gradient row sums to zero, but these individually rounded stored components need not do so exactly.

Read the maintained calculation and its trace

The actual chapter wrapper is displayed directly:

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-42 — Cross-Entropy, NLL and Perplexity, canonical NumPy source.

Three logit rows each predict classes a/b/EOS. The public target IDs97/98/512
map explicitly to compact rows0/1/2; PAD is not accepted. For each row compute
m=max(z), shifted=z-m, terms=exp(shifted), S=sum(terms), logS=ln(S),
LSE=m+logS and independently nll=(m-z[target])+logS. The factored NLL
avoids subtracting a large rounded LSE and never logs a rounded probability.
Natural logarithms give nats. Every row computes even when its numeric mask0.

Reduce lossSum=sum(mask*nll), count=sum(mask), meanNLL=lossSum/count,
PPL=exp(meanNLL). No valid target means UNAVAILABLE. The weighted mean
logit derivative is (mask/count)*(P-oneHot), with every factor saved.
This analytic derivative is not independent validation and performs no update.

Hand default diagonal unit logits: S=1+2/exp(1), NLL=ln(S), PPL=S.
With Z=exp(1)+2, each diagonal gradient is (exp(1)/Z-1)/3 and each
off-diagonal is 1/(3Z). Uniform zero logits yield NLL=ln3, PPL3.
A common row shift preserves the mathematical P/NLL/gradient; floating-point
representability and cancellation still condition comparisons. Different
tokenizers define different events, so their PPLs are not directly comparable.

Keep language_reference.py beside this file. All reference paths remain unrun.
"""
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_IV42 = MappingProxyType(dict(_helper.IV42_DEFAULTS))


@_helper.guarded
def derive_iv42(state):
    """Compute stable rows, effective-mask mean NLL/PPL and analytic dLogits."""
    return _helper.derive42(state)


def source_self_check():
    """DEFERRED owner-only assertions; never called on import or CLI query."""
    s = dict(DEFAULT_IV42)
    result = derive_iv42(s)
    assert result["status"] == "defined"
    o, S = result["outputs"], 1 + 2 / math.e
    assert o["validCount"] == 3
    assert math.isclose(o["lossSum"], 3 * math.log(S))
    assert math.isclose(o["meanNLL"], math.log(S)) and math.isclose(o["perplexity"], S)
    uniform = derive_iv42({**s, **{f"z{t}{c}": 0 for t in range(3) for c in range(3)}})
    assert math.isclose(uniform["outputs"]["perplexity"], 3)
    assert derive_iv42({**s, "m0": 0, "m1": 0, "m2": 0})["code"] == "UNAVAILABLE"
    one = derive_iv42({**s, "m0": 0, "m2": 0})
    assert one["outputs"]["validCount"] == 1 and math.isclose(one["outputs"]["meanNLL"], math.log(S))
    assert derive_iv42({**s, "m0": 0, "z00": float("nan")})["code"] == "NONFINITE"
    for patch in ({"z00": 41}, {"y0": 768}, {"m1": 0.5}):
        assert derive_iv42({**s, **patch})["code"] == "INVALID_INPUT"
    assert list(result) == ["status", "outputs", "steps", "tensors"]
    assert len(result["steps"]) == 47 and len(result["tensors"]) == 19
    gradient = next(t["values"] for t in result["tensors"] if t["id"] == "dLogits")
    Z = math.e + 2
    for t in range(3):
        for c in range(3):
            expected = (math.e / Z - 1) / 3 if c == t else 1 / (3 * Z)
            assert math.isclose(gradient[3 * t + c], expected)
    one_gradient = next(t["values"] for t in one["tensors"] if t["id"] == "dLogits")
    assert all(value == 0 and math.copysign(1, value) == 1 for value in one_gradient[:3] + one_gradient[6:])
    tiny = float.fromhex("0x0.0000000000001p-1022")
    near = derive_iv42({**s, "z00": 0, "z01": tiny, "z02": 0})
    assert near["outputs"]["row_0_argmax_nextID"] == 98
    extreme = derive_iv42({**s, "z00": 40, "z01": -40, "z02": -40, "y0": 98})
    assert extreme["outputs"]["row_0_target_nll"] == 80
    assert extreme["outputs"]["row_0_target_contribution"] == 80
    assert extreme["outputs"]["row_0_probability_1_probability"] > 0


if __name__ == "__main__":
    _helper.run(derive_iv42, DEFAULT_IV42)

The actual shared source includes the stable probability/NLL calculations, reduction and weighted analytic gradient:

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 row maximum, every shift and exponential, denominator, lnS and target score before the row loss. Then follow effective weights into count and loss sum, and finally the factor, P−indicator difference and product for each gradient cell. Tables, summaries and saved operation operands use the same derived result. Independent oracle, parity, derivative and browser checks are authored separately; their declarations are not evidence of their results.

The Python wrapper derive_iv42 calls derive42. It builds actual float64 logits and int32 ids/masks, calls distribution and then target_loss for each complete row, and calls reduce_loss before forming derivatives. In the nested position/class loops, indicator, factor, difference and value implement the four parts of the derivative above. gradient[t,c] saves each result; mask0 explicitly stores positive zero. target_nll uses gap plus log-sum rather than probability logs. distribution_tensors and target_tensors expose the same working values as detached row-major records. The wrapper loads its adjacent helper relative to its own file, accepts defaults or one complete JSON state or JSON standard input, and leaves its separate self-check uncalled.

Five corrective checks matched to the lab

These outlines follow the five actual graded questions in order. The live derivative question always uses row0/class0, independently of view selectors.

  1. What do NLL and perplexity measure? NLL is −ln of the target probability in nats; perplexity is exp of the mean over effective target rows. Neither is an argmax accuracy count, the largest raw score or an arithmetic mean of inverse probabilities. One-hot cross-entropy retains exactly the target NLL.
  2. At reset, with S=1+2/exp(1), what are mean NLL and perplexity? The target has maximum score1, so its factored gap is0 and NLLlnS. Three contributions give sum3lnS and count3, hence meanlnS and perplexityS. ln(exp(1)+2) forgets the target score subtraction; 3lnS mistakes the sum for the mean.
  3. Which derivative matches the current saved row0/class0 record? Inspect gradient_0_0: its indicator is1 only if the current target class is0. The factor is weight/validCount, the difference is the actual class0 probability minus that indicator, and their product is the derivative. With weight1, the factor uses the current count, which can be1 rather than3. With weight0, the real NLL remains computed but the factor and derivative are exactly0. Subtracting a public target ID instead of the one-hot indicator would be a different, incorrect formula.
  4. What should adding the same constant to all logits of one row preserve? Probabilities, factored NLL and weighted mean-loss derivatives are invariant in real arithmetic with fixed masks/targets. LSE itself increases by the constant; that increase cancels the target score increase. Staying within bounds does not guarantee bitwise floating invariance if input additions round away tiny differences. Argmax uses highest computed logits rather than apparently tied rounded probabilities.
  5. With every logit0 and masks [0,1,0], what denominator, loss and perplexity follow? Every row still has P=(1/3,1/3,1/3) and NLLln3. Only the middle target contributes: count1, lossSumln3, meanln3 and perplexity3. Its gradient is P−oneHot with factor1; the excluded rows have exact zero gradients. Turning the remaining mask off makes the result unavailable, not mean0 or perplexity1.

Recap and bridge

  • Stable NLL uses the target gap plus ln of shifted exponential terms.
  • One-hot cross-entropy equals target NLL; mean loss counts only included targets.
  • Perplexity is exp(mean NLL), with comparisons tied to data and tokenization.
  • Each logit derivative is mask/count times probability minus the target indicator.
  • Common shifts preserve real results, subject to representability and rounding.

The next planned chapter, IV-43 — End-to-End Tiny Language-Model Objective, composes tokenization, positions and a real tiny decoder with this objective. The one-token affine predictor used in IV-40/41 is a disclosed stepping stone to that larger computation.