The neural notebook
← All chapters

IV-49 / Part XII · KV Cache

Cached Versus Uncached Decoding

Compare a genuine one-row cached append with an independent full-prefix forward, deriving ab plus a, absolute-position masks, actual error evidence and honest work counts.

Review the ideas this chapter uses

Two calculations can answer the same next-token question while doing different amounts of work. One retains the prompt’s keys and values; the other recalculates every observed row. We will give both calculations exactly the same token IDs, parameters and absolute positions, then compare their actual saved answers.

Learning objective: Independently compute cached and full-prefix outputs for each step.

Compute it yourself

Cached Versus Uncached Decoding

Prefill the actual prompt once, then supply one observed public ID. For non-EOS input the record contains both a genuine one-query append and an independent full-prefix append. Select either saved path to inspect it. EOS instead stops after logical append and strict decoding. These hand-set parameters are untrained.

promptTokens2
cacheEntries3
cachedNewQueryRows1
comparisonAvailable1

Use raw a/b letters only: at most six UTF-8 bytes and one or two actual BPE prompt tokens. Empty text is UNAVAILABLE. All 27 numeric fields validate, including nextID and inactive model entries. Choose an active public ID; EOS stops without append neural work. No seed or generated-choice control is used.

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

promptTokens 2. cacheEntries 3. cachedNewQueryRows 1. comparisonAvailable 1. Validate all raw fields before text semantics; tokenize exactly once. All numeric parameters and nextID validate before Unicode/domain interpretation, even when nextID is EOS. Both real comparison paths share one actual full-prefill call.

Validate all raw fields before text semantics; tokenize exactly once

N=actual prompt tokens1..2; nextID is external observed input; active V=3+merges

All numeric parameters and nextID validate before Unicode/domain interpretation, even when nextID is EOS. Both real comparison paths share one actual full-prefill call.

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
tokenBound
2
promptTokens
2
classCount
3

One actual prefill, then a controlled observed append

Exact input "ab" encoded once as [97,98]. Supplied observed ID=a / ID97. Logical result [97,98,97]; strict reconstruction "aba", bytes [97,98,97].

External observed input; not asserted to be a model-generated selection. A generator can later feed its selected public ID into the same append primitive. Prefill predicts b / ID98, stored probability=0.7234156524931242. That prediction is never substituted for your supplied ID.

IV-49 actual neural work — stored values without display rounding
Actual saved callNeural query rowsRaw score cells
Shared full prefill24
Cached append13
Independent full append39
Actual harness total616

Cold logical path rows=3 cached / 5 full. They share prefill and cannot be added as actual harness work. The toy counts query rows and raw score cells, including full-call future scores; they measure no latency. Cached attention still reads the whole available prefix.

Inspecting cached, absolute query 2, key 0, compact class 0. Inspection only reads the saved record; it leaves the trace cursor and graded answers unchanged.

Selected trace operation: setup. Matching arithmetic rows are marked current.

Coherent cache captured from the actual shared prefill

prefill_CacheKeys [1,1,2,2] · B,H,CachePosition,Dk · float64 · precision 8 · Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

prefill_CacheValues [1,1,2,2] · B,H,CachePosition,Dv · float64 · precision 8 · Saved unrotated projected V in observed-prefix order.

Coherent cache captured from the actual shared prefill — stored values without display rounding
Cache rowObserved public IDAbsolute positionAlready rotated K0K1Unrotated V0V1
0a / ID9700.4472135954999579-0.44721359549995790.4472135954999579-0.4472135954999579
1b / ID981-0.6179478014890387-0.1346867277606211-0.44721359549995790.4472135954999579
Actual prefill capture operands
IV-49 real prefill capture — stored values without display rounding
Saved operation / equationActual inputsActual outputs
prefill_capture

cache.K=RotatedKHeads; cache.V=ProjectionVHeads; positions=0..N-1

The constructor establishes coherence from real forward outputs. It retains no old queries, hidden rows, logits or probabilities in the cache. Full prefill evidence remains separately saved.

N=2
inputID0=97
inputID1=98
rotatedK0=0.4472135954999579
rotatedK1=-0.4472135954999579
rotatedK2=-0.6179478014890387
rotatedK3=-0.1346867277606211
projectedV0=0.4472135954999579
projectedV1=-0.4472135954999579
projectedV2=-0.4472135954999579
projectedV3=0.4472135954999579
cacheEntries=2
id0=97
position0=0
id1=98
position1=1
key0=0.4472135954999579
key1=-0.4472135954999579
key2=-0.6179478014890387
key3=-0.1346867277606211
value0=0.4472135954999579
value1=-0.4472135954999579
value2=-0.4472135954999579
value3=0.4472135954999579

Detached cache before actual append

cached_BeforeKeys [1,1,2,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

cached_BeforeValues [1,1,2,2] · B,H,CachePosition,Dv · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.

Detached cache before actual append — stored values without display rounding
Cache rowObserved public IDAbsolute positionAlready rotated K0K1Unrotated V0V1
0a / ID9700.4472135954999579-0.44721359549995790.4472135954999579-0.4472135954999579
1b / ID981-0.6179478014890387-0.1346867277606211-0.44721359549995790.4472135954999579

Actual cache after one new row

cached_AfterKeys [1,1,3,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

cached_AfterValues [1,1,3,2] · B,H,CachePosition,Dv · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.

Actual cache after one new row — stored values without display rounding
Cache rowObserved public IDAbsolute positionAlready rotated K0K1Unrotated V0V1
0a / ID9700.4472135954999579-0.44721359549995790.4472135954999579-0.4472135954999579
1b / ID981-0.6179478014890387-0.1346867277606211-0.44721359549995790.4472135954999579
2a / ID9720.220543648601392170.59275669465775380.4472135954999579-0.4472135954999579
Actual append and unchanged-copy operands
IV-49 actual retained copies — stored values without display rounding
Saved operation / equationActual inputsActual outputs
cached_append

after=[before,new]; retained_i=(before_i===after_i)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Same-implementation retained-copy equality is a narrow check, separate from cross-library numerical witnesses. Empty-before has metadata only, never a zero-shape tensor.

N=2
newID=97
newK0=0.22054364860139217
newK1=0.5927566946577538
newV0=0.4472135954999579
newV1=-0.4472135954999579
beforeID0=97
beforeID1=98
beforePosition0=0
beforePosition1=1
beforeK0=0.4472135954999579
beforeK1=-0.4472135954999579
beforeK2=-0.6179478014890387
beforeK3=-0.1346867277606211
beforeV0=0.4472135954999579
beforeV1=-0.4472135954999579
beforeV2=-0.4472135954999579
beforeV3=0.4472135954999579
cacheEntries=3
retainedID0=1
retainedID1=1
afterID0=97
afterID1=98
afterID2=97
retainedPosition0=1
retainedPosition1=1
afterPosition0=0
afterPosition1=1
afterPosition2=2
retainedK0=1
retainedK1=1
retainedK2=1
retainedK3=1
afterK0=0.4472135954999579
afterK1=-0.4472135954999579
afterK2=-0.6179478014890387
afterK3=-0.1346867277606211
afterK4=0.22054364860139217
afterK5=0.5927566946577538
retainedV0=1
retainedV1=1
retainedV2=1
retainedV3=1
afterV0=0.4472135954999579
afterV1=-0.4472135954999579
afterV2=-0.4472135954999579
afterV3=0.4472135954999579
afterV4=0.4472135954999579
afterV5=-0.4472135954999579
retainedExact=1

cached: actual query at absolute position 2

B=1 batch, H=1 head, D=Dk=Dv=2 features; FFN hidden width3; active V=3. Local query0 is the one new row; old queries are absent from this call.

cached_RotatedQHeads [1,1,1,2] · B,H,Query,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New query rotated at absolute N; Query length1.

cached_AfterKeys [1,1,3,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

cached_Attentionprobabilities [1,1,1,3] · B,H,Query,Key · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.

cached selected feature row — stored values without display rounding
Saved stageFeature0Feature1
X10
LN10.4472135954999579-0.4472135954999579
AttentionOutput0.19749416642975512-0.19749416642975512
R11.1974941664297551-0.19749416642975512
LN20.5720821519582194-0.5720821519582194
F0.57208215195821940
Y1.7695763183879745-0.19749416642975512

R1=X+attention output; LN2 normalizes that row; the full three-coordinate ReLU FFN produces F; Y=R1+F. Both layer norms use population variance, epsilon1 inside the square root, gamma1 and beta0.

cached actual rotations — stored values without display rounding
PairAbsolute positionUnrotated pairAngleCosineSineRotated pair
Q2[0.4472135954999579,-0.4472135954999579]2-0.41614683654714240.9092974268256817[0.22054364860139217,0.5927566946577538]
K2[0.4472135954999579,-0.4472135954999579]2-0.41614683654714240.9092974268256817[0.22054364860139217,0.5927566946577538]

The K rotation row above is only the newly appended key. Earlier keys below were already rotated in their saved prefixes; they are not rotated again. V stays unrotated.

cached query 2 attention — stored values without display rounding
Key / observed IDRotated K pairRaw dotScaled scoreAllowed?Attention probabilityUnrotated V pair
0 / a / ID97[0.4472135954999579,-0.4472135954999579]-0.1664587346188569-0.11770410003672563true — allowed0.2891733251316062[0.4472135954999579,-0.4472135954999579]
1 / b / ID98[-0.6179478014890387,-0.1346867277606211]-0.21612092234725588-0.15282056974803587true — allowed0.2791948093517053[-0.4472135954999579,0.4472135954999579]
2 / a / ID97[0.22054364860139217,0.5927566946577538]0.399999999999999970.28284271247461895true — allowed0.43163186551668853[0.4472135954999579,-0.4472135954999579]

The mask means allowed=true when absolute key≤absolute query. All available keys are allowed on a cached append. A full call retains raw future scores but assigns forbidden probabilities exact zero. Scores divide the two-product dot by sqrt2; the mixtures multiply and immediately accumulate unrotated V in key order.

cached selected score and normalization — stored values without display rounding
Saved operation / equationActual inputsActual outputs
cached_score_0

product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The query axis has length1; the key axis has length N+1. Only this new query is evaluated.

position=2
j=0
Dk=2
divisor=1.4142135623730951
q0=0.22054364860139217
k0=0.4472135954999579
q1=0.5927566946577538
k1=-0.4472135954999579
product0=0.09863011805570786
product1=-0.2650888526745648
raw=-0.1664587346188569
score=-0.11770410003672563
cached_row

logit=score+0; allowed=(keyPosition<=N); max=max(allowed logits); term=exp(logit-max); running starts0; p=term/denominator

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. All available positions0..N are allowed. Comparing keys to local query0 would be wrong. Every shift, exponential and left-to-right running sum is retained.

position=2
shift=0
score0=-0.11770410003672563
keyPosition0=0
allowed0=1
score1=-0.15282056974803587
keyPosition1=1
allowed1=1
score2=0.28284271247461895
keyPosition2=2
allowed2=1
max=0.28284271247461895
logit0=-0.11770410003672563
shifted0=-0.4005468125113446
term0=0.6699536068437599
running0=0.6699536068437599
logit1=-0.15282056974803587
shifted1=-0.4356632822226548
term1=0.646835490279414
running1=1.316789097123174
logit2=0.28284271247461895
shifted2=0
term2=1
running2=2.316789097123174
denominator=2.316789097123174
p0=0.2891733251316062
p1=0.2791948093517053
p2=0.43163186551668853
cached_mix_0

product_j=p_j*v_j; running starts0; running_j=previous+product_j; value=last running

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order.

d=0
p0=0.2891733251316062
v0=0.4472135954999579
p1=0.2791948093517053
v1=-0.4472135954999579
p2=0.43163186551668853
v2=0.4472135954999579
product0=0.12932224245478396
running0=0.12932224245478396
product1=-0.12485971453510142
running1=0.004462527919682546
product2=0.19303163851007257
running2=0.19749416642975512
value=0.19749416642975512
cached_mix_1

product_j=p_j*v_j; running starts0; running_j=previous+product_j; value=last running

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order.

d=1
p0=0.2891733251316062
v0=-0.4472135954999579
p1=0.2791948093517053
v1=0.4472135954999579
p2=0.43163186551668853
v2=-0.4472135954999579
product0=-0.12932224245478396
running0=-0.12932224245478396
product1=0.12485971453510142
running1=-0.004462527919682546
product2=-0.19303163851007257
running2=-0.19749416642975512
value=-0.19749416642975512
cached complete hidden FFN row — stored values without display rounding
Hidden coordinateAffine ZReLU activation
00.57208215195821940.5720821519582194
1-0.57208215195821940
200

cached_Logits [1,3] · Position,Class · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual new Y times active U, then active Bias.

cached_ChoiceP [3] · Class · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.

cached query 2 active class distribution — stored values without display rounding
Compact class / public IDLogitShifted logitExponential termStored probability
0 / a / ID971.7695763183879745010.7632007976561935
1 / b / ID98-0.19749416642975512-1.96707048481772960.13986599619088480.1067458398578614
2 / EOS / ID5120-1.76957631838797450.170405171070761360.13005336248594518

Saved maximum=1.7695763183879745, denominator=1.310271167261646, logS=0.2702341137016024, LSE=2.0398104320895767. Winner=a / ID97; probability=0.7632007976561935. Argmax uses strict computed logits and lowest compact index for exact ties. This winner does not select the observed input.

cached selected readout and stable class normalization — stored values without display rounding
Saved operation / equationActual inputsActual outputs
cached_readout_0

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only V=3+merges active columns are output classes; all five storage columns were validated.

c=0
y0=1.7695763183879745
u0=1
y1=-0.19749416642975512
u1=0
bias=0
product0=1.7695763183879745
product1=0
sum=1.7695763183879745
logit=1.7695763183879745
cached_class_max

max=max(z0,...,z[V-1])

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.

z0=1.7695763183879745
z1=-0.19749416642975512
z2=0
max=1.7695763183879745
cached_class_exp_0

shifted=logit-max; term=exp(shifted)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.

c=0
logit=1.7695763183879745
max=1.7695763183879745
shifted=0
term=1
cached_class_normalize

running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The denominator adds terms in ascending compact class order. Every actual running sum is saved.

term0=1
term1=0.1398659961908848
term2=0.17040517107076136
max=1.7695763183879745
running0=1
running1=1.1398659961908848
running2=1.310271167261646
denominator=1.310271167261646
logS=0.2702341137016024
lse=2.0398104320895767
cached_class_probability_0

probability=term/S

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. This stored binary64 probability is displayed without feeding its formatting back into arithmetic.

c=0
term=1
denominator=1.310271167261646
probability=0.7632007976561935
cached_class_argmax

strict greater-than updates the winner; exact ties retain lowest compact index

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order.

z0=1.7695763183879745
z1=-0.19749416642975512
z2=0
nextRow=0
nextID=97
nextProbability=0.7632007976561935
Every actual operation in this saved path, including every coordinate

No neural arithmetic is reconstructed in this view. These are all saved operands, products, sums, copy offsets, masks and results for normalization, Q/K/V projection, rotations, attention, output projection, residuals, hidden3 FFN and readout.

cached complete arithmetic — stored values without display rounding
Saved operation / equationActual inputsActual outputs
cached_input_0

inputRow=compactRow(newID); X=E[inputRow,:]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Numeric helpers permit observed EOS; outer wrappers separately implement logical EOS stopping.

position=2
newID=97
inputRow=0
x0=1
x1=0
cached_ln1_0_statistics

sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed.

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
cached_ln1_0_feature_0

normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The source is the saved centered feature. Gamma and beta may change output mean and variance.

d=0
source=0.5
denominator=1.118033988749895
gamma=1
beta=0
normalized=0.4472135954999579
scaled=0.4472135954999579
value=0.4472135954999579
cached_ln1_0_feature_1

normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The source is the saved centered feature. Gamma and beta may change output mean and variance.

d=1
source=-0.5
denominator=1.118033988749895
gamma=1
beta=0
normalized=-0.4472135954999579
scaled=-0.4472135954999579
value=-0.4472135954999579
cached_heads_setup

D=2; X[B,T,2]; WQ,WK[2,H*Dk]; WV[2,H*Dv]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights.

B=1
T=1
H=1
Dk=2
Dv=2
x000=0.4472135954999579
x001=-0.4472135954999579
x010=0
x011=1
x020=1
x021=1
x100=1
x101=1
x110=-1
x111=0
x120=0
x121=2
wq000=1
wq001=0
wq010=0
wq011=1
wq100=0
wq101=1
wq110=1
wq111=0
wk000=1
wk001=0
wk010=0
wk011=1
wk100=0
wk101=1
wk110=1
wk111=0
wv000=1
wv001=0
wv010=0
wv011=1
wv100=0
wv101=1
wv110=1
wv111=0
mode=1
valid0=1
valid1=1
valid2=1
shift=0
wo000=1
wo001=0
wo010=0
wo011=1
wo100=1
wo101=-1
wo110=0
wo111=0.5
B=1
T=1
D=2
H=1
Dk=2
Dv=2
cached_heads_project_Q_0_0_0_0

product0=x0*w0; product1=x1*w1; value=product0+product1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.

b=0
t=0
h=0
f=0
x0=0.4472135954999579
x1=-0.4472135954999579
w0=1
w1=0
product0=0.4472135954999579
product1=0
value=0.4472135954999579
cached_heads_project_Q_0_0_0_1

product0=x0*w0; product1=x1*w1; value=product0+product1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.

b=0
t=0
h=0
f=1
x0=0.4472135954999579
x1=-0.4472135954999579
w0=0
w1=1
product0=0
product1=-0.4472135954999579
value=-0.4472135954999579
cached_heads_project_K_0_0_0_0

product0=x0*w0; product1=x1*w1; value=product0+product1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.

b=0
t=0
h=0
f=0
x0=0.4472135954999579
x1=-0.4472135954999579
w0=1
w1=0
product0=0.4472135954999579
product1=0
value=0.4472135954999579
cached_heads_project_K_0_0_0_1

product0=x0*w0; product1=x1*w1; value=product0+product1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.

b=0
t=0
h=0
f=1
x0=0.4472135954999579
x1=-0.4472135954999579
w0=0
w1=1
product0=0
product1=-0.4472135954999579
value=-0.4472135954999579
cached_heads_project_V_0_0_0_0

product0=x0*w0; product1=x1*w1; value=product0+product1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.

b=0
t=0
h=0
f=0
x0=0.4472135954999579
x1=-0.4472135954999579
w0=1
w1=0
product0=0.4472135954999579
product1=0
value=0.4472135954999579
cached_heads_project_V_0_0_0_1

product0=x0*w0; product1=x1*w1; value=product0+product1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden.

b=0
t=0
h=0
f=1
x0=0.4472135954999579
x1=-0.4472135954999579
w0=0
w1=1
product0=0
product1=-0.4472135954999579
value=-0.4472135954999579
cached_heads_reshape_Q

[B,T,H*F] → [B,T,H,F]; feature=h*F+f

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped.

B=1
T=1
H=1
F=2
features=2
elements=2
elements=2
cached_heads_permute_Q_0_0_0_0

axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.

b=0
h=0
t=0
f=0
feature=0
sourceOffset=0
destinationOffset=0
sourceValue=0.4472135954999579
value=0.4472135954999579
cached_heads_permute_Q_0_0_0_1

axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.

b=0
h=0
t=0
f=1
feature=1
sourceOffset=1
destinationOffset=1
sourceValue=-0.4472135954999579
value=-0.4472135954999579
cached_heads_reshape_K

[B,T,H*F] → [B,T,H,F]; feature=h*F+f

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped.

B=1
T=1
H=1
F=2
features=2
elements=2
elements=2
cached_heads_permute_K_0_0_0_0

axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.

b=0
h=0
t=0
f=0
feature=0
sourceOffset=0
destinationOffset=0
sourceValue=0.4472135954999579
value=0.4472135954999579
cached_heads_permute_K_0_0_0_1

axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.

b=0
h=0
t=0
f=1
feature=1
sourceOffset=1
destinationOffset=1
sourceValue=-0.4472135954999579
value=-0.4472135954999579
cached_heads_reshape_V

[B,T,H*F] → [B,T,H,F]; feature=h*F+f

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped.

B=1
T=1
H=1
F=2
features=2
elements=2
elements=2
cached_heads_permute_V_0_0_0_0

axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.

b=0
h=0
t=0
f=0
feature=0
sourceOffset=0
destinationOffset=0
sourceValue=0.4472135954999579
value=0.4472135954999579
cached_heads_permute_V_0_0_0_1

axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Source is the new LN1 row, local T=1. Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged.

b=0
h=0
t=0
f=1
feature=1
sourceOffset=1
destinationOffset=1
sourceValue=-0.4472135954999579
value=-0.4472135954999579
cached_rope_Q_0

frequency=10000^0; angle=N*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only the new Q/K rotate. Cached K is already rotated and V never rotates. Each product and coordinate is real arithmetic.

position=2
x0=0.4472135954999579
x1=-0.4472135954999579
base=10000
exponent=0
frequency=1
angle=2
cos=-0.4161468365471424
sin=0.9092974268256817
product0=-0.18610652302818084
product1=-0.406650171629573
product2=0.406650171629573
product3=0.18610652302818084
rotated0=0.22054364860139217
rotated1=0.5927566946577538
cached_rope_K_0

frequency=10000^0; angle=N*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only the new Q/K rotate. Cached K is already rotated and V never rotates. Each product and coordinate is real arithmetic.

position=2
x0=0.4472135954999579
x1=-0.4472135954999579
base=10000
exponent=0
frequency=1
angle=2
cos=-0.4161468365471424
sin=0.9092974268256817
product0=-0.18610652302818084
product1=-0.406650171629573
product2=0.406650171629573
product3=0.18610652302818084
rotated0=0.22054364860139217
rotated1=0.5927566946577538
cached_append

after=[before,new]; retained_i=(before_i===after_i)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Same-implementation retained-copy equality is a narrow check, separate from cross-library numerical witnesses. Empty-before has metadata only, never a zero-shape tensor.

N=2
newID=97
newK0=0.22054364860139217
newK1=0.5927566946577538
newV0=0.4472135954999579
newV1=-0.4472135954999579
beforeID0=97
beforeID1=98
beforePosition0=0
beforePosition1=1
beforeK0=0.4472135954999579
beforeK1=-0.4472135954999579
beforeK2=-0.6179478014890387
beforeK3=-0.1346867277606211
beforeV0=0.4472135954999579
beforeV1=-0.4472135954999579
beforeV2=-0.4472135954999579
beforeV3=0.4472135954999579
cacheEntries=3
retainedID0=1
retainedID1=1
afterID0=97
afterID1=98
afterID2=97
retainedPosition0=1
retainedPosition1=1
afterPosition0=0
afterPosition1=1
afterPosition2=2
retainedK0=1
retainedK1=1
retainedK2=1
retainedK3=1
afterK0=0.4472135954999579
afterK1=-0.4472135954999579
afterK2=-0.6179478014890387
afterK3=-0.1346867277606211
afterK4=0.22054364860139217
afterK5=0.5927566946577538
retainedV0=1
retainedV1=1
retainedV2=1
retainedV3=1
afterV0=0.4472135954999579
afterV1=-0.4472135954999579
afterV2=-0.4472135954999579
afterV3=0.4472135954999579
afterV4=0.4472135954999579
afterV5=-0.4472135954999579
retainedExact=1
cached_score_0

product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The query axis has length1; the key axis has length N+1. Only this new query is evaluated.

position=2
j=0
Dk=2
divisor=1.4142135623730951
q0=0.22054364860139217
k0=0.4472135954999579
q1=0.5927566946577538
k1=-0.4472135954999579
product0=0.09863011805570786
product1=-0.2650888526745648
raw=-0.1664587346188569
score=-0.11770410003672563
cached_score_1

product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The query axis has length1; the key axis has length N+1. Only this new query is evaluated.

position=2
j=1
Dk=2
divisor=1.4142135623730951
q0=0.22054364860139217
k0=-0.6179478014890387
q1=0.5927566946577538
k1=-0.1346867277606211
product0=-0.13628446278560138
product1=-0.0798364595616545
raw=-0.21612092234725588
score=-0.15282056974803587
cached_score_2

product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The query axis has length1; the key axis has length N+1. Only this new query is evaluated.

position=2
j=2
Dk=2
divisor=1.4142135623730951
q0=0.22054364860139217
k0=0.22054364860139217
q1=0.5927566946577538
k1=0.5927566946577538
product0=0.04863950093841435
product1=0.3513604990615856
raw=0.39999999999999997
score=0.28284271247461895
cached_row

logit=score+0; allowed=(keyPosition<=N); max=max(allowed logits); term=exp(logit-max); running starts0; p=term/denominator

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. All available positions0..N are allowed. Comparing keys to local query0 would be wrong. Every shift, exponential and left-to-right running sum is retained.

position=2
shift=0
score0=-0.11770410003672563
keyPosition0=0
allowed0=1
score1=-0.15282056974803587
keyPosition1=1
allowed1=1
score2=0.28284271247461895
keyPosition2=2
allowed2=1
max=0.28284271247461895
logit0=-0.11770410003672563
shifted0=-0.4005468125113446
term0=0.6699536068437599
running0=0.6699536068437599
logit1=-0.15282056974803587
shifted1=-0.4356632822226548
term1=0.646835490279414
running1=1.316789097123174
logit2=0.28284271247461895
shifted2=0
term2=1
running2=2.316789097123174
denominator=2.316789097123174
p0=0.2891733251316062
p1=0.2791948093517053
p2=0.43163186551668853
cached_mix_0

product_j=p_j*v_j; running starts0; running_j=previous+product_j; value=last running

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order.

d=0
p0=0.2891733251316062
v0=0.4472135954999579
p1=0.2791948093517053
v1=-0.4472135954999579
p2=0.43163186551668853
v2=0.4472135954999579
product0=0.12932224245478396
running0=0.12932224245478396
product1=-0.12485971453510142
running1=0.004462527919682546
product2=0.19303163851007257
running2=0.19749416642975512
value=0.19749416642975512
cached_mix_1

product_j=p_j*v_j; running starts0; running_j=previous+product_j; value=last running

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate in ascending cached-key order.

d=1
p0=0.2891733251316062
v0=-0.4472135954999579
p1=0.2791948093517053
v1=0.4472135954999579
p2=0.43163186551668853
v2=-0.4472135954999579
product0=-0.12932224245478396
running0=-0.12932224245478396
product1=0.12485971453510142
running1=-0.004462527919682546
product2=-0.19303163851007257
running2=-0.19749416642975512
value=-0.19749416642975512
cached_concat

C[d]=OHeads[0,0,0,d]; sourceOffset=d; destinationOffset=d

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. H=1 still has a real declared copy; both coordinates and offsets are retained.

sourceOffset0=0
sourceValue0=0.19749416642975512
sourceOffset1=1
sourceValue1=-0.19749416642975512
destinationOffset0=0
c0=0.19749416642975512
destinationOffset1=1
c1=-0.19749416642975512
cached_output_0

product0=c0*w0; running0=0+product0; product1=c1*w1; running1=running0+product1; value=running1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Identity WO is actually multiplied in the same order as the full-prefix kernel; neither products nor zero additions are bypassed.

d=0
c0=0.19749416642975512
w0=1
c1=-0.19749416642975512
w1=0
product0=0.19749416642975512
running0=0.19749416642975512
product1=0
running1=0.19749416642975512
value=0.19749416642975512
cached_output_1

product0=c0*w0; running0=0+product0; product1=c1*w1; running1=running0+product1; value=running1

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Identity WO is actually multiplied in the same order as the full-prefix kernel; neither products nor zero additions are bypassed.

d=1
c0=0.19749416642975512
w0=0
c1=-0.19749416642975512
w1=1
product0=0
running0=0
product1=-0.19749416642975512
running1=-0.19749416642975512
value=-0.19749416642975512
cached_residual1

value_d=left_d+right_d

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Exact same named [B,T,D] shapes; no broadcast or hidden coordinate omission.

left0=1
right0=0.19749416642975512
left1=0
right1=-0.19749416642975512
value0=1.1974941664297551
value1=-0.19749416642975512
cached_ln2_0_statistics

sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed.

x0=1.1974941664297551
x1=-0.19749416642975512
epsilon=1
sum=1
mean=0.5
centered0=0.6974941664297551
centered1=-0.6974941664297551
square0=0.48649811220353895
square1=0.48649811220353895
squareSum=0.9729962244070779
variance=0.48649811220353895
variancePlusEpsilon=1.486498112203539
denominator=1.2192202886285723
cached_ln2_0_feature_0

normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The source is the saved centered feature. Gamma and beta may change output mean and variance.

d=0
source=0.6974941664297551
denominator=1.2192202886285723
gamma=1
beta=0
normalized=0.5720821519582194
scaled=0.5720821519582194
value=0.5720821519582194
cached_ln2_0_feature_1

normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The source is the saved centered feature. Gamma and beta may change output mean and variance.

d=1
source=-0.6974941664297551
denominator=1.2192202886285723
gamma=1
beta=0
normalized=-0.5720821519582194
scaled=-0.5720821519582194
value=-0.5720821519582194
cached_ffn_hidden_0_0_0

product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs.

b=0
t=0
m=0
x0=0.5720821519582194
x1=-0.5720821519582194
w0=1
w1=0
bias=0
product0=0.5720821519582194
product1=0
sum=0.5720821519582194
preactivation=0.5720821519582194
cached_ffn_hidden_0_0_1

product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs.

b=0
t=0
m=1
x0=0.5720821519582194
x1=-0.5720821519582194
w0=0
w1=1
bias=0
product0=0
product1=-0.5720821519582194
sum=-0.5720821519582194
preactivation=-0.5720821519582194
cached_ffn_hidden_0_0_2

product0=x0*w0; product1=x1*w1; sum=product0+product1; preactivation=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs.

b=0
t=0
m=2
x0=0.5720821519582194
x1=-0.5720821519582194
w0=0
w1=0
bias=0
product0=0
product1=0
sum=0
preactivation=0
cached_ffn_relu_0_0_0

activation=max(0,preactivation)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.

b=0
t=0
m=0
preactivation=0.5720821519582194
activation=0.5720821519582194
cached_ffn_relu_0_0_1

activation=max(0,preactivation)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.

b=0
t=0
m=1
preactivation=-0.5720821519582194
activation=0
cached_ffn_relu_0_0_2

activation=max(0,preactivation)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself.

b=0
t=0
m=2
preactivation=0
activation=0
cached_ffn_output_0_0_0

product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN.

b=0
t=0
d=0
h0=0.5720821519582194
w0=1
h1=0
w1=0
h2=0
w2=0
bias=0
product0=0.5720821519582194
product1=0
product2=0
running0=0.5720821519582194
running1=0.5720821519582194
running2=0.5720821519582194
sum=0.5720821519582194
value=0.5720821519582194
cached_ffn_output_0_0_1

product_m=h_m*w_m; running starts at 0; running_m=previous+product_m; sum=running2; value=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN.

b=0
t=0
d=1
h0=0.5720821519582194
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
cached_residual2

value_d=left_d+right_d

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Exact same named [B,T,D] shapes; no broadcast or hidden coordinate omission.

left0=1.1974941664297551
right0=0.5720821519582194
left1=-0.19749416642975512
right1=0
value0=1.7695763183879745
value1=-0.19749416642975512
cached_readout_0

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only V=3+merges active columns are output classes; all five storage columns were validated.

c=0
y0=1.7695763183879745
u0=1
y1=-0.19749416642975512
u1=0
bias=0
product0=1.7695763183879745
product1=0
sum=1.7695763183879745
logit=1.7695763183879745
cached_readout_1

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only V=3+merges active columns are output classes; all five storage columns were validated.

c=1
y0=1.7695763183879745
u0=0
y1=-0.19749416642975512
u1=1
bias=0
product0=0
product1=-0.19749416642975512
sum=-0.19749416642975512
logit=-0.19749416642975512
cached_readout_2

product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Only V=3+merges active columns are output classes; all five storage columns were validated.

c=2
y0=1.7695763183879745
u0=0
y1=-0.19749416642975512
u1=0
bias=0
product0=0
product1=0
sum=0
logit=0
cached_class_max

max=max(z0,...,z[V-1])

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.

z0=1.7695763183879745
z1=-0.19749416642975512
z2=0
max=1.7695763183879745
cached_class_exp_0

shifted=logit-max; term=exp(shifted)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.

c=0
logit=1.7695763183879745
max=1.7695763183879745
shifted=0
term=1
cached_class_exp_1

shifted=logit-max; term=exp(shifted)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.

c=1
logit=-0.19749416642975512
max=1.7695763183879745
shifted=-1.9670704848177296
term=0.1398659961908848
cached_class_exp_2

shifted=logit-max; term=exp(shifted)

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.

c=2
logit=0
max=1.7695763183879745
shifted=-1.7695763183879745
term=0.17040517107076136
cached_class_normalize

running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. The denominator adds terms in ascending compact class order. Every actual running sum is saved.

term0=1
term1=0.1398659961908848
term2=0.17040517107076136
max=1.7695763183879745
running0=1
running1=1.1398659961908848
running2=1.310271167261646
denominator=1.310271167261646
logS=0.2702341137016024
lse=2.0398104320895767
cached_class_probability_0

probability=term/S

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. This stored binary64 probability is displayed without feeding its formatting back into arithmetic.

c=0
term=1
denominator=1.310271167261646
probability=0.7632007976561935
cached_class_probability_1

probability=term/S

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. This stored binary64 probability is displayed without feeding its formatting back into arithmetic.

c=1
term=0.1398659961908848
denominator=1.310271167261646
probability=0.1067458398578614
cached_class_probability_2

probability=term/S

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. This stored binary64 probability is displayed without feeding its formatting back into arithmetic.

c=2
term=0.17040517107076136
denominator=1.310271167261646
probability=0.13005336248594518
cached_class_argmax

strict greater-than updates the winner; exact ties retain lowest compact index

True one-query append: local row0 is absolute position 2; no prior query or old K/V projection is recomputed. Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order.

z0=1.7695763183879745
z1=-0.19749416642975512
z2=0
nextRow=0
nextID=97
nextProbability=0.7632007976561935
All saved path tensor shapes and provenance

cached_AllClassIDs [5] · ModelRow · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All possible compact model rows; public IDs are labels.

cached_ClassIDs [3] · Class · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Active compact prefix; V=3+merges.

cached_E [5,2] · ModelRow,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All ten validated editable embeddings, including inactive rows.

cached_U [2,5] · D,ModelRow · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All ten validated readout weights; active prefix alone produces logits.

cached_Bias [5] · ModelRow · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All five validated biases; inactive columns remain outside the distribution.

cached_InputIDs [1] · LocalPosition · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Exactly one new observed token is processed.

cached_InputRows [1] · LocalPosition · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Compact embedding row for the new token.

cached_AbsoluteQueryPosition [1] · Query · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Absolute N, distinct from the single local query index0.

cached_BeforeIDs [2] · CachePosition · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.

cached_BeforePositions [2] · CachePosition · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.

cached_BeforeKeys [1,1,2,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

cached_BeforeValues [1,1,2,2] · B,H,CachePosition,Dv · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.

cached_X [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Only the new embedding row; local T=1, absolute position is saved separately.

cached_LN1 [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.

cached_ProjectionX [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Active token rows; D=2 input features always retained.

cached_ProjectionWQ [2,2] · D,QueryFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Query columns packed by h*Dk+f from wq{d}{h}{f}.

cached_ProjectionWK [2,2] · D,KeyFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Key columns packed by h*Dk+f from wk{d}{h}{f}.

cached_ProjectionWV [2,2] · D,ValueFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Value columns packed by h*Dv+f from wv{d}{h}{f}.

cached_ProjectionQConcat [1,1,2] · B,T,QueryFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWQ; each packed coordinate has two products and one sum.

cached_ProjectionKConcat [1,1,2] · B,T,KeyFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWK; each packed coordinate has two products and one sum.

cached_ProjectionVConcat [1,1,2] · B,T,ValueFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWV; values are projected separately from queries and keys.

cached_ProjectionQSplit [1,1,1,2] · B,T,H,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. QConcat reshaped without changing flat order; feature=h*F+f.

cached_ProjectionQHeads [1,1,1,2] · B,H,T,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

cached_ProjectionKSplit [1,1,1,2] · B,T,H,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. KConcat reshaped without changing flat order; feature=h*F+f.

cached_ProjectionKHeads [1,1,1,2] · B,H,T,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

cached_ProjectionVSplit [1,1,1,2] · B,T,H,Dv · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. VConcat reshaped without changing flat order; feature=h*F+f.

cached_ProjectionVHeads [1,1,1,2] · B,H,T,Dv · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

cached_RotatedQHeads [1,1,1,2] · B,H,Query,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New query rotated at absolute N; Query length1.

cached_NewRotatedKHeads [1,1,1,2] · B,H,NewPosition,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Only the newly computed key, rotated once at absolute N.

cached_RoPEAngles [1] · Query · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual absolute N times frequency1, radians.

cached_RoPECos [1] · Query · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Cosine used by new Q/K rotations.

cached_RoPESin [1] · Query · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Sine used by new Q/K rotations.

cached_AfterIDs [3] · CachePosition · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.

cached_AfterPositions [3] · CachePosition · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.

cached_AfterKeys [1,1,3,2] · B,H,CachePosition,Dk · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

cached_AfterValues [1,1,3,2] · B,H,CachePosition,Dv · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.

cached_Attentionraw [1,1,1,3] · B,H,Query,Key · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual two-product new Q dot every cached K.

cached_Attentionscores [1,1,1,3] · B,H,Query,Key · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Raw dot products divided by sqrt(Dk=2).

cached_Attentionallowed [1,1,1,3] · B,H,Query,Key · bool · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Allowed iff cached absolute key position <= absolute query N.

cached_Attentionlogits [1,1,1,3] · B,H,Query,Key · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual scaled scores plus the fixed common shift0.

cached_Attentionprobabilities [1,1,1,3] · B,H,Query,Key · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.

cached_AttentionOHeads [1,1,1,2] · B,H,Query,Dv · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New query weighted sum of all unrotated cached V.

cached_AttentionC [1,1,2] · B,T,JoinedValue · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. One-head Query to local token-major joined-feature copy.

cached_AttentionWO [2,2] · JoinedValue,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Explicit identity2 output projection.

cached_AttentionOutput [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. C WO for one local row, with explicit identity WO.

cached_R1 [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Exact named-shape addition of X and AttentionOutput; no broadcasting.

cached_LN2 [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.

cached_W1 [2,3] · D,HiddenFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

cached_b1 [3] · HiddenFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared hidden bias, added after the two products.

cached_Z [1,1,3] · B,T,HiddenFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Hidden preactivations X W1+b1; no batch or token mixing.

cached_Hidden [1,1,3] · B,T,HiddenFeature · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. ReLU(Z)=max(0,Z), before the second affine layer.

cached_W2 [3,2] · HiddenFeature,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared hidden-to-output weights, f2{m}{d}.

cached_b2 [2] · D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared output bias, added after all three running sums.

cached_F [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

cached_Y [1,1,2] · B,T,D · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Exact named-shape addition of R1 and F; no broadcasting.

cached_Logits [1,3] · Position,Class · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual new Y times active U, then active Bias.

cached_ChoiceClassIDs [3] · Class · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.

cached_ChoiceZ [3] · Class · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual finite computed input logits; no derived-input clipping.

cached_ChoiceShifted [3] · Class · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Z minus the saved active maximum.

cached_ChoiceTerms [3] · Class · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual exp(Shifted), before normalization.

cached_ChoiceDenominator [1] · Scalar · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual left-to-right sum of active shifted terms.

cached_ChoiceLogS [1] · Scalar · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Natural logarithm of Denominator.

cached_ChoiceLSE [1] · Scalar · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved max+LogS in binary64.

cached_ChoiceP [3] · Class · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.

cached_ChoiceNextRow [1] · Decision · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Lowest compact index among highest computed logits.

cached_ChoiceNextID [1] · Decision · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Public class ID gathered at NextRow.

cached_ChoiceNextProbability [1] · Decision · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Stored P gathered at the computed-logit winner.

Actual cached winner a / ID97, probability=0.7632007976561935; full winner a / ID97, probability=0.7632007976561935. Computed ID agreement=true; exact retained-copy flag=1. ID agreement alone cannot certify numeric equivalence.

Six comparisons from real operands

Read every coordinate, not only the winning ID. Delta is cached−full; the running maximum follows flat storage order. These are computed differences, never a forced zero.

K: maximum absolute error 0

CompareKDelta [3,2] · Position,Dk · float64 · precision 8 · Actual cached-full subtraction.

K actual coordinate errors — stored values without display rounding
Flat coordinateCachedFullSigned deltaAbsolute errorRunning maximum
00.44721359549995790.4472135954999579000
1-0.4472135954999579-0.4472135954999579000
2-0.6179478014890387-0.6179478014890387000
3-0.1346867277606211-0.1346867277606211000
40.220543648601392170.22054364860139217000
50.59275669465775380.5927566946577538000
K saved comparison calculation — stored values without display rounding
Saved operation / equationActual inputsActual outputs
compare_K

delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)

These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.

count=6
initialMaximum=0
cached0=0.4472135954999579
full0=0.4472135954999579
cached1=-0.4472135954999579
full1=-0.4472135954999579
cached2=-0.6179478014890387
full2=-0.6179478014890387
cached3=-0.1346867277606211
full3=-0.1346867277606211
cached4=0.22054364860139217
full4=0.22054364860139217
cached5=0.5927566946577538
full5=0.5927566946577538
delta0=0
absolute0=0
runningMax0=0
delta1=0
absolute1=0
runningMax1=0
delta2=0
absolute2=0
runningMax2=0
delta3=0
absolute3=0
runningMax3=0
delta4=0
absolute4=0
runningMax4=0
delta5=0
absolute5=0
runningMax5=0
maximum=0
V: maximum absolute error 0

CompareVDelta [3,2] · Position,Dv · float64 · precision 8 · Actual cached-full subtraction.

V actual coordinate errors — stored values without display rounding
Flat coordinateCachedFullSigned deltaAbsolute errorRunning maximum
00.44721359549995790.4472135954999579000
1-0.4472135954999579-0.4472135954999579000
2-0.4472135954999579-0.4472135954999579000
30.44721359549995790.4472135954999579000
40.44721359549995790.4472135954999579000
5-0.4472135954999579-0.4472135954999579000
V saved comparison calculation — stored values without display rounding
Saved operation / equationActual inputsActual outputs
compare_V

delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)

These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.

count=6
initialMaximum=0
cached0=0.4472135954999579
full0=0.4472135954999579
cached1=-0.4472135954999579
full1=-0.4472135954999579
cached2=-0.4472135954999579
full2=-0.4472135954999579
cached3=0.4472135954999579
full3=0.4472135954999579
cached4=0.4472135954999579
full4=0.4472135954999579
cached5=-0.4472135954999579
full5=-0.4472135954999579
delta0=0
absolute0=0
runningMax0=0
delta1=0
absolute1=0
runningMax1=0
delta2=0
absolute2=0
runningMax2=0
delta3=0
absolute3=0
runningMax3=0
delta4=0
absolute4=0
runningMax4=0
delta5=0
absolute5=0
runningMax5=0
maximum=0
Attention: maximum absolute error 0

CompareAttentionDelta [1,2] · Position,Dv · float64 · precision 8 · Actual cached-full subtraction.

Attention actual coordinate errors — stored values without display rounding
Flat coordinateCachedFullSigned deltaAbsolute errorRunning maximum
00.197494166429755120.19749416642975512000
1-0.19749416642975512-0.19749416642975512000
Attention saved comparison calculation — stored values without display rounding
Saved operation / equationActual inputsActual outputs
compare_Attention

delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)

These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.

count=2
initialMaximum=0
cached0=0.19749416642975512
full0=0.19749416642975512
cached1=-0.19749416642975512
full1=-0.19749416642975512
delta0=0
absolute0=0
runningMax0=0
delta1=0
absolute1=0
runningMax1=0
maximum=0
Y: maximum absolute error 0

CompareYDelta [1,2] · Position,D · float64 · precision 8 · Actual cached-full subtraction.

Y actual coordinate errors — stored values without display rounding
Flat coordinateCachedFullSigned deltaAbsolute errorRunning maximum
01.76957631838797451.7695763183879745000
1-0.19749416642975512-0.19749416642975512000
Y saved comparison calculation — stored values without display rounding
Saved operation / equationActual inputsActual outputs
compare_Y

delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)

These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.

count=2
initialMaximum=0
cached0=1.7695763183879745
full0=1.7695763183879745
cached1=-0.19749416642975512
full1=-0.19749416642975512
delta0=0
absolute0=0
runningMax0=0
delta1=0
absolute1=0
runningMax1=0
maximum=0
Logits: maximum absolute error 0

CompareLogitsDelta [1,3] · Position,Class · float64 · precision 8 · Actual cached-full subtraction.

Logits actual coordinate errors — stored values without display rounding
Flat coordinateCachedFullSigned deltaAbsolute errorRunning maximum
01.76957631838797451.7695763183879745000
1-0.19749416642975512-0.19749416642975512000
200000
Logits saved comparison calculation — stored values without display rounding
Saved operation / equationActual inputsActual outputs
compare_Logits

delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)

These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.

count=3
initialMaximum=0
cached0=1.7695763183879745
full0=1.7695763183879745
cached1=-0.19749416642975512
full1=-0.19749416642975512
cached2=0
full2=0
delta0=0
absolute0=0
runningMax0=0
delta1=0
absolute1=0
runningMax1=0
delta2=0
absolute2=0
runningMax2=0
maximum=0
P: maximum absolute error 0

ComparePDelta [1,3] · Position,Class · float64 · precision 8 · Actual cached-full subtraction.

P actual coordinate errors — stored values without display rounding
Flat coordinateCachedFullSigned deltaAbsolute errorRunning maximum
00.76320079765619350.7632007976561935000
10.10674583985786140.1067458398578614000
20.130053362485945180.13005336248594518000
P saved comparison calculation — stored values without display rounding
Saved operation / equationActual inputsActual outputs
compare_P

delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)

These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.

count=3
initialMaximum=0
cached0=0.7632007976561935
full0=0.7632007976561935
cached1=0.1067458398578614
full1=0.1067458398578614
cached2=0.13005336248594518
full2=0.13005336248594518
delta0=0
absolute0=0
runningMax0=0
delta1=0
absolute1=0
runningMax1=0
delta2=0
absolute2=0
runningMax2=0
maximum=0
Actual BPE, append/stop decision and strict reverse decoding

Fixed corpus="abab". Rules=[]. Expansions=[]. Prompt labels=["ID 97, bytes [97]","ID 98, bytes [98]"]. Zero merges requested: no training round or pair selection occurs.

EOS512 is appended logically then strict reverse-decoded; no new neural row, full append call, cache entry or comparison is computed. Reverse decoding uses the same learned rules on the retained IDs, without retokenizing across their boundaries.

IV-49 tokenizer, logical append and actual decoder — stored values without display rounding
Saved operation / equationActual inputsActual outputs
tokenizer_setup

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.

requestedMerges=0
eos=0
corpusUnits=4
corpusScalars=4
utf16Units=2
scalarCount=2
byteBound=24
mergeBase=256
mergeBound=4
EOS=512
tokenizer_corpus_scalar_0

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.

scalarIndex=0
utf16Offset=0
utf16Width=1
codePoint=97
unit0=97
byteOffset=0
byteWidth=1
payload0=97
byte0=97
tokenizer_corpus_scalar_1

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.

scalarIndex=1
utf16Offset=1
utf16Width=1
codePoint=98
unit0=98
byteOffset=1
byteWidth=1
payload0=98
byte0=98
tokenizer_corpus_scalar_2

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.

scalarIndex=2
utf16Offset=2
utf16Width=1
codePoint=97
unit0=97
byteOffset=2
byteWidth=1
payload0=97
byte0=97
tokenizer_corpus_scalar_3

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.

scalarIndex=3
utf16Offset=3
utf16Width=1
codePoint=98
unit0=98
byteOffset=3
byteWidth=1
payload0=98
byte0=98
tokenizer_source_scalar_0

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.

scalarIndex=0
utf16Offset=0
utf16Width=1
codePoint=97
unit0=97
byteOffset=0
byteWidth=1
payload0=97
byte0=97
tokenizer_source_scalar_1

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.

scalarIndex=1
utf16Offset=1
utf16Width=1
codePoint=98
unit0=98
byteOffset=1
byteWidth=1
payload0=98
byte0=98
tokenizer_corpus_expand_0

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.

index=0
id=97
byteOffset=0
byteWidth=1
byte0=97
tokenizer_corpus_expand_1

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.

index=1
id=98
byteOffset=1
byteWidth=1
byte0=98
tokenizer_corpus_expand_2

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.

index=2
id=97
byteOffset=2
byteWidth=1
byte0=97
tokenizer_corpus_expand_3

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.

index=3
id=98
byteOffset=3
byteWidth=1
byte0=98
tokenizer_corpus_decode_0

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.

scalarIndex=0
byteOffset=0
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
tokenizer_corpus_decode_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.

scalarIndex=1
byteOffset=1
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
tokenizer_corpus_decode_2

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.

scalarIndex=2
byteOffset=2
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
tokenizer_corpus_decode_3

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.

scalarIndex=3
byteOffset=3
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
tokenizer_target_expand_0

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.

index=0
id=97
byteOffset=0
byteWidth=1
byte0=97
tokenizer_target_expand_1

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.

index=1
id=98
byteOffset=1
byteWidth=1
byte0=98
tokenizer_target_decode_0

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.

scalarIndex=0
byteOffset=0
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
tokenizer_target_decode_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.

scalarIndex=1
byteOffset=1
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
tokenizer_roundtrip

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.

corpusOriginalUnits=4
corpusDecodedUnits=4
corpusDecodedByteCount=4
originalUnits=2
decodedUnits=2
decodedByteCount=2
corpusTokens=4
tokenCount=2
corpusEqual=1
equal=1
append_decision

ResultIDs=[PromptIDs,nextID]; nextID=512 => no append neural work

The supplied nextID is not replaced by a model prediction. EOS is a logical tail marker decoded without an EOS gather, new cache row, second forward, copy comparison or phantom delta.

promptTokens=2
nextID=97
EOS=512
logicalResultTokens=3
stoppedEOS=0
decodeExecuted=1
absoluteAppendPosition=2
cachedNewQueryRows=1
fullNewQueryRows=3
cachedScoreCells=3
fullScoreCells=9
prediction_comparison

predictionsEqual=(cachedNextID===fullNextID); exact ties use lowest compact index in each real path

Agreement of IDs alone does not establish numerical equivalence. Six complete operand/error families are retained separately; same-implementation copied K/V equality is a narrower fact.

cachedNextRow=0
cachedNextID=97
fullNextRow=0
fullNextID=97
predictionsEqual=1
retainedExact=1
result_expand_0

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.

index=0
id=97
byteOffset=0
byteWidth=1
byte0=97
result_expand_1

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.

index=1
id=98
byteOffset=1
byteWidth=1
byte0=98
result_expand_2

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.

index=2
id=97
byteOffset=2
byteWidth=1
byte0=97
result_decode_0

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.

scalarIndex=0
byteOffset=0
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
result_decode_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.

scalarIndex=1
byteOffset=1
byteWidth=1
byte0=98
payload0=98
accumulator0=98
codePoint=98
utf16Width=1
unit0=98
result_decode_2

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.

scalarIndex=2
byteOffset=2
byteWidth=1
byte0=97
payload0=97
accumulator0=97
codePoint=97
utf16Width=1
unit0=97
finish

harness=N+cachedNewQueryRows+fullNewQueryRows; coldCached=N+cachedNewQueryRows; coldFull=N+fullNewQueryRows

The prefill is shared once. Do not add the two cold logical path totals as actual work. Counts concern this one-layer toy, with no latency, training-quality or universal speedup claim.

promptTokens=2
cachedNewQueryRows=1
fullNewQueryRows=3
prefillScoreCells=4
cachedScoreCells=3
fullScoreCells=9
actualHarnessRows=6
cacheEntries=3
resultByteCount=3
coldCachedRows=3
coldFullRows=5
Cache trust, model identity and numerical limits

External helper callers must supply coherent K/V. Finite metadata, freezing and structural checks do not certify arbitrary supplied payloads. The app constructs every cache internally.

All26 numeric parameters must agree under numeric ===, including readout and inactive embeddings; signed zeros are equivalent. This conservative policy exceeds the minimal K/V dependency.

Absolute positions start at0. Only new Q/K rotate at the agreed prefix length; V never rotates.

Exact unchanged copies within one implementation are a separate fact from independently witnessing numeric coherence. Exact-real equivalence does not promise bitwise agreement across math libraries. Stored binary64 operands and actual computed differences remain visible; no timing or trained-model quality is measured.

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.

tokenizer_CorpusCodePoints

Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198
297
398

tokenizer_CorpusUTF16Offsets

Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

tokenizer_CorpusUTF16Widths

Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11
21
31

tokenizer_CorpusByteOffsets

Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11
22
33

tokenizer_CorpusByteWidths

Scalars=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11
21
31

tokenizer_CorpusBytes

Bytes=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198
297
398

tokenizer_SourceCodePoints

Scalars=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Validated Unicode scalars in exact input order.

Zero-based storage indexStored value
097
198

tokenizer_SourceUTF16Offsets

Scalars=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-16 storage offset for each scalar.

Zero-based storage indexStored value
00
11

tokenizer_SourceUTF16Widths

Scalars=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. UTF-16 storage units consumed by each scalar.

Zero-based storage indexStored value
01
11

tokenizer_SourceByteOffsets

Scalars=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Zero-based UTF-8 byte offset for each scalar.

Zero-based storage indexStored value
00
11

tokenizer_SourceByteWidths

Scalars=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual UTF-8 bytes emitted by each scalar.

Zero-based storage indexStored value
01
11

tokenizer_SourceBytes

Bytes=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Manual UTF-8 encoding in source order, preserving all data.

Zero-based storage indexStored value
097
198

tokenizer_TrainInitialIDs

Tokens=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Initial training byte IDs, one ID for each actual corpus byte.

Zero-based storage indexStored value
097
198
297
398

tokenizer_CorpusIDs

Tokens=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Final learned corpus token IDs; corpus training never contains EOS.

Zero-based storage indexStored value
097
198
297
398

tokenizer_EncodeInitialIDs

Tokens=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Initial target byte IDs before any ranked application.

Zero-based storage indexStored value
097
198

tokenizer_TargetIDs

Tokens=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Final target token IDs after all learned ranks, then optional unique EOS tail.

Zero-based storage indexStored value
097
198

tokenizer_CorpusDecodedBytes

Bytes=4 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual final corpus ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198
297
398

tokenizer_TargetDecodedBytes

Bytes=2 · int32 · precision 0 · Actual prompt BPE once, fixed corpus abab and EOS off. Actual final target ID expansions passed to strict UTF-8 decoding.

Zero-based storage indexStored value
097
198

prefill_AllClassIDs

ModelRow=5 · int32 · precision 0 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ClassIDs

Class=3 · int32 · precision 0 · Actual full-prefix call prefill, absolute positions 0..1. Active prefix of the full model row map; V=3+merges.

Zero-based storage indexStored value
097
198
2512

prefill_E

ModelRow=5 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_U

D=2 × ModelRow=5 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Bias

ModelRow=5 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. All five validated editable biases; inactive columns have no objective dependency.

Zero-based storage indexStored value
00
10
20
30
40

prefill_InputIDs

Position=2 · int32 · precision 0 · Actual full-prefix call prefill, absolute positions 0..1. Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.

Zero-based storage indexStored value
097
198

prefill_InputRows

Position=2 · int32 · precision 0 · Actual full-prefix call prefill, absolute positions 0..1. Compact model row gathered for each observed ID; never index by public ID512.

Zero-based storage indexStored value
00
11

prefill_X

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Actual gathered E rows; B=1, token-major storage and D=2.

Zero-based storage indexStored value
01
10
20
31

prefill_LN1

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionX

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionWQ

D=2 × QueryFeature=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionWK

D=2 × KeyFeature=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionWV

D=2 × ValueFeature=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionQConcat

B=1 × T=2 × QueryFeature=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionKConcat

B=1 × T=2 × KeyFeature=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionVConcat

B=1 × T=2 × ValueFeature=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionQSplit

B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionQHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionKSplit

B=1 × T=2 × H=1 × Dk=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionKHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionVSplit

B=1 × T=2 × H=1 × Dv=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_ProjectionVHeads

B=1 × H=1 × T=2 × Dv=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_RotatedQHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_RotatedKHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_RoPEAngles

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Absolute position t times the single-pair frequency1, in radians.

Zero-based storage indexStored value
00
11

prefill_RoPECos

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Stored cos(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
01
10.5403023058681398

prefill_RoPESin

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Stored sin(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
00
10.8414709848078965

prefill_Attentionraw

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Attentionscores

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Attentionallowed

B=1 × H=1 × Query=2 × Key=2 · bool · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Attentionlogits

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Attentionprobabilities

B=1 × H=1 × Query=2 × Key=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_AttentionOHeads

B=1 × H=1 × Query=2 × Dv=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_AttentionC

B=1 × T=2 × JoinedValue=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_AttentionWO

JoinedValue=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_AttentionOutput

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_R1

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_LN2

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_W1

D=2 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

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

prefill_b1

HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Shared hidden bias, added after the two products.

Zero-based storage indexStored value
00
10
20

prefill_Z

B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Hidden

B=1 × T=2 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. ReLU(Z)=max(0,Z), before the second affine layer.

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

prefill_W2

HiddenFeature=3 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Shared hidden-to-output weights, f2{m}{d}.

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

prefill_b2

D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Shared output bias, added after all three running sums.

Zero-based storage indexStored value
00
10

prefill_F

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

Zero-based storage indexStored value
00.6876854075163181
10
20
30.5119068988408909

prefill_Y

B=1 × T=2 × D=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Logits

Position=2 × Class=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Max

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Maximum computed active class logit at each position.

Zero-based storage indexStored value
02.134899003016276
11.6078120278761694

prefill_Shifted

Position=2 × Class=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_Terms

Position=2 × Class=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Actual exp(Shifted) before left-to-right class summation.

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

prefill_Denominator

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Shifted exponential sum from zero in ascending compact class order.

Zero-based storage indexStored value
01.1938706262744982
11.3823311626637835

prefill_LogS

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. ln(Denominator), saved for factored NLL.

Zero-based storage indexStored value
00.17720065589584005
10.3237713223010388

prefill_LSE

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Max+LogS; saved evidence, not subtracted from target logits to compute NLL.

Zero-based storage indexStored value
02.312099658912116
11.9315833501772082

prefill_P

Position=2 × Class=3 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. 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

prefill_NextRows

Position=2 · int32 · precision 0 · Actual full-prefix call prefill, absolute positions 0..1. Highest computed logit; exact ties keep the smallest compact class.

Zero-based storage indexStored value
00
11

prefill_NextIDs

Position=2 · int32 · precision 0 · Actual full-prefix call prefill, absolute positions 0..1. Public ID mapped from each computed-logit winner.

Zero-based storage indexStored value
097
198

prefill_NextProbability

Position=2 · float64 · precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Stored class probability of the computed-logit winner; never fed back as an observed input.

Zero-based storage indexStored value
00.8376116959343609
10.7234156524931242

prefill_CacheIDs

CachePosition=2 · int32 · precision 0 · Ordered observed public IDs; cache coherence is an external-helper input precondition.

Zero-based storage indexStored value
097
198

prefill_CachePositions

CachePosition=2 · int32 · precision 0 · Absolute positions 0..N-1, not local append-query indices.

Zero-based storage indexStored value
00
11

prefill_CacheKeys

B=1 × H=1 × CachePosition=2 × Dk=2 · float64 · precision 8 · Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

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

prefill_CacheValues

B=1 × H=1 × CachePosition=2 × Dv=2 · float64 · precision 8 · Saved unrotated projected V in observed-prefix order.

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

cached_AllClassIDs

ModelRow=5 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All possible compact model rows; public IDs are labels.

Zero-based storage indexStored value
097
198
2512
3256
4257

cached_ClassIDs

Class=3 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Active compact prefix; V=3+merges.

Zero-based storage indexStored value
097
198
2512

cached_E

ModelRow=5 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All ten validated editable embeddings, including inactive rows.

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

cached_U

D=2 × ModelRow=5 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All ten validated readout weights; active prefix alone produces logits.

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

cached_Bias

ModelRow=5 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. All five validated biases; inactive columns remain outside the distribution.

Zero-based storage indexStored value
00
10
20
30
40

cached_InputIDs

LocalPosition=1 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Exactly one new observed token is processed.

Zero-based storage indexStored value
097

cached_InputRows

LocalPosition=1 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Compact embedding row for the new token.

Zero-based storage indexStored value
00

cached_AbsoluteQueryPosition

Query=1 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Absolute N, distinct from the single local query index0.

Zero-based storage indexStored value
02

cached_BeforeIDs

CachePosition=2 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.

Zero-based storage indexStored value
097
198

cached_BeforePositions

CachePosition=2 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.

Zero-based storage indexStored value
00
11

cached_BeforeKeys

B=1 × H=1 × CachePosition=2 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

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

cached_BeforeValues

B=1 × H=1 × CachePosition=2 × Dv=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.

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

cached_X

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Only the new embedding row; local T=1, absolute position is saved separately.

Zero-based storage indexStored value
01
10

cached_LN1

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionX

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Active token rows; D=2 input features always retained.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionWQ

D=2 × QueryFeature=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Query columns packed by h*Dk+f from wq{d}{h}{f}.

Zero-based storage indexStored value
01
10
20
31

cached_ProjectionWK

D=2 × KeyFeature=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Key columns packed by h*Dk+f from wk{d}{h}{f}.

Zero-based storage indexStored value
01
10
20
31

cached_ProjectionWV

D=2 × ValueFeature=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. Value columns packed by h*Dv+f from wv{d}{h}{f}.

Zero-based storage indexStored value
01
10
20
31

cached_ProjectionQConcat

B=1 × T=1 × QueryFeature=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWQ; each packed coordinate has two products and one sum.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionKConcat

B=1 × T=1 × KeyFeature=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWK; each packed coordinate has two products and one sum.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionVConcat

B=1 × T=1 × ValueFeature=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. XWV; values are projected separately from queries and keys.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionQSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. QConcat reshaped without changing flat order; feature=h*F+f.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionQHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. QSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionKSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. KConcat reshaped without changing flat order; feature=h*F+f.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionKHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. KSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionVSplit

B=1 × T=1 × H=1 × Dv=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. VConcat reshaped without changing flat order; feature=h*F+f.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_ProjectionVHeads

B=1 × H=1 × T=1 × Dv=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New LN1 row only. VSplit permuted by axes [0,2,1,3]; every copied source/destination offset is traced.

Zero-based storage indexStored value
00.4472135954999579
1-0.4472135954999579

cached_RotatedQHeads

B=1 × H=1 × Query=1 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New query rotated at absolute N; Query length1.

Zero-based storage indexStored value
00.22054364860139217
10.5927566946577538

cached_NewRotatedKHeads

B=1 × H=1 × NewPosition=1 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Only the newly computed key, rotated once at absolute N.

Zero-based storage indexStored value
00.22054364860139217
10.5927566946577538

cached_RoPEAngles

Query=1 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual absolute N times frequency1, radians.

Zero-based storage indexStored value
02

cached_RoPECos

Query=1 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Cosine used by new Q/K rotations.

Zero-based storage indexStored value
0-0.4161468365471424

cached_RoPESin

Query=1 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Sine used by new Q/K rotations.

Zero-based storage indexStored value
00.9092974268256817

cached_AfterIDs

CachePosition=3 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Ordered observed public IDs; cache coherence is an external-helper input precondition.

Zero-based storage indexStored value
097
198
297

cached_AfterPositions

CachePosition=3 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Absolute positions 0..N-1, not local append-query indices.

Zero-based storage indexStored value
00
11
22

cached_AfterKeys

B=1 × H=1 × CachePosition=3 × Dk=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation.

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

cached_AfterValues

B=1 × H=1 × CachePosition=3 × Dv=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved unrotated projected V in observed-prefix order.

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

cached_Attentionraw

B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual two-product new Q dot every cached K.

Zero-based storage indexStored value
0-0.1664587346188569
1-0.21612092234725588
20.39999999999999997

cached_Attentionscores

B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Raw dot products divided by sqrt(Dk=2).

Zero-based storage indexStored value
0-0.11770410003672563
1-0.15282056974803587
20.28284271247461895

cached_Attentionallowed

B=1 × H=1 × Query=1 × Key=3 · bool · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Allowed iff cached absolute key position <= absolute query N.

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

cached_Attentionlogits

B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual scaled scores plus the fixed common shift0.

Zero-based storage indexStored value
0-0.11770410003672563
1-0.15282056974803587
20.28284271247461895

cached_Attentionprobabilities

B=1 × H=1 × Query=1 × Key=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Stable softmax over the complete cached key axis; Query length1.

Zero-based storage indexStored value
00.2891733251316062
10.2791948093517053
20.43163186551668853

cached_AttentionOHeads

B=1 × H=1 × Query=1 × Dv=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New query weighted sum of all unrotated cached V.

Zero-based storage indexStored value
00.19749416642975512
1-0.19749416642975512

cached_AttentionC

B=1 × T=1 × JoinedValue=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. One-head Query to local token-major joined-feature copy.

Zero-based storage indexStored value
00.19749416642975512
1-0.19749416642975512

cached_AttentionWO

JoinedValue=2 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Explicit identity2 output projection.

Zero-based storage indexStored value
01
10
20
31

cached_AttentionOutput

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. C WO for one local row, with explicit identity WO.

Zero-based storage indexStored value
00.19749416642975512
1-0.19749416642975512

cached_R1

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Exact named-shape addition of X and AttentionOutput; no broadcasting.

Zero-based storage indexStored value
01.1974941664297551
1-0.19749416642975512

cached_LN2

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.

Zero-based storage indexStored value
00.5720821519582194
1-0.5720821519582194

cached_W1

D=2 × HiddenFeature=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

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

cached_b1

HiddenFeature=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared hidden bias, added after the two products.

Zero-based storage indexStored value
00
10
20

cached_Z

B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Hidden preactivations X W1+b1; no batch or token mixing.

Zero-based storage indexStored value
00.5720821519582194
1-0.5720821519582194
20

cached_Hidden

B=1 × T=1 × HiddenFeature=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. ReLU(Z)=max(0,Z), before the second affine layer.

Zero-based storage indexStored value
00.5720821519582194
10
20

cached_W2

HiddenFeature=3 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared hidden-to-output weights, f2{m}{d}.

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

cached_b2

D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Shared output bias, added after all three running sums.

Zero-based storage indexStored value
00
10

cached_F

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. ReLU(X W1+b1) W2+b2, independently per token with shared parameters.

Zero-based storage indexStored value
00.5720821519582194
10

cached_Y

B=1 × T=1 × D=2 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Exact named-shape addition of R1 and F; no broadcasting.

Zero-based storage indexStored value
01.7695763183879745
1-0.19749416642975512

cached_Logits

Position=1 × Class=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual new Y times active U, then active Bias.

Zero-based storage indexStored value
01.7695763183879745
1-0.19749416642975512
20

cached_ChoiceClassIDs

Class=3 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets.

Zero-based storage indexStored value
097
198
2512

cached_ChoiceZ

Class=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual finite computed input logits; no derived-input clipping.

Zero-based storage indexStored value
01.7695763183879745
1-0.19749416642975512
20

cached_ChoiceShifted

Class=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Z minus the saved active maximum.

Zero-based storage indexStored value
00
1-1.9670704848177296
2-1.7695763183879745

cached_ChoiceTerms

Class=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual exp(Shifted), before normalization.

Zero-based storage indexStored value
01
10.1398659961908848
20.17040517107076136

cached_ChoiceDenominator

Scalar=1 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Actual left-to-right sum of active shifted terms.

Zero-based storage indexStored value
01.310271167261646

cached_ChoiceLogS

Scalar=1 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Natural logarithm of Denominator.

Zero-based storage indexStored value
00.2702341137016024

cached_ChoiceLSE

Scalar=1 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Saved max+LogS in binary64.

Zero-based storage indexStored value
02.0398104320895767

cached_ChoiceP

Class=3 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Terms/Denominator for active classes only, without clipping or padding.

Zero-based storage indexStored value
00.7632007976561935
10.1067458398578614
20.13005336248594518

cached_ChoiceNextRow

Decision=1 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Lowest compact index among highest computed logits.

Zero-based storage indexStored value
00

cached_ChoiceNextID

Decision=1 · int32 · precision 0 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Public class ID gathered at NextRow.

Zero-based storage indexStored value
097

cached_ChoiceNextProbability

Decision=1 · float64 · precision 8 · Actual cached append cached: local row0 is absolute 2; no old query/K/V recomputation. Stored P gathered at the computed-logit winner.

Zero-based storage indexStored value
00.7632007976561935

uncached_AllClassIDs

ModelRow=5 · int32 · precision 0 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ClassIDs

Class=3 · int32 · precision 0 · Actual full-prefix call uncached, absolute positions 0..2. Active prefix of the full model row map; V=3+merges.

Zero-based storage indexStored value
097
198
2512

uncached_E

ModelRow=5 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_U

D=2 × ModelRow=5 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Bias

ModelRow=5 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. All five validated editable biases; inactive columns have no objective dependency.

Zero-based storage indexStored value
00
10
20
30
40

uncached_InputIDs

Position=3 · int32 · precision 0 · Actual full-prefix call uncached, absolute positions 0..2. Observed public IDs supplied directly to the numeric kernel; active EOS is permitted.

Zero-based storage indexStored value
097
198
297

uncached_InputRows

Position=3 · int32 · precision 0 · Actual full-prefix call uncached, absolute positions 0..2. Compact model row gathered for each observed ID; never index by public ID512.

Zero-based storage indexStored value
00
11
20

uncached_X

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Actual gathered E rows; B=1, token-major storage and D=2.

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

uncached_LN1

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionX

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionWQ

D=2 × QueryFeature=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionWK

D=2 × KeyFeature=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionWV

D=2 × ValueFeature=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionQConcat

B=1 × T=3 × QueryFeature=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionKConcat

B=1 × T=3 × KeyFeature=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionVConcat

B=1 × T=3 × ValueFeature=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionQSplit

B=1 × T=3 × H=1 × Dk=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionQHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionKSplit

B=1 × T=3 × H=1 × Dk=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionKHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionVSplit

B=1 × T=3 × H=1 × Dv=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_ProjectionVHeads

B=1 × H=1 × T=3 × Dv=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_RotatedQHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_RotatedKHeads

B=1 × H=1 × T=3 × Dk=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_RoPEAngles

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Absolute position t times the single-pair frequency1, in radians.

Zero-based storage indexStored value
00
11
22

uncached_RoPECos

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_RoPESin

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Stored sin(angle) used in the Q pair rotation; K uses the same angle.

Zero-based storage indexStored value
00
10.8414709848078965
20.9092974268256817

uncached_Attentionraw

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Attentionscores

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Attentionallowed

B=1 × H=1 × Query=3 × Key=3 · bool · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Attentionlogits

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Attentionprobabilities

B=1 × H=1 × Query=3 × Key=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_AttentionOHeads

B=1 × H=1 × Query=3 × Dv=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_AttentionC

B=1 × T=3 × JoinedValue=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_AttentionWO

JoinedValue=2 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_AttentionOutput

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_R1

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_LN2

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_W1

D=2 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Shared input-to-hidden weights, f1{d}{m}; M=3 hidden features.

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

uncached_b1

HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Shared hidden bias, added after the two products.

Zero-based storage indexStored value
00
10
20

uncached_Z

B=1 × T=3 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Hidden

B=1 × T=3 × HiddenFeature=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_W2

HiddenFeature=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Shared hidden-to-output weights, f2{m}{d}.

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

uncached_b2

D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Shared output bias, added after all three running sums.

Zero-based storage indexStored value
00
10

uncached_F

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Y

B=1 × T=3 × D=2 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Logits

Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Max

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Maximum computed active class logit at each position.

Zero-based storage indexStored value
02.134899003016276
11.6078120278761694
21.7695763183879745

uncached_Shifted

Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Terms

Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_Denominator

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Shifted exponential sum from zero in ascending compact class order.

Zero-based storage indexStored value
01.1938706262744982
11.3823311626637835
21.310271167261646

uncached_LogS

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. ln(Denominator), saved for factored NLL.

Zero-based storage indexStored value
00.17720065589584005
10.3237713223010388
20.2702341137016024

uncached_LSE

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. Max+LogS; saved evidence, not subtracted from target logits to compute NLL.

Zero-based storage indexStored value
02.312099658912116
11.9315833501772082
22.0398104320895767

uncached_P

Position=3 × Class=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

uncached_NextRows

Position=3 · int32 · precision 0 · Actual full-prefix call uncached, absolute positions 0..2. Highest computed logit; exact ties keep the smallest compact class.

Zero-based storage indexStored value
00
11
20

uncached_NextIDs

Position=3 · int32 · precision 0 · Actual full-prefix call uncached, absolute positions 0..2. Public ID mapped from each computed-logit winner.

Zero-based storage indexStored value
097
198
297

uncached_NextProbability

Position=3 · float64 · precision 8 · Actual full-prefix call uncached, absolute positions 0..2. 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

CompareKCached

Position=3 × Dk=2 · float64 · precision 8 · Actual cached operands.

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

CompareKFull

Position=3 × Dk=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.

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

CompareKDelta

Position=3 × Dk=2 · float64 · precision 8 · Actual cached-full subtraction.

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

CompareKAbs

Position=3 × Dk=2 · float64 · precision 8 · Actual abs(Delta).

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

CompareKRunningMax

Position=3 × Dk=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.

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

CompareVCached

Position=3 × Dv=2 · float64 · precision 8 · Actual cached operands.

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

CompareVFull

Position=3 × Dv=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.

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

CompareVDelta

Position=3 × Dv=2 · float64 · precision 8 · Actual cached-full subtraction.

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

CompareVAbs

Position=3 × Dv=2 · float64 · precision 8 · Actual abs(Delta).

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

CompareVRunningMax

Position=3 × Dv=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.

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

CompareAttentionCached

Position=1 × Dv=2 · float64 · precision 8 · Actual cached operands.

Zero-based storage indexStored value
00.19749416642975512
1-0.19749416642975512

CompareAttentionFull

Position=1 × Dv=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.

Zero-based storage indexStored value
00.19749416642975512
1-0.19749416642975512

CompareAttentionDelta

Position=1 × Dv=2 · float64 · precision 8 · Actual cached-full subtraction.

Zero-based storage indexStored value
00
10

CompareAttentionAbs

Position=1 × Dv=2 · float64 · precision 8 · Actual abs(Delta).

Zero-based storage indexStored value
00
10

CompareAttentionRunningMax

Position=1 × Dv=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.

Zero-based storage indexStored value
00
10

CompareYCached

Position=1 × D=2 · float64 · precision 8 · Actual cached operands.

Zero-based storage indexStored value
01.7695763183879745
1-0.19749416642975512

CompareYFull

Position=1 × D=2 · float64 · precision 8 · Actual independently recomputed full-prefix operands.

Zero-based storage indexStored value
01.7695763183879745
1-0.19749416642975512

CompareYDelta

Position=1 × D=2 · float64 · precision 8 · Actual cached-full subtraction.

Zero-based storage indexStored value
00
10

CompareYAbs

Position=1 × D=2 · float64 · precision 8 · Actual abs(Delta).

Zero-based storage indexStored value
00
10

CompareYRunningMax

Position=1 × D=2 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.

Zero-based storage indexStored value
00
10

CompareLogitsCached

Position=1 × Class=3 · float64 · precision 8 · Actual cached operands.

Zero-based storage indexStored value
01.7695763183879745
1-0.19749416642975512
20

CompareLogitsFull

Position=1 × Class=3 · float64 · precision 8 · Actual independently recomputed full-prefix operands.

Zero-based storage indexStored value
01.7695763183879745
1-0.19749416642975512
20

CompareLogitsDelta

Position=1 × Class=3 · float64 · precision 8 · Actual cached-full subtraction.

Zero-based storage indexStored value
00
10
20

CompareLogitsAbs

Position=1 × Class=3 · float64 · precision 8 · Actual abs(Delta).

Zero-based storage indexStored value
00
10
20

CompareLogitsRunningMax

Position=1 × Class=3 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.

Zero-based storage indexStored value
00
10
20

ComparePCached

Position=1 × Class=3 · float64 · precision 8 · Actual cached operands.

Zero-based storage indexStored value
00.7632007976561935
10.1067458398578614
20.13005336248594518

ComparePFull

Position=1 × Class=3 · float64 · precision 8 · Actual independently recomputed full-prefix operands.

Zero-based storage indexStored value
00.7632007976561935
10.1067458398578614
20.13005336248594518

ComparePDelta

Position=1 × Class=3 · float64 · precision 8 · Actual cached-full subtraction.

Zero-based storage indexStored value
00
10
20

ComparePAbs

Position=1 × Class=3 · float64 · precision 8 · Actual abs(Delta).

Zero-based storage indexStored value
00
10
20

ComparePRunningMax

Position=1 × Class=3 · float64 · precision 8 · Actual running maximum from0 in flat coordinate order.

Zero-based storage indexStored value
00
10
20

PromptIDs

PromptPosition=2 · int32 · precision 0 · Actual EOS-off prompt BPE IDs.

Zero-based storage indexStored value
097
198

ResultIDs

LogicalPosition=3 · int32 · precision 0 · Retained prompt IDs plus exactly one supplied ID; terminal EOS is logical only.

Zero-based storage indexStored value
097
198
297

ResultBytes

Bytes=3 · int32 · precision 0 · Actual strict reverse-decoder expansions with the same learned rules; EOS emits no bytes.

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 the shared prefill do before this controlled append?
2. For N=2 and V=3, which saved shapes describe the genuine cached append?
3. Current N=2, nextID=97, stoppedEOS=0. Which actual harness counts are saved?
4. Cached/full winners are ID97/ID97, probabilities=0.7632007976561935/0.7632007976561935; YMaxError=0, PMaxError=0. Which interpretation is valid?
5. Transfer: change only a readout weight U, or an inactive embedding row, while requesting reuse of an old externally supplied cache. What does this helper promise?

Try EOS512, then inspect prefill. With merges2, text ab and nextID256 the logical result keeps [256,256] and decodes abab; it is never retokenized to [257]. Input edits, reset and trace navigation clear answers. Inspection selectors only read saved evidence.

Start with prompt ab, zero merges and external nextID97, meaning a. Prefill processes [97,98] once. The cached branch processes one new row at absolute position2; the full branch independently processes [97,98,97]. Inspection selects saved evidence from these real paths. It does not change which arithmetic was performed or create a cached result by cropping a full result.

Begin with Cached in Saved neural path (inspection only). Switch to Full to inspect the matching absolute query N, which is2 at reset. Saved query also lets you explicitly inspect an earlier full row; switching paths again restores the corresponding append row. Shared full prefill contains only the original N rows, so its query selection is clamped to N−1. Attention key and Active compact class select actual saved score and readout operands. Open their operation tables and the complete-path details to follow products, sums, rotations and all three FFN coordinates; the tensor inspector retains every value and its metadata.

Native input edits rebuild the calculation from its raw state. Editing, pressing Reset example, or seeking with Previous step, Next step or Calculation step clears graded answers. The inspection selectors preserve both answers and trace cursor because they only choose saved evidence. Invalid drafts display a reason and remove the unavailable calculation and its questions. With EOS selected, the path selector offers only the real prefill; there is no append path to inspect.

Review IV-48 — Keys, Values and the Cache Invariant for the cache invariant and IV-47 — Complete Autoregressive Generation Trace for generation’s choice-and-append loop. Book II’s II.10 — Matrix × matrix as composition explains how operations join; its VIII.2 — Rounding and representation error separates mathematical identities from machine values. Book III’s III-41 — Composition and Learned Representations reviews forward composition, while III-16 — Multiclass Classification and Softmax Regression reviews output probabilities.

Fix the experiment before comparing it

Prefill processes the supplied prompt. Cached decoding reuses its past attention keys and values when a new input arrives. Uncached decoding recalculates the extended prefix. These are forward calculations with disclosed, fixed, untrained weights: no targets, loss or parameter updates are involved.

The appended ID is an externally controlled observed input, not a token selected by the model. At reset the last prefill row prefers b/98, but we deliberately append a/97. Both branches then predict what could follow aba. A generator such as IV-47 can feed its selected ID into this append primitive; this experiment isolates the primitive without adding unused sampling controls or a seed.

A token is a piece with an integer public ID. Byte-pair encoding (BPE) learns rules from fixed corpus abab, then tokenizes the prompt once, with EOS insertion off. Compact rows [0,1,2,3,4] map to public IDs [97,98,512,256,257]: a, b, EOS, ab, abab. EOS means end of sequence. With m merges the active vocabulary size is V=3+m. At reset only a, b and EOS are output classes, although all five potential rows remain stored and validated.

The embedding table E has shape [5,2]. Reset rows are (1,0), (0,1), (0,0), (1/2,1/2), (1,1). The readout U has shape [2,5], with rows (1,0,0,0,0) and (0,1,0,0,0); its five biases are0. E supplies input features. U and bias turn final features into logits, scores for possible next tokens. Softmax normalizes the active logits into class probabilities.

Shapes distinguish a new query from all available keys

A tensor is an array with named axes. Here batch B=1, head count H=1 and feature widths D=Dk=Dv=2. One attention head compares a query Q with keys K, then mixes values using normalized weights. Let N be the actual prompt-token count, Tk=N+1 the nonterminal extended length, j a key position and c an active compact class.

QuantityCached appendSeparate full-prefix append
Gathered X, normalized rows, residuals, final Y; B,T,D[1,1,2][1,Tk,2]
Rotated queries; B,H,Query,Dk[1,1,1,2][1,1,Tk,2]
Available rotated keys; B,H,CachePosition,Dk for cache[1,1,Tk,2][1,1,Tk,2] with full position axis
Available unrotated values; last axis Dv[1,1,Tk,2][1,1,Tk,2]
Scores, allowed mask, attention weights; B,H,Query,Key[1,1,1,Tk][1,1,Tk,Tk]
FFN hidden features; B,T,HiddenFeature[1,1,3][1,Tk,3]
Logits; Position,Class[1,V][Tk,V]
Class probabilities; Class for the cached vector, Position,Class for full[V][Tk,V]

The class comparison places that cached vector alongside the full last row as matching [1,V] operands; it does not add a second query computation. The cached row has local array index0 and absolute position N. It must be compared with full row N. Both use key positions0 through N. A causal mask allows j≤the absolute query position, so every available key is allowed for this last query. Local0 is not a new position origin. ID/position evidence is int32, the mask is boolean, and floating arithmetic is binary64; formatted decimals are not new operands.

Reconstruct the shared prefill by hand

The next expressions are exact real derivations, not executed numerical results. Layer normalization computes mean μ, population variance v and normalized feature d by

μ=(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}.

Epsilon1 is inside the square root; the fixed per-feature scale gamma1 and offset beta0 leave these outputs unchanged. For a=(1,0), μ=1/2, centered features=(1/2,−1/2), v=1/4 and divisor=√5/2. Define α=1/√5 and u=(α,−α). Then LN1(a)=u and LN1(b)=−u. Identity Q/K/value projections preserve those coordinates; for example the first projected feature is α·1+(−α)·0=α.

RoPE, rotary positional encoding, applies

Rt(x,y)=(xcos⁡t−ysin⁡t, xsin⁡t+ycos⁡t)R_t(x,y)=(x\cos t-y\sin t,\ x\sin t+y\cos t)

to Q and K, using t radians at absolute position t. Values are not rotated. Prefill therefore saves K=[u,−R1u] and values=[u,−u]. At query0 only key0 is allowed. Its scaled score is g=2α²/√2=√2/5, weight1 and attention output u.

For query1 the scores are (−g cos1,g). Define e=exp(−g(1+cos1)) and p=e/(e+1). Subtracting maximum g gives exponential terms (e,1); accumulating from0 gives (0+e)+1. The mixed value is (2p−1)u. Write δ=1−2p>0, so this is (−αδ,αδ).

A residual adds corresponding input features back. The b row becomes R1_b=(−αδ,1+αδ). Its mean is1/2. With d_b=1/2+αδ and r_b=d_b/√(1+d_b²), second normalization gives (−r_b,r_b). The fixed feed-forward network (FFN) projects to three hidden coordinates, applies ReLU (retain positive values, replace negatives by0), then projects back. Here it maps (−r_b,r_b,0) to (0,r_b,0) and then (0,r_b). The second residual gives Y_b=(−αδ,1+αδ+r_b).

Readout produces logits (−αδ,1+αδ+r_b,0), so b wins. For the earlier a row substitute attention u: d_a=1/2+α, r_a=d_a/√(1+d_a²), Y_a=(1+α+r_a,−α), and logits (1+α+r_a,−α,0). Each row’s complete three-class distribution subtracts its own maximum, exponentiates all three shifts and divides by their ordered sum.

Derive the new a without recomputing old rows

Gather a=(1,0), normalize to u, and project new Q/K/value to u. Put c_t=cos t and s_t=sin t. Rotate the new Q and K at absolute2:

q=knew=(α(c2+s2),α(s2−c2)).q=k_{\mathrm{new}}=(\alpha(c_2+s_2),\alpha(s_2-c_2)).

Append this key and the unrotated value u, retaining both old K/V rows unchanged. The first dot product is

[α(c2+s2)]α+[α(s2−c2)](−α)=2α2c2.[\alpha(c_2+s_2)]\alpha+[\alpha(s_2-c_2)](-\alpha)=2\alpha^2c_2.

The middle uses old key −R1u:

[α(c2+s2)][−α(c1+s1)]+[α(s2−c2)][α(c1−s1)]=−2α2c1.[\alpha(c_2+s_2)][-\alpha(c_1+s_1)] +[\alpha(s_2-c_2)][\alpha(c_1-s_1)]=-2\alpha^2c_1.

The self product is [α(c2+s2)]²+[α(s2−c2)]²=2α². The simplifications use cos(2−1)=cos1 and sin²2+cos²2=1. Actual floating products need not obey those simplified identities bit for bit. Dividing each dot sum by√2 gives scores (g cos2,−g cos1,g); all three permissions are true.

Subtract maximum g and exponentiate:

e0=exp⁡(g(cos⁡2−1)),e1=exp⁡(−g(1+cos⁡1)),e2=1,Z=((0+e0)+e1)+1,pj=ej/Z.e_0=\exp(g(\cos2-1)),\quad e_1=\exp(-g(1+\cos1)),\quad e_2=1, \qquad Z=((0+e_0)+e_1)+1,\quad p_j=e_j/Z.

Here p_j are attention weights, distinct from output-class probabilities. Accumulate the first mixed coordinate as ((0+p0·α)+p1·(−α))+p2·α, and the second as ((0+p0·(−α))+p1·α)+p2·(−α). In real arithmetic define h=p0−p1+p2=1−2p1; output is (αh,−αh). Since e1<1=e2 and e0>0, p1<1/2 and 0<h<1. Identity output projection preserves the mixture.

The remaining row is R1=(1+αh,−αh). Its mean1/2 gives centered features (d,−d) with d=1/2+αh, population variance d² and normalization divisor √(1+d²). Set r=d/√(1+d²)>0. LN2 is (r,−r); FFN hidden preactivations are (r,−r,0), ReLU gives (r,0,0) and the output contraction gives (r,0). All three hidden coordinates participate; zero is a computed result. Thus

Y=(1+αh+r,−αh).Y=(1+\alpha h+r,-\alpha h).

Write A=1+αh+r. Readout calculates two products, their sum and then bias for each active class: logits are (A,−αh,0). Maximum A yields

Zclass=((0+1)+exp⁡(−αh−A))+exp⁡(−A),P=(1,exp⁡(−αh−A),exp⁡(−A))/Zclass.Z_{\mathrm{class}}=((0+1)+\exp(-\alpha h-A))+\exp(-A),\qquad P=(1,\exp(-\alpha h-A),\exp(-A))/Z_{\mathrm{class}}.

P contains exactly three probabilities, including EOS. Adding two inactive zero-logit classes would change every probability. Strict computed-logit argmax chooses a/97; exact ties retain the lowest compact class. Rounded displayed probabilities do not decide ties.

What equivalence does, and does not, establish

In the full-prefix path, causality preserves earlier K/V: the future key is forbidden for earlier queries, and normalization/FFN are row-local. Its last row uses the same new embedding, absolute2 rotation, ordered keys, mask and contractions as the cached append. This establishes exact-real equivalence. In deeper decoders the argument repeats inductively per layer, with separate layer caches.

The comparison must retain both actual operands, their componentwise signed subtractions, absolute errors and running maxima for K, values, attention, Y, logits and P. For a coordinate i, let C_i be the cached operand and F_i its full-prefix counterpart. Start a running maximum m at0; calculate the signed subtraction Δ_i=C_i−F_i, absolute error a_i=|Δ_i|, then replace m by max(m,a_i). An early discrepancy cannot disappear because a later coordinate happens to match. These operations use stored values before display formatting.

Retaining old cache entries unchanged within one implementation is a separate copy check. Neither check is replaced by writing0 into an expected-error field.

Different elementary-function libraries can round sine, cosine or exp differently. Independent witnesses therefore assess each actual record under the declared numerical assumptions. They do not certify universal cross-language bit equality. Near a logit tie, small differences can change a valid argmax; exact cross-language ID agreement needs a certified margin or exact tie anchor. Two branches choosing a says less than their full logits and probability rows agreeing.

For a concrete position error, reset BOTH new Q/K to0 but retain correct old keys. Scores become (g,−g cos1,g), replacing e0 by1. Since e0<1, this changes p1 and h, yet a can still win. Unrotated keys, double-rotated old keys and rotated values supply other distinct wrong calculations. With all-a input, every value is u and normalized mixtures remain u in exact arithmetic, concealing some score errors downstream.

Count actual work without claiming a speed measurement

Both branches share one real prefill. For a non-EOS append, actual harness neural rows are N+1+(N+1)=2N+2: N shared prefill rows, one cached row and N+1 full-reference rows. At reset that is2+1+3=6. The append attention stores Tk cached score cells versus Tk² full cells:3 versus9 at reset. The full kernel retains even future forbidden raw-score evidence; masking makes the corresponding probabilities0.

Separate cold alternatives would cost N+1 cached rows and 2N+1 uncached rows, including their own prefills. Adding those totals would count this harness’s shared prefill twice. Cached attention still reads all Tk keys and values; its next-query work grows with context. These are declared operation counts for a one-layer toy, not latency, speedup, heap usage or training-quality measurements. IV-50 develops the memory and cost accounting further.

EOS, token boundaries and invalidation

Select nextID512. Logical IDs become [97,98,512], strict decoding reconstructs ab, and execution stops after prefill. No new cache entry, append query, full append reference, comparison delta or placeholder zero tensor exists. Actual neural rows=N, not2N+2. The standalone numeric append helper permits observed active EOS; this wrapper’s terminal policy deliberately stops before invoking it.

With text ab, merges2 and nextID256, prompt IDs are [256] and logical append gives [256,256], decoding to abab. Fresh BPE on those characters would produce [257]; that is a different token sequence. Both branches must retain actual observed boundaries and use learned rules for strict reverse decoding, without retokenizing after append.

Cache reuse requires matching ordered requested IDs, positions and fixed revision. All26 numeric fields must match under the conservative policy, including readout-only and inactive embedding edits that need not mathematically alter past K/V. A changed embedding can directly invalidate them. Finite, frozen, correctly shaped external arrays still do not prove numeric coherence; external helpers require it as a precondition. The app builds caches from raw controls internally and never accepts raw K/V.

Raw state has exactly28 fields: text, merges, ten E entries, ten U entries, five biases and nextID. All numeric fields, including inactive ones and nextID’s active membership, validate before text semantics. E/U lie in [−2,2], biases in [−4,4], merges is integer0..2. Text is raw a/b, at most6 UTF-8 bytes; the outer UTF-16 guard precedes strict surrogate checks, actual bytes, alphabet and emptiness. Actual prompt BPE must yield1..2 IDs, extended neural input at most3. No invalid state is silently coerced, normalized or cropped; an invalid unused parameter remains invalid on EOS too.

The lab’s five actual graded checks give corrective feedback from the saved branch. Use the current prompt length, actual work and actual comparison operands when answering; a stopped branch has no append evidence to infer.

The checks move from the meaning of shared prefill to live shapes, work counts, interpretation of saved predictions and errors, then reuse policy. On a non-EOS state, read the one-query Q, the key-axis score tensor, the class probability vector [V] and separate logits [1,V]. The work table distinguishes shared prefill from both append calls; the six comparison tables retain every operand and error coordinate. The evidence question reads actual winner probabilities and maxima, so no rounded probability or assumed zero error supplies the answer.

After selecting EOS512, the shape check instead uses the actual prefill K and unchanged cache-entry count. The work check retains the N prefill rows and reports zero append rows/score cells because both calls are absent. The evidence check uses the real prefill prediction and probability; there are no append predictions or comparison magnitudes. For the transfer check, distinguish an actual change to the conservative all26 parameter identity from the narrower mathematical dependencies of old K/V. These are the same five lab questions with branch-aware feedback, defined once in the lab above.

Follow the actual Python source

Each panel imports a maintained file as raw text. Keep the relative directories intact: the loaders resolve dependencies from their own file locations. NumPy and Python’s standard library are required for later execution. Reading these panels does not run code or establish Python/TypeScript parity. The entry point accepts no arguments for fresh defaults, one complete replacement JSON state, or - for a complete state on standard input; a partial object is not an edit patch. Its strict JSON parser rejects duplicate keys and non-JSON NaN, Infinity and -Infinity. Invalid input returns an unavailable record with a code and reason, rather than stale numerical results. The explicit --self-check mode is separate from a state query; ordinary queries invoke no self-checks.

Chapter entry — code/python/p12/iv49.py. Guarded derive_iv49 calls cached_vs_full in the adjacent cache module. _raw_state(state,True) validates all28 fields, including active nextID, before text semantics. cache_prompt(text,merges,2) obtains the actual two-token-bounded prompt from IV39 once. Setup and tokenizer evidence precede one prefill_cache call and the logical append/stop decision. Non-EOS alone calls genuine append_cached under cached and separate scoped_forward under uncached; six actual comparison families and computed prediction/copy evidence follow. EOS omits those calls and their evidence entirely. Both branches extract the same saved learned rules through _inference._tokenizer_rules(prompt) and call _bpe.decode_bpe_ids on the retained result IDs, with terminal EOS stripping only on the stopped branch. Actual reverse steps, ID/byte tensors and finish counts then reach chapter_record, which detaches the complete ordered status, outputs, steps, tensors, texts record, with summaries before all saved step-output aliases.

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.

"""IV49: complete canonical cached/full observed append and logical EOS.

No args uses defaults; full JSON or '-' stdin replaces all28 raw fields.
--self-check invokes only this file's declared leaf, outside query fault catch.
"""
import importlib.util
from pathlib import Path
from types import MappingProxyType

_path = Path(__file__).resolve().with_name("cache_reference.py")
_spec = importlib.util.spec_from_file_location("_p12_iv49_cache", _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_IV49 = MappingProxyType(dict(_helper.DEFAULT_IV49))


@_helper.guarded
def derive_iv49(state):
    """Derive the full adopted IV49 record; no implicit self-checks."""
    return _helper.cached_vs_full(state)


def source_self_check():
    """DEFERRED complete-record/EOS/guard leaf; no dependency check calls."""
    assert __debug__, "Deferred checks require assertions enabled."
    assert Path(_helper.__file__).resolve() == _path
    assert list(DEFAULT_IV49) == ["text", *_helper.NUMERIC_DEFAULTS, "nextID"]
    state = dict(DEFAULT_IV49)
    record = derive_iv49(state)
    _helper._assert_complete_record(record, 375, 236)
    outputs = record["outputs"]
    summary_names = ["promptTokens", "cacheEntries", "cachedNewQueryRows", "comparisonAvailable", "stoppedEOS", "decodeExecuted", "nextID", "logicalResultTokens", "absoluteAppendPosition", "prefillQueryRows", "fullNewQueryRows", "actualHarnessRows", "coldCachedRows", "coldFullRows", "prefillScoreCells", "cachedScoreCells", "fullScoreCells", "actualHarnessScoreCells", "classCount", "actualMerges", "B", "D", "H", "Dk", "Dv", "hiddenWidth", "byteBound", "prefillNextRow", "prefillNextID", "prefillNextProbability"]
    conditional = ["cachedNextRow", "cachedNextID", "cachedNextProbability", "fullNextRow", "fullNextID", "fullNextProbability", "predictionsEqual", "retainedExact", "KMaxError", "VMaxError", "AttentionMaxError", "YMaxError", "LogitsMaxError", "PMaxError"]
    expected = [*summary_names, *conditional, "resultByteCount", *(f"tokenizer_{key}" for key in _helper._TOKENIZER_SUMMARY)]
    assert list(outputs)[:len(expected)] == expected
    assert list(record["texts"]) == ["input", "decoded", "nextIDSource", "stopPolicy", "cacheRevision", "cacheTrust", "modelIdentityPolicy", "comparisonPolicy", "modelVocabulary", "tokenizer_corpus", "tokenizer_input", "tokenizer_corpusDecoded", "tokenizer_decoded", "tokenizer_corpusLabels", "tokenizer_corpusExpansions", "tokenizer_targetLabels", "tokenizer_targetExpansions", "tokenizer_ruleLabels", "tokenizer_ruleExpansions", "tokenizer_trainingStop"]
    assert _helper._tensor_values(record, "ResultIDs") == [97, 98, 97]
    assert record["texts"]["decoded"] == "aba" and outputs["resultByteCount"] == 3
    assert outputs["actualHarnessRows"] == 6 and outputs["cachedNewQueryRows"] == 1 and outputs["fullNewQueryRows"] == 3
    assert outputs["coldCachedRows"] == 3 and outputs["coldFullRows"] == 5 and outputs["actualHarnessScoreCells"] == 16
    assert outputs["predictionsEqual"] == int(outputs["cachedNextID"] == outputs["fullNextID"])
    assert outputs["cachedNextID"] == 97 and outputs["nextID"] == 97
    _helper._assert_comparisons(record, [1, 2], [1, 3])
    for prefix, frames, tensors in (("prefill_", 113, 61), ("cached_", 57, 67), ("uncached_", 169, 57)):
        assert sum(step["id"].startswith(prefix) for step in record["steps"]) == frames
        assert sum(item["id"].startswith(prefix) for item in record["tensors"]) == tensors
    capture = next(step for step in record["steps"] if step["id"] == "prefill_capture")
    assert list(capture["inputs"]) == ["N", "inputID0", "inputID1", "rotatedK0", "rotatedK1", "rotatedK2", "rotatedK3", "projectedV0", "projectedV1", "projectedV2", "projectedV3"]
    assert record["steps"][-1]["label"] == "Count actual harness work and distinguish overlapping cold logical paths"
    stopped = derive_iv49({**state, "nextID": 512})
    _helper._assert_complete_record(stopped, 141, 82)
    assert _helper._tensor_values(stopped, "ResultIDs") == [97, 98, 512] and stopped["texts"]["decoded"] == "ab"
    assert stopped["outputs"]["cacheEntries"] == 2 and stopped["outputs"]["actualHarnessRows"] == 2
    assert stopped["outputs"]["cachedNewQueryRows"] == stopped["outputs"]["fullNewQueryRows"] == 0
    assert not any(key in stopped["outputs"] for key in conditional)
    eos_summary = [*summary_names, "resultByteCount", *(f"tokenizer_{key}" for key in _helper._TOKENIZER_SUMMARY)]
    assert list(stopped["outputs"])[:len(eos_summary)] == eos_summary
    assert not any(step["id"].startswith(("cached_", "uncached_", "compare_", "prediction_comparison")) for step in stopped["steps"])
    assert not any(item["id"].startswith(("cached_", "uncached_", "Compare")) for item in stopped["tensors"])
    assert any(step["id"] == "result_strip_eos" for step in stopped["steps"])
    merged = derive_iv49({**state, "merges": 2, "nextID": 256})
    assert _helper._tensor_values(merged, "ResultIDs") == [256, 256] and merged["texts"]["decoded"] == "abab"
    maximum = derive_iv49({**state, "text": "ababab", "merges": 2, "nextID": 257})
    _helper._assert_complete_record(maximum, 442, 255)
    assert _helper._tensor_values(maximum, "ResultIDs") == [257, 256, 257] and maximum["outputs"]["resultByteCount"] == 10
    max_eos = derive_iv49({**state, "text": "ababab", "merges": 2, "nextID": 512})
    _helper._assert_complete_record(max_eos, 181, 101)
    assert max_eos["outputs"]["actualHarnessRows"] == 2
    for patch, code in (({"text": "aaa"}, "UNSUPPORTED_SIZE"), ({"nextID": 256}, "INVALID_INPUT"),
                        ({"text": "\ud800", "nextID": True}, "NONFINITE"), ({"text": "\ud800", "nextID": 512}, "INVALID_INPUT"),
                        ({"nextID": 512, "e40": 3}, "INVALID_INPUT"), ({"nextID": 512, "b4": float("nan")}, "NONFINITE"),
                        ({"text": "a" * 6 + "\ud800", "nextID": 512}, "UNSUPPORTED_SIZE"), ({"text": "é" * 4, "nextID": 512}, "UNSUPPORTED_SIZE"),
                        ({"text": "é", "nextID": 512}, "UNAVAILABLE"), ({"text": [], "nextID": True}, "INVALID_INPUT"),
                        ({"text": "\ud800", "e40": 3, "nextID": True}, "INVALID_INPUT"), ({"text": "", "nextID": 256}, "INVALID_INPUT")):
        fault = derive_iv49({**state, **patch})
        assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
    assert derive_iv49({})["code"] == derive_iv49({**state, "extra": 0})["code"] == "INVALID_INPUT"
    record["tensors"][0]["values"].clear()
    record["texts"]["modelVocabulary"].clear()
    assert derive_iv49(state)["tensors"][0]["values"] and derive_iv49(state)["texts"]["modelVocabulary"]
    assert state == dict(DEFAULT_IV49)


if __name__ == "__main__":
    _helper.run(derive_iv49, DEFAULT_IV49, source_self_check)

Cache mechanics — code/python/p12/cache_reference.py. empty_cache validates parameters and creates empty metadata. prefill_cache performs the real full forward and copies its rotated K and unrotated V. append_cached first checks structure, model identity and requested prefix, then gathers only the new embedding. Follow its two-product score sums, ascending-key softmax and value mixture, residuals, normalization, FFN and active readout. The scalar products and running sums correspond to the hand derivation above; they are not an animation or a slice of recomputed old queries. Its external coherence precondition remains explicit.

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 XII canonical NumPy and complete owner-adopted ordered records.

Keep the disclosed twelve-file relative source closure. External cache numeric
coherence is an INPUT PRECONDITION; metadata cannot certify finite forgeries.
Helpers return detached plain data and never mutate inputs. Python callers can
mutate their own returns; no freezing is claimed. All execution is deferred.
"""
import argparse
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):
    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


_inference = _load("_p12_inference", _ROOT / "p11" / "inference_reference.py")
_choice = _load("_p12_choice", _ROOT / "p11" / "choice_reference.py")
_tiny, _iv39 = _inference._tiny, _inference._iv39
_bpe, _token = _inference._bpe, _inference._token
_component, _head, _ffn = _tiny._component, _tiny._head, _tiny._ffn
NumericalFault = _tiny.NumericalFault
_DEPENDENCY_FAULTS = (*_inference._DEPENDENCY_FAULTS, _choice.NumericalFault)
NUMERIC_DEFAULTS, ALL_IDS = _tiny.NUMERIC_DEFAULTS, _tiny.ALL_IDS
DEFAULT_IV48 = MappingProxyType(dict(text="aba", **NUMERIC_DEFAULTS))
DEFAULT_IV49 = MappingProxyType(dict(_inference.DEFAULT_IV44))
REVISION = "tiny-kv-v1"
CACHE_FIELDS = ("revision", "parameters", "ids", "positions", "keys", "values")


def detached(value):
    """Copy finite JSON; returned Python lists belong to their caller."""
    return json.loads(json.dumps(value, allow_nan=False, ensure_ascii=False))


def guarded(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))
    call.__name__, call.__doc__ = derive.__name__, derive.__doc__
    return call


def _prefix(prefix):
    if type(prefix) is not str or not prefix:
        raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")


def _array(values, label):
    # Exact built-ins reject custom access before reading numerical entries.
    if type(values) is not list:
        raise NumericalFault("INVALID_INPUT", f"{label} must have the ordinary Array prototype.")
    if len(values) > 6:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} exceeds 6 stored entries.")


def _token_length(length, allow_empty=True):
    if not allow_empty and not length:
        raise NumericalFault("UNAVAILABLE", "Numeric prefill requires at least one observed token.")
    if length > 3:
        raise NumericalFault("UNSUPPORTED_SIZE", "Cache prefixes support at most 3 observed tokens.")


def _active_id(value, active, label):
    if type(value) not in (int, float):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an active public model ID.")
    try:
        number = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("INVALID_INPUT", f"{label} must be an active public model ID.") from error
    if not math.isfinite(number) or not number.is_integer() or number not in active:
        raise NumericalFault("INVALID_INPUT", f"{label} must be an active public model ID.")
    return int(number)


def _cache(parameters, ids, keys, values):
    return detached(dict(revision=REVISION, parameters=parameters, ids=ids,
                         positions=list(range(len(ids))), keys=keys, values=values))


def empty_cache(parameters):
    """Validate all26; empty metadata emits no neural step or empty tensor."""
    return _cache(_tiny.numeric_parameters(parameters), [], [], [])


def _validated_append(parameters, expected_prefix_ids, cache, new_id, prefix):
    """Signed guard order, with zero new neural arithmetic before acceptance."""
    _prefix(prefix)
    target = _tiny.numeric_parameters(parameters)
    if type(cache) is not dict:
        raise NumericalFault("INVALID_INPUT", "cache must be a plain object.")
    if any(type(key) is not str for key in cache) or set(cache) != set(CACHE_FIELDS):
        raise NumericalFault("INVALID_INPUT", "cache requires exactly revision, parameters, ids, positions, keys, values as own data fields.")
    if type(cache["revision"]) is not str or cache["revision"] != REVISION:
        raise NumericalFault("INVALID_INPUT", "cache.revision must be tiny-kv-v1.")
    old = _tiny.numeric_parameters(cache["parameters"])
    for key in ("ids", "positions", "keys", "values"):
        _array(cache[key], f"cache.{key}")
    N = len(cache["ids"])
    _token_length(N)
    if len(cache["positions"]) != N or len(cache["keys"]) != 2 * N or len(cache["values"]) != 2 * N:
        raise NumericalFault("SHAPE_MISMATCH", "cache positions length must be N; keys and values lengths must be 2N.")
    ids = [_active_id(value, ALL_IDS[:3 + old["merges"]], f"cache.ids[{j}]") for j, value in enumerate(cache["ids"])]
    for j, value in enumerate(cache["positions"]):
        if type(value) not in (int, float) or value != j:
            raise NumericalFault("INVALID_INPUT", "CACHE_POSITION_MISMATCH: positions must be exact ordered integers 0..N-1.")
    keys = [_tiny.finite(value, f"cache.keys[{j}]") for j, value in enumerate(cache["keys"])]
    values = [_tiny.finite(value, f"cache.values[{j}]") for j, value in enumerate(cache["values"])]
    _array(expected_prefix_ids, "expectedPrefixIDs")
    _token_length(len(expected_prefix_ids))
    expected = [_active_id(value, ALL_IDS[:3 + target["merges"]], f"expectedPrefixIDs[{j}]") for j, value in enumerate(expected_prefix_ids)]
    scalar = _tiny.finite(new_id, "newID")
    if not scalar.is_integer() or scalar not in ALL_IDS[:3 + target["merges"]]:
        raise NumericalFault("INVALID_INPUT", "newID must be an active public model ID.")
    if any(target[key] != old[key] for key in NUMERIC_DEFAULTS):
        raise NumericalFault("UNAVAILABLE", "CACHE_MODEL_MISMATCH: all 26 numeric parameters must agree under numeric ===.")
    if expected != ids:
        raise NumericalFault("UNAVAILABLE", "CACHE_PREFIX_MISMATCH: the requested ordered prefix must equal cache.ids.")
    if N >= 3:
        raise NumericalFault("UNSUPPORTED_SIZE", "Appending would exceed 3 observed cache entries.")
    return target, old, ids, keys, values, int(scalar)


def _scope(trace, saved, prefix, context):
    for step in saved.steps:
        trace.add(f"{prefix}_{step['id']}", f"{prefix}: {step['label']}", step["equation"],
                  f"{context} {step['explanation']}", step["inputs"], step["outputs"])


def _old_step(step):
    """Literal adopted old primitive prose; never parse TS or interpret math."""
    identifier, inputs = step["id"], step["inputs"]
    label, equation, explanation = step["label"], step["equation"], step["explanation"]
    head_id = identifier.removeprefix("heads_")
    if identifier.startswith(("ln1_", "ln2_")):
        if identifier.endswith("_statistics"):
            stem = identifier.removesuffix("_statistics")
            label = f"{stem}: feature-only mean and population variance"
            equation = "sum=x0+x1; mean=sum/2; centered=x-mean; squareSum=centered0²+centered1²; variance=squareSum/2; denominator=sqrt(variance+epsilon)"
            explanation = "Only these two features contribute. Epsilon is inside the square root; no batch or token statistics are mixed."
        else:
            explanation = "The source is the saved centered feature. Gamma and beta may change output mean and variance."
    elif identifier.startswith("ffn_hidden_"):
        explanation = "The same W1 and b1 apply separately to each token. Add bias after the two input products; no token sum occurs."
    elif identifier.startswith("ffn_relu_"):
        explanation = "ReLU means rectified linear unit: keep a positive value and replace a nonpositive value with zero, including zero itself."
    elif identifier.startswith("ffn_output_"):
        explanation = "Multiply then immediately accumulate hidden features in ascending order 0,1,2. Add b2 last. Output may be signed; there is no softmax or residual inside the FFN."
    elif head_id == "setup":
        label, equation = "Validate every scalar slot, then select active dimensions", "D=2; X[B,T,2]; WQ,WK[2,H*Dk]; WV[2,H*Dv]"
        explanation = "All inactive fields remain finite and bounded. Parameter names identify input d, head h and feature f, so changing width never relabels a head’s weights."
    elif head_id.startswith("project_"):
        role = head_id.split("_")[1]
        b, t, h, f = (int(inputs[key]) for key in ("b", "t", "h", "f"))
        label = f"{role}[{b},{t},head {h},feature {f}]: both input contributions"
        explanation = "One token row times the packed column h*F+f, keeping both input-feature rows. Weights are hand-set; no bias, activation or learning is hidden."
    elif head_id.startswith("reshape_"):
        role = head_id.split("_")[1]
        label, equation = f"{role}: reshape the packed feature axis", "[B,T,H*F] → [B,T,H,F]; feature=h*F+f"
        explanation = "Reshaping preserves every flat value and its order. H counts attention heads; F counts features within each head. No projection feature is dropped."
    elif head_id.startswith("permute_"):
        role = head_id.split("_")[1]
        b, t, h, f = (int(inputs[key]) for key in ("b", "t", "h", "f"))
        label = f"{role}: copy [{b},{t},{h},{f}] to [{b},{h},{t},{f}]"
        equation = "axes [0,2,1,3]; destination[b,h,t,f]=source[b,t,h,f]"
        explanation = "Moving the head axis is a declared permutation, separate from reshape. The recorded offsets are actual row-major flat indices; this indexed value is copied unchanged."
    elif head_id.startswith("score_"):
        explanation = "Matching features are multiplied inside this batch and head only. Dk, not H or T or Dv, supplies the scaling width. Signed scores are not probabilities."
    elif head_id.startswith("row_"):
        b, h, i = (int(inputs[key]) for key in ("b", "h", "i"))
        label = f"Batch {b}, head {h}, query {i}: key-axis stable softmax"
        explanation = "Each head has its own probabilities. Key validity is shared across batches and heads; queries remain. Forbidden terms are exactly zero, without an infinity sentinel or invented shifted value. Allowed terms can underflow; a large common shift can change low bits."
    elif head_id.startswith("head_mix_"):
        b, h, i, f = (int(inputs[key]) for key in ("b", "h", "i", "f"))
        label = f"OHeads[{b},{h},{i},{f}]: this head’s weighted values"
        explanation = "Use the real probability row and values in the same head and batch. Compute each product, then immediately accumulate in ascending key order, including actual zero times V for forbidden keys. No averaging across heads or extra division."
    elif head_id.startswith("concat_"):
        b, t, h, f, c = (int(inputs[key]) for key in ("b", "t", "h", "f", "concatFeature"))
        label = f"Join head {h}, feature {f} into C[{b},{t},{c}]"
        explanation = "Copy one actual head output unchanged. Concatenate in head order then within-head feature order; never average heads or mix batches."
    elif head_id.startswith("output_"):
        b, t, d = (int(inputs[key]) for key in ("b", "t", "d"))
        label = f"Y[{b},{t},{d}]: explicit output projection"
        equation = "product_c=C_c*WO[c,d]; running starts at 0; running_c=previous+product_c; Y=last running sum"
        explanation = "WO rows preserve named head/feature identity when Dv changes. Every joined feature contributes one recorded product and running sum. Y may be signed; no output softmax, bias, residual, dropout or normalization is added."
    elif identifier.startswith("input_"):
        t = int(inputs["t"])
        label, equation = f"Gather observed token at position {t}", "inputRow=compactRow(inputID); X[0,t,:]=E[inputRow,:]"
        explanation = "EOS is an ordinary available embedding row in this numeric kernel. There is no implicit stop rule or target lookup."
    elif identifier.startswith("rope_"):
        role, t = identifier.split("_")[1], int(inputs["t"])
        label = f"Rotate {role} pair at absolute position {t}"
        equation = "frequency=10000^0; angle=t*frequency; cos=cos(angle); sin=sin(angle); rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos"
        explanation = "The only adjacent feature pair has frequency1 and angle t radians. Q and K rotate; V keeps its original projection. Every product and both final coordinates are saved."
    elif identifier.startswith(("residual1_", "residual2_")):
        t, d = int(inputs["t"]), int(inputs["d"])
        if identifier.startswith("residual1_"):
            label, equation = f"First residual position {t}, feature {d}", "value=X+AttentionOutput"
            explanation = "Add identical named [B,T,D] shapes without broadcasting. The shortcut carries the original embedding."
        else:
            label, equation = f"Second residual position {t}, feature {d}", "value=R1+F"
            explanation = "The FFN applies to each token separately; the real third hidden coordinate is computed with zero weights."
    elif identifier.startswith("readout_"):
        t, c = int(inputs["t"]), int(inputs["c"])
        label = f"Readout position {t}, class {c}"
        explanation = "Final decoder features multiply only the active class columns. Bias is added last; targets are not operands."
    elif identifier.startswith("class_"):
        t, kind = int(identifier.split("_")[1]), identifier.split("_")[2]
        if kind == "max":
            label = f"Position {t}: active class maximum"
            explanation = "The maximum stabilizes exponentiation; every active class participates before the target is selected."
        elif kind == "exp":
            label = f"Position {t}: exponentiate class {int(inputs['c'])}"
            explanation = "At least one term is exp(0)=1. No probability is clipped or rounded for this calculation."
        elif kind == "normalize":
            label = f"Position {t}: class denominator and logsumexp"
            equation = "running starts at 0; running_c=previous+term_c; S=last running; logS=ln(S); LSE=max+logS"
            explanation = "Terms accumulate left to right in compact class order. NLL later uses the factored max-minus-target form, not subtraction of a rounded LSE."
        elif kind == "probability":
            label, equation = f"Position {t}: normalize class {int(inputs['c'])}", "probability=term/S"
            explanation = "This is the stored binary64 probability for a real active class, before display formatting."
        elif kind == "argmax":
            label, equation = f"Position {t}: computed-logit winner", "argmax computed logits; exact ties choose smallest compact class"
            explanation = "Stored probabilities can appear tied even for different computed logits. This prediction is inspected, never fed back into teacher forcing."
    return label, equation, explanation


def _copy_old_steps(saved, trace, prefix="", context=""):
    for step in saved.steps:
        label, equation, explanation = _old_step(step)
        trace.add(f"{prefix}_{step['id']}" if prefix else step["id"], f"{prefix}: {label}" if prefix else label,
                  equation, f"{context} {explanation}" if context else explanation, step["inputs"], step["outputs"])


def _float(identifier, shape, axes, values, provenance):
    return _tiny._float_tensor(identifier, shape, axes, np.array(values, dtype=np.float64).reshape(shape), provenance)


def _integer(identifier, axis, values, provenance):
    return _token.tensor(identifier, axis, np.array(values, dtype=np.int32), provenance)


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


def cache_tensors(cache, stem):
    if not cache["ids"]:
        return []
    N = len(cache["ids"])
    return [
        _integer(f"{stem}IDs", "CachePosition", cache["ids"], "Ordered observed public IDs; cache coherence is an external-helper input precondition."),
        _integer(f"{stem}Positions", "CachePosition", cache["positions"], "Absolute positions 0..N-1, not local append-query indices."),
        _float(f"{stem}Keys", [1, 1, N, 2], ["B", "H", "CachePosition", "Dk"], cache["keys"], "Saved already-rotated K. Appends retain prior coordinates exactly; no second rotation."),
        _float(f"{stem}Values", [1, 1, N, 2], ["B", "H", "CachePosition", "Dv"], cache["values"], "Saved unrotated projected V in observed-prefix order."),
    ]


def scoped_forward(parameters, ids, trace, prefix):
    _prefix(prefix)
    numeric = _tiny.numeric_parameters(parameters)
    _array(ids, "inputIDs")
    _token_length(len(ids), False)
    ids = [_active_id(value, ALL_IDS[:3 + numeric["merges"]], f"inputIDs[{i}]") for i, value in enumerate(ids)]
    saved = _tiny.tiny_trace()
    forward = _tiny.forward_tiny(numeric, ids, saved)
    context = f"Actual full-prefix call {prefix}, absolute positions 0..{len(ids) - 1}."
    _copy_old_steps(saved, trace, prefix, context)
    return dict(forward=forward, tensors=_copy_records(forward["tensors"], f"{prefix}_", context))


def prefill_cache(parameters, input_ids, trace, prefix="prefill"):
    _prefix(prefix)
    numeric = _tiny.numeric_parameters(parameters)
    saved = scoped_forward(numeric, input_ids, trace, prefix)
    forward = saved["forward"]
    keys, values = _tensor_values(forward, "RotatedKHeads"), _tensor_values(forward, "ProjectionVHeads")
    cache = _cache(numeric, forward["inputIDs"], keys, values)
    inputs, outputs = dict(N=forward["T"]), dict(cacheEntries=len(cache["ids"]))
    for j, identifier in enumerate(cache["ids"]):
        inputs[f"inputID{j}"] = identifier
        outputs[f"id{j}"], outputs[f"position{j}"] = identifier, cache["positions"][j]
    for i, value in enumerate(keys):
        inputs[f"rotatedK{i}"], outputs[f"key{i}"] = value, cache["keys"][i]
    for i, value in enumerate(values):
        inputs[f"projectedV{i}"], outputs[f"value{i}"] = value, cache["values"][i]
    trace.add(f"{prefix}_capture", "Capture actual full-prefill rotated keys and unrotated values", "cache.K=RotatedKHeads; cache.V=ProjectionVHeads; positions=0..N-1",
              "The constructor establishes coherence from real forward outputs. It retains no old queries, hidden rows, logits or probabilities in the cache. Full prefill evidence remains separately saved.", inputs, outputs)
    return detached(dict(cache=cache, forward=forward, tensors=[*saved["tensors"], *cache_tensors(cache, f"{prefix}_Cache")]))


def _new_norm(name, source, trace, provenance):
    saved = _tiny.tiny_trace()
    row = _component.feature_norm("layer", f"{name.lower()}_0", source["values"], [1, 1], [0, 0], 1, saved)
    _copy_old_steps(saved, trace)
    return _float(name, [1, 1, 2], ["B", "T", "D"], row["values"], provenance)


def _new_residual(identifier, prefix, left, right, trace):
    result = _component.same_shape_add(identifier, left, right)
    inputs, outputs = {}, {}
    for d in range(2):
        inputs[f"left{d}"], inputs[f"right{d}"] = left["values"][d], right["values"][d]
        outputs[f"value{d}"] = result["values"][d]
    trace.add(prefix, f"{identifier}: both new-row residual coordinates", "value_d=left_d+right_d",
              "Exact same named [B,T,D] shapes; no broadcast or hidden coordinate omission.", inputs, outputs)
    return result


def append_cached(parameters, expected_prefix_ids, cache, new_id, trace, prefix="cache"):
    """Compute one new neural row; external cache coherence is a precondition."""
    s, old, ids, old_keys, old_values, new_id = _validated_append(parameters, expected_prefix_ids, cache, new_id, prefix)
    N, V, Tk = len(ids), 3 + s["merges"], len(ids) + 1
    before, saved = _cache(old, ids, old_keys, old_values), _tiny.tiny_trace()
    row = ALL_IDS.index(new_id)
    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 = E[row].copy().reshape(1, 1, 2)
    saved.add("input_0", f"Gather only new observed ID{new_id} at absolute position {N}", "inputRow=compactRow(newID); X=E[inputRow,:]",
              "Numeric helpers permit observed EOS; outer wrappers separately implement logical EOS stopping.",
              dict(position=N, newID=new_id), dict(inputRow=row, x0=float(X[0, 0, 0]), x1=float(X[0, 0, 1])))
    x_tensor = _float("X", [1, 1, 2], ["B", "T", "D"], X, "Only the new embedding row; local T=1, absolute position is saved separately.")
    n1 = _new_norm("LN1", x_tensor, saved, "New-row feature LayerNorm; population variance, epsilon1, gamma1, beta0.")
    tensors = [
        _integer("AllClassIDs", "ModelRow", ALL_IDS, "All possible compact model rows; public IDs are labels."),
        _integer("ClassIDs", "Class", ALL_IDS[:V], "Active compact prefix; V=3+merges."),
        _float("E", [5, 2], ["ModelRow", "D"], E, "All ten validated editable embeddings, including inactive rows."),
        _float("U", [2, 5], ["D", "ModelRow"], U, "All ten validated readout weights; active prefix alone produces logits."),
        _float("Bias", [5], ["ModelRow"], bias, "All five validated biases; inactive columns remain outside the distribution."),
        _integer("InputIDs", "LocalPosition", [new_id], "Exactly one new observed token is processed."),
        _integer("InputRows", "LocalPosition", [row], "Compact embedding row for the new token."),
        _integer("AbsoluteQueryPosition", "Query", [N], "Absolute N, distinct from the single local query index0."),
        *cache_tensors(before, "Before"), x_tensor, n1,
    ]
    hs = dict(_head.OUTPUT_HEAD_DEFAULTS)
    hs.update(B=1, T=1, H=1, Dk=2, Dv=2, mode=1, shift=0, x000=n1["values"][0], x001=n1["values"][1])
    for role in ("wq", "wk", "wv"):
        for d in range(2):
            for f in range(2):
                hs[f"{role}{d}0{f}"] = int(d == f)
    for f in range(2):
        for d in range(2):
            hs[f"wo0{f}{d}"] = int(f == d)
    child = _head.head_trace()
    projected = _head.project_heads(hs, child)
    _copy_old_steps(child, saved, "heads", "Source is the new LN1 row, local T=1.")
    tensors.extend({**record, "id": f"Projection{record['id']}", "provenance": f"New LN1 row only. {_tiny._PROJECTION_PROVENANCE[record['id']]}"} for record in projected["tensors"])
    rotated = {}
    angle = cosine = sine = 0.0
    for role in ("Q", "K"):
        x0, x1 = (float(projected[f"{role}Heads"][0, 0, 0, d]) for d in range(2))
        frequency = 10000 ** 0
        angle = _tiny.finite(N * frequency, "RoPE angle")
        cosine, sine = _tiny.finite(math.cos(angle), "RoPE cosine"), _tiny.finite(math.sin(angle), "RoPE sine")
        p0, p1 = _tiny.finite(x0 * cosine, "RoPE x0*cos"), _tiny.finite(x1 * sine, "RoPE x1*sin")
        p2, p3 = _tiny.finite(x0 * sine, "RoPE x0*sin"), _tiny.finite(x1 * cosine, "RoPE x1*cos")
        r0, r1 = _tiny.finite(p0 - p1, "RoPE first coordinate"), _tiny.finite(p2 + p3, "RoPE second coordinate")
        rotated[role] = np.array([r0, r1], dtype=np.float64).reshape(1, 1, 1, 2)
        saved.add(f"rope_{role}_0", f"Rotate new {role} at absolute position {N}", "frequency=10000^0; angle=N*frequency; rotated0=x0*cos-x1*sin; rotated1=x0*sin+x1*cos",
                  "Only the new Q/K rotate. Cached K is already rotated and V never rotates. Each product and coordinate is real arithmetic.",
                  dict(position=N, x0=x0, x1=x1, base=10000, exponent=0),
                  dict(frequency=frequency, angle=angle, cos=cosine, sin=sine, product0=p0, product1=p1, product2=p2, product3=p3, rotated0=r0, rotated1=r1))
    new_key, new_value = rotated["K"].reshape(-1).tolist(), projected["VHeads"].reshape(-1).tolist()
    tensors.extend([
        _float("RotatedQHeads", [1, 1, 1, 2], ["B", "H", "Query", "Dk"], rotated["Q"], "New query rotated at absolute N; Query length1."),
        _float("NewRotatedKHeads", [1, 1, 1, 2], ["B", "H", "NewPosition", "Dk"], rotated["K"], "Only the newly computed key, rotated once at absolute N."),
        _float("RoPEAngles", [1], ["Query"], [angle], "Actual absolute N times frequency1, radians."),
        _float("RoPECos", [1], ["Query"], [cosine], "Cosine used by new Q/K rotations."),
        _float("RoPESin", [1], ["Query"], [sine], "Sine used by new Q/K rotations."),
    ])
    after = _cache(s, [*ids, new_id], [*old_keys, *new_key], [*old_values, *new_value])
    copy_inputs = dict(N=N, newID=new_id, newK0=new_key[0], newK1=new_key[1], newV0=new_value[0], newV1=new_value[1])
    copy_outputs, retained_exact = dict(cacheEntries=Tk), 1
    for family, previous, current in (("ID", ids, after["ids"]), ("Position", before["positions"], after["positions"]), ("K", old_keys, after["keys"]), ("V", old_values, after["values"])):
        for i, value in enumerate(previous):
            copy_inputs[f"before{family}{i}"] = value
            equal = int(value == current[i])
            copy_outputs[f"retained{family}{i}"] = equal
            retained_exact = int(retained_exact and equal)
        for i, value in enumerate(current):
            copy_outputs[f"after{family}{i}"] = value
    copy_outputs["retainedExact"] = retained_exact
    if not retained_exact:
        raise NumericalFault("UNAVAILABLE", "Retained cache coordinates changed during append.")
    saved.add("append", "Copy prior K/V unchanged and append one actual new row", "after=[before,new]; retained_i=(before_i===after_i)",
              "Same-implementation retained-copy equality is a narrow check, separate from cross-library numerical witnesses. Empty-before has metadata only, never a zero-shape tensor.", copy_inputs, copy_outputs)
    tensors.extend(cache_tensors(after, "After"))
    K = np.array(after["keys"], dtype=np.float64).reshape(1, 1, Tk, 2)
    values = np.array(after["values"], dtype=np.float64).reshape(1, 1, Tk, 2)
    q = rotated["Q"]
    shape, axes = [1, 1, 1, Tk], ["B", "H", "Query", "Key"]
    raw, scores, logits, terms, probabilities = (np.empty(shape, dtype=np.float64) for _ in range(5))
    allowed = np.array([j <= N for j in after["positions"]], dtype=np.bool_).reshape(shape)
    divisor = _tiny.finite(math.sqrt(2), "sqrt(Dk)")
    for j in range(Tk):
        q0, q1, k0, k1 = float(q[0, 0, 0, 0]), float(q[0, 0, 0, 1]), float(K[0, 0, j, 0]), float(K[0, 0, j, 1])
        p0, p1 = _tiny.finite(q0 * k0, "score product0"), _tiny.finite(q1 * k1, "score product1")
        dot = _tiny.finite(p0 + p1, "raw score")
        score = _tiny.finite(dot / divisor, "scaled score")
        raw[0, 0, 0, j], scores[0, 0, 0, j] = dot, score
        saved.add(f"score_{j}", f"New absolute query {N} against cached key {j}", "product0=q0*k0; product1=q1*k1; raw=product0+product1; score=raw/sqrt(Dk)",
                  "The query axis has length1; the key axis has length N+1. Only this new query is evaluated.",
                  dict(position=N, j=j, Dk=2, divisor=divisor, q0=q0, k0=k0, q1=q1, k1=k1), dict(product0=p0, product1=p1, raw=dot, score=score))
    for j in range(Tk):
        logits[0, 0, 0, j] = _tiny.finite(float(scores[0, 0, 0, j]) + 0, "attention common shift")
    maximum = max(float(logits[0, 0, 0, j]) for j in range(Tk) if allowed[0, 0, 0, j])
    inputs, outputs, denominator = dict(position=N, shift=0), dict(max=maximum), 0.0
    for j in range(Tk):
        inputs.update({f"score{j}": float(scores[0, 0, 0, j]), f"keyPosition{j}": after["positions"][j], f"allowed{j}": int(allowed[0, 0, 0, j])})
        logit = float(logits[0, 0, 0, j])
        shift = _tiny.finite(logit - maximum, "attention shifted logit")
        term = _tiny.finite(math.exp(shift), "attention exp") if allowed[0, 0, 0, j] else 0.0
        terms[0, 0, 0, j] = term
        denominator = _tiny.finite(denominator + term, "attention denominator")
        outputs.update({f"logit{j}": logit, f"shifted{j}": shift, f"term{j}": term, f"running{j}": denominator})
    if not denominator > 0:
        raise NumericalFault("FULLY_MASKED_ROW", "The new query has no allowed key.")
    outputs["denominator"] = denominator
    for j in range(Tk):
        probability = _tiny.finite(float(terms[0, 0, 0, j]) / denominator, "attention probability")
        probabilities[0, 0, 0, j], outputs[f"p{j}"] = probability, probability
    saved.add("row", "Normalize every available key at the absolute append position", "logit=score+0; allowed=(keyPosition<=N); max=max(allowed logits); term=exp(logit-max); running starts0; p=term/denominator",
              "All available positions0..N are allowed. Comparing keys to local query0 would be wrong. Every shift, exponential and left-to-right running sum is retained.", inputs, outputs)
    O = np.empty((1, 1, 1, 2), dtype=np.float64)
    for d in range(2):
        inputs, outputs, running = dict(d=d), {}, 0.0
        for j in range(Tk):
            probability, value = float(probabilities[0, 0, 0, j]), float(values[0, 0, j, d])
            product = _tiny.finite(probability * value, "weighted V product")
            running = _tiny.finite(running + product, "weighted V running sum")
            inputs[f"p{j}"], inputs[f"v{j}"] = probability, value
            outputs[f"product{j}"], outputs[f"running{j}"] = product, running
        O[0, 0, 0, d], outputs["value"] = running, running
        saved.add(f"mix_{d}", f"Mix unrotated value feature {d}", "product_j=p_j*v_j; running starts0; running_j=previous+product_j; value=last running",
                  "Multiply then immediately accumulate in ascending cached-key order.", inputs, outputs)
    tensors.extend([
        _float("Attentionraw", shape, axes, raw, "Actual two-product new Q dot every cached K."),
        _float("Attentionscores", shape, axes, scores, "Raw dot products divided by sqrt(Dk=2)."),
        _head.tensor("Attentionallowed", shape, axes, allowed, "Allowed iff cached absolute key position <= absolute query N."),
        _float("Attentionlogits", shape, axes, logits, "Actual scaled scores plus the fixed common shift0."),
        _float("Attentionprobabilities", shape, axes, probabilities, "Stable softmax over the complete cached key axis; Query length1."),
        _float("AttentionOHeads", [1, 1, 1, 2], ["B", "H", "Query", "Dv"], O, "New query weighted sum of all unrotated cached V."),
    ])
    C = O.transpose(0, 2, 1, 3).copy().reshape(1, 1, 2)
    saved.add("concat", "Copy the one-head output into joined feature order", "C[d]=OHeads[0,0,0,d]; sourceOffset=d; destinationOffset=d",
              "H=1 still has a real declared copy; both coordinates and offsets are retained.",
              dict(sourceOffset0=0, sourceValue0=float(O[0, 0, 0, 0]), sourceOffset1=1, sourceValue1=float(O[0, 0, 0, 1])),
              dict(destinationOffset0=0, c0=float(C[0, 0, 0]), destinationOffset1=1, c1=float(C[0, 0, 1])))
    WO, attention = np.eye(2, dtype=np.float64), np.empty((1, 1, 2), dtype=np.float64)
    for d in range(2):
        inputs, outputs, running = dict(d=d), {}, 0.0
        for f in range(2):
            c, w = float(C[0, 0, f]), float(WO[f, d])
            product = _tiny.finite(c * w, "WO product")
            running = _tiny.finite(running + product, "WO running sum")
            inputs[f"c{f}"], inputs[f"w{f}"] = c, w
            outputs[f"product{f}"], outputs[f"running{f}"] = product, running
        attention[0, 0, d], outputs["value"] = running, running
        saved.add(f"output_{d}", f"Identity output projection feature {d}", "product0=c0*w0; running0=0+product0; product1=c1*w1; running1=running0+product1; value=running1",
                  "Identity WO is actually multiplied in the same order as the full-prefix kernel; neither products nor zero additions are bypassed.", inputs, outputs)
    tensors.extend([
        _float("AttentionC", [1, 1, 2], ["B", "T", "JoinedValue"], C, "One-head Query to local token-major joined-feature copy."),
        _float("AttentionWO", [2, 2], ["JoinedValue", "D"], WO, "Explicit identity2 output projection."),
        _float("AttentionOutput", [1, 1, 2], ["B", "T", "D"], attention, "C WO for one local row, with explicit identity WO."),
    ])
    r1 = _new_residual("R1", "residual1", x_tensor, tensors[-1], saved)
    n2 = _new_norm("LN2", r1, saved, "New-row feature LayerNorm of R1; population variance, epsilon1, gamma1, beta0.")
    fs = dict(B=1, T=1, 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)
    child = _tiny.tiny_trace()
    ffn = _ffn.feed_forward(fs, n2, child, "ffn")
    _copy_old_steps(child, saved)
    ft = [{**record, "provenance": _tiny._FFN_PROVENANCE[record["id"]]} for record in ffn["tensors"]]
    y = _new_residual("Y", "residual2", r1, ffn["output"], saved)
    tensors.extend([r1, n2, *ft, y])
    z = np.empty(V, dtype=np.float64)
    for c in range(V):
        y0, y1, u0, u1, b = y["values"][0], y["values"][1], float(U[0, c]), float(U[1, c]), float(bias[c])
        p0, p1 = _tiny.finite(y0 * u0, "readout product0"), _tiny.finite(y1 * u1, "readout product1")
        summed = _tiny.finite(p0 + p1, "readout sum")
        z[c] = _tiny.finite(summed + b, "readout logit")
        saved.add(f"readout_{c}", f"Read out active compact class {c}", "product0=y0*u0; product1=y1*u1; sum=product0+product1; logit=sum+bias",
                  "Only V=3+merges active columns are output classes; all five storage columns were validated.",
                  dict(c=c, y0=y0, u0=u0, y1=y1, u1=u1, bias=b), dict(product0=p0, product1=p1, sum=summed, logit=float(z[c])))
    tensors.append(_float("Logits", [1, V], ["Position", "Class"], z, "Actual new Y times active U, then active Bias."))
    distribution = _choice.direct_distribution(z, np.array(ALL_IDS[:V], dtype=np.int32), saved, "class")
    tensors.extend({**record, "id": f"Choice{record['id']}"} for record in distribution["tensors"])
    _scope(trace, saved, prefix, f"True one-query append: local row0 is absolute position {N}; no prior query or old K/V projection is recomputed.")
    tensors = _copy_records(tensors, f"{prefix}_", f"Actual cached append {prefix}: local row0 is absolute {N}; no old query/K/V recomputation.")
    return detached(dict(before=before, cache=after, position=N, newID=new_id, distribution=distribution, tensors=tensors))


def _raw_state(state, observed_append=False):
    defaults = DEFAULT_IV49 if observed_append else DEFAULT_IV48
    if type(state) is not dict:
        reason = "Provide a plain object with exactly the named input fields." if observed_append else "Provide a plain object with exactly the named data fields."
        raise NumericalFault("INVALID_INPUT", reason)
    if any(type(key) is not str for key in state) or set(state) != set(defaults):
        reason = "Provide every field, including inactive parameters, and no extra or symbol fields." if observed_append else "Provide every own field and no extra or symbol fields, including inactive parameters."
        raise NumericalFault("INVALID_INPUT", reason)
    checked = _tiny.tiny_state({key: state[key] for key in DEFAULT_IV48})
    if observed_append:
        next_id = _tiny.finite(state["nextID"], "nextID")
        if not next_id.is_integer() or next_id not in ALL_IDS[:3 + checked["numeric"]["merges"]]:
            raise NumericalFault("INVALID_INPUT", "nextID must be an active public ID: a97, b98, EOS512, ab256 with merges>=1, or abab257 with merges=2.")
        checked["nextID"] = int(next_id)
    return checked


def cache_prompt(text, merges, token_bound=3):
    """Real IV39 once, then the adopted outer text/token semantics in order."""
    if type(text) is not str:
        raise NumericalFault("INVALID_INPUT", "text must be an actual string.")
    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.")
    if _token.utf16_length(text) > 6:
        raise NumericalFault("UNSUPPORTED_SIZE", "text exceeds the outer 6 UTF-16-unit guard for a 6-byte prompt.")
    prompt = _iv39.derive_iv39(dict(corpus="abab", text=text, merges=int(merges), eos=0))
    if prompt["status"] != "defined":
        raise NumericalFault(prompt["code"], prompt["reason"])
    values = lambda identifier: next((record["values"] for record in prompt["tensors"] if record["id"] == identifier), [])
    data = values("SourceBytes")
    if len(data) > 6:
        raise NumericalFault("UNSUPPORTED_SIZE", "The actual UTF-8 prompt exceeds 6 bytes.")
    if any(byte not in (97, 98) for byte in data):
        reason = "This toy prompt accepts raw a/b letters only, without normalization, unknown tokens or truncation." if token_bound == 3 else "This toy prompt accepts raw a/b letters only; no normalization, unknown token or truncation is applied."
        raise NumericalFault("UNAVAILABLE", reason)
    if not data:
        reason = "An empty prompt has no observed first token." if token_bound == 3 else "An empty prompt has no observed first token to prefill."
        raise NumericalFault("UNAVAILABLE", reason)
    ids = np.array(values("TargetIDs"), dtype=np.int32)
    if len(ids) > token_bound:
        reason = "The actual BPE prompt exceeds 3 tokens; change text or merges explicitly." if token_bound == 3 else "The actual BPE prompt exceeds 2 tokens; change the text or merges explicitly."
        raise NumericalFault("UNSUPPORTED_SIZE", reason)
    return prompt, ids


def _copy_records(records, stem, context):
    return [{**record, "id": f"{stem}{record['id']}", "provenance": f"{context} {record['provenance']}"} for record in records]


def _prompt_evidence(prompt, trace):
    for step in prompt["steps"]:
        trace.add(f"tokenizer_{step['id']}", step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
    return _copy_records(prompt["tensors"], "tokenizer_", "Actual prompt BPE once, fixed corpus abab and EOS off.")


def compare_values(name, cached, full, shape, axes, trace, tensors):
    """Save each actual subtraction, absolute value and running maximum."""
    if len(cached) != len(full):
        raise NumericalFault("SHAPE_MISMATCH", f"{name}: comparison operands must have identical lengths.")
    a, b = (np.array(values, dtype=np.float64).reshape(shape) for values in (cached, full))
    delta, absolute, running = (np.empty(shape, dtype=np.float64) for _ in range(3))
    inputs, outputs, maximum = dict(count=len(cached), initialMaximum=0), {}, 0.0
    for i, (left, right) in enumerate(zip(cached, full)):
        inputs[f"cached{i}"], inputs[f"full{i}"] = left, right
        difference = _tiny.finite(left - right, f"{name} subtraction")
        error = _tiny.finite(abs(difference), f"{name} absolute error")
        maximum = max(maximum, error)
        delta.flat[i], absolute.flat[i], running.flat[i] = difference, error, maximum
        outputs[f"delta{i}"], outputs[f"absolute{i}"], outputs[f"runningMax{i}"] = difference, error, maximum
    outputs["maximum"] = maximum
    trace.add(f"compare_{name}", f"Compare every actual {name} coordinate", "delta_i=cached_i-full_i; absolute_i=abs(delta_i); runningMax_i=max(previous,absolute_i)",
              "These are actual saved operands, subtractions and maxima. No zero fill, rounding or universal cross-library bitwise assertion is used.", inputs, outputs)
    for suffix, data, provenance in (("Cached", a, "Actual cached operands."), ("Full", b, "Actual independently recomputed full-prefix operands."),
                                     ("Delta", delta, "Actual cached-full subtraction."), ("Abs", absolute, "Actual abs(Delta)."),
                                     ("RunningMax", running, "Actual running maximum from0 in flat coordinate order.")):
        tensors.append(_float(f"Compare{name}{suffix}", shape, axes, data, provenance))
    return maximum


_TOKENIZER_SUMMARY = ("corpusBytes", "byteCount", "actualMerges", "tokenCount", "requestedMerges", "corpusTokens", "eos", "byteBound", "vocabularyItems", "corpusEqual", "equal")
_MODEL_VOCABULARY = ["0: a / ID97", "1: b / ID98", "2: EOS / ID512", "3: ab / ID256 (merges>=1)", "4: abab / ID257 (merges=2)"]
_CACHE_TRUST = "External helper callers must supply coherent K/V. Finite metadata, freezing and structural checks do not certify arbitrary supplied payloads. The app constructs every cache internally."


def chapter_record(summary, trace, tensors, texts):
    """Detach the complete root, summary then every ordered scalar alias."""
    outputs = dict(summary)
    for step in trace.steps:
        outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
    return detached(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))


def cache_growth(state):
    """Complete IV48: genuine observed-token growth and one full reference."""
    checked = _raw_state(state)
    text, numeric = checked["text"], checked["numeric"]
    prompt, observed = cache_prompt(text, numeric["merges"])
    ids, trace, N, V = observed.tolist(), _tiny.tiny_trace(), len(observed), 3 + numeric["merges"]
    trace.add("setup", "Validate every raw field before interpreting text; start with empty cache metadata", "N=actual BPE token count1..3; active V=3+merges; fixed corpus abab; EOS off",
              "All26 numeric fields validate before Unicode/domain checks. The app accepts no raw K/V. Each cache row is constructed internally at its absolute position; the final reference is one genuine full-prefix call.",
              numeric, dict(utf16Units=_token.utf16_length(text), byteBound=6, tokenBound=3, observedTokens=N, classCount=V, initialCacheEntries=0))
    tensors = _prompt_evidence(prompt, trace)
    cache, cached_score_cells, retained_exact = empty_cache(numeric), 0, 1
    growth, query_rows, key_counts, copies = [], [], [], []
    for t, identifier in enumerate(ids):
        saved = append_cached(numeric, ids[:t], cache, identifier, trace, f"growth{t}")
        growth.append(saved)
        tensors.extend(saved["tensors"])
        cache = saved["cache"]
        cached_score_cells += len(cache["ids"])
        exact = int(saved["before"]["keys"] == cache["keys"][:2 * t] and saved["before"]["values"] == cache["values"][:2 * t])
        retained_exact = int(retained_exact and exact)
        query_rows.append(1)
        key_counts.append(len(cache["ids"]))
        copies.append(exact)
        trace.add(f"growth_count_{t}", f"Count actual query work after observed token {t}", "newQueryRows=1; runningQueryRows=previous+1; keyCount=t+1; runningScoreCells=previous+keyCount",
                  "One append computes one new neural row. Prior K/V is copied, not reprojected. These are toy operation counts, never timings.",
                  dict(t=t, previousQueryRows=t, previousScoreCells=cached_score_cells - len(cache["ids"]), newQueryRows=1, keyCount=len(cache["ids"])),
                  dict(cachedQueryRows=t + 1, cachedScoreCells=cached_score_cells, cacheEntries=len(cache["ids"]), retainedExact=exact))
    reference = scoped_forward(numeric, ids, trace, "reference")
    tensors.extend(reference["tensors"])
    full = reference["forward"]
    from_growth = lambda identifier: [value for t, saved in enumerate(growth) for value in _tensor_values(saved, f"growth{t}_{identifier}")]
    comparisons = {}
    for name, left, right, width, feature in (
        ("K", cache["keys"], _tensor_values(full, "RotatedKHeads"), 2, "Dk"),
        ("V", cache["values"], _tensor_values(full, "ProjectionVHeads"), 2, "Dv"),
        ("Attention", from_growth("AttentionOHeads"), _tensor_values(full, "AttentionOHeads"), 2, "Dv"),
        ("Y", from_growth("Y"), _tensor_values(full, "Y"), 2, "D"),
        ("Logits", from_growth("Logits"), _tensor_values(full, "Logits"), V, "Class"),
        ("P", [value for saved in growth for value in saved["distribution"]["probabilities"]], _tensor_values(full, "P"), V, "Class"),
    ):
        comparisons[f"{name}MaxError"] = compare_values(name, left, right, [N, width], ["Position", feature], trace, tensors)
    tensors.extend([
        _integer("ObservedIDs", "Position", ids, "Actual EOS-off observed BPE IDs, never sampled or retokenized."),
        _integer("GrowthQueryRows", "Append", query_rows, "Actual new query-row count for each genuine append."),
        _integer("GrowthKeyCounts", "Append", key_counts, "Actual available cached keys for each append."),
        _integer("GrowthRetainedExact", "Append", copies, "Computed same-implementation prior K/V equality flags; not a cross-library assertion."),
    ])
    trace.add("finish", "Report true cache growth and one complete reference", "cachedQueryRows=N; referenceQueryRows=N; actualHarnessRows=2*N",
              "Causality lets each new cached row be compared with its corresponding row of the single final full-prefix call. Every error is computed from actual saved operands.",
              dict(observedTokens=N, cachedQueryRows=len(growth), referenceQueryRows=full["T"], cachedScoreCells=cached_score_cells, referenceScoreCells=N * N),
              dict(cacheEntries=len(cache["ids"]), actualHarnessRows=len(growth) + full["T"], retainedExact=retained_exact, **comparisons))
    last = growth[-1]["distribution"]
    summary = dict(observedTokens=N, cacheEntries=len(cache["ids"]), cachedQueryRows=len(growth), YMaxError=comparisons["YMaxError"],
                   cachedScoreCells=cached_score_cells, referenceQueryRows=full["T"], referenceScoreCells=N * N, actualHarnessRows=len(growth) + full["T"],
                   retainedExact=retained_exact, KMaxError=comparisons["KMaxError"], VMaxError=comparisons["VMaxError"], AttentionMaxError=comparisons["AttentionMaxError"],
                   LogitsMaxError=comparisons["LogitsMaxError"], PMaxError=comparisons["PMaxError"], classCount=V, actualMerges=numeric["merges"],
                   B=1, D=2, H=1, Dk=2, Dv=2, hiddenWidth=3, byteBound=6, lastNextRow=last["nextRow"], lastNextID=last["nextID"], lastNextProbability=last["nextProbability"])
    summary.update({f"tokenizer_{key}": prompt["outputs"][key] for key in _TOKENIZER_SUMMARY})
    texts = dict(input=text, decoded=prompt["texts"]["decoded"], cacheRevision=cache["revision"], cacheTrust=_CACHE_TRUST,
                 modelIdentityPolicy="All26 numeric parameters must agree under numeric ===, including readout and inactive embeddings; signed zeros are equivalent. This is a conservative reuse policy, not the minimal mathematical K/V dependency.",
                 positionPolicy="Each cache entry stores absolute position j; each append has local query0 at absolute agreed prefix length N. Q/K rotate once; V never rotates.", modelVocabulary=_MODEL_VOCABULARY)
    texts.update({f"tokenizer_{key}": value for key, value in prompt["texts"].items()})
    return chapter_record(summary, trace, tensors, texts)


def cached_vs_full(state):
    """Complete IV49: one shared prefill, genuine new row/full path, EOS absence."""
    checked = _raw_state(state, True)
    text, numeric, next_id = checked["text"], checked["numeric"], checked["nextID"]
    prompt, observed = cache_prompt(text, numeric["merges"], 2)
    ids, trace, N, V = observed.tolist(), _tiny.tiny_trace(), len(observed), 3 + numeric["merges"]
    stopped, result_ids = int(next_id == 512), [*ids, next_id]
    trace.add("setup", "Validate all raw fields before text semantics; tokenize exactly once", "N=actual prompt tokens1..2; nextID is external observed input; active V=3+merges",
              "All numeric parameters and nextID validate before Unicode/domain interpretation, even when nextID is EOS. Both real comparison paths share one actual full-prefill call.",
              dict(**numeric, nextID=next_id), dict(utf16Units=_token.utf16_length(text), byteBound=6, tokenBound=2, promptTokens=N, classCount=V))
    tensors = _prompt_evidence(prompt, trace)
    prefill = prefill_cache(numeric, ids, trace, "prefill")
    tensors.extend(prefill["tensors"])
    before, comparisons, predictions = prefill["forward"]["rows"][-1], {}, {}
    decode_executed = 1 - stopped
    cached_rows, full_rows = decode_executed, 0 if stopped else N + 1
    cached_cells, full_cells = (0, 0) if stopped else (N + 1, (N + 1) * (N + 1))
    cache_entries = len(prefill["cache"]["ids"])
    trace.add("append_decision", "Append the external ID logically and apply EOS stopping", "ResultIDs=[PromptIDs,nextID]; nextID=512 => no append neural work",
              "The supplied nextID is not replaced by a model prediction. EOS is a logical tail marker decoded without an EOS gather, new cache row, second forward, copy comparison or phantom delta.",
              dict(promptTokens=N, nextID=next_id, EOS=512),
              dict(logicalResultTokens=len(result_ids), stoppedEOS=stopped, decodeExecuted=decode_executed, absoluteAppendPosition=N,
                   cachedNewQueryRows=cached_rows, fullNewQueryRows=full_rows, cachedScoreCells=cached_cells, fullScoreCells=full_cells))
    if not stopped:
        cached = append_cached(numeric, ids, prefill["cache"], next_id, trace, "cached")
        tensors.extend(cached["tensors"])
        uncached = scoped_forward(numeric, result_ids, trace, "uncached")
        tensors.extend(uncached["tensors"])
        full, cache_entries = uncached["forward"], len(cached["cache"]["ids"])
        for name, left, right, shape, axes in (
            ("K", cached["cache"]["keys"], _tensor_values(full, "RotatedKHeads"), [N + 1, 2], ["Position", "Dk"]),
            ("V", cached["cache"]["values"], _tensor_values(full, "ProjectionVHeads"), [N + 1, 2], ["Position", "Dv"]),
            ("Attention", _tensor_values(cached, "cached_AttentionOHeads"), _tensor_values(full, "AttentionOHeads")[N * 2:], [1, 2], ["Position", "Dv"]),
            ("Y", _tensor_values(cached, "cached_Y"), _tensor_values(full, "Y")[N * 2:], [1, 2], ["Position", "D"]),
            ("Logits", cached["distribution"]["logits"], _tensor_values(full, "Logits")[N * V:], [1, V], ["Position", "Class"]),
            ("P", cached["distribution"]["probabilities"], _tensor_values(full, "P")[N * V:], [1, V], ["Position", "Class"]),
        ):
            comparisons[f"{name}MaxError"] = compare_values(name, left, right, shape, axes, trace, tensors)
        last, distribution = full["rows"][N], cached["distribution"]
        retained_exact = int(cached["before"]["keys"] == cached["cache"]["keys"][:N * 2] and cached["before"]["values"] == cached["cache"]["values"][:N * 2])
        predictions.update(cachedNextRow=distribution["nextRow"], cachedNextID=distribution["nextID"], cachedNextProbability=distribution["nextProbability"],
                           fullNextRow=last["nextRow"], fullNextID=last["nextID"], fullNextProbability=last["nextProbability"],
                           predictionsEqual=int(distribution["nextID"] == last["nextID"]), retainedExact=retained_exact)
        trace.add("prediction_comparison", "Compare actual computed-logit decisions and retained copies", "predictionsEqual=(cachedNextID===fullNextID); exact ties use lowest compact index in each real path",
                  "Agreement of IDs alone does not establish numerical equivalence. Six complete operand/error families are retained separately; same-implementation copied K/V equality is a narrower fact.",
                  dict(cachedNextRow=distribution["nextRow"], cachedNextID=distribution["nextID"], fullNextRow=last["nextRow"], fullNextID=last["nextID"]),
                  dict(predictionsEqual=predictions["predictionsEqual"], retainedExact=retained_exact))
    reverse = _token.TokenTrace()
    decoded = _bpe.decode_bpe_ids(np.array(result_ids, dtype=np.int32), _inference._tokenizer_rules(prompt), stopped, "result", reverse)
    for step in reverse.steps:
        trace.add(step["id"], step["label"], step["equation"], step["explanation"], step["inputs"], step["outputs"])
    tensors.extend([
        _integer("PromptIDs", "PromptPosition", ids, "Actual EOS-off prompt BPE IDs."),
        _integer("ResultIDs", "LogicalPosition", result_ids, "Retained prompt IDs plus exactly one supplied ID; terminal EOS is logical only."),
        _integer("ResultBytes", "Bytes", decoded["bytes"], "Actual strict reverse-decoder expansions with the same learned rules; EOS emits no bytes."),
    ])
    harness_rows = N + cached_rows + full_rows
    trace.add("finish", "Count actual harness work and distinguish overlapping cold logical paths", "harness=N+cachedNewQueryRows+fullNewQueryRows; coldCached=N+cachedNewQueryRows; coldFull=N+fullNewQueryRows",
              "The prefill is shared once. Do not add the two cold logical path totals as actual work. Counts concern this one-layer toy, with no latency, training-quality or universal speedup claim.",
              dict(promptTokens=N, cachedNewQueryRows=cached_rows, fullNewQueryRows=full_rows, prefillScoreCells=N * N, cachedScoreCells=cached_cells, fullScoreCells=full_cells),
              dict(actualHarnessRows=harness_rows, cacheEntries=cache_entries, resultByteCount=len(decoded["bytes"]), coldCachedRows=N + cached_rows, coldFullRows=N + full_rows))
    summary = dict(promptTokens=N, cacheEntries=cache_entries, cachedNewQueryRows=cached_rows, comparisonAvailable=decode_executed,
                   stoppedEOS=stopped, decodeExecuted=decode_executed, nextID=next_id, logicalResultTokens=len(result_ids), absoluteAppendPosition=N,
                   prefillQueryRows=N, fullNewQueryRows=full_rows, actualHarnessRows=harness_rows, coldCachedRows=N + cached_rows, coldFullRows=N + full_rows,
                   prefillScoreCells=N * N, cachedScoreCells=cached_cells, fullScoreCells=full_cells, actualHarnessScoreCells=N * N + cached_cells + full_cells,
                   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"],
                   **predictions, **comparisons, resultByteCount=len(decoded["bytes"]))
    summary.update({f"tokenizer_{key}": prompt["outputs"][key] for key in _TOKENIZER_SUMMARY})
    texts = dict(input=text, decoded=decoded["decoded"],
                 nextIDSource="External observed input; not asserted to be a model-generated selection. A generator can later feed its selected public ID into the same append primitive.",
                 stopPolicy="EOS512 is appended logically then strict reverse-decoded; no new neural row, full append call, cache entry or comparison is computed.",
                 cacheRevision=prefill["cache"]["revision"], cacheTrust=_CACHE_TRUST,
                 modelIdentityPolicy="All26 numeric parameters must agree under numeric ===, including readout and inactive embeddings; signed zeros are equivalent. This conservative policy exceeds the minimal K/V dependency.",
                 comparisonPolicy="One shared real prefill, one genuine cached new query and one separate full-prefix append call. Inspection selects saved paths only. Compare all six error families as well as actual computed-logit decisions.",
                 modelVocabulary=_MODEL_VOCABULARY)
    texts.update({f"tokenizer_{key}": value for key, value in prompt["texts"].items()})
    return chapter_record(summary, trace, tensors, texts)


def _json_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate JSON key: {key}")
        result[key] = value
    return result


def _json_constant(value):
    raise ValueError(f"Invalid JSON constant: {value}")


_JSON_INT = int


def _json_integer(token):
    return -0.0 if token == "-0" else _JSON_INT(token)


def run(derive, defaults, self_check):
    """Default/full replacement JSON/'-' queries; --self-check is explicit only."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    parser.add_argument("--self-check", action="store_true")
    args = parser.parse_args()
    if args.self_check:
        if args.state is not None:
            parser.error("--self-check cannot be combined with a state query")
        self_check()  # Deliberately outside query fault catch: assertions must fail.
        return
    try:
        if args.state is None:
            state = dict(defaults)
        else:
            raw = sys.stdin.read() if args.state == "-" else args.state
            state = json.loads(raw, object_pairs_hook=_json_object,
                               parse_constant=_json_constant, parse_int=_json_integer)
        result = derive(state)
    except (ValueError, OSError) as error:
        result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
    print(json.dumps(result, allow_nan=False, ensure_ascii=False, separators=(",", ":")))


def _assert_complete_record(record, frame_count, tensor_count):
    """Deferred assertion utility, reached only from explicit check leaves."""
    assert list(record) == ["status", "outputs", "steps", "tensors", "texts"] and record["status"] == "defined"
    assert len(record["steps"]) == frame_count < 480 and len(record["tensors"]) == tensor_count
    assert len({step["id"] for step in record["steps"]}) == frame_count
    assert len({item["id"] for item in record["tensors"]}) == tensor_count
    flattened = {}
    for step in record["steps"]:
        assert list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"]
        assert all(type(step[key]) is str and step[key] for key in ("id", "label", "equation", "explanation"))
        assert all(type(value) in (int, float) and math.isfinite(value) for value in (*step["inputs"].values(), *step["outputs"].values()))
        for key, value in step["outputs"].items():
            alias = f"{step['id']}_{key}"
            assert alias not in flattened
            flattened[alias] = value
    assert list(record["outputs"])[-len(flattened):] == list(flattened)
    assert {key: record["outputs"][key] for key in flattened} == flattened
    assert all(type(value) in (int, float) and math.isfinite(value) for value in record["outputs"].values())
    for item in record["tensors"]:
        assert list(item) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
        assert len(item["shape"]) == len(item["axes"]) == len(set(item["axes"]))
        assert all(type(size) is int and 1 <= size <= 64 for size in item["shape"])
        assert math.prod(item["shape"]) == len(item["values"]) <= 4096
        expected_type = {"float64": float, "int32": int, "bool": bool}[item["dtype"]]
        assert all(type(value) is expected_type and math.isfinite(value) for value in item["values"])
        assert item["precision"] == (0 if item["dtype"] == "int32" else 8)
        assert type(item["provenance"]) is str and item["provenance"]
    assert all(type(value) is str or (type(value) is list and all(type(entry) is str for entry in value)) for value in record["texts"].values())
    assert detached(record) == record


def _assert_comparisons(record, row_shape, class_shape):
    """Actual errors/copies within Python; not independent numerical authority."""
    tensors = {item["id"]: item for item in record["tensors"]}
    steps = {step["id"]: step for step in record["steps"]}
    for name in ("K", "V", "Attention", "Y", "Logits", "P"):
        stem, maximum = f"Compare{name}", 0.0
        cached, full = tensors[f"{stem}Cached"]["values"], tensors[f"{stem}Full"]["values"]
        shape = [len(cached) // 2, 2] if name in ("K", "V") else class_shape if name in ("Logits", "P") else row_shape
        axes = ["Position", {"K": "Dk", "V": "Dv", "Attention": "Dv", "Y": "D", "Logits": "Class", "P": "Class"}[name]]
        inputs, outputs = ["count", "initialMaximum"], []
        for i, (left, right) in enumerate(zip(cached, full)):
            difference, error = left - right, abs(left - right)
            maximum = max(maximum, error)
            assert tensors[f"{stem}Delta"]["values"][i] == difference
            assert tensors[f"{stem}Abs"]["values"][i] == error
            assert tensors[f"{stem}RunningMax"]["values"][i] == maximum
            inputs.extend((f"cached{i}", f"full{i}"))
            outputs.extend((f"delta{i}", f"absolute{i}", f"runningMax{i}"))
        outputs.append("maximum")
        assert record["outputs"][f"{name}MaxError"] == steps[f"compare_{name}"]["outputs"]["maximum"] == maximum
        assert list(steps[f"compare_{name}"]["inputs"]) == inputs
        assert list(steps[f"compare_{name}"]["outputs"]) == outputs
        for suffix, provenance in (("Cached", "Actual cached operands."), ("Full", "Actual independently recomputed full-prefix operands."), ("Delta", "Actual cached-full subtraction."), ("Abs", "Actual abs(Delta)."), ("RunningMax", "Actual running maximum from0 in flat coordinate order.")):
            assert tensors[f"{stem}{suffix}"]["shape"] == shape and tensors[f"{stem}{suffix}"]["axes"] == axes
            assert tensors[f"{stem}{suffix}"]["provenance"] == provenance


def source_self_check():
    """DEFERRED explicit helper leaf; invokes NO dependency self-check."""
    assert __debug__, "Deferred checks require assertions enabled."
    parameters = dict(NUMERIC_DEFAULTS)
    assert len(parameters) == 26 and len(DEFAULT_IV48) == 27 and len(DEFAULT_IV49) == 28
    assert Path(_inference.__file__).resolve() == _ROOT / "p11" / "inference_reference.py"
    assert Path(_choice.__file__).resolve() == _ROOT / "p11" / "choice_reference.py"
    cache, rows = empty_cache(parameters), []
    assert list(cache) == list(CACHE_FIELDS) and cache["ids"] == cache["keys"] == cache["values"] == []
    for identifier in (97, 98, 97):
        before = detached(cache)
        trace = _tiny.tiny_trace()
        saved = append_cached(parameters, cache["ids"], cache, identifier, trace)
        assert cache == before and saved["before"] == before
        assert saved["cache"]["keys"][:-2] == before["keys"]
        assert saved["cache"]["values"][:-2] == before["values"]
        assert len(trace.steps) == len(saved["cache"]["ids"]) + 3 * (3 + parameters["merges"]) + 45
        assert len(saved["tensors"]) == (63 if not before["ids"] else 67)
        assert all(step["id"].startswith("cache_") for step in trace.steps)
        assert saved["before"]["parameters"] is not saved["cache"]["parameters"]
        for record in saved["tensors"]:
            assert list(record) == ["id", "shape", "axes", "dtype", "values", "provenance", "precision"]
            assert len(record["shape"]) == len(record["axes"]) == len(set(record["axes"]))
            assert all(type(size) is int and 1 <= size <= 64 for size in record["shape"])
            assert math.prod(record["shape"]) == len(record["values"]) <= 4096
            assert record["precision"] == (0 if record["dtype"] == "int32" else 8)
            expected_type = {"float64": float, "int32": int, "bool": bool}[record["dtype"]]
            assert all(type(value) is expected_type for value in record["values"])
        assert all(list(step) == ["id", "label", "equation", "explanation", "inputs", "outputs"] for step in trace.steps)
        rows.append(saved)
        cache = saved["cache"]
    full = _tiny.forward_tiny(parameters, [97, 98, 97], _tiny.tiny_trace())
    assert cache["keys"] == _tensor_values(full, "RotatedKHeads")
    assert cache["values"] == _tensor_values(full, "ProjectionVHeads")
    for position, saved in enumerate(rows):
        assert saved["distribution"]["logits"] == full["rows"][position]["logits"]
        assert saved["distribution"]["probabilities"] == full["rows"][position]["probabilities"]
        assert saved["distribution"]["nextID"] == (97, 98, 97)[position]
    prefill = prefill_cache(parameters, [97, 98], _tiny.tiny_trace())
    trace = _tiny.tiny_trace()
    numeric_eos = append_cached(parameters, [97, 98], prefill["cache"], 512, trace)
    assert numeric_eos["cache"]["ids"] == [97, 98, 512]
    assert numeric_eos["cache"]["keys"][-2:] == [0, 0]
    assert numeric_eos["cache"]["values"][-2:] == [0, 0]

    def rejects(call, code, reason=""):
        try:
            call()
        except _DEPENDENCY_FAULTS as error:
            assert error.code == code and reason in str(error), (error.code, str(error))
        else:
            raise AssertionError("Invalid helper boundary accepted")

    def attempt(model=parameters, expected=None, supplied=None, identifier=97, prefix="cache"):
        saved_trace = _tiny.tiny_trace()
        try:
            return append_cached(model, [97, 98] if expected is None else expected,
                                 prefill["cache"] if supplied is None else supplied, identifier, saved_trace, prefix)
        except _DEPENDENCY_FAULTS:
            assert not saved_trace.steps
            raise

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

    class HostileDict(dict):
        def __getitem__(self, key):
            raise AssertionError("Custom dict indexing must not run")

    rejects(lambda: attempt(prefix=None, model={}), "INVALID_INPUT", "prefix")
    rejects(lambda: attempt(supplied=HostileDict(prefill["cache"])), "INVALID_INPUT")
    rejects(lambda: attempt(supplied={**prefill["cache"], "keys": HostileList()}), "INVALID_INPUT")
    rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [float("nan"), 98], "values": []}), "SHAPE_MISMATCH")
    rejects(lambda: attempt(expected=HostileList([97, 98])), "INVALID_INPUT")
    rejects(lambda: attempt(supplied={**prefill["cache"], "keys": [0] * 7}), "UNSUPPORTED_SIZE")
    rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [float("nan"), 98], "values": [0] * 7}), "UNSUPPORTED_SIZE")
    rejects(lambda: attempt(expected=[97] * 4), "UNSUPPORTED_SIZE")
    rejects(lambda: attempt(expected=[97] * 7), "UNSUPPORTED_SIZE")
    rejects(lambda: attempt(supplied={**prefill["cache"], "positions": [0, 0]}), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
    rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [True, 98]}), "INVALID_INPUT")
    rejects(lambda: attempt(identifier=True), "NONFINITE")
    rejects(lambda: attempt(identifier=float("nan")), "NONFINITE")
    rejects(lambda: attempt(identifier=256), "INVALID_INPUT")
    rejects(lambda: attempt(model={**parameters, "u04": 1}), "UNAVAILABLE", "CACHE_MODEL_MISMATCH")
    rejects(lambda: attempt(model={**parameters, "e40": 0}), "UNAVAILABLE", "CACHE_MODEL_MISMATCH")
    rejects(lambda: attempt(expected=[98, 97]), "UNAVAILABLE", "CACHE_PREFIX_MISMATCH")
    rejects(lambda: attempt(supplied=cache, expected=[97, 98, 97]), "UNSUPPORTED_SIZE")
    rejects(lambda: attempt(supplied=cache, expected=[98, 97, 97]), "UNAVAILABLE", "CACHE_PREFIX_MISMATCH")
    rejects(lambda: prefill_cache(parameters, HostileList([97]), _tiny.tiny_trace()), "INVALID_INPUT")
    rejects(lambda: prefill_cache(parameters, [], _tiny.tiny_trace()), "UNAVAILABLE")
    # Simultaneous faults pin the signed structural -> entries -> request order.
    rejects(lambda: attempt(model={}, supplied=HostileDict()), "INVALID_INPUT", "every own field")
    rejects(lambda: attempt(supplied={**prefill["cache"], "revision": "other", "parameters": {}}), "INVALID_INPUT", "revision")
    rejects(lambda: attempt(supplied={**prefill["cache"], "parameters": {}, "keys": HostileList()}), "INVALID_INPUT", "every own field")
    rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [97] * 4, "values": HostileList()}), "INVALID_INPUT", "ordinary Array prototype")
    rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [97] * 4}), "UNSUPPORTED_SIZE")
    rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [True, 98], "positions": [0, 0]}), "INVALID_INPUT", "cache.ids")
    rejects(lambda: attempt(supplied={**prefill["cache"], "positions": [0, 0], "keys": [float("nan")] * 4}), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
    rejects(lambda: attempt(supplied={**prefill["cache"], "keys": [float("nan")] * 4}, expected=HostileList()), "NONFINITE", "cache.keys")
    rejects(lambda: attempt(supplied={**prefill["cache"], "values": [True] * 4}, identifier=256), "NONFINITE", "cache.values")
    rejects(lambda: attempt(expected=[True], identifier=float("nan")), "INVALID_INPUT", "expectedPrefixIDs")
    rejects(lambda: attempt(model={**parameters, "u04": 1}, expected=[98, 97], identifier=True), "NONFINITE", "newID")
    rejects(lambda: attempt(model={**parameters, "u04": 1}, expected=[98, 97]), "UNAVAILABLE", "CACHE_MODEL_MISMATCH")
    rejects(lambda: attempt(supplied={**cache, "positions": [1, 2, 3]}, expected=[98, 97, 97]), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
    for invalid_ids, code in (((), "INVALID_INPUT"), ([97] * 4, "UNSUPPORTED_SIZE"), ([True], "INVALID_INPUT")):
        rejected_trace = _tiny.tiny_trace()
        rejects(lambda: prefill_cache(parameters, invalid_ids, rejected_trace), code)
        assert not rejected_trace.steps
    # Numeric equality deliberately equates signed zero and rounded-away edits.
    assert attempt(model={**parameters, "u04": -0.0})["cache"]["parameters"]["u04"] == 0
    assert attempt(model={**parameters, "e00": 1 + math.ulp(0.0)})["cache"]["parameters"]["e00"] == 1
    for model in ({**parameters, "merges": 2, "e00": -0.75, "e01": 1.25, "u00": -1.5, "b4": 0.5},
                  {**parameters, **{key: 0 for key in parameters if key != "merges"}}):
        coherent = prefill_cache(model, [97, 98], _tiny.tiny_trace())["cache"]
        appended = append_cached(model, [97, 98], coherent, 97, _tiny.tiny_trace())
        reference_full = _tiny.forward_tiny(model, [97, 98, 97], _tiny.tiny_trace())
        assert appended["cache"]["keys"] == _tensor_values(reference_full, "RotatedKHeads")
        assert appended["cache"]["values"] == _tensor_values(reference_full, "ProjectionVHeads")
        assert appended["distribution"]["logits"] == reference_full["rows"][-1]["logits"]
        assert appended["distribution"]["probabilities"] == reference_full["rows"][-1]["probabilities"]
        if not any(model[key] for key in model if key != "merges"):
            assert appended["distribution"]["nextRow"] == 0 and appended["distribution"]["nextID"] == 97
    try:
        json.loads('{"text":"a","text":"b"}', object_pairs_hook=_json_object)
    except ValueError as error:
        assert "Duplicate JSON key: text" in str(error)
    else:
        raise AssertionError("Duplicate CLI JSON keys were accepted")
    assert list(prefill) == ["cache", "forward", "tensors"]
    assert len(prefill["tensors"]) == 61
    assert list(saved) == ["before", "cache", "position", "newID", "distribution", "tensors"]
    assert list(saved["distribution"]) == ["classIDs", "logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability", "tensors"]
    assert len(saved["distribution"]["tensors"]) == 11
    for bad in (10 ** 1000, float("inf"), True, None):
        rejects(lambda: attempt(supplied={**prefill["cache"], "ids": [bad, 98]}), "INVALID_INPUT")
        rejects(lambda: attempt(supplied={**prefill["cache"], "positions": [bad, 1]}), "INVALID_INPUT", "CACHE_POSITION_MISMATCH")
    # Exercise CLI routing with local streams; no subprocess or dependency checks.
    class Stream:
        def __init__(self, value=""):
            self.value = value
        def read(self):
            return self.value
        def write(self, value):
            self.value += value
            return len(value)
        def flush(self):
            pass

    original = sys.argv, sys.stdin, sys.stdout
    calls = []

    def query(value):
        calls.append(value)
        return dict(status="defined", value=value)

    def forbidden_check():
        raise AssertionError("Ordinary CLI query invoked a self-check")

    try:
        raw = json.dumps(dict(DEFAULT_IV48), allow_nan=False)
        for argument in ([], [raw], ["-"]):
            sys.argv, sys.stdin, sys.stdout = ["iv48.py", *argument], Stream(raw), Stream()
            run(query, DEFAULT_IV48, forbidden_check)
            assert json.loads(sys.stdout.value)["value"] == dict(DEFAULT_IV48)
        assert len(calls) == 3
        for raw in ('{"text":"a","text":"b"}', '[]', '{"text":"a"}'):
            sys.argv, sys.stdin, sys.stdout = ["iv48.py", "-"], Stream(raw), Stream()
            run(guarded(cache_growth), DEFAULT_IV48, forbidden_check)
            fault = json.loads(sys.stdout.value)
            assert list(fault) == ["status", "code", "reason"] and fault["code"] == "INVALID_INPUT"
        for constant in ("NaN", "Infinity", "-Infinity"):
            sys.argv, sys.stdin, sys.stdout = ["iv48.py", "-"], Stream(constant), Stream()
            run(query, DEFAULT_IV48, forbidden_check)
            fault = json.loads(sys.stdout.value)
            assert fault == dict(status="unavailable", code="INVALID_INPUT", reason=f"Invalid JSON constant: {constant}")
        assert len(calls) == 3
        sys.argv, sys.stdout = ["iv48.py", "--self-check"], Stream()
        try:
            run(query, DEFAULT_IV48, forbidden_check)
        except AssertionError as error:
            assert "invoked a self-check" in str(error)
        else:
            raise AssertionError("--self-check assertion was swallowed")
        assert not sys.stdout.value
    finally:
        sys.argv, sys.stdin, sys.stdout = original
    # A finite forged cache is structurally accepted under the EXPLICIT precondition.
    forged = detached(prefill["cache"])
    forged["keys"][0] += 0.25
    accepted = attempt(supplied=forged)
    assert accepted["cache"]["keys"][0] == forged["keys"][0]
    assert forged["keys"][0] != prefill["cache"]["keys"][0]
    saved = attempt()
    saved["cache"]["keys"].clear()
    saved["tensors"][0]["values"].clear()
    assert attempt()["cache"]["keys"] and attempt()["tensors"][0]["values"]
    assert parameters == dict(NUMERIC_DEFAULTS)


if __name__ == "__main__":
    run(guarded(cache_growth), DEFAULT_IV48, source_self_check)

Dependency loader and saved rules — code/python/p11/inference_reference.py. The cache module loads this file for its Tiny decoder, IV39 tokenizer and BPE/codec bindings, and actually calls _tokenizer_rules to recover learned rules from saved tokenizer tensors. The new wrappers use their own _raw_state and cache_prompt; they do not call this file’s old inference_state, prompt_bpe or uncached inference composition. Follow the saved-rule extraction into the strict reverse decoder, rather than treating it as another prompt tokenization. The complete file remains part of the disclosed dependency closure.

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)

Class normalization and choice — code/python/p11/choice_reference.py. direct_distribution takes all active computed logits, subtracts their maximum, exponentiates and accumulates the denominator in compact class order. Its strict greater-than winner update keeps the lowest compact class on exact ties. Attention weights over positions and these probabilities over next-token classes are different arrays.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Direct logits -> stable probabilities -> strict-logit greedy choice.

NumPy float64/int32 arrays are the actual storage. Scalar binary64 arithmetic
preserves exp, left-to-right denominator and division order. No neural/tokenizer
import is needed for the literal five-ID model contract. Full ordered chapter
records follow the owner-adopted A inventory. All execution remains DEFERRED.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np

ALL_IDS = (97, 98, 512, 256, 257)
DEFAULT_IV45 = MappingProxyType(dict(V=3, z0=1, z1=0, z2=0, z3=0, z4=0))


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


def finite(value, label):
    """No coercion, bools, custom scalar conversions, infinities or NaNs."""
    if type(value) not in (int, float):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (OverflowError, ValueError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def choice_state(state):
    """Validate all six own fields in raw order, including inactive logits."""
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly V,z0,z1,z2,z3,z4.")
    if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV45):
        raise NumericalFault("INVALID_INPUT", "Provide every own field and no extra or symbol fields, including inactive logits.")
    checked = {}
    for key in DEFAULT_IV45:
        value = finite(state[key], key)
        if key == "V":
            if not value.is_integer() or not 3 <= value <= 5:
                raise NumericalFault("INVALID_INPUT", "V must be an integer from 3 to 5.")
            checked[key] = int(value)
        else:
            if not -40 <= value <= 40:
                raise NumericalFault("INVALID_INPUT", f"{key} must be between -40 and 40.")
            checked[key] = value
    return checked


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


class ChoiceTrace:
    """Finite detached scalar records; no implicit invocation of self-checks."""
    def __init__(self):
        self.steps = []

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


def _dense(values, label):
    """Inspect both containers before either helper operand is read."""
    if type(values) is np.ndarray:
        if values.ndim != 1 or values.dtype.kind not in "iuf":
            raise NumericalFault("INVALID_INPUT", f"{label} must be a dense one-dimensional numeric array.")
    elif type(values) not in (list, tuple):
        raise NumericalFault("INVALID_INPUT", f"{label} must be an actual dense array.")
    if not 3 <= len(values) <= 5:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{label} must have 3 to 5 entries.")


def _tensor(identifier, axis, values, provenance):
    """Serialize actual internal float64/int32 vectors into detached metadata."""
    if type(values) is not np.ndarray or values.ndim != 1 or values.dtype not in (np.dtype(np.float64), np.dtype(np.int32)):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier} requires actual float64/int32 vector storage.")
    if not 1 <= len(values) <= 5:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier} requires 1 to 5 entries.")
    flat = values.tolist()
    for value in flat:
        finite(value, identifier)
    integer = values.dtype == np.dtype(np.int32)
    return dict(id=identifier, shape=[len(flat)], axes=[axis], dtype="int32" if integer else "float64",
                values=flat, provenance=provenance, precision=0 if integer else 8)


def direct_distribution(logits, class_ids, trace, prefix="choice"):
    """Dynamic V3..5 distribution; no slider bound on finite derived logits.

    Prefix precedes both container guards; both descriptors precede entries.
    Highest computed input logit wins; ties keep the lowest compact index.
    """
    if type(prefix) is not str or not prefix:
        raise NumericalFault("INVALID_INPUT", "prefix must be an actual nonempty string.")
    _dense(logits, "logits")
    _dense(class_ids, "classIDs")
    if len(logits) != len(class_ids):
        raise NumericalFault("SHAPE_MISMATCH", "logits and classIDs must have equal lengths.")
    raw_z = logits.tolist() if type(logits) is np.ndarray else logits
    raw_ids = class_ids.tolist() if type(class_ids) is np.ndarray else class_ids
    V = len(raw_z)
    z = np.array([finite(value, f"logits[{c}]") for c, value in enumerate(raw_z)], dtype=np.float64)
    numeric_ids = [finite(value, f"classIDs[{c}]") for c, value in enumerate(raw_ids)]
    checked_ids = []
    for c, identifier in enumerate(numeric_ids):
        if not identifier.is_integer() or identifier != ALL_IDS[c]:
            raise NumericalFault("INVALID_INPUT", "classIDs must be the active prefix of [97,98,512,256,257].")
        checked_ids.append(int(identifier))
    ids = np.array(checked_ids, dtype=np.int32)
    maximum_inputs = {f"z{c}": float(z[c]) for c in range(V)}
    maximum = max(maximum_inputs.values())
    trace.add(f"{prefix}_max", "Find the maximum active computed logit", "max=max(z0,...,z[V-1])",
              "All active computed input logits participate. The maximum stabilizes exponentiation; it is not a rounded probability.",
              maximum_inputs, dict(max=maximum))
    shifted, terms, probabilities = (np.empty(V, dtype=np.float64) for _ in range(3))
    denominator, running = 0.0, {}
    for c in range(V):
        logit = float(z[c])
        shift = finite(logit - maximum, "shifted logit")
        term = finite(math.exp(shift), "shifted exponential")
        shifted[c], terms[c] = shift, term
        trace.add(f"{prefix}_exp_{c}", f"Exponentiate active class {c}", "shifted=logit-max; term=exp(shifted)",
                  "No clipping, epsilon or display rounding feeds the distribution. Underflow is retained if a derived input reaches it.",
                  dict(c=c, logit=logit, max=maximum), dict(shifted=shift, term=term))
        denominator = finite(denominator + term, "denominator")
        running[f"running{c}"] = denominator
    if denominator <= 0:
        raise NumericalFault("UNAVAILABLE", "The shifted exponential denominator must be positive.")
    log_s = finite(math.log(denominator), "logS")
    lse = finite(maximum + log_s, "logsumexp")
    trace.add(f"{prefix}_normalize", "Accumulate terms and compute logsumexp",
              "running starts at 0; running_c=previous+term_c; logS=ln(S); LSE=max+logS",
              "The denominator adds terms in ascending compact class order. Every actual running sum is saved.",
              {**{f"term{c}": float(terms[c]) for c in range(V)}, "max": maximum},
              {**running, "denominator": denominator, "logS": log_s, "lse": lse})
    for c in range(V):
        term = float(terms[c])
        probability = finite(term / denominator, "probability")
        probabilities[c] = probability
        trace.add(f"{prefix}_probability_{c}", f"Normalize active class {c}", "probability=term/S",
                  "This stored binary64 probability is displayed without feeding its formatting back into arithmetic.",
                  dict(c=c, term=term, denominator=denominator), dict(probability=probability))
    next_row = 0
    for c in range(1, V):
        if float(z[c]) > float(z[next_row]):
            next_row = c
    next_id, next_probability = int(ids[next_row]), float(probabilities[next_row])
    trace.add(f"{prefix}_argmax", "Choose the highest computed input logit",
              "strict greater-than updates the winner; exact ties retain lowest compact index",
              "Greedy choice uses the saved logits, never argmax of rounded or stored probabilities. Compact index order differs from ascending public ID order.",
              maximum_inputs, dict(nextRow=next_row, nextID=next_id, nextProbability=next_probability))
    tensors = [
        _tensor("ClassIDs", "Class", ids, "Active compact prefix [97,98,512,256,257]; public IDs are labels, not offsets."),
        _tensor("Z", "Class", z, "Actual finite computed input logits; no derived-input clipping."),
        _tensor("Shifted", "Class", shifted, "Z minus the saved active maximum."),
        _tensor("Terms", "Class", terms, "Actual exp(Shifted), before normalization."),
        _tensor("Denominator", "Scalar", np.array([denominator], dtype=np.float64), "Actual left-to-right sum of active shifted terms."),
        _tensor("LogS", "Scalar", np.array([log_s], dtype=np.float64), "Natural logarithm of Denominator."),
        _tensor("LSE", "Scalar", np.array([lse], dtype=np.float64), "Saved max+LogS in binary64."),
        _tensor("P", "Class", probabilities, "Terms/Denominator for active classes only, without clipping or padding."),
        _tensor("NextRow", "Decision", np.array([next_row], dtype=np.int32), "Lowest compact index among highest computed logits."),
        _tensor("NextID", "Decision", np.array([next_id], dtype=np.int32), "Public class ID gathered at NextRow."),
        _tensor("NextProbability", "Decision", np.array([next_probability], dtype=np.float64), "Stored P gathered at the computed-logit winner."),
    ]
    return dict(classIDs=ids.tolist(), logits=z.tolist(), max=maximum, shifted=shifted.tolist(), terms=terms.tolist(),
                denominator=denominator, logS=log_s, lse=lse, probabilities=probabilities.tolist(),
                nextRow=next_row, nextID=next_id, nextProbability=next_probability, tensors=tensors)


def compute_choice(state):
    """Full ordered IV45 record, including raw inactive metadata and every step."""
    s = choice_state(state)
    raw_z = np.array([s[f"z{c}"] for c in range(5)], dtype=np.float64)
    class_ids = np.array(ALL_IDS[:s["V"]], dtype=np.int32)
    trace = ChoiceTrace()
    trace.add("setup", "Validate all raw logits before selecting active classes", "V in {3,4,5}; every raw z in [-40,40]; activeZ=rawZ[:V]",
              "Inactive raw logits still validate and remain visible as metadata. This direct lesson has no text, target, loss, training, seed or sampling.",
              s, dict(classCount=s["V"], rawLogitCount=5))
    row = direct_distribution(raw_z[:s["V"]], class_ids, trace)
    trace.add("finish", "Keep the distribution and greedy decision together", "nextID=classIDs[argmax computed activeZ]; nextProbability=P[nextRow]",
              "The selected ID is a deterministic decision. Equal stored probabilities need not mean equal logits.",
              dict(nextRow=row["nextRow"]), dict(nextID=row["nextID"], nextProbability=row["nextProbability"]))
    outputs = dict(nextID=row["nextID"], nextProbability=row["nextProbability"], classCount=s["V"], logsumexp=row["lse"],
                   nextRow=row["nextRow"], max=row["max"], denominator=row["denominator"], logS=row["logS"], rawLogitCount=5)
    for step in trace.steps:
        outputs.update({f"{step['id']}_{key}": value for key, value in step["outputs"].items()})
    tensors = [_tensor("RawZ", "ModelRow", raw_z, "All five validated editable raw logits, including inactive slots."), *row["tensors"]]
    return dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors)


def source_self_check():
    """DEFERRED helper checks; never calls any other file's self-check."""
    assert __debug__, "Deferred checks require assertions enabled."
    state = dict(DEFAULT_IV45)
    trace = ChoiceTrace()
    row = direct_distribution([1, 0, 0], [97, 98, 512], trace)
    assert list(row) == ["classIDs", "logits", "max", "shifted", "terms", "denominator", "logS", "lse", "probabilities", "nextRow", "nextID", "nextProbability", "tensors"]
    ndarray_row = direct_distribution(np.array([1, 0, 0], dtype=np.float64), np.array([97, 98, 512], dtype=np.int32), ChoiceTrace())
    assert ndarray_row == row
    assert direct_distribution((1, 0, 0), (97, 98, 512), ChoiceTrace()) == row
    assert len(trace.steps) == 9 and trace.steps[0]["id"] == "choice_max"
    denominator = math.e + 2
    assert row["nextRow"] == 0 and row["nextID"] == 97
    assert math.isclose(row["probabilities"][0], math.e / denominator, rel_tol=1e-14)
    assert math.isclose(row["probabilities"][1], 1 / denominator, rel_tol=1e-14)
    assert math.isclose(row["lse"], math.log(denominator), rel_tol=1e-14)
    tied = direct_distribution([0, 0, 1, 1, 0], ALL_IDS, ChoiceTrace())
    assert tied["nextRow"] == 2 and tied["nextID"] == 512
    uniform = direct_distribution([0] * 5, ALL_IDS, ChoiceTrace())
    assert uniform["probabilities"] == [0.2] * 5 and uniform["nextID"] == 97
    rounded = direct_distribution([0, math.ulp(0.0), 0], ALL_IDS[:3], ChoiceTrace())
    assert rounded["probabilities"] == [1 / 3] * 3 and rounded["nextID"] == 98
    thin = direct_distribution([-40, 40, -40], ALL_IDS[:3], ChoiceTrace())
    assert thin["probabilities"][0] > 0 and thin["probabilities"][2] > 0
    derived_trace = ChoiceTrace()
    shifted = direct_distribution([101, 100, 100], ALL_IDS[:3], derived_trace, "derived")
    assert shifted["probabilities"] == row["probabilities"] and shifted["nextID"] == row["nextID"]
    assert all(step["id"].startswith("derived_") for step in derived_trace.steps)
    for patch, code in ((dict(V=True), "NONFINITE"), (dict(V=2), "INVALID_INPUT"),
                        (dict(V=3.5), "INVALID_INPUT"), (dict(z4=True), "NONFINITE"),
                        (dict(z4=41), "INVALID_INPUT"), (dict(z4=float("nan")), "NONFINITE"),
                        (dict(z4=10**1000), "NONFINITE")):
        fault = guarded(compute_choice)({**state, **patch})
        assert list(fault) == ["status", "code", "reason"] and fault["code"] == code
    class Hostile(dict):
        def __getitem__(self, key):
            raise AssertionError("Custom indexing must not be read")
    assert guarded(compute_choice)(Hostile(state))["code"] == "INVALID_INPUT"
    class HostileList(list):
        def __getitem__(self, key):
            raise AssertionError("Custom indexing must not be read")
    for logits, ids, code in (([1, 0, 0], HostileList([97, 98, 512]), "INVALID_INPUT"),
                             (HostileList([1, 0, 0]), [97, 98, 512], "INVALID_INPUT"),
                             ([1, 0, 0], [97, 98, 256], "INVALID_INPUT"),
                             ([1, 0, 0], [99, float("nan"), 512], "NONFINITE"),
                             ([1, float("nan"), 0], None, "INVALID_INPUT"),
                             ([1, 0, 0], [97, 98, 512, 256], "SHAPE_MISMATCH"),
                             (np.array([True, False, False]), ALL_IDS[:3], "INVALID_INPUT"),
                             ([1, True, 0], ALL_IDS[:3], "NONFINITE"),
                             ([1, float("inf"), 0], ALL_IDS[:3], "NONFINITE"),
                             ([1e308, -1e308, 0], ALL_IDS[:3], "NONFINITE"),
                             ([1, 0], [97, 98], "UNSUPPORTED_SIZE")):
        try:
            direct_distribution(logits, ids, ChoiceTrace(), "bad")
        except NumericalFault as error:
            assert error.code == code
        else:
            raise AssertionError("Invalid helper boundary was accepted")
    for prefix in (None, "", 0, True):
        rejected_trace = ChoiceTrace()
        try:
            direct_distribution(HostileList(), None, rejected_trace, prefix)
        except NumericalFault as error:
            assert error.code == "INVALID_INPUT" and "prefix" in str(error)
            assert not rejected_trace.steps
        else:
            raise AssertionError("Prefix must validate before containers")
    assert _tensor("F", "Class", np.array([1.0], dtype=np.float64), "check")["dtype"] == "float64"
    assert _tensor("I", "Class", np.array([97], dtype=np.int32), "check")["dtype"] == "int32"
    row["tensors"][0]["values"][0] = -1
    row["probabilities"][0] = -1
    trace.steps[0]["outputs"].clear()
    assert direct_distribution([1, 0, 0], ALL_IDS[:3], ChoiceTrace())["tensors"][0]["values"] == [97, 98, 512]
    assert state == dict(DEFAULT_IV45)


_JSON_INT = int


def run(derive, defaults):
    """Default / full replacement JSON / '-' stdin; never invokes self-checks."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

    def _members(pairs):
        value = {}
        for key, member in pairs:
            if key in value:
                raise ParseFault("Duplicate JSON object members are not allowed.")
            value[key] = member
        return value

    def _constant(token):
        raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")

    def _integer(token):
        if token == "-0":
            return -0.0
        try:
            return _JSON_INT(token)
        except ValueError as fault:
            if type(fault) is not ValueError:
                raise
            raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault

    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members,
                               parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
        else:
            result = derive(state)
    else:
        result = derive(dict(defaults))
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

Unchanged full decoder — code/python/p10/tiny_reference.py. forward_tiny gathers observed IDs, normalizes, projects, rotates Q/K, performs full causal attention, adds residuals, applies the FFN and reads out active logits. This supplies the separate complete reference path. Its objective and derivative functions also remain visible in the file; these cache lessons do not call them or train parameters. The loader temporarily supplies the intended component module for the FFN’s bare import, then restores the prior module binding.

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)

Tokenizer composition — code/python/p09/iv39.py. derive_iv39 learns from the fixed corpus and applies the learned rules to the prompt, retaining actual tokenizer evidence. Prompt tokenization runs once with automatic EOS insertion off. A later ID append is not a request to tokenize the reconstructed characters again.

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)

Learned rules and reverse expansion — code/python/p09/bpe_reference.py. train_bpe counts pairs and selects replacements using the declared tie order. encode_bpe applies ranked rules. decode_bpe_ids expands the actual supplied IDs with those rules and the explicit EOS policy. Distinct module instances can load this same source; the raw disclosure is by unique source file.

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]))]))

Strict text codec — code/python/p09/token_reference.py. utf16_length, utf8_encode and utf8_decode distinguish code units, Unicode scalar values and bytes. A scalar value is a Unicode character number excluding the surrogate range. Invalid surrogates do not silently become replacement characters. Integer token evidence remains separate from floating neural features.

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=(",", ":")))

Feature-local normalization and residuals — code/python/p07/component_reference.py. feature_norm saves means, centered values, squared deviations, population variance and epsilon-inside-root division. same_shape_add checks matching named shapes before adding residual features. Neither operation mixes token positions.

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=(",", ":")))

Three-coordinate feed-forward network — code/python/p07/ffn_reference.py. feed_forward records hidden projection products, bias addition, each ReLU and the output contraction. Its zero third hidden coordinate is calculated, not dropped. Follow both feature sums back to the second residual Y.

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)

Projection and full attention primitives — code/python/p06/head_reference.py. project_heads supplies explicit Q/K/value projection and layout conversion. The full decoder uses attend_heads and join_heads; their coupled full-query/full-key layout is why the new cache module separately implements one-query attention and output projection. Reusing projections does not justify pretending an old square attention result was a cached row.

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=(",", ":")))

Declared self-checks are separate later actions, not evidence supplied by displaying a file. In particular, the old IV-39 self-check calls its BPE self-check internally; those are not two independent explicit invocations. The independent oracle is separate from this canonical implementation. Its future assessment must examine the actual produced records rather than import the canonical calculation as its authority.

Recap and bridge

  • Share one prefill, then compare a genuine cached new row with a separately computed full prefix.
  • Match absolute positions, ordered IDs, active vocabulary, parameters and causal permissions.
  • Exact-real equivalence, immutable copies and cross-library numerical agreement are different claims.
  • Count actual neural work; keep terminal EOS logical and absent neural evidence absent.

IV-50 uses this distinction to calculate K/V storage and explain why less repeated work does not by itself establish lower measured latency.