The neural notebook
← All chapters

IV-44 / Part XI · Autoregressive Inference

Prefill and Single-Token Decode

Separate prompt prefill from one externally supplied next ID, derive the new causal row, and inspect uncached work, absolute positions, exact token boundaries and EOS stopping.

Review the ideas this chapter uses

You have already supplied ab. Now one more token arrives. Which positions must the model calculate, and which token is actually new? We will keep those two questions separate: this small reference processes the prompt, then recomputes the extended prefix after one selected ID is appended.

Learning objective: Distinguish processing a prompt from subsequent decoding calls.

Compute it yourself

Prefill and Single-Token Decode

Follow a real short prompt through the same tiny decoder, then supply exactly one next ID. At reset the prompt ab has two tokens; appending a is one novel input, while the uncached second call recomputes three rows. EOS instead stops before that call. All parameters are hand-set and untrained.

promptTokens2
newTokensConsumed1
prefillWorkTokens2
decodeWorkTokens3

Use raw a/b letters only, at most six UTF-8 bytes, and one or two actual BPE prompt tokens. Empty text is UNAVAILABLE. Merges from the fixed corpus abab may compress a longer string; overlong token contexts are reported, never cropped. The next public ID is supplied externally and must be active for the current merge budget.

Full embedding E [5,2]
Full readout U [2,5]
Full readout biases [5]
Exact starting inputs for this saved calculation

promptTokens 2. newTokensConsumed 1. prefillWorkTokens 2. decodeWorkTokens 3. Validate the complete input before interpreting prompt text. All raw fields validate, including inactive and EOS parameters. The prompt is tokenized once with EOS off. No probability of the external choice is asserted.

Validate the complete input before interpreting prompt text

outer bytes<=6; actual prompt tokens N in {1,2}; nextID is externally supplied

All raw fields validate, including inactive and EOS parameters. The prompt is tokenized once with EOS off. No probability of the external choice is asserted.

Saved inputs

merges
0
e00
1
e01
0
e10
0
e11
1
e20
0
e21
0
e30
0.5
e31
0.5
e40
1
e41
1
u00
1
u01
0
u02
0
u03
0
u04
0
u10
0
u11
1
u12
0
u13
0
u14
0
b0
0
b1
0
b2
0
b3
0
b4
0
nextID
97

Saved outputs

utf16Units
2
byteBound
6
promptTokenBound
2

One prompt, one externally supplied continuation

Prompt "ab" encoded once as [97,98]. Append a (ID97) to obtain logical IDs [97,98,97]. The actual strict decoder reconstructed "aba", from bytes [97,98,97].

The supplied ID is your external choice. The model's last prefill prediction is b (ID98), stored probability 0.7234156524931242. After processing the extended prefix, its last prediction is a (ID97), stored probability 0.7632007976561935. Neither prediction is substituted for your choice.

Prefill processes 2 token rows and 4 score cells. The second call processes 3 rows and 9 score cells, although only 1 ID is novel. Its appended token has absolute position 2. Cache used=0; cache entries=0. K/V reuse is a later chapter.

  1. Actual BPE prompt, EOS off → compact embedding gathers at absolute positions0..N−1.
  2. Feature normalization → Q/K/V → Q/K position rotations → causal attention.
  3. Two residual additions around the attention and FFN branches → logits and probabilities.
  4. Append the selected ID; stop on EOS or recompute the extended prefix at absolute positions0..N.
  5. Strictly reverse-decode the retained logical ID stream with the same learned rules.

Inspecting actual Prefill position 0, key 0, compact class 0. Inspection selectors read the same saved result and leave exercise answers unchanged.

Selected trace operation setup. Its matching operation row is marked current when included in this inspection. Trace selection and these selectors are independent.

Prefill: actual inputs and absolute positions

Here B=1 batch, T=2 consumed positions, D=2 features, H=1 head, Dk=Dv=2, M=3 hidden coordinates and V=3 active classes. Raw E[5,2], U[2,5], Bias[5] include inactive values. Logits[2,3] contain only active classes. Position0 is always the first retained ID.

Prefill consumed IDs — saved values without display rounding
Absolute positionObserved IDCompact embedding rowComputed next-ID predictionStored prediction probability
0a (ID97)0a (ID97)0.8376116959343609
1b (ID98)1b (ID98)0.7234156524931242

Follow both features without dropping residuals

Prefill position 0 features — saved values without display rounding
Saved stageFeature0Feature1Meaning
X10Actual embedding gather
LN10.4472135954999579-0.4472135954999579Feature-only layer norm
AttentionOutput0.4472135954999579-0.4472135954999579Causal weighted values and output projection
R11.4472135954999579-0.4472135954999579X plus attention output
LN20.6876854075163181-0.6876854075163181Feature-only layer norm of R1
F0.68768540751631810Three-coordinate ReLU FFN
Y2.134899003016276-0.4472135954999579R1 plus FFN output
Inspect this position's normalization and residual operands

Both layer norms use only this row's two features, population variance, gamma=(1,1), beta=(0,0) and epsilon1 inside the square root. Residual addition requires identical named [B,T,D] shapes.

Saved normalization and residual arithmetic — saved values without display rounding
Saved operationActual inputsActual outputs
prefill_ln1_0_statistics
x0=1
x1=0
epsilon=1
sum=1
mean=0.5
centered0=0.5
centered1=-0.5
square0=0.25
square1=0.25
squareSum=0.5
variance=0.25
variancePlusEpsilon=1.25
denominator=1.118033988749895
prefill_ln1_0_feature_0
d=0
source=0.5
denominator=1.118033988749895
gamma=1
beta=0
normalized=0.4472135954999579
scaled=0.4472135954999579
value=0.4472135954999579
prefill_ln1_0_feature_1
d=1
source=-0.5
denominator=1.118033988749895
gamma=1
beta=0
normalized=-0.4472135954999579
scaled=-0.4472135954999579
value=-0.4472135954999579
prefill_residual1_0_0
t=0
d=0
left=1
right=0.4472135954999579
value=1.4472135954999579
prefill_residual1_0_1
t=0
d=1
left=0
right=-0.4472135954999579
value=-0.4472135954999579
prefill_ln2_0_statistics
x0=1.4472135954999579
x1=-0.4472135954999579
epsilon=1
sum=1
mean=0.5
centered0=0.9472135954999579
centered1=-0.9472135954999579
square0=0.8972135954999578
square1=0.8972135954999578
squareSum=1.7944271909999157
variance=0.8972135954999578
variancePlusEpsilon=1.8972135954999578
denominator=1.3773937692250382
prefill_ln2_0_feature_0
d=0
source=0.9472135954999579
denominator=1.3773937692250382
gamma=1
beta=0
normalized=0.6876854075163181
scaled=0.6876854075163181
value=0.6876854075163181
prefill_ln2_0_feature_1
d=1
source=-0.9472135954999579
denominator=1.3773937692250382
gamma=1
beta=0
normalized=-0.6876854075163181
scaled=-0.6876854075163181
value=-0.6876854075163181
prefill_residual2_0_0
t=0
d=0
left=1.4472135954999579
right=0.6876854075163181
value=2.134899003016276
prefill_residual2_0_1
t=0
d=1
left=-0.4472135954999579
right=0
value=-0.4472135954999579

Position rotates Q and K; values stay unrotated

Prefill selected Q/K rotations — saved values without display rounding
PairAbsolute positionUnrotated pairAngleCosineSineRotated pair
Q0[0.4472135954999579,-0.4472135954999579]010[0.4472135954999579,-0.4472135954999579]
K0[0.4472135954999579,-0.4472135954999579]010[0.4472135954999579,-0.4472135954999579]
Inspect all rotation products and sums
Saved position rotation arithmetic — saved values without display rounding
Saved operationActual inputsActual outputs
prefill_rope_Q_0
t=0
x0=0.4472135954999579
x1=-0.4472135954999579
base=10000
exponent=0
frequency=1
angle=0
cos=1
sin=0
product0=0.4472135954999579
product1=0
product2=0
product3=-0.4472135954999579
rotated0=0.4472135954999579
rotated1=-0.4472135954999579
prefill_rope_K_0
t=0
x0=0.4472135954999579
x1=-0.4472135954999579
base=10000
exponent=0
frequency=1
angle=0
cos=1
sin=0
product0=0.4472135954999579
product1=0
product2=0
product3=-0.4472135954999579
rotated0=0.4472135954999579
rotated1=-0.4472135954999579

Only keys at or before the query contribute

Prefill query 0 attention — saved values without display rounding
Key / IDRaw Q·KScaled scoreAllowed?Stored probabilityUnrotated V pair
0 / a (ID97)0.399999999999999970.28284271247461895true1[0.4472135954999579,-0.4472135954999579]
1 / b (ID98)-0.2161209223472559-0.1528205697480359false0[-0.4472135954999579,0.4472135954999579]

Scores divide the rotated dot product by sqrt(Dk)=sqrt2. A forbidden future cell retains its actual raw score but has exactly zero probability. Each value mixture multiplies then immediately accumulates in ascending key order, including masked zero terms. This is computation, not an explanation of a trained model's reasoning.

Inspect selected score, stable attention row and both value mixtures
Saved causal attention arithmetic — saved values without display rounding
Saved operationActual inputsActual outputs
prefill_heads_score_0_0_0_0
b=0
h=0
i=0
j=0
Dk=2
divisor=1.4142135623730951
q0=0.4472135954999579
k0=0.4472135954999579
q1=-0.4472135954999579
k1=-0.4472135954999579
product0=0.19999999999999998
product1=0.19999999999999998
raw=0.39999999999999997
score=0.28284271247461895
prefill_heads_row_0_0_0
b=0
h=0
i=0
mode=1
shift=0
score0=0.28284271247461895
score1=-0.1528205697480359
allowed0=1
allowed1=0
max=0.28284271247461895
denominator=1
shifted0=0
term0=1
term1=0
p0=1
p1=0
prefill_heads_head_mix_0_0_0_0
b=0
h=0
i=0
f=0
p0=1
v0=0.4472135954999579
p1=0
v1=-0.4472135954999579
product0=0.4472135954999579
product1=0
running0=0.4472135954999579
running1=0.4472135954999579
value=0.4472135954999579
prefill_heads_head_mix_0_0_0_1
b=0
h=0
i=0
f=1
p0=1
v0=-0.4472135954999579
p1=0
v1=0.4472135954999579
product0=-0.4472135954999579
product1=0
running0=-0.4472135954999579
running1=-0.4472135954999579
value=-0.4472135954999579
prefill_heads_output_0_0_0
b=0
t=0
d=0
c0=0.4472135954999579
w0=1
c1=-0.4472135954999579
w1=0
product0=0.4472135954999579
product1=0
running0=0.4472135954999579
running1=0.4472135954999579
value=0.4472135954999579
prefill_heads_output_0_0_1
b=0
t=0
d=1
c0=0.4472135954999579
w0=0
c1=-0.4472135954999579
w1=1
product0=0
product1=-0.4472135954999579
running0=0
running1=-0.4472135954999579
value=-0.4472135954999579

All three FFN coordinates are real calculations

Prefill position 0 FFN — saved values without display rounding
Hidden coordinateAffine ZReLU activation
00.68768540751631810.6876854075163181
1-0.68768540751631810
200

The fixed third hidden coordinate has zero weights, so its zero is computed. The residual retains X even when normalized branches vanish. This lesson performs no target scoring, loss calculation, gradient or parameter update.

Inspect this token's complete FFN products and ReLU operations
Saved FFN arithmetic — saved values without display rounding
Saved operationActual inputsActual outputs
prefill_ffn_hidden_0_0_0
b=0
t=0
m=0
x0=0.6876854075163181
x1=-0.6876854075163181
w0=1
w1=0
bias=0
product0=0.6876854075163181
product1=0
sum=0.6876854075163181
preactivation=0.6876854075163181
prefill_ffn_hidden_0_0_1
b=0
t=0
m=1
x0=0.6876854075163181
x1=-0.6876854075163181
w0=0
w1=1
bias=0
product0=0
product1=-0.6876854075163181
sum=-0.6876854075163181
preactivation=-0.6876854075163181
prefill_ffn_hidden_0_0_2
b=0
t=0
m=2
x0=0.6876854075163181
x1=-0.6876854075163181
w0=0
w1=0
bias=0
product0=0
product1=0
sum=0
preactivation=0
prefill_ffn_relu_0_0_0
b=0
t=0
m=0
preactivation=0.6876854075163181
activation=0.6876854075163181
prefill_ffn_relu_0_0_1
b=0
t=0
m=1
preactivation=-0.6876854075163181
activation=0
prefill_ffn_relu_0_0_2
b=0
t=0
m=2
preactivation=0
activation=0
prefill_ffn_output_0_0_0
b=0
t=0
d=0
h0=0.6876854075163181
w0=1
h1=0
w1=0
h2=0
w2=0
bias=0
product0=0.6876854075163181
product1=0
product2=0
running0=0.6876854075163181
running1=0.6876854075163181
running2=0.6876854075163181
sum=0.6876854075163181
value=0.6876854075163181
prefill_ffn_output_0_0_1
b=0
t=0
d=1
h0=0.6876854075163181
w0=0
h1=0
w1=1
h2=0
w2=0
bias=0
product0=0
product1=0
product2=0
running0=0
running1=0
running2=0
sum=0
value=0

Readout produces actual logits and active probabilities

Prefill position 0 active classes — saved values without display rounding
Compact class / public IDComputed logitShifted logitexp(shifted)Stored probability
0 / a (ID97)2.134899003016276010.8376116959343609
1 / b (ID98)-0.4472135954999579-2.5821125985162340.07561409294780220.063335248630547
2 / EOS (ID512)0-2.1348990030162760.118256533326695960.09905305543509206

Saved maximum 2.134899003016276, denominator 1.1938706262744982, logS 0.17720065589584005, LSE 2.312099658912116. Computed-logit winner a (ID97); exact ties keep the lowest compact class. This prediction does not claim the probability of the externally supplied ID.

Inspect selected affine readout and stable class normalization
Saved readout arithmetic — saved values without display rounding
Saved operationActual inputsActual outputs
prefill_readout_0_0
t=0
c=0
y0=2.134899003016276
u0=1
y1=-0.4472135954999579
u1=0
bias=0
product0=2.134899003016276
product1=0
sum=2.134899003016276
logit=2.134899003016276
prefill_class_0_max
z0=2.134899003016276
z1=-0.4472135954999579
z2=0
max=2.134899003016276
prefill_class_0_exp_0
t=0
c=0
logit=2.134899003016276
max=2.134899003016276
shifted=0
term=1
prefill_class_0_normalize
term0=1
term1=0.0756140929478022
term2=0.11825653332669596
max=2.134899003016276
running0=1
running1=1.0756140929478022
running2=1.1938706262744982
denominator=1.1938706262744982
logS=0.17720065589584005
lse=2.312099658912116
prefill_class_0_probability_0
t=0
c=0
term=1
denominator=1.1938706262744982
probability=0.8376116959343609
prefill_class_0_argmax
z0=2.134899003016276
z1=-0.4472135954999579
z2=0
nextRow=0
nextID=97
nextProbability=0.8376116959343609

Compare every earlier row from the two actual calls

Saved maximum absolute differences: Y=0, logits=0, P=0. These come from actual before/after operands. The same IDs, positions and parameters plus strict causal masking preserve the earlier rows; raw future score cells are not required to match.

Complete saved prior-row comparison operands — saved values without display rounding
Saved operationActual inputsActual outputs
compare_Y_0
t=0
before0=2.134899003016276
after0=2.134899003016276
before1=-0.4472135954999579
after1=-0.4472135954999579
difference0=0
runningMax0=0
difference1=0
runningMax1=0
maxDifference=0
compare_Y_1
t=1
before0=-0.0959051290352784
after0=-0.0959051290352784
before1=1.6078120278761694
after1=1.6078120278761694
difference0=0
runningMax0=0
difference1=0
runningMax1=0
maxDifference=0
compare_Logits_0
t=0
before0=2.134899003016276
after0=2.134899003016276
before1=-0.4472135954999579
after1=-0.4472135954999579
before2=0
after2=0
difference0=0
runningMax0=0
difference1=0
runningMax1=0
difference2=0
runningMax2=0
maxDifference=0
compare_Logits_1
t=1
before0=-0.0959051290352784
after0=-0.0959051290352784
before1=1.6078120278761694
after1=1.6078120278761694
before2=0
after2=0
difference0=0
runningMax0=0
difference1=0
runningMax1=0
difference2=0
runningMax2=0
maxDifference=0
compare_P_0
t=0
before0=0.8376116959343609
after0=0.8376116959343609
before1=0.063335248630547
after1=0.063335248630547
before2=0.09905305543509206
after2=0.09905305543509206
difference0=0
runningMax0=0
difference1=0
runningMax1=0
difference2=0
runningMax2=0
maxDifference=0
compare_P_1
t=1
before0=0.13166578760192524
after0=0.13166578760192524
before1=0.7234156524931242
after1=0.7234156524931242
before2=0.14491855990495064
after2=0.14491855990495064
difference0=0
runningMax0=0
difference1=0
runningMax1=0
difference2=0
runningMax2=0
maxDifference=0
Inspect prompt BPE evidence and actual final reconstruction

Fixed corpus "abab". Learned rules []. Actual prompt labels ["ID 97, bytes [97]","ID 98, bytes [98]"]. Zero merges requested: no training round or pair selection occurs.

The old helper records its real inner bound24bytes/4merges; this lesson enforces the smaller outer6bytes/2merges and at most2 encoded prompt tokens. Result IDs remain fixed even when decoding them creates characters that a fresh tokenizer would combine.

Saved tokenizer and strict reverse decoder operations — saved values without display rounding
Saved operationActual inputsActual outputs
tokenizer_setup
requestedMerges=0
eos=0
corpusUnits=4
corpusScalars=4
utf16Units=2
scalarCount=2
byteBound=24
mergeBase=256
mergeBound=4
EOS=512
tokenizer_corpus_scalar_0
scalarIndex=0
utf16Offset=0
utf16Width=1
codePoint=97
unit0=97
byteOffset=0
byteWidth=1
payload0=97
byte0=97
tokenizer_corpus_scalar_1
scalarIndex=1
utf16Offset=1
utf16Width=1
codePoint=98
unit0=98
byteOffset=1
byteWidth=1
payload0=98
byte0=98
tokenizer_corpus_scalar_2
scalarIndex=2
utf16Offset=2
utf16Width=1
codePoint=97
unit0=97
byteOffset=2
byteWidth=1
payload0=97
byte0=97
tokenizer_corpus_scalar_3
scalarIndex=3
utf16Offset=3
utf16Width=1
codePoint=98
unit0=98
byteOffset=3
byteWidth=1
payload0=98
byte0=98
tokenizer_source_scalar_0
scalarIndex=0
utf16Offset=0
utf16Width=1
codePoint=97
unit0=97
byteOffset=0
byteWidth=1
payload0=97
byte0=97
tokenizer_source_scalar_1
scalarIndex=1
utf16Offset=1
utf16Width=1
codePoint=98
unit0=98
byteOffset=1
byteWidth=1
payload0=98
byte0=98
tokenizer_corpus_expand_0
index=0
id=97
byteOffset=0
byteWidth=1
byte0=97
tokenizer_corpus_expand_1
index=1
id=98
byteOffset=1
byteWidth=1
byte0=98
tokenizer_corpus_expand_2
index=2
id=97
byteOffset=2
byteWidth=1
byte0=97
tokenizer_corpus_expand_3
index=3
id=98
byteOffset=3
byteWidth=1
byte0=98
tokenizer_corpus_decode_0
scalarIndex=0
byteOffset=0
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
tokenizer_corpus_decode_1
scalarIndex=1
byteOffset=1
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
tokenizer_corpus_decode_2
scalarIndex=2
byteOffset=2
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
tokenizer_corpus_decode_3
scalarIndex=3
byteOffset=3
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
tokenizer_target_expand_0
index=0
id=97
byteOffset=0
byteWidth=1
byte0=97
tokenizer_target_expand_1
index=1
id=98
byteOffset=1
byteWidth=1
byte0=98
tokenizer_target_decode_0
scalarIndex=0
byteOffset=0
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
tokenizer_target_decode_1
scalarIndex=1
byteOffset=1
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
tokenizer_roundtrip
corpusOriginalUnits=4
corpusDecodedUnits=4
corpusDecodedByteCount=4
originalUnits=2
decodedUnits=2
decodedByteCount=2
corpusTokens=4
tokenCount=2
corpusEqual=1
equal=1
result_expand_0
index=0
id=97
byteOffset=0
byteWidth=1
byte0=97
result_expand_1
index=1
id=98
byteOffset=1
byteWidth=1
byte0=98
result_expand_2
index=2
id=97
byteOffset=2
byteWidth=1
byte0=97
result_decode_0
scalarIndex=0
byteOffset=0
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
result_decode_1
scalarIndex=1
byteOffset=1
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
result_decode_2
scalarIndex=2
byteOffset=2
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97

The full inspector retains all57 tensors from each actual forward call, every dtype/axis/provenance and all decoder evidence. Values shown here are stored binary64 values. Square roots, trigonometry, exponentials and logarithms are approximate library operations; these hand-set parameters have not been trained.

Inspect all stored values, text metadata and tensor storage

Every scalar output, including flattened operation outputs

Exact text evidence from the same record

These are the stored values, shown without display rounding. Each tensor names its axes, dtype and display precision. Empty arrays are omitted rather than padded.

TokenizerCorpusCodePoints

Scalars=4 · int32 · precision 0 · Prompt BPE with EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198
297
398

TokenizerCorpusUTF16Offsets

Scalars=4 · int32 · precision 0 · Prompt BPE with EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

TokenizerCorpusUTF16Widths

Scalars=4 · int32 · precision 0 · Prompt BPE with EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11
21
31

TokenizerCorpusByteOffsets

Scalars=4 · int32 · precision 0 · Prompt BPE with EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

TokenizerCorpusByteWidths

Scalars=4 · int32 · precision 0 · Prompt BPE with EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11
21
31

TokenizerCorpusBytes

Bytes=4 · int32 · precision 0 · Prompt BPE with EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198
297
398

TokenizerSourceCodePoints

Scalars=2 · int32 · precision 0 · Prompt BPE with EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198

TokenizerSourceUTF16Offsets

Scalars=2 · int32 · precision 0 · Prompt BPE with EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11

TokenizerSourceUTF16Widths

Scalars=2 · int32 · precision 0 · Prompt BPE with EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11

TokenizerSourceByteOffsets

Scalars=2 · int32 · precision 0 · Prompt BPE with EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11

TokenizerSourceByteWidths

Scalars=2 · int32 · precision 0 · Prompt BPE with EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11

TokenizerSourceBytes

Bytes=2 · int32 · precision 0 · Prompt BPE with EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198

TokenizerTrainInitialIDs

Tokens=4 · int32 · precision 0 · Prompt BPE with EOS off. Initial training byte IDs, one ID for each actual corpus byte.

Zero-based storage indexStored value
097
198
297
398

TokenizerCorpusIDs

Tokens=4 · int32 · precision 0 · Prompt BPE with EOS off. Final learned corpus token IDs; corpus training never contains EOS.

Zero-based storage indexStored value
097
198
297
398

TokenizerEncodeInitialIDs

Tokens=2 · int32 · precision 0 · Prompt BPE with EOS off. Initial target byte IDs before any ranked application.

Zero-based storage indexStored value
097
198

TokenizerTargetIDs

Tokens=2 · int32 · precision 0 · Prompt BPE with EOS off. Final target token IDs after all learned ranks, then optional unique EOS tail.

Zero-based storage indexStored value
097
198

TokenizerCorpusDecodedBytes

Bytes=4 · int32 · precision 0 · Prompt BPE with EOS off. Actual final corpus ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198
297
398

TokenizerTargetDecodedBytes

Bytes=2 · int32 · precision 0 · Prompt BPE with EOS off. Actual final target ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198

PrefillAllClassIDs

ModelRow=5 · int32 · precision 0 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets.

Zero-based storage indexStored value
097
198
2512
3256
4257

PrefillClassIDs

Class=3 · int32 · precision 0 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Active prefix of the full model row map; V=3+merges.

Zero-based storage indexStored value
097
198
2512

PrefillE

ModelRow=5 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: All ten validated editable embeddings, including EOS and inactive learned pieces.

Zero-based storage indexStored value
01
10
20
31
40
50
60.5
70.5
81
91

PrefillU

D=2 × ModelRow=5 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: All ten validated editable readout weights; only the first V columns contribute logits.

Zero-based storage indexStored value
01
10
20
30
40
50
61
70
80
90

PrefillBias

ModelRow=5 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: All five validated editable biases; inactive columns have no objective dependency.

Zero-based storage indexStored value
00
10
20
30
40

PrefillInputIDs

Position=2 · int32 · precision 0 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.

Zero-based storage indexStored value
097
198

PrefillInputRows

Position=2 · int32 · precision 0 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Compact model row gathered for each observed ID; never index by public ID512.

Zero-based storage indexStored value
00
11

PrefillX

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Actual gathered E rows; B=1, token-major storage and D=2.

Zero-based storage indexStored value
01
10
20
31

PrefillLN1

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Per-token feature layer norm of X; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionX

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Active token rows; D=2 input features always retained. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionWQ

D=2 × QueryFeature=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Query columns packed by h*Dk+f from wq{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

PrefillProjectionWK

D=2 × KeyFeature=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Key columns packed by h*Dk+f from wk{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

PrefillProjectionWV

D=2 × ValueFeature=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Value columns packed by h*Dv+f from wv{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

PrefillProjectionQConcat

B=1 × T=2 × QueryFeature=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: XWQ; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionKConcat

B=1 × T=2 × KeyFeature=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: XWK; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionVConcat

B=1 × T=2 × ValueFeature=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: XWV; values are projected separately from queries and keys. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionQSplit

B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: QConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionQHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionKSplit

B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: KConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionKHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionVSplit

B=1 × T=2 × H=1 × Dv=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: VConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillProjectionVHeads

B=1 × H=1 × T=2 × Dv=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

PrefillRotatedQHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211

PrefillRotatedKHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211

PrefillRoPEAngles

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Absolute position t times the single-pair frequency1, in radians.

Zero-based storage indexStored value
00
11

PrefillRoPECos

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Stored cos(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
01
10.5403023058681398

PrefillRoPESin

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Stored sin(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
00
10.8414709848078965

PrefillAttentionraw

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Separate QHeads KHeads transpose products within every batch and head. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.39999999999999997
1-0.2161209223472559
2-0.2161209223472559
30.4000000000000001

PrefillAttentionscores

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895
1-0.1528205697480359
2-0.1528205697480359
30.28284271247461906

PrefillAttentionallowed

B=1 × H=1 × Query=2 × Key=2 · bool · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Causal and/or valid-key mask; shared validity across B and H; every query retained. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
0true
1false
2true
3true

PrefillAttentionlogits

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Finite score+shift, including forbidden cells; mask applied separately. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895
1-0.1528205697480359
2-0.1528205697480359
30.28284271247461906

PrefillAttentionprobabilities

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
01
10
20.3927748060431144
30.6072251939568857

PrefillAttentionOHeads

B=1 × H=1 × Query=2 × Dv=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Actual per-head P times VHeads; every product and running sum is traced. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784

PrefillAttentionC

B=1 × T=2 × JoinedValue=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784

PrefillAttentionWO

JoinedValue=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: wo{h}{f}{d} packed in h,f,d order, preserving parameter identity. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
01
10
20
31

PrefillAttentionOutput

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Y=C WO, summing products in ascending joined-feature order from zero; no normalization. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784

PrefillR1

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Exact named-shape addition of X and AttentionOutput; no broadcasting.

Zero-based storage indexStored value
01.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
31.0959051290352784

PrefillLN2

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Per-token feature layer norm of R1; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
00.6876854075163181
1-0.6876854075163181
2-0.5119068988408909
30.5119068988408909

PrefillW1

D=2 × HiddenFeature=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

Zero-based storage indexStored value
01
10
20
30
41
50

Prefillb1

HiddenFeature=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Shared hidden bias, added after the two products.

Zero-based storage indexStored value
00
10
20

PrefillZ

B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Hidden preactivations X W1+b1; no batch or token mixing.

Zero-based storage indexStored value
00.6876854075163181
1-0.6876854075163181
20
3-0.5119068988408909
40.5119068988408909
50

PrefillHidden

B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: ReLU(Z)=max(0,Z), before the second affine layer.

Zero-based storage indexStored value
00.6876854075163181
10
20
30
40.5119068988408909
50

PrefillW2

HiddenFeature=3 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Shared hidden-to-output weights, f2{m}{d}.

Zero-based storage indexStored value
01
10
20
31
40
50

Prefillb2

D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Shared output bias, added after all three running sums.

Zero-based storage indexStored value
00
10

PrefillF

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

Zero-based storage indexStored value
00.6876854075163181
10
20
30.5119068988408909

PrefillY

B=1 × T=2 × D=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Exact named-shape addition of R1 and F; no broadcasting.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
2-0.0959051290352784
31.6078120278761694

PrefillLogits

Position=2 × Class=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Final Y times the active U prefix, then active Bias; targets are not operands.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
20
3-0.0959051290352784
41.6078120278761694
50

PrefillMax

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Maximum computed active class logit at each position.

Zero-based storage indexStored value
02.134899003016276
11.6078120278761694

PrefillShifted

Position=2 × Class=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Computed class logit minus its saved row maximum.

Zero-based storage indexStored value
00
1-2.582112598516234
2-2.134899003016276
3-1.7037171569114478
40
5-1.6078120278761694

PrefillTerms

Position=2 × Class=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Actual exp(Shifted) before left-to-right class summation.

Zero-based storage indexStored value
01
10.0756140929478022
20.11825653332669596
30.1820057212588121
41
50.20032544140497158

PrefillDenominator

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Shifted exponential sum from zero in ascending compact class order.

Zero-based storage indexStored value
01.1938706262744982
11.3823311626637835

PrefillLogS

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: ln(Denominator), saved for factored NLL.

Zero-based storage indexStored value
00.17720065589584005
10.3237713223010388

PrefillLSE

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Max+LogS; saved evidence, not subtracted from target logits to compute NLL.

Zero-based storage indexStored value
02.312099658912116
11.9315833501772082

PrefillP

Position=2 × Class=3 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Terms/Denominator for real active classes only; no inactive-class probabilities.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
20.09905305543509206
30.13166578760192524
40.7234156524931242
50.14491855990495064

PrefillNextRows

Position=2 · int32 · precision 0 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Highest computed logit; exact ties keep the smallest compact class.

Zero-based storage indexStored value
00
11

PrefillNextIDs

Position=2 · int32 · precision 0 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Public ID mapped from each computed-logit winner.

Zero-based storage indexStored value
097
198

PrefillNextProbability

Position=2 · float64 · precision 8 · Prefill full-prefix inference, absolute positions 0..1; inherited kernel provenance: Stored class probability of the computed-logit winner; never fed back as an observed input.

Zero-based storage indexStored value
00.8376116959343609
10.7234156524931242

DecodeAllClassIDs

ModelRow=5 · int32 · precision 0 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets.

Zero-based storage indexStored value
097
198
2512
3256
4257

DecodeClassIDs

Class=3 · int32 · precision 0 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Active prefix of the full model row map; V=3+merges.

Zero-based storage indexStored value
097
198
2512

DecodeE

ModelRow=5 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: All ten validated editable embeddings, including EOS and inactive learned pieces.

Zero-based storage indexStored value
01
10
20
31
40
50
60.5
70.5
81
91

DecodeU

D=2 × ModelRow=5 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: All ten validated editable readout weights; only the first V columns contribute logits.

Zero-based storage indexStored value
01
10
20
30
40
50
61
70
80
90

DecodeBias

ModelRow=5 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: All five validated editable biases; inactive columns have no objective dependency.

Zero-based storage indexStored value
00
10
20
30
40

DecodeInputIDs

Position=3 · int32 · precision 0 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.

Zero-based storage indexStored value
097
198
297

DecodeInputRows

Position=3 · int32 · precision 0 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Compact model row gathered for each observed ID; never index by public ID512.

Zero-based storage indexStored value
00
11
20

DecodeX

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Actual gathered E rows; B=1, token-major storage and D=2.

Zero-based storage indexStored value
01
10
20
31
41
50

DecodeLN1

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Per-token feature layer norm of X; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionX

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Active token rows; D=2 input features always retained. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionWQ

D=2 × QueryFeature=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Query columns packed by h*Dk+f from wq{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

DecodeProjectionWK

D=2 × KeyFeature=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Key columns packed by h*Dk+f from wk{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

DecodeProjectionWV

D=2 × ValueFeature=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Value columns packed by h*Dv+f from wv{d}{h}{f}. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
01
10
20
31

DecodeProjectionQConcat

B=1 × T=3 × QueryFeature=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: XWQ; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionKConcat

B=1 × T=3 × KeyFeature=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: XWK; each packed coordinate has two products and one sum. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionVConcat

B=1 × T=3 × ValueFeature=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: XWV; values are projected separately from queries and keys. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionQSplit

B=1 × T=3 × H=1 × Dk=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: QConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionQHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionKSplit

B=1 × T=3 × H=1 × Dk=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: KConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionKHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionVSplit

B=1 × T=3 × H=1 × Dv=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: VConcat reshaped without changing flat order; feature=h*F+f. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeProjectionVHeads

B=1 × H=1 × T=3 × Dv=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced. Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

DecodeRotatedQHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211
40.22054364860139217
50.5927566946577538

DecodeRotatedKHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211
40.22054364860139217
50.5927566946577538

DecodeRoPEAngles

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Absolute position t times the single-pair frequency1, in radians.

Zero-based storage indexStored value
00
11
22

DecodeRoPECos

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Stored cos(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
01
10.5403023058681398
2-0.4161468365471424

DecodeRoPESin

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Stored sin(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
00
10.8414709848078965
20.9092974268256817

DecodeAttentionraw

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Separate QHeads KHeads transpose products within every batch and head. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.39999999999999997
1-0.2161209223472559
2-0.1664587346188569
3-0.2161209223472559
40.4000000000000001
5-0.21612092234725588
6-0.1664587346188569
7-0.21612092234725588
80.39999999999999997

DecodeAttentionscores

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895
1-0.1528205697480359
2-0.11770410003672563
3-0.1528205697480359
40.28284271247461906
5-0.15282056974803587
6-0.11770410003672563
7-0.15282056974803587
80.28284271247461895

DecodeAttentionallowed

B=1 × H=1 × Query=3 × Key=3 · bool · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Causal and/or valid-key mask; shared validity across B and H; every query retained. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
0true
1false
2false
3true
4true
5false
6true
7true
8true

DecodeAttentionlogits

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Finite score+shift, including forbidden cells; mask applied separately. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.28284271247461895
1-0.1528205697480359
2-0.11770410003672563
3-0.1528205697480359
40.28284271247461906
5-0.15282056974803587
6-0.11770410003672563
7-0.15282056974803587
80.28284271247461895

DecodeAttentionprobabilities

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
01
10
20
30.3927748060431144
40.6072251939568857
50
60.2891733251316062
70.2791948093517053
80.43163186551668853

DecodeAttentionOHeads

B=1 × H=1 × Query=3 × Dv=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Actual per-head P times VHeads; every product and running sum is traced. QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784
40.19749416642975512
5-0.19749416642975512

DecodeAttentionC

B=1 × T=3 × JoinedValue=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784
40.19749416642975512
5-0.19749416642975512

DecodeAttentionWO

JoinedValue=2 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: wo{h}{f}{d} packed in h,f,d order, preserving parameter identity. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
01
10
20
31

DecodeAttentionOutput

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Y=C WO, summing products in ascending joined-feature order from zero; no normalization. Source is AttentionOHeads; active WO is explicitly identity2.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784
40.19749416642975512
5-0.19749416642975512

DecodeR1

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Exact named-shape addition of X and AttentionOutput; no broadcasting.

Zero-based storage indexStored value
01.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
31.0959051290352784
41.1974941664297551
5-0.19749416642975512

DecodeLN2

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Per-token feature layer norm of R1; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.

Zero-based storage indexStored value
00.6876854075163181
1-0.6876854075163181
2-0.5119068988408909
30.5119068988408909
40.5720821519582194
5-0.5720821519582194

DecodeW1

D=2 × HiddenFeature=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

Zero-based storage indexStored value
01
10
20
30
41
50

Decodeb1

HiddenFeature=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Shared hidden bias, added after the two products.

Zero-based storage indexStored value
00
10
20

DecodeZ

B=1 × T=3 × HiddenFeature=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Hidden preactivations X W1+b1; no batch or token mixing.

Zero-based storage indexStored value
00.6876854075163181
1-0.6876854075163181
20
3-0.5119068988408909
40.5119068988408909
50
60.5720821519582194
7-0.5720821519582194
80

DecodeHidden

B=1 × T=3 × HiddenFeature=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: ReLU(Z)=max(0,Z), before the second affine layer.

Zero-based storage indexStored value
00.6876854075163181
10
20
30
40.5119068988408909
50
60.5720821519582194
70
80

DecodeW2

HiddenFeature=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Shared hidden-to-output weights, f2{m}{d}.

Zero-based storage indexStored value
01
10
20
31
40
50

Decodeb2

D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Shared output bias, added after all three running sums.

Zero-based storage indexStored value
00
10

DecodeF

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

Zero-based storage indexStored value
00.6876854075163181
10
20
30.5119068988408909
40.5720821519582194
50

DecodeY

B=1 × T=3 × D=2 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Exact named-shape addition of R1 and F; no broadcasting.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
2-0.0959051290352784
31.6078120278761694
41.7695763183879745
5-0.19749416642975512

DecodeLogits

Position=3 × Class=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Final Y times the active U prefix, then active Bias; targets are not operands.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
20
3-0.0959051290352784
41.6078120278761694
50
61.7695763183879745
7-0.19749416642975512
80

DecodeMax

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Maximum computed active class logit at each position.

Zero-based storage indexStored value
02.134899003016276
11.6078120278761694
21.7695763183879745

DecodeShifted

Position=3 × Class=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Computed class logit minus its saved row maximum.

Zero-based storage indexStored value
00
1-2.582112598516234
2-2.134899003016276
3-1.7037171569114478
40
5-1.6078120278761694
60
7-1.9670704848177296
8-1.7695763183879745

DecodeTerms

Position=3 × Class=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Actual exp(Shifted) before left-to-right class summation.

Zero-based storage indexStored value
01
10.0756140929478022
20.11825653332669596
30.1820057212588121
41
50.20032544140497158
61
70.1398659961908848
80.17040517107076136

DecodeDenominator

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Shifted exponential sum from zero in ascending compact class order.

Zero-based storage indexStored value
01.1938706262744982
11.3823311626637835
21.310271167261646

DecodeLogS

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: ln(Denominator), saved for factored NLL.

Zero-based storage indexStored value
00.17720065589584005
10.3237713223010388
20.2702341137016024

DecodeLSE

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Max+LogS; saved evidence, not subtracted from target logits to compute NLL.

Zero-based storage indexStored value
02.312099658912116
11.9315833501772082
22.0398104320895767

DecodeP

Position=3 × Class=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Terms/Denominator for real active classes only; no inactive-class probabilities.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
20.09905305543509206
30.13166578760192524
40.7234156524931242
50.14491855990495064
60.7632007976561935
70.1067458398578614
80.13005336248594518

DecodeNextRows

Position=3 · int32 · precision 0 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Highest computed logit; exact ties keep the smallest compact class.

Zero-based storage indexStored value
00
11
20

DecodeNextIDs

Position=3 · int32 · precision 0 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Public ID mapped from each computed-logit winner.

Zero-based storage indexStored value
097
198
297

DecodeNextProbability

Position=3 · float64 · precision 8 · Decode full-prefix inference, absolute positions 0..2; inherited kernel provenance: Stored class probability of the computed-logit winner; never fed back as an observed input.

Zero-based storage indexStored value
00.8376116959343609
10.7234156524931242
20.7632007976561935

PrefixYBefore

PriorPosition=2 × D=2 · float64 · precision 8 · Actual complete prefill rows copied from the saved forward tensor.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
2-0.0959051290352784
31.6078120278761694

PrefixYAfter

PriorPosition=2 × D=2 · float64 · precision 8 · Actual first N rows copied from the extended-prefix forward tensor.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
2-0.0959051290352784
31.6078120278761694

PrefixYAbsDiff

PriorPosition=2 × D=2 · float64 · precision 8 · Computed abs(after-before) for every prior-row coordinate; no synthetic zero fill.

Zero-based storage indexStored value
00
10
20
30

PrefixLogitsBefore

PriorPosition=2 × Class=3 · float64 · precision 8 · Actual complete prefill rows copied from the saved forward tensor.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
20
3-0.0959051290352784
41.6078120278761694
50

PrefixLogitsAfter

PriorPosition=2 × Class=3 · float64 · precision 8 · Actual first N rows copied from the extended-prefix forward tensor.

Zero-based storage indexStored value
02.134899003016276
1-0.4472135954999579
20
3-0.0959051290352784
41.6078120278761694
50

PrefixLogitsAbsDiff

PriorPosition=2 × Class=3 · float64 · precision 8 · Computed abs(after-before) for every prior-row coordinate; no synthetic zero fill.

Zero-based storage indexStored value
00
10
20
30
40
50

PrefixPBefore

PriorPosition=2 × Class=3 · float64 · precision 8 · Actual complete prefill rows copied from the saved forward tensor.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
20.09905305543509206
30.13166578760192524
40.7234156524931242
50.14491855990495064

PrefixPAfter

PriorPosition=2 × Class=3 · float64 · precision 8 · Actual first N rows copied from the extended-prefix forward tensor.

Zero-based storage indexStored value
00.8376116959343609
10.063335248630547
20.09905305543509206
30.13166578760192524
40.7234156524931242
50.14491855990495064

PrefixPAbsDiff

PriorPosition=2 × Class=3 · float64 · precision 8 · Computed abs(after-before) for every prior-row coordinate; no synthetic zero fill.

Zero-based storage indexStored value
00
10
20
30
40
50

DecodePositions

Position=3 · int32 · precision 0 · Actual absolute positions consumed by the uncached extended-prefix call.

Zero-based storage indexStored value
00
11
22

PromptIDs

PromptPosition=2 · int32 · precision 0 · Actual EOS-off BPE prompt, tokenized once.

Zero-based storage indexStored value
097
198

ResultIDs

LogicalPosition=3 · int32 · precision 0 · Prompt IDs plus exactly the externally supplied ID; a final EOS is logical control only.

Zero-based storage indexStored value
097
198
297

PrefillPositions

Position=2 · int32 · precision 0 · Actual absolute positions processed by prefill.

Zero-based storage indexStored value
00
11

ResultBytes

Bytes=3 · int32 · precision 0 · Actual strict reverse-decoder expansion bytes; a stopping EOS emits none.

Zero-based storage indexStored value
097
198
297

Check your understanding

Use the inputs stated in each question. Live questions use the current calculation. Each option pairs a value or conclusion with its mechanism. Editing a raw input, resetting or selecting a trace step clears graded answers; local inspection selectors preserve them.

1. What does prefill mean in this walkthrough?
2. The current record has promptTokens=2, nextID=97, stoppedEOS=0. Which novel-input count and total token-row work agree with the saved calls?
3. Current prompt length N=2; appended slot newPosition=2. Which absolute positions and score-cell counts match the saved forward calls?
4. The prefill last-row model prediction is public ID98; your supplied nextID is 97. Which statement respects the actual saved prefix comparisons?
5. Set text=ab, merges=2 and nextID=256 (ab). The actual prompt encodes as [256]. What logical result and reconstructed text should this lab retain?

Try EOS512 to see the second-call region disappear. Then set merges2 and nextID256 with prompt ab: the retained result IDs are [256,256], even though freshly tokenizing the decoded abab would give [257]. Select a phase, query, key and compact class to inspect the actual saved arithmetic.

All25 model parameters remain editable and validated, including inactive and EOS rows. A stopping EOS has no input gather. No cache, target loss, gradient, training or latency measurement is implemented here. Input edits, reset and trace navigation clear graded answers; independent inspection selectors only change the view.

Begin at reset: text ab, zero merges, and externally supplied nextID=97, the token a. The first four summaries are promptTokens=2, newTokensConsumed=1, prefillWorkTokens=2, decodeWorkTokens=3. Read them as two prompt tokens, one novel input, two rows calculated initially and three rows calculated afterward. Three decode work rows do not mean three newly generated tokens.

Use Actual model call to inspect to switch between the saved Prefill and executed Decode call, then Observed position / attention query, Attention key position, and Active compact readout class to follow one indexed calculation. EOS removes the Decode choice because that call does not exist. These inspection selectors preserve graded answers and clamp their displayed indices to actual shapes. Input edits, Reset example and Calculation step trace navigation clear grades; a trace step and the independent inspection choices can point to different saved evidence. Parameter groups reveal the actual embedding, readout and bias controls; the final next-ID control is explicitly external.

Review IV-43 — End-to-End Tiny Language-Model Objective for this same tiny decoder. Book II’s II.9 — Matrix × vector and II.10 — Matrix × matrix as composition explain the matrix products; Book III’s III-16 — Multiclass Classification and Softmax Regression reviews class probabilities. The forward examples in III-40 — From Linear Model to Artificial Neuron and III-41 — Composition and Learned Representations are useful preparation for composing operations. Here, too, the weights are disclosed, hand-set and untrained. No loss, target, gradient or parameter update is needed to perform inference.

Two calls, one new ID, no cache

Inference evaluates a model with fixed parameters. Prefill processes the already supplied prompt. A subsequent decode call evaluates the prefix after a new token is supplied. A token is a piece named by an integer ID; the integer’s magnitude is not a feature value. This walkthrough supplies the appended ID explicitly. It does not claim that the model predicted that choice, even when the choice happens to agree with a model prediction.

A key/value cache, or KV cache, would retain earlier attention keys and values for reuse. This chapter implements no such reuse: cacheUsed=0 and cacheEntries=0. Both calls use the same ordinary forward kernel. For N prompt IDs, prefill computes N rows. For a non-EOS appended ID, the second call computes N+1 rows from the full extended prefix. Only the last ID is novel. Part XII will introduce actual caching; an unchanged earlier result here is evidence of causality, not evidence of a cache.

At reset the tokenizer produces [97,98]. Prefill uses positions [0,1]. Appending ID97 preserves those IDs and gives [97,98,97]; decode uses positions [0,1,2]. The new token’s absolute position is N=2. Calling it the first token of a new API request does not make its position zero.

PhaseActual input IDsAbsolute positionsNovel inputs consumed after prefillRows calculated in this call
Prefill[97,98][0,1]not a subsequent call2
Non-EOS decode[97,98,97][0,1,2]13

There are 2²=4 prefill score cells and 3²=9 decode score cells, including recorded forbidden comparisons. A causal mask allows key j only when j≤i for query i. Forbidden attention probabilities are exactly zero by construction; forbidden raw scores can still be recorded. Work counts describe this implementation’s explicit arrays, not a production latency or memory benchmark.

Follow the actual pieces and shapes

The tokenizer learns byte-pair encoding (BPE) rules from the fixed corpus abab, then applies them to the prompt with EOS insertion off. The compact neural map is fixed:

Compact row/classPublic IDPieceReset embedding
097a(1,0)
198b(0,1)
2512EOS(0,0)
3256ab(1/2,1/2)
4257abab(1,1)

With k merges, k=0,1,2, the active class count is V=3+k: take the first V rows of this map. ID512 addresses compact row2; it does not allocate 513 rows. ID256 requires at least one merge and ID257 requires two. An inactive next ID is invalid even if its characters look familiar.

A tensor is an array with named dimensions; its shape lists their lengths. For either forward call let T be its actual input count: N for prefill and N+1 for a non-EOS decode. Batch B=1, feature width D=2, head count H=1, query/key width Dk=2 and value width Dv=2 are fixed.

A query Q is the current position’s comparison vector; a key K is a candidate position’s comparison vector; a value supplies the features mixed by the resulting weights. One attention head performs one such comparison-and-mixture calculation. Here there is only one head. A logit is a real output-class score before probability normalization; the class probability P is the normalized weight of that possible next token.

QuantityShape; axesMeaning
E[5,2]; ModelRow, DAll stored embeddings, including inactive rows
Input IDs and gathered rows[T]; PositionPublic names and corresponding compact addresses
X, LN1, R1, LN2, F, Y[1,T,2]; B, T, DGathered and transformed token features
Q, K, value heads[1,1,T,2]; B, H, T, Dk or DvComparison and mixing features
Attention scores, mask, weights[1,1,T,T]; B, H, Query, KeyEvery query/key comparison and permission
FFN hidden features[1,T,3]; B, T, HiddenFeatureThree computed hidden coordinates
U; Bias[2,5]; [5]; D, ModelRow and ModelRowFull readout parameter storage
Logits and class probabilities P[T,V]; Position, ClassOnly active prediction classes

An embedding gathers a feature row from E. A readout multiplies final features by active columns of U and adds the corresponding biases. Feature-last rows [T,2] times weights [2,V] produce [T,V]; the matching feature dimension is summed. This is the row form of the earlier books’ matrix-times-column notation. IDs and positions are integers, the mask is boolean, and neural arithmetic is float64, also called binary64. Formatted decimals do not feed back into the computation.

The editable state has text, merges, ten E entries, ten U entries, five biases and finally nextID. For example, e30 means embedding row3/feature0; u12 means feature1/class2; b2 is class2’s bias. E/U entries lie in [−2,2], biases in [−4,4]. All raw parameters validate even when their rows are unused. The fixed Q/K/value and output projections are identity matrices of shape [2,2]. Both layer normalizations use gamma=(1,1), beta=(0,0) and epsilon1 inside the square root.

Gamma is the per-feature scale and beta the per-feature offset: multiply each normalized coordinate by its gamma entry, then add beta. Their fixed values 1 and 0 leave that coordinate unchanged. In the formulas below, exp(x) means the exponential e to the power x; square roots, sine and cosine use their usual real functions before the separate floating-point evaluation.

Reconstruct the prefill rows before deriving the new one

The following are exact real expressions, not reported machine outputs. A layer normalization centers the two features of each token, divides their squared deviations’ sum by2 to obtain population variance, adds epsilon1, and divides by its square root. For a row x=(x0,x1),

μ=(x0+x1)/2,v=((x0−μ)2+(x1−μ)2)/2,LN(x)d=(xd−μ)/v+1.\mu=(x_0+x_1)/2,\quad v=((x_0-\mu)^2+(x_1-\mu)^2)/2,\quad \mathrm{LN}(x)_d=(x_d-\mu)/\sqrt{v+1}.

Here μ is the feature mean, v the variance and d is feature0 or1. The reset embeddings (1,0) and (0,1) have mean1/2, centered squares1/4 and1/4, variance1/4 and denominator√5/2. Define α=1/√5. Their normalized rows are (α,−α) and (−α,α). Identity projections preserve those coordinates for queries Q, keys K and values.

RoPE, rotary positional encoding, rotates Q and K at absolute position t through angle t radians. Values are not rotated. For any pair (v0,v1),

Rt(v0,v1)=(v0cos⁡t−v1sin⁡t, v0sin⁡t+v1cos⁡t).R_t(v_0,v_1)=(v_0\cos t-v_1\sin t,\ v_0\sin t+v_1\cos t).

Define c1=cos1, s1=sin1 and g=2α²/√2. Position0’s rotated query/key is (α,−α); position1’s is (−α(c1+s1),α(c1−s1)). A score is their two-product dot sum divided by√2. The prefill score matrix is (g,−g c1;−g c1,g), with its row0/key1 cell forbidden.

Row0 has allowed exponential term1 and forbidden term0, so its attention weights are (1,0) and its mixed value is (α,−α). For row1 subtract maximum g: terms are (exp(−g(c1+1)),1). Put r=exp(g(1+c1)) and δ=(r−1)/(r+1). Dividing by the ordered sum gives weights (1/(1+r),r/(1+r)); mixing the unrotated values gives (−αδ,αδ). The identity attention output projection retains these values.

A residual adds the original input back to its transformed branch. The first residual rows are (1+α,−α) and (−αδ,1+αδ). Let Δ0=1/2+α, Δ1=1/2+αδ and ρi=Δi/√(Δi²+1) for i=0,1. Centering each residual row gives second normalized rows (ρ0,−ρ0) and (−ρ1,ρ1).

The fixed feed-forward network (FFN) maps (n0,n1) to hidden preactivations (n0,n1,0), applies ReLU, then reads back its first two coordinates. ReLU retains positive values and replaces negative values by0. In matrix form W1 has rows (1,0,0),(0,1,0) and W2 has rows (1,0),(0,1),(0,0); both bias vectors are zero. Their shapes [2,3] and [3,2] make the third hidden coordinate a real computed zero. Each output includes all three products. The FFN outputs are (ρ0,0) and (0,ρ1). Adding the second residual produces

Y0=(1+α+ρ0,−α),Y1=(−αδ,1+αδ+ρ1).Y_0=(1+\alpha+\rho_0,-\alpha),\qquad Y_1=(-\alpha\delta,1+\alpha\delta+\rho_1).

Reset U has rows (1,0,0,0,0) and (0,1,0,0,0) and Bias is zero. Each active logit first computes Y0·U0c, then Y1·U1c, adds those products, then adds bias c. Thus define A0=1+α+ρ0, B1=−αδ and A1=1+αδ+ρ1. Prefill logits are (A0,−α,0) and (B1,A1,0).

Their complete stable probability rows are

S0=((0+1)+exp⁡(−α−A0))+exp⁡(−A0),P0=(1,exp⁡(−α−A0),exp⁡(−A0))/S0,S_0=((0+1)+\exp(-\alpha-A_0))+\exp(-A_0),\quad P_0=(1,\exp(-\alpha-A_0),\exp(-A_0))/S_0, S1=((0+exp⁡(B1−A1))+1)+exp⁡(−A1),P1=(exp⁡(B1−A1),1,exp⁡(−A1))/S1.S_1=((0+\exp(B_1-A_1))+1)+\exp(-A_1),\quad P_1=(\exp(B_1-A_1),1,\exp(-A_1))/S_1.

Division of a tuple means dividing every coordinate by that row’s denominator. The last prefill winner is b/98 because A1 is positive and B1 negative. This is the same real row1 as IV-43’s forward calculation, without its subsequent target, loss or gradient calculations. Reset’s externally appended a is deliberately different from that winner.

Derive every operation for appended a at position 2

Gathering ID97 again supplies X2=(1,0). Its mean1/2, centered features (1/2,−1/2), variance1/4 and denominator√5/2 give LN1 row2=(α,−α). Identity Q/K/value projections compute α·1+(−α)·0=α and α·0+(−α)·1=−α. Put c2=cos2 and s2=sin2. Rotating the new query and key gives

q2′=k2′=(α(c2+s2),α(s2−c2)).q'_2=k'_2=(\alpha(c_2+s_2),\alpha(s_2-c_2)).

The new query may use all three keys. Its individual two-product sums are

q2′⋅k0′=α(c2+s2)α+α(s2−c2)(−α)=2α2c2,q'_2\cdot k'_0=\alpha(c_2+s_2)\alpha+\alpha(s_2-c_2)(-\alpha)=2\alpha^2c_2, q2′⋅k1′=[α(c2+s2)][−α(c1+s1)]+[α(s2−c2)][α(c1−s1)]=−2α2c1,q'_2\cdot k'_1=[\alpha(c_2+s_2)][-\alpha(c_1+s_1)] +[\alpha(s_2-c_2)][\alpha(c_1-s_1)]=-2\alpha^2c_1, q2′⋅k2′=[α(c2+s2)]2+[α(s2−c2)]2=2α2.q'_2\cdot k'_2=[\alpha(c_2+s_2)]^2+[\alpha(s_2-c_2)]^2=2\alpha^2.

The middle simplification uses cos(2−1)=cos1; the last uses sin²2+cos²2=1. Dividing each sum by√2 gives scores (g cos2,−g cos1,g). These equalities describe ideal real rotations; the saved trace uses the actual products and library sin/cos, whose rounding need not preserve the simplified identities bit for bit.

The maximum is g. Softmax turns scores into normalized mixing weights: subtract the maximum, exponentiate, add in key order and divide. Let

w0=exp⁡(g(cos⁡2−1)),w1=exp⁡(−g(cos⁡1+1)),w2=1,S=((0+w0)+w1)+1,pj=wj/S.w_0=\exp(g(\cos2-1)),\quad w_1=\exp(-g(\cos1+1)),\quad w_2=1, \quad S=((0+w_0)+w_1)+1,\quad p_j=w_j/S.

The index j visits key positions0,1,2. These p values are attention weights, distinct from class probabilities P. Mixing unrotated value rows yields first coordinate ((0+p0·α)+p1·(−α))+p2·α and second ((0+p0·(−α))+p1·α)+p2·(−α). Define a=α(p0−p1+p2)=α(1−2p1). The mixed value is (a,−a); identity WO computes a·1+(−a)·0 and a·0+(−a)·1, preserving it.

The new residual is R1₂=(1+a,−a). Its mean is1/2. Put Δ=1/2+a; centered coordinates are (Δ,−Δ), squared-feature sum2Δ², varianceΔ² and denominator√(Δ²+1). Let ρ=Δ/√(Δ²+1). LN2₂ is (ρ,−ρ).

The self-score g exceeds the score −g cos1, so w2>w1. Together with w0>0 this implies p1<1/2, a>0 and ρ>0. FFN preactivations are (ρ,−ρ,0), ReLU outputs (ρ,0,0), and the output products sum to (ρ,0). The final residual is therefore

Y2=(1+a+ρ,−a).Y_2=(1+a+\rho,-a).

Write A=1+a+ρ. Readout class a computes A·1+(−a)·0+0=A; class b computes A·0+(−a)·1+0=−a; EOS computes A·0+(−a)·0+0=0. Thus new logits are (A,−a,0). Their maximum is A; shifts are (0,−a−A,−A), terms (1,exp(−a−A),exp(−A)), denominator Sclass=((0+1)+exp(−a−A))+exp(−A) and every class probability is

P2=(1,exp⁡(−a−A),exp⁡(−A))/Sclass.P_2=(1,\exp(-a-A),\exp(-A))/S_{\mathrm{class}}.

The new winner is a/97. It describes the model’s preference for a token after aba; it is not a probability assertion about our external decision to append the preceding a. There is no target to score, no teacher forcing and no NLL in this lesson.

Why earlier rows remain equal

For an earlier query i, the new key N is forbidden. Its exponential term and probability are exactly0 and it contributes no value. All allowed old keys, their absolute positions and the parameters are unchanged. Layer normalization and the FFN operate within a row; the residuals add corresponding features. Earlier Y, logits and P therefore keep their old numerical values within this implementation, with signed zero treated as equivalent.

The record saves both comparison operands and calculated differences. Inspect those comparisons; they are not constants filled with an assumed zero. Do not compare the entire old and new records: their shapes, forbidden score evidence, work counts and input metadata differ. In particular a raw score involving a future key may change while its masked probability remains zero.

In the full-precision inspector, PrefixYBefore, PrefixYAfter and PrefixYAbsDiff have shape [N,2], axes PriorPosition and D. The corresponding PrefixLogitsBefore/After/AbsDiff and PrefixPBefore/After/AbsDiff have shape [N,V], axes PriorPosition and Class. They compare complete old rows against the first N rows of the extended call. PrefillPositions records the first call’s actual positions, and DecodePositions exists only for an executed second call. PromptIDs and logical ResultIDs describe token boundaries; ResultBytes and the reconstructed text describe the actual strict expansion.

A fixed-ID counterexample to retokenizing text

Set text ab, merges2 and externally select ID256, keeping all neural parameters at reset. The first learned rule combines a,b to256 and the second combines256,256 to257. The actual prompt is [256]. Appending256 gives [256,256] at positions0,1 and decoding these pieces gives abab.

Freshly tokenizing abab with two merges would instead give [257]. That is a different input list. Generation retains the actual piece boundaries; it does not decode characters and retokenize the entire result after each choice. Here prefill work is1 row and decode work2, with one novel ID. The reconstructed string alone cannot tell you that work count.

Both actual inputs gather (1/2,1/2). Each feature mean is1/2, centered features0, variance0 and normalization denominator1. Q/K/value features are0; each allowed score is0. Row0 attention is (1,0) and row1 attention (1/2,1/2); all mixed values remain0. Residuals preserve (1/2,1/2), the second normalization and FFN output0, and Y stays (1/2,1/2) at both positions.

With V=5, logits are (1/2,1/2,0,0,0). Put q=exp(−1/2). Shifted terms are (1,1,q,q,q) and the sequential denominator is ((((0+1)+1)+q)+q)+q. Equivalently, in exact real arithmetic Z=2exp(1/2)+3 and P=(exp(1/2),exp(1/2),1,1,1)/Z. The tied largest logits select a/97, the lowest compact class. Constant embeddings eliminate the normalized branches; they do not erase the residual input or create a cache.

EOS is an explicit terminal policy

Reset and select nextID=512. EOS means end of sequence. This walkthrough declares that selection terminal: logical ResultIDs becomes [97,98,512], strict decoding removes the terminal marker and reconstructs ab, stoppedEOS=1, newTokensConsumed=0, decodeWorkTokens=0 and decodeExecuted=0. Prefill still calculates its two rows.

No decode call occurs. There is no decode probability row, EOS embedding gather or zero-filled Decode tensor to inspect. The standalone forward kernel permits an active observed EOS as an input; this outer generation policy deliberately does not feed a stopping EOS to it. “Selected a terminal marker” and “consumed a new model input” are different events. All raw parameters, even the unused EOS embedding, must still be valid.

Bounds, edits and evidence

Prompt text is raw a/b only, at most6 UTF-8 bytes, with no trimming or normalization. Empty text is UNAVAILABLE. After actual BPE the prompt must have one or two IDs; a longer prompt is UNSUPPORTED_SIZE and is never cropped. Zero-merge aba therefore exceeds this lesson’s prompt limit despite fitting its byte bound. At two merges, ab fits as one token. Tokenization occurs once before the ID append; strict reverse decoding uses the actual learned rules afterward.

The wrapper checks exact own fields and string type, then every numeric parameter in declared order, then finite integer active membership of nextID, before text semantics. More than6 UTF-16 units is rejected first; unpaired surrogates cannot encode as valid UTF-8; actual byte length is checked before the a/b alphabet. These units happen to agree for ordinary a/b but are not interchangeable in general. The reused tokenizer’s inner bounds do not enlarge this lesson’s outer6-byte/two-prompt-ID limits.

With every E entry zero and all biases zero, both phases have Y=0, logits0 and P=1/V for every active class. That is a real uniform case. With valid unused parameter edits, raw parameter metadata changes while quantities with no dependency on those fields remain unchanged. Invalid unused values still invalidate the state. Neither a cache benefit nor training progress follows from these experiments.

Use the tensor inspector to distinguish stored parameters, prompt BPE evidence, actual Prefill tensors and, only when called, actual Decode tensors. Every view must explain saved calculation operands. Exact formulas above supply hand expectations; independent oracle, Python/TypeScript parity, browser interaction and accessibility checks provide separate evidence. Source inspection does not establish a runtime result.

Read the actual Python calculation and all its local dependencies

These nine disclosures are raw imports of the maintained source files, not rewritten demonstration snippets. Keep their relative directories intact. They require NumPy and Python’s standard library; displaying the files is not executing them or establishing parity with TypeScript. The entry point supports defaults, a complete replacement JSON state, and - for JSON on standard input. A partial state is not an edit patch.

1. Chapter wrapper — code/python/p11/iv44.py. Begin with derive_iv44 for the public derived record and command-line entry point. Follow how validated inputs become saved steps, tensors, text evidence and summary outputs. An unavailable input must return its reason rather than a stale successful answer.

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.

"""IV44 — Prefill and Single-Token Decode, full canonical chapter record.

Keep the disclosed nine-file p11/p10/p09/p06/p07 closure at its relative paths.
No args uses defaults; one complete JSON argument replaces all raw fields;
'-' reads that complete state from stdin. Every query returns the full record
or status/code/reason. All execution and declared checks remain DEFERRED.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType

_path = Path(__file__).resolve().with_name("inference_reference.py")
_spec = importlib.util.spec_from_file_location("_p11_inference_reference", _path)
if _spec is None or _spec.loader is None:
    raise ImportError(f"Cannot load canonical dependency: {_path}")
_helper = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_helper)
DEFAULT_IV44 = MappingProxyType(dict(_helper.DEFAULT_IV44))


@_helper.guarded
def derive_iv44(state):
    """Return all ordered outputs, steps, tensors/provenance and strict texts."""
    return _helper.prefill_and_decode(state)


def source_self_check():
    """DEFERRED wrapper-only checks; never invokes another file's self-check."""
    assert __debug__, "Deferred checks require assertions enabled."
    assert Path(_helper.__file__).resolve() == _path
    state = dict(DEFAULT_IV44)
    result = derive_iv44(state)
    assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
    summary = ["promptTokens", "newTokensConsumed", "prefillWorkTokens", "decodeWorkTokens", "nextID", "logicalResultTokenCount",
               "newPosition", "decodeExecuted", "stoppedEOS", "cacheUsed", "cacheEntries", "prefillScoreCells", "decodeScoreCells",
               "classCount", "actualMerges", "B", "D", "H", "Dk", "Dv", "hiddenWidth", "byteBound", "prefillNextRow",
               "prefillNextID", "prefillNextProbability", "decodeNextRow", "decodeNextID", "decodeNextProbability",
               "prefixYMaxDiff", "prefixLogitsMaxDiff", "prefixPMaxDiff", "resultByteCount"]
    tokenizer = ["corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"]
    flat = [f"{step['id']}_{key}" for step in result["steps"] for key in step["outputs"]]
    assert list(result["outputs"]) == summary + [f"tokenizer_{key}" for key in tokenizer] + flat
    assert [result["outputs"][key] for key in summary[:4]] == [2, 1, 2, 3]
    # Manual source counts:20 prompt +112 prefill +169 decode +6 compare +6 inverse +5 outer.
    assert len(result["steps"]) == 318 and len(result["tensors"]) == 146
    assert sum(step["id"].startswith("prefill_") for step in result["steps"]) == 112
    assert sum(step["id"].startswith("decode_") for step in result["steps"]) == 169
    assert all(list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"] for step in result["steps"])
    assert all(list(record) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"] for record in result["tensors"])
    tensors = {record["id"]: record for record in result["tensors"]}
    assert len(tensors) == 146
    assert tensors["PromptIDs"]["values"] == [97, 98] and tensors["ResultIDs"]["values"] == [97, 98, 97]
    assert result["texts"]["decoded"] == "aba"
    assert list(result["texts"]) == ["input", "decoded", "nextIDSource", "stopPolicy", "cachePolicy", "modelVocabulary",
                                     "tokenizer_corpus", "tokenizer_input", "tokenizer_corpusDecoded", "tokenizer_decoded",
                                     "tokenizer_corpusLabels", "tokenizer_corpusExpansions", "tokenizer_targetLabels",
                                     "tokenizer_targetExpansions", "tokenizer_ruleLabels", "tokenizer_ruleExpansions", "tokenizer_trainingStop"]
    assert sum(record["id"].startswith("Prefill") and record["id"] != "PrefillPositions" for record in result["tensors"]) == 57
    assert sum(record["id"].startswith("Decode") and record["id"] != "DecodePositions" for record in result["tensors"]) == 57
    assert all(type(value) is bool for value in tensors["PrefillAttentionallowed"]["values"])
    assert tensors["PrefillAttentionallowed"]["dtype"] == "bool" and tensors["PrefillAttentionallowed"]["precision"] == 8
    assert tensors["ResultIDs"]["dtype"] == "int32" and tensors["ResultIDs"]["precision"] == 0
    assert tensors["DecodeLogits"]["dtype"] == "float64" and tensors["DecodeLogits"]["precision"] == 8
    stopped = derive_iv44({**state, "nextID": 512})
    assert len(stopped["steps"]) == 142 and len(stopped["tensors"]) == 79
    assert [stopped["outputs"][key] for key in summary[:4]] == [2, 0, 2, 0]
    assert stopped["texts"]["decoded"] == "ab"
    assert "decodeNextID" not in stopped["outputs"] and "prefixPMaxDiff" not in stopped["outputs"]
    assert not any(record["id"].startswith(("Decode", "Prefix")) for record in stopped["tensors"])
    for raw in ({}, {**state, "extra": 0}, [], None):
        fault = derive_iv44(raw)
        assert list(fault) == ["status", "code", "reason"] and fault["code"] == "INVALID_INPUT"
    result["tensors"][0]["values"].clear()
    result["steps"][0]["outputs"].clear()
    result["texts"]["modelVocabulary"].clear()
    repeated = derive_iv44(state)
    assert repeated["tensors"][0]["values"] and repeated["steps"][0]["outputs"]
    assert len(repeated["texts"]["modelVocabulary"]) == 5 and state == dict(DEFAULT_IV44)


if __name__ == "__main__":
    _helper.run(derive_iv44, DEFAULT_IV44)

2. Inference mechanics — code/python/p11/inference_reference.py. inference_state validates the complete raw state. prompt_bpe obtains actual prompt IDs, _tokenizer_rules reconstructs the actual learned-rule data, and prefill_and_decode calls the existing numerical forward on those IDs. _compare_prefix saves both old and new operands and computes differences; it does not assume equality. Follow the explicit stopped-EOS branch to see why decode evidence is absent, then follow strict reverse decoding of the logical result IDs.

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.

"""IV44 canonical NumPy mechanics, source-authored under the resource hold.

Reuse the actual IV39 tokenizer and IV43 observed-ID forward, without any
objective/gradient call. One externally supplied ID is appended without
retokenization. EOS is a logical stop; otherwise recompute the entire prefix.
The full chapter record follows the owner-adopted ordered A inventory.
All execution and self-checks remain DEFERRED.
"""
import importlib.util
import json
from pathlib import Path
from types import MappingProxyType
from functools import wraps
import numpy as np

_ROOT = Path(__file__).resolve().parent.parent


def _load(name, path):
    """Load exactly the disclosed file, independently of cwd and sys.path."""
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load canonical dependency: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


_tiny = _load("_iv44_tiny_reference", _ROOT / "p10" / "tiny_reference.py")
_iv39 = _load("_iv44_iv39", _ROOT / "p09" / "iv39.py")
_bpe = _iv39._bpe
_token = _bpe._token
NumericalFault = _tiny.NumericalFault
# IV39 and tiny load distinct instances of the same readonly codec source.
_DEPENDENCY_FAULTS = (*_tiny._DEPENDENCY_FAULTS, _bpe.NumericalFault)
ALL_IDS = _tiny.ALL_IDS
NUMERIC_DEFAULTS = _tiny.NUMERIC_DEFAULTS
DEFAULT_IV44 = MappingProxyType(dict(text="ab", **NUMERIC_DEFAULTS, nextID=97))


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except _DEPENDENCY_FAULTS 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


def inference_state(state):
    """Exact own fields; string type, all26 numeric fields, then nextID."""
    _tiny._object(state, DEFAULT_IV44, "state")
    if type(state["text"]) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
    numeric = _tiny.numeric_parameters({key: state[key] for key in NUMERIC_DEFAULTS})
    next_id = _tiny.finite(state["nextID"], "nextID")
    if not next_id.is_integer() or next_id not in ALL_IDS[:3 + numeric["merges"]]:
        raise NumericalFault("INVALID_INPUT", "nextID must be an active public model ID.")
    return dict(text=state["text"], numeric=numeric, nextID=int(next_id))


def prompt_bpe(text, merges):
    """Validate the outer boundary, then tokenize ONCE using actual IV39.

    No native codec or guessed segmentation supplies the answer. The precheck
    uses the existing manual encoder solely for strict Unicode/byte validation;
    IV39 alone supplies the saved tokenization and every displayed BPE record.
    """
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
    merges = _tiny.finite(merges, "merges")
    if not merges.is_integer() or not 0 <= merges <= 2:
        raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
    merges = int(merges)
    if _token.utf16_length(text) > 6:
        raise NumericalFault("UNSUPPORTED_SIZE", "text: more than 6 UTF-16 units exceeds the 6-byte input bound.")
    encoded = _token.utf8_encode(text)
    if len(encoded["bytes"]) > 6:
        raise NumericalFault("UNSUPPORTED_SIZE", "text: the actual UTF-8 encoding exceeds 6 bytes.")
    if any(character not in "ab" for character in text):
        raise NumericalFault("UNAVAILABLE", "This toy model supports only raw a and b letters, without normalization or truncation.")
    if not text:
        raise NumericalFault("UNAVAILABLE", "Empty text has no observed prompt token.")
    result = _iv39.derive_iv39(dict(corpus="abab", text=text, merges=merges, eos=0))
    if result["status"] != "defined":
        raise NumericalFault(result["code"], result["reason"])
    ids = np.array(next(t["values"] for t in result["tensors"] if t["id"] == "TargetIDs"), dtype=np.int32)
    if len(ids) > 2:
        raise NumericalFault("UNSUPPORTED_SIZE", "The actual BPE prompt exceeds 2 tokens; change text or merges explicitly.")
    return result, ids


def _tokenizer_rules(tokenized):
    """Rebuild only actual saved IV39 rules, including their actual byte arrays."""
    tensors = {record["id"]: record for record in tokenized["tensors"]}
    if "RuleIDs" not in tensors:
        return []
    ids = tensors["RuleIDs"]["values"]
    left, right = tensors["RuleLeft"]["values"], tensors["RuleRight"]["values"]
    rules = [dict(id=identifier, left=left[rank], right=right[rank],
                  bytes=np.array(tensors[f"Rule{identifier}Bytes"]["values"], dtype=np.int32))
             for rank, identifier in enumerate(ids)]
    _bpe.rule_table(rules)
    return rules


def _tensor_values(forward, identifier):
    return next(record["values"] for record in forward["tensors"] if record["id"] == identifier)


def _compare_prefix(prefill, decode, trace, tensors):
    """Save complete prior-row operands and computed differences in family order."""
    N, V = prefill["T"], prefill["V"]
    if decode["T"] != N + 1 or decode["V"] != V or decode["inputIDs"][:N] != prefill["inputIDs"]:
        raise NumericalFault("SHAPE_MISMATCH", "Prefix comparison requires the same model classes and an extended observed prefix.")
    maxima = {}
    for identifier, width in (("Y", 2), ("Logits", V), ("P", V)):
        before = np.array(_tensor_values(prefill, identifier), dtype=np.float64).reshape(N, width)
        after = np.array(_tensor_values(decode, identifier), dtype=np.float64).reshape(N + 1, width)[:N].copy()
        differences = np.empty((N, width), dtype=np.float64)
        maximum = 0.0
        for t in range(N):
            inputs, outputs = dict(t=t), {}
            for c in range(width):
                previous, current = float(before[t, c]), float(after[t, c])
                inputs[f"before{c}"], inputs[f"after{c}"] = previous, current
                difference = _tiny.finite(abs(_tiny.finite(current - previous, "prefix subtraction")), "prefix absolute difference")
                differences[t, c] = difference
                outputs[f"difference{c}"] = difference
                maximum = max(maximum, difference)
                outputs[f"runningMax{c}"] = maximum
            outputs["maxDifference"] = maximum
            trace.add(f"compare_{identifier}_{t}", f"Compare saved prior {identifier} row {t}",
                      "difference_c=abs(after_c-before_c); runningMax=max(previous,difference_c)",
                      "Both operands come from actual saved calls with identical prior IDs, parameters and absolute positions. Differences are computed, never forced to zero. Signed zeros compare equivalently; future masked raw scores need not match.",
                      inputs, outputs)
        maxima[f"prefix{identifier}MaxDiff"] = maximum
        axes = ["PriorPosition", "D" if identifier == "Y" else "Class"]
        tensors.extend([
            _tiny._float_tensor(f"Prefix{identifier}Before", [N, width], axes, before,
                                "Actual complete prefill rows copied from the saved forward tensor."),
            _tiny._float_tensor(f"Prefix{identifier}After", [N, width], axes, after,
                                "Actual first N rows copied from the extended-prefix forward tensor."),
            _tiny._float_tensor(f"Prefix{identifier}AbsDiff", [N, width], axes, differences,
                                "Computed abs(after-before) for every prior-row coordinate; no synthetic zero fill."),
        ])
    return maxima


def prefill_and_decode(state):
    """Full ordered IV44 record: actual BPE, uncached forwards and strict inverse.

    IDs/positions/bytes use real int32 arrays; comparisons and the reused neural
    arithmetic use float64 arrays. Returned JSON data is detached from all state.
    EOS contributes logical control only, with no second forward or comparison.
    """
    s = inference_state(state)
    numeric, next_id = s["numeric"], s["nextID"]
    prompt, prompt_ids = prompt_bpe(s["text"], numeric["merges"])
    N, V = len(prompt_ids), 3 + numeric["merges"]
    stopped = int(next_id == 512)
    result_ids = np.concatenate((prompt_ids, np.array([next_id], dtype=np.int32)))
    trace = _tiny.tiny_trace()
    trace.add("setup", "Validate the complete input before interpreting prompt text", "outer bytes<=6; actual prompt tokens N in {1,2}; nextID is externally supplied",
              "All raw fields validate, including inactive and EOS parameters. The prompt is tokenized once with EOS off. No probability of the external choice is asserted.",
              {**numeric, "nextID": next_id}, dict(utf16Units=_token.utf16_length(s["text"]), byteBound=6, promptTokenBound=2))
    for step in prompt["steps"]:
        trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
    trace.add("class_map", "Keep public token IDs distinct from model storage rows", "V=3+merges; active classIDs=prefix([97,98,512,256,257],V)",
              "The same real learned rules supply the prompt and final reverse decoder. Public ID512 does not allocate 513 embeddings.",
              dict(actualMerges=prompt["outputs"]["actualMerges"], vocabularyItems=prompt["outputs"]["vocabularyItems"]), dict(classCount=V))
    tensors = [{**record, "id": f"Tokenizer{record['id']}", "provenance": f"Prompt BPE with EOS off. {record['provenance']}"}
               for record in prompt["tensors"]]

    def call(phase, ids):
        saved = _tiny.tiny_trace()
        forward = _tiny.forward_tiny(numeric, ids, saved)
        for step in saved.steps:
            trace.add(f"{phase.lower()}_{step['id']}", f"{phase}: {step['label']}", step["equation"],
                      f"{phase} uncached inference call. Reused generic forward arithmetic; no target, loss, gradient or cache operation is called here. Kernel explanation: {step['explanation']}",
                      step["inputs"], step["outputs"])
        tensors.extend({**record, "id": f"{phase}{record['id']}",
                        "provenance": f"{phase} full-prefix inference, absolute positions 0..{len(ids) - 1}; inherited kernel provenance: {record['provenance']}"}
                       for record in forward["tensors"])
        return forward

    prefill = call("Prefill", prompt_ids)
    before = prefill["rows"][N - 1]
    trace.add("append", "Append exactly the externally selected public ID", "ResultIDs=PromptIDs followed by nextID; logicalResultTokenCount=N+1",
              "Appending a piece preserves the ID stream even if retokenizing its decoded characters would merge across this boundary.",
              dict(promptTokens=N, nextID=next_id), dict(logicalResultTokenCount=len(result_ids)))
    decode_executed = 1 - stopped
    decode_work = 0 if stopped else N + 1
    trace.add("stop_decision", "Apply the declared terminal EOS policy", "nextID=512 => stop; otherwise recompute the full extended prefix",
              "A stopping EOS enters the logical result only. It triggers no second neural call or EOS embedding gather. A non-EOS call consumes one novel ID but recomputes N+1 rows; no K/V cache is implemented.",
              dict(nextID=next_id, EOS=512, promptTokens=N),
              dict(stoppedEOS=stopped, decodeExecuted=decode_executed, newTokensConsumed=decode_executed,
                   decodeWorkTokens=decode_work, newPosition=N, cacheUsed=0, cacheEntries=0))
    prediction, comparisons = {}, {}
    if not stopped:
        decode = call("Decode", result_ids)
        last = decode["rows"][N]
        prediction = dict(decodeNextRow=last["nextRow"], decodeNextID=last["nextID"], decodeNextProbability=last["nextProbability"])
        comparisons = _compare_prefix(prefill, decode, trace, tensors)
        tensors.append(_token.tensor("DecodePositions", "Position", np.arange(N + 1, dtype=np.int32),
                                     "Actual absolute positions consumed by the uncached extended-prefix call."))
    reverse = _token.TokenTrace()
    reconstructed = _bpe.decode_bpe_ids(result_ids, _tokenizer_rules(prompt), stopped, "result", reverse)
    result_bytes = reconstructed["bytes"]
    if len(result_bytes) > 10:
        raise NumericalFault("UNSUPPORTED_SIZE", "Result expansions exceed the declared 10-byte bound.")
    for step in reverse.steps:
        trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
    tensors.extend([
        _token.tensor("PromptIDs", "PromptPosition", prompt_ids, "Actual EOS-off BPE prompt, tokenized once."),
        _token.tensor("ResultIDs", "LogicalPosition", result_ids, "Prompt IDs plus exactly the externally supplied ID; a final EOS is logical control only."),
        _token.tensor("PrefillPositions", "Position", np.arange(N, dtype=np.int32), "Actual absolute positions processed by prefill."),
        _token.tensor("ResultBytes", "Bytes", result_bytes, "Actual strict reverse-decoder expansion bytes; a stopping EOS emits none."),
    ])
    trace.add("finish", "Keep novel input, total work and actual reconstruction distinct", "prefillWorkTokens=N; decodeWorkTokens=stoppedEOS?0:N+1; newTokensConsumed=stoppedEOS?0:1",
              "This is a bounded uncached inference walkthrough with hand-set parameters. All probabilities belong to actual model calls; the supplied nextID is not claimed as a model prediction.",
              dict(promptTokens=N, nextID=next_id, stoppedEOS=stopped),
              dict(promptTokens=N, newTokensConsumed=decode_executed, prefillWorkTokens=N, decodeWorkTokens=decode_work, resultByteCount=len(result_bytes)))
    summary = dict(promptTokens=N, newTokensConsumed=decode_executed, prefillWorkTokens=N, decodeWorkTokens=decode_work,
                   nextID=next_id, logicalResultTokenCount=len(result_ids), newPosition=N, decodeExecuted=decode_executed,
                   stoppedEOS=stopped, cacheUsed=0, cacheEntries=0, prefillScoreCells=N * N,
                   decodeScoreCells=0 if stopped else (N + 1) * (N + 1), classCount=V, actualMerges=numeric["merges"],
                   B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6,
                   prefillNextRow=before["nextRow"], prefillNextID=before["nextID"], prefillNextProbability=before["nextProbability"],
                   **prediction, **comparisons, resultByteCount=len(result_bytes))
    tokenizer_names = ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens",
                       "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal")
    summary.update({f"tokenizer_{key}": prompt["outputs"][key] for key in tokenizer_names})
    result = trace.result(summary, tensors)
    result["texts"] = dict(input=s["text"], decoded=reconstructed["decoded"],
                           nextIDSource="Externally selected observed/chosen ID; not asserted to be the model prediction.",
                           stopPolicy="EOS512 is a terminal logical marker: no second forward call and no EOS embedding gather.",
                           cachePolicy="No K/V reuse; a non-EOS call recomputes all N+1 rows at absolute positions 0..N.",
                           modelVocabulary=["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256 (merges>=1)", "4: abab / ID257 (merges=2)"],
                           **{f"tokenizer_{key}": value for key, value in prompt["texts"].items()})
    return json.loads(json.dumps(result, allow_nan=False, ensure_ascii=False))


def source_self_check():
    """DEFERRED helper assertions; does NOT call any other file's self-check."""
    assert __debug__, "Deferred checks require assertions enabled."
    assert Path(_tiny.__file__).resolve() == _ROOT / "p10" / "tiny_reference.py"
    assert Path(_iv39.__file__).resolve() == _ROOT / "p09" / "iv39.py"
    assert Path(_bpe.__file__).resolve() == _ROOT / "p09" / "bpe_reference.py"
    assert Path(_token.__file__).resolve() == _ROOT / "p09" / "token_reference.py"
    assert _tiny._ffn.NumericalFault is _tiny._component.NumericalFault
    assert _tiny._ffn.tensor is _tiny._component.tensor
    assert list(DEFAULT_IV44) == ["text", *NUMERIC_DEFAULTS, "nextID"] and len(DEFAULT_IV44) == 28
    state = dict(DEFAULT_IV44)
    result = prefill_and_decode(state)
    tensors = {record["id"]: record for record in result["tensors"]}
    assert tensors["PromptIDs"]["values"] == [97, 98] and tensors["ResultIDs"]["values"] == [97, 98, 97]
    assert result["texts"]["decoded"] == "aba" and tensors["ResultBytes"]["values"] == [97, 98, 97]
    assert tensors["PrefillPositions"]["values"] == [0, 1] and tensors["DecodePositions"]["values"] == [0, 1, 2]
    assert result["outputs"]["prefillNextID"] == 98 and result["outputs"]["decodeNextID"] == 97
    for identifier in ("Y", "Logits", "P"):
        assert result["outputs"][f"prefix{identifier}MaxDiff"] == 0
        assert all(value == 0 for value in tensors[f"Prefix{identifier}AbsDiff"]["values"])
        assert tensors[f"Prefix{identifier}Before"]["values"] == tensors[f"Prefix{identifier}After"]["values"]
    stopped = prefill_and_decode({**state, "nextID": 512})
    assert stopped["texts"]["decoded"] == "ab"
    assert stopped["outputs"]["newTokensConsumed"] == stopped["outputs"]["decodeWorkTokens"] == 0
    assert not any(record["id"].startswith(("Decode", "Prefix")) for record in stopped["tensors"])
    assert not any(step["id"].startswith(("decode_", "compare_")) for step in stopped["steps"])
    fixed = prefill_and_decode({**state, "merges": 2, "nextID": 256})
    fixed_tensors = {record["id"]: record for record in fixed["tensors"]}
    assert fixed_tensors["PromptIDs"]["values"] == [256] and fixed_tensors["ResultIDs"]["values"] == [256, 256]
    assert fixed["texts"]["decoded"] == "abab"
    # Retokenizing is shown only as a counterexample in this explicit future check.
    fresh, ids = prompt_bpe("abab", 2)
    assert ids.dtype == np.dtype(np.int32) and ids.tolist() == [257]
    assert fresh["texts"]["decoded"] == fixed["texts"]["decoded"]
    for patch, code in (({"text": ""}, "UNAVAILABLE"), ({"text": "c"}, "UNAVAILABLE"),
                        ({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "\ud800"}, "INVALID_INPUT"),
                        ({"text": "ababab"}, "UNSUPPORTED_SIZE"), ({"text": "🦊🦊"}, "UNSUPPORTED_SIZE"),
                        ({"nextID": 256}, "INVALID_INPUT"), ({"nextID": True}, "NONFINITE"),
                        ({"text": "\ud800", "nextID": float("inf")}, "NONFINITE"),
                        ({"text": [], "merges": float("nan")}, "INVALID_INPUT"),
                        ({"nextID": 512, "e40": 3}, "INVALID_INPUT"),
                        ({"nextID": 512, "b4": float("nan")}, "NONFINITE")):
        fault = guarded(prefill_and_decode)({**state, **patch})
        assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
    for text, merges, code in (("ab", 3, "INVALID_INPUT"), ("ab", 4, "INVALID_INPUT"),
                               ("\ud800", float("nan"), "NONFINITE"),
                               ("a" * 7, float("nan"), "NONFINITE"),
                               ([], float("nan"), "INVALID_INPUT")):
        try:
            prompt_bpe(text, merges)
        except _DEPENDENCY_FAULTS as error:
            assert error.code == code
        else:
            raise AssertionError("Invalid prompt helper boundary was accepted")
    class Hostile(dict):
        def __getitem__(self, key):
            raise AssertionError("Custom indexing must not be read")
    assert guarded(prefill_and_decode)(Hostile(state))["code"] == "INVALID_INPUT"
    result["tensors"][0]["values"][0] = -1
    result["steps"][0]["outputs"].clear()
    result["texts"]["modelVocabulary"].clear()
    repeated = prefill_and_decode(state)
    assert repeated["tensors"][0]["values"][0] != -1 and repeated["steps"][0]["outputs"]
    assert len(repeated["texts"]["modelVocabulary"]) == 5 and state == dict(DEFAULT_IV44)


def run(derive, defaults):
    """Default / full replacement JSON argument / '-' stdin; no self-check call."""
    _tiny.run(derive, defaults)

3. Same tiny decoder — code/python/p10/tiny_reference.py. forward_tiny gathers E, normalizes features, projects Q/K/value, rotates Q/K at absolute positions, performs causal attention, adds residuals, applies the second normalization and FFN, and computes logits and class probabilities. This file also contains IV-43 objective functions, but inference calls the ID-based forward directly; it does not call that objective, its targets or its derivatives. Find _rope, _attention, _norm, _residual and _class_row to connect the hand derivation to saved products and running sums. NumPy float64 arrays hold the neural arithmetic; ordinary detached containers carry the public evidence.

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.

"""IV43 tiny decoder: actual NumPy arrays and scalar-ordered arithmetic.

Text -> learned BPE -> E gather -> LN1 -> Q/K/V -> Q/K RoPE -> causal
attention -> identity WO -> residual -> LN2 -> M3 ReLU FFN -> residual
-> U/bias logits -> stable conditional objective and readout derivatives.
The first token is given. No optimizer, embedding/full-block gradient,
pretrained model or trained capability is supplied. All execution DEFERRED.

Keep the original p06, p07 and p09 files at their relative locations. The
chapter displays this exact dependency closure, rather than a rewritten demo.
"""
import argparse
from functools import wraps
import importlib.util
import json
import math
from pathlib import Path
import sys
from types import MappingProxyType
import numpy as np


_ROOT = Path(__file__).resolve().parent.parent


def _load(name, path):
    """Resolve an explicit source file; never search cwd or sys.path for helpers."""
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load canonical dependency: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


_component = _load("_iv43_component_reference", _ROOT / "p07" / "component_reference.py")
# The unchanged FFN imports this bare name. Force OUR canonical dependency,
# even when an unrelated module already occupies the name, then restore it.
_missing = object()
_previous_component = sys.modules.get("component_reference", _missing)
sys.modules["component_reference"] = _component
try:
    _ffn = _load("_iv43_ffn_reference", _ROOT / "p07" / "ffn_reference.py")
finally:
    if _previous_component is _missing:
        del sys.modules["component_reference"]
    else:
        sys.modules["component_reference"] = _previous_component
del _previous_component, _missing
_head = _load("_iv43_head_reference", _ROOT / "p06" / "head_reference.py")
_bpe = _load("_iv43_bpe_reference", _ROOT / "p09" / "bpe_reference.py")
_token = _bpe._token  # BPE itself loads this exact adjacent token file.
NumericalFault = _component.NumericalFault
_DEPENDENCY_FAULTS = (NumericalFault, _head.NumericalFault, _bpe.NumericalFault, _ffn.NumericalFault)

ALL_IDS = (97, 98, 512, 256, 257)
PARAMETER_DEFAULTS = MappingProxyType(dict(
    e00=1, e01=0, e10=0, e11=1, e20=0, e21=0, e30=0.5, e31=0.5, e40=1, e41=1,
    u00=1, u01=0, u02=0, u03=0, u04=0, u10=0, u11=1, u12=0, u13=0, u14=0,
    b0=0, b1=0, b2=0, b3=0, b4=0,
))
NUMERIC_DEFAULTS = MappingProxyType(dict(merges=0, **PARAMETER_DEFAULTS))
DEFAULT_IV43 = MappingProxyType(dict(text="ab", **NUMERIC_DEFAULTS))


def finite(value, label):
    """Own numbers only: booleans, coercion and overflowing integers are faults."""
    if type(value) not in (int, float):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def _object(value, fields, label):
    # Exact dict rejects inherited/overridden indexing without invoking a getter.
    if type(value) is not dict:
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named data fields.")
    if any(type(key) is not str for key in value) or set(value) != set(fields):
        raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive parameters.")


def numeric_parameters(state):
    """Check all26 numeric fields, including unused rows/columns, in raw order."""
    _object(state, NUMERIC_DEFAULTS, "numeric parameters")
    checked = {}
    for key in NUMERIC_DEFAULTS:
        value = finite(state[key], key)
        low, high = (0, 2) if key == "merges" else (-4, 4) if key.startswith("b") else (-2, 2)
        if key == "merges" and (not value.is_integer() or not low <= value <= high):
            raise NumericalFault("INVALID_INPUT", "merges must be an integer from 0 to 2.")
        if not low <= value <= high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        checked[key] = int(value) if key == "merges" else value
    return checked


def tiny_state(state):
    """String type first, then EVERY numeric field, then text semantics later."""
    _object(state, DEFAULT_IV43, "state")
    if type(state["text"]) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
    return dict(text=state["text"], numeric=numeric_parameters({key: state[key] for key in NUMERIC_DEFAULTS}))


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except _DEPENDENCY_FAULTS 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


def _ids(values, active):
    """Validate original public IDs before narrowing to real int32 storage."""
    if type(values) is np.ndarray:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", "inputIDs must be a dense one-dimensional numeric array.")
        entries = values.tolist()
    elif type(values) in (list, tuple):
        entries = values
    else:
        raise NumericalFault("INVALID_INPUT", "inputIDs must be an actual dense array.")
    if len(entries) > 3:
        raise NumericalFault("UNSUPPORTED_SIZE", "Numeric inputIDs must contain at most 3 observed tokens.")
    if not entries:
        raise NumericalFault("UNAVAILABLE", "Numeric forward requires at least one observed input token.")
    result = []
    for t, value in enumerate(entries):
        if type(value) not in (int, float):
            raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
        try:
            value = float(value)
        except (ValueError, OverflowError) as error:
            raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.") from error
        if not math.isfinite(value) or not value.is_integer() or value not in active:
            raise NumericalFault("INVALID_INPUT", f"inputIDs[{t}] must be an active public model ID.")
        result.append(int(value))
    return np.array(result, dtype=np.int32)


def _float_tensor(identifier, shape, axes, values, provenance):
    """Serialize an actual float64 array into detached row-major JSON storage."""
    if type(values) is not np.ndarray or values.dtype != np.dtype(np.float64) or tuple(shape) != values.shape:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64 storage of the declared shape.")
    return _component.tensor(identifier, shape, axes, values.reshape(-1).tolist(), provenance)


def _norm(name, x, trace):
    """Keep normalization statistics in real scalar steps, without extra tensors."""
    T = x["shape"][1]
    X = np.array(x["values"], dtype=np.float64).reshape(1, T, 2)
    output = np.empty((1, T, 2), dtype=np.float64)
    for t in range(T):
        row = _component.feature_norm("layer", f"{name.lower()}_{t}", X[0, t].tolist(),
                                      [1, 1], [0, 0], 1, trace)
        output[0, t] = row["values"]
    source = "X" if name == "LN1" else "R1"
    return _float_tensor(name, [1, T, 2], ["B", "T", "D"], output,
                         f"Per-token feature layer norm of {source}; population variance, gamma=(1,1), beta=(0,0), epsilon=1 inside sqrt.")


def _residual(name, prefix, left, right, trace):
    result = _component.same_shape_add(name, left, right)
    for t in range(result["shape"][1]):
        for d in range(2):
            index = 2 * t + d
            trace.add(f"{prefix}_{t}_{d}", f"{name} residual [0,{t},{d}]", "value=left+right",
                      "Actual same-shape addition; no broadcasting or second numerical engine.",
                      dict(t=t, d=d, left=left["values"][index], right=right["values"][index]),
                      dict(value=result["values"][index]))
    return result


def _rope(role, values, trace):
    """One adjacent Q/K pair, frequency1, angle=absolute token position radians."""
    T = values.shape[2]
    rotated = np.empty((1, 1, T, 2), dtype=np.float64)
    angles, cosines, sines = (np.empty(T, dtype=np.float64) for _ in range(3))
    for t in range(T):
        frequency = 10000 ** 0
        angle = finite(t * frequency, "RoPE angle")
        cosine, sine = finite(math.cos(angle), "RoPE cosine"), finite(math.sin(angle), "RoPE sine")
        x0, x1 = float(values[0, 0, t, 0]), float(values[0, 0, t, 1])
        product0, product1 = finite(x0 * cosine, "RoPE x0*cos"), finite(x1 * sine, "RoPE x1*sin")
        product2, product3 = finite(x0 * sine, "RoPE x0*sin"), finite(x1 * cosine, "RoPE x1*cos")
        rotated0, rotated1 = finite(product0 - product1, "RoPE first coordinate"), finite(product2 + product3, "RoPE second coordinate")
        rotated[0, 0, t] = [rotated0, rotated1]
        angles[t], cosines[t], sines[t] = angle, cosine, sine
        trace.add(f"rope_{role}_{t}", f"RoPE {role} token {t}",
                  "frequency=10000^0; angle=t*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
                  "Rotate this single adjacent pair at absolute position t. Q and K rotate; V remains unrotated. Every product is saved.",
                  dict(t=t, x0=x0, x1=x1, base=10000, exponent=0),
                  dict(frequency=frequency, angle=angle, cos=cosine, sin=sine, product0=product0, product1=product1,
                       product2=product2, product3=product3, rotated0=rotated0, rotated1=rotated1))
    return rotated, angles, cosines, sines


# Literal metadata adoption is local: unchanged helpers still supply all storage and steps.
_PROJECTION_PROVENANCE = {
    "X": "Active token rows; D=2 input features always retained.",
    "WQ": "Query columns packed by h*Dk+f from wq{d}{h}{f}.",
    "WK": "Key columns packed by h*Dk+f from wk{d}{h}{f}.",
    "WV": "Value columns packed by h*Dv+f from wv{d}{h}{f}.",
    "QConcat": "XWQ; each packed coordinate has two products and one sum.",
    "KConcat": "XWK; each packed coordinate has two products and one sum.",
    "VConcat": "XWV; values are projected separately from queries and keys.",
    "QSplit": "QConcat reshaped without changing flat order; feature=h*F+f.",
    "QHeads": "QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
    "KSplit": "KConcat reshaped without changing flat order; feature=h*F+f.",
    "KHeads": "KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
    "VSplit": "VConcat reshaped without changing flat order; feature=h*F+f.",
    "VHeads": "VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.",
}
_ATTENTION_PROVENANCE = {
    "raw": "Separate QHeads KHeads transpose products within every batch and head.",
    "scores": "raw/sqrt(Dk); the two-product order matches IV25 for H1,Dk2.",
    "allowed": "Causal and/or valid-key mask; shared validity across B and H; every query retained.",
    "logits": "Finite score+shift, including forbidden cells; mask applied separately.",
    "probabilities": "Stable allowed-key softmax for each B/H/query independently; forbidden probabilities exactly zero.",
    "OHeads": "Actual per-head P times VHeads; every product and running sum is traced.",
}
_JOIN_PROVENANCE = {
    "C": "OHeads permuted to token-major order then joined by c=h*Dv+f; values unchanged.",
    "WO": "wo{h}{f}{d} packed in h,f,d order, preserving parameter identity.",
    "Y": "Y=C WO, summing products in ascending joined-feature order from zero; no normalization.",
}
_FFN_PROVENANCE = {
    "W1": "Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.",
    "b1": "Shared hidden bias, added after the two products.",
    "Z": "Hidden preactivations X W1+b1; no batch or token mixing.",
    "Hidden": "ReLU(Z)=max(0,Z), before the second affine layer.",
    "W2": "Shared hidden-to-output weights, f2{m}{d}.",
    "b2": "Shared output bias, added after all three running sums.",
    "F": "ReLU(X W1+b1) W2+b2, independently per token with shared parameters.",
}


def _attention(n1, trace):
    """Reuse project/attend/join kernels; explicitly override their old WO."""
    T = n1["shape"][1]
    s = dict(_head.OUTPUT_HEAD_DEFAULTS)
    s.update(B=1, T=T, H=1, Dk=2, Dv=2, mode=1, shift=0)
    for t in range(T):
        for d in range(2):
            s[f"x0{t}{d}"] = n1["values"][2 * t + d]
    for prefix in ("wq", "wk", "wv"):
        for d in range(2):
            for f in range(2):
                s[f"{prefix}{d}0{f}"] = int(d == f)
    for f in range(2):
        for d in range(2):
            s[f"wo0{f}{d}"] = int(f == d)
    child = _head.head_trace()
    try:
        projected = _head.project_heads(s, child)
        for step in child.steps:
            trace.add(f"heads_{step['id']}", step["label"], step["equation"],
                      step["explanation"], step["inputs"], step["outputs"])
        q, angles, cosines, sines = _rope("Q", projected["QHeads"], trace)
        k, _, _, _ = _rope("K", projected["KHeads"], trace)
        rotated = {**projected, "QHeads": q, "KHeads": k}
        child = _head.head_trace()
        attended = _head.attend_heads(s, rotated, child)
        joined = _head.join_heads(s, attended, child)
    except _head.NumericalFault as error:
        raise NumericalFault(error.code, str(error)) from error
    for step in child.steps:
        trace.add(f"heads_{step['id']}", step["label"], step["equation"],
                  step["explanation"], step["inputs"], step["outputs"])
    tensors = [{**record, "id": f"Projection{record['id']}",
                "provenance": _PROJECTION_PROVENANCE[record["id"]] + " Source is LN1; ProjectionQHeads and ProjectionKHeads are unrotated."}
               for record in projected["tensors"]]
    tensors.extend([
        _float_tensor("RotatedQHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], q,
                      "Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately."),
        _float_tensor("RotatedKHeads", [1, 1, T, 2], ["B", "H", "T", "Dk"], k,
                      "Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately."),
        _float_tensor("RoPEAngles", [T], ["Position"], angles, "Absolute position t times the single-pair frequency1, in radians."),
        _float_tensor("RoPECos", [T], ["Position"], cosines, "Stored cos(angle) used in the Q pair rotation; K uses the same angle."),
        _float_tensor("RoPESin", [T], ["Position"], sines, "Stored sin(angle) used in the Q pair rotation; K uses the same angle."),
    ])
    tensors.extend({**record, "id": f"Attention{record['id']}",
                    "provenance": _ATTENTION_PROVENANCE[record["id"]] + " QHeads=RotatedQHeads; KHeads=RotatedKHeads; VHeads=ProjectionVHeads."}
                   for record in attended["tensors"])
    tensors.extend({**record, "id": "AttentionOutput" if record["id"] == "Y" else f"Attention{record['id']}",
                    "provenance": _JOIN_PROVENANCE[record["id"]] + " Source is AttentionOHeads; active WO is explicitly identity2."}
                   for record in joined["tensors"])
    return tensors[-1], tensors


def tiny_trace():
    """An explicit finite scalar accumulator; forward_tiny never discards one."""
    return _component.component_trace()


def forward_tiny(numeric_state, input_ids, trace):
    """Observed-ID forward with the adopted T,V,classIDs,inputIDs,inputRows,rows,tensors.

    Validate26 parameters first, then dense active public IDs, including EOS.
    Real float64/int32/bool arrays back the computation; the public return is a
    detached JSON snapshot with complete stable distributions, without targets.
    """
    s = numeric_parameters(numeric_state)
    V = 3 + s["merges"]
    ids = _ids(input_ids, ALL_IDS[:V])
    T = len(ids)
    class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
    input_rows = np.array([ALL_IDS.index(int(identifier)) for identifier in ids], dtype=np.int32)
    E = np.array([[s[f"e{r}{d}"] for d in range(2)] for r in range(5)], dtype=np.float64)
    U = np.array([[s[f"u{d}{c}"] for c in range(5)] for d in range(2)], dtype=np.float64)
    bias = np.array([s[f"b{c}"] for c in range(5)], dtype=np.float64)
    X = np.empty((1, T, 2), dtype=np.float64)
    for t, identifier in enumerate(ids):
        row = int(input_rows[t])
        X[0, t] = E[row]
        trace.add(f"input_{t}", f"Gather embedding for observed token {t}", "inputRow=compactRow(inputID); X[0,t,d]=E[inputRow,d]",
                  "The full model has an ordinary EOS embedding row. This kernel does not stop on EOS.",
                  dict(t=t, inputID=int(identifier)), dict(inputRow=row, x0=float(X[0, t, 0]), x1=float(X[0, t, 1])))
    tensors = [
        _token.tensor("AllClassIDs", "ModelRow", np.array(ALL_IDS, dtype=np.int32), "Full compact model row map: a,b,EOS,ab,abab; public IDs are not storage offsets."),
        _token.tensor("ClassIDs", "Class", class_ids, "Active prefix of the full model row map; V=3+merges."),
        _float_tensor("E", [5, 2], ["ModelRow", "D"], E, "All ten validated editable embeddings, including EOS and inactive learned pieces."),
        _float_tensor("U", [2, 5], ["D", "ModelRow"], U, "All ten validated editable readout weights; only the first V columns contribute logits."),
        _float_tensor("Bias", [5], ["ModelRow"], bias, "All five validated editable biases; inactive columns have no objective dependency."),
        _token.tensor("InputIDs", "Position", ids, "Observed public IDs supplied directly to the numeric kernel; active EOS is permitted."),
        _token.tensor("InputRows", "Position", input_rows, "Compact model row gathered for each observed ID; never index by public ID512."),
        _float_tensor("X", [1, T, 2], ["B", "T", "D"], X, "Actual gathered E rows; B=1, token-major storage and D=2."),
    ]
    n1 = _norm("LN1", tensors[-1], trace)
    attention, at = _attention(n1, trace)
    r1 = _residual("R1", "residual1", tensors[-1], attention, trace)
    n2 = _norm("LN2", r1, trace)
    fs = dict(B=1, T=T,
              f100=1, f101=0, f102=0, f110=0, f111=1, f112=0,
              fb10=0, fb11=0, fb12=0,
              f200=1, f201=0, f210=0, f211=1, f220=0, f221=0,
              fb20=0, fb21=0)
    ffn = _ffn.feed_forward(fs, n2, trace, "ffn")
    y = _residual("Y", "residual2", r1, ffn["output"], trace)
    ft = [{**record, "provenance": _FFN_PROVENANCE[record["id"]]} for record in ffn["tensors"]]
    tensors.extend([n1, *at, r1, n2, *ft, y])
    Y = np.array(y["values"], dtype=np.float64).reshape(1, T, 2)
    logits = np.empty((T, V), dtype=np.float64)
    rows = []
    for t in range(T):
        for c in range(V):
            y0, y1, u0, u1, b = float(Y[0, t, 0]), float(Y[0, t, 1]), float(U[0, c]), float(U[1, c]), float(bias[c])
            product0, product1 = finite(y0 * u0, "readout product0"), finite(y1 * u1, "readout product1")
            summed = finite(product0 + product1, "readout sum")
            value = finite(summed + b, "readout logit")
            logits[t, c] = value
            trace.add(f"readout_{t}_{c}", f"Readout row {t}, class {c}",
                      "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
                      "Only the active compact class prefix contributes to logits; targets are not operands.",
                      dict(t=t, c=c, y0=y0, u0=u0, y1=y1, u1=u1, bias=b),
                      dict(product0=product0, product1=product1, sum=summed, logit=value))
        rows.append(_class_row(logits[t], t, class_ids, trace))
    tensors.extend([
        _float_tensor("Logits", [T, V], ["Position", "Class"], logits, "Final Y times the active U prefix, then active Bias; targets are not operands."),
        _float_tensor("Max", [T], ["Position"], np.array([row["max"] for row in rows], dtype=np.float64), "Maximum computed active class logit at each position."),
        _float_tensor("Shifted", [T, V], ["Position", "Class"], np.array([row["shifted"] for row in rows], dtype=np.float64), "Computed class logit minus its saved row maximum."),
        _float_tensor("Terms", [T, V], ["Position", "Class"], np.array([row["terms"] for row in rows], dtype=np.float64), "Actual exp(Shifted) before left-to-right class summation."),
        _float_tensor("Denominator", [T], ["Position"], np.array([row["denominator"] for row in rows], dtype=np.float64), "Shifted exponential sum from zero in ascending compact class order."),
        _float_tensor("LogS", [T], ["Position"], np.array([row["logS"] for row in rows], dtype=np.float64), "ln(Denominator), saved for factored NLL."),
        _float_tensor("LSE", [T], ["Position"], np.array([row["lse"] for row in rows], dtype=np.float64), "Max+LogS; saved evidence, not subtracted from target logits to compute NLL."),
        _float_tensor("P", [T, V], ["Position", "Class"], np.array([row["probabilities"] for row in rows], dtype=np.float64), "Terms/Denominator for real active classes only; no inactive-class probabilities."),
        _token.tensor("NextRows", "Position", np.array([row["nextRow"] for row in rows], dtype=np.int32), "Highest computed logit; exact ties keep the smallest compact class."),
        _token.tensor("NextIDs", "Position", np.array([row["nextID"] for row in rows], dtype=np.int32), "Public ID mapped from each computed-logit winner."),
        _float_tensor("NextProbability", [T], ["Position"], np.array([row["nextProbability"] for row in rows], dtype=np.float64), "Stored class probability of the computed-logit winner; never fed back as an observed input."),
    ])
    return json.loads(json.dumps(dict(T=T, V=V, classIDs=class_ids.tolist(), inputIDs=ids.tolist(),
                                     inputRows=input_rows.tolist(), rows=rows, tensors=tensors), allow_nan=False))


def _tokenize(text, merges, trace):
    """Actual IV39 algorithm with the narrower IV43 text/model boundary.

    Prepare encoders before copying any successful record. Size in UTF16 units
    precedes surrogate validation, then actual UTF8 size, then model alphabet.
    The unchanged24/32-byte helper limits remain unchanged in their own files.
    """
    if _token.utf16_length(text) > 6:
        raise NumericalFault("UNSUPPORTED_SIZE", "text: more than 6 UTF-16 units exceeds the 6-byte model input bound.")
    encoding = _token.TokenTrace()
    try:
        corpus = _bpe.encode_bounded("abab", "corpus", "corpus", encoding)
        source = _bpe.encode_bounded(text, "text", "source", encoding)
        if len(source["bytes"]) > 6:
            raise NumericalFault("UNSUPPORTED_SIZE", "text: the actual UTF-8 encoding exceeds 6 bytes.")
        if any(character not in "ab" for character in text):
            raise NumericalFault("UNAVAILABLE", "This toy model supports only raw a and b letters; no normalization, unknown token or truncation is applied.")
        if not text:
            raise NumericalFault("UNAVAILABLE", "Empty text has no observed first token and no conditional target.")
        child = _token.TokenTrace()
        child.add("setup", "Declare learned byte-pair encoding and both exact inputs",
                  "byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
                  "The disclosed training corpus is always abab. Encode the separate exact target with learned ranks, then append EOS. No normalization, trimming, unknown token or truncation.",
                  dict(requestedMerges=merges, eos=1),
                  dict(corpusUnits=4, corpusScalars=4, utf16Units=_token.utf16_length(text),
                       scalarCount=len(source["codePoints"]), byteBound=_bpe.BPE_BYTE_BOUND,
                       mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=512))
        child.steps.extend(encoding.steps)
        tensors = []
        for stem, encoded in (("Corpus", corpus), ("Source", source)):
            for suffix, key, axis, provenance in (
                ("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
                ("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
                ("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
                ("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
                ("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
                ("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
            ):
                _bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
        trained = _bpe.train_bpe(corpus["bytes"], merges, child, tensors)
        ids = _bpe.encode_bpe(source["bytes"], trained["rules"], 1, child, tensors)
        corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", child)
        decoded = _bpe.decode_bpe_ids(ids, trained["rules"], 1, "target", child)
        corpus_equal = int(corpus_decoded["decoded"] == "abab")
        equal = int(decoded["decoded"] == text)
        if not corpus_equal or not equal:
            raise NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
        child.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
                  "corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
                  "Expand actual saved IDs, concatenate bytes, strictly reconstruct scalars, then compare complete strings.",
                  dict(corpusOriginalUnits=4, corpusDecodedUnits=_token.utf16_length(corpus_decoded["decoded"]),
                       corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=_token.utf16_length(text),
                       decodedUnits=_token.utf16_length(decoded["decoded"]), decodedByteCount=len(decoded["bytes"])),
                  dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
        _bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"], "Actual final corpus ID expansions passed to strict UTF-8 decoding.")
        _bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", decoded["bytes"], "Actual final target ID expansions passed to strict UTF-8 decoding.")
    except _bpe.NumericalFault as error:
        raise NumericalFault(error.code, str(error)) from error
    if len(ids) - 1 > 3:
        raise NumericalFault("UNSUPPORTED_SIZE", "The actual BPE sequence exceeds 3 observed input positions; change text or merges explicitly.")
    for step in child.steps:
        trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"],
                  step["explanation"], step["inputs"], step["outputs"])
    tensors = [{**record, "id": f"Tokenizer{record['id']}"} for record in tensors]
    expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}

    def expansion(identifier):
        return [] if identifier == 512 else [identifier] if identifier <= 255 else expansions[identifier]

    def labels(values):
        return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == 512 else
                f"ID {int(identifier)}, bytes {_token.json_text(expansion(int(identifier)))}" for identifier in values]

    texts = dict(
        corpus="abab", input=text, corpusDecoded=corpus_decoded["decoded"], decoded=decoded["decoded"],
        corpusLabels=labels(trained["ids"]), corpusExpansions=[_token.json_text(expansion(int(identifier))) for identifier in trained["ids"]],
        targetLabels=labels(ids), targetExpansions=[_token.json_text(expansion(int(identifier))) for identifier in ids],
        ruleLabels=[f"ID {rule['id']}, bytes {_token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
        ruleExpansions=[_token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
        trainingStop="Zero merges requested: no training round or pair selection occurs." if merges == 0 else "Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < merges else "Requested merge budget completed.",
    )
    summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]), actualMerges=len(trained["rules"]),
                   tokenCount=len(ids), requestedMerges=merges, corpusTokens=len(trained["ids"]), eos=1,
                   byteBound=_bpe.BPE_BYTE_BOUND, vocabularyItems=256 + len(trained["rules"]) + 1,
                   corpusEqual=corpus_equal, equal=equal)
    return dict(ids=ids, tensors=tensors, texts=texts, summary=summary)


def _class_row(logits, t, class_ids, trace):
    """Stable complete row before the next token's readout; strict-logit argmax."""
    V = len(class_ids)
    maximum_inputs = {f"z{c}": float(logits[c]) for c in range(V)}
    maximum = max(maximum_inputs.values())
    trace.add(f"class_{t}_max", f"Class maximum for prediction row {t}", "max=max(active logits)",
              "Only active classes contribute. The maximum term exp(0)=1 prevents a zero normalizer.",
              maximum_inputs, dict(max=maximum))
    shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
    denominator, running = 0.0, {}
    for c in range(V):
        z = float(logits[c])
        shift = finite(z - maximum, "class shifted logit")
        term = finite(math.exp(shift), "class exponential")
        shifted[c], terms[c] = shift, term
        trace.add(f"class_{t}_exp_{c}", f"Class row {t}, exponential {c}", "shifted=logit-max; term=exp(shifted)",
                  "Save each actual shifted exponential; no epsilon, clipping or rounded display operand.",
                  dict(t=t, c=c, logit=z, max=maximum), dict(shifted=shift, term=term))
        denominator = finite(denominator + term, "class denominator")
        running[f"running{c}"] = denominator
    log_s = finite(math.log(denominator), "class logS")
    lse = finite(maximum + log_s, "class logsumexp")
    trace.add(f"class_{t}_normalize", f"Class denominator and logsumexp for row {t}",
              "running starts at 0; running_c=previous+term_c; denominator=last running; logS=ln(denominator); lse=max+logS",
              "Terms accumulate left to right. The objective uses (max-targetLogit)+logS rather than subtraction of rounded LSE.",
              {**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
              {**running, "denominator": denominator, "logS": log_s, "lse": lse})
    for c in range(V):
        term = float(terms[c])
        probability = finite(term / denominator, "class probability")
        probabilities[c] = probability
        trace.add(f"class_{t}_probability_{c}", f"Class row {t}, probability {c}", "probability=term/denominator",
                  "This is an actual stored probability, never a rounded display value used as arithmetic input.",
                  dict(t=t, c=c, term=term, denominator=denominator), dict(probability=probability))
    next_row = 0
    for c in range(1, V):
        if float(logits[c]) > float(logits[next_row]):
            next_row = c
    next_id, next_probability = int(class_ids[next_row]), float(probabilities[next_row])
    trace.add(f"class_{t}_argmax", f"Computed-logit winner for row {t}", "argmax(logits); exact ties use smallest compact class",
              "Probability rounding can make distinct logits appear tied. Compare computed logits; predictions are not observed teacher-forcing inputs.",
              maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
    return dict(logits=logits.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
                denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
                nextRow=next_row, nextID=next_id, nextProbability=next_probability)


def _objective(forward, targets, trace):
    """Mean shifted-target NLL and ONLY the conditional readout derivatives."""
    T, V, rows, class_ids = forward["T"], forward["V"], forward["rows"], forward["classIDs"]
    Y = np.array(next(record["values"] for record in forward["tensors"] if record["id"] == "Y"), dtype=np.float64).reshape(1, T, 2)
    target_rows = np.empty(T, dtype=np.int32)
    nll, gaps, target_logits, target_probabilities = (np.empty(T, dtype=np.float64) for _ in range(4))
    for t in range(T):
        target_id = int(targets[t])
        if target_id not in class_ids:
            raise NumericalFault("INVALID_INPUT", "Every shifted target must be an active model class.")
        c = class_ids.index(target_id)
        target_rows[t] = c
        trace.add(f"target_lookup_{t}", f"Map shifted target at position {t}", "targetRow=compactRow(sequence[t+1])",
                  "Teacher forcing keeps the observed input and its next target distinct. Final EOS contributes one loss.",
                  dict(t=t, targetID=target_id, V=V), dict(targetRow=c))
        row = rows[t]
        target_logit, maximum, log_s, probability = row["logits"][c], row["max"], row["logS"], row["probabilities"][c]
        gaps[t] = finite(maximum - target_logit, "target gap")
        nll[t] = finite(float(gaps[t]) + log_s, "target NLL")
        target_logits[t], target_probabilities[t] = target_logit, probability
        trace.add(f"loss_{t}", f"Shifted target loss at position {t}", "gap=max-targetLogit; nll=gap+logS",
                  "Use the saved stable operands. The first piece is given; every continuation through EOS has weight1.",
                  dict(t=t, targetID=target_id, targetRow=c, max=maximum, targetLogit=target_logit, logS=log_s, probability=probability),
                  dict(gap=float(gaps[t]), nll=float(nll[t])))
    loss_sum = 0.0
    for t in range(T):
        previous = loss_sum
        loss_sum = finite(previous + float(nll[t]), "loss sum")
        trace.add(f"reduce_{t}", f"Accumulate target loss {t}", "lossSum=previousLossSum+nll",
                  "Accumulate every actual shifted target loss in ascending position order, including EOS.",
                  dict(t=t, previousLossSum=previous, nll=float(nll[t])), dict(lossSum=loss_sum))
    mean_nll = finite(loss_sum / T, "mean NLL")
    perplexity = finite(math.exp(mean_nll), "perplexity")
    trace.add("reduction", "Mean conditional objective and perplexity", "validCount=T; meanNLL=lossSum/T; perplexity=exp(meanNLL)",
              "Natural-log loss is in nats per shifted target. Tokenizer changes alter the events and conditioning.",
              dict(T=T, lossSum=loss_sum), dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity))
    d_logits = np.empty((T, V), dtype=np.float64)
    for t in range(T):
        for c in range(V):
            probability, indicator = rows[t]["probabilities"][c], int(c == int(target_rows[t]))
            difference = finite(probability - indicator, "probability minus target")
            gradient = finite(difference / T, "mean logit derivative")
            d_logits[t, c] = gradient
            trace.add(f"gradient_{t}_{c}", f"Mean-loss logit derivative [{t},{c}]", "indicator=(c=targetRow)?1:0; difference=P-indicator; gradient=difference/T",
                      "The analytic sensitivity includes the mean-loss denominator; it is not a gradient check or update.",
                      dict(t=t, c=c, targetRow=int(target_rows[t]), probability=probability, T=T),
                      dict(indicator=indicator, difference=difference, gradient=gradient))
    # Inactive raw columns have zero dependency, not fabricated active probabilities.
    d_u = np.zeros((2, 5), dtype=np.float64)
    d_bias = np.zeros(5, dtype=np.float64)
    for d in range(2):
        for c in range(V):
            inputs, outputs, gradient = dict(d=d, c=c), {}, 0.0
            for t in range(T):
                feature, g = float(Y[0, t, d]), float(d_logits[t, c])
                inputs[f"y{t}"], inputs[f"g{t}"] = feature, g
                product = finite(feature * g, "readout gradient product")
                gradient = finite(gradient + product, "readout gradient sum")
                outputs[f"product{t}"], outputs[f"running{t}"] = product, gradient
            outputs["gradient"] = gradient
            d_u[d, c] = gradient
            trace.add(f"readout_gradient_{d}_{c}", f"Readout weight derivative [{d},{c}]", "product_t=Y[t,d]*dLogits[t,c]; running starts at 0; gradient=sum_t product_t",
                      "Hold final decoder features fixed. Each product immediately enters the sum in ascending position order.", inputs, outputs)
    for c in range(V):
        inputs, outputs, gradient = dict(c=c), {}, 0.0
        for t in range(T):
            g = float(d_logits[t, c])
            inputs[f"g{t}"] = g
            gradient = finite(gradient + g, "bias gradient sum")
            outputs[f"running{t}"] = gradient
        outputs["gradient"] = gradient
        d_bias[c] = gradient
        trace.add(f"bias_gradient_{c}", f"Readout bias derivative [{c}]", "running starts at 0; gradient=sum_t dLogits[t,c]",
                  "Each active bias contributes directly at each position. Inactive raw columns have structural zero dependency.", inputs, outputs)
    tensors = [
        _token.tensor("TargetIDs", "Position", targets, "sequence[1:]; final EOS included exactly once as a scored continuation."),
        _token.tensor("TargetRows", "Position", target_rows, "Active compact class of each observed shifted target."),
        _float_tensor("TargetLogits", [T], ["Position"], target_logits, "Actual class logit gathered after computing the entire causal distribution."),
        _float_tensor("TargetProbability", [T], ["Position"], target_probabilities, "Actual target class probability; never rounded before loss computation."),
        _float_tensor("TargetGap", [T], ["Position"], gaps, "Saved max-targetLogit used in the factored NLL."),
        _float_tensor("NLL", [T], ["Position"], nll, "TargetGap+LogS for every shifted target, including EOS."),
        _float_tensor("dLogits", [T, V], ["Position", "Class"], d_logits, "(P-oneHot(target))/T for the actual mean objective."),
        _float_tensor("dU", [2, 5], ["D", "ModelRow"], d_u, "Conditional readout gradient sum_t Y[t,d]*dLogits[t,c]; inactive raw class columns have structural zero dependency."),
        _float_tensor("db", [5], ["ModelRow"], d_bias, "Conditional readout bias gradient sum_t dLogits[t,c]; inactive raw biases have structural zero dependency."),
    ]
    return dict(validCount=T, lossSum=loss_sum, meanNLL=mean_nll, perplexity=perplexity, tensors=tensors)


_JSON_INT = int


def run(derive, defaults):
    """No args: default; one JSON argument: COMPLETE replacement; '-': stdin.

    No query calls any self-check. Invalid data returns only status/code/reason.
    No caller cwd supplies a helper; source loading above is file-relative.
    """
    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 source_self_check():
    """DEFERRED explicit helper assertions; never called by import or query.

    Source-authored anchors/metamorphics are not independent oracle authority.
    Future V5 separately invokes this, the wrapper check and the old BPE check.
    """
    assert __debug__, "Deferred checks require assertions enabled."
    assert _ffn.NumericalFault is _component.NumericalFault
    assert _ffn.tensor is _component.tensor
    assert _ffn.finite is _component.finite
    assert Path(_component.__file__).resolve() == _ROOT / "p07" / "component_reference.py"
    assert Path(_ffn.__file__).resolve() == _ROOT / "p07" / "ffn_reference.py"
    assert Path(_head.__file__).resolve() == _ROOT / "p06" / "head_reference.py"
    assert Path(_bpe.__file__).resolve() == _ROOT / "p09" / "bpe_reference.py"
    assert Path(_token.__file__).resolve() == _ROOT / "p09" / "token_reference.py"
    assert len(DEFAULT_IV43) == 27 and len(NUMERIC_DEFAULTS) == 26
    assert list(DEFAULT_IV43) == ["text", "merges", *PARAMETER_DEFAULTS]
    assert list(tiny_state(dict(DEFAULT_IV43))) == ["text", "numeric"]

    def rejects(call, code):
        try:
            call()
        except NumericalFault as error:
            assert error.code == code, (error.code, code)
        else:
            raise AssertionError("Invalid helper input was accepted")

    def forward(parameters, ids):
        return forward_tiny(parameters, ids, tiny_trace())

    def saved(record, identifier):
        return next(tensor for tensor in record["tensors"] if tensor["id"] == identifier)

    s = dict(NUMERIC_DEFAULTS)
    trace = tiny_trace()
    f = forward_tiny(s, [97, 98], trace)
    assert list(f) == ["T", "V", "classIDs", "inputIDs", "inputRows", "rows", "tensors"]
    assert list(f["rows"][0]) == ["logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability"]
    assert f["T"] == 2 and f["V"] == 3 and f["inputRows"] == [0, 1]
    assert len(trace.steps) == 112 and len(f["tensors"]) == 57
    assert saved(f, "E")["shape"] == [5, 2] and saved(f, "U")["shape"] == [2, 5]
    assert saved(f, "Bias")["shape"] == [5]
    assert saved(f, "InputIDs")["dtype"] == "int32" and _ids([97, 98], ALL_IDS).dtype == np.dtype(np.int32)
    assert all(saved(f, name)["dtype"] == "float64" for name in ("E", "U", "Bias", "Y", "Logits", "P"))
    for tensor in f["tensors"]:
        assert list(tensor) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
        assert tensor["precision"] == (0 if tensor["dtype"] == "int32" else 8)
    # These constructors require real float64 storage before JSON projection.
    rejects(lambda: _float_tensor("bad", [1], ["D"], np.array([1], dtype=np.int32), "wrong dtype"), "SHAPE_MISMATCH")
    rejects(lambda: _float_tensor("bad", [2], ["D"], np.array([1], dtype=np.float64), "wrong shape"), "SHAPE_MISMATCH")
    alpha = 1 / math.sqrt(5)
    r = math.exp((2 * alpha * alpha / math.sqrt(2)) * (1 + math.cos(1)))
    d = (r - 1) / (r + 1)
    delta0, delta1 = 0.5 + alpha, 0.5 + alpha * d
    rho0, rho1 = delta0 / math.sqrt(delta0 * delta0 + 1), delta1 / math.sqrt(delta1 * delta1 + 1)
    expected = [[1 + alpha + rho0, -alpha], [-alpha * d, 1 + alpha * d + rho1]]
    for t in range(2):
        for coordinate in range(2):
            assert math.isclose(saved(f, "Y")["values"][t * 2 + coordinate], expected[t][coordinate], rel_tol=1e-12, abs_tol=1e-14)
    attention_p, allowed = saved(f, "Attentionprobabilities"), saved(f, "Attentionallowed")
    assert allowed["dtype"] == "bool" and allowed["precision"] == 8 and allowed["values"] == [True, False, True, True]
    assert attention_p["values"][:2] == [1, 0]
    assert math.isclose(attention_p["values"][2], 1 / (1 + r), rel_tol=1e-12)
    assert math.isclose(attention_p["values"][3], r / (1 + r), rel_tol=1e-12)
    # Earlier causal features survive a later ID edit; forbidden raw scores need not.
    later = forward(s, [97, 97])
    assert saved(f, "Y")["values"][:2] == saved(later, "Y")["values"][:2]
    assert f["rows"][0] == later["rows"][0]
    eos_input = forward({**s, "e20": 1, "e21": -1}, [512])
    assert eos_input["inputIDs"] == [512] and eos_input["inputRows"] == [2]
    assert saved(eos_input, "X")["values"] == [1, -1]
    assert forward(s, [97])["rows"][0] == f["rows"][0]
    assert forward(s, [512, 97])["inputRows"] == [2, 0]
    for merges, text, ids in ((0, "ab", [97, 98, 512]), (1, "ab", [256, 512]),
                              (2, "abab", [257, 512]), (1, "ababab", [256, 256, 256, 512]),
                              (2, "ababab", [257, 256, 512])):
        checked = tiny_state({**DEFAULT_IV43, "text": text, "merges": merges})
        tokenized = _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace())
        assert tokenized["ids"].tolist() == ids and tokenized["ids"].dtype == np.dtype(np.int32)
    for ids, code in (([], "UNAVAILABLE"), ([97] * 4, "UNSUPPORTED_SIZE"), ([256], "INVALID_INPUT"),
                      ([True], "INVALID_INPUT"), (["97"], "INVALID_INPUT"), ([None], "INVALID_INPUT"),
                      ([768], "INVALID_INPUT"), ([97.5], "INVALID_INPUT"),
                      ([float("nan")], "INVALID_INPUT"), ([float("inf")], "INVALID_INPUT"), ([10**1000], "INVALID_INPUT")):
        rejects(lambda: forward(s, ids), code)
    rejects(lambda: forward(s, np.array([True])), "INVALID_INPUT")
    rejects(lambda: forward(s, np.array([[97]])), "INVALID_INPUT")
    rejects(lambda: forward(s, {0: 97}), "INVALID_INPUT")
    for field, value, code in (("e40", 3, "INVALID_INPUT"), ("u04", True, "NONFINITE"),
                                ("b4", 10**1000, "NONFINITE"), ("merges", 0.5, "INVALID_INPUT")):
        rejects(lambda: forward({**s, field: value}, [97]), code)
    rejects(lambda: forward({**s, "b4": float("nan")}, []), "NONFINITE")
    rejects(lambda: numeric_parameters({**s, "extra": 1}), "INVALID_INPUT")
    rejects(lambda: numeric_parameters({key: value for key, value in s.items() if key != "u04"}), "INVALID_INPUT")

    class GetterDict(dict):
        def __getitem__(self, key):
            raise AssertionError("Custom getter must not execute")

    rejects(lambda: tiny_state(GetterDict(DEFAULT_IV43)), "INVALID_INPUT")
    rejects(lambda: tiny_state({**DEFAULT_IV43, "text": [], "e40": float("nan")}), "INVALID_INPUT")
    for patch, code in (({"text": "a" * 7}, "UNSUPPORTED_SIZE"), ({"text": "\ud800"}, "INVALID_INPUT"),
                        ({"text": "🦊🦊"}, "UNSUPPORTED_SIZE"), ({"text": "ééé"}, "UNAVAILABLE"),
                        ({"text": "c"}, "UNAVAILABLE"), ({"text": ""}, "UNAVAILABLE"),
                        ({"text": "ababab"}, "UNSUPPORTED_SIZE")):
        checked = tiny_state({**DEFAULT_IV43, **patch})
        rejects(lambda: _tokenize(checked["text"], checked["numeric"]["merges"], tiny_trace()), code)
    rejects(lambda: tiny_state({**DEFAULT_IV43, "text": "\ud800", "b4": float("nan")}), "NONFINITE")
    # Public records and the explicit trace are detached from state and later calls.
    f["rows"][0]["probabilities"][0] = 99
    saved(f, "Y")["values"][0] = 99
    f["tensors"][0]["values"][0] = 0
    trace.steps[0]["outputs"].clear()
    again = forward(s, [97, 98])
    assert saved(again, "Y")["values"][0] != 99
    assert again["rows"][0]["probabilities"][0] != 99
    assert again["inputIDs"] == [97, 98]
    assert s == dict(NUMERIC_DEFAULTS)


def derive43(state):
    """Compose the owner-adopted complete ordered numerical/text snapshot."""
    checked = tiny_state(state)
    text, numeric = checked["text"], checked["numeric"]
    token_trace = tiny_trace()
    tokenized = _tokenize(text, numeric["merges"], token_trace)
    sequence = tokenized["ids"]
    inputs, targets = sequence[:-1].copy(), sequence[1:].copy()
    T, V = len(inputs), 3 + numeric["merges"]
    trace = tiny_trace()
    trace.add("setup", "Validate all raw fields before interpreting the text",
              "text<=6 UTF-8 bytes; fixed corpus=abab; eos=1; inputs=sequence[:-1]; targets=sequence[1:]",
              "The first encoded piece is given. Score each continuation through EOS; no first-piece probability, cropping or learning update.",
              numeric, dict(utf16Units=_token.utf16_length(text), byteBound=6, eos=1, corpusUnits=4))
    for step in token_trace.steps:
        trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
    class_ids = np.array(ALL_IDS[:V], dtype=np.int32)
    token_summary = tokenized["summary"]
    trace.add("class_map", "Map tokenizer IDs to active compact model classes", "V=3+actualMerges; classIDs=prefix([97,98,512,256,257],V)",
              "Tokenizer vocabularyItems=257+merges differs from the model's 3+merges active classes; public IDs never allocate513 rows.",
              dict(actualMerges=token_summary["actualMerges"], vocabularyItems=token_summary["vocabularyItems"]),
              {"classCount": V, **{f"id{c}": int(identifier) for c, identifier in enumerate(class_ids)}})
    forward = forward_tiny(numeric, inputs, trace)
    objective = _objective(forward, targets, trace)
    trace.add("finish", "Keep the objective and conditional readout derivatives together",
              "objective=mean shifted NLL; derivatives=dLogits,dU,db with decoder features fixed",
              "All parameters are hand-set and untrained. No optimizer, embedding/full-block gradient or language-learning claim.",
              dict(contextLength=T, classCount=V),
              dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"]))
    last = forward["rows"][-1]
    summary = dict(validCount=T, lossSum=objective["lossSum"], meanNLL=objective["meanNLL"], perplexity=objective["perplexity"],
                   classCount=V, actualMerges=numeric["merges"], contextLength=T,
                   B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6,
                   nextRow=last["nextRow"], nextID=last["nextID"], nextProbability=last["nextProbability"],
                   **{f"tokenizer_{key}": value for key, value in token_summary.items()})
    tensors = [*tokenized["tensors"], *forward["tensors"],
               _token.tensor("SequenceIDs", "Sequence", sequence, "Actual ranked BPE result with one final EOS; the first piece is given."),
               *objective["tensors"]]
    texts = dict(input=text, decoded=tokenized["texts"]["decoded"],
                 objective="Conditional continuation through EOS given the first encoded piece; no probability for that first piece.",
                 gradientScope="Analytic readout U/bias derivatives with decoder features fixed; no embedding/full-block gradient, optimizer update or training.",
                 modelVocabulary=["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256", "4: abab / ID257"],
                 **{f"tokenizer_{key}": value for key, value in tokenized["texts"].items()})
    result = trace.result(summary, tensors)
    result["texts"] = texts
    # Python exposes ordinary detached JSON; TS additionally freezes its snapshot.
    return json.loads(json.dumps(result, allow_nan=False, ensure_ascii=False))


if __name__ == "__main__":
    run(guarded(derive43), DEFAULT_IV43)

4. Actual BPE composition — code/python/p09/iv39.py. The inference helper uses derive_iv39 with fixed corpus abab, the editable prompt, the requested merges and eos=0. Its complete trace includes real tokenizer training/application/decoder evidence. This call determines prompt IDs once; it does not tokenize the extended decoded string after appending.

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-39 — Byte-Pair Encoding: A Full Merge Trace.

Train adjacent byte-ID pairs on a separate, literal training corpus. Count
ALL adjacent occurrences, including overlaps, choose the greatest count,
then the lexicographically smallest NUMERIC (left ID, right ID) on ties.
Replace matches left to right without overlap. Recount after every rule.
Encode the target with the learned rules in increasing rank, not by taking
the longest dictionary prefix. Only the target can receive explicit EOS512.

Hand default: corpus abab starts [97,98,97,98]. Counts ab2,ba1 select ab256,
so [256,256] becomes rule257=[97,98,97,98]. Target ababab becomes
[256,256,256] then [257,256]; expanding BOTH IDs reconstructs six bytes.
Corpus aaaa has three adjacent aa occurrences but only two replacements.
Corpus bbaa encounters bb,ba,aa once each; numeric order chooses the LAST
encountered aa=(97,97), producing [98,98,256], not insertion-order bb.
Corpus 'bc bc ab' learns bc256,bc-space257,ab258. In its third round
(97,98) beats pairs starting257 numerically, not by decimal string keys.
Target abc becomes [97,256]; greedy longest-prefix ab258 would differ.

All source is authored without imports, execution, fixtures generation or
runtime validation. Keep bpe_reference.py AND token_reference.py beside this
wrapper. File-relative loading supports an arbitrary caller working directory.
"""
import importlib.util
from pathlib import Path

_bpe_spec = importlib.util.spec_from_file_location(
    "_p09_bpe_reference", Path(__file__).resolve().with_name("bpe_reference.py"))
_bpe = importlib.util.module_from_spec(_bpe_spec)
_bpe_spec.loader.exec_module(_bpe)

DEFAULT_IV39 = _bpe.DEFAULT_IV39


@_bpe._token.guarded
def derive_iv39(state):
    """Train a real corpus, encode a separate target, and decode both actual IDs."""
    token = _bpe._token
    s = _bpe.bpe_state(state)
    encoding_trace = token.TokenTrace()
    corpus = _bpe.encode_bounded(s["corpus"], "corpus", "corpus", encoding_trace)
    source = _bpe.encode_bounded(s["text"], "text", "source", encoding_trace)
    trace = token.TokenTrace()
    corpus_units, units = token.utf16_length(s["corpus"]), token.utf16_length(s["text"])
    trace.add("setup", "Declare learned byte-pair encoding and both exact inputs",
              "byte IDs=0..255; learned ID=256+rank; EOS=512; each text field<=24 UTF-8 bytes",
              "Validate every raw field before corpus then target Unicode semantics. Train on the corpus byte stream including spaces; encode the separate target using learned ranks. No normalization, word splitting, inferred EOS or pretrained vocabulary is used.",
              dict(requestedMerges=s["merges"], eos=s["eos"]),
              dict(corpusUnits=corpus_units, corpusScalars=len(corpus["codePoints"]), utf16Units=units,
                   scalarCount=len(source["codePoints"]), byteBound=_bpe.BYTE_BOUND,
                   mergeBase=_bpe.MERGE_BASE, mergeBound=_bpe.MERGE_BOUND, EOS=_bpe.EOS))
    # Scalar records were prepared during validation; keep their actual order.
    trace.steps.extend(encoding_trace.steps)
    tensors = []
    for stem, encoded in (("Corpus", corpus), ("Source", source)):
        for suffix, key, axis, provenance in (
            ("CodePoints", "codePoints", "Scalars", "Validated Unicode scalars in exact input order."),
            ("UTF16Offsets", "offsets", "Scalars", "Zero-based UTF-16 storage offset for each scalar."),
            ("UTF16Widths", "widths", "Scalars", "UTF-16 storage units consumed by each scalar."),
            ("ByteOffsets", "byteOffsets", "Scalars", "Zero-based UTF-8 byte offset for each scalar."),
            ("ByteWidths", "byteWidths", "Scalars", "Actual UTF-8 bytes emitted by each scalar."),
            ("Bytes", "bytes", "Bytes", "Manual UTF-8 encoding in source order, preserving all data."),
        ):
            _bpe.save_tensor(tensors, f"{stem}{suffix}", axis, encoded[key], provenance)
    trained = _bpe.train_bpe(corpus["bytes"], s["merges"], trace, tensors)
    ids = _bpe.encode_bpe(source["bytes"], trained["rules"], s["eos"], trace, tensors)
    # Corpus is NEVER EOS-trained. Both inverse paths expand real saved IDs.
    corpus_decoded = _bpe.decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)
    target_decoded = _bpe.decode_bpe_ids(ids, trained["rules"], s["eos"], "target", trace)
    corpus_equal = int(corpus_decoded["decoded"] == s["corpus"])
    equal = int(target_decoded["decoded"] == s["text"])
    if not (corpus_equal and equal):
        raise _bpe.NumericalFault("INVALID_INPUT", "Actual BPE reconstructions did not equal both original strings.")
    trace.add("roundtrip", "Compare both actual strict reconstructions with the original strings",
              "corpusEqual=(corpusDecoded===corpus); equal=(targetDecoded===text)",
              "Expand real corpus and target IDs separately, concatenate real bytes, strictly reconstruct Unicode scalars, and only then compare strings. Empty content reconstructs the empty string; optional target EOS emits no bytes.",
              dict(corpusOriginalUnits=corpus_units, corpusDecodedUnits=token.utf16_length(corpus_decoded["decoded"]),
                   corpusDecodedByteCount=len(corpus_decoded["bytes"]), originalUnits=units,
                   decodedUnits=token.utf16_length(target_decoded["decoded"]), decodedByteCount=len(target_decoded["bytes"])),
              dict(corpusTokens=len(trained["ids"]), tokenCount=len(ids), corpusEqual=corpus_equal, equal=equal))
    _bpe.save_tensor(tensors, "CorpusDecodedBytes", "Bytes", corpus_decoded["bytes"],
                     "Actual final corpus ID expansions passed to strict UTF-8 decoding.")
    _bpe.save_tensor(tensors, "TargetDecodedBytes", "Bytes", target_decoded["bytes"],
                     "Actual final target ID expansions passed to strict UTF-8 decoding.")
    expansions = {rule["id"]: rule["bytes"].tolist() for rule in trained["rules"]}

    def expansion(identifier):
        return [] if identifier == _bpe.EOS else [identifier] if identifier <= 255 else expansions[identifier]

    def labels(token_ids):
        return ["ID 512: EOS (explicit control), bytes []" if int(identifier) == _bpe.EOS else
                f"ID {int(identifier)}, bytes {token.json_text(expansion(int(identifier)))}" for identifier in token_ids]

    def expansion_labels(token_ids):
        return [token.json_text(expansion(int(identifier))) for identifier in token_ids]

    summary = dict(corpusBytes=len(corpus["bytes"]), byteCount=len(source["bytes"]),
                   actualMerges=len(trained["rules"]), tokenCount=len(ids), requestedMerges=s["merges"],
                   corpusTokens=len(trained["ids"]), eos=s["eos"], byteBound=_bpe.BYTE_BOUND,
                   vocabularyItems=256 + len(trained["rules"]) + 1, corpusEqual=corpus_equal, equal=equal)
    texts = dict(corpus=s["corpus"], input=s["text"], corpusDecoded=corpus_decoded["decoded"],
                 decoded=target_decoded["decoded"], corpusLabels=labels(trained["ids"]),
                 corpusExpansions=expansion_labels(trained["ids"]), targetLabels=labels(ids),
                 targetExpansions=expansion_labels(ids),
                 ruleLabels=[f"ID {rule['id']}, bytes {token.json_text(rule['bytes'].tolist())}" for rule in trained["rules"]],
                 ruleExpansions=[token.json_text(rule["bytes"].tolist()) for rule in trained["rules"]],
                 trainingStop="Zero merges requested: no training round or pair selection occurs." if s["merges"] == 0 else
                 "Stopped early: fewer than two current training tokens remain." if len(trained["rules"]) < s["merges"] else
                 "Requested merge budget completed.")
    return trace.result(summary, tensors, texts)


def source_self_check():
    """Deferred hand-literal record checks; never part of the normal CLI path."""
    assert __debug__, "Run later checks with assertions enabled."
    _bpe.source_self_check()
    result = derive_iv39(dict(DEFAULT_IV39))
    assert list(result) == ["status", "outputs", "steps", "tensors", "texts"]
    assert list(result["outputs"])[:11] == ["corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal"]
    assert [result["outputs"][key] for key in ("corpusBytes", "byteCount", "actualMerges", "tokenCount")] == [4, 6, 2, 2]
    assert len(result["steps"]) == 44 and len(result["tensors"]) == 37
    assert result["texts"]["corpusDecoded"] == "abab" and result["texts"]["decoded"] == "ababab"
    assert result["texts"]["targetLabels"] == ["ID 257, bytes [97,98,97,98]", "ID 256, bytes [97,98]"]
    # Tensor count:12source+1initial+10round+1corpus+3rules+2expansions+
    # 1targetinitial+4targetpasses+1targetfinal+2decoded=37. No program counted it.
    tensor_ids = [record["id"] for record in result["tensors"]]
    for merges, eos, steps in ((2, 1, 46), (3, 0, 45), (3, 1, 47), (4, 0, 45), (4, 1, 47)):
        case = derive_iv39(dict(corpus="abab", text="ababab", merges=merges, eos=eos))
        assert len(case["steps"]) == steps
        assert [record["id"] for record in case["tensors"]] == tensor_ids
    for eos in (0, 1):
        empty = derive_iv39(dict(corpus="", text="", merges=0, eos=eos))
        assert empty["outputs"]["tokenCount"] == eos
        assert len(empty["steps"]) == 2 + 2 * eos
        assert empty["texts"]["decoded"] == empty["texts"]["corpusDecoded"] == ""
    for patch, code in (
        (dict(corpus="\ud800", merges=float("nan")), "NONFINITE"),
        (dict(corpus="a" * 25, text="\ud800"), "UNSUPPORTED_SIZE"),
        (dict(corpus="\ud800", text="a" * 25), "INVALID_INPUT"),
        (dict(text="🦊" * 7), "UNSUPPORTED_SIZE"),
        (dict(text="🦊" * 9), "UNSUPPORTED_SIZE"),
    ):
        bad = derive_iv39({**DEFAULT_IV39, **patch})
        assert list(bad) == ["status", "code", "reason"] and bad["code"] == code


if __name__ == "__main__":
    # No args: defaults; one complete JSON state: replacement; '-': stdin JSON.
    _bpe._token.run(derive_iv39, DEFAULT_IV39)

5. Learned rules and strict expansion — code/python/p09/bpe_reference.py. train_bpe counts pairs, chooses by the declared numeric tie order and replaces disjoint occurrences. encode_bpe applies learned rules in rank order. decode_bpe_ids expands the actual supplied result IDs using those rules and the explicit EOS flag. This is the mechanism behind [256,256] decoding to abab while fresh tokenization could choose [257].

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-39: complete learned byte-pair encoding, authored without execution.

NumPy int32 arrays hold actual bytes, code points, offsets, IDs and rule
expansions. Python integers do scalar comparisons, counts and index arithmetic.
The unchanged token_reference.py supplies the manual UTF-8 codec and record
storage. No native codec supplies a production answer. A byte piece need not
be valid Unicode alone: concatenate all expansions before strict decoding.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType
import numpy as np

# File-relative loading works even when the caller has an unrelated cwd.
_token_spec = importlib.util.spec_from_file_location(
    "_p09_bpe_token_reference", Path(__file__).resolve().with_name("token_reference.py"))
_token = importlib.util.module_from_spec(_token_spec)
_token_spec.loader.exec_module(_token)

NumericalFault = _token.NumericalFault
BPE_BYTE_BOUND = 24
BYTE_BOUND = BPE_BYTE_BOUND
MERGE_BASE = 256
MERGE_BOUND = 4
EOS = 512
DEFAULT_IV39 = MappingProxyType(dict(corpus="abab", text="ababab", merges=2, eos=0))


def data_object(value, fields, label):
    """Exact built-in mappings have own data entries, never property getters."""
    if type(value) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", f"{label} must be a plain object.")
    if any(type(key) is not str for key in value) or set(value) != set(fields):
        raise NumericalFault("INVALID_INPUT", f"{label} must have exactly {', '.join(fields)} as own fields.")


def dense_data(values, limit, label, numeric=True):
    """Reject custom indexing BEFORE reading entries; never narrow invalid data."""
    if type(values) is np.ndarray and numeric:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
    if len(values) > limit:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")


def budget(merges):
    if type(merges) not in (int, float):
        raise NumericalFault("NONFINITE", "merges must be an actual finite number.")
    # The reused integer validator catches finiteness OverflowError on huge ints.
    return _token.integer(merges, 0, MERGE_BOUND, "merges")


def eos_flag(eos):
    _token._flag(eos)
    return int(eos)


def bpe_state(state):
    """ALL raw strings/numbers precede corpus, then target Unicode semantics."""
    data_object(state, DEFAULT_IV39, "state")
    for key in ("corpus", "text"):
        if type(state[key]) is not str:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an actual string, without coercion.")
    merges = budget(state["merges"])
    if type(state["eos"]) not in (int, float):
        raise NumericalFault("NONFINITE", "eos must be an actual finite number.")
    # Check finite before the flag domain, preserving NONFINITE error precedence.
    eos = _token.integer(state["eos"], 0, 1, "eos")
    return dict(corpus=state["corpus"], text=state["text"], merges=merges, eos=eos)


def encode_bounded(text, field, prefix, trace):
    """Early UTF-16 bound, all surrogate checks, then actual UTF-8 byte bound."""
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", f"{field} must be an actual string, without coercion.")
    if _token.utf16_length(text) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{field}: more than 24 UTF-16 units necessarily exceeds this 24-byte field.")
    reason = f"{field}: the actual UTF-8 encoding exceeds 24 bytes; shorten this field explicitly."
    try:
        encoded = _token.utf8_encode(text, prefix, trace)
    except NumericalFault as error:
        # Nine foxes hit the inherited32-byte bound before this24-byte postcheck.
        if error.code == "UNSUPPORTED_SIZE":
            raise NumericalFault("UNSUPPORTED_SIZE", reason) from error
        raise
    if len(encoded["bytes"]) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", reason)
    return encoded


def bytes_input(values):
    dense_data(values, BYTE_BOUND, "BPE bytes")
    return _token.int_array(values, high=255, label="BPE bytes", limit=BYTE_BOUND)


def rule_table(rules):
    """Validate a lossless, acyclic rule namespace before expanding caller IDs."""
    dense_data(rules, MERGE_BOUND, "BPE rules", numeric=False)
    # Inspect every object/container first; no arbitrary mapping/index getter runs.
    for rule in rules:
        data_object(rule, ("id", "left", "right", "bytes"), "rule")
        dense_data(rule["bytes"], BYTE_BOUND, "Rule bytes")
    expansions, pairs = {}, set()
    for rank, rule in enumerate(rules):
        expected_id = MERGE_BASE + rank
        identifier = int(_token.int_array([rule["id"]], high=259, label="Rule ID")[0])
        if identifier != expected_id:
            raise NumericalFault("INVALID_INPUT", f"Rule {rank} must have ID {expected_id}.")
        operands = _token.int_array([rule["left"], rule["right"]], high=expected_id - 1, label="Rule operands")
        left, right = int(operands[0]), int(operands[1])
        # IDs between255 and this ID must already be present, never forward/cyclic.
        if any(operand > 255 and operand not in expansions for operand in (left, right)):
            raise NumericalFault("INVALID_INPUT", "Each rule operand must be a byte ID or an earlier merge ID.")
        if (left, right) in pairs:
            raise NumericalFault("INVALID_INPUT", "Duplicate BPE rule pairs are not allowed.")
        pairs.add((left, right))
        stored = _token.int_array(rule["bytes"], high=255, label="Rule bytes", limit=BYTE_BOUND)
        left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
        right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
        expected = np.concatenate((left_bytes, right_bytes))
        if len(expected) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "A rule expansion exceeds 24 bytes.")
        if len(expected) != len(stored) or any(int(a) != int(b) for a, b in zip(expected, stored)):
            raise NumericalFault("INVALID_INPUT", "Rule bytes must equal the left expansion followed by the right expansion.")
        expansions[identifier] = expected
    return expansions


def save_tensor(tensors, identifier, axis, values, provenance):
    """Keep actual int32 storage; an empty stream has no fabricated tensor."""
    if len(values):
        tensors.append(_token.tensor(identifier, axis, values, provenance))


def replace_pass(ids, rule, rank, stage, trace, tensors):
    """Count positions in CURRENT input tokens, not original UTF-8 bytes."""
    stem = f"{'Train' if stage == 'train' else 'Encode'}R{rank}"
    save_tensor(tensors, f"{stem}Before", "Tokens", ids,
                "Complete current token list before this nonoverlapping left-to-right pass.")
    result, position = [], 0
    while position < len(ids):
        current_id = int(ids[position])
        next_id = int(ids[position + 1]) if position + 1 < len(ids) else -1
        matched = int(current_id == rule["left"] and next_id == rule["right"])
        consumed = 2 if matched else 1
        identifier = rule["id"] if matched else current_id
        next_position = position + consumed
        inputs = dict(rank=rank, position=position, inputLength=len(ids), left=rule["left"],
                      right=rule["right"], newID=rule["id"], currentID=current_id,
                      nextID=next_id, outputLength=len(result))
        result.append(identifier)
        trace.add(f"{stage}_replace_{rank}_{position}", f"{stage}: rank {rank}, current-token position {position}",
                  "matched=(currentID=left and nextID=right); emit matched?newID:currentID; consumed=matched?2:1; nextPosition=position+consumed",
                  "Positions index the current token list, not original bytes. A match consumes two tokens and emits one; a nonmatch copies one token. Advancing past both matched operands prevents overlapping replacements. The complete pass snapshots and position/consumed/nextPosition retain every scan; nextID -1 means no next token, never a token or padding item.",
                  inputs, dict(matched=matched, id=identifier, consumed=consumed,
                               nextPosition=next_position, outputLength=len(result)))
        position = next_position
    values = np.array(result, dtype=np.int32)
    save_tensor(tensors, f"{stem}After", "Tokens", values,
                "Complete actual output token list after this rank; no padding or truncation.")
    return values


def train_bpe(values, merges, trace, tensors):
    """Count overlaps, select numeric ties, concatenate bytes, replace disjointly."""
    merges = budget(merges)
    ids = bytes_input(values).copy()
    rules, expansions = [], {}
    save_tensor(tensors, "TrainInitialIDs", "Tokens", ids,
                "Initial training byte IDs, one ID for each actual corpus byte.")
    for rank in range(merges):
        if len(ids) < 2:
            trace.add("train_stop", "Stop: fewer than two training tokens remain", "length<2 means no adjacent pair exists",
                      "This is one real early stop, not a fabricated merge. A zero requested budget does not enter training at all.",
                      dict(rank=rank, length=len(ids), requestedMerges=merges), dict(actualMerges=len(rules)))
            break
        counts = {}
        # Advance by ONE here: unlike replacement, counting includes overlaps.
        for position in range(len(ids) - 1):
            left, right = int(ids[position]), int(ids[position + 1])
            count_before = counts.get((left, right), 0)
            counts[(left, right)] = count_before + 1
            trace.add(f"train_count_{rank}_{position}", f"Count round {rank} pair at current-token position {position}",
                      "frequency(left,right)=previous frequency+1; next counting position=position+1",
                      "Count every adjacent occurrence, including overlaps. The table starts empty each round. In aaaa, aa occurs at positions 0, 1 and 2 even though replacement will consume only two disjoint pairs.",
                      dict(rank=rank, position=position, left=left, right=right, countBefore=count_before),
                      dict(countAfter=counts[(left, right)], distinctPairs=len(counts)))
        # Sort NUMERIC tuples, never string keys or insertion order (bbaa anchor).
        candidates = sorted(counts)
        for suffix, entries, provenance in (
            ("Left", [pair[0] for pair in candidates], "Numeric tuple order: left ID, then right ID; aligned candidate columns."),
            ("Right", [pair[1] for pair in candidates], "Right ID in the same sorted candidate order."),
            ("Frequency", [counts[pair] for pair in candidates], "Actual adjacent-pair frequency, including overlapping occurrences."),
        ):
            save_tensor(tensors, f"TrainR{rank}Candidate{suffix}", "Candidates",
                        np.array(entries, dtype=np.int32), provenance)
        best = None
        best_frequency = 0
        for candidate_index, (left, right) in enumerate(candidates):
            frequency = counts[(left, right)]
            best_left, best_right = best if best is not None else (-1, -1)
            inputs = dict(candidateIndex=candidate_index, left=left, right=right, frequency=frequency,
                          bestLeft=best_left, bestRight=best_right, bestFrequency=best_frequency)
            frequency_greater = int(frequency > best_frequency)
            frequency_equal = int(frequency == best_frequency)
            lex_smaller = int(best is not None and (left, right) < best)
            take = int(best is None or frequency_greater or (frequency_equal and lex_smaller))
            if take:
                best, best_frequency = (left, right), frequency
            trace.add(f"train_compare_{rank}_{candidate_index}", f"Compare round {rank} candidate {candidate_index}",
                      "take=first candidate or greater frequency or (equal frequency and numerically smaller (left,right))",
                      "Compare integer IDs, left first and then right, not string keys or encounter order. Candidate columns use numeric tuple order. The first comparison uses best IDs -1 and frequency 0 as an explicit empty-best sentinel.",
                      inputs, dict(take=take, frequencyGreater=frequency_greater, frequencyEqual=frequency_equal,
                                   lexSmaller=lex_smaller, bestLeft=best[0], bestRight=best[1], bestFrequency=best_frequency))
        left, right = best
        identifier = MERGE_BASE + rank
        trace.add(f"train_select_{rank}", f"Select round {rank} winning pair",
                  "newID=256+rank; select greatest frequency, then smallest numeric pair",
                  "Frequency 1 is eligible. Requested merges are a budget; actual merges stop early only when no adjacent pair remains.",
                  dict(rank=rank, currentLength=len(ids), candidateCount=len(candidates)),
                  dict(id=identifier, left=left, right=right, frequency=best_frequency))
        left_bytes = np.array([left], dtype=np.int32) if left <= 255 else expansions[left]
        right_bytes = np.array([right], dtype=np.int32) if right <= 255 else expansions[right]
        expansion = np.concatenate((left_bytes, right_bytes))
        rule = dict(id=identifier, left=left, right=right, bytes=expansion)
        inputs = dict(id=identifier, left=left, right=right, leftWidth=len(left_bytes), rightWidth=len(right_bytes))
        inputs.update({f"leftByte{i}": int(byte) for i, byte in enumerate(left_bytes)})
        inputs.update({f"rightByte{i}": int(byte) for i, byte in enumerate(right_bytes)})
        outputs = dict(byteWidth=len(expansion))
        outputs.update({f"byte{i}": int(byte) for i, byte in enumerate(expansion)})
        trace.add(f"train_rule_{rank}", f"Build rule {rank} byte expansion", "new bytes=left bytes followed by right bytes",
                  "Both operands are bytes or earlier merge IDs. Their complete concatenation defines the new ID and cannot create a cycle. A piece may end inside a UTF-8 scalar, so its label uses ID and exact JSON bytes.",
                  inputs, outputs)
        rules.append(rule)
        expansions[identifier] = expansion.copy()
        ids = replace_pass(ids, rule, rank, "train", trace, tensors)
    save_tensor(tensors, "CorpusIDs", "Tokens", ids,
                "Final learned corpus token IDs; corpus training never contains EOS.")
    for identifier, key, provenance in (
        ("RuleIDs", "id", "Learned IDs in ascending rank, ID=256+rank."),
        ("RuleLeft", "left", "Left operand ID for each learned rank."),
        ("RuleRight", "right", "Right operand ID for each learned rank."),
    ):
        save_tensor(tensors, identifier, "Rules", np.array([rule[key] for rule in rules], dtype=np.int32), provenance)
    for rule in rules:
        save_tensor(tensors, f"Rule{rule['id']}Bytes", "Bytes", rule["bytes"],
                    "Actual concatenated operand bytes; the piece alone need not be valid UTF-8.")
    return dict(ids=ids, rules=rules)


def encode_bpe(values, rules, eos, trace, tensors):
    """Apply each learned rank once; only then append optional target EOS512.

    A later rule emits a higher ID and leaves a replacement token between any
    untouched neighbors, so it cannot create an earlier rule's lower-ID pair.
    """
    rule_table(rules)
    eos = eos_flag(eos)
    ids = bytes_input(values).copy()
    save_tensor(tensors, "EncodeInitialIDs", "Tokens", ids,
                "Initial target byte IDs before any ranked application.")
    for rank, rule in enumerate(rules):
        # Public rule fields may be integral floats; scalar trace fields are ints.
        actual = dict(id=int(rule["id"]), left=int(rule["left"]), right=int(rule["right"]))
        ids = replace_pass(ids, actual, rank, "encode", trace, tensors)
    ids = _token.append_eos(ids, eos, "target", trace)
    save_tensor(tensors, "TargetIDs", "Tokens", ids,
                "Final target token IDs after all learned ranks, then optional unique EOS tail.")
    return ids


def decode_bpe_ids(values, rules, eos, prefix, trace):
    """Expand the ACTUAL validated IDs, then strictly reconstruct Unicode."""
    expansions = rule_table(rules)
    eos = eos_flag(eos)
    dense_data(values, BYTE_BOUND + 1, "BPE token IDs")
    ids = _token.int_array(values, high=EOS, label="BPE token IDs", limit=BYTE_BOUND + 1)
    has_tail = len(ids) > 0 and int(ids[-1]) == EOS
    content = ids[:-1] if has_tail else ids
    if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
        raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
    for stored in content:
        identifier = int(stored)
        if identifier > 255 and identifier not in expansions:
            raise NumericalFault("INVALID_INPUT", f"Unknown or inactive BPE ID {identifier}.")
    byte_values = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        expansion = [identifier] if identifier <= 255 else expansions[identifier].tolist()
        byte_offset = len(byte_values)
        byte_values.extend(expansion)
        if len(byte_values) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "Decoded BPE expansions exceed 24 bytes.")
        outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
        outputs.update({f"byte{i}": byte for i, byte in enumerate(expansion)})
        trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → validated byte expansion",
                  "Byte IDs expand to their own byte; learned IDs expand to their validated concatenated bytes. Concatenate every expansion before strict UTF-8 decoding; no replacement-character guess or input copy is used.",
                  dict(index=index, id=identifier), outputs)
    if eos == 1:
        trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
                  "The decoder has validated the unique required tail marker. Its empty expansion is a control convention, not a lost source character.",
                  dict(index=len(ids) - 1, id=EOS), dict(stripped=1))
    actual_bytes = np.array(byte_values, dtype=np.int32)
    return dict(bytes=actual_bytes, decoded=_token.utf8_decode(actual_bytes, prefix, trace))


def source_self_check():
    """Hand-derived deferred assertions: NEVER called by import or normal CLI.

    The human resource hold forbids invoking this function now. These are
    source checks for later owner validation, not generated expected answers.
    """
    assert __debug__, "Run later checks with assertions enabled."

    def rejects(call, code="INVALID_INPUT"):
        try:
            call()
        except NumericalFault as error:
            assert error.code == code, (error.code, code)
            return error
        raise AssertionError("Invalid boundary was accepted")

    def train(values, merges):
        trace, tensors = _token.TokenTrace(), []
        result = train_bpe(values, merges, trace, tensors)
        return result, trace, tensors

    # Default: abab -> ab/ab -> abab; target ababab -> abab/ab.
    trained, trace, tensors = train([97, 98, 97, 98], 2)
    assert trained["ids"].tolist() == [257]
    assert [(rule["id"], rule["left"], rule["right"]) for rule in trained["rules"]] == [(256, 97, 98), (257, 256, 256)]
    assert [rule["bytes"].tolist() for rule in trained["rules"]] == [[97, 98], [97, 98, 97, 98]]
    ids = encode_bpe([97, 98, 97, 98, 97, 98], trained["rules"], 1, trace, tensors)
    assert ids.tolist() == [257, 256, 512]
    assert decode_bpe_ids(trained["ids"], trained["rules"], 0, "corpus", trace)["decoded"] == "abab"
    assert decode_bpe_ids(ids, trained["rules"], 1, "target", trace)["decoded"] == "ababab"
    assert ids.dtype == np.dtype(np.int32) and trained["ids"].dtype == np.dtype(np.int32)
    assert all(rule["bytes"].dtype == np.dtype(np.int32) for rule in trained["rules"])
    assert all(record["dtype"] == "int32" and record["precision"] == 0 for record in tensors)
    concat = next(step for step in trace.steps if step["id"] == "train_rule_1")
    assert list(concat["inputs"]) == ["id", "left", "right", "leftWidth", "rightWidth", "leftByte0", "leftByte1", "rightByte0", "rightByte1"]
    tail = next(step for step in trace.steps if step["id"] == "encode_replace_1_2")
    assert tail["inputs"]["nextID"] == -1
    assert tail["outputs"] == dict(matched=0, id=256, consumed=1, nextPosition=3, outputLength=2)

    # Count overlaps3, replace disjointly2; every emitted token remains lossless.
    overlap, overlap_trace, _ = train([97, 97, 97, 97], 1)
    assert overlap["ids"].tolist() == [256, 256]
    assert next(step for step in overlap_trace.steps if step["id"] == "train_count_0_2")["outputs"]["countAfter"] == 3
    assert len([step for step in overlap_trace.steps if step["id"].startswith("train_replace_")]) == 2
    last_tie, _, _ = train([98, 98, 97, 97], 1)
    assert (last_tie["rules"][0]["left"], last_tie["rules"][0]["right"]) == (97, 97)
    assert last_tie["ids"].tolist() == [98, 98, 256]

    # Numeric97 precedes257; rank application differs from greedy prefix ab.
    ranked, rank_trace, rank_tensors = train([98, 99, 32, 98, 99, 32, 97, 98], 3)
    assert [(rule["left"], rule["right"]) for rule in ranked["rules"]] == [(98, 99), (256, 32), (97, 98)]
    assert ranked["ids"].tolist() == [257, 257, 258]
    assert encode_bpe([97, 98, 99], ranked["rules"], 0, rank_trace, rank_tensors).tolist() == [97, 256]
    empty, empty_trace, empty_tensors = train([], 4)
    assert not empty["rules"] and empty["ids"].tolist() == []
    assert [step["id"] for step in empty_trace.steps] == ["train_stop"] and empty_tensors == []
    _, zero_trace, _ = train([97, 98], 0)
    assert zero_trace.steps == []
    assert encode_bpe([], [], 1, _token.TokenTrace(), []).tolist() == [512]

    # Malformed IDs/EOS/rules fail before any guessed/replacement decoding.
    for values, eos in (([], 1), ([512], 0), ([512, 65], 1), ([65, 512, 512], 1), ([256], 0), ([384], 0), ([1024], 0), ([True], 0), ([10**1000], 0)):
        rejects(lambda: decode_bpe_ids(values, [], eos, "target", _token.TokenTrace()))
    rejects(lambda: decode_bpe_ids([65] * 25, [], 0, "target", _token.TokenTrace()), "UNSUPPORTED_SIZE")
    for values in ([195], [192, 128], [237, 160, 128], [244, 144, 128, 128]):
        rejects(lambda: decode_bpe_ids(values, [], 0, "target", _token.TokenTrace()))
    assert decode_bpe_ids([239, 187, 191, 0], [], 0, "target", _token.TokenTrace())["decoded"] == "\ufeff\0"
    for bad in (
        [dict(id=257, left=97, right=98, bytes=[97, 98])],
        [dict(id=256, left=256, right=98, bytes=[97, 98])],
        [dict(id=256, left=97, right=98, bytes=[98, 97])],
        [dict(id=256, left=97, right=98, bytes=[97, 98]), dict(id=257, left=97, right=98, bytes=[97, 98])],
    ):
        rejects(lambda: rule_table(bad))

    # Both 7fox/28byte postcheck and 9fox/36byte inherited32 rejection say24.
    for text in ("🦊" * 7, "🦊" * 9):
        error = rejects(lambda: encode_bounded(text, "corpus", "corpus", _token.TokenTrace()), "UNSUPPORTED_SIZE")
        assert "24" in str(error) and "32" not in str(error)
    rejects(lambda: encode_bounded("🦊" * 7 + "\ud800", "corpus", "corpus", _token.TokenTrace()))
    rejects(lambda: bpe_state(dict(corpus=None, text="", merges=0, eos=float("nan"))))
    rejects(lambda: bpe_state(dict(corpus="\ud800", text="", merges=float("nan"), eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=10**1000, eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=10**1000)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=True, eos=0)), "NONFINITE")
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0, eos=0, extra=0)))
    rejects(lambda: bpe_state(dict(corpus="", text="", merges=0)))

    class AccessorState:
        @property
        def corpus(self):
            raise AssertionError("Getter must never run")

    class AccessorList(list):
        def __getitem__(self, index):
            raise AssertionError("Custom indexing must never run")

    rejects(lambda: bpe_state(AccessorState()))
    rejects(lambda: decode_bpe_ids(AccessorList([65]), [], 0, "target", _token.TokenTrace()))
    rejects(lambda: rule_table([dict(id=256, left=97, right=98, bytes=AccessorList([97, 98]))]))

6. Strict text codec — code/python/p09/token_reference.py. Follow the UTF-16 length, Unicode-scalar and UTF-8 construction/decoding functions. Token integers use int32 arrays and remain separate from float64 neural features. No normalization or replacement character silently changes the user’s raw text.

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 IX: bounded integer tokenization, authored without execution.

NumPy int32 arrays store actual code points, offsets, bytes and IDs. Arithmetic
uses Python integers, so bit shifts never depend on NumPy scalar promotion.
UTF-8 is implemented below; no native codec supplies an encoded/decoded answer.
Empty streams, BOMs, noncharacters, spaces and NULs are ordinary valid data.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np

EOS = 512
BYTE_BOUND = 32
CHARACTER_BASE = 1024
IV37_DEFAULTS = MappingProxyType(dict(text="Aé🦊", eos=0))
IV38_DEFAULTS = MappingProxyType(dict(text="lower low", vocabLimit=8, eos=0))
# Fixed active-prefix dictionary: these pieces are authored, not trained.
SUBWORDS = (
    (384, "low", (108, 111, 119)),
    (385, "lower", (108, 111, 119, 101, 114)),
    (386, "lowest", (108, 111, 119, 101, 115, 116)),
    (387, "er", (101, 114)),
    (388, "est", (101, 115, 116)),
    (389, "ing", (105, 110, 103)),
    (390, "a", (97,)),
    (391, "ab", (97, 98)),
)


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


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))
    return call


def integer(value, low, high, label):
    """Validate before conversion; Python bool is not a mathematical number here."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    try:
        finite = math.isfinite(value)
    except OverflowError:
        finite = False
    if not finite:
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    if value < low or value > high or int(value) != value:
        raise NumericalFault("INVALID_INPUT", f"{label} must be an integer from {low} to {high}.")
    return int(value)


def scalar_valid(cp):
    return 0 <= cp <= 0x10FFFF and not 0xD800 <= cp <= 0xDFFF


def utf16_units(cp):
    """Reconstruct the actual high/low units from a validated supplementary scalar."""
    if cp <= 0xFFFF:
        return [cp]
    return [0xD800 + ((cp - 0x10000) >> 10), 0xDC00 + ((cp - 0x10000) & 1023)]


def utf16_length(text):
    return sum(2 if ord(character) > 0xFFFF else 1 for character in text)


def text_state(state, chapter):
    """Exact raw fields and numeric domains precede ALL Unicode/size semantics."""
    if type(chapter) is not int or chapter not in (37, 38):
        raise NumericalFault("INVALID_INPUT", "Use token chapter 37 or 38.")
    defaults = IV37_DEFAULTS if chapter == 37 else IV38_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the named fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields.")
    if type(state["text"]) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string, without coercion.")
    result = dict(text=state["text"])
    for key in defaults:
        if key != "text":
            if type(state[key]) not in (int, float):
                raise NumericalFault("NONFINITE", f"{key} must be an actual finite number.")
            result[key] = integer(state[key], 0, 8 if key == "vocabLimit" else 1, key)
    return result


def int_array(values, low=0, high=0x7FFFFFFF, label="integer array", limit=BYTE_BOUND):
    """Check dense numeric storage BEFORE narrowing; integral-valued floats are legal."""
    if type(values) is np.ndarray:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual array.")
    if len(values) > limit:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds {limit} entries.")
    checked = []
    for index, value in enumerate(values):
        if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
            raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
        try:
            finite = math.isfinite(value)
        except OverflowError:
            finite = False
        if not finite or value < low or value > high or int(value) != value:
            raise NumericalFault("INVALID_INPUT", f"{label}[{index}] must be an own integer from {low} to {high}.")
        checked.append(int(value))
    return np.array(checked, dtype=np.int32)


def utf8_encode(text, prefix="source", trace=None):
    """Scan valid scalars first; then split each into explicit UTF-8 payload groups."""
    if trace is None:
        trace = TokenTrace()
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", "UTF-8 input must be an actual string.")
    if utf16_length(text) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", "More than 32 UTF-16 units necessarily exceeds this 32-byte lab.")
    code_points, offsets, widths = [], [], []
    offset = 0
    # Python strings store scalars directly; explicit surrogate values are invalid.
    for character in text:
        cp = ord(character)
        if 0xD800 <= cp <= 0xDBFF:
            raise NumericalFault("INVALID_INPUT", f"Unpaired high surrogate at UTF-16 offset {offset}.")
        if 0xDC00 <= cp <= 0xDFFF:
            raise NumericalFault("INVALID_INPUT", f"Unpaired low surrogate at UTF-16 offset {offset}.")
        width = len(utf16_units(cp))
        code_points.append(cp)
        offsets.append(offset)
        widths.append(width)
        offset += width
    byte_values, byte_offsets, byte_widths = [], [], []
    for index, cp in enumerate(code_points):
        if cp <= 0x7F:
            expansion = [cp]
        elif cp <= 0x7FF:
            expansion = [0xC0 | (cp >> 6), 0x80 | (cp & 63)]
        elif cp <= 0xFFFF:
            expansion = [0xE0 | (cp >> 12), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
        else:
            expansion = [0xF0 | (cp >> 18), 0x80 | ((cp >> 12) & 63),
                         0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)]
        units = utf16_units(cp)
        inputs = dict(scalarIndex=index, utf16Offset=offsets[index], utf16Width=widths[index], codePoint=cp, unit0=units[0])
        if len(units) == 2:
            inputs["unit1"] = units[1]
        outputs = dict(byteOffset=len(byte_values), byteWidth=len(expansion))
        for j, byte in enumerate(expansion):
            mask = (31 if len(expansion) == 2 else 15 if len(expansion) == 3 else 7) if j == 0 else 63
            outputs[f"payload{j}"] = byte if len(expansion) == 1 else byte & mask
        outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
        trace.add(f"{prefix}_scalar_{index}", f"Encode scalar {index}: U+{cp:04X}",
                  "supplementary cp=(high−55296)*1024+(low−56320)+65536; split cp into payload groups; add UTF-8 prefix bits",
                  "A continuation byte has prefix 10 and six payload bits (base 64). Lead prefixes are 0, 110, 1110 or 11110. UTF-16 offsets count storage units, not perceived characters. No normalization or BOM stripping occurs.",
                  inputs, outputs)
        byte_offsets.append(len(byte_values))
        byte_widths.append(len(expansion))
        byte_values.extend(expansion)
    if len(byte_values) > BYTE_BOUND:
        raise NumericalFault("UNSUPPORTED_SIZE", "The actual UTF-8 encoding exceeds 32 bytes; shorten the input explicitly.")
    return dict(bytes=int_array(byte_values, high=255, label="UTF-8 bytes"), codePoints=int_array(code_points),
                offsets=int_array(offsets), widths=int_array(widths), byteOffsets=int_array(byte_offsets), byteWidths=int_array(byte_widths))


def utf8_decode(values, prefix="utf8", trace=None):
    """Remove prefixes, accumulate radix-64 digits, validate, then rebuild the text."""
    if trace is None:
        trace = TokenTrace()
    values = int_array(values, high=255, label="UTF-8 bytes")
    characters, offset = [], 0
    while offset < len(values):
        lead = int(values[offset])
        width = 1 if lead <= 0x7F else 2 if 0xC2 <= lead <= 0xDF else 3 if 0xE0 <= lead <= 0xEF else 4 if 0xF0 <= lead <= 0xF4 else 0
        if not width:
            raise NumericalFault("INVALID_INPUT", f"Invalid UTF-8 lead at byte {offset}.")
        if offset + width > len(values):
            raise NumericalFault("INVALID_INPUT", f"Truncated UTF-8 sequence at byte {offset}.")
        inputs = dict(scalarIndex=len(characters), byteOffset=offset, byteWidth=width)
        outputs, cp = {}, 0
        for j in range(width):
            byte = int(values[offset + j])
            if j > 0 and not 0x80 <= byte <= 0xBF:
                raise NumericalFault("INVALID_INPUT", f"Invalid continuation byte at {offset + j}.")
            inputs[f"byte{j}"] = byte
            mask = (31 if width == 2 else 15 if width == 3 else 7) if j == 0 else 63
            payload = byte if width == 1 else byte & mask
            outputs[f"payload{j}"] = payload
            cp = cp * 64 + payload
            outputs[f"accumulator{j}"] = cp
        minimum = 0 if width == 1 else 0x80 if width == 2 else 0x800 if width == 3 else 0x10000
        if cp < minimum or not scalar_valid(cp):
            raise NumericalFault("INVALID_INPUT", f"Overlong, surrogate or out-of-range scalar at byte {offset}.")
        units = utf16_units(cp)
        outputs.update(codePoint=cp, utf16Width=len(units))
        outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
        # chr uses the validated scalar; no source text is available to copy here.
        characters.append(chr(cp))
        trace.add(f"{prefix}_decode_{len(characters) - 1}", f"Decode UTF-8 scalar {len(characters) - 1}",
                  "accumulator=previous*64+payload; reconstruct UTF-16 units from the validated scalar",
                  "Remove lead/continuation prefixes, combine payloads in byte order, reject non-shortest encodings and invalid scalars, then append actual reconstructed units. U+FEFF and noncharacters are preserved.",
                  inputs, outputs)
        offset += width
    return "".join(characters)


def _flag(eos):
    if type(eos) not in (int, float) or eos not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "eos must be numeric 0 or 1.")


def _vocabulary(limit):
    try:
        if type(limit) not in (int, float):
            raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.")
        return integer(limit, 0, 8, "vocabLimit")
    except NumericalFault as error:
        raise NumericalFault("INVALID_INPUT", "vocabLimit must be an integer from 0 to 8.") from error


def _strip_eos(ids, eos):
    _flag(eos)
    ids = int_array(ids, high=CHARACTER_BASE + 0x10FFFF, label="Token IDs", limit=BYTE_BOUND + 1)
    has_tail = len(ids) > 0 and int(ids[-1]) == EOS
    content = ids[:-1].copy() if has_tail else ids.copy()
    if has_tail != (eos == 1) or any(int(value) == EOS for value in content):
        raise NumericalFault("INVALID_INPUT", "EOS must occur exactly once at the tail when eos=1, and nowhere when eos=0.")
    return ids, content


def append_eos(ids, eos, prefix, trace):
    """Return actual int32 storage with the optional reserved tail, never text matching."""
    _flag(eos)
    if eos == 1:
        index = len(ids)
        ids = np.concatenate((ids, np.array([EOS], dtype=np.int32)))
        trace.add(f"{prefix}_eos", f"{prefix}: append explicit EOS", "id=512",
                  "Only this flag appends EOS; literal text such as <eos> remains ordinary input.",
                  dict(index=index, eos=eos), dict(id=EOS))
    return ids


def _eos_record(ids, eos, prefix, trace):
    if eos == 1:
        trace.add(f"{prefix}_strip_eos", f"{prefix}: strip explicit tail EOS", "EOS emits no text bytes",
                  "The decoder has validated the whole ID stream and the required unique tail marker.",
                  dict(index=len(ids) - 1, id=EOS), dict(stripped=1))


def decode_byte_ids(ids, eos, prefix="byte", trace=None):
    return _decode_pieces(ids, eos, 0, False, prefix, TokenTrace() if trace is None else trace)


def decode_subword_ids(ids, eos, limit, prefix="subword", trace=None):
    limit = _vocabulary(limit)
    return _decode_pieces(ids, eos, limit, True, prefix, TokenTrace() if trace is None else trace)


def _decode_pieces(ids, eos, limit, subwords, prefix, trace):
    ids, content = _strip_eos(ids, eos)
    active = {identifier: expansion for identifier, _, expansion in SUBWORDS[:limit]} if subwords else {}
    byte_values = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        if identifier <= 255:
            expansion = (identifier,)
        elif identifier in active:
            expansion = active[identifier]
        else:
            raise NumericalFault("INVALID_INPUT", f"Unknown or inactive {prefix} ID {identifier}.")
        byte_offset = len(byte_values)
        byte_values.extend(expansion)
        if len(byte_values) > BYTE_BOUND:
            raise NumericalFault("UNSUPPORTED_SIZE", "Decoded token expansions exceed 32 bytes.")
        outputs = dict(byteOffset=byte_offset, byteWidth=len(expansion))
        outputs.update({f"byte{j}": byte for j, byte in enumerate(expansion)})
        trace.add(f"{prefix}_expand_{index}", f"{prefix}: expand ID at token {index}", "ID → declared byte expansion",
                  "Fallback byte IDs equal their byte value; active subword IDs expand to their full declared bytes. A single fallback byte may be only part of a Unicode scalar.",
                  dict(index=index, id=identifier), outputs)
    _eos_record(ids, eos, prefix, trace)
    values = int_array(byte_values, high=255, label="UTF-8 bytes")
    return dict(bytes=values, decoded=utf8_decode(values, prefix, trace))


def decode_character_ids(ids, eos, prefix="char", trace=None):
    if trace is None:
        trace = TokenTrace()
    ids, content = _strip_eos(ids, eos)
    characters = []
    for index, stored in enumerate(content):
        identifier = int(stored)
        cp = identifier - CHARACTER_BASE
        if not scalar_valid(cp):
            raise NumericalFault("INVALID_INPUT", f"Character ID {identifier} does not name a Unicode scalar.")
        units = utf16_units(cp)
        outputs = dict(codePoint=cp, utf16Width=len(units))
        outputs.update({f"unit{j}": unit for j, unit in enumerate(units)})
        characters.append(chr(cp))
        trace.add(f"{prefix}_inverse_{index}", f"Character ID {index}: inverse mapping",
                  "codePoint=id−1024; reconstruct UTF-16 units",
                  "The scalar range excludes surrogate code points but includes noncharacters. The comparison vocabulary is algorithmic; no million-row matrix is allocated.",
                  dict(index=index, id=identifier), outputs)
    _eos_record(ids, eos, prefix, trace)
    decoded = "".join(characters)
    # External ID streams obey the same text bound; this private trace is omitted.
    utf8_encode(decoded)
    return decoded


def greedy_ids(values, limit, trace):
    """Choose longest matching byte expansion, then lowest ID; no match keeps a byte."""
    values = int_array(values, high=255, label="Greedy source bytes")
    limit = _vocabulary(limit)
    ids, offset = [], 0
    while offset < len(values):
        matches = []
        for identifier, _, expansion in SUBWORDS[:limit]:
            if offset + len(expansion) <= len(values) and all(int(values[offset + j]) == byte for j, byte in enumerate(expansion)):
                matches.append((identifier, len(expansion)))
        chosen, width = int(values[offset]), 1
        if matches:
            chosen, width = min(matches, key=lambda candidate: (-candidate[1], candidate[0]))
        inputs = dict(byteOffset=offset, remaining=len(values) - offset, candidateMatches=len(matches))
        for index, (identifier, match_width) in enumerate(matches):
            inputs[f"candidate{index}ID"] = identifier
            inputs[f"candidate{index}Width"] = match_width
        trace.add(f"subword_decision_{len(ids)}", f"Choose subword at byte offset {offset}",
                  "choose longest matching active byte expansion; tie: lowest subword ID; no match: current byte",
                  "Matched candidates are listed in fixed vocabulary order. An active one-byte entry is preferred to fallback when it matches. Advance by the actual chosen byte width; spaces and unmatched Unicode bytes remain in the stream.",
                  inputs, dict(id=chosen, byteWidth=width, nextByteOffset=offset + width))
        ids.append(chosen)
        offset += width
    return int_array(ids)


def json_text(value):
    """Match JSON string/array metadata without ASCII escaping or added spaces."""
    return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))


def byte_labels(ids):
    return ["EOS (explicit control)" if int(value) == EOS else f"byte {int(value)}" for value in ids]


def byte_expansions(ids):
    return [json_text([] if int(value) == EOS else [int(value)]) for value in ids]


def numbers(values):
    return {key: integer(value, -0x80000000, 0x7FFFFFFF, key) for key, value in values.items()}


class TokenTrace:
    def __init__(self):
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, outputs):
        inputs, outputs = numbers(inputs), numbers(outputs)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
                               inputs=inputs, outputs=outputs))

    def result(self, summary, tensors, texts):
        # Include copied encoding steps too, after the signed first summary aliases.
        outputs = numbers(summary)
        for step in self.steps:
            outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
        return dict(status="defined", outputs=outputs, steps=self.steps, tensors=tensors, texts=texts)


def tensor(identifier, axis, values, provenance):
    """Serialize actual nonempty int32 storage; empty streams yield no fake tensor."""
    if type(values) is not np.ndarray or values.dtype != np.dtype(np.int32) or values.ndim != 1:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: require one-dimensional int32 storage.")
    if not 1 <= len(values) <= 64:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions must be 1–64.")
    if type(axis) is not str or not axis:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name the axis.")
    return dict(id=identifier, shape=[len(values)], axes=[axis], dtype="int32", values=values.tolist(),
                provenance=provenance, precision=0)


_JSON_INT = int


def run(derive, defaults):
    """No args: defaults; one JSON arg: full replacement; '-': JSON from stdin."""
    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=(",", ":")))

7. Head operations — code/python/p06/head_reference.py. project_heads records the projection products and explicit layout conversion. attend_heads records score products, permissions, allowed-only softmax and weighted-value sums. join_heads rejoins the head and performs WO. The tiny composition supplies identity WO explicitly; the helper’s independent default example is not the configuration used here.

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 VI: real NumPy head arrays with explicit Python-float arithmetic.

The stages are local: project_heads owns projections and layout, attend_heads
owns scores/probabilities/weighted values, join_heads owns concatenation and WO.
Chapter wrappers combine those records explicitly. No Part V helper is imported.
Keep this file beside iv27.py, iv28.py and iv29.py. Source authored under hold;
none of these numerical programs has been executed or runtime-validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


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


def finite(value, label):
    """Accept numerical scalars, never strings, booleans or nonfinite values."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


# Weight names mean input feature d, head h, feature f WITHIN that head.
_head_defaults = dict(
    B=1, T=3, H=2, Dk=1, Dv=1,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
)
for _prefix in ("wq", "wk", "wv"):
    for _d in range(2):
        for _h in range(2):
            for _f in range(2):
                _head_defaults[f"{_prefix}{_d}{_h}{_f}"] = 1 if _d == (_h + _f) % 2 else 0
HEAD_DEFAULTS = MappingProxyType(_head_defaults)
ATTENTION_HEAD_DEFAULTS = MappingProxyType(dict(
    **HEAD_DEFAULTS, mode=1, valid0=1, valid1=1, valid2=1, shift=0,
))
OUTPUT_HEAD_DEFAULTS = MappingProxyType(dict(
    **ATTENTION_HEAD_DEFAULTS,
    wo000=1, wo001=1, wo010=0.5, wo011=0,
    wo100=1, wo101=-1, wo110=0, wo111=0.5,
))
del _head_defaults, _prefix, _d, _h, _f


def head_state(state, stage):
    """Validate exactly 41/46/54 fields BEFORE selecting any active slots."""
    if type(stage) is not int or stage not in (27, 28, 29):
        raise NumericalFault("INVALID_INPUT", "Use head stage 27, 28 or 29.")
    defaults = {27: HEAD_DEFAULTS, 28: ATTENTION_HEAD_DEFAULTS, 29: OUTPUT_HEAD_DEFAULTS}[stage]
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every named scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), H=(1, 2), Dk=(1, 2), Dv=(1, 2),
                          mode=(0, 3), valid0=(0, 1), valid1=(0, 1), valid2=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (-10000, 10000) if key == "shift" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class HeadTrace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        # New finite dictionaries detach records from the caller's mutable state.
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))

    def result(self, summary, tensors):
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def head_trace():
    return HeadTrace()


def tensor(identifier, shape, axes, values, provenance):
    if not 1 <= len(shape) <= 4 or len(shape) != len(axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    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.")
    array = np.asarray(values)
    if array.shape != tuple(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    boolean = array.dtype == np.dtype(np.bool_)
    flat = [bool(value) for value in array.reshape(-1)] if boolean else [finite(value, identifier) for value in array.reshape(-1)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="bool" if boolean else "float64",
                values=flat, provenance=provenance, precision=8)


def split_heads(identifier, values, B, T, H, F, features, trace):
    """Reshape [B,T,H*F] first; then separately permute axes (0,2,1,3)."""
    for name, value, maximum in (("B", B, 2), ("T", T, 3), ("H", H, 2), ("F", F, 2), ("features", features, 4)):
        value = finite(value, name)
        if not value.is_integer() or not 1 <= value <= maximum:
            raise NumericalFault("INVALID_INPUT", f"{name} must be an integer between 1 and {maximum}.")
    B, T, H, F, features = int(B), int(T), int(H), int(F), int(features)
    if features != H * F:
        raise NumericalFault("SHAPE_MISMATCH", "Projection features must equal H*F; no feature may be discarded.")
    if type(values) is not list or len(values) != B * T * features:
        raise NumericalFault("SHAPE_MISMATCH", "Projection storage must be a dense array of B*T*features values.")
    # Shape/storage errors precede traversal of any numerical element.
    flat = [finite(value, f"{identifier}[{index}]") for index, value in enumerate(values)]
    split = np.array(flat, dtype=np.float64).reshape((B, T, H, F))
    trace.add(f"reshape_{identifier}", f"{identifier}: expose the head and within-head feature axes",
              "[B,T,H*F] -> [B,T,H,F]; the flat value order is unchanged",
              "A reshape changes only the coordinate description. It does not move a token or a head value.",
              dict(B=B, T=T, H=H, F=F, features=features, elements=B*T*H*F), dict(elements=B*T*H*F))
    # This declared permutation is a separate copy, not a disguised reshape.
    heads = np.transpose(split, axes=(0, 2, 1, 3)).copy()
    for b in range(B):
        for h in range(H):
            for t in range(T):
                for f in range(F):
                    feature = h * F + f
                    source_offset = (b * T + t) * (H * F) + feature
                    destination_offset = ((b * H + h) * T + t) * F + f
                    source_value = float(split[b, t, h, f])
                    trace.add(f"permute_{identifier}_{b}_{h}_{t}_{f}", f"{identifier}[{b},{h},{t},{f}]: copy to head-major order",
                              "U[b,h,t,f]=R[b,t,h,f]; axes=(0,2,1,3)",
                              "The source and destination flat offsets differ in general; the indexed value is copied unchanged.",
                              dict(b=b, h=h, t=t, f=f, feature=feature, sourceOffset=source_offset,
                                   destinationOffset=destination_offset, sourceValue=source_value),
                              dict(value=float(heads[b, h, t, f])))
    feature_axis = "Dv" if identifier == "V" else "Dk"
    tensors = [tensor(f"{identifier}Split", [B, T, H, F], ["B", "T", "H", feature_axis], split,
                      "Storage-preserving reshape of the concatenated projection; each feature is h*F+f."),
               tensor(f"{identifier}Heads", [B, H, T, F], ["B", "H", "T", feature_axis], heads,
                      "Separate declared axis permutation (0,2,1,3) from token-major to head-major storage.")]
    return dict(split=split, heads=heads, tensors=tensors)


def project_heads(s, trace):
    """Project Q,K,V in role/b/t/h/f order, then expose each head layout."""
    B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
    X = np.empty((B, T, 2), dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                X[b, t, d] = s[f"x{b}{t}{d}"]
    trace.add("setup", "Validate all scalar inputs and select active dimensions",
              "D=2; X[B,T,D]; WQ,WK[D,H*Dk]; WV[D,H*Dv]",
              "Validate even inactive fields, then pack each named head/feature parameter. Both input rows remain active.",
              s, dict(B=B, T=T, D=2, H=H, Dk=Dk, Dv=Dv))
    stage = dict(X=X)
    for name, prefix, width in (("Q", "wq", Dk), ("K", "wk", Dk), ("V", "wv", Dv)):
        weights = np.empty((2, H * width), dtype=np.float64)
        joined = np.empty((B, T, H * width), dtype=np.float64)
        for d in range(2):
            for h in range(H):
                for f in range(width):
                    weights[d, h * width + f] = s[f"{prefix}{d}{h}{f}"]
        for b in range(B):
            for t in range(T):
                for h in range(H):
                    for f in range(width):
                        x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                        w0, w1 = float(weights[0, h * width + f]), float(weights[1, h * width + f])
                        product0 = finite(x0 * w0, "projection product0")
                        product1 = finite(x1 * w1, "projection product1")
                        value = finite(product0 + product1, "projection value")
                        joined[b, t, h * width + f] = value
                        trace.add(f"project_{name}_{b}_{t}_{h}_{f}", f"{name} token {b},{t}, head {h}, feature {f}",
                                  "product0=x0*w0; product1=x1*w1; value=product0+product1",
                                  "Multiply one input row by the column for this head and feature. The two products precede their sum.",
                                  dict(b=b, t=t, h=h, f=f, x0=x0, x1=x1, w0=w0, w1=w1),
                                  dict(product0=product0, product1=product1, value=value))
        stage[f"W{name}"] = weights
        stage[f"{name}Concat"] = joined
    tensors = [tensor("X", [B, T, 2], ["B", "T", "D"], X, "Active input token rows; both input features are retained.")]
    for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
        tensors.append(tensor(f"W{name}", [2, H*width], ["D", axis], stage[f"W{name}"],
                              "Packed named weights: column h*F+f, retaining both input rows."))
    for name, width, axis in (("Q", Dk, "QueryFeature"), ("K", Dk, "KeyFeature"), ("V", Dv, "ValueFeature")):
        tensors.append(tensor(f"{name}Concat", [B, T, H*width], ["B", "T", axis], stage[f"{name}Concat"],
                              "Real two-product projections in token-major, packed-head feature order."))
    aliases = {}
    for name, width in (("Q", Dk), ("K", Dk), ("V", Dv)):
        layout = split_heads(name, stage[f"{name}Concat"].reshape(-1).tolist(), B, T, H, width, H*width, trace)
        stage[f"{name}Split"], stage[f"{name}Heads"] = layout["split"], layout["heads"]
        tensors.extend(layout["tensors"])
        for b in range(B):
            for h in range(H):
                for t in range(T):
                    for f in range(width):
                        aliases[f"{name.lower()}{b}{h}{t}{f}"] = float(layout["heads"][b, h, t, f])
    return dict(X=stage["X"], WQ=stage["WQ"], WK=stage["WK"], WV=stage["WV"],
                QConcat=stage["QConcat"], KConcat=stage["KConcat"], VConcat=stage["VConcat"],
                QSplit=stage["QSplit"], QHeads=stage["QHeads"], KSplit=stage["KSplit"],
                KHeads=stage["KHeads"], VSplit=stage["VSplit"], VHeads=stage["VHeads"],
                aliases=aliases, tensors=tensors)


def stable_softmax(logits, allowed):
    """M1 operation order: allowed max, ascending terms/sum, then quotients."""
    if type(logits) is not list or type(allowed) is not list or not 1 <= len(logits) <= 64 or len(logits) != len(allowed):
        raise NumericalFault("SHAPE_MISMATCH", "A boolean allowed mask must match 1–64 logits.")
    logits = [finite(value, f"logit {j}") for j, value in enumerate(logits)]
    if any(type(value) is not bool for value in allowed):
        raise NumericalFault("INVALID_INPUT", "Every mask entry must be boolean.")
    candidates = [value for j, value in enumerate(logits) if allowed[j]]
    if not candidates:
        raise NumericalFault("FULLY_MASKED_ROW", "This query has no allowed keys; no probability distribution exists.")
    maximum = max(candidates)
    # Match Math.max zero ties without erasing an all-negative-zero maximum.
    if maximum == 0.0 and any(value == 0.0 and math.copysign(1.0, value) > 0.0 for value in candidates):
        maximum = 0.0
    terms = []
    for j, logit in enumerate(logits):
        term = finite(math.exp(finite(logit - maximum, "shifted logit")), "softmax term") if allowed[j] else 0.0
        terms.append(term)
    denominator = 0.0
    for term in terms:
        denominator = finite(denominator + term, "softmax denominator")
    probabilities = [finite(term / denominator, "softmax probability") for term in terms]
    return dict(max=maximum, terms=terms, denominator=denominator, probabilities=probabilities)


def attend_heads(s, projected, trace):
    """Each b,h path scores, masks and mixes independently along the key axis."""
    B, T, H, Dk, Dv = (s[key] for key in ("B", "T", "H", "Dk", "Dv"))
    Q, K, V = projected["QHeads"], projected["KHeads"], projected["VHeads"]
    shape = (B, H, T, T)
    raw, scores = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    aliases = {}
    divisor = finite(math.sqrt(Dk), "score divisor")
    for b in range(B):
        for h in range(H):
            for i in range(T):
                for j in range(T):
                    q0, k0 = float(Q[b, h, i, 0]), float(K[b, h, j, 0])
                    inputs = dict(b=b, h=h, i=i, j=j, Dk=Dk, divisor=divisor, q0=q0, k0=k0)
                    product0 = finite(q0 * k0, "score product0")
                    values, dot = dict(product0=product0), product0
                    if Dk == 2:
                        q1, k1 = float(Q[b, h, i, 1]), float(K[b, h, j, 1])
                        inputs.update(q1=q1, k1=k1)
                        product1 = finite(q1 * k1, "score product1")
                        values["product1"] = product1
                        dot = finite(product0 + product1, "raw score")
                    scaled = finite(dot / divisor, "scaled score")
                    raw[b, h, i, j], scores[b, h, i, j] = dot, scaled
                    values.update(raw=dot, score=scaled)
                    aliases[f"raw{b}{h}{i}{j}"] = dot
                    aliases[f"score{b}{h}{i}{j}"] = scaled
                    trace.add(f"score_{b}_{h}_{i}_{j}", f"Batch {b}, head {h}: query {i} against key {j}",
                              "product0=q0*k0; raw=product0; score=raw/sqrt(Dk)" if Dk == 1 else
                              "product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
                              "Only matching features in this batch and head contribute. The divisor is the per-head key width.", inputs, values)
    allowed = np.empty(shape, dtype=np.bool_)
    logits, probabilities = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    causal, padding = s["mode"] in (1, 3), s["mode"] in (2, 3)
    for b in range(B):
        for h in range(H):
            for i in range(T):
                inputs = dict(b=b, h=h, i=i, mode=s["mode"], shift=s["shift"])
                row_logits, row_allowed = [], []
                for j in range(T):
                    score = float(scores[b, h, i, j])
                    inputs[f"score{j}"] = score
                    permit = (not causal or j <= i) and (not padding or s[f"valid{j}"] == 1)
                    allowed[b, h, i, j] = permit
                    logit = finite(score + s["shift"], "shifted score")
                    logits[b, h, i, j] = logit
                    row_logits.append(logit)
                    row_allowed.append(permit)
                for j in range(T):
                    inputs[f"allowed{j}"] = 1 if row_allowed[j] else 0
                if not any(row_allowed):
                    raise NumericalFault("FULLY_MASKED_ROW", f"Batch {b}, head {h}, query {i} has no allowed keys; the entire result is unavailable.")
                row = stable_softmax(row_logits, row_allowed)
                values = dict(max=row["max"], denominator=row["denominator"])
                for j in range(T):
                    if row_allowed[j]:
                        values[f"shifted{j}"] = finite(row_logits[j] - row["max"], "shifted logit")
                for j in range(T):
                    values[f"term{j}"] = row["terms"][j]
                for j in range(T):
                    p = row["probabilities"][j]
                    probabilities[b, h, i, j] = p
                    values[f"p{j}"] = p
                    aliases[f"p{b}{h}{i}{j}"] = p
                trace.add(f"row_{b}_{h}_{i}", f"Batch {b}, head {h}: masked key softmax for query {i}",
                          "logit_j=score_j+shift; max=max(allowed logits); term_j=allowed_j?exp(logit_j-max):0; denominator=sum_j term_j; p_j=term_j/denominator",
                          "Normalize allowed keys only, in ascending key order. Queries remain; masks are shared across heads/batches. Forbidden probabilities are exactly zero; allowed exponential underflow is distinct.", inputs, values)
    OHeads = np.empty((B, H, T, Dv), dtype=np.float64)
    for b in range(B):
        for h in range(H):
            for i in range(T):
                for f in range(Dv):
                    inputs, products, running = dict(b=b, h=h, i=i, f=f), {}, {}
                    value = 0.0
                    for j in range(T):
                        p, v = float(probabilities[b, h, i, j]), float(V[b, h, j, f])
                        inputs[f"p{j}"], inputs[f"v{j}"] = p, v
                        product = finite(p * v, "head value product")
                        products[f"product{j}"] = product
                        value = finite(value + product, "head value running sum")
                        running[f"running{j}"] = value
                    OHeads[b, h, i, f] = value
                    aliases[f"oh{b}{h}{i}{f}"] = value
                    trace.add(f"head_mix_{b}_{h}_{i}_{f}", f"Head output [{b},{h},{i},{f}]",
                              "product_j=p_j*v_j; running starts at 0; running_j=previous+product_j; value=last running sum",
                              "Use this head's actual probability row and value feature. Every key contributes its product, including masked 0*V, followed immediately by its running sum.",
                              inputs, {**products, **running, "value": value})
    axes = ["B", "H", "Query", "Key"]
    tensors = [tensor("raw", list(shape), axes, raw, "Per-head query-key products, summed before scaling."),
               tensor("scores", list(shape), axes, scores, "Raw dot products divided by sqrt(Dk)."),
               tensor("allowed", list(shape), axes, allowed, "Boolean allowed-key masks; validity is shared across B and H; queries remain."),
               tensor("logits", list(shape), axes, logits, "Finite score+common shift for every key, including forbidden keys; no infinity sentinel."),
               tensor("probabilities", list(shape), axes, probabilities, "Per-batch/head/query stable softmax along allowed keys only."),
               tensor("OHeads", [B, H, T, Dv], ["B", "H", "Query", "Dv"], OHeads,
                      "Actual per-head weighted values: ascending key products and sequential sums from zero.")]
    return dict(raw=raw, scores=scores, allowed=allowed, logits=logits, probabilities=probabilities,
                OHeads=OHeads, aliases=aliases, tensors=tensors)


def join_heads(s, attended, trace):
    """Copy OHeads into C in head/feature order, then compute every C*WO term."""
    B, T, H, Dv = (s[key] for key in ("B", "T", "H", "Dv"))
    OHeads = attended["OHeads"]
    C = np.empty((B, T, H*Dv), dtype=np.float64)
    aliases = {}
    for b in range(B):
        for t in range(T):
            for h in range(H):
                for f in range(Dv):
                    c = h * Dv + f
                    source_offset = ((b * H + h) * T + t) * Dv + f
                    destination_offset = (b * T + t) * (H * Dv) + c
                    value = finite(OHeads[b, h, t, f], "head output to concatenate")
                    C[b, t, c] = value
                    aliases[f"c{b}{t}{c}"] = value
                    trace.add(f"concat_{b}_{t}_{h}_{f}", f"Joined feature [{b},{t},{c}] from head {h}, feature {f}",
                              "C[b,t,h*Dv+f]=OHeads[b,h,t,f]",
                              "Copy the actual head output unchanged; concatenation rearranges coordinates and never averages heads.",
                              dict(b=b, t=t, h=h, f=f, concatFeature=c, sourceOffset=source_offset,
                                   destinationOffset=destination_offset, sourceValue=value), dict(value=value))
    WO = np.empty((H*Dv, 2), dtype=np.float64)
    for h in range(H):
        for f in range(Dv):
            for d in range(2):
                WO[h*Dv+f, d] = s[f"wo{h}{f}{d}"]
    Y = np.empty((B, T, 2), dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                inputs, products, running = dict(b=b, t=t, d=d), {}, {}
                value = 0.0
                for c in range(H*Dv):
                    coordinate, weight = float(C[b, t, c]), float(WO[c, d])
                    inputs[f"c{c}"], inputs[f"w{c}"] = coordinate, weight
                    product = finite(coordinate * weight, "output projection product")
                    products[f"product{c}"] = product
                    value = finite(value + product, "output projection running sum")
                    running[f"running{c}"] = value
                Y[b, t, d] = value
                aliases[f"y{b}{t}{d}"] = value
                trace.add(f"output_{b}_{t}_{d}", f"Output [{b},{t},{d}]: joined values times WO",
                          "product_c=c_c*w_c; running starts at 0; running_c=previous+product_c; value=last running sum",
                          "Pack WO rows by h*Dv+f, retaining parameter identity as Dv changes. Products and immediate running sums follow ascending joined features. Signed output is allowed; no output normalization is added.",
                          inputs, {**products, **running, "value": value})
    tensors = [tensor("C", [B, T, H*Dv], ["B", "T", "JoinedValue"], C, "Head/within-head feature concatenation of actual OHeads, preserving each copied value."),
               tensor("WO", [H*Dv, 2], ["JoinedValue", "D"], WO, "Named output parameters packed in head/feature row order h*Dv+f."),
               tensor("Y", [B, T, 2], ["B", "T", "D"], Y, "C times WO via explicit scalar products and sequential running sums; no output softmax.")]
    return dict(C=C, WO=WO, Y=Y, aliases=aliases, tensors=tensors)


_JSON_INT = int


def run(derive, defaults):
    """No argument uses defaults; JSON replaces all fields; '-' reads stdin."""
    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=(",", ":")))

8. Normalization and residuals — code/python/p07/component_reference.py. feature_norm records means, centered features, squared deviations, population variance and epsilon-inside-root division. same_shape_add checks matching shapes before residual addition. These feature-local operations explain why no new token can affect an earlier row through a normalization or residual broadcast.

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 VII component kernels: real NumPy storage, explicit float operations.

Keep this file beside iv30.py and iv31.py. NumPy represents actual shaped arrays;
Python floats perform each product/addition/division separately in signed trace
order. No matmul, vector reduction, broadcast, fused multiply-add or hidden norm.
Authored under the resource hold: this source has NOT been executed or validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


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


def finite(value, label):
    """Reject booleans, numeric strings, complex numbers and nonfinite scalars."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


RESIDUAL_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
    w00=0.5, w01=0, w10=0, w11=-0.5, b0=0, b1=0,
    g000=1, g001=2, g010=1, g011=2, g020=1, g021=2,
    g100=1, g101=2, g110=1, g111=2, g120=1, g121=2,
    residual=1,
))
NORM_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=3, x001=1, x010=2, x011=2, x020=-1, x021=1,
    x100=1, x101=-1, x110=0, x111=0, x120=-2, x121=3,
    gamma0=1, gamma1=1, beta0=0, beta1=0, epsilon=3,
))


def component_state(state, stage):
    """Validate all 33/19 own fields, including inactive X/g, before selecting."""
    if type(stage) is not int or stage not in (30, 31):
        raise NumericalFault("INVALID_INPUT", "Use component stage 30 or 31.")
    defaults = RESIDUAL_DEFAULTS if stage == 30 else NORM_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), residual=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (1e-8, 4) if key == "epsilon" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


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


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class ComponentTrace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        # Finite clones detach each saved operand/result from mutable arrays/state.
        inputs, values = numbers(inputs), numbers(values)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})

    def result(self, summary, tensors):
        # Aliases first, then ALL flattened step outputs in their insertion order.
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def component_trace():
    return ComponentTrace()


def tensor(identifier, shape, axes, values, provenance):
    """Platform-style float64 boundary: explicit named shape and dense flat list."""
    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 type(values) is not list or len(values) != math.prod(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match dimensions.")
    flat = [finite(value, f"{identifier}[{n}]") for n, value in enumerate(values)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="float64",
                values=flat, provenance=provenance, precision=8)


def same_shape_add(identifier, left, right):
    """Add validated float64 TensorRecords; equal element count is insufficient."""
    checked = []
    for n, record in enumerate((left, right)):
        if type(record) not in (dict, MappingProxyType) or record.get("dtype") != "float64":
            raise NumericalFault("INVALID_INPUT", f"{identifier}: operand {n} must be a float64 tensor.")
        checked.append(tensor(record.get("id"), record.get("shape"), record.get("axes"),
                              record.get("values"), record.get("provenance")))
    a, b = checked
    if a["shape"] != b["shape"] or a["axes"] != b["axes"]:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: addition needs identical dimensions and named axes; no broadcasting.")
    values = [finite(value + b["values"][n], f"{identifier}[{n}]") for n, value in enumerate(a["values"])]
    return tensor(identifier, a["shape"], a["axes"], values,
                  f"Exact named-shape addition of {left['id']} and {right['id']}; no broadcasting.")


def feature_norm(kind, prefix, x, gamma, beta, epsilon, trace):
    """Normalize one width-two token; no chapter bounds on derived IV33 rows.

    Inputs are dense lists, as in the TS kernel. Validate beta even for RMS,
    then deliberately omit it from RMS arithmetic and feature trace inputs.
    """
    if kind not in ("layer", "rms"):
        raise NumericalFault("INVALID_INPUT", "Use layer or rms normalization.")
    checked = []
    for name, values in (("x", x), ("gamma", gamma), ("beta", beta)):
        if type(values) is not list or len(values) != 2:
            raise NumericalFault("SHAPE_MISMATCH", f"{name} needs exactly two dense features.")
        checked.append([finite(value, f"{name}[{d}]") for d, value in enumerate(values)])
    x, gamma, beta = checked
    epsilon = finite(epsilon, "epsilon")
    if epsilon <= 0:
        raise NumericalFault("INVALID_INPUT", "epsilon must be strictly positive.")
    statistics = {}
    if kind == "layer":
        # Population variance: two centered squares, then sum, then divide by 2.
        statistics["sum"] = finite(x[0] + x[1], "feature sum")
        statistics["mean"] = finite(statistics["sum"] / 2, "feature mean")
        statistics["centered0"] = finite(x[0] - statistics["mean"], "centered0")
        statistics["centered1"] = finite(x[1] - statistics["mean"], "centered1")
        statistics["square0"] = finite(statistics["centered0"] * statistics["centered0"], "centered square0")
        statistics["square1"] = finite(statistics["centered1"] * statistics["centered1"], "centered square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "centered square sum")
        statistics["variance"] = finite(statistics["squareSum"] / 2, "population variance")
        statistics["variancePlusEpsilon"] = finite(statistics["variance"] + epsilon, "variance plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["variancePlusEpsilon"]), "LN denominator")
        source = [statistics["centered0"], statistics["centered1"]]
    else:
        # RMS uses original features, with neither mean subtraction nor beta.
        statistics["square0"] = finite(x[0] * x[0], "square0")
        statistics["square1"] = finite(x[1] * x[1], "square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "square sum")
        statistics["meanSquare"] = finite(statistics["squareSum"] / 2, "mean square")
        statistics["meanSquarePlusEpsilon"] = finite(statistics["meanSquare"] + epsilon, "mean square plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["meanSquarePlusEpsilon"]), "RMS denominator")
        source = list(x)
    trace.add(f"{prefix}_statistics", f"{prefix}: feature-only statistics",
              "mean=(x0+x1)/2; variance=(centered0²+centered1²)/2; denominator=sqrt(variance+epsilon)" if kind == "layer" else
              "meanSquare=(x0²+x1²)/2; denominator=sqrt(meanSquare+epsilon)",
              "Only this token's two features contribute. Epsilon stays inside the square root.",
              dict(x0=x[0], x1=x[1], epsilon=epsilon), statistics)
    normalized, values = [], []
    for d in range(2):
        n = finite(source[d] / statistics["denominator"], "normalized feature")
        scaled = finite(gamma[d] * n, "scaled feature")
        value = finite(scaled + beta[d], "LN affine feature") if kind == "layer" else scaled
        normalized.append(n)
        values.append(value)
        inputs = dict(d=d, source=source[d], denominator=statistics["denominator"], gamma=gamma[d])
        if kind == "layer":
            inputs["beta"] = beta[d]
        trace.add(f"{prefix}_feature_{d}", f"{prefix}: affine feature {d}",
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta" if kind == "layer" else
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled",
                  "LayerNorm uses centered features and beta; scale-only RMS uses original features and no beta.",
                  inputs, dict(normalized=n, scaled=scaled, value=value))
    return dict(values=values, normalized=normalized, statistics=statistics)


_JSON_INT = int


def run(derive, defaults):
    """No argument uses defaults; one JSON argument replaces all; '-' reads stdin."""
    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=(",", ":")))

9. Actual three-coordinate FFN — code/python/p07/ffn_reference.py. feed_forward computes all three hidden preactivations, each ReLU and the output contractions in feature order. The third hidden zero in the hand example comes from these fixed weights; it is not an omitted computation or an extra token.

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 VII position-wise FFN: actual NumPy storage, explicit float order.

D=2 input features -> M=3 hidden features -> D=2 output features. Parameters
are shared across tokens/batches; arithmetic never sums over token positions.
NumPy stores shaped float64 arrays, but every arithmetic operation below uses
Python floats, with finite checks and saved operands/results. No BLAS reduction,
broadcast, fused multiply-add, residual, dropout or output softmax is hidden.
Source only: this program has not been imported, executed or validated.
"""
from types import MappingProxyType
import numpy as np
from component_reference import NORM_DEFAULTS, NumericalFault, finite, tensor


FFN_PARAMETERS = MappingProxyType(dict(
    f100=1, f101=0, f102=1, f110=0, f111=1, f112=-1,
    fb10=0, fb11=0, fb12=0,
    f200=0.5, f201=0, f210=0, f211=-0.5, f220=0.25, f221=0.25,
    fb20=0, fb21=0,
))
FFN_DEFAULTS = MappingProxyType(dict(
    B=NORM_DEFAULTS["B"], T=NORM_DEFAULTS["T"],
    **{key: value for key, value in NORM_DEFAULTS.items() if key.startswith("x")},
    **FFN_PARAMETERS,
))


def ffn_state(state):
    """Validate all 31 exact own scalar fields, including inactive X slots."""
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(FFN_DEFAULTS):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    result = {}
    for key in FFN_DEFAULTS:
        value = finite(state[key], key)
        low, high = (1, 2) if key == "B" else (1, 3) if key == "T" else (-4, 4)
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in ("B", "T") and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in ("B", "T") else value
    return result


def feed_forward(s, input_record, trace, prefix="ffn"):
    """Return seven stage tensors and aliases; the caller owns input_record.

    This reusable kernel accepts finite derived inputs beyond raw [-4,4] bounds.
    It requires exact [B,T,2] dimensions/axes and finite values for all parameters.
    """
    dimensions = []
    for key, maximum in (("B", 2), ("T", 3)):
        value = finite(s.get(key), key)
        if not value.is_integer() or not 1 <= value <= maximum:
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer between 1 and {maximum}.")
        dimensions.append(int(value))
    B, T = dimensions
    parameters = {key: finite(s.get(key), key) for key in FFN_PARAMETERS}
    if type(input_record) not in (dict, MappingProxyType) or input_record.get("dtype") != "float64":
        raise NumericalFault("INVALID_INPUT", "FFN input must be a float64 tensor.")
    checked = tensor(input_record.get("id"), input_record.get("shape"), input_record.get("axes"),
                     input_record.get("values"), input_record.get("provenance"))
    shape, axes = [B, T, 2], ["B", "T", "D"]
    if checked["shape"] != shape or checked["axes"] != axes:
        raise NumericalFault("SHAPE_MISMATCH", "FFN input needs exact [B,T,2] dimensions and B,T,D axes.")
    # NumPy holds real shaped storage; scalar float reads prevent reordered reductions.
    X = np.array(checked["values"], dtype=np.float64).reshape(shape)
    W1, b1 = np.empty((2, 3), dtype=np.float64), np.empty(3, dtype=np.float64)
    W2, b2 = np.empty((3, 2), dtype=np.float64), np.empty(2, dtype=np.float64)
    for d in range(2):
        for m in range(3):
            W1[d, m] = parameters[f"f1{d}{m}"]
    for m in range(3):
        b1[m] = parameters[f"fb1{m}"]
        for d in range(2):
            W2[m, d] = parameters[f"f2{m}{d}"]
    for d in range(2):
        b2[d] = parameters[f"fb2{d}"]
    hidden_shape, hidden_axes = [B, T, 3], ["B", "T", "HiddenFeature"]
    Z, Hidden = np.empty(hidden_shape, dtype=np.float64), np.empty(hidden_shape, dtype=np.float64)
    F = np.empty(shape, dtype=np.float64)
    # Save ALL hidden affines before any activation, in ascending b/t/m order.
    for b in range(B):
        for t in range(T):
            for m in range(3):
                x0, x1 = float(X[b, t, 0]), float(X[b, t, 1])
                w0, w1, bias = float(W1[0, m]), float(W1[1, m]), float(b1[m])
                product0 = finite(x0 * w0, "FFN hidden product0")
                product1 = finite(x1 * w1, "FFN hidden product1")
                summed = finite(product0 + product1, "FFN hidden sum")
                preactivation = finite(summed + bias, "FFN hidden preactivation")
                Z[b, t, m] = preactivation
                trace.add(f"{prefix}_hidden_{b}_{t}_{m}", f"Hidden affine [{b},{t},{m}]",
                          "product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias",
                          "The same input-to-hidden weights and bias are reused at every token; bias is added last.",
                          dict(b=b, t=t, m=m, x0=x0, x1=x1, w0=w0, w1=w1, bias=bias),
                          dict(product0=product0, product1=product1, sum=summed, preactivation=preactivation))
    for b in range(B):
        for t in range(T):
            for m in range(3):
                preactivation = float(Z[b, t, m])
                activation = finite(max(0.0, preactivation), "FFN ReLU")
                Hidden[b, t, m] = activation
                trace.add(f"{prefix}_relu_{b}_{t}_{m}", f"ReLU [{b},{t},{m}]",
                          "activation=max(0,preactivation)",
                          "ReLU keeps positive values and maps negative values and zero to zero; it is not a softmax.",
                          dict(b=b, t=t, m=m, preactivation=preactivation), dict(activation=activation))
    for b in range(B):
        for t in range(T):
            for d in range(2):
                inputs, products, running = dict(b=b, t=t, d=d), {}, {}
                summed = 0.0
                # Each product is immediately accumulated from zero; bias follows all three.
                for m in range(3):
                    h, w = float(Hidden[b, t, m]), float(W2[m, d])
                    inputs[f"h{m}"], inputs[f"w{m}"] = h, w
                    product = finite(h * w, "FFN output product")
                    products[f"product{m}"] = product
                    summed = finite(summed + product, "FFN output running sum")
                    running[f"running{m}"] = summed
                bias = float(b2[d])
                inputs["bias"] = bias
                value = finite(summed + bias, "FFN output")
                F[b, t, d] = value
                trace.add(f"{prefix}_output_{b}_{t}_{d}", f"FFN output [{b},{t},{d}]",
                          "product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias",
                          "Three hidden features are contracted in ascending order. No token sum, residual or output softmax is added.",
                          inputs, {**products, **running, "sum": summed, "value": value})
    aliases = {}
    for name, values, width in (("pre", Z, 3), ("h", Hidden, 3), ("f", F, 2)):
        for b in range(B):
            for t in range(T):
                for coordinate in range(width):
                    aliases[f"{name}{b}{t}{coordinate}"] = float(values[b, t, coordinate])
    tensors = [
        tensor("W1", [2, 3], ["D", "HiddenFeature"], W1.reshape(-1).tolist(), "Shared row weights from two input features to three hidden features."),
        tensor("b1", [3], ["HiddenFeature"], b1.tolist(), "Shared hidden-feature biases, added after the two input products."),
        tensor("Z", hidden_shape, hidden_axes, Z.reshape(-1).tolist(), "Hidden affine preactivations before ReLU."),
        tensor("Hidden", hidden_shape, hidden_axes, Hidden.reshape(-1).tolist(), "ReLU applied separately to each preactivation, including zero -> zero."),
        tensor("W2", [3, 2], ["HiddenFeature", "D"], W2.reshape(-1).tolist(), "Shared row weights from three hidden features back to two output features."),
        tensor("b2", [2], ["D"], b2.tolist(), "Shared output-feature biases, added after the three hidden products."),
        tensor("F", shape, axes, F.reshape(-1).tolist(), "Position-wise FFN output; each token uses the same parameters without token mixing."),
    ]
    return dict(output=tensors[-1], tensors=tensors, aliases=aliases)

Each loader resolves dependencies from its own __file__, not the working directory. The tiny helper temporarily binds the intended component_reference while loading the existing FFN, then restores the previous module binding. Independently loaded numerical-fault classes are handled at the new wrapper boundary. A caller does not need an unrelated file from the current directory to supply a hidden primitive.

All declared source_self_check routines require explicit calls; normal queries are not self-check runs. The existing IV-39 check calls its BPE check internally, so a check plan must count that nested call once rather than also explicitly run a second BPE instance’s check. Neither displaying the closure nor reading those declarations is execution evidence.

Explain the five actual graded checks

These explanations follow the lab’s five questions in order. The live questions read the current derived record, including its stopped/nonstopped branch; they do not substitute a row selected by an independent inspector. Choose an option in the lab to see corrective feedback explaining the mechanism.

  1. What does prefill mean in this walkthrough? Process every actual prompt ID with fixed parameters before the external append/stop decision. The current prompt count is the number entering that first forward call. Prefill does not train until a loss vanishes, and this implementation creates no K/V cache.
  2. Which novel-input count and total token-row work agree with the saved calls? Read newTokensConsumed, prefillWorkTokens and decodeWorkTokens. For a non-EOS supplied ID they are1, N and N+1; reset gives1,2,3. For EOS they are0,N,0; reset with EOS gives0,2,0. Gaining one logical result ID does not guarantee a new neural input: terminal EOS stops before that call. Conversely, one novel non-EOS ID does not imply only one computed row in an uncached implementation. No absent Decode result should be filled with zeros.
  3. Which positions and score-cell counts match the current calls? For a non-EOS append, prefill positions are0 through N−1, and decode positions0 through N. The appended slot keeps absolute position N; score counts are N² and (N+1)². At reset these are positions0,1 then0,1,2 and score counts4 then9. On EOS only the prefill positions and N² cells exist; logical append slot N receives no RoPE/attention processing, and decode score work is0. The causal mask controls permissions without eliminating the generic kernel’s recorded future raw score cells.
  4. Which statement respects the actual prefix comparisons, or the stopped result? Read the current prefillNextID separately from your supplied nextID. At reset the model’s prefill winner is b while you append a. For non-EOS, the Y/logit/P maxima come from complete actual before/after operands; causality preserves earlier dependent rows with parameters, IDs and positions fixed. Do not demand identical future raw score cells or metadata. On EOS the original prefill prediction remains inspectable, while there is no decode prediction or comparison to invent. Neither branch replaces your external decision with an argmax or asserts its selection probability.
  5. With text=ab, merges=2 and nextID=256, which logical result and reconstruction survive? Retain [256,256] and decode abab. Appending the selected piece does not rerun BPE across its boundary. [257] belongs to the different operation of freshly tokenizing the decoded characters. The full constant-embedding calculation above explains the actual two-ID forward case; a learned piece is not silently converted into EOS.

Recap and bridge

  • Prefill calculates the given prompt; one non-EOS ID extends that fixed token prefix at absolute position N.
  • This uncached reference recomputes N+1 rows while consuming only one novel ID.
  • A causal mask preserves earlier output rows; it does not implement a cache.
  • Piece IDs survive appending even when fresh tokenization of the decoded characters would differ.
  • EOS is terminal here and produces no second forward call.

Next, IV-45 isolates the decision between active output classes: turn actual logits into probabilities, then choose a token using an explicit deterministic rule.