The neural notebook
← All chapters

IV-50 / Part XII · KV Cache

KV Cache Memory, Latency and Invalidation

Calculate exact logical K/V storage and next-step work, then inspect genuine cache reuse and invalidation without confusing a large planner with a tiny neural probe.

Review the ideas this chapter uses

Saving yesterday’s calculations avoids doing them again, but the saved numbers occupy space. A KV cache makes that trade: it retains past attention keys and values so that the next token needs only one new query row. We will count the storage, identify the work that remains, and examine when those saved numbers may be reused.

Learning objective: Calculate cache footprint and demonstrate relevant invalidations.

Two separate experiences: the planner describes hypothetical dimensions and storage bits; it never allocates that hypothetical cache. The real reuse probe always uses one sequence, one layer, one head, two old tokens and two features per key/value in float64. Changing the planner does not enlarge or quantize the probe.

Budget the logical memory for stored keys and values, then inspect an independent real cache-reuse request. Seven analytical controls change counts without allocating their payload. The last two controls edit a fixed untrained toy request; its old context always has two observed tokens.

Compute it yourself

KV Cache Memory, Latency and Invalidation

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
B
1
L
1
Hkv
1
T
2
Dk
2
Dv
2
bits
64
editKind
0
delta
0.5
payloadBytes64
nextPayloadBytes96
bytesPerToken32
reuseAccepted1

payloadBytes 64. nextPayloadBytes 96. bytesPerToken 32. reuseAccepted 1. Separate a logical budget from a fixed actual invalidation probe. All nine raw fields, including inactive delta, validate before any calculation. The probe uses default26 untrained parameters and already observed IDs[97,98], without a tokenizer or full-append reference.. probeB 1. probeL 1. probeHkv 1. probeN 2. probeDk 2. probeDv 2. probeBits 64. probeClassCount 3. newID 97

Separate a logical budget from a fixed actual invalidation probe

planner inputs never set neural dimensions; probe B=L=Hkv=1,N=2,Dk=Dv=2,bits=64,V=3,newID=97

All nine raw fields, including inactive delta, validate before any calculation. The probe uses default26 untrained parameters and already observed IDs[97,98], without a tokenizer or full-append reference.

Inputs

B
1
L
1
Hkv
1
T
2
Dk
2
Dv
2
bits
64
editKind
0
delta
0.5

Outputs

probeB
1
probeL
1
probeHkv
1
probeN
2
probeDk
2
probeDv
2
probeBits
64
probeClassCount
3
newID
97

Analytical budget: count a payload without allocating it

Logical K+V storage only; excludes queries, weights, metadata, heap and allocator overhead. No planner-sized allocation occurs. 8/16/32/64 bits are hypothetical logical storage scenarios. The actual probe remains float64; no quantizer or dtype mutation is implemented.

Separate from the real probe: Independent actual probe: B=L=Hkv=1, old N=2, Dk=Dv=2, bits64, merges0, default26 untrained parameters, observed IDs[97,98], supplied newID97. Analytical dimensions never feed neural arrays.

Here T=2 is the old context and Tk=3 is the next analytical length. Each batch entry contributes one independent sequence; L counts layers; each layer has Hkv heads. Each saved key has Dk features and each value has Dv features. Storage bits describe each element, with8 bits per byte.

K elements = B × L × Hkv × T × Dk; V elements = B × L × Hkv × T × Dv; bytes = (K elements + V elements) × bits ÷ 8.

Logical old K+V payload

[8] · PayloadMetric · float64 · display precision 0. Analytical payload metrics in payloadMetricNames order; exact integer binary64, never int32; no payload allocation.

Logical old K+V payload — stored values without display rounding
Saved metricExact stored count
batchLayers1
factor1
oldHeadRows2
KElements4
VElements4
payloadElements8
payloadBits512
payloadBytes64

Logical one-token increase

[6] · TokenMetric · float64 · display precision 0. Analytical one-token metrics in tokenMetricNames order; hypothetical bits do not mutate the actual float64 probe.

Logical one-token increase — stored values without display rounding
Saved metricExact stored count
featureWidth4
elementsPerToken4
bitsPerToken256
bytesPerToken32
nextPayloadBytes96
nextPayloadBits768

Analytical next-query work

[6] · WorkMetric · float64 · display precision 0. Analytical MHA work metrics in workMetricNames order; score cells and paired K/V head rows, not latency or FLOPs.

Analytical next-query work — stored values without display rounding
Saved metricExact stored count
Tk3
nextSquare9
cachedScoreCells3
fullScoreCells9
cachedProjectedHeadRows1
fullProjectedHeadRows3

Hq=Hkv simple MHA. A projected head row is the pair of K/V vectors for one head and token, not distinct input embeddings or FLOPs. IV61 introduces GQA. Cached attention still reads all available keys and values, so longer contexts increase work and bandwidth; no latency or speedup is measured.

At T=0 the old payload is zero, yet all three count vectors stay nonempty. At the maximum old T=8192, next Tk=8193 is an analytical count; it never becomes a neural tensor dimension.

Every saved budget multiplication, addition and division
IV-50 analytical budget arithmetic — stored values without display rounding
Saved operation / equationActual inputsActual outputs
planner_payload

batchLayers=B*L; factor=batchLayers*Hkv; oldHeadRows=factor*T; KElements=oldHeadRows*Dk; VElements=oldHeadRows*Dv; payloadElements=KElements+VElements; payloadBits=payloadElements*bits; payloadBytes=payloadBits/8

Analytical integer counts only. No planner-sized neural array is allocated. Q, weights, metadata, heap and allocator overhead are excluded.

B=1
L=1
Hkv=1
T=2
Dk=2
Dv=2
bits=64
bitsPerByte=8
batchLayers=1
factor=1
oldHeadRows=2
KElements=4
VElements=4
payloadElements=8
payloadBits=512
payloadBytes=64
planner_token

featureWidth=Dk+Dv; elementsPerToken=factor*featureWidth; bitsPerToken=elementsPerToken*bits; bytesPerToken=bitsPerToken/8; nextPayloadBytes=payloadBytes+bytesPerToken; nextPayloadBits=nextPayloadBytes*8

T is the old analytical context. Even at T=8192 the analytical next length8193 does not enlarge the fixed two-token neural probe.

factor=1
Dk=2
Dv=2
bits=64
payloadBytes=64
bitsPerByte=8
featureWidth=4
elementsPerToken=4
bitsPerToken=256
bytesPerToken=32
nextPayloadBytes=96
nextPayloadBits=768
planner_work

Tk=T+1; nextSquare=Tk*Tk; cachedScoreCells=factor*Tk; fullScoreCells=factor*nextSquare; cachedProjectedHeadRows=factor; fullProjectedHeadRows=factor*Tk

Hq=Hkv simple MHA. One projected head row is the pair of K/V projected vectors for one head and token, not a distinct input embedding or a FLOP count. A cached query still reads all available keys and values; these are not timings or speedups.

T=2
oneNewToken=1
factor=1
Tk=3
nextSquare=9
cachedScoreCells=3
fullScoreCells=9
cachedProjectedHeadRows=1
fullProjectedHeadRows=3

Actual fixed probe: reuse, or reject before a new neural row

Independent of all seven analytical controls: Independent actual probe: B=L=Hkv=1, old N=2, Dk=Dv=2, bits64, merges0, default26 untrained parameters, observed IDs[97,98], supplied newID97. Analytical dimensions never feed neural arrays.

Prefill observes a / ID97, then b / ID98. Its real last-row prediction is b / ID98 with stored probability=0.7234156524931242. The new supplied ID is a / ID97; a prediction never replaces that observed input.

Request accepted. Edit field=none; delta used=0; actual represented target=1; model changed=0. The actual append succeeded and its complete neural evidence is saved.

IV-50 actual probe call work — stored values without display rounding
Actual saved callQuery rowsRaw score cells
One actual full prefill24
Guarded append13
Actual harness total37

Append neural frames=57; current successful cache entries=3. These actual calls have no full-append comparison, tokenizer, benchmark or measured latency. Rejected requests keep the original two-entry prefill cache.

Immutable coherent baseline captured from real 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.

Immutable coherent baseline captured from real 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

Detached attempted cache metadata and supplied payload

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

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

Detached attempted cache metadata and supplied payload — 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

The attempt table is evidence of the supplied request. For edit3 its shifted positions are deliberately invalid; the table does not certify this attempt as a coherent origin0 cache. Requested prefix IDs=[97,98], checked separately from the attempted cache IDs.

All26 baseline and actual requested parameters, including inactive entries
IV-50 actual parameter identity inputs — stored values without display rounding
ParameterBaselineActual target
merges00
e0011
e0100
e1000
e1111
e2000
e2100
e300.50.5
e310.50.5
e4011
e4111
u0011
u0100
u0200
u0300
u0400
u1000
u1111
u1200
u1300
u1400
b000
b100
b200
b300
b400
IV-50 actual request edit and guarded outcome — stored values without display rounding
Saved operation / equationActual inputsActual outputs
probe_edit

edit1:e00=1+delta; edit2:expected=[98,97]; edit3:attempt.positions=[1,2]; edit4:u00=1+delta; edit5:e40=1+delta; otherwise unchanged; modelChanged=any actual target!==baseline

The actual represented addition decides model identity, including ties-to-even and subnormal deltas. No tolerance or nonzero-delta heuristic is used. The original prefill cache is immutable; the attempt is never repaired or rebuilt at a changed origin.

editKind=0
delta=0.5
baseValue=1
deltaUsed=0
targetValue=1
modelChanged=0
expectedID0=97
expectedID1=98
attemptPosition0=0
attemptPosition1=1
probe_outcome

reuseAccepted=(actual append returned); rejected attempt emits zero neural frames/tensors; accepted attempt keeps every actual output

Only the three exact declared cache code/reason pairs are captured. Unknown errors propagate. On rejection append predictions, retained-copy flags and probe neural tensors are absent, not filled with zeros.

editKind=0
modelChanged=0
beforeAppendFrames=118
reuseAccepted=1
appendFrames=57
appendQueryRows=1
appendScoreCells=3
cacheEntries=3
retainedExact=1
appendNextRow=0
appendNextID=97
appendNextProbability=0.7632007976561935

All26 numeric parameters must agree under numeric ===; signed zeros are equivalent. Actual readout-only or inactive embedding edits invalidate under this conservative policy even though they do not change old K/V mathematically in this one-layer toy.

Origin0 only: positions must be exact ordered integers0..N-1 and expectedPrefixIDs must separately match cache.ids. A changed origin is rejected, never silently repaired.

Why a tiny nonzero edit can leave the model unchanged

Binary64 stores a finite set of representable numbers. At the power of two1 the gap just below is half the gap just above. At a midpoint, ties-to-even chooses1 on either side. Thus +2^-53 rounds back to1, while -2^-53 reaches the next smaller value. A nonzero input edit can therefore preserve the actual stored parameter.

At1 the spacing upward is2^-52 and downward2^-53. RN ties-even leaves1 unchanged for represented delta in[-2^-54,+2^-53], including both endpoints, signed zeros and +/-Number.MIN_VALUE. +2^-52 and -2^-53 change the target. Compare the actual represented1+delta, never a tolerance or merely delta!=0.

Try model edit1,4 or5 with delta=1.1102230246251565e-16 (+2^-53), then -1.1102230246251565e-16 (-2^-53). Inspect the saved target and actual guard outcome. The positive edit leaves1 unchanged; the negative edit changes it. Nothing is accepted by a tolerance.

Actual accepted append before snapshot

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

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

Actual accepted append before snapshot — 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 accepted append after snapshot

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

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

Actual accepted append after snapshot — 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 winner=a / ID97, stored probability=0.7632007976561935; actual retained-copy flag=1. Every per-coordinate copy flag is saved in the append operation.

Actual accepted append coordinate copies
IV-50 actual accepted retained copies — stored values without display rounding
Saved operation / equationActual inputsActual outputs
probe_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

Inspecting saved probe, absolute query 2, key 0, compact class 0. Inspection does not recompute a model, move the trace cursor or clear graded answers.

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

probe: 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.

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

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

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

probe 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.

probe 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.

probe 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.

probe selected score and normalization — stored values without display rounding
Saved operation / equationActual inputsActual outputs
probe_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
probe_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
probe_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
probe_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
probe complete hidden FFN row — stored values without display rounding
Hidden coordinateAffine ZReLU activation
00.57208215195821940.5720821519582194
1-0.57208215195821940
200

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

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

probe 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.

probe selected readout and stable class normalization — stored values without display rounding
Saved operation / equationActual inputsActual outputs
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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.

probe complete arithmetic — stored values without display rounding
Saved operation / equationActual inputsActual outputs
probe_edit

edit1:e00=1+delta; edit2:expected=[98,97]; edit3:attempt.positions=[1,2]; edit4:u00=1+delta; edit5:e40=1+delta; otherwise unchanged; modelChanged=any actual target!==baseline

The actual represented addition decides model identity, including ties-to-even and subnormal deltas. No tolerance or nonzero-delta heuristic is used. The original prefill cache is immutable; the attempt is never repaired or rebuilt at a changed origin.

editKind=0
delta=0.5
baseValue=1
deltaUsed=0
targetValue=1
modelChanged=0
expectedID0=97
expectedID1=98
attemptPosition0=0
attemptPosition1=1
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_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
probe_outcome

reuseAccepted=(actual append returned); rejected attempt emits zero neural frames/tensors; accepted attempt keeps every actual output

Only the three exact declared cache code/reason pairs are captured. Unknown errors propagate. On rejection append predictions, retained-copy flags and probe neural tensors are absent, not filled with zeros.

editKind=0
modelChanged=0
beforeAppendFrames=118
reuseAccepted=1
appendFrames=57
appendQueryRows=1
appendScoreCells=3
cacheEntries=3
retainedExact=1
appendNextRow=0
appendNextID=97
appendNextProbability=0.7632007976561935
All saved path tensor shapes and provenance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

probe_ProjectionWQ [2,2] · D,QueryFeature · float64 · precision 8 · Actual cached append probe: 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}.

probe_ProjectionWK [2,2] · D,KeyFeature · float64 · precision 8 · Actual cached append probe: 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}.

probe_ProjectionWV [2,2] · D,ValueFeature · float64 · precision 8 · Actual cached append probe: 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}.

probe_ProjectionQConcat [1,1,2] · B,T,QueryFeature · float64 · precision 8 · Actual cached append probe: 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.

probe_ProjectionKConcat [1,1,2] · B,T,KeyFeature · float64 · precision 8 · Actual cached append probe: 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.

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

probe_ProjectionQSplit [1,1,1,2] · B,T,H,Dk · float64 · precision 8 · Actual cached append probe: 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.

probe_ProjectionQHeads [1,1,1,2] · B,H,T,Dk · float64 · precision 8 · Actual cached append probe: 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.

probe_ProjectionKSplit [1,1,1,2] · B,T,H,Dk · float64 · precision 8 · Actual cached append probe: 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.

probe_ProjectionKHeads [1,1,1,2] · B,H,T,Dk · float64 · precision 8 · Actual cached append probe: 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.

probe_ProjectionVSplit [1,1,1,2] · B,T,H,Dv · float64 · precision 8 · Actual cached append probe: 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.

probe_ProjectionVHeads [1,1,1,2] · B,H,T,Dv · float64 · precision 8 · Actual cached append probe: 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

probe_ChoiceClassIDs [3] · Class · int32 · precision 0 · Actual cached append probe: 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.

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

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

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

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

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

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

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

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

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

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

Actual setup, prefill capture and harness counting
IV-50 setup, capture and actual harness counts — stored values without display rounding
Saved operation / equationActual inputsActual outputs
setup

planner inputs never set neural dimensions; probe B=L=Hkv=1,N=2,Dk=Dv=2,bits=64,V=3,newID=97

All nine raw fields, including inactive delta, validate before any calculation. The probe uses default26 untrained parameters and already observed IDs[97,98], without a tokenizer or full-append reference.

B=1
L=1
Hkv=1
T=2
Dk=2
Dv=2
bits=64
editKind=0
delta=0.5
probeB=1
probeL=1
probeHkv=1
probeN=2
probeDk=2
probeDv=2
probeBits=64
probeClassCount=3
newID=97
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
finish

actualHarnessRows=2+appendQueryRows; actualHarnessScoreCells=4+appendScoreCells

The actual harness has one two-row prefill and optionally one new-row append. Analytical T, layers, heads, widths and storage bits never change those calls. No elapsed time, measured speedup or quantizer is present.

prefillQueryRows=2
appendQueryRows=1
prefillScoreCells=4
appendScoreCells=3
actualHarnessRows=3
actualHarnessScoreCells=7
Cache trust, model identity and numerical limits

The probe constructs its own coherent prefill and preserves that immutable baseline. Shape/finite/model/prefix checks cannot certify arbitrary externally supplied K/V; external helper coherence remains a precondition.

All26 numeric parameters must agree under numeric ===; signed zeros are equivalent. Actual readout-only or inactive embedding edits invalidate under this conservative policy even though they do not change old K/V mathematically in this one-layer toy.

Origin0 only: positions must be exact ordered integers0..N-1 and expectedPrefixIDs must separately match cache.ids. A changed origin is rejected, never silently repaired.

The actual prefill and accepted append operands and per-coordinate retained-copy flags remain inspectable. Exact unchanged copies within one implementation are a narrower fact than independently witnessing numerical coherence. Cross-library witnesses remain conditional on their declared math-library error premise; exact-real identities do not promise universal bitwise agreement. This probe computes no cached/full comparison or difference tensors, elapsed time or trained-model quality.

Inspect tensor shapes and full precision

All computed outputs

payloadBytes
64
nextPayloadBytes
96
bytesPerToken
32
reuseAccepted
1
B
1
L
1
Hkv
1
T
2
Dk
2
Dv
2
bits
64
editKind
0
delta
0.5
batchLayers
1
factor
1
oldHeadRows
2
KElements
4
VElements
4
payloadElements
8
payloadBits
512
featureWidth
4
elementsPerToken
4
bitsPerToken
256
nextPayloadBits
768
Tk
3
nextSquare
9
cachedScoreCells
3
fullScoreCells
9
cachedProjectedHeadRows
1
fullProjectedHeadRows
3
probeB
1
probeL
1
probeHkv
1
probeN
2
probeDk
2
probeDv
2
probeBits
64
probeClassCount
3
newID
97
deltaUsed
0
targetValue
1
modelChanged
0
prefillQueryRows
2
appendQueryRows
1
prefillScoreCells
4
appendScoreCells
3
actualHarnessRows
3
actualHarnessScoreCells
7
cacheEntries
3
appendFrames
57
prefillNextRow
1
prefillNextID
98
prefillNextProbability
0.7234156524931242
retainedExact
1
appendNextRow
0
appendNextID
97
appendNextProbability
0.7632007976561935
setup_probeB
1
setup_probeL
1
setup_probeHkv
1
setup_probeN
2
setup_probeDk
2
setup_probeDv
2
setup_probeBits
64
setup_probeClassCount
3
setup_newID
97
planner_payload_batchLayers
1
planner_payload_factor
1
planner_payload_oldHeadRows
2
planner_payload_KElements
4
planner_payload_VElements
4
planner_payload_payloadElements
8
planner_payload_payloadBits
512
planner_payload_payloadBytes
64
planner_token_featureWidth
4
planner_token_elementsPerToken
4
planner_token_bitsPerToken
256
planner_token_bytesPerToken
32
planner_token_nextPayloadBytes
96
planner_token_nextPayloadBits
768
planner_work_Tk
3
planner_work_nextSquare
9
planner_work_cachedScoreCells
3
planner_work_fullScoreCells
9
planner_work_cachedProjectedHeadRows
1
planner_work_fullProjectedHeadRows
3
prefill_input_0_inputRow
0
prefill_input_0_x0
1
prefill_input_0_x1
0
prefill_input_1_inputRow
1
prefill_input_1_x0
0
prefill_input_1_x1
1
prefill_ln1_0_statistics_sum
1
prefill_ln1_0_statistics_mean
0.5
prefill_ln1_0_statistics_centered0
0.5
prefill_ln1_0_statistics_centered1
-0.5
prefill_ln1_0_statistics_square0
0.25
prefill_ln1_0_statistics_square1
0.25
prefill_ln1_0_statistics_squareSum
0.5
prefill_ln1_0_statistics_variance
0.25
prefill_ln1_0_statistics_variancePlusEpsilon
1.25
prefill_ln1_0_statistics_denominator
1.118033988749895
prefill_ln1_0_feature_0_normalized
0.4472135954999579
prefill_ln1_0_feature_0_scaled
0.4472135954999579
prefill_ln1_0_feature_0_value
0.4472135954999579
prefill_ln1_0_feature_1_normalized
-0.4472135954999579
prefill_ln1_0_feature_1_scaled
-0.4472135954999579
prefill_ln1_0_feature_1_value
-0.4472135954999579
prefill_ln1_1_statistics_sum
1
prefill_ln1_1_statistics_mean
0.5
prefill_ln1_1_statistics_centered0
-0.5
prefill_ln1_1_statistics_centered1
0.5
prefill_ln1_1_statistics_square0
0.25
prefill_ln1_1_statistics_square1
0.25
prefill_ln1_1_statistics_squareSum
0.5
prefill_ln1_1_statistics_variance
0.25
prefill_ln1_1_statistics_variancePlusEpsilon
1.25
prefill_ln1_1_statistics_denominator
1.118033988749895
prefill_ln1_1_feature_0_normalized
-0.4472135954999579
prefill_ln1_1_feature_0_scaled
-0.4472135954999579
prefill_ln1_1_feature_0_value
-0.4472135954999579
prefill_ln1_1_feature_1_normalized
0.4472135954999579
prefill_ln1_1_feature_1_scaled
0.4472135954999579
prefill_ln1_1_feature_1_value
0.4472135954999579
prefill_heads_setup_B
1
prefill_heads_setup_T
2
prefill_heads_setup_D
2
prefill_heads_setup_H
1
prefill_heads_setup_Dk
2
prefill_heads_setup_Dv
2
prefill_heads_project_Q_0_0_0_0_product0
0.4472135954999579
prefill_heads_project_Q_0_0_0_0_product1
0
prefill_heads_project_Q_0_0_0_0_value
0.4472135954999579
prefill_heads_project_Q_0_0_0_1_product0
0
prefill_heads_project_Q_0_0_0_1_product1
-0.4472135954999579
prefill_heads_project_Q_0_0_0_1_value
-0.4472135954999579
prefill_heads_project_Q_0_1_0_0_product0
-0.4472135954999579
prefill_heads_project_Q_0_1_0_0_product1
0
prefill_heads_project_Q_0_1_0_0_value
-0.4472135954999579
prefill_heads_project_Q_0_1_0_1_product0
0
prefill_heads_project_Q_0_1_0_1_product1
0.4472135954999579
prefill_heads_project_Q_0_1_0_1_value
0.4472135954999579
prefill_heads_project_K_0_0_0_0_product0
0.4472135954999579
prefill_heads_project_K_0_0_0_0_product1
0
prefill_heads_project_K_0_0_0_0_value
0.4472135954999579
prefill_heads_project_K_0_0_0_1_product0
0
prefill_heads_project_K_0_0_0_1_product1
-0.4472135954999579
prefill_heads_project_K_0_0_0_1_value
-0.4472135954999579
prefill_heads_project_K_0_1_0_0_product0
-0.4472135954999579
prefill_heads_project_K_0_1_0_0_product1
0
prefill_heads_project_K_0_1_0_0_value
-0.4472135954999579
prefill_heads_project_K_0_1_0_1_product0
0
prefill_heads_project_K_0_1_0_1_product1
0.4472135954999579
prefill_heads_project_K_0_1_0_1_value
0.4472135954999579
prefill_heads_project_V_0_0_0_0_product0
0.4472135954999579
prefill_heads_project_V_0_0_0_0_product1
0
prefill_heads_project_V_0_0_0_0_value
0.4472135954999579
prefill_heads_project_V_0_0_0_1_product0
0
prefill_heads_project_V_0_0_0_1_product1
-0.4472135954999579
prefill_heads_project_V_0_0_0_1_value
-0.4472135954999579
prefill_heads_project_V_0_1_0_0_product0
-0.4472135954999579
prefill_heads_project_V_0_1_0_0_product1
0
prefill_heads_project_V_0_1_0_0_value
-0.4472135954999579
prefill_heads_project_V_0_1_0_1_product0
0
prefill_heads_project_V_0_1_0_1_product1
0.4472135954999579
prefill_heads_project_V_0_1_0_1_value
0.4472135954999579
prefill_heads_reshape_Q_elements
4
prefill_heads_permute_Q_0_0_0_0_value
0.4472135954999579
prefill_heads_permute_Q_0_0_0_1_value
-0.4472135954999579
prefill_heads_permute_Q_0_0_1_0_value
-0.4472135954999579
prefill_heads_permute_Q_0_0_1_1_value
0.4472135954999579
prefill_heads_reshape_K_elements
4
prefill_heads_permute_K_0_0_0_0_value
0.4472135954999579
prefill_heads_permute_K_0_0_0_1_value
-0.4472135954999579
prefill_heads_permute_K_0_0_1_0_value
-0.4472135954999579
prefill_heads_permute_K_0_0_1_1_value
0.4472135954999579
prefill_heads_reshape_V_elements
4
prefill_heads_permute_V_0_0_0_0_value
0.4472135954999579
prefill_heads_permute_V_0_0_0_1_value
-0.4472135954999579
prefill_heads_permute_V_0_0_1_0_value
-0.4472135954999579
prefill_heads_permute_V_0_0_1_1_value
0.4472135954999579
prefill_rope_Q_0_frequency
1
prefill_rope_Q_0_angle
0
prefill_rope_Q_0_cos
1
prefill_rope_Q_0_sin
0
prefill_rope_Q_0_product0
0.4472135954999579
prefill_rope_Q_0_product1
0
prefill_rope_Q_0_product2
0
prefill_rope_Q_0_product3
-0.4472135954999579
prefill_rope_Q_0_rotated0
0.4472135954999579
prefill_rope_Q_0_rotated1
-0.4472135954999579
prefill_rope_Q_1_frequency
1
prefill_rope_Q_1_angle
1
prefill_rope_Q_1_cos
0.5403023058681398
prefill_rope_Q_1_sin
0.8414709848078965
prefill_rope_Q_1_product0
-0.2416305368642088
prefill_rope_Q_1_product1
0.3763172646248299
prefill_rope_Q_1_product2
-0.3763172646248299
prefill_rope_Q_1_product3
0.2416305368642088
prefill_rope_Q_1_rotated0
-0.6179478014890387
prefill_rope_Q_1_rotated1
-0.1346867277606211
prefill_rope_K_0_frequency
1
prefill_rope_K_0_angle
0
prefill_rope_K_0_cos
1
prefill_rope_K_0_sin
0
prefill_rope_K_0_product0
0.4472135954999579
prefill_rope_K_0_product1
0
prefill_rope_K_0_product2
0
prefill_rope_K_0_product3
-0.4472135954999579
prefill_rope_K_0_rotated0
0.4472135954999579
prefill_rope_K_0_rotated1
-0.4472135954999579
prefill_rope_K_1_frequency
1
prefill_rope_K_1_angle
1
prefill_rope_K_1_cos
0.5403023058681398
prefill_rope_K_1_sin
0.8414709848078965
prefill_rope_K_1_product0
-0.2416305368642088
prefill_rope_K_1_product1
0.3763172646248299
prefill_rope_K_1_product2
-0.3763172646248299
prefill_rope_K_1_product3
0.2416305368642088
prefill_rope_K_1_rotated0
-0.6179478014890387
prefill_rope_K_1_rotated1
-0.1346867277606211
prefill_heads_score_0_0_0_0_product0
0.19999999999999998
prefill_heads_score_0_0_0_0_product1
0.19999999999999998
prefill_heads_score_0_0_0_0_raw
0.39999999999999997
prefill_heads_score_0_0_0_0_score
0.28284271247461895
prefill_heads_score_0_0_0_1_product0
-0.27635465813520727
prefill_heads_score_0_0_0_1_product1
0.06023373578795136
prefill_heads_score_0_0_0_1_raw
-0.2161209223472559
prefill_heads_score_0_0_0_1_score
-0.1528205697480359
prefill_heads_score_0_0_1_0_product0
-0.27635465813520727
prefill_heads_score_0_0_1_0_product1
0.06023373578795136
prefill_heads_score_0_0_1_0_raw
-0.2161209223472559
prefill_heads_score_0_0_1_0_score
-0.1528205697480359
prefill_heads_score_0_0_1_1_product0
0.3818594853651364
prefill_heads_score_0_0_1_1_product1
0.01814051463486366
prefill_heads_score_0_0_1_1_raw
0.4000000000000001
prefill_heads_score_0_0_1_1_score
0.28284271247461906
prefill_heads_row_0_0_0_max
0.28284271247461895
prefill_heads_row_0_0_0_denominator
1
prefill_heads_row_0_0_0_shifted0
0
prefill_heads_row_0_0_0_term0
1
prefill_heads_row_0_0_0_term1
0
prefill_heads_row_0_0_0_p0
1
prefill_heads_row_0_0_0_p1
0
prefill_heads_row_0_0_1_max
0.28284271247461906
prefill_heads_row_0_0_1_denominator
1.646835490279414
prefill_heads_row_0_0_1_shifted0
-0.43566328222265494
prefill_heads_row_0_0_1_shifted1
0
prefill_heads_row_0_0_1_term0
0.646835490279414
prefill_heads_row_0_0_1_term1
1
prefill_heads_row_0_0_1_p0
0.3927748060431144
prefill_heads_row_0_0_1_p1
0.6072251939568857
prefill_heads_head_mix_0_0_0_0_product0
0.4472135954999579
prefill_heads_head_mix_0_0_0_0_product1
0
prefill_heads_head_mix_0_0_0_0_running0
0.4472135954999579
prefill_heads_head_mix_0_0_0_0_running1
0.4472135954999579
prefill_heads_head_mix_0_0_0_0_value
0.4472135954999579
prefill_heads_head_mix_0_0_0_1_product0
-0.4472135954999579
prefill_heads_head_mix_0_0_0_1_product1
0
prefill_heads_head_mix_0_0_0_1_running0
-0.4472135954999579
prefill_heads_head_mix_0_0_0_1_running1
-0.4472135954999579
prefill_heads_head_mix_0_0_0_1_value
-0.4472135954999579
prefill_heads_head_mix_0_0_1_0_product0
0.17565423323233978
prefill_heads_head_mix_0_0_1_0_product1
-0.2715593622676182
prefill_heads_head_mix_0_0_1_0_running0
0.17565423323233978
prefill_heads_head_mix_0_0_1_0_running1
-0.0959051290352784
prefill_heads_head_mix_0_0_1_0_value
-0.0959051290352784
prefill_heads_head_mix_0_0_1_1_product0
-0.17565423323233978
prefill_heads_head_mix_0_0_1_1_product1
0.2715593622676182
prefill_heads_head_mix_0_0_1_1_running0
-0.17565423323233978
prefill_heads_head_mix_0_0_1_1_running1
0.0959051290352784
prefill_heads_head_mix_0_0_1_1_value
0.0959051290352784
prefill_heads_concat_0_0_0_0_value
0.4472135954999579
prefill_heads_concat_0_0_0_1_value
-0.4472135954999579
prefill_heads_concat_0_1_0_0_value
-0.0959051290352784
prefill_heads_concat_0_1_0_1_value
0.0959051290352784
prefill_heads_output_0_0_0_product0
0.4472135954999579
prefill_heads_output_0_0_0_product1
0
prefill_heads_output_0_0_0_running0
0.4472135954999579
prefill_heads_output_0_0_0_running1
0.4472135954999579
prefill_heads_output_0_0_0_value
0.4472135954999579
prefill_heads_output_0_0_1_product0
0
prefill_heads_output_0_0_1_product1
-0.4472135954999579
prefill_heads_output_0_0_1_running0
0
prefill_heads_output_0_0_1_running1
-0.4472135954999579
prefill_heads_output_0_0_1_value
-0.4472135954999579
prefill_heads_output_0_1_0_product0
-0.0959051290352784
prefill_heads_output_0_1_0_product1
0
prefill_heads_output_0_1_0_running0
-0.0959051290352784
prefill_heads_output_0_1_0_running1
-0.0959051290352784
prefill_heads_output_0_1_0_value
-0.0959051290352784
prefill_heads_output_0_1_1_product0
0
prefill_heads_output_0_1_1_product1
0.0959051290352784
prefill_heads_output_0_1_1_running0
0
prefill_heads_output_0_1_1_running1
0.0959051290352784
prefill_heads_output_0_1_1_value
0.0959051290352784
prefill_residual1_0_0_value
1.4472135954999579
prefill_residual1_0_1_value
-0.4472135954999579
prefill_residual1_1_0_value
-0.0959051290352784
prefill_residual1_1_1_value
1.0959051290352784
prefill_ln2_0_statistics_sum
1
prefill_ln2_0_statistics_mean
0.5
prefill_ln2_0_statistics_centered0
0.9472135954999579
prefill_ln2_0_statistics_centered1
-0.9472135954999579
prefill_ln2_0_statistics_square0
0.8972135954999578
prefill_ln2_0_statistics_square1
0.8972135954999578
prefill_ln2_0_statistics_squareSum
1.7944271909999157
prefill_ln2_0_statistics_variance
0.8972135954999578
prefill_ln2_0_statistics_variancePlusEpsilon
1.8972135954999578
prefill_ln2_0_statistics_denominator
1.3773937692250382
prefill_ln2_0_feature_0_normalized
0.6876854075163181
prefill_ln2_0_feature_0_scaled
0.6876854075163181
prefill_ln2_0_feature_0_value
0.6876854075163181
prefill_ln2_0_feature_1_normalized
-0.6876854075163181
prefill_ln2_0_feature_1_scaled
-0.6876854075163181
prefill_ln2_0_feature_1_value
-0.6876854075163181
prefill_ln2_1_statistics_sum
1
prefill_ln2_1_statistics_mean
0.5
prefill_ln2_1_statistics_centered0
-0.5959051290352784
prefill_ln2_1_statistics_centered1
0.5959051290352784
prefill_ln2_1_statistics_square0
0.3551029228105518
prefill_ln2_1_statistics_square1
0.3551029228105518
prefill_ln2_1_statistics_squareSum
0.7102058456211036
prefill_ln2_1_statistics_variance
0.3551029228105518
prefill_ln2_1_statistics_variancePlusEpsilon
1.3551029228105518
prefill_ln2_1_statistics_denominator
1.1640888809753969
prefill_ln2_1_feature_0_normalized
-0.5119068988408909
prefill_ln2_1_feature_0_scaled
-0.5119068988408909
prefill_ln2_1_feature_0_value
-0.5119068988408909
prefill_ln2_1_feature_1_normalized
0.5119068988408909
prefill_ln2_1_feature_1_scaled
0.5119068988408909
prefill_ln2_1_feature_1_value
0.5119068988408909
prefill_ffn_hidden_0_0_0_product0
0.6876854075163181
prefill_ffn_hidden_0_0_0_product1
0
prefill_ffn_hidden_0_0_0_sum
0.6876854075163181
prefill_ffn_hidden_0_0_0_preactivation
0.6876854075163181
prefill_ffn_hidden_0_0_1_product0
0
prefill_ffn_hidden_0_0_1_product1
-0.6876854075163181
prefill_ffn_hidden_0_0_1_sum
-0.6876854075163181
prefill_ffn_hidden_0_0_1_preactivation
-0.6876854075163181
prefill_ffn_hidden_0_0_2_product0
0
prefill_ffn_hidden_0_0_2_product1
0
prefill_ffn_hidden_0_0_2_sum
0
prefill_ffn_hidden_0_0_2_preactivation
0
prefill_ffn_hidden_0_1_0_product0
-0.5119068988408909
prefill_ffn_hidden_0_1_0_product1
0
prefill_ffn_hidden_0_1_0_sum
-0.5119068988408909
prefill_ffn_hidden_0_1_0_preactivation
-0.5119068988408909
prefill_ffn_hidden_0_1_1_product0
0
prefill_ffn_hidden_0_1_1_product1
0.5119068988408909
prefill_ffn_hidden_0_1_1_sum
0.5119068988408909
prefill_ffn_hidden_0_1_1_preactivation
0.5119068988408909
prefill_ffn_hidden_0_1_2_product0
0
prefill_ffn_hidden_0_1_2_product1
0
prefill_ffn_hidden_0_1_2_sum
0
prefill_ffn_hidden_0_1_2_preactivation
0
prefill_ffn_relu_0_0_0_activation
0.6876854075163181
prefill_ffn_relu_0_0_1_activation
0
prefill_ffn_relu_0_0_2_activation
0
prefill_ffn_relu_0_1_0_activation
0
prefill_ffn_relu_0_1_1_activation
0.5119068988408909
prefill_ffn_relu_0_1_2_activation
0
prefill_ffn_output_0_0_0_product0
0.6876854075163181
prefill_ffn_output_0_0_0_product1
0
prefill_ffn_output_0_0_0_product2
0
prefill_ffn_output_0_0_0_running0
0.6876854075163181
prefill_ffn_output_0_0_0_running1
0.6876854075163181
prefill_ffn_output_0_0_0_running2
0.6876854075163181
prefill_ffn_output_0_0_0_sum
0.6876854075163181
prefill_ffn_output_0_0_0_value
0.6876854075163181
prefill_ffn_output_0_0_1_product0
0
prefill_ffn_output_0_0_1_product1
0
prefill_ffn_output_0_0_1_product2
0
prefill_ffn_output_0_0_1_running0
0
prefill_ffn_output_0_0_1_running1
0
prefill_ffn_output_0_0_1_running2
0
prefill_ffn_output_0_0_1_sum
0
prefill_ffn_output_0_0_1_value
0
prefill_ffn_output_0_1_0_product0
0
prefill_ffn_output_0_1_0_product1
0
prefill_ffn_output_0_1_0_product2
0
prefill_ffn_output_0_1_0_running0
0
prefill_ffn_output_0_1_0_running1
0
prefill_ffn_output_0_1_0_running2
0
prefill_ffn_output_0_1_0_sum
0
prefill_ffn_output_0_1_0_value
0
prefill_ffn_output_0_1_1_product0
0
prefill_ffn_output_0_1_1_product1
0.5119068988408909
prefill_ffn_output_0_1_1_product2
0
prefill_ffn_output_0_1_1_running0
0
prefill_ffn_output_0_1_1_running1
0.5119068988408909
prefill_ffn_output_0_1_1_running2
0.5119068988408909
prefill_ffn_output_0_1_1_sum
0.5119068988408909
prefill_ffn_output_0_1_1_value
0.5119068988408909
prefill_residual2_0_0_value
2.134899003016276
prefill_residual2_0_1_value
-0.4472135954999579
prefill_residual2_1_0_value
-0.0959051290352784
prefill_residual2_1_1_value
1.6078120278761694
prefill_readout_0_0_product0
2.134899003016276
prefill_readout_0_0_product1
0
prefill_readout_0_0_sum
2.134899003016276
prefill_readout_0_0_logit
2.134899003016276
prefill_readout_0_1_product0
0
prefill_readout_0_1_product1
-0.4472135954999579
prefill_readout_0_1_sum
-0.4472135954999579
prefill_readout_0_1_logit
-0.4472135954999579
prefill_readout_0_2_product0
0
prefill_readout_0_2_product1
0
prefill_readout_0_2_sum
0
prefill_readout_0_2_logit
0
prefill_class_0_max_max
2.134899003016276
prefill_class_0_exp_0_shifted
0
prefill_class_0_exp_0_term
1
prefill_class_0_exp_1_shifted
-2.582112598516234
prefill_class_0_exp_1_term
0.0756140929478022
prefill_class_0_exp_2_shifted
-2.134899003016276
prefill_class_0_exp_2_term
0.11825653332669596
prefill_class_0_normalize_running0
1
prefill_class_0_normalize_running1
1.0756140929478022
prefill_class_0_normalize_running2
1.1938706262744982
prefill_class_0_normalize_denominator
1.1938706262744982
prefill_class_0_normalize_logS
0.17720065589584005
prefill_class_0_normalize_lse
2.312099658912116
prefill_class_0_probability_0_probability
0.8376116959343609
prefill_class_0_probability_1_probability
0.063335248630547
prefill_class_0_probability_2_probability
0.09905305543509206
prefill_class_0_argmax_nextRow
0
prefill_class_0_argmax_nextID
97
prefill_class_0_argmax_nextProbability
0.8376116959343609
prefill_readout_1_0_product0
-0.0959051290352784
prefill_readout_1_0_product1
0
prefill_readout_1_0_sum
-0.0959051290352784
prefill_readout_1_0_logit
-0.0959051290352784
prefill_readout_1_1_product0
0
prefill_readout_1_1_product1
1.6078120278761694
prefill_readout_1_1_sum
1.6078120278761694
prefill_readout_1_1_logit
1.6078120278761694
prefill_readout_1_2_product0
0
prefill_readout_1_2_product1
0
prefill_readout_1_2_sum
0
prefill_readout_1_2_logit
0
prefill_class_1_max_max
1.6078120278761694
prefill_class_1_exp_0_shifted
-1.7037171569114478
prefill_class_1_exp_0_term
0.1820057212588121
prefill_class_1_exp_1_shifted
0
prefill_class_1_exp_1_term
1
prefill_class_1_exp_2_shifted
-1.6078120278761694
prefill_class_1_exp_2_term
0.20032544140497158
prefill_class_1_normalize_running0
0.1820057212588121
prefill_class_1_normalize_running1
1.182005721258812
prefill_class_1_normalize_running2
1.3823311626637835
prefill_class_1_normalize_denominator
1.3823311626637835
prefill_class_1_normalize_logS
0.3237713223010388
prefill_class_1_normalize_lse
1.9315833501772082
prefill_class_1_probability_0_probability
0.13166578760192524
prefill_class_1_probability_1_probability
0.7234156524931242
prefill_class_1_probability_2_probability
0.14491855990495064
prefill_class_1_argmax_nextRow
1
prefill_class_1_argmax_nextID
98
prefill_class_1_argmax_nextProbability
0.7234156524931242
prefill_capture_cacheEntries
2
prefill_capture_id0
97
prefill_capture_position0
0
prefill_capture_id1
98
prefill_capture_position1
1
prefill_capture_key0
0.4472135954999579
prefill_capture_key1
-0.4472135954999579
prefill_capture_key2
-0.6179478014890387
prefill_capture_key3
-0.1346867277606211
prefill_capture_value0
0.4472135954999579
prefill_capture_value1
-0.4472135954999579
prefill_capture_value2
-0.4472135954999579
prefill_capture_value3
0.4472135954999579
probe_edit_deltaUsed
0
probe_edit_targetValue
1
probe_edit_modelChanged
0
probe_edit_expectedID0
97
probe_edit_expectedID1
98
probe_edit_attemptPosition0
0
probe_edit_attemptPosition1
1
probe_input_0_inputRow
0
probe_input_0_x0
1
probe_input_0_x1
0
probe_ln1_0_statistics_sum
1
probe_ln1_0_statistics_mean
0.5
probe_ln1_0_statistics_centered0
0.5
probe_ln1_0_statistics_centered1
-0.5
probe_ln1_0_statistics_square0
0.25
probe_ln1_0_statistics_square1
0.25
probe_ln1_0_statistics_squareSum
0.5
probe_ln1_0_statistics_variance
0.25
probe_ln1_0_statistics_variancePlusEpsilon
1.25
probe_ln1_0_statistics_denominator
1.118033988749895
probe_ln1_0_feature_0_normalized
0.4472135954999579
probe_ln1_0_feature_0_scaled
0.4472135954999579
probe_ln1_0_feature_0_value
0.4472135954999579
probe_ln1_0_feature_1_normalized
-0.4472135954999579
probe_ln1_0_feature_1_scaled
-0.4472135954999579
probe_ln1_0_feature_1_value
-0.4472135954999579
probe_heads_setup_B
1
probe_heads_setup_T
1
probe_heads_setup_D
2
probe_heads_setup_H
1
probe_heads_setup_Dk
2
probe_heads_setup_Dv
2
probe_heads_project_Q_0_0_0_0_product0
0.4472135954999579
probe_heads_project_Q_0_0_0_0_product1
0
probe_heads_project_Q_0_0_0_0_value
0.4472135954999579
probe_heads_project_Q_0_0_0_1_product0
0
probe_heads_project_Q_0_0_0_1_product1
-0.4472135954999579
probe_heads_project_Q_0_0_0_1_value
-0.4472135954999579
probe_heads_project_K_0_0_0_0_product0
0.4472135954999579
probe_heads_project_K_0_0_0_0_product1
0
probe_heads_project_K_0_0_0_0_value
0.4472135954999579
probe_heads_project_K_0_0_0_1_product0
0
probe_heads_project_K_0_0_0_1_product1
-0.4472135954999579
probe_heads_project_K_0_0_0_1_value
-0.4472135954999579
probe_heads_project_V_0_0_0_0_product0
0.4472135954999579
probe_heads_project_V_0_0_0_0_product1
0
probe_heads_project_V_0_0_0_0_value
0.4472135954999579
probe_heads_project_V_0_0_0_1_product0
0
probe_heads_project_V_0_0_0_1_product1
-0.4472135954999579
probe_heads_project_V_0_0_0_1_value
-0.4472135954999579
probe_heads_reshape_Q_elements
2
probe_heads_permute_Q_0_0_0_0_value
0.4472135954999579
probe_heads_permute_Q_0_0_0_1_value
-0.4472135954999579
probe_heads_reshape_K_elements
2
probe_heads_permute_K_0_0_0_0_value
0.4472135954999579
probe_heads_permute_K_0_0_0_1_value
-0.4472135954999579
probe_heads_reshape_V_elements
2
probe_heads_permute_V_0_0_0_0_value
0.4472135954999579
probe_heads_permute_V_0_0_0_1_value
-0.4472135954999579
probe_rope_Q_0_frequency
1
probe_rope_Q_0_angle
2
probe_rope_Q_0_cos
-0.4161468365471424
probe_rope_Q_0_sin
0.9092974268256817
probe_rope_Q_0_product0
-0.18610652302818084
probe_rope_Q_0_product1
-0.406650171629573
probe_rope_Q_0_product2
0.406650171629573
probe_rope_Q_0_product3
0.18610652302818084
probe_rope_Q_0_rotated0
0.22054364860139217
probe_rope_Q_0_rotated1
0.5927566946577538
probe_rope_K_0_frequency
1
probe_rope_K_0_angle
2
probe_rope_K_0_cos
-0.4161468365471424
probe_rope_K_0_sin
0.9092974268256817
probe_rope_K_0_product0
-0.18610652302818084
probe_rope_K_0_product1
-0.406650171629573
probe_rope_K_0_product2
0.406650171629573
probe_rope_K_0_product3
0.18610652302818084
probe_rope_K_0_rotated0
0.22054364860139217
probe_rope_K_0_rotated1
0.5927566946577538
probe_append_cacheEntries
3
probe_append_retainedID0
1
probe_append_retainedID1
1
probe_append_afterID0
97
probe_append_afterID1
98
probe_append_afterID2
97
probe_append_retainedPosition0
1
probe_append_retainedPosition1
1
probe_append_afterPosition0
0
probe_append_afterPosition1
1
probe_append_afterPosition2
2
probe_append_retainedK0
1
probe_append_retainedK1
1
probe_append_retainedK2
1
probe_append_retainedK3
1
probe_append_afterK0
0.4472135954999579
probe_append_afterK1
-0.4472135954999579
probe_append_afterK2
-0.6179478014890387
probe_append_afterK3
-0.1346867277606211
probe_append_afterK4
0.22054364860139217
probe_append_afterK5
0.5927566946577538
probe_append_retainedV0
1
probe_append_retainedV1
1
probe_append_retainedV2
1
probe_append_retainedV3
1
probe_append_afterV0
0.4472135954999579
probe_append_afterV1
-0.4472135954999579
probe_append_afterV2
-0.4472135954999579
probe_append_afterV3
0.4472135954999579
probe_append_afterV4
0.4472135954999579
probe_append_afterV5
-0.4472135954999579
probe_append_retainedExact
1
probe_score_0_product0
0.09863011805570786
probe_score_0_product1
-0.2650888526745648
probe_score_0_raw
-0.1664587346188569
probe_score_0_score
-0.11770410003672563
probe_score_1_product0
-0.13628446278560138
probe_score_1_product1
-0.0798364595616545
probe_score_1_raw
-0.21612092234725588
probe_score_1_score
-0.15282056974803587
probe_score_2_product0
0.04863950093841435
probe_score_2_product1
0.3513604990615856
probe_score_2_raw
0.39999999999999997
probe_score_2_score
0.28284271247461895
probe_row_max
0.28284271247461895
probe_row_logit0
-0.11770410003672563
probe_row_shifted0
-0.4005468125113446
probe_row_term0
0.6699536068437599
probe_row_running0
0.6699536068437599
probe_row_logit1
-0.15282056974803587
probe_row_shifted1
-0.4356632822226548
probe_row_term1
0.646835490279414
probe_row_running1
1.316789097123174
probe_row_logit2
0.28284271247461895
probe_row_shifted2
0
probe_row_term2
1
probe_row_running2
2.316789097123174
probe_row_denominator
2.316789097123174
probe_row_p0
0.2891733251316062
probe_row_p1
0.2791948093517053
probe_row_p2
0.43163186551668853
probe_mix_0_product0
0.12932224245478396
probe_mix_0_running0
0.12932224245478396
probe_mix_0_product1
-0.12485971453510142
probe_mix_0_running1
0.004462527919682546
probe_mix_0_product2
0.19303163851007257
probe_mix_0_running2
0.19749416642975512
probe_mix_0_value
0.19749416642975512
probe_mix_1_product0
-0.12932224245478396
probe_mix_1_running0
-0.12932224245478396
probe_mix_1_product1
0.12485971453510142
probe_mix_1_running1
-0.004462527919682546
probe_mix_1_product2
-0.19303163851007257
probe_mix_1_running2
-0.19749416642975512
probe_mix_1_value
-0.19749416642975512
probe_concat_destinationOffset0
0
probe_concat_c0
0.19749416642975512
probe_concat_destinationOffset1
1
probe_concat_c1
-0.19749416642975512
probe_output_0_product0
0.19749416642975512
probe_output_0_running0
0.19749416642975512
probe_output_0_product1
0
probe_output_0_running1
0.19749416642975512
probe_output_0_value
0.19749416642975512
probe_output_1_product0
0
probe_output_1_running0
0
probe_output_1_product1
-0.19749416642975512
probe_output_1_running1
-0.19749416642975512
probe_output_1_value
-0.19749416642975512
probe_residual1_value0
1.1974941664297551
probe_residual1_value1
-0.19749416642975512
probe_ln2_0_statistics_sum
1
probe_ln2_0_statistics_mean
0.5
probe_ln2_0_statistics_centered0
0.6974941664297551
probe_ln2_0_statistics_centered1
-0.6974941664297551
probe_ln2_0_statistics_square0
0.48649811220353895
probe_ln2_0_statistics_square1
0.48649811220353895
probe_ln2_0_statistics_squareSum
0.9729962244070779
probe_ln2_0_statistics_variance
0.48649811220353895
probe_ln2_0_statistics_variancePlusEpsilon
1.486498112203539
probe_ln2_0_statistics_denominator
1.2192202886285723
probe_ln2_0_feature_0_normalized
0.5720821519582194
probe_ln2_0_feature_0_scaled
0.5720821519582194
probe_ln2_0_feature_0_value
0.5720821519582194
probe_ln2_0_feature_1_normalized
-0.5720821519582194
probe_ln2_0_feature_1_scaled
-0.5720821519582194
probe_ln2_0_feature_1_value
-0.5720821519582194
probe_ffn_hidden_0_0_0_product0
0.5720821519582194
probe_ffn_hidden_0_0_0_product1
0
probe_ffn_hidden_0_0_0_sum
0.5720821519582194
probe_ffn_hidden_0_0_0_preactivation
0.5720821519582194
probe_ffn_hidden_0_0_1_product0
0
probe_ffn_hidden_0_0_1_product1
-0.5720821519582194
probe_ffn_hidden_0_0_1_sum
-0.5720821519582194
probe_ffn_hidden_0_0_1_preactivation
-0.5720821519582194
probe_ffn_hidden_0_0_2_product0
0
probe_ffn_hidden_0_0_2_product1
0
probe_ffn_hidden_0_0_2_sum
0
probe_ffn_hidden_0_0_2_preactivation
0
probe_ffn_relu_0_0_0_activation
0.5720821519582194
probe_ffn_relu_0_0_1_activation
0
probe_ffn_relu_0_0_2_activation
0
probe_ffn_output_0_0_0_product0
0.5720821519582194
probe_ffn_output_0_0_0_product1
0
probe_ffn_output_0_0_0_product2
0
probe_ffn_output_0_0_0_running0
0.5720821519582194
probe_ffn_output_0_0_0_running1
0.5720821519582194
probe_ffn_output_0_0_0_running2
0.5720821519582194
probe_ffn_output_0_0_0_sum
0.5720821519582194
probe_ffn_output_0_0_0_value
0.5720821519582194
probe_ffn_output_0_0_1_product0
0
probe_ffn_output_0_0_1_product1
0
probe_ffn_output_0_0_1_product2
0
probe_ffn_output_0_0_1_running0
0
probe_ffn_output_0_0_1_running1
0
probe_ffn_output_0_0_1_running2
0
probe_ffn_output_0_0_1_sum
0
probe_ffn_output_0_0_1_value
0
probe_residual2_value0
1.7695763183879745
probe_residual2_value1
-0.19749416642975512
probe_readout_0_product0
1.7695763183879745
probe_readout_0_product1
0
probe_readout_0_sum
1.7695763183879745
probe_readout_0_logit
1.7695763183879745
probe_readout_1_product0
0
probe_readout_1_product1
-0.19749416642975512
probe_readout_1_sum
-0.19749416642975512
probe_readout_1_logit
-0.19749416642975512
probe_readout_2_product0
0
probe_readout_2_product1
0
probe_readout_2_sum
0
probe_readout_2_logit
0
probe_class_max_max
1.7695763183879745
probe_class_exp_0_shifted
0
probe_class_exp_0_term
1
probe_class_exp_1_shifted
-1.9670704848177296
probe_class_exp_1_term
0.1398659961908848
probe_class_exp_2_shifted
-1.7695763183879745
probe_class_exp_2_term
0.17040517107076136
probe_class_normalize_running0
1
probe_class_normalize_running1
1.1398659961908848
probe_class_normalize_running2
1.310271167261646
probe_class_normalize_denominator
1.310271167261646
probe_class_normalize_logS
0.2702341137016024
probe_class_normalize_lse
2.0398104320895767
probe_class_probability_0_probability
0.7632007976561935
probe_class_probability_1_probability
0.1067458398578614
probe_class_probability_2_probability
0.13005336248594518
probe_class_argmax_nextRow
0
probe_class_argmax_nextID
97
probe_class_argmax_nextProbability
0.7632007976561935
probe_outcome_reuseAccepted
1
probe_outcome_appendFrames
57
probe_outcome_appendQueryRows
1
probe_outcome_appendScoreCells
3
probe_outcome_cacheEntries
3
probe_outcome_retainedExact
1
probe_outcome_appendNextRow
0
probe_outcome_appendNextID
97
probe_outcome_appendNextProbability
0.7632007976561935
finish_actualHarnessRows
3
finish_actualHarnessScoreCells
7

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

PlannerPayload

PayloadMetric=8 · float64 · display precision 0 · Analytical payload metrics in payloadMetricNames order; exact integer binary64, never int32; no payload allocation.

Storage indexValue
01
11
22
34
44
58
6512
764

PlannerToken

TokenMetric=6 · float64 · display precision 0 · Analytical one-token metrics in tokenMetricNames order; hypothetical bits do not mutate the actual float64 probe.

Storage indexValue
04
14
2256
332
496
5768

PlannerWork

WorkMetric=6 · float64 · display precision 0 · Analytical MHA work metrics in workMetricNames order; score cells and paired K/V head rows, not latency or FLOPs.

Storage indexValue
03
19
23
39
41
53

prefill_AllClassIDs

ModelRow=5 · int32 · display 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.

Storage indexValue
097
198
2512
3256
4257

prefill_ClassIDs

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

Storage indexValue
097
198
2512

prefill_E

ModelRow=5 × D=2 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. All ten validated editable embeddings, including EOS and inactive learned pieces.

Storage indexValue
01
10
20
31
40
50
60.5
70.5
81
91

prefill_U

D=2 × ModelRow=5 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. All ten validated editable readout weights; only the first V columns contribute logits.

Storage indexValue
01
10
20
30
40
50
61
70
80
90

prefill_Bias

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

Storage indexValue
00
10
20
30
40

prefill_InputIDs

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

Storage indexValue
097
198

prefill_InputRows

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

Storage indexValue
00
11

prefill_X

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

Storage indexValue
01
10
20
31

prefill_LN1

B=1 × T=2 × D=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionX

B=1 × T=2 × D=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionWQ

D=2 × QueryFeature=2 · float64 · display 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.

Storage indexValue
01
10
20
31

prefill_ProjectionWK

D=2 × KeyFeature=2 · float64 · display 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.

Storage indexValue
01
10
20
31

prefill_ProjectionWV

D=2 × ValueFeature=2 · float64 · display 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.

Storage indexValue
01
10
20
31

prefill_ProjectionQConcat

B=1 × T=2 × QueryFeature=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionKConcat

B=1 × T=2 × KeyFeature=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionVConcat

B=1 × T=2 × ValueFeature=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionQSplit

B=1 × T=2 × H=1 × Dk=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionQHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionKSplit

B=1 × T=2 × H=1 × Dk=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionKHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionVSplit

B=1 × T=2 × H=1 × Dv=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_ProjectionVHeads

B=1 × H=1 × T=2 × Dv=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

prefill_RotatedQHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Actual RoPE(ProjectionQHeads) supplied as attendHeads QHeads; original projection is retained separately.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211

prefill_RotatedKHeads

B=1 × H=1 × T=2 × Dk=2 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Actual RoPE(ProjectionKHeads) supplied as attendHeads KHeads; original projection is retained separately.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211

prefill_RoPEAngles

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

Storage indexValue
00
11

prefill_RoPECos

Position=2 · float64 · display 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.

Storage indexValue
01
10.5403023058681398

prefill_RoPESin

Position=2 · float64 · display 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.

Storage indexValue
00
10.8414709848078965

prefill_Attentionraw

B=1 × H=1 × Query=2 × Key=2 · float64 · display 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.

Storage indexValue
00.39999999999999997
1-0.2161209223472559
2-0.2161209223472559
30.4000000000000001

prefill_Attentionscores

B=1 × H=1 × Query=2 × Key=2 · float64 · display 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.

Storage indexValue
00.28284271247461895
1-0.1528205697480359
2-0.1528205697480359
30.28284271247461906

prefill_Attentionallowed

B=1 × H=1 × Query=2 × Key=2 · bool · display 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.

Storage indexValue
0true
1false
2true
3true

prefill_Attentionlogits

B=1 × H=1 × Query=2 × Key=2 · float64 · display 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.

Storage indexValue
00.28284271247461895
1-0.1528205697480359
2-0.1528205697480359
30.28284271247461906

prefill_Attentionprobabilities

B=1 × H=1 × Query=2 × Key=2 · float64 · display 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.

Storage indexValue
01
10
20.3927748060431144
30.6072251939568857

prefill_AttentionOHeads

B=1 × H=1 × Query=2 × Dv=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784

prefill_AttentionC

B=1 × T=2 × JoinedValue=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784

prefill_AttentionWO

JoinedValue=2 × D=2 · float64 · display 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.

Storage indexValue
01
10
20
31

prefill_AttentionOutput

B=1 × T=2 × D=2 · float64 · display 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
30.0959051290352784

prefill_R1

B=1 × T=2 × D=2 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Exact named-shape addition of X and AttentionOutput; no broadcasting.

Storage indexValue
01.4472135954999579
1-0.4472135954999579
2-0.0959051290352784
31.0959051290352784

prefill_LN2

B=1 × T=2 × D=2 · float64 · display 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.

Storage indexValue
00.6876854075163181
1-0.6876854075163181
2-0.5119068988408909
30.5119068988408909

prefill_W1

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

Storage indexValue
01
10
20
30
41
50

prefill_b1

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

Storage indexValue
00
10
20

prefill_Z

B=1 × T=2 × HiddenFeature=3 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Hidden preactivations X W1+b1; no batch or token mixing.

Storage indexValue
00.6876854075163181
1-0.6876854075163181
20
3-0.5119068988408909
40.5119068988408909
50

prefill_Hidden

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

Storage indexValue
00.6876854075163181
10
20
30
40.5119068988408909
50

prefill_W2

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

Storage indexValue
01
10
20
31
40
50

prefill_b2

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

Storage indexValue
00
10

prefill_F

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

Storage indexValue
00.6876854075163181
10
20
30.5119068988408909

prefill_Y

B=1 × T=2 × D=2 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Exact named-shape addition of R1 and F; no broadcasting.

Storage indexValue
02.134899003016276
1-0.4472135954999579
2-0.0959051290352784
31.6078120278761694

prefill_Logits

Position=2 × Class=3 · float64 · display 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.

Storage indexValue
02.134899003016276
1-0.4472135954999579
20
3-0.0959051290352784
41.6078120278761694
50

prefill_Max

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

Storage indexValue
02.134899003016276
11.6078120278761694

prefill_Shifted

Position=2 × Class=3 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Computed class logit minus its saved row maximum.

Storage indexValue
00
1-2.582112598516234
2-2.134899003016276
3-1.7037171569114478
40
5-1.6078120278761694

prefill_Terms

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

Storage indexValue
01
10.0756140929478022
20.11825653332669596
30.1820057212588121
41
50.20032544140497158

prefill_Denominator

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

Storage indexValue
01.1938706262744982
11.3823311626637835

prefill_LogS

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

Storage indexValue
00.17720065589584005
10.3237713223010388

prefill_LSE

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

Storage indexValue
02.312099658912116
11.9315833501772082

prefill_P

Position=2 × Class=3 · float64 · display precision 8 · Actual full-prefix call prefill, absolute positions 0..1. Terms/Denominator for real active classes only; no inactive-class probabilities.

Storage indexValue
00.8376116959343609
10.063335248630547
20.09905305543509206
30.13166578760192524
40.7234156524931242
50.14491855990495064

prefill_NextRows

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

Storage indexValue
00
11

prefill_NextIDs

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

Storage indexValue
097
198

prefill_NextProbability

Position=2 · float64 · display 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.

Storage indexValue
00.8376116959343609
10.7234156524931242

prefill_CacheIDs

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

Storage indexValue
097
198

prefill_CachePositions

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

Storage indexValue
00
11

prefill_CacheKeys

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211

prefill_CacheValues

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

ProbeBaselineParameters

Parameter=26 · float64 · display precision 8 · All26 default prefill parameters in parameterNames order; baseline is independent of planner dimensions.

Storage indexValue
00
11
20
30
41
50
60
70.5
80.5
91
101
111
120
130
140
150
160
171
180
190
200
210
220
230
240
250

ProbeTargetParameters

Parameter=26 · float64 · display precision 8 · Actual represented requested parameters in parameterNames order, including inactive fields.

Storage indexValue
00
11
20
30
41
50
60
70.5
80.5
91
101
111
120
130
140
150
160
171
180
190
200
210
220
230
240
250

ProbeExpectedIDs

RequestedPosition=2 · int32 · display precision 0 · Independently requested ordered prefix, distinct from the attempted cache IDs.

Storage indexValue
097
198

attempt_IDs

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

Storage indexValue
097
198

attempt_Positions

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

Storage indexValue
00
11

attempt_Keys

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211

attempt_Values

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

probe_AllClassIDs

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

Storage indexValue
097
198
2512
3256
4257

probe_ClassIDs

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

Storage indexValue
097
198
2512

probe_E

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

Storage indexValue
01
10
20
31
40
50
60.5
70.5
81
91

probe_U

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

Storage indexValue
01
10
20
30
40
50
61
70
80
90

probe_Bias

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

Storage indexValue
00
10
20
30
40

probe_InputIDs

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

Storage indexValue
097

probe_InputRows

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

Storage indexValue
00

probe_AbsoluteQueryPosition

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

Storage indexValue
02

probe_BeforeIDs

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

Storage indexValue
097
198

probe_BeforePositions

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

Storage indexValue
00
11

probe_BeforeKeys

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211

probe_BeforeValues

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579

probe_X

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

Storage indexValue
01
10

probe_LN1

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionX

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionWQ

D=2 × QueryFeature=2 · float64 · display precision 8 · Actual cached append probe: 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}.

Storage indexValue
01
10
20
31

probe_ProjectionWK

D=2 × KeyFeature=2 · float64 · display precision 8 · Actual cached append probe: 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}.

Storage indexValue
01
10
20
31

probe_ProjectionWV

D=2 × ValueFeature=2 · float64 · display precision 8 · Actual cached append probe: 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}.

Storage indexValue
01
10
20
31

probe_ProjectionQConcat

B=1 × T=1 × QueryFeature=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionKConcat

B=1 × T=1 × KeyFeature=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionVConcat

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionQSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionQHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionKSplit

B=1 × T=1 × H=1 × Dk=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionKHeads

B=1 × H=1 × T=1 × Dk=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionVSplit

B=1 × T=1 × H=1 × Dv=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_ProjectionVHeads

B=1 × H=1 × T=1 × Dv=2 · float64 · display precision 8 · Actual cached append probe: 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.

Storage indexValue
00.4472135954999579
1-0.4472135954999579

probe_RotatedQHeads

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

Storage indexValue
00.22054364860139217
10.5927566946577538

probe_NewRotatedKHeads

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

Storage indexValue
00.22054364860139217
10.5927566946577538

probe_RoPEAngles

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

Storage indexValue
02

probe_RoPECos

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

Storage indexValue
0-0.4161468365471424

probe_RoPESin

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

Storage indexValue
00.9092974268256817

probe_AfterIDs

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

Storage indexValue
097
198
297

probe_AfterPositions

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

Storage indexValue
00
11
22

probe_AfterKeys

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.6179478014890387
3-0.1346867277606211
40.22054364860139217
50.5927566946577538

probe_AfterValues

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

Storage indexValue
00.4472135954999579
1-0.4472135954999579
2-0.4472135954999579
30.4472135954999579
40.4472135954999579
5-0.4472135954999579

probe_Attentionraw

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

Storage indexValue
0-0.1664587346188569
1-0.21612092234725588
20.39999999999999997

probe_Attentionscores

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

Storage indexValue
0-0.11770410003672563
1-0.15282056974803587
20.28284271247461895

probe_Attentionallowed

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

Storage indexValue
0true
1true
2true

probe_Attentionlogits

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

Storage indexValue
0-0.11770410003672563
1-0.15282056974803587
20.28284271247461895

probe_Attentionprobabilities

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

Storage indexValue
00.2891733251316062
10.2791948093517053
20.43163186551668853

probe_AttentionOHeads

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

Storage indexValue
00.19749416642975512
1-0.19749416642975512

probe_AttentionC

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

Storage indexValue
00.19749416642975512
1-0.19749416642975512

probe_AttentionWO

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

Storage indexValue
01
10
20
31

probe_AttentionOutput

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

Storage indexValue
00.19749416642975512
1-0.19749416642975512

probe_R1

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

Storage indexValue
01.1974941664297551
1-0.19749416642975512

probe_LN2

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

Storage indexValue
00.5720821519582194
1-0.5720821519582194

probe_W1

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

Storage indexValue
01
10
20
30
41
50

probe_b1

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

Storage indexValue
00
10
20

probe_Z

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

Storage indexValue
00.5720821519582194
1-0.5720821519582194
20

probe_Hidden

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

Storage indexValue
00.5720821519582194
10
20

probe_W2

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

Storage indexValue
01
10
20
31
40
50

probe_b2

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

Storage indexValue
00
10

probe_F

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

Storage indexValue
00.5720821519582194
10

probe_Y

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

Storage indexValue
01.7695763183879745
1-0.19749416642975512

probe_Logits

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

Storage indexValue
01.7695763183879745
1-0.19749416642975512
20

probe_ChoiceClassIDs

Class=3 · int32 · display precision 0 · Actual cached append probe: 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.

Storage indexValue
097
198
2512

probe_ChoiceZ

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

Storage indexValue
01.7695763183879745
1-0.19749416642975512
20

probe_ChoiceShifted

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

Storage indexValue
00
1-1.9670704848177296
2-1.7695763183879745

probe_ChoiceTerms

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

Storage indexValue
01
10.1398659961908848
20.17040517107076136

probe_ChoiceDenominator

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

Storage indexValue
01.310271167261646

probe_ChoiceLogS

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

Storage indexValue
00.2702341137016024

probe_ChoiceLSE

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

Storage indexValue
02.0398104320895767

probe_ChoiceP

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

Storage indexValue
00.7632007976561935
10.1067458398578614
20.13005336248594518

probe_ChoiceNextRow

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

Storage indexValue
00

probe_ChoiceNextID

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

Storage indexValue
097

probe_ChoiceNextProbability

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

Storage indexValue
00.7632007976561935

Try T=0 and T=8192: the analytical payload changes while the real probe keeps the same two-row prefill. Try each request edit. For model edits use delta=0, then delta=0.5, and inspect the actual represented target. Reset, input edits and trace navigation clear graded answers. Saved-path selectors only inspect evidence.

Check your understanding

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

1. For the current analytical B=1, L=1, Hkv=1, old T=2, Dk=2, Dv=2, bits=64, which logical K+V budget is saved?
2. The analytical next length is Tk=3 and factor=B*L*Hkv=1. Which saved work counts and units are correct?
3. The planner has old T=2, but the fixed probe is accepted. Which neural evidence actually exists?
4. Current editKind=0, delta=0.5, edit field=none, represented target=1, modelChanged=0. What explains the saved reuse outcome?
5. Transfer: edit a model field initially equal to1. Which binary64 round-to-nearest, ties-to-even outcome should the actual identity guard use?

At reset the planner’s old payload is 64 bytes. Adding one token adds 32 bytes, giving 96 bytes. Those are logical K/V counts, not a measurement of JavaScript memory. The independent probe prefills the observed IDs [97,98] and attempts to append observed ID97 using the actual cache helper. A successful attempt contains real new-row arithmetic; a rejected attempt contains the real guard reason and no new neural row.

Read the first four summaries as old payload bytes, next payload bytes, bytes per token and actual reuse acceptance. In Analytical budget: count a payload without allocating it, the saved PlannerPayload[8], PlannerToken[6] and PlannerWork[6] vectors contain named count slots, rather than one slot per hypothetical token. Open Every saved budget multiplication, addition and division to follow the actual saved operands.

In Actual fixed probe: reuse, or reject before a new neural row, inspect the unchanged baseline, detached attempt, separately requested IDs and all26 baseline/target parameters. The outcome reports whether δ was used, its actual represented target and whether the model changed. Saved neural path (inspection only) offers the actual prefill and, after success, the accepted append. Saved query, Attention key and Active compact class select saved operands. The append has absolute query2/local0; switching to prefill selects its last available query1, and you can explicitly inspect query0 as well. After rejection only prefill remains available.

Editing an input, choosing Reset example, or seeking with Previous step, Next step or Calculation step clears graded answers. The four inspection selectors preserve answers and the trace cursor because they only select saved evidence. Invalid drafts show a reason and remove the unavailable result and its questions. No result is repaired behind the controls.

Review IV-49 — Cached Versus Uncached Decoding for cached/full equivalence. Book II’s I.8 — Indexed quantities and summation explains indexed counting, II.4 — Dot product, angle, and orthogonality explains a dot product, and VIII.2 — Rounding and representation error explains rounding. Book III’s III-41 — Composition and Learned Representations reviews composition of operations and III-16 — Multiclass Classification and Softmax Regression reviews logits and probabilities.

Give each number a job

A token is an observed input piece represented by an integer ID. Prefill processes the old prompt and constructs its cache. A key is a feature vector compared with a query; a value is the feature vector mixed using attention weights. A query belongs to the token currently asking for that mixture. A head is one such comparison-and-mixture channel. A layer is one decoder block, with its own past keys and values.

Q denotes queries, K denotes keys and V denotes values. A tensor is an array with named dimensions, called axes. A shape such as [B,Hkv,T,Dk] tells us how many entries occur along each axis. Multiplying those lengths counts scalar entries. A payload means only the numeric K/V entries counted here. A bit is one binary digit; eight bits make one byte. A proposed bit width is a storage assumption, not evidence that the running model uses that representation.

Planner symbol / controlMeaningAllowed valuesReset
BNumber of sequences in the batchInteger 1 through 41
LNumber of decoder layersInteger 1 through 641
HkvKey/value heads per layerInteger 1 through 321
TOLD stored tokens per sequenceInteger 0 through 81922
DkScalar features in one key, and in a matching queryInteger 1 through 2562
DvScalar features in one valueInteger 1 through 2562
bitsHypothetical stored bits per K/V scalarExactly 8, 16, 32 or 6464
editKindWhich real reuse request to tryInteger 0 through 50
delta, written δ in equationsRequested parameter adjustment in selected editsFinite number from −1 through 10.5

All nine fields validate, including δ when the chosen edit does not use it. Dimensions must already be integers: 2.5 is rejected, not rounded down. At the raw state boundary, a numeric string is not a number; the native controls separately parse and validate their text drafts. Nonfinite numeric inputs are unavailable, and an invalid state has a reason rather than an old successful result.

For the planner, define factor = B × L × Hkv: the number of batch/layer/head combinations. One layer’s K has conceptual shape [B,Hkv,T,Dk]; its V has [B,Hkv,T,Dv]. L copies contribute to the total. These are conceptual shapes, not arrays allocated by the lesson.

We assume ordinary multi-head attention (MHA): the query-head count Hq equals Hkv. Hq is the number of query heads. Grouped-query attention, where different query heads can share K/V, needs a separate mapping and is developed in IV-61 — Multi-Query and Grouped-Query Attention. Our score-count formula should not be carried into that setting unchanged.

Count entries before counting bytes

Each old token has Dk key entries and Dv value entries for every batch/layer/head combination. Follow this arithmetic in order:

factor=BLHkv,KElements=factor TDk,VElements=factor TDv,payloadElements=KElements+VElements,payloadBits=payloadElements bits,payloadBytes=payloadBits/8.\begin{aligned} \mathrm{factor}&=B L Hkv,\\ \mathrm{KElements}&=\mathrm{factor}\,T Dk,\\ \mathrm{VElements}&=\mathrm{factor}\,T Dv,\\ \mathrm{payloadElements}&=\mathrm{KElements}+\mathrm{VElements},\\ \mathrm{payloadBits}&=\mathrm{payloadElements}\,\mathrm{bits},\\ \mathrm{payloadBytes}&=\mathrm{payloadBits}/8. \end{aligned}

Names ending in Elements count scalars; Bits count bits; Bytes count bytes. Keys and values are separate payloads, so their counts add. Multiplication by L includes every layer; forgetting it undercounts a multilayer model. Multiplying by two instead of Dk+Dv works only when the key and value widths have already been counted correctly.

One additional token contributes

bytesPerToken=factor(Dk+Dv)bits/8,nextPayloadBytes=payloadBytes+bytesPerToken.\mathrm{bytesPerToken}=\mathrm{factor}(Dk+Dv)\mathrm{bits}/8, \qquad \mathrm{nextPayloadBytes}=\mathrm{payloadBytes}+\mathrm{bytesPerToken}.

At reset, factor=1×1×1=1. There are 1×2×2=4 key entries and 4 value entries. Their 8 scalars occupy 8×64=512 bits, or 512/8=64 bytes. One new token adds 1×(2+2)=4 scalars, then 4×64/8=32 bytes. The next payload is 64+32=96 bytes. The key and value parts each grow from 32 to 48 bytes.

To separate the two widths, change only Dk from2 to3 at reset. K now has6 entries and V still has4, so the old10 scalars use80 bytes. Each token adds5 scalars or40 bytes, giving next payload120 bytes. Score-cell counts remain3 and9 although each dot product is longer. These planner edits leave the actual two-feature probe unchanged.

Hold dimensions fixed and change bits from64 to32,16,8. The old logical payload becomes32,16,8 bytes; its next payload becomes48,24,12 bytes, respectively. This arithmetic assumes that proposed representation. No quantizer, rounding of neural features, packed buffer or changed model dtype follows from this control. Actual probe arithmetic stays float64, also called binary64: a 64-bit floating-point representation.

The estimate excludes queries, model weights, attention scores, output tensors, token IDs, metadata, object headers, allocator padding and temporary workspaces. An allocator is the runtime’s memory manager. The lesson also retains extensive teaching evidence beyond the reusable cache. Neither total process memory nor peak memory equals this payload formula.

An empty analytical cache is a useful boundary

Set only T=0 at the reset dimensions. KElements=1×0×2=0 and VElements=0, so payloadElements, payloadBits and payloadBytes are all0. Per-token storage is still32 bytes. The next hypothetical cache has one token and32 bytes.

Write Tk=T+1 for the number of available keys after that next token. Here Tk=1. Cached and full next-prefix score counts are both1, and each projects one head row. There is no past work to save on the first token. T=0 creates no empty neural tensor: the separate real probe still prefills its fixed two observed tokens. Likewise, planner T=8192 permits an analytical next length8193 without extending the toy kernel’s three-token capacity.

A large exact count without a large allocation

At the maximum settings, B=4, L=64, Hkv=32, T=8192, Dk=Dv=256 and bits=64. Powers of two let us check the arithmetic by hand. The notation 2 raised to n means multiply 2 by itself n times.

factor=4×64×32=8192=2^13. Each K/V part has 2^13×2^13×2^8=2^34=17,179,869,184 scalar entries. Together that is 2^35=34,359,738,368 entries. Multiplying by 64=2^6 gives 2^41=2,199,023,255,552 bits; dividing by8 gives 2^38=274,877,906,944 bytes.

One new token adds 2^13×(256+256)=2^22=4,194,304 entries. Its 2^28=268,435,456 bits occupy 2^25=33,554,432 bytes. Therefore nextPayloadBytes=274,877,906,944+33,554,432=274,911,461,376 and the next bit count is2,199,023,255,552+268,435,456=2,199,291,691,008.

These are handwritten integer anchors, not observed allocations. At these settings each key/value part contributes 137,438,953,472 bytes, adding to the total above. Every intermediate integer in this bounded planner is below2^53, the limit relevant to consecutive exact integers in binary64. Count tensors use float64 with display precision0. A 32-bit integer conversion would corrupt large counts; a scientific-looking decimal rounded for display must not become a later operand. The evidence uses small fixed vectors, rather than a row for each hypothetical token.

One new query still reads all keys and values

Caching saves the projection of old rows; it does not remove old rows from attention. A query must compare itself with every available key, normalize those scores, then mix every corresponding value. Bandwidth is the amount of data transferred per unit time. Reading a growing cache can therefore matter even when only one new row is projected.

For the next token, Tk=T+1. A score cell is one query/key dot product divided by the square root of Dk. For one batch/layer/head, the cached score shape is [1,Tk], whereas a full next-prefix call has [Tk,Tk]. Including all combinations gives

cachedScoreCells=factor Tk,fullScoreCells=factor Tk2,cachedProjectedHeadRows=factor,fullProjectedHeadRows=factor Tk.\begin{aligned} \mathrm{cachedScoreCells}&=\mathrm{factor}\,Tk,\\ \mathrm{fullScoreCells}&=\mathrm{factor}\,Tk^2,\\ \mathrm{cachedProjectedHeadRows}&=\mathrm{factor},\\ \mathrm{fullProjectedHeadRows}&=\mathrm{factor}\,Tk. \end{aligned}

A projected head row here means the pair of newly computed K and V vectors for one head/token. It does not mean Hkv different input-token embeddings, two separate rows for K versus V, or a specified number of floating-point operations. The full score count includes the square kernel’s raw future-key cells; its causal mask later forbids those keys for earlier queries. It is not a count of only the allowed lower triangle.

At reset, Tk=3, so cached/full score cells are 1×3=3 and 1×3×3=9. Projected head rows are 1 and 3. The cached query still reads three keys and three values. Making Dk larger lengthens each dot product even if the score-cell count is unchanged; making Dv larger lengthens the weighted mixture. Counting cells alone cannot describe all arithmetic.

At maximum, Tk=8193 and Tk²=(8192+1)²=8192²+2×8192+1=67,125,249. Cached cells are 8192×8193=2^26+2^13=67,117,056. Full cells are 8192×67,125,249=2^39+2^27+2^13=549,890,039,808. Projected head rows are 8192 cached and67,117,056 full.

Latency means elapsed time to obtain a result. None of these counts measures it. Hardware, data movement, kernel implementation and fixed overhead affect elapsed time. The lesson has no timer or measured speedup, and a ratio of cell counts is not a measured latency ratio. Cached next-query attention grows linearly with Tk under these assumptions; it does not become constant-time.

Fix the actual model before trying reuse

The probe is deliberately small and independent of every planner dimension: B=L=H=1, where H is the actual head count, old length N=2, feature widths D=Dk=Dv=2, where D is the input and residual feature width, float64, and zero BPE merges. N denotes actual old probe tokens, while T remains the planner’s hypothetical old context. BPE means byte-pair encoding; this probe already receives observed IDs and does not tokenize text again. IDs97 and98 denote a and b; appended ID97 denotes a. The input is [97,98] then97, rather than a generated choice.

The fixed embedding table E has shape [5,2], mapping a compact row to two input features. Its five rows, in compact storage order a,b,EOS,ab,abab, 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 entries named e00 or e40 mean row0/feature0 or row4/feature0. U entry u00 means feature0/output-column0. Only compact classes0,1,2, mapped to public IDs [97,98,512], are active at zero merges. ID512 is EOS, end of sequence. Five stored columns do not make five active output probabilities.

The 26 model fields comprise one merge count, ten E entries, ten U entries and five biases. The probe starts each derivation with all26 defaults. First the actual prefillCache constructs the old cache and preserves every full-forward step and tensor. A separate target model, requested prefix and attempted cache are then prepared. The original cache is retained unchanged. The actual appendCached checks the attempt before it can gather a new embedding or compute attention; it is not a table of predicted success messages.

Why these are the keys and values being saved

This short real-arithmetic derivation connects the probe to the counted payload. A row vector x=(x0,x1) has feature mean μ=(x0+x1)/2 and population variance v=((x0−μ)²+(x1−μ)²)/2. Layer normalization subtracts that mean and divides by√(v+1), with fixed scale1 and offset0. The added1 is epsilon, preventing division by zero. For a=(1,0), μ=1/2, v=1/4 and divisor√5/2. Define α=1/√5 and u=(α,−α). The first normalized a is u and normalized b is−u.

Identity Q/K/V projection matrices preserve these two features. RoPE, rotary positional encoding, rotates Q and K at absolute token position j using

Rj(x,y)=(xcos⁡j−ysin⁡j, xsin⁡j+ycos⁡j).R_j(x,y)=(x\cos j-y\sin j,\ x\sin j+y\cos j).

Here cos and sin are cosine and sine, the functions that determine a two-dimensional rotation. Angles are j radians; j=0,1,2 counts positions from the original origin. Values remain unrotated. Thus the old cache has K=[u,−R1u], V=[u,−u] and positions [0,1]. The new a has q=k_new=R2u and v_new=u. Its local row index0 is absolute position2. The updated K/V shapes are [1,1,3,2]; new Q has shape [1,1,1,2], with axes batch, head, query, key feature.

Define g=√2/5. The three scaled query/key scores are (g cos2,−g cos1,g) in key order0,1,2. For example, q dotted with u is2α²cos2, and division by√Dk=√2 yields g cos2. Every key is allowed because its position is at most2. Subtract the maximum g; define exponential terms e0=exp(g(cos2−1)), e1=exp(−g(1+cos1)), e2=1, and denominator Z=((0+e0)+e1)+1. Here exp is the exponential function. Attention weight pj=ej/Z, with j labeling the corresponding key, gives mixture (αh,−αh) where h=p0−p1+p2=1−2p1.

For completeness, the first residual adds the new embedding: R1=(1+αh,−αh). Its mean is1/2. Put d=1/2+αh and r=d/√(1+d²). The second normalization is (r,−r). The fixed feed-forward network (FFN) projects to three hidden coordinates (r,−r,0), applies ReLU (replace negatives with0) to get (r,0,0), then projects to (r,0). The second residual gives final features Y=(1+αh+r,−αh). All three hidden coordinates are actually calculated.

A logit is an unnormalized output-class score. Let A=1+αh+r. The three active logits are (A,−αh,0). Subtracting maximum A gives class denominator Zclass=((0+1)+exp(−αh−A))+exp(−A), and class probabilities (1,exp(−αh−A),exp(−A))/Zclass. These class probabilities differ from attention weights pj. The largest logit selects a/97; an exact tie uses the lowest compact class index. Display rounding does not choose the winner.

These expressions are exact-real explanations, not a substitute for the saved binary64 operations. Products, ordered additions, sine, cosine, square roots and exponentials can round. Read the actual saved probabilities and intermediate values in the inspector; the manuscript does not invent a decimal probability or claim universal cross-library bit equality.

Six requests, three kinds of identity

Invalidation means refusing reuse because the request does not satisfy the cache contract. It does not mean silently editing the old cache to make the request fit. The model is its parameters and fixed kernel revision; the prefix is the ordered old IDs; the position records where those IDs occurred. Matching shapes alone cannot establish any of those identities.

editKindActual requestWhat the probe demonstrates
0Same model, requested IDs [97,98], positions [0,1]Reuse succeeds for every valid δ; δ is inactive
1Target e00 becomes the represented result of1+δAn actual represented change rejects model identity; old a K/V can change
2Requested old IDs become [98,97]Rejected prefix identity; same length does not mean same ordered context
3A detached attempted cache has positions [1,2]Rejected position identity; this helper requires the original0-based positions
4Target u00 becomes represented1+δAn actual change rejects the conservative model policy even though readout is downstream of old K/V
5Target e40 becomes represented1+δAn actual change rejects the same policy even though row4 is inactive here

Policy versus minimum dependency: old K/V in this one-layer model depend on old embeddings, normalization, projections and positions. U reads final features afterward, so changing only U does not require different old K/V mathematically. An inactive embedding row is not read by this observed prefix either. Nevertheless, this helper deliberately compares all26 numeric fields. That conservative rule is simple and safe within its declared contract; it does not assert that every changed field mathematically changes every cache coordinate. Deeper decoders require reasoning about dependencies separately for each layer.

For a concrete active-embedding counterexample, choose edit1 and δ=−1. The target a row becomes (0,0), so its normalized row, required key and required value become zero. Retaining the old nonzero a key/value would be stale. With δ=0.5, the target a row (1.5,0) has normalized coordinates (3/5,−3/5) in exact arithmetic, different from (1/√5,−1/√5).

A prefix swap requests a different computation without changing the cache’s own IDs. This is why expectedPrefixIDs is a separate argument: checking cache.ids against itself cannot detect changed intent. A position shift changes the rotation angles. The attempted [1,2] metadata is rejected; the helper does not rebuild a cache at a shifted origin or silently reset its positions.

A nonzero edit can leave the represented model unchanged

Binary64 stores selected real numbers. Round to nearest, ties to even (RN) chooses the nearest representable value; at an exact halfway case it chooses the value with an even last significand bit. The significand is the stored significant binary digits. δ is first a represented input, and the addition1+δ produces another represented result. Reuse compares that actual target field with1 using numeric equality, with no tolerance.

The next representable value above1 is1+2^−52; the next below is1−2^−53. Spacing halves below this power-of-two boundary. The upward midpoint is therefore1+2^−53, while the downward midpoint is1−2^−54. Both ties select1. For a represented δ,

RN⁡(1+δ)=1exactly when−2−54≤δ≤2−53.\operatorname{RN}(1+\delta)=1 \quad\text{exactly when}\quad -2^{-54}\leq\delta\leq2^{-53}.
Represented δTarget after the additionModel-edit reuse for edits1,4,5
0, including either signed zero1Accepted
+2^−531, upward midpoint tieAccepted
−2^−541, downward midpoint tieAccepted
+2^−521+2^−52Rejected: actual model change
−2^−531−2^−53Rejected: actual model change
±2^−1074, the smallest nonzero binary64 magnitudes1Accepted
+0.51.5Rejected: actual model change

The smallest positive magnitude is Number.MIN_VALUE in JavaScript. Such subnormal numbers extend representation toward zero with fixed tiny spacing; adding either sign here is too small to change1. The unequal midpoint distances are why the same-sized positive and negative edits can behave differently. For example, +2^−53 leaves1 unchanged while −2^−53 changes it. No tolerance or “δ is nonzero” shortcut reproduces these boundary cases correctly. Signed zeros compare numerically equal. All of this concerns the actual target addition; planner integers are never silently rounded into a valid dimension.

What rejected and accepted attempts actually contain

A rejected attempt leaves the real prefill intact. It has zero new neural frames and zero new neural tensors: there is no new Q, score row, probability vector, prediction or copied-looking placeholder. Planner quantities remain meaningful because they describe a separate analytical calculation. Model and prefix rejections have code UNAVAILABLE and reasons beginning CACHE_MODEL_MISMATCH or CACHE_PREFIX_MISMATCH; the position rejection has code INVALID_INPUT and reason beginning CACHE_POSITION_MISMATCH. A handled rejection records the actual complete code/reason pair; an unrelated fault must not be relabeled as a familiar invalidation.

A successful attempt gathers only the new a row, projects it, rotates its Q/K once at absolute2, appends K/V and reads all three available keys/values. It retains actual old-coordinate copy flags, logits, class probabilities and prediction. Actual harness rows are2 prefill+1 append=3 when accepted and2+0=2 when rejected. Those counts never multiply by planner B, L or Hkv. There is no additional full-append reference in this probe.

For orientation, the source retains112 full-prefill steps and one capture step, plus57 original full-forward tensors and four captured cache tensors. The accepted append contributes57 more steps and67 tensors. Three small planner vectors and the request/outcome evidence complete the record:

Complete saved lesson recordStepsTensorsActual query rows
Accepted reuse1771382 prefill + 1 append = 3
Rejected reuse120712 prefill + 0 append = 2

These are manually counted source declarations, not observed execution results. They stay the same when only planner dimensions change. A step saves an operation and its operands/outputs; a tensor record saves an array and its shape/axis/dtype/provenance metadata, so these are different counts. Extra teaching records are excluded from the logical payload budget.

Structural guards still cannot certify an arbitrary finite external K/V payload. A forged array can have correct shape and IDs but incorrect numbers; freezing prevents later mutation, not forgery. This lesson constructs its own coherent prefill and does not accept learner-entered K/V. Claims about unchanged copies concern this internally produced record, rather than a universal provenance certificate.

Equal predictions are also insufficient evidence. Resetting both new Q/K rotations to0 while retaining old keys changes scores to (g,−g cos1,g); a can still win with different probabilities. With repeated a values, all V rows equal u, so an exact normalized mixture can stay u even when scores are wrong. Inspect keys, positions and scores as well as final predictions. A model edit may be invalid even if its winning ID stays the same.

From cache reuse to training contexts

K/V storage grows with batch size, layers, key/value heads, context, widths and assumed bits. One cached query avoids old projections while still reading the whole available prefix. Valid reuse requires the declared model, ordered context and position contract; conservative policy can reject more edits than minimal K/V dependence requires.

IV-51 — Training Data, Packing and Causal Boundaries turns to training data, packing and causal boundaries. It changes which examples and contexts are supplied to a training calculation. Caching alone updates no model parameters and supplies no evidence of learning.

Use the five checks in the lab

The five graded checks above use the current saved record and are defined once in the lab. The first follows the live old/next/per-token footprint through K and V entry counts, bits and bytes. The second distinguishes live score-cell counts from paired K/V head rows and from measured latency. Changing planner dimensions changes those two checks while the neural probe stays fixed.

The third checks the evidence that actually exists. Accepted reuse has new Q [1,1,1,2], available K [1,1,3,2], logits [1,3] and a class-probability vector [3]. Rejected reuse instead has the real prefill K [1,1,2,2], no new neural frames and no append Q/logits/probability/winner. Its corrective feedback refers to the actual guard reason, rather than looking up an absent tensor. Baseline and attempted metadata are evidence of the request, not a substitute for a computed append.

The fourth uses the saved edit kind, δ, edited field, represented target and modelChanged. An accepted model edit explains why the actual rounded target still equals1; the unchanged-request branch explains matching model/prefix/positions. A rejected branch supplies the actual code and reason. Its feedback separates conservative full26 policy from minimum K/V dependence and warns that shape alone cannot certify a finite payload. The fifth transfers the asymmetric RN interval and tiny-delta examples to all three editable model fields. These are the same five checks at the top, with immediate corrective feedback after an answer.

Read the complete Python dependency closure

Each panel below displays a maintained file through a raw-source import, including its implementation and any explicitly declared checks. The project closure is eleven unique source files: the IV50 entry plus ten dependencies. Python’s standard library and NumPy are runtime requirements, rather than additional project panels. Reading source does not execute it or establish parity with TypeScript.

Keep the code/python/p12, p11, p10, p09, p07 and p06 directory relationships intact. Loaders resolve from their own __file__ paths, rather than from the caller’s working directory. Copying only the entry file would omit its executable dependencies. Several loaded module instances can come from the same file; the panels disclose unique source paths, not one panel per module instance.

The entry accepts no arguments for fresh defaults, one complete replacement JSON object, or - to read that complete object from standard input. A full reset object is {"B":1,"L":1,"Hkv":1,"T":2,"Dk":2,"Dv":2,"bits":64,"editKind":0,"delta":0.5}. Supplying only {"T":0} is not an edit patch. The strict JSON parser rejects duplicate keys and non-JSON NaN, Infinity and -Infinity. Invalid raw state returns an unavailable record; a known rejected reuse attempt instead keeps the defined planner and real prefill, with its actual failure text. Unknown mechanical faults propagate.

--self-check is an explicit separate assertion mode, outside ordinary query fault handling, and cannot combine with a state query. Imports and default/JSON/stdin queries call no declared self-check. The IV50 check leaf does not invoke dependency check leaves. These paths and assertions are source evidence, not execution results.

The graph is IV50 → adjacent cache reference → p11 inference and choice references. Inference loads the Tiny decoder and IV39. Tiny loads component, FFN, head and BPE references; IV39 also loads BPE; BPE loads the token codec. This loader closure is broader than the calculation actually invoked: this probe uses fixed observed IDs, so it does not call IV39 tokenization, decode a newly generated text, train weights or invoke the old objective/gradient functions.

Entry and planner — code/python/p12/iv50.py. budget_state validates the complete nine-field replacement. logical_counts computes small scalar quantities without allocating planner-sized neural arrays. invalidation_probe creates an actual fixed prefill_cache, preserves its detached baseline, constructs the requested target/prefix/attempt and calls the actual append_cached. It handles only the exact known invalidation code/reason pairs; unexpected faults propagate. derive_iv50 combines the planner, all actual prefill/request/accepted-only append evidence and outcome counts, then chapter_record detaches the complete ordered outputs, steps, tensors and policy texts. run parses strict query input separately before calling the derive, so a mechanical failure is not mislabeled as a JSON error. The source preserves the represented target addition, rather than deciding reuse from the sign or magnitude of δ.

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.

"""IV50: complete canonical NumPy budget and actual invalidation record.

No args uses defaults; complete JSON or '-' stdin replaces all nine raw fields.
--self-check alone invokes the explicit leaf outside ordinary fault handling.
Analytical sizes never allocate neural arrays. Keep the eleven-file closure.
All execution and checks remain DEFERRED under the human resource hold.
"""
import importlib.util
import math
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_iv50_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)
NumericalFault = _helper.NumericalFault
DEFAULT_IV50 = MappingProxyType(dict(B=1, L=1, Hkv=1, T=2, Dk=2, Dv=2,
                                    bits=64, editKind=0, delta=0.5))
_BOUNDS = dict(B=(1, 4), L=(1, 64), Hkv=(1, 32), T=(0, 8192),
               Dk=(1, 256), Dv=(1, 256), editKind=(0, 5))
_EXPECTED_FAULTS = {
    ("UNAVAILABLE", "CACHE_MODEL_MISMATCH: all 26 numeric parameters must agree under numeric ===."),
    ("UNAVAILABLE", "CACHE_PREFIX_MISMATCH: the requested ordered prefix must equal cache.ids."),
    ("INVALID_INPUT", "CACHE_POSITION_MISMATCH: positions must be exact ordered integers 0..N-1."),
}
_PAYLOAD_NAMES = ("batchLayers", "factor", "oldHeadRows", "KElements", "VElements", "payloadElements", "payloadBits", "payloadBytes")
_TOKEN_NAMES = ("featureWidth", "elementsPerToken", "bitsPerToken", "bytesPerToken", "nextPayloadBytes", "nextPayloadBits")
_WORK_NAMES = ("Tk", "nextSquare", "cachedScoreCells", "fullScoreCells", "cachedProjectedHeadRows", "fullProjectedHeadRows")


def budget_state(state):
    """Inspect the complete exact container before values; never coerce scalars."""
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "Provide a plain object with exactly the nine IV50 data fields.")
    if any(type(key) is not str for key in state) or set(state) != set(DEFAULT_IV50):
        raise NumericalFault("INVALID_INPUT", "Provide every IV50 own field and no extra or symbol fields.")
    checked = {}
    for key in DEFAULT_IV50:
        value = state[key]
        if type(value) not in (int, float) or (type(value) is float and not math.isfinite(value)):
            raise NumericalFault("NONFINITE", f"{key} must be finite.")
        # Finite arbitrary-size Python integers must fail domain before float().
        if key == "bits":
            if value not in (8, 16, 32, 64):
                raise NumericalFault("INVALID_INPUT", "bits must be one of 8, 16, 32, 64.")
        elif key == "delta":
            if not -1 <= value <= 1:
                raise NumericalFault("INVALID_INPUT", "delta must be between -1 and 1, including when inactive.")
        else:
            low, high = _BOUNDS[key]
            if not low <= value <= high or (type(value) is float and not value.is_integer()):
                raise NumericalFault("INVALID_INPUT", f"{key} must be an integer from {low} to {high}.")
        checked[key] = float(value)
    return checked


def logical_counts(state, trace=None):
    """Validated scalar plan; no analytical dimension feeds array allocation."""
    B, L, Hkv, T, Dk, Dv, bits = (state[key] for key in ("B", "L", "Hkv", "T", "Dk", "Dv", "bits"))
    batch_layers = B * L
    factor = batch_layers * Hkv
    old_head_rows = factor * T
    keys, values = old_head_rows * Dk, old_head_rows * Dv
    elements = keys + values
    payload_bits = elements * bits
    payload_bytes = payload_bits / 8
    width = Dk + Dv
    token_elements = factor * width
    token_bits = token_elements * bits
    token_bytes = token_bits / 8
    next_bytes = payload_bytes + token_bytes
    next_bits = next_bytes * 8
    next_context = T + 1
    square = next_context * next_context
    cached_cells = factor * next_context
    full_cells = factor * square
    counts = dict(batchLayers=batch_layers, factor=factor, oldHeadRows=old_head_rows,
                  KElements=keys, VElements=values, payloadElements=elements,
                  payloadBits=payload_bits, payloadBytes=payload_bytes,
                  featureWidth=width, elementsPerToken=token_elements, bitsPerToken=token_bits,
                  bytesPerToken=token_bytes, nextPayloadBytes=next_bytes, nextPayloadBits=next_bits,
                  Tk=next_context, nextSquare=square, cachedScoreCells=cached_cells,
                  fullScoreCells=full_cells, cachedProjectedHeadRows=factor,
                  fullProjectedHeadRows=factor * next_context)
    if trace is not None:
        trace.add("planner_payload", "Count logical old K and V payload only", "batchLayers=B*L; factor=batchLayers*Hkv; oldHeadRows=factor*T; KElements=oldHeadRows*Dk; VElements=oldHeadRows*Dv; payloadElements=KElements+VElements; payloadBits=payloadElements*bits; payloadBytes=payloadBits/8",
                  "Analytical integer counts only. No planner-sized neural array is allocated. Q, weights, metadata, heap and allocator overhead are excluded.",
                  dict(B=B, L=L, Hkv=Hkv, T=T, Dk=Dk, Dv=Dv, bits=bits, bitsPerByte=8),
                  {key: counts[key] for key in _PAYLOAD_NAMES})
        trace.add("planner_token", "Add one logical token without allocating it", "featureWidth=Dk+Dv; elementsPerToken=factor*featureWidth; bitsPerToken=elementsPerToken*bits; bytesPerToken=bitsPerToken/8; nextPayloadBytes=payloadBytes+bytesPerToken; nextPayloadBits=nextPayloadBytes*8",
                  "T is the old analytical context. Even at T=8192 the analytical next length8193 does not enlarge the fixed two-token neural probe.",
                  dict(factor=factor, Dk=Dk, Dv=Dv, bits=bits, payloadBytes=payload_bytes, bitsPerByte=8),
                  {key: counts[key] for key in _TOKEN_NAMES})
        trace.add("planner_work", "Count next-query score cells and projected head rows", "Tk=T+1; nextSquare=Tk*Tk; cachedScoreCells=factor*Tk; fullScoreCells=factor*nextSquare; cachedProjectedHeadRows=factor; fullProjectedHeadRows=factor*Tk",
                  "Hq=Hkv simple MHA. One projected head row is the pair of K/V projected vectors for one head and token, not a distinct input embedding or a FLOP count. A cached query still reads all available keys and values; these are not timings or speedups.",
                  dict(T=T, oneNewToken=1, factor=factor), {key: counts[key] for key in _WORK_NAMES})
    return counts


def invalidation_probe(state, trace=None):
    """Actual fixed prefill and append, with only exact known-fault capture."""
    trace = _helper._tiny.tiny_trace() if trace is None else trace
    parameters = dict(_helper.NUMERIC_DEFAULTS)
    prefill = _helper.prefill_cache(parameters, [97, 98], trace, "prefill")
    baseline = _helper.detached(prefill["cache"])
    target, expected = dict(parameters), [97, 98]
    attempt = _helper.detached(baseline)
    kind = int(state["editKind"])
    field = {1: "e00", 4: "u00", 5: "e40"}.get(kind, "")
    target_value = 1.0 + state["delta"] if field else 1.0
    if field:
        target[field] = target_value
    if kind == 2:
        expected = [98, 97]
    if kind == 3:
        attempt["positions"] = [1, 2]
    changed = int(any(target[key] != parameters[key] for key in parameters))
    trace.add("probe_edit", "Prepare a detached request while preserving the coherent baseline", "edit1:e00=1+delta; edit2:expected=[98,97]; edit3:attempt.positions=[1,2]; edit4:u00=1+delta; edit5:e40=1+delta; otherwise unchanged; modelChanged=any actual target!==baseline",
              "The actual represented addition decides model identity, including ties-to-even and subnormal deltas. No tolerance or nonzero-delta heuristic is used. The original prefill cache is immutable; the attempt is never repaired or rebuilt at a changed origin.",
              dict(editKind=state["editKind"], delta=state["delta"], baseValue=1),
              dict(deltaUsed=int(bool(field)), targetValue=target_value, modelChanged=changed,
                   expectedID0=expected[0], expectedID1=expected[1], attemptPosition0=attempt["positions"][0], attemptPosition1=attempt["positions"][1]))
    before_steps = len(trace.steps)
    try:
        append = _helper.append_cached(target, expected, attempt, 97, trace, "probe")
    except NumericalFault as error:
        if (error.code, str(error)) not in _EXPECTED_FAULTS:
            raise
        append, fault = None, dict(code=error.code, reason=str(error))
    else:
        fault = None
    if append is None and len(trace.steps) != before_steps:
        raise RuntimeError("Rejected cache probe unexpectedly emitted neural frames.")
    return dict(parameters=parameters, target=target, expected=expected, baseline=baseline,
                attempt=attempt, prefill=prefill, append=append, fault=fault, trace=trace,
                beforeSteps=before_steps, modelChanged=changed, field=field,
                deltaUsed=int(bool(field)), targetValue=target_value)


def _count_tensor(identifier, axis, names, counts, provenance):
    record = _helper._float(identifier, [len(names)], [axis], [counts[key] for key in names], provenance)
    record["precision"] = 0
    return record


def derive_iv50(state):
    """Complete owner-adopted record; raw known faults alone are unavailable."""
    try:
        s = budget_state(state)
    except NumericalFault as error:
        return dict(status="unavailable", code=error.code, reason=str(error))
    trace = _helper._tiny.tiny_trace()
    trace.add("setup", "Separate a logical budget from a fixed actual invalidation probe", "planner inputs never set neural dimensions; probe B=L=Hkv=1,N=2,Dk=Dv=2,bits=64,V=3,newID=97",
              "All nine raw fields, including inactive delta, validate before any calculation. The probe uses default26 untrained parameters and already observed IDs[97,98], without a tokenizer or full-append reference.",
              s, dict(probeB=1, probeL=1, probeHkv=1, probeN=2, probeDk=2, probeDv=2, probeBits=64, probeClassCount=3, newID=97))
    p = logical_counts(s, trace)
    tensors = [
        _count_tensor("PlannerPayload", "PayloadMetric", _PAYLOAD_NAMES, p, "Analytical payload metrics in payloadMetricNames order; exact integer binary64, never int32; no payload allocation."),
        _count_tensor("PlannerToken", "TokenMetric", _TOKEN_NAMES, p, "Analytical one-token metrics in tokenMetricNames order; hypothetical bits do not mutate the actual float64 probe."),
        _count_tensor("PlannerWork", "WorkMetric", _WORK_NAMES, p, "Analytical MHA work metrics in workMetricNames order; score cells and paired K/V head rows, not latency or FLOPs."),
    ]
    probe = invalidation_probe(s, trace)
    tensors.extend(probe["prefill"]["tensors"])
    parameter_names = list(probe["parameters"])
    tensors.extend([
        _helper._float("ProbeBaselineParameters", [26], ["Parameter"], list(probe["parameters"].values()), "All26 default prefill parameters in parameterNames order; baseline is independent of planner dimensions."),
        _helper._float("ProbeTargetParameters", [26], ["Parameter"], list(probe["target"].values()), "Actual represented requested parameters in parameterNames order, including inactive fields."),
        _helper._integer("ProbeExpectedIDs", "RequestedPosition", probe["expected"], "Independently requested ordered prefix, distinct from the attempted cache IDs."),
        *_helper.cache_tensors(probe["attempt"], "attempt_"),
    ])
    appended, fault = probe["append"], probe["fault"]
    accepted = {}
    if appended is not None:
        tensors.extend(appended["tensors"])
        copies = next(step["outputs"] for step in trace.steps if step["id"] == "probe_append")
        distribution = appended["distribution"]
        accepted = dict(retainedExact=copies["retainedExact"], appendNextRow=distribution["nextRow"],
                        appendNextID=distribution["nextID"], appendNextProbability=distribution["nextProbability"])
    reuse_accepted = int(appended is not None)
    append_frames = len(trace.steps) - probe["beforeSteps"]
    append_rows, append_cells = reuse_accepted, 3 * reuse_accepted
    entries = len(appended["cache"]["ids"] if appended is not None else probe["prefill"]["cache"]["ids"])
    trace.add("probe_outcome", "Save the actual guarded append outcome", "reuseAccepted=(actual append returned); rejected attempt emits zero neural frames/tensors; accepted attempt keeps every actual output",
              "Only the three exact declared cache code/reason pairs are captured. Unknown errors propagate. On rejection append predictions, retained-copy flags and probe neural tensors are absent, not filled with zeros.",
              dict(editKind=s["editKind"], modelChanged=probe["modelChanged"], beforeAppendFrames=probe["beforeSteps"]),
              dict(reuseAccepted=reuse_accepted, appendFrames=append_frames, appendQueryRows=append_rows,
                   appendScoreCells=append_cells, cacheEntries=entries, **accepted))
    harness_rows, harness_cells = 2 + append_rows, 4 + append_cells
    trace.add("finish", "Count actual probe calls separately from analytical work", "actualHarnessRows=2+appendQueryRows; actualHarnessScoreCells=4+appendScoreCells",
              "The actual harness has one two-row prefill and optionally one new-row append. Analytical T, layers, heads, widths and storage bits never change those calls. No elapsed time, measured speedup or quantizer is present.",
              dict(prefillQueryRows=2, appendQueryRows=append_rows, prefillScoreCells=4, appendScoreCells=append_cells),
              dict(actualHarnessRows=harness_rows, actualHarnessScoreCells=harness_cells))
    last = probe["prefill"]["forward"]["rows"][1]
    summary = dict(payloadBytes=p["payloadBytes"], nextPayloadBytes=p["nextPayloadBytes"], bytesPerToken=p["bytesPerToken"], reuseAccepted=reuse_accepted,
                   **s, batchLayers=p["batchLayers"], factor=p["factor"], oldHeadRows=p["oldHeadRows"], KElements=p["KElements"], VElements=p["VElements"],
                   payloadElements=p["payloadElements"], payloadBits=p["payloadBits"], featureWidth=p["featureWidth"], elementsPerToken=p["elementsPerToken"],
                   bitsPerToken=p["bitsPerToken"], nextPayloadBits=p["nextPayloadBits"], Tk=p["Tk"], nextSquare=p["nextSquare"],
                   cachedScoreCells=p["cachedScoreCells"], fullScoreCells=p["fullScoreCells"], cachedProjectedHeadRows=p["cachedProjectedHeadRows"], fullProjectedHeadRows=p["fullProjectedHeadRows"],
                   probeB=1, probeL=1, probeHkv=1, probeN=2, probeDk=2, probeDv=2, probeBits=64, probeClassCount=3, newID=97,
                   deltaUsed=probe["deltaUsed"], targetValue=probe["targetValue"], modelChanged=probe["modelChanged"], prefillQueryRows=2,
                   appendQueryRows=append_rows, prefillScoreCells=4, appendScoreCells=append_cells, actualHarnessRows=harness_rows,
                   actualHarnessScoreCells=harness_cells, cacheEntries=entries, appendFrames=append_frames,
                   prefillNextRow=last["nextRow"], prefillNextID=last["nextID"], prefillNextProbability=last["nextProbability"], **accepted)
    texts = dict(
        plannerScope="Logical K+V storage only; excludes queries, weights, metadata, heap and allocator overhead. No planner-sized allocation occurs.",
        storagePolicy="8/16/32/64 bits are hypothetical logical storage scenarios. The actual probe remains float64; no quantizer or dtype mutation is implemented.",
        workPolicy="Hq=Hkv simple MHA. A projected head row is the pair of K/V vectors for one head and token, not distinct input embeddings or FLOPs. IV61 introduces GQA. Cached attention still reads all available keys and values, so longer contexts increase work and bandwidth; no latency or speedup is measured.",
        probeScope="Independent actual probe: B=L=Hkv=1, old N=2, Dk=Dv=2, bits64, merges0, default26 untrained parameters, observed IDs[97,98], supplied newID97. Analytical dimensions never feed neural arrays.",
        editField=probe["field"] or "none", attemptStatus="accepted" if appended is not None else "rejected",
        failureCode=fault["code"] if fault is not None else "", failureReason=fault["reason"] if fault is not None else "",
        modelIdentityPolicy="All26 numeric parameters must agree under numeric ===; signed zeros are equivalent. Actual readout-only or inactive embedding edits invalidate under this conservative policy even though they do not change old K/V mathematically in this one-layer toy.",
        positionPolicy="Origin0 only: positions must be exact ordered integers0..N-1 and expectedPrefixIDs must separately match cache.ids. A changed origin is rejected, never silently repaired.",
        roundingPolicy="At1 the spacing upward is2^-52 and downward2^-53. RN ties-even leaves1 unchanged for represented delta in[-2^-54,+2^-53], including both endpoints, signed zeros and +/-Number.MIN_VALUE. +2^-52 and -2^-53 change the target. Compare the actual represented1+delta, never a tolerance or merely delta!=0.",
        cacheTrust="The probe constructs its own coherent prefill and preserves that immutable baseline. Shape/finite/model/prefix checks cannot certify arbitrary externally supplied K/V; external helper coherence remains a precondition.",
        payloadMetricNames=list(_PAYLOAD_NAMES), tokenMetricNames=list(_TOKEN_NAMES), workMetricNames=list(_WORK_NAMES), parameterNames=parameter_names)
    return _helper.chapter_record(summary, trace, tensors, texts)


def source_self_check():
    """DEFERRED explicit leaf: no dependency source_self_check calls."""
    assert __debug__, "Deferred checks require assertions enabled."
    _assert_public_records()
    _assert_cli()
    defaults = dict(DEFAULT_IV50)
    assert list(defaults) == ["B", "L", "Hkv", "T", "Dk", "Dv", "bits", "editKind", "delta"]
    state = budget_state(defaults)
    counts = logical_counts(state)
    assert counts["payloadBytes"] == 64 and counts["nextPayloadBytes"] == 96
    assert counts["bytesPerToken"] == 32 and counts["cachedScoreCells"] == 3 and counts["fullScoreCells"] == 9
    maximum = logical_counts(budget_state({**defaults, "B": 4, "L": 64, "Hkv": 32, "T": 8192, "Dk": 256, "Dv": 256}))
    for key, expected in dict(factor=8192, KElements=17179869184, VElements=17179869184,
                              payloadElements=34359738368, payloadBits=2199023255552,
                              payloadBytes=274877906944, elementsPerToken=4194304,
                              bitsPerToken=268435456, bytesPerToken=33554432,
                              nextPayloadBytes=274911461376, nextPayloadBits=2199291691008,
                              Tk=8193, nextSquare=67125249, cachedScoreCells=67117056,
                              fullScoreCells=549890039808, cachedProjectedHeadRows=8192,
                              fullProjectedHeadRows=67117056).items():
        assert maximum[key] == expected, key
    assert all(type(value) is float and value.is_integer() and 0 <= value < 2 ** 53 for value in maximum.values())
    for bits in (8, 16, 32, 64):
        old = logical_counts(budget_state({**defaults, "bits": bits}))
        assert old["payloadBytes"] == bits and old["bytesPerToken"] == bits / 2
        zero = logical_counts(budget_state({**defaults, "T": 0, "bits": bits}))
        assert all(zero[key] == 0 for key in ("KElements", "VElements", "payloadElements", "payloadBits", "payloadBytes"))
        assert zero["nextPayloadBytes"] == zero["bytesPerToken"] == bits / 2
        assert zero["Tk"] == zero["cachedScoreCells"] == zero["fullScoreCells"] == 1

    def rejects(raw, code):
        try:
            budget_state(raw)
        except NumericalFault as error:
            assert error.code == code, (error.code, str(error))
        else:
            raise AssertionError("Invalid raw state was accepted")

    class HostileDict(dict):
        def __iter__(self):
            raise AssertionError("Custom mapping iteration")
        def __getitem__(self, key):
            raise AssertionError("Custom mapping read")

    class Coercion:
        def __float__(self):
            raise AssertionError("Scalar coercion")

    rejects(HostileDict(defaults), "INVALID_INPUT")
    for invalid in (None, [], {}, {**defaults, "extra": 1}, {**defaults, 1: 1}):
        rejects(invalid, "INVALID_INPUT")
    for field in defaults:
        for value in (True, None, "1", Coercion(), float("nan"), float("inf"), -float("inf")):
            rejects({**defaults, field: value}, "NONFINITE")
        for value in (10 ** 1000, -(10 ** 1000)):
            rejects({**defaults, field: value}, "INVALID_INPUT")
        if field != "delta":
            rejects({**defaults, field: 0.5}, "INVALID_INPUT")
    rejects({**defaults, "delta": 1.0000000000000002}, "INVALID_INPUT")
    rejects({**defaults, "delta": -1.0000000000000002}, "INVALID_INPUT")
    assert budget_state({**defaults, "T": -0.0})["T"] == 0

    # Spacing differs across the binade at1; these are exact paper anchors.
    unchanged = (0.0, -0.0, 2.0 ** -53, -(2.0 ** -54), math.ulp(0.0), -math.ulp(0.0))
    changed = ((2.0 ** -52, 1.0000000000000002), (-(2.0 ** -53), 0.9999999999999999), (-1.0, 0.0), (1.0, 2.0))
    for delta in unchanged:
        assert 1.0 + delta == 1.0
    for delta, target in changed:
        assert 1.0 + delta == target and target != 1.0
    for kind, field in ((1, "e00"), (4, "u00"), (5, "e40")):
        for delta in (*unchanged, *(item[0] for item in changed)):
            result = invalidation_probe(budget_state({**defaults, "editKind": kind, "delta": delta}))
            actual_change = int(1.0 + delta != 1.0)
            public = derive_iv50({**defaults, "editKind": kind, "delta": delta})
            _assert_record(public, not actual_change)
            assert public["outputs"]["targetValue"] == 1.0 + delta
            assert result["target"][field] == 1.0 + delta and result["modelChanged"] == actual_change
            assert (result["append"] is None) == bool(actual_change)
            assert len(result["prefill"]["forward"]["tensors"]) == 57
            assert len(result["prefill"]["tensors"]) == 61 and result["beforeSteps"] == 114
            assert result["prefill"]["cache"] == result["baseline"] == result["attempt"]
            if actual_change:
                assert result["fault"] == dict(code="UNAVAILABLE", reason="CACHE_MODEL_MISMATCH: all 26 numeric parameters must agree under numeric ===.")
                assert len(result["trace"].steps) == result["beforeSteps"]
            else:
                assert result["fault"] is None and len(result["trace"].steps) == 171
                appended = result["append"]
                assert appended["before"] == result["baseline"] and len(appended["tensors"]) == 67
                assert appended["cache"]["ids"] == [97, 98, 97] and appended["position"] == 2
                assert appended["cache"]["keys"][:4] == result["baseline"]["keys"]
                assert appended["cache"]["values"][:4] == result["baseline"]["values"]
    for kind in (0, 2, 3):
        for delta in (-1.0, 0.5, 1.0):
            result = invalidation_probe(budget_state({**defaults, "editKind": kind, "delta": delta}))
            assert result["modelChanged"] == 0 and result["target"] == result["parameters"]
            assert result["prefill"]["cache"] == result["baseline"]
            if kind == 0:
                assert result["append"] is not None and result["fault"] is None
            else:
                expected_fault = dict(code="UNAVAILABLE", reason="CACHE_PREFIX_MISMATCH: the requested ordered prefix must equal cache.ids.") if kind == 2 else dict(code="INVALID_INPUT", reason="CACHE_POSITION_MISMATCH: positions must be exact ordered integers 0..N-1.")
                assert result["append"] is None and result["fault"] == expected_fault
                assert len(result["trace"].steps) == 114
                assert all(step["id"] == "probe_edit" for step in result["trace"].steps if step["id"].startswith("probe_"))
                if kind == 2:
                    assert result["expected"] == [98, 97] and result["attempt"] == result["baseline"]
                else:
                    assert result["attempt"]["positions"] == [1, 2] and result["baseline"]["positions"] == [0, 1]

    # Only the exact known fault pairs may be handled; every other error escapes.
    original_append = _helper.append_cached
    try:
        for injected in (NumericalFault("UNAVAILABLE", "unknown failure"),
                         NumericalFault("INVALID_INPUT", "CACHE_MODEL_MISMATCH: all 26 numeric parameters must agree under numeric ===."),
                         RuntimeError("unexpected append failure")):
            def broken_append(*args, **kwargs):
                raise injected
            _helper.append_cached = broken_append
            try:
                invalidation_probe(state)
            except Exception as error:
                assert error is injected
            else:
                raise AssertionError("Unknown append failure was swallowed")
    finally:
        _helper.append_cached = original_append

    root = Path(__file__).resolve().parent.parent
    closure = ((_helper, "p12/cache_reference.py"), (_helper._inference, "p11/inference_reference.py"),
               (_helper._choice, "p11/choice_reference.py"), (_helper._tiny, "p10/tiny_reference.py"),
               (_helper._iv39, "p09/iv39.py"), (_helper._bpe, "p09/bpe_reference.py"),
               (_helper._token, "p09/token_reference.py"), (_helper._component, "p07/component_reference.py"),
               (_helper._ffn, "p07/ffn_reference.py"), (_helper._head, "p06/head_reference.py"))
    assert len({Path(module.__file__).resolve() for module, _ in closure}) == 10
    for module, relative in closure:
        assert Path(module.__file__).resolve() == root / relative
    # The unchanged Tiny loader must restore absent, None and unrelated bindings.
    import sys
    from types import ModuleType
    missing = object()
    previous = sys.modules.get("component_reference", missing)
    try:
        for sentinel in (missing, None, ModuleType("unrelated_component")):
            if sentinel is missing:
                sys.modules.pop("component_reference", None)
            else:
                sys.modules["component_reference"] = sentinel
            tiny = _helper._load("_iv50_closure_sentinel", root / "p10" / "tiny_reference.py")
            assert sys.modules.get("component_reference", missing) is sentinel
            assert tiny._ffn.NumericalFault is tiny._component.NumericalFault
            assert tiny._ffn.finite is tiny._component.finite
    finally:
        if previous is missing:
            sys.modules.pop("component_reference", None)
        else:
            sys.modules["component_reference"] = previous


def run():
    """Strict defaults/full replacement JSON/stdin; assertions escape catches."""
    import argparse
    import json
    import sys
    parser = argparse.ArgumentParser(description=__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")
        source_self_check()
        return
    try:
        if args.state is None:
            state = dict(DEFAULT_IV50)
        else:
            raw = sys.stdin.read() if args.state == "-" else args.state
            state = json.loads(raw, object_pairs_hook=_helper._json_object,
                               parse_constant=_helper._json_constant, parse_int=_helper._json_integer)
    except (ValueError, OSError) as error:
        result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
    else:
        # Unknown numerical/mechanical failures must not become JSON input faults.
        result = derive_iv50(state)
    print(json.dumps(result, allow_nan=False, ensure_ascii=False, separators=(",", ":")))


def _assert_cli():
    """Deferred actual CLI assertions, called only by this file's check leaf."""
    import contextlib
    import io
    import json
    import sys
    original = sys.argv, sys.stdin, source_self_check, derive_iv50

    def forbidden_check():
        raise AssertionError("explicit check sentinel")

    try:
        globals()["source_self_check"] = forbidden_check
        raw = json.dumps(dict(DEFAULT_IV50), allow_nan=False)
        for arguments in ([], [raw], ["-"]):
            sys.argv, sys.stdin = [str(Path(__file__).resolve()), *arguments], io.StringIO(raw)
            with contextlib.redirect_stdout(io.StringIO()) as output:
                run()
            record = json.loads(output.getvalue())
            assert record["status"] == "defined" and record["outputs"]["payloadBytes"] == 64
            assert record["outputs"]["reuseAccepted"] == 1
        replacement = {**DEFAULT_IV50, "T": 0, "editKind": 2}
        sys.argv = [str(Path(__file__).resolve()), json.dumps(replacement)]
        with contextlib.redirect_stdout(io.StringIO()) as output:
            run()
        record = json.loads(output.getvalue())
        assert record["outputs"]["payloadBytes"] == 0 and record["outputs"]["reuseAccepted"] == 0
        for raw in ('{"B":1,"B":2}', '{"nested":{"x":1,"x":2}}', '[]', '{}', '{"B":1}',
                    'NaN', 'Infinity', '-Infinity', '{bad json', 'null'):
            sys.argv, sys.stdin = [str(Path(__file__).resolve()), "-"], io.StringIO(raw)
            with contextlib.redirect_stdout(io.StringIO()) as output:
                run()
            fault = json.loads(output.getvalue())
            assert list(fault) == ["status", "code", "reason"]
            assert fault["status"] == "unavailable" and fault["code"] == "INVALID_INPUT"
        for injected in (NumericalFault("UNAVAILABLE", "unexpected numerical failure"), RuntimeError("unexpected mechanics failure")):
            def broken_derive(state):
                raise injected
            globals()["derive_iv50"] = broken_derive
            sys.argv = [str(Path(__file__).resolve())]
            with contextlib.redirect_stdout(io.StringIO()) as output:
                try:
                    run()
                except Exception as error:
                    assert error is injected
                else:
                    raise AssertionError("CLI swallowed an unknown derive failure")
            assert not output.getvalue()
        globals()["derive_iv50"] = original[3]
        sys.argv = [str(Path(__file__).resolve()), "--self-check"]
        with contextlib.redirect_stdout(io.StringIO()) as output:
            try:
                run()
            except AssertionError as error:
                assert str(error) == "explicit check sentinel"
            else:
                raise AssertionError("Explicit self-check assertion was swallowed")
        assert not output.getvalue()
        sys.argv = [str(Path(__file__).resolve()), "--self-check", json.dumps(dict(DEFAULT_IV50))]
        with contextlib.redirect_stderr(io.StringIO()):
            try:
                run()
            except SystemExit as error:
                assert error.code == 2
            else:
                raise AssertionError("CLI combined --self-check with a state query")
    finally:
        sys.argv, sys.stdin = original[:2]
        globals()["source_self_check"], globals()["derive_iv50"] = original[2:]


def _assert_record(record, accepted):
    """Deferred whole-record/order/absence assertion utility, not an oracle."""
    assert list(record) == ["status", "outputs", "steps", "tensors", "texts"] and record["status"] == "defined"
    assert len(record["steps"]) == (177 if accepted else 120)
    assert len(record["tensors"]) == (138 if accepted else 71)
    summary = ("payloadBytes nextPayloadBytes bytesPerToken reuseAccepted B L Hkv T Dk Dv bits editKind delta "
               "batchLayers factor oldHeadRows KElements VElements payloadElements payloadBits featureWidth elementsPerToken "
               "bitsPerToken nextPayloadBits Tk nextSquare cachedScoreCells fullScoreCells cachedProjectedHeadRows fullProjectedHeadRows "
               "probeB probeL probeHkv probeN probeDk probeDv probeBits probeClassCount newID deltaUsed targetValue modelChanged "
               "prefillQueryRows appendQueryRows prefillScoreCells appendScoreCells actualHarnessRows actualHarnessScoreCells "
               "cacheEntries appendFrames prefillNextRow prefillNextID prefillNextProbability").split()
    conditional = ["retainedExact", "appendNextRow", "appendNextID", "appendNextProbability"]
    if accepted:
        summary.extend(conditional)
    assert len(summary) == (57 if accepted else 53)
    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"]) == [*summary, *flattened]
    assert {key: record["outputs"][key] for key in flattened} == flattened
    assert len({step["id"] for step in record["steps"]}) == len(record["steps"])
    assert len({tensor["id"] for tensor in record["tensors"]}) == len(record["tensors"])
    assert [step["id"] for step in record["steps"][:4]] == ["setup", "planner_payload", "planner_token", "planner_work"]
    assert sum(step["id"].startswith("prefill_") for step in record["steps"]) == 113
    assert record["steps"][116]["id"] == "prefill_capture" and record["steps"][117]["id"] == "probe_edit"
    assert [step["id"] for step in record["steps"][-2:]] == ["probe_outcome", "finish"]
    assert record["steps"][-2]["inputs"]["beforeAppendFrames"] == 118
    neural = [step for step in record["steps"] if step["id"].startswith("probe_") and step["id"] not in ("probe_edit", "probe_outcome")]
    assert len(neural) == (57 if accepted else 0)
    assert list(record["texts"]) == ("plannerScope storagePolicy workPolicy probeScope editField attemptStatus failureCode failureReason "
                                      "modelIdentityPolicy positionPolicy roundingPolicy cacheTrust payloadMetricNames tokenMetricNames workMetricNames parameterNames").split()
    for key, names in (("payloadMetricNames", _PAYLOAD_NAMES), ("tokenMetricNames", _TOKEN_NAMES), ("workMetricNames", _WORK_NAMES)):
        assert record["texts"][key] == list(names)
    assert record["texts"]["parameterNames"] == list(_helper.NUMERIC_DEFAULTS)
    for index, item in enumerate(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"]) <= 64
        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 index < 3 or item["dtype"] == "int32" else 8)
        assert type(item["provenance"]) is str and item["provenance"]
    assert [item["id"] for item in record["tensors"][:3]] == ["PlannerPayload", "PlannerToken", "PlannerWork"]
    for item, names, axis in zip(record["tensors"][:3], (_PAYLOAD_NAMES, _TOKEN_NAMES, _WORK_NAMES), ("PayloadMetric", "TokenMetric", "WorkMetric")):
        assert item["dtype"] == "float64" and item["shape"] == [len(names)] and item["axes"] == [axis]
        assert item["values"] == [record["outputs"][key] for key in names]
        assert all(value.is_integer() and 0 <= value < 2 ** 53 for value in item["values"])
    assert sum(item["id"].startswith("prefill_") for item in record["tensors"]) == 61
    assert [item["id"] for item in record["tensors"][64:71]] == ["ProbeBaselineParameters", "ProbeTargetParameters", "ProbeExpectedIDs", "attempt_IDs", "attempt_Positions", "attempt_Keys", "attempt_Values"]
    assert sum(item["id"].startswith("probe_") for item in record["tensors"]) == (67 if accepted else 0)
    outputs = record["outputs"]
    assert outputs["reuseAccepted"] == int(accepted) and outputs["appendFrames"] == (57 if accepted else 0)
    assert outputs["appendQueryRows"] == int(accepted) and outputs["appendScoreCells"] == (3 if accepted else 0)
    assert outputs["actualHarnessRows"] == 2 + int(accepted) and outputs["actualHarnessScoreCells"] == 4 + 3 * int(accepted)
    assert outputs["cacheEntries"] == (3 if accepted else 2)
    if accepted:
        assert outputs["retainedExact"] == 1 and record["texts"]["attemptStatus"] == "accepted"
        assert record["texts"]["failureCode"] == record["texts"]["failureReason"] == ""
        for family in ("Keys", "Values", "IDs", "Positions"):
            assert _helper._tensor_values(record, f"prefill_Cache{family}") == _helper._tensor_values(record, f"probe_Before{family}")
    else:
        assert record["texts"]["attemptStatus"] == "rejected"
        assert not any(key in outputs or key in record["steps"][-2]["outputs"] for key in conditional)
        assert (record["texts"]["failureCode"], record["texts"]["failureReason"]) in _EXPECTED_FAULTS
    assert _helper.detached(record) == record


def _assert_public_records():
    """Deferred complete canonical assertions; no independent authority import."""
    state = dict(DEFAULT_IV50)
    for patch in ({}, dict(B=4, L=64, Hkv=32, T=8192, Dk=256, Dv=256), dict(T=0)):
        for kind in range(6):
            raw = {**state, **patch, "editKind": kind}
            record = derive_iv50(raw)
            _assert_record(record, kind == 0)
            assert raw == {**state, **patch, "editKind": kind}
            assert _helper._tensor_values(record, "attempt_Positions") == ([1, 2] if kind == 3 else [0, 1])
            assert _helper._tensor_values(record, "prefill_CachePositions") == [0, 1]
            assert _helper._tensor_values(record, "ProbeExpectedIDs") == ([98, 97] if kind == 2 else [97, 98])
    for raw, reason in (([], "Provide a plain object with exactly the nine IV50 data fields."),
                        ({}, "Provide every IV50 own field and no extra or symbol fields."),
                        ({**state, "B": 10 ** 1000, "delta": float("nan")}, "B must be an integer from 1 to 4."),
                        ({**state, "bits": 10 ** 1000}, "bits must be one of 8, 16, 32, 64."),
                        ({**state, "delta": 10 ** 1000}, "delta must be between -1 and 1, including when inactive.")):
        assert derive_iv50(raw) == dict(status="unavailable", code="INVALID_INPUT", reason=reason)
    record = derive_iv50(state)
    assert derive_iv50(dict(reversed(list(state.items())))) == record
    assert record["outputs"]["payloadBytes"] == 64 and record["outputs"]["nextPayloadBytes"] == 96
    record["tensors"][0]["values"].clear()
    record["texts"]["parameterNames"].clear()
    record["steps"][0]["inputs"].clear()
    fresh = derive_iv50(state)
    assert fresh["tensors"][0]["values"] and fresh["texts"]["parameterNames"] and fresh["steps"][0]["inputs"]
    assert state == dict(DEFAULT_IV50)


if __name__ == "__main__":
    run()

Real cache operations — code/python/p12/cache_reference.py. prefill_cache retains the old full-forward result and captures its actual rotated K and unrotated V. append_cached validates the target, baseline structure, positions, expected ordered prefix, next ID and conservative parameter identity before computing a genuine new row. Follow the one-query scores and value mixture, both residuals, normalization, all three FFN coordinates, readout and stable class distribution. This module also contains IV48/49 compositions; the IV50 probe does not call their growth/comparison/decoding paths.

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 composition — code/python/p11/inference_reference.py. This file loads the actual Tiny, IV39 and codec modules that the cache helper reuses. Its prompt/tokenizer and controlled full-prefix lesson functions remain visible, but are not invoked merely because the probe obtains its dependencies through this loader.

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)

Actual output distribution — code/python/p11/choice_reference.py. direct_distribution retains the maximum, shifted logits, exponentials, left-to-right denominator, log normalization, each class probability and the strict computed-logit decision. It works on all active classes. The cached result’s ChoiceP has shape [3]; its Logits has shape [1,3].

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

Fixed decoder and complete prefill — code/python/p10/tiny_reference.py. forward_tiny computes all old rows and supplies the full prefill evidence. It gathers the embedding, normalizes features, projects Q/K/V, rotates Q/K, computes causal attention, adds residuals, applies the three-coordinate FFN and reads out active classes. Its unused objective/derivative functions are not cache training. The loader temporarily supplies the intended component module for FFN’s bare import and restores the previous module binding afterward.

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)

Loaded tokenizer composition — code/python/p09/iv39.py. This maintained composition trains ranked BPE rules from a supplied corpus, encodes a separate input and retains exact integer evidence. It belongs to the import closure; the IV50 probe already has [97,98] and appended97, so it does not call derive_iv39.

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)

Loaded BPE operations — code/python/p09/bpe_reference.py. These functions count adjacent pairs, apply ranked nonoverlapping replacements and expand retained IDs with explicit EOS policy. They explain tokenization in the earlier lessons. The fixed probe does not retokenize its observed IDs or use decoding to decide cache identity.

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

Loaded strict codec — code/python/p09/token_reference.py. The codec distinguishes Unicode character numbers, UTF-16 code units and UTF-8 bytes. Its numerical/fault utilities are also reused through the old dependencies. Importing this file does not mean the IV50 probe performed a text conversion.

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

Normalization and residual addition — code/python/p07/component_reference.py. feature_norm records the feature mean, population variance, epsilon-inside-root divisor and normalized features. same_shape_add adds residuals only after checking matching shapes. These operations act within a row, preserving the causal argument about earlier 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=(",", ":")))

Complete FFN — code/python/p07/ffn_reference.py. feed_forward saves all hidden projection products, bias additions, ReLU results and output contractions. A zero hidden coordinate remains a computed coordinate; removing it from the explanation would hide part of the actual path.

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)

Head projections and full attention — code/python/p06/head_reference.py. project_heads makes the explicit Q/K/V layout conversions. The full prefill uses the old square attention/join operations. The cache helper separately performs its rectangular one-query attention, since retaining only the last row of a newly computed square result would not save old-row work.

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

Numerical checks and limits

The planner can be checked against the exact hand-counted integer anchors above. For the real probe, independent numerical verification must first establish the complete actual prefill and then bind every accepted new-row operand, result and unchanged coordinate to that produced prefix. It must also check that a rejected request has no new neural region. Shape checks or a canonical implementation compared with itself cannot replace that independent argument.

Exact-real algebra, numerical equality of retained copies within one implementation, and agreement across floating-point libraries are separate claims. Elementary-function error assumptions require validation. Source review alone does not establish Python/TypeScript parity, executable import linkage, rendered accessibility or timing.

Recap

Count scalar K and V entries, then convert bits to bytes. Keep hypothetical storage separate from the actual probe. Inspect the actual represented model edit and actual guard outcome; rejected reuse has no new neural evidence. Neither fewer score cells nor a smaller logical payload is a measured speedup.