The neural notebook
← All chapters

IV-41 / Part X · Language Modeling

Teacher Forcing and Shifted Targets

Align actual inputs with next-token targets, distinguish ignored PAD rows from computed masked losses, and derive the valid-token mean without target leakage.

Review the ideas this chapter uses

A recorded sequence already tells us what followed each token. We can use those observations to score several next-token predictions together. The important bookkeeping is to place each prediction beside the next observed token, feed the actual sequence into later positions, and leave unused storage out of the score. This arrangement is called teacher forcing with shifted targets.

Learning objective: Align input and target token positions in a causal training example.

Compute it yourself

Teacher Forcing and Shifted Targets

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
s0
97
s1
98
s2
512
s3
768
m0
1
m1
1
m2
1
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
validCount2
lossSum3.102889427864102
meanNLL1.551444713932051
perplexity4.7182818284590455
Content embedding E [2,2]
Output weights U [2,3]
Output biases [3]

validCount 2. lossSum 3.102889427864102. meanNLL 1.551444713932051. perplexity 4.7182818284590455. Validate four physical slots and three requested masks. 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.. physicalSlots 4. physicalRows 3. classCount 3. receptiveField 1

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.

Inputs

s0
97
s1
98
s2
512
s3
768
m0
1
m1
1
m2
1
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

physicalSlots
4
physicalRows
3
classCount
3
receptiveField
1

Physical storage, shifted targets and computed rows

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.

All four physical slots: s0=a (97) s1=b (98) s2=EOS (512) s3=PAD (768) . Physical row t aligns s[t] to target s[t+1]. NonPAD targets are computed even when their requested mask is0.

All three physical rows — saved values without display rounding
Physical tObserved input IDNext target IDTarget classRequested maskPAD targetComputedEffective mask
0a (97)b (98)11011
1b (98)EOS (512)21011
2EOS (512)PAD (768)-11100
Compact computed rows map back to physical positions — saved values without display rounding
Computed row kPhysical position t
00
11

Teacher forcing feeds the actual stored input. At reset row0 predicts a, but physical row1 reads observed b; the prediction is not fed back. EOS→PAD is an ignored physical row with no E gather. Manually masked NLL is still real; PAD NLL does not exist.

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
row_0_alignment
t=0
inputID=97
targetID=98
requestedMask=1
targetRow=1
isPadding=0
computed=1
effectiveMask=1

Effective count=2, weighted loss sum=3.102889427864102, mean NLL=1.551444713932051 nats, perplexity=4.7182818284590455. 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=1.551444713932051
previousCount=0
previousLossSum=0
validCount=1
contribution=1.551444713932051
lossSum=1.551444713932051
reduce_1
k=1
weight=1
nll=1.551444713932051
previousCount=1
previousLossSum=1.551444713932051
validCount=2
contribution=1.551444713932051
lossSum=3.102889427864102
reduction
validCount=2
lossSum=3.102889427864102
meanNLL=1.551444713932051
perplexity=4.7182818284590455

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.

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

validCount
2
lossSum
3.102889427864102
meanNLL
1.551444713932051
perplexity
4.7182818284590455
setup_physicalSlots
4
setup_physicalRows
3
setup_classCount
3
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
row_0_alignment_targetRow
1
row_0_alignment_isPadding
0
row_0_alignment_computed
1
row_0_alignment_effectiveMask
1
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
row_1_alignment_targetRow
2
row_1_alignment_isPadding
0
row_1_alignment_computed
1
row_1_alignment_effectiveMask
1
row_2_alignment_targetRow
-1
row_2_alignment_isPadding
1
row_2_alignment_computed
0
row_2_alignment_effectiveMask
0
reduce_0_validCount
1
reduce_0_contribution
1.551444713932051
reduce_0_lossSum
1.551444713932051
reduce_1_validCount
2
reduce_1_contribution
1.551444713932051
reduce_1_lossSum
3.102889427864102
reduction_meanNLL
1.551444713932051
reduction_perplexity
4.7182818284590455

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

Slots

PhysicalSlot=4 · int32 · display precision 0 · All four physical storage slots, including the untrimmed PAD tail.

Storage indexValue
097
198
2512
3768

InputIDs

PhysicalRow=3 · int32 · display precision 0 · Physical row t reads actual slot s[t], not a previous argmax.

Storage indexValue
097
198
2512

TargetIDs

PhysicalRow=3 · int32 · display precision 0 · Physical row t targets s[t+1]; PAD768 remains visible storage metadata.

Storage indexValue
098
1512
2768

TargetRows

PhysicalRow=3 · int32 · display precision 0 · Compact target class for non-PAD rows; -1 marks PAD and is never gathered.

Storage indexValue
01
12
2-1

RequestedMask

PhysicalRow=3 · int32 · display precision 0 · All three learner-requested numeric 0/1 masks, before structural PAD exclusion.

Storage indexValue
01
11
21

IsPadding

PhysicalRow=3 · int32 · display precision 0 · 1 exactly when the physical row targets PAD768.

Storage indexValue
00
10
21

Computed

PhysicalRow=3 · int32 · display precision 0 · 1 for a real non-PAD target, including a manually masked row; 0 for uncomputed PAD.

Storage indexValue
01
11
20

EffectiveMask

PhysicalRow=3 · int32 · display precision 0 · Requested mask for a computed row; zero for PAD. Both numerator and denominator use this mask.

Storage indexValue
01
11
20

ComputedPositions

ComputedRow=2 · int32 · display precision 0 · Explicit compact computed-row index to physical row t map; no fake PAD numeric rows.

Storage indexValue
00
11

InputRows

ComputedRow=2 · int32 · display precision 0 · Compact a/b embedding rows for computed positions only.

Storage indexValue
00
11

H

ComputedRow=2 × Feature=2 · float64 · display precision 8 · Current observed input embeddings for computed positions only; no EOS or PAD embedding.

Storage indexValue
01
10
20
31

Logits

ComputedRow=2 × 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

Shifted

ComputedRow=2 × 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

Terms

ComputedRow=2 × 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

Max

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

Storage indexValue
01
11

Denominator

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

Storage indexValue
01.7357588823428847
11.7357588823428847

LogS

ComputedRow=2 · float64 · display precision 8 · Natural log of the shifted exponential denominator.

Storage indexValue
00.5514447139320511
10.5514447139320511

LSE

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

Storage indexValue
01.551444713932051
11.551444713932051

P

ComputedRow=2 × 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

NextRows

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

Storage indexValue
00
11

NextIDs

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

Storage indexValue
097
198

TargetLogits

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

Storage indexValue
00
10

TargetProbability

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

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

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

Storage indexValue
01
11

Contributions

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

Reset shows four physical slots a,b,EOS,PAD. Shift the targets one slot left relative to their inputs: a→b, b→EOS, EOS→PAD. Only the first two rows have real prediction targets. EOS is a class to predict; PAD is storage that does not enter the model's class or embedding table.

With E identity2 and U rows(1,0,0)/(0,1,0), each active default target has probability1/Z and NLLlnZ, where Z=exp(1)+2. Sum2lnZ divided by count2 gives meanlnZ and perplexityZ. Row0 predicts a, yet row1 reads observed b: this is the teacher-forcing distinction.

Set m0=0 to retain row0's actual NLL but exclude its numerator and count contribution. Set m1=0 too to see the honest unavailable objective; m2 cannot activate a PAD target. Reset, then try s2=a: row1's target becomes a while row2 still targets PAD, so there are still two computed rows and earlier causal logits stay fixed. Then set s3=b to create the third computed row a→b. Try s2=EOS and s3=a to see the invalid content-after-EOS reason. There is no silent trim, previous-prediction feedback or parameter update.

Check your understanding

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

1. At reset a,b,EOS,PAD, row0 predicts a. Which input is used for row1 under teacher forcing?
2. For physical slots [a,b,EOS,PAD] and requested masks [1,1,1], which alignment and denominator are correct?
3. Current physical row0 targets public ID98 with probability=0.21194155761708544, NLL=1.551444713932051, weight=1, contribution=1.551444713932051. What enters the current weighted objective with validCount=2?
4. Which four-slot edit must be rejected before numerical computation, and why?
5. At reset keep the slots unchanged, set m0=m1=0 and leave m2=1. What is the complete objective?

Reset stores a,b,EOS,PAD in s0 through s3, with all three requested masks set to1. Two next-token losses contribute. Turn m0 off: its actual prediction remains computed, but both its loss contribution and its contribution to the denominator disappear. Compare that row with the EOS→PAD row, whose probability and NLL are not computed at all.

Review IV-40 — Autoregressive Next-Token Prediction for the affine conditional and causal scoring order. Book II’s VII.4 — Cross entropy and negative log-likelihood gives the NLL background, and Book III’s III-02 — Samples, Features, Labels and Targets distinguishes supplied inputs from targets. These are authored toy sequences and hand-set parameters. The lab computes a training objective, a quantity training could minimize; it performs no parameter update or generation.

The four Physical slot selectors edit s0,s1,s2,s3. The three Requested target mask selectors edit m0,m1,m2 for physical rows 0,1,2. The collapsible Content embedding E [2,2], Output weights U [2,3] and Output biases [3] groups expose the same 13 parameters as IV-40. Use Reset example before each worked edit; trace navigation selects saved calculations and clears exercise answers, while editing recomputes the complete result.

Teacher forcing does not mean feeding the answer early

A target is the observed item a prediction is judged against. Teacher forcing supplies the actual recorded token as the input at each position rather than feeding the previous prediction’s chosen output. At reset, input a makes the model prefer a next, yet the actual following input is b. Row1 therefore receives b, not the earlier argmax a. This keeps scoring aligned with the recorded sequence even when the model would have generated something else.

Shifting aligns two views of one stored sequence. With zero-based position t, input is sts_t and target is st+1s_{t+1}. The shift changes which item is scored; it does not copy st+1s_{t+1} into the arithmetic producing row t’s logits. A causal model can compute many rows together while preserving this separation. Here each row still has only a one-token receptive field: it uses its current input and ignores older prefix tokens. A full Transformer is deferred to IV-43.

Four physical slots give three possible input/target pairs. Physical means their positions remain present in storage even when some do not produce a numerical prediction. The full slot list has shape [4], and alignment columns have shape [3] on the physical-position axis. These dimensions count slots and pairs, not independent sequences or vocabulary classes.

EOS is a target; PAD is unused storage

The public prediction vocabulary is a/97, b/98, EOS/512, mapped to compact classes0,1,2. EOS, end of sequence, is a genuine next-token outcome with its own logit and probability. PAD/768 is a storage sentinel, a reserved marker saying that no further token occupies that slot. PAD is neither a fourth prediction class nor an embedding row.

The sequence must begin with a or b. Non-PAD tokens occupy one contiguous prefix, with PAD only at its tail. EOS is optional, occurs at most once and must be the last non-PAD token. This rejects a,EOS,b,PAD and a,PAD,b,PAD; it never silently trims or rearranges them. A sequence of four a/b tokens is also permitted, with three ordinary targets and no EOS or PAD.

Why are there only two embedding rows? A computed pair has a non-PAD target. Under these sequence rules its current input must be a or b: an EOS could only be the final non-PAD item and therefore could not have a later non-PAD target. A physical EOS→PAD row is uncomputed. Thus E has shape [2,2], U [2,3], biases [3]; no EOS input embedding is missing. A later model supporting different sequences would need its own declared input vocabulary.

Compute a real row before applying its loss weight

Let h=(h0,h1) be the input’s two-feature embedding. For class c=0,1,2, the affine score is zc=h0U[0,c]+h1U[1,c]+bcz_c=h_0U[0,c]+h_1U[1,c]+b_c. Both products, their sum and the bias are saved. Then maximum m, shifts d, terms w, sum S, probabilities P and target NLL ℓ are

m=max⁡czc,dc=zc−m,wc=exp⁡(dc),S=∑c=02wc,Pc=wc/S,ℓ=(m−zy)+ln⁡S.m=\max_c z_c,\quad d_c=z_c-m,\quad w_c=\exp(d_c),\quad S=\sum_{c=0}^{2}w_c,\quad P_c=w_c/S,\quad \ell=(m-z_y)+\ln S.

Here y is the target’s compact class, not its public ID. The summation sign means add one term for each class. exp(v) means eve^v; ln is the natural logarithm. The recorded log-sum-exp is LSE=m+lnS. NLL uses the factored expression above rather than subtracting a large rounded target logit from a large rounded LSE. No rounded probability is logged.

For each physical row the alignment saves inputID, targetID, targetRow, requestedMask, isPadding, computed and effectiveMask. targetRow=−1 is metadata for a PAD target, never a class to gather. requestedMask is the editable numeric 0/1 choice. If the target is PAD, computed=0 and effectiveMask=0 whatever the request. There are no logits, probabilities or NLL for that pair. For a non-PAD target, computed=1 and the entire prediction/NLL is computed even when requestedMask=0; effectiveMask then equals the request.

A loss mask chooses which computed rows contribute to the objective. It differs from the attention permissions in IV-26 — Causal, Bidirectional and Padding Attention: these three vocabulary classes remain available to every computed softmax. Turning a loss mask off does not remove a class, erase a token, or change a row’s probabilities.

Full default alignment and arithmetic

Reset uses E rows (1,0),(0,1), U rows (1,0,0),(0,1,0) and zero biases. For a: a score is 1·1+0·0+0=1, b score1·0+0·1+0=0, EOS score1·0+0·0+0=0. For b: a score0·1+1·0+0=0, b score0·0+1·1+0=1, EOS score0·0+1·0+0=0.

Define e=exp(1), Z=e+2 and S=1+2/e=Z/e. In row0, maximum1 gives shifts (0,−1,−1), terms (1,1/e,1/e) and denominator (0+1)+1/e+1/e=S. P=(e/Z,1/Z,1/Z). Row1 gives shifts (−1,0,−1), terms (1/e,1,1/e), the same S, and P=(1/Z,e/Z,1/Z).

Position tInput→targetTarget classRequestedPaddingComputedEffectiveReal NLLWeighted contribution
0a→b11011(1−0)+lnS=lnZ1·lnZ=lnZ
1b→EOS21011(1−0)+lnS=lnZ1·lnZ=lnZ
2EOS→PAD−1 metadata1100uncomputedignored

The PAD row has no fake zero NLL. Only the two actual numerical rows enter dense logits, probability and loss tensors. At reset, their computed-position map is [0,1]; their embeddings have shape [2,2], logits/probabilities [2,3] and NLL values [2]. With four content tokens, the map becomes [0,1,2], logits become [3,3] and NLL [3]. This explicit map tells you which physical position each compact computed row represents. Dense storage never pads these numerical arrays with invented losses.

Count exactly the targets included in the sum

For a computed row t let wtw_t denote its effective numeric 0/1 mask, and ℓt\ell_t its real NLL. Let C be the valid target count, L the loss sum, μ the mean NLL and PP the perplexity:

C=∑t computedwt,L=∑t computedwtℓt,μ=L/C,PP=exp⁡(μ),C>0.C=\sum_{t\ \mathrm{computed}}w_t,\qquad L=\sum_{t\ \mathrm{computed}}w_t\ell_t,\qquad \mu=L/C,\qquad \mathrm{PP}=\exp(\mu),\quad C>0.

“Computed” restricts the sums to real rows. Ignored PAD contributes neither a term nor a count. At reset C=1+1=2, L=lnZ+lnZ=2lnZ, μ=2lnZ/2=lnZ, PP=exp(lnZ)=Z=e+2. These are the four summaries validCount, lossSum, meanNLL and perplexity. There is no division by four storage slots or three physical pairs.

Set m0=0, keeping reset slots. Row0 still has target P=1/Z and NLLlnZ, with real weighted contribution 0·lnZ=0. Row1 contributes lnZ. C=0+1=1, L=0+lnZ=lnZ, μ=lnZ/1=lnZ and PP=Z. Equal losses make the mean look unchanged, but both numerator and denominator changed. Dividing by the old count2 would incorrectly halve the remaining row’s loss.

For unequal losses, reset and change s2 to b. The pairs become a→b,b→b,b→PAD. Row0 still has NLLlnZ. Row1 has target score1, P=e/Z and NLL(1−1)+lnS=lnZ−1. With both masks on, C=2, L=2lnZ−1, μ=lnZ−1/2, PP=Z/exp(1/2). Now set m0=0: C=1, L=lnZ−1, μ=lnZ−1 and PP=Z/e=S. Removing the harder target changes the average; a lower reported objective after changing a mask is not evidence of learning.

Causality, invalid states and empty objectives

Reset and change s2 from EOS to a. Row1 now scores a instead of EOS, but still computes its logits from b. Row0’s logits remain unchanged too. The earlier score may change with its target; the earlier predictor never reads that future target. Supplying actual b at row1 is permitted because b is now the current observed input for that row. Then set s3=b as a separate edit: storage is now a,b,a,b, and the third physical pair a→b becomes computed. With default parameters and all masks1, each of the three target probabilities is1/Z and each NLLlnZ. The computed-position map becomes [0,1,2], count becomes3 and loss sum3lnZ; dividing by3 still gives meanlnZ and perplexityZ. Changing s2 alone had left s3=PAD and therefore only two computed rows.

Set all requested masks to0: computed non-PAD rows may be defined individually, but C=0 leaves the whole lesson result unavailable, code UNAVAILABLE, with a no-valid-target reason. There is no mean0 or PP1 to invent. Likewise a,PAD,PAD,PAD contains no valid next target even with requested masks1. This differs from IV-40’s empty continuation product: an empty product has a definition, while a mean over zero observations has no denominator.

All four slot choices, three numeric masks and 13 parameters validate before computation, including ignored/inactive values. Masks accept0/1 rather than arbitrary weights; E/U entries are bounded [−2,2], biases [−4,4]. Invalid EOS placement, a PAD gap, a bad ID or an out-of-domain parameter makes the state unavailable rather than changing the data. Affine |z|≤12 implies NLL≤24+ln3, so the stated finite-domain mean and perplexity remain finite. Display rounding is separate from calculation.

Use Physical position / loss row to inspect to select physical row2 at reset. The view says Ignored / PAD target, with no numerical probability/NLL row. Row0 with m0=0 instead keeps its numerical table. Compact prediction class to inspect selects a saved affine operation on computed rows; changing either view selector leaves the objective and exercise inputs fixed. The compact-position table shows why physical row numbers and numerical row indices must be kept separate.

Read the actual wrapper and shared helper

The maintained chapter wrapper supplies this lesson’s complete state and entry point:

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-41 — Teacher Forcing and Shifted Targets, canonical NumPy source.

Four physical slots store a/b, optional last EOS, and a contiguous PAD tail.
Three physical rows align input=s[t] and target=s[t+1]. Teacher forcing feeds
that actual input, not a previous prediction. All parameters and slots validate
before sequence semantics. EOS=512 is a prediction class, but never an active
input. PAD=768 has no class, probability, NLL or embedding gather.

Hand default [a,b,EOS,PAD]: row0 a->b and row1 b->EOS each have
P=1/(exp(1)+2), NLL=ln(exp(1)+2). Row2 EOS->PAD is UNCOMPUTED.
The valid count is2; lossSum=2ln(Z), meanNLL=ln(Z), perplexity=Z.
A manually masked non-PAD row still computes its real distribution/loss, then
contributes zero to BOTH numerator and denominator. This differs from PAD,
which stores no fake loss. No valid targets means UNAVAILABLE, never PPL1.

Keep language_reference.py beside this file. Loading is __file__-relative.
All actual calculations and deferred self-check declarations 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_IV41 = MappingProxyType(dict(_helper.IV41_DEFAULTS))


@_helper.guarded
def derive_iv41(state):
    """Align physical rows, omit PAD gathers, and reduce effective target masks."""
    return _helper.derive41(state)


def source_self_check():
    """DEFERRED owner-only assertions; never called on import or CLI query."""
    s = dict(DEFAULT_IV41)
    result = derive_iv41(s)
    assert result["status"] == "defined"
    o, Z = result["outputs"], math.e + 2
    assert o["validCount"] == 2
    assert math.isclose(o["lossSum"], 2 * math.log(Z))
    assert math.isclose(o["meanNLL"], math.log(Z)) and math.isclose(o["perplexity"], Z)
    masked = derive_iv41({**s, "m0": 0})
    assert masked["outputs"]["validCount"] == 1
    assert math.isclose(masked["outputs"]["meanNLL"], math.log(Z))
    for patch in ({"m0": 0, "m1": 0, "m2": 0}, {"s1": 768, "s2": 768}):
        assert derive_iv41({**s, **patch})["code"] == "UNAVAILABLE"
    for patch in ({"s0": 512}, {"s1": 768}, {"s1": 512, "s2": 97}, {"s3": 97}):
        assert derive_iv41({**s, **patch})["code"] == "INVALID_INPUT"
    assert derive_iv41({**s, "m2": True})["code"] == "NONFINITE"
    assert derive_iv41({**s, "e11": float("inf")})["code"] == "NONFINITE"
    assert list(result) == ["status", "outputs", "steps", "tensors"]
    assert len(result["steps"]) == 35 and len(result["tensors"]) == 31
    tensors = {t["id"]: t for t in result["tensors"]}
    masked_tensors = {t["id"]: t for t in masked["tensors"]}
    assert tensors["ComputedPositions"]["values"] == [0, 1]
    assert tensors["TargetRows"]["values"] == [1, 2, -1]
    assert tensors["Computed"]["values"] == [1, 1, 0]
    assert tensors["NLL"]["shape"] == [2]
    assert tensors["NLL"]["values"] == masked_tensors["NLL"]["values"]
    assert masked_tensors["Weights"]["values"] == [0, 1]
    assert [step["id"] for step in result["steps"] if step["id"].startswith("row_2_")] == ["row_2_alignment"]
    unequal = derive_iv41({**s, "s2": 98, "m0": 0})
    assert math.isclose(unequal["outputs"]["meanNLL"], math.log(Z) - 1)
    full = derive_iv41({**s, "s2": 97, "s3": 512})
    assert len(full["steps"]) == 50 and full["outputs"]["validCount"] == 3


if __name__ == "__main__":
    _helper.run(derive_iv41, DEFAULT_IV41)

The actual shared source performs sequence validation, causal affine prediction, shifted target selection and effective-mask 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)

Read the physical alignment before inspecting the compact numerical arrays. Follow computed/effectiveMask separately: computed answers whether a prediction exists, effectiveMask answers whether it enters this objective. Saved trace operands, tensor values and summaries derive from one result, not a separate display calculation. Source descriptions alone do not establish runtime, rendering or parity results.

The Python wrapper derive_iv41 calls derive41. After language_state validates every raw field and the sequence structure, input_ids=slots[:-1] takes the first three physical inputs and target_ids=slots[1:] takes the last three targets. These slices align existing data; they do not feed targets into prediction. A PAD target sets the numerical row and loss to None. Real rows call affine_distribution then target_loss, enter positions and are finally reduced by reduce_loss. Only actual rows are stacked into numerical tensors. This is why ComputedPositions includes a manually masked row but excludes PAD. The adjacent-helper loader and complete-state JSON CLI follow IV-40; the self-check is declared separately.

Five corrective checks matched to the lab

These outlines follow the five actual graded questions in order. The live question reads physical row0 from the current starting inputs.

  1. At reset, which input does row1 use when row0 predicts a? Teacher forcing uses observed b from slot s1. It does not feed the previous argmax a, and it does not skip ahead to EOS. Row0 predicts s1 from s0; row1 predicts s2 from the actual s1.
  2. For [a,b,EOS,PAD] and requested masks [1,1,1], which alignment and denominator are correct? a→b and b→EOS are computed and counted, giving count2. EOS→PAD is uncomputed despite its requested mask1. EOS is a genuine class2 target; PAD is not a fourth class, embedding row or zero-NLL observation.
  3. What do the current row0 probability, NLL, weight and contribution mean? A defined storage prefix always gives row0 a non-PAD target. If its weight is1, its actual contribution enters the sum and its one weight enters the count. If its weight is0, the same real prediction and NLL remain computed but its contribution and count increment are0. Read the saved values and current mean rather than divide by all three physical rows. The compact computed-position map includes this row in either branch.
  4. Which storage edit must be rejected, and why? [a,EOS,b,PAD] puts content after EOS and is invalid. [a,b,PAD,PAD] is structurally valid with one computed target; EOS is optional. [a,b,a,EOS] is valid with three targets; EOS may be predicted as the last token. A PAD gap such as [a,PAD,b,PAD] is another error. None is silently trimmed or reordered.
  5. At reset, what happens with m0=m1=0 but m2=1? The effective masks are still [0,0,0]: two real losses are excluded and the last target is PAD. The whole result is UNAVAILABLE, with no fabricated mean or perplexity. Requested mask1 cannot rescue a nonexistent PAD observation. This differs from the explicit empty-product identity in IV-40.

Recap and bridge

  • Shifted targets pair current input with the next recorded token, without exposing that token to the predictor.
  • Teacher forcing follows real inputs; it does not follow previous predicted choices.
  • PAD rows are uncomputed; manually masked real rows retain their actual NLL and have zero weighted contribution.
  • The mean divides by included targets, and zero included targets makes it unavailable.

Next, IV-42 — Cross-Entropy, NLL and Perplexity derives stable cross-entropy, perplexity and the exact analytic derivative with respect to every logit.